Class System.Net.Security.CertificationPolicies

Represents the policies used to validate X.509 certificates during SSL/TLS connections. This class provides a way to customize the certificate validation process, allowing you to define specific rules and checks for certificate trust.

Namespace

System.Net.Security

Assembly

System.Net.Security.dll

Remarks

The CertificationPolicies class is crucial for establishing secure communication channels. When a client connects to a server using SSL/TLS, the client's certificate (or the server's certificate, depending on the authentication type) is presented for validation. The CertificationPolicies class allows developers to intercept and influence this validation process.

By default, .NET Framework performs a standard chain-building and revocation check. However, in certain scenarios, you might need to implement custom validation logic, such as:

  • Validating certificates against a private certificate store.
  • Implementing custom revocation checking mechanisms.
  • Performing checks based on specific certificate attributes or policies.
  • Allowing self-signed certificates under controlled conditions.

This class typically works in conjunction with delegates like System.Net.Security.RemoteCertificateValidationCallback, which are invoked during the SSL/TLS handshake to determine whether a remote certificate is trusted.

Properties

Name Description
DefaultPolicy Gets a read-only instance of the default certification policy. This policy uses the system's trusted root certificate store and performs standard revocation checks.

Methods

Name Description
Evaluate(X509Certificate2, X509Chain, SslPolicyErrors) Evaluates the given certificate against the current certification policy.

Method: Evaluate(X509Certificate2, X509Chain, SslPolicyErrors)

Evaluates the given certificate against the current certification policy.

Parameters
certificate As X509Certificate2
The certificate to evaluate.
chain As X509Chain
The certificate chain associated with the certificate.
sslPolicyErrors As SslPolicyErrors
The errors encountered during the initial SSL policy evaluation.
Returns

Boolean - True if the certificate is considered valid according to the policy; otherwise, False.

Remarks

This method is typically called internally by the .NET Framework's networking stack. When implementing custom certificate validation, you often provide a callback function that performs similar logic.

Example Usage

C#
VB.NET

C# Example: Custom Certificate Validation

This example demonstrates how to create a custom certificate validation callback to bypass certificate errors for testing purposes (use with caution in production).


using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class CustomCertificateValidation
{
    public static void Main(string[] args)
    {
        // In a real application, you would likely be using an HttpClient or similar
        // For demonstration, we'll simulate a scenario where we need to bypass validation.

        string url = "https://self-signed.example.com"; // A URL that might have certificate issues

        // Create a ServicePointManager configuration for the specific URL
        // Note: Modifying ServicePointManager affects all HTTP requests in the application domain.
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

        try
        {
            // Attempt to make an HTTP request. The custom callback will be used.
            using (WebClient client = new WebClient())
            {
                Console.WriteLine($"Attempting to access: {url}");
                string result = client.DownloadString(url);
                Console.WriteLine("Successfully accessed URL.");
                // Console.WriteLine("Response: " + result); // Uncomment to see response
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
            if (ex.Status == WebExceptionStatus.TrustFailure)
            {
                Console.WriteLine("This is likely due to certificate validation failure.");
            }
        }
        finally
        {
            // It's good practice to reset the callback if you only need it for specific operations.
            // In this simple example, it's commented out, but in larger apps, manage scope.
            // ServicePointManager.ServerCertificateValidationCallback = null;
        }
    }

    public static bool ValidateServerCertificate(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        // *** CAUTION: This is a permissive validation for demonstration only. ***
        // *** Do not use this in production environments without understanding the risks. ***

        Console.WriteLine($"Certificate received: {(certificate as X509Certificate2)?.Subject ?? "Unknown"}");
        Console.WriteLine($"SSL Policy Errors: {sslPolicyErrors}");

        // If there are no errors, the certificate is valid.
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            Console.WriteLine("Certificate is valid.");
            return true;
        }

        // Handle specific errors you want to allow.
        // For example, allowing untrusted root certificates for testing:
        if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
        {
            Console.WriteLine("Ignoring RemoteCertificateChainErrors. Proceeding with validation...");
            // You could inspect the chain here for specific reasons if needed.
            // For example, if you know the specific root is trusted in your custom store.
            return true; // Allow if only chain errors, and we want to bypass them
        }

        // If there are other errors or we don't want to bypass them, return false.
        Console.WriteLine("Certificate validation failed.");
        return false;
    }
}

VB.NET Example: Custom Certificate Validation

This example demonstrates how to create a custom certificate validation callback to bypass certificate errors for testing purposes (use with caution in production).


Imports System
Imports System.Net
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates

Public Class CustomCertificateValidationVB
    Public Shared Sub Main(args As String())
        ' In a real application, you would likely be using an HttpClient or similar
        ' For demonstration, we'll simulate a scenario where we need to bypass validation.

        Dim url As String = "https://self-signed.example.com" ' A URL that might have certificate issues

        ' Create a ServicePointManager configuration for the specific URL
        ' Note: Modifying ServicePointManager affects all HTTP requests in the application domain.
        ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateServerCertificate

        Try
            ' Attempt to make an HTTP request. The custom callback will be used.
            Using client As New WebClient()
                Console.WriteLine($"Attempting to access: {url}")
                Dim result As String = client.DownloadString(url)
                Console.WriteLine("Successfully accessed URL.")
                ' Console.WriteLine("Response: " + result) ' Uncomment to see response
            End Using
        Catch ex As WebException
            Console.WriteLine($"An error occurred: {ex.Message}")
            If ex.Status = WebExceptionStatus.TrustFailure Then
                Console.WriteLine("This is likely due to certificate validation failure.")
            End If
        Finally
            ' It's good practice to reset the callback if you only need it for specific operations.
            ' In this simple example, it's commented out, but in larger apps, manage scope.
            ' ServicePointManager.ServerCertificateValidationCallback = Nothing
        End Try
    End Sub

    Public Shared Function ValidateServerCertificate(
        sender As Object,
        certificate As X509Certificate,
        chain As X509Chain,
        sslPolicyErrors As SslPolicyErrors) As Boolean

        ' *** CAUTION: This is a permissive validation for demonstration only. ***
        ' *** Do not use this in production environments without understanding the risks. ***

        Console.WriteLine($"Certificate received: {(certificate)?.Subject ?? "Unknown"}")
        Console.WriteLine($"SSL Policy Errors: {sslPolicyErrors}")

        ' If there are no errors, the certificate is valid.
        If sslPolicyErrors = SslPolicyErrors.None Then
            Console.WriteLine("Certificate is valid.")
            Return True
        End If

        ' Handle specific errors you want to allow.
        ' For example, allowing untrusted root certificates for testing:
        If (sslPolicyErrors And SslPolicyErrors.RemoteCertificateChainErrors) <> 0 Then
            Console.WriteLine("Ignoring RemoteCertificateChainErrors. Proceeding with validation...")
            ' You could inspect the chain here for specific reasons if needed.
            ' For example, if you know the specific root is trusted in your custom store.
            Return True ' Allow if only chain errors, and we want to bypass them
        End If

        ' If there are other errors or we don't want to bypass them, return false.
        Console.WriteLine("Certificate validation failed.")
        Return False
    End Function
End Class

See Also