Do not disable certificate validation
Do not disable certificate validation
Microsoft docsDescription
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. If the System.Net.ServicePointManager.ServerCertificateValidationCallback always returns true, then by default any certificate will pass validation for all outgoing HTTPS requests.
Cause
The callback assigned to System.Net.ServicePointManager.ServerCertificateValidationCallback always returns true.
How to fix violations
- Considering overriding certificate validation logic on the specific outgoing HTTPS requests that require custom certificate validation, instead of overriding the global System.Net.ServicePointManager.ServerCertificateValidationCallback.
- Apply custom validation logic to only specific hostnames and certificates, and otherwise check that the System.Net.Security.SslPolicyErrors enum value is
None.
Example
using System.Net;
class ExampleClass
{
public void ExampleMethod()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => { return true; };
}
}
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;
}
}When to suppress
If multiple delegates are attached to System.Net.ServicePointManager.ServerCertificateValidationCallback, only the value from the last delegate is respected, so it's safe to suppress warnings from other delegates. However, you may want to remove the unused delegates entirely.