Verifying a remote SSL certificate during an HTTPS request

When making an HTTPS request to a remote web server, I use WebRequest, which establishes a secure connection to the remote web server. During development, I use a self-signed certificate on the server, and WebRequest cannot establish a secure connection because the certificate is invalid, which is the expected behavior.

I found this code that “removes” the cert check is activated when the SetCertificatePolicy() method is SetCertificatePolicy() in the following code.

 public static void SetCertificatePolicy() { ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate; } /// <summary> /// Remotes the certificate validate. /// </summary> private static bool RemoteCertificateValidate( object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { // trust any certificate!!! System.Console.WriteLine("Warning, trust any certificate"); return true; } 

I am wondering if it is possible to perform special checks on a remote SSL certificate (for example using the code above) so that I can verify that the remote web server is using a valid SSL certificate, not just any valid certificate, but exactly the one I want ? For example, I want to make sure that I speak on the website www.someplace.com, a certificate issued by ACME Inc, with a fingerprint of 00:11:22: .....

What is the “best practice” approach for this scenario?

Thanks!

+7
c # ssl
source share
1 answer

If you really want to nail it to one specific certificate, you can compare the certificate data (in DER format) with byte[] in certificate.GetRawCertData() .

You can also use GetCertHashString() and Subject in the certificate parameter in RemoteCertificateValidate to get the information you use. The host name must be as an alternate name for the certificate or, if there is no alternate name for the object, in the CN of the subject name (allocated). Given the way a text string is formatted in .NET, this should be the first CN = you find there.

You will also get more data if certificate is an instance of X509Certificate2 . Then you can get the SubjectName as X500PrincipalName , as well as Extensions (to check the extension of the alternate name of the object). It might be useful to use tools like BouncyCastle to parse the name of an object.

You will probably also get additional information about the name of the host you are trying to contact in sender , depending on the type of execution.

+7
source

All Articles