Search code examples
c#sslhttpclient

Get detailed explanation for invalid SSL certificate (.NET)


My service does health pings to customer web sites and reports their health. One of common issues of web site being down is being something wrong with SSL certificate.

In ServicePointManager.ServerCertificateValidationCallback it is possible to get access to certificates, chain, etc. and to do manual checks (when SslPolicyErrors is not None).

I wonder whether there is a library/method which gives explanation what's wrong (for instance, certificate is expired or root certificate is untrusted, etc.)


Solution

  • The X509Chain class can provide a detailed explanation why some certificate is considered invalid.

      var errors = new List<string>();
      var chain = new X509Chain();
      // certificate is the one you want to check
      chain.Build(certificate);
    
      // traverse certificate chain
      foreach (var chainElement in chain.ChainElements)
      {
        // ChainElementStatus contains validation errors
        foreach (var status in chainElement.ChainElementStatus)
        {
          errors.Add(status.Status + " " + chainElement.Certificate + ": " + status.StatusInformation.Trim());
        }
      }
    

    This is similar to what X509Certificate2.Verify does (if you look into the source code), albeit Verify only returns true or false.