Testing SChannel code

I developed the new SChannel SSL adapter for The Server Framework in a mostly test driven style; a while ago I called this Just In Time Testing… It worked well and, to be honest, I couldn’t imagine developing code as complex as the SChannel adapter without tests; though as I noted when I first set out on the development, back in 2001 I’d developed the corresponding OpenSSL adapter without any tests at all… The tests worked well for me this time around and I was able to both learn about the SChannel API that I was using and implement the required code far easier with the tests in place. One thing wasn’t quite right though…

To test the SChannel code I created a client and server version of the adapter and pushed clear text data into one and pushed the resulting encrypted data into the other and pulled the clear text out the other end. Of course, this was a bit more of an integration test than I would have liked but there weren’t many other choices. Before I could even get to that point I needed a certificate for my SChannel context. I simply added a suitable certificate to my development machine’s certificate store using the MMC plugin and then pulled the certificate out of the local machine’s certificate store and into my test code. This worked but it meant that running the tests on any machine was impossible. The machine had to have the appropriate certificate installed before I could run tests. This meant that these tests weren’t automatically run by my build machines as I couldn’t be bothered to jump through all the hoops required to set up the hard coded certificates and what’s more the tests were somewhat fragile in that they wanted a particular certificate (mainly due to the tests expecting the ‘correct’ amount of data to flow between the two ends of the connection and ‘correct’ during the initial handshake depended on the contents of the certificate itself).

I knew how to fix all of this and so an item was added to my todo list. Today I’ve almost knocked that item off the list.

SChannel uses certificates from the Microsoft Certificate Store. You can have multiple stores on a machine and you can create your own in memory or file backed stores. My tests now use an in memory store that loads itself from a PFX format PKCS#12 file. This means that I can ship the certificate to use as part of my tests and the tests can load the certificate. It also opens up the option of embedding a certificate (or even a whole certificate store) in code; perhaps as a resource.

In getting to this point I needed to learn (once again) about how to create certificates using OpenSSL and how to convert them to the correct format for the Microsoft APIs to load them. These links here and here were very useful for that.

Now that I have a set of Certificate Store manipulation code I expect I can use it to allow tighter integration of the OpenSSL adapter to the Microsoft Certificate Store; should anyone want it…