.NET编程:验证什么上安装SSL自签名证书证书、NET、SSL

2023-09-04 02:17:50 作者:穷极一生

我不能让用户创建真正的证书为他们的服务器,但我想,做一些安全检查。所以下面是太亮,因为,因为我读它,还有的没有的检查功能的证书。

I cannot get the users to create real certs for their servers but I'd like to do some security checks. So the following is too light because, as I read it, there is no checking on the certs.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

你有什么建议这样做,我有客户检查的X509证书?由于我使用的.NET语言(C#/ F#)。

What do you recommend that I have the clients check on the x509 cert? Given that I'm using a .NET language (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;
}
 
精彩推荐