public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
SslPolicyErrors errors = sslPolicyErrors;
if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch)
{
Zone zone = Zone.CreateFromUrl(((HttpWebRequest)sender).RequestUri.ToString());
if (zone.SecurityZone == SecurityZone.Intranet || zone.SecurityZone == SecurityZone.MyComputer)
{
errors -= SslPolicyErrors.RemoteCertificateNameMismatch;
}
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (X509ChainStatus status in chain.ChainStatus)
{
// Self-signed certificates have the issuer in the subject field.
if ((certificate.Subject == certificate.Issuer) && (status.Status == X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else if (status.Status != X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid, the method returns false.
return false;
}
}
}
// When processing reaches this line, the only errors in the certificate chain are untrusted root errors for self-signed certificates.
// These certificates are valid.
errors -= SslPolicyErrors.RemoteCertificateChainErrors;
}
return errors == SslPolicyErrors.None;
}