Partilhar via


Lesser known feature of SSL validation overrides in .NET

During setup of an SSL connection, the client validates the server's digital certificate. This is done automatically when the HttpWebRequest class is used with the https protocol. 

 

Now, consider the following scenarios:

Custom Security Lesser-than-normal

You want the SSL connection to be established even though the SSL server certificate validated has failed.

This case is common during the coding phase of a project when you have only have a test SSL server certificate to "play" with, and the certificate expires.

 

Custom Security More-than-normal

You want to add bespoke checks to the server certificate. For example, your customer might require that clients only accept SSL connections from a server installed with a certificate issued only by a particular CA. This means that although the SSL sanity checks on the certificate have succeeded, you still have control over whether to allow the SSL connection to go through or not. (Interesting, huh?)

 

You can perform custom security on the SSL connection by setting the ServerCertificateValidationCallback property on the ServicePointManager class to a delegate of type RemoteCertificateValidationCallback. During SSL certificate validation, the frameworks checks for the presence of this callback and, if present, executes the code in the callback.

 

The callback function gives you provides you the following 3 pieces of information:

a) The server's SSL certificate

b) The server's certificate chain that was built by the framework for certificate validation

c) SSL policy errors encountered

 

Here are the code steps:

a) Set the callback property to the CustomValidation delegate of type RemoteCertificateValidationCallback

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CustomValidation);

b) Implement CustomValidation with the checks specific to your situation

private bool CustomValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    if (certificate.issuername != "My Fav CA")

        return false;

}