Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF per connection server certificate validation

Tags:

c#

ssl

wcf

I'm trying to bypass https certificate validation only to our own testing environment (multiple machines), while trying to keep certificate validation for all the other connection.

From reading online, most (if not all) WCF related suggestion seems to point to the something similar of following

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

However, this is a global setting and I would like to apply this for only a specific connection. Is this even possible/supported usage scenario?

like image 968
BlueFox Avatar asked Dec 06 '13 19:12

BlueFox


People also ask

How do I validate a server certificate?

To check an SSL certificate on any website, all you need to do is follow two simple steps. First, check if the URL of the website begins with HTTPS, where S indicates it has an SSL certificate. Second, click on the padlock icon on the address bar to check all the detailed information related to the certificate.

What are WCF certificates?

To program Windows Communication Foundation (WCF) security, X. 509 digital certificates are commonly used to authenticate clients and servers, encrypt, and digitally sign messages.


1 Answers

I was finally able to found a real solution when using .net 4.5.

This code allows you to use a custom validator only for a specific WCF client.

It has been tested against BasicHttpBinding with BasicHttpSecurityMode.Transport.

There is a new property named SslCertificateAuthentication in ClientBase.ClientCredentials.ServiceCertificate.

You can initialize this property with a X509ServiceCertificateAuthentication where you can provide a custom X509CertificateValidator.

For example:

// initialize the ssl certificate authentication
client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
{
   CertificateValidationMode = X509CertificateValidationMode.Custom,
   CustomCertificateValidator = new CustomValidator(serverCert)
};

// simple custom validator, only valid against a specific thumbprint
class CustomValidator : X509CertificateValidator
{
    private readonly X509Certificate2 knownCertificate;

    public CustomValidator(X509Certificate2 knownCertificate)
    {
        this.knownCertificate = knownCertificate;
    }

    public override void Validate(X509Certificate2 certificate)
    {
        if (this.knownCertificate.Thumbprint != certificate.Thumbprint)
        {
            throw new SecurityTokenValidationException("Unknown certificate");
        }
    }
}
like image 194
tbolon Avatar answered Nov 15 '22 19:11

tbolon