我无法让用户为他们的服务器创建真正的证书,但我想做一些安全检查。所以以下内容太轻了,因为在我阅读时,没有检查证书。
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
你有什么建议让客户检查 x509 证书?鉴于我使用的是 .NET 语言 (c#/f#)。
我无法让用户为他们的服务器创建真正的证书,但我想做一些安全检查。所以以下内容太轻了,因为在我阅读时,没有检查证书。
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
你有什么建议让客户检查 x509 证书?鉴于我使用的是 .NET 语言 (c#/f#)。
If you're using self signed certs then the only errors you should expect is a chain error on the root (Cert. Issuer). I would suggest something like this that traps for that chain error specifically and lets all other errors fall through.
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(
ValidateRemoteCertificate
);
private static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors )
{
string trustedIssuer = "CN=www.domain.com";
string trustedDomain = "CN=www.domain.com";
bool policyErr = false;
switch (policyErrors)
{
case SslPolicyErrors.None:
policyErr |= false;
break;
case SslPolicyErrors.RemoteCertificateChainErrors:
bool chainErr = false;
foreach (X509ChainStatus status in chain.ChainStatus)
{
switch (status.Status)
{
case X509ChainStatusFlags.NoError:
chainErr |= false;
break;
case X509ChainStatusFlags.UntrustedRoot:
if (certificate.Subject != trustedDomain || certificate.Issuer != trustedIssuer)
chainErr |= true;
else
chainErr |= false;
break;
default:
chainErr |= true;
break;
}
}
policyErr |= chainErr;
break;
default:
policyErr |= true;
break;
}
return !policyErr;
}
如果您无法让客户端创建真正的证书,您至少应该尝试让他们使用您的服务器创建证书。然后您可以检查证书是否有效或至少来自您的 CA,因为您会知道您的 CA 是否已被盗用。如果您信任任何和所有 CA,那么确实没有什么值得检查的。
如果您可以检查证书,您可以将自己的验证逻辑放入函数 ValidateRemoteCertificate
System.Net.ServicePointManager.ServerCertificateValidationCallback += (a, b, c, d) =>
{
return ValidateRemoteCertificate(a, b, c, d);
};
private static bool ValidateRemoteCertificate(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors policyErrors)
{
if (certificate.Subject.Equals("CN=www.domain.com"))
return true;
else
return policyErrors == SslPolicyErrors.None;
}