Class SslValidationResults

System.Net.Security
Summary: Represents the results of an SSL certificate validation.

Syntax

public sealed class SslValidationResults

Remarks

The SslValidationResults class provides information about the outcome of the SSL/TLS certificate validation process performed by the .NET Framework. When establishing a secure connection using SSL/TLS, the client validates the server's certificate. This validation process checks various aspects of the certificate, such as its authenticity, validity period, and whether it's trusted by a trusted Certificate Authority (CA).

Instances of this class are typically returned by methods that perform certificate validation, allowing you to inspect the details of any validation errors or successes. This information is crucial for debugging and for implementing custom validation logic.

Fields

Properties

Methods

Fields

InvalidCertificateName

public const SslValidationResult InvalidCertificateName

Indicates that the certificate's subject name does not match the name of the server. This is a common validation failure.

InvalidCertificateType

public const SslValidationResult InvalidCertificateType

Indicates that the certificate is of an invalid type (e.g., a client certificate used for server authentication).

InvalidCertificateVersion

public const SslValidationResult InvalidCertificateVersion

Indicates that the certificate uses an unsupported version.

InvalidChain

public const SslValidationResult InvalidChain

Indicates that the certificate chain is invalid, meaning it cannot be traced back to a trusted root certificate.

InvalidTrustRoot

public const SslValidationResult InvalidTrustRoot

Indicates that the trusted root certificate used to validate the chain is not trusted by the system.

InvalidSignature

public const SslValidationResult InvalidSignature

Indicates that the certificate's signature is invalid, which could mean it has been tampered with.

InvalidNotBefore

public const SslValidationResult InvalidNotBefore

Indicates that the certificate is not yet valid (the validity period has not started).

InvalidNotAfter

public const SslValidationResult InvalidNotAfter

Indicates that the certificate has expired (the validity period has ended).

UntrustedRoot

public const SslValidationResult UntrustedRoot

Indicates that the root certificate in the chain is not trusted by the local system.

Revoked

public const SslValidationResult Revoked

Indicates that the certificate has been revoked by the issuing Certificate Authority (CA).

Expired

public const SslValidationResult Expired

A shorthand for InvalidNotAfter, indicating the certificate has expired.

UnknownError

public const SslValidationResult UnknownError

Indicates an unspecified error occurred during validation.

Success

public const SslValidationResult Success

Indicates that the certificate validation was successful without any errors.

Properties

IsValid

public bool IsValid { get; }

Gets a value indicating whether the SSL certificate validation was successful.

ValidationFlags

public SslValidationResult ValidationFlags { get; }

Gets a bitmask of SslValidationResult values that indicate specific reasons for validation failure. If the certificate is valid, this property will be SslValidationResults.Success.

Methods

Equals

public override bool Equals(object obj)

Determines whether the specified object is equal to the current object.

GetHashCode

public override int GetHashCode()

Serves as the default hash function.

GetType

public Type GetType()

Gets the type of the current instance.

ToString

public override string ToString()

Returns a string that represents the current object.

Examples

The following example demonstrates how to use the SslValidationResults class to check the validity of an SSL certificate during an HTTP request.


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

public class SslValidationExample
{
    public static void Main(string[] args)
    {
        string serverName = "www.example.com";
        int port = 443;

        try
        {
            using (TcpClient client = new TcpClient(serverName, port))
            {
                using (SslStream sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null))
                {
                    SslProtocol[] protocols = new SslProtocol[] {
                        SslProtocol.Tls12,
                        SslProtocol.Tls11,
                        SslProtocol.Tls
                    };
                    sslStream.AuthenticateAsClient(serverName, null, SslProtocols.Tls12, false);

                    // If authentication is successful, sslStream.IsAuthenticated will be true.
                    // The ValidateServerCertificate callback handles explicit validation results.

                    // Further communication can happen here...
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: {0}", ex.Message);
        }
    }

    public static bool ValidateServerCertificate(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        SslValidationResult validationResult = SslValidationResult.Success;

        // Check for common policy errors
        if (sslPolicyErrors != SslPolicyErrors.None)
        {
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                validationResult |= SslValidationResult.InvalidCertificateName;
                Console.WriteLine("Certificate name mismatch.");
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                // This error is less common in typical scenarios, indicates certificate not provided.
                validationResult |= SslValidationResult.UnknownError;
                Console.WriteLine("Remote certificate not available.");
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                // Examine the chain to find the specific error
                foreach (X509ChainStatus status in chain.ChainStatus)
                {
                    switch (status.Status)
                    {
                        case X509ChainStatusFlags.Revoked:
                            validationResult |= SslValidationResult.Revoked;
                            break;
                        case X509ChainStatusFlags.Expired:
                            validationResult |= SslValidationResult.Expired;
                            break;
                        case X509ChainStatusFlags.NotTimeValid:
                            validationResult |= SslValidationResult.InvalidNotBefore | SslValidationResult.InvalidNotAfter;
                            break;
                        case X509ChainStatusFlags.UntrustedRoot:
                            validationResult |= SslValidationResult.UntrustedRoot;
                            break;
                        case X509ChainStatusFlags.InvalidSignature:
                            validationResult |= SslValidationResult.InvalidSignature;
                            break;
                        default:
                            validationResult |= SslValidationResult.UnknownError;
                            break;
                    }
                }
            }
        }

        // You can then use validationResult to determine if the connection is safe.
        if (validationResult == SslValidationResult.Success)
        {
            Console.WriteLine("Certificate validation successful.");
            return true;
        }
        else
        {
            Console.WriteLine("Certificate validation failed. Result: {0}", validationResult);
            return false; // Reject the connection
        }
    }
}