private bool VerifyCert(LdapConnection conn, X509Certificate cert)
{
m_logger.Debug("VerifyCert(...)");
m_logger.DebugFormat("Verifying certificate from host: {0}", conn.SessionOptions.HostName);
// Convert to X509Certificate2
X509Certificate2 serverCert = new X509Certificate2(cert);
// If we don't need to verify the cert, the verification succeeds
if (!m_verifyCert)
{
m_logger.Debug("Server certificate accepted without verification.");
return true;
}
// If the certificate is null, then we verify against the machine's/user's certificate store
if (m_cert == null)
{
m_logger.Debug("Verifying server cert with Windows store.");
// We set the RevocationMode to NoCheck because most custom (self-generated) CAs
// do not work properly with revocation lists. This is slightly less secure, but
// the most common use case for this plugin probably doesn't rely on revocation
// lists.
X509ChainPolicy policy = new X509ChainPolicy() {
RevocationMode = X509RevocationMode.NoCheck
};
// Create a validator using the policy
X509CertificateValidator validator = X509CertificateValidator.CreatePeerOrChainTrustValidator(false,policy);
try
{
validator.Validate(serverCert);
// If we get here, validation succeeded.
m_logger.Debug("Server certificate verification succeeded.");
return true;
}
catch (SecurityTokenValidationException e)
{
m_logger.ErrorFormat("Server certificate validation failed: {0}", e.Message);
return false;
}
}
else
{
m_logger.Debug("Validating server certificate with provided certificate.");
// Verify against the provided cert by comparing the thumbprint
bool result = m_cert.Thumbprint == serverCert.Thumbprint;
if (result) m_logger.Debug("Server certificate validated.");
else m_logger.Debug("Server certificate validation failed.");
return result;
}
}