Using client certificates in .NET part 1: introduction

Introduction

Digital certificates play a crucial role in web security. If you work as a web developer then you’ve probably come across at least some security related project where you had to deal with certificates in code.

Certificates come in a couple of different versions depending on their function, the most pervasive of which probably being server side ones for SSL connections. We’ve gone through server side certificates in some detail before on this blog starting here. In this series we’ll concentrate on client certificates and see what role they can play in web security. Most of the material on server side certificates, especially the first 2 posts are also relevant for this discussion.

It’s important to note already now that you can combine a number of security levels and solutions in your projects:

  • You can have the traditional forms based authentication. You can read about it on this blog here and here.
  • Custom authentication. Here‘s a series dedicated to custom auth in Web API 2 as an OWIN/Katana component
  • Server-side certificates, see the reference above
  • Client-side certificates, to be discussed in this series
  • Various techniques related to cryptography, such as asymmetric encryption. You can check out the section called “Security and cryptography” on this page for inspiration.

…and there are probably many more options not listed here. The point is that these techniques can be combined, you are not restricted to just using one of them.

Read more of this post

HTTPS and X509 certificates in .NET Part 5: validating certificates in code

Introduction

In the previous post we looked at some basic classes in the .NET framework that deal with X509 certificates. We saw how to load, inspect, install and remove certificates.

In this post we’ll continue working with certificates in code and concentrate on validation techniques.

Certificate validation in C#

The two most important objects in .NET that will help you validate a certificate are X509Chain and X509ChainPolicy.

The X509Chain object represents the chain of trust when checking the validity of a certificate. X509ChainPolicy fine-tunes how you’d like to validate the certificate, i.e. which criteria the chain of trust should fulfil.

Let’s see how the self-signed certificate we created before can be validated. Consider the following sample code:

private static void RunValidation()
{
	X509Store computerCaStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
	try
	{
		computerCaStore.Open(OpenFlags.ReadOnly);
		X509Certificate2Collection certificatesInStore = computerCaStore.Certificates;
		X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, "mylocalsite.local", false);				
		foreach (X509Certificate2 cert in findResult)
		{
			X509Chain chain = new X509Chain();
			X509ChainPolicy chainPolicy = new X509ChainPolicy()
			{
				RevocationMode = X509RevocationMode.Online,
				RevocationFlag = X509RevocationFlag.EntireChain
			};
			chain.ChainPolicy = chainPolicy;
			if (!chain.Build(cert))
			{
				foreach (X509ChainElement chainElement in chain.ChainElements)
				{
					foreach (X509ChainStatus chainStatus in chainElement.ChainElementStatus)
					{
						Debug.WriteLine(chainStatus.StatusInformation);
					}
				}
			}
		}				
	}
	finally
	{
		computerCaStore.Close();
	}
}

You’ll recognise the part of this code where we open the certificate store and load the self-signed derived certificate. Note that the Find method will return a collection of X509 certificates but there’s no way to extract just a single element from a X509Certificate2Collection object. Even if you know that there’s only one certificate that fulfils the search criteria you’ll need to iterate over the collection.

Anyway, the validation part of the code starts within the foreach loop by constructing an X509Chain object. We then build a policy for the chain by specifying a couple of properties.

The RevokationMode enumeration will define whether or not we want to check the revocation list for this certificate: check it on-line, off-line or not at all. X509RevocationFlag will specify if we want to check the revocation list with or without the CA root. The X509ChainPolicy object has some more properties that will let you fine-grain the chain policy. The VerificationFlags enumeration will let you switch off parts of the chain, e.g.:

VerificationFlags = X509VerificationFlags.IgnoreInvalidName | X509VerificationFlags.IgnoreNotTimeValid

Normally you’d want to verify all properties so you’ll leave VerificationFlags untouched.

We then want to build the chain by calling the Build method with the certificate. If Build returns false then we know that something isn’t correct with the validation chain. So for each element in the chain elements we want to check the element status messages.

If you run the above code then you should get a validation error:

“The revocation function was unable to check revocation for the certificate.”

That’s because we specified that the online revocation list should be checked. However, there’s no revocation list anywhere on Earth that knows about our self-signed certificate. If we change the code to…

X509ChainPolicy chainPolicy = new X509ChainPolicy()
{
	RevocationMode = X509RevocationMode.NoCheck,
        RevocationFlag = X509RevocationFlag.EntireChain
};

…then the Build method passes as everything is fine with the certificate.

Open IIS for another test. We’ll use the IIS GUI to quickly create another certificate. Double-click on the following icon:

Certificates button in IIS

Then click on the following link in the right-hand panel:

Create self signed certificate link in IIS

Provide some friendly name for the certificate and click OK.

The certificate should appear in the Personal folder in the Certificates snap-in after a refresh. I called my certificate “iiscertificate”:

Certificate created in IIS visible in MMC snap in

If you double-click this certificate then you’ll see that it is valid. Now if we change the code back to online revocation list checking…

X509ChainPolicy chainPolicy = new X509ChainPolicy()
{
	RevocationMode = X509RevocationMode.Online,
        RevocationFlag = X509RevocationFlag.EntireChain
};

…and search for the IIS certificate…:

X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, "andras1.Apica.local", false);

…then Build will return true, the IIS certificate is fully trusted even after the CRL is checked.

The certificate was also inserted into the Trusted Root Certification Authorities folder:

IIS certificate also listed among CA certificates

If you don’t see it then refresh the list by pressing F5.

Now remove the certificate from the trusted CA folder. Then go back to the Personal folder and double-click the IIS certificate. You should see that it is not trusted any more:

IIS certificate not trusted after removing from global CA store

If we run the same code again then Build returns false and we get the following validation error:

“A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.”

The message clearly says that the root certificate is not trusted.

A more compact solution

The above code lets you fine-grain your chain building logic. There are specialised X509 validators in .NET that provide a more compact way of validating a certificate. Add the following references to your project:

References for X509 validators

The below example will build a validator that validates the chain of trust with all the validation flags turned on:

X509CertificateValidator chainTrustValidator = X509CertificateValidator.ChainTrust;
try
{
	chainTrustValidator.Validate(cert);
}
catch (Exception ex)
{
	Debug.WriteLine(ex.Message);
}

The Validate method will throw an exception if the validation fails. The untrusted IIS certificate will give the following exception message:

“The X.509 certificate CN=andras1.Apica.local chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.”

That’s all folks about the basics of certificate validation in .NET.

This was the last post in this HTTPS basics series.

You can view the list of posts on Security and Cryptography here.

HTTPS and X509 certificates in .NET Part 4: working with certificates in code

Introduction

In the previous post we successfully installed our self-signed CA certificate in the Trusted Root CA folder. We also installed a derived certificate in the Personal certificates folder. We then saw how to make IIS use our certificate for a secured web site.

In this post we’ll start looking into the certificate-related classes in .NET.

Loading a certificate from a file

Digital certificates are represented by the X509Certificate2 class in .NET located in the System.Security.Cryptography.X509Certificates namespace. The class has numerous overloaded constructors. You can pass in the file path to the certificate, a byte array content, a password etc. Let’s see whether we can load the CA certificate we created before in this series:

Read more of this post

HTTPS and X509 certificates in .NET Part 3: how to install certificates and use them with IIS

Introduction

In the previous post we looked at the command line tools makecert and pvk2pfx. We saw how they could be used to create a root and a derived certificate and to package the private key and certificate files.

In this post we will install the certificates in the Windows certificate store so that they are trusted by IIS. We’ll also see how to tell IIS to use a specific SSL certificate.

certmgr and MMC snap in

The c:\windows\system32 folder includes two GUI tools for certificate management: certmgr.msc and mmc.exe. MMC.exe is a more general tool where you can import so-called snap-ins. Certificates have their own snap-in.

Run mmc.exe as an administrator. The following empty window will open:

Read more of this post

HTTPS and X509 certificates in .NET Part 2: creating self-signed certificates

Introduction

In the previous post we looked at TLS and certificates in general. We saw what makes up an SSL certificate and how browsers use it to verify the identity of the server and to decrypt/encrypt the communication.

In this post we’ll look at a tool called makecert.exe.

Before we actually continue there are some other important terms that we need to investigate.

Read more of this post

HTTPS and X509 certificates in .NET Part 1: introduction

Introduction

HTTPS, SSL, TLS – these terms are used interchangeably to denote secure communication between a web client and a web server. Secure HTTP communication generally must ensure all of the following:

  • The data sent by the client to the server shouldn’t be tampered with by a third party in between – at least not without the server noticing it
  • The secured data sent by the client should not be easily deciphered by a third party
  • The client must be sure that the web server is really the one it claims to be, i.e. the it belongs to twitter.com and not some bogus site claiming to be twitter.com
  • An attacker should not be able to take the client’s input and resend it to the server multiple times

Read more of this post

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: