CS.X509.VALIDATION

Certificate validation is disabled

A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. The CS.X509.VALIDATION checker flags code instances in which the ServicePointManager.ServerCertificateValidationCallback property always returns with a value of true. If it does, then any certificate, even invalid or malicious ones, will pass validation.

Vulnerability and risk

When a certificate is invalid or malicious, it can allow an attacker to spoof a trusted entity by interfering in the communication path between the host and client. The software could connect to a malicious host while believing it is a trusted host, or the software could be deceived into accepting spoofed data that appears to originate from a trusted host.

Vulnerable code example

Copy
  using System.Net;
  using System.Net.Security;
   using System.Security.Cryptography.X509Certificates;
    
  class ExampleClass
  {
      public void ExampleMethod()
      {
          ServicePointManager.ServerCertificateValidationCallback += SelfSignedForLocalhost;
     }
  
     private static bool SelfSignedForLocalhost(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
     {
         return true; // Any certificate will pass validation
     }
 }

Fixed code example

Copy
  using System.Net;
  using System.Net.Security;
  using System.Security.Cryptography.X509Certificates;
   
  class ExampleClass
  {
      public void ExampleMethod()
      {
          ServicePointManager.ServerCertificateValidationCallback += SelfSignedForLocalhost;
     }
  
     private static bool SelfSignedForLocalhost(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
     {
         if (sslPolicyErrors == SslPolicyErrors.None)
         {
             return true;
         }
  
         // For HTTPS requests to this specific host, we expect this specific certificate.
         // In practice, you'd want this to be configurable and allow for multiple certificates per host, to enable
         // seamless certificate rotations.
         return sender is HttpWebRequest httpWebRequest
                 && httpWebRequest.RequestUri.Host == "localhost"
                 && certificate is X509Certificate2 x509Certificate2
                 && x509Certificate2.Thumbprint == "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                 && sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors;
     }
 }

Security training

Application security training materials provided by Secure Code Warrior.