Sunday, 10 December 2017

Configure IIS to use your self signed certificates with your application including IIS client certificate mapping authentication

I’m now assuming that you read my previous post about how to create self signed certificates for development and it might’ve left you thinking “Yay great! ….But how do I actually use them?”. This blog post will take you step by step through the manual process of configuring IIS on your PC or Windows Server to use your self signed certificates together with IIS client certificate mapping authentication.
Please note that I in my examples I use my localhost hosting and a random domain name but you can do this on your real server’s IIS if you have a static IP address from your internet service provider or your domain hosting company as well as configured your firewall, router etc. correctly where finally you can point your domain name to your that address. BUT I won’t recommend either together with self signed certificates unless your clients/users are willing to receive and install your self-signed root and client certificate. A good example of this is in a closed intranet where you have access to all the end-user’s computers because then you can install the certificates on their machines, which is necessary if you don’t want your users to get a big fat warning about trust issues with your self signed server certificate. If you are looking for a commercial production-worthy solution you should purchase your certificates instead of self signing. So now we have that out of the way I’m using a PC with Windows 8.1 Pro, IIS 8.5 and Visual Studio Premium 2013. (I’ve also tested with a Windows Server 2012 R2 Hyper-V VM on my PC).
Installing IISIf you haven’t already installed IIS on the machine that will act as the hosting server, please do so by pressing the Windows button for a PC and search “Turn Windows features on or off” (or go to Control Panel and search). Check Internet Information Services and the following childnodes.1 complete IIS install(If you are running on .NET 3.5 you need to check the .NET Extensibility 3.5 and ASP.NET 3.5)
For Windows Server 2012 go to the Server Manager Dashboard  Click add roles and features  Choose role-based or feature-based installation and go next  Select the server  Enable the server role called Web Server (IIS) and following child elementsServer IIS
Also make sure Application Development is checked with the following childnodesServer IIS application dev
Click OK and let Windows install.
Creating our sample project
For the sake of this demo we’ll create a really simple mini application that we will be hosting in the local IIS. (You can also just fork mine directly at Github)
In Visual Studio, create a new empty web application and reference web api5 New Project
We’ll just need a reeeeaally simple controller:
You should now be able to run both routes (F5) and surf to the localhost url with /api/cats (mine looks like http://localhost:62172/api/cats). Awesome, lets host this application using our local IIS.
NOTE: We will no longer be running the application directly from Visual Studio (F5) which is set to use IIS Express.
Configuring IIS
Open your IIS Manager (Windows button + search for it). Add a new website and application pool with our sample application. (Right-click Sites  Add Website) The path needs to be the folder where your web site documents are located, so if you have published your website point the path there. I’m just going to use the direct path to the project in Visual Studio for this very simple example.
Now let’s locally host this site by specifying the host name AKA. your domain name.7 yourdomain.com
Since I’m just hosting locally I need to add the site to my local hosts file in order to bind my localhost IP address with the host name. This is done by running notepad as administrator and opening the hosts file in the path: %systemroot%\System32\drivers\etchosts file
Adding the following at the end: 127.0.0.1 yourdomain.com www.yourdomain.com8 hosts file
Now whenever I surf to yourdomain.com and www.yourdomain.com on my machine it will resolve the site with my newly added bindings to the 127.0.0.1 IP address (which is localhost’s IP).
Let’s add the www. binding to your site in the IIS Manager as well9 IIS bindings10 add http binding11 domain with www12 both http added
Surf to the domain name you set up in the bindings with or without www. and add the ending /api/cats and you should get the meowing cats. (If not try emptying the cache)
IMPORTANT: This is ONLY going to happen on the local machine because we altered the hosts file to redirect our requests of the domain name we added to the localhost IP address. It is meant for development and to be able to test your changes before deploying them to your real web hosting server.
Securing the server with SSL
Now we want to secure the cats by adding a SSL certificate to our Server.
In your IIS Manager go to your server (The top of the tree to the left) ➜ Scroll down and double-click Server Certificates.13 IIS Server
(If your self signed certificate is already here, jump ahead to the bindings steps)
We need to import our self signed server certificate in order to enable https communication with SSL, so click Import…14 Import server cert
Click the … and find your .pfx file, fill out the password (the -po parameter in your command batch file) and click OK15 browse server cert
Your certificate is now added16 cert added
Double-click the newly added cert to verify that it is trusted (Your self signed certificates were added to the correct stores in my previous post, so again: read it if you are lost right now ;-))
17 trusted server cert
So far, so good! Now we can add the https binding, the same way as before but choose https with port 443, your domain as the host name and find your self signed certificate in the drop down list
18 bindings add ssl
Check the Server Name Indication box which enables our server to have multiple certificates installed on the same IP address by sending the hostname with the first stage of the SSL handshake. Repeat the same steps to add SSL for www.yourdomain.com but with a certificate where the CN name matches the domain name or a wildcard certificate
19 https www with wildcard
Our bindings are complete for now
19 All bindings
Tadaa, you can now use https://yourdomain.com/api/cats and https://www.yourdomain.com/api/cats
NOTE: Firefox doesn’t use the Windows certificate store, so you will have to add your root CA manually. Go to Firefox Settings Options  Advanced  View Certificates  Authorities  import your CARoot.cer file
IIS Client Certificate Mapping Authentication
We have now been through the uses of the root and server certificates and you are probably wondering what to do with the client certificate we also created in my previous post. This is for situations when we for example need to authenticate clients without a user login and password approach but rather want the server to ask the client to show it’s certificate and if it’s the correct one the client is allowed in. This can be done with a Many-To-One or a One-To-One mapping and I will show you how to do both manually in the IIS Manager.
First we need to install the feature, so bring up the “Turn Windows features on or off” again and install the following20 IIS client cert mapping
We’ll tell our server to require a SSL certificate from the client21 SSL Settings22 apply require ssl
Then we need to configure the server to know which client certificate it needs to validate, so go to the Configuration Editor and choose the iisClientCertificateMappingAuthentication section (you can also enter the path system.webServer/security/authentication/iisClientCertificateMappingAuthentication into the Section field)24 iisClientCertMapAuth section
Many-To-One MappingsIf you want to map multiple client certificate to a single user this approach is what you need. You can also share client certificates like this by installing the client certificate (and the CA Root, since we are self-signing certificate) on other users on whichever machine to gain access as long as the client certificate matches the rule criterias of the mapping. It would for example be useful in a situation where you would want all users in an organization to gain access through a single user mapping.
Enable the client certificate mapping authentication25 enable client auth
To add a mapping click the … of the manyToOneMappings26 add mapping
Here you add the users that you want to grant access.27 add new mapping
Fill out the properties for a mapping and repeat for each user you want to configure for access or denial. Remember that you need the client certificate and root CA certificate installed on all the user’s mmc.
28 manytoone mapping
IMPORTANT: In order for this to work you need to enter a valid username and password and since my computer is the server, the credentials will be my Windows username and password.
Now we need to create some rules to go with this mapping so the server can determine if a client is allowed in or not. It’s a  so click on the rules property and the … button
29 add rule
I will add one rule as an example where the server will check the client certificate to see if it’s signed by the correct CA root. Go ahead and add more rules for more safety, please visit the IIS Many-To-One Mapping reference for more documentation.
31 rule
Remember to apply the changes in the IIS Manager, so close the rules and mappings windows and click Apply32 apply changes
Open a new incognito browser window to make sure to start from a clean slate cache and cookie-wise and enter your url with the /api/cats and see the browser prompting you for a certificate. Choose the ClientCert and click ok to gain access to the cats.33 ok client cert
If this is not working make sure that your client certificate is in your CurrentUser/Personal store as well as in your browser’s certificate store. If yes, then go to Control Panel  Internet Options  Content and click Clear SSL state.34 clear ssl state
Open a new incognito windows and try again, your browser should now prompt you for the client certificate.
NOTE: Remember as I explained earlier on, Firefox has it’s own certificate store so you need to import the client certificate into “Your Certificates” in order to use this.
One-To-One Mappings
Let’s walk through the one-to-one mappings as well. This approach means that we need an individual client certificate for each user mapping. You can either disable the many-to-one mapping and use the same certificate and user or create new ones. Go back to the Configuration Editor and open the iisClientCertificateMappingAuthentication section again. Click the … of the oneToOneMappings.35 enable one to one mappings
To add the mapping to the certificate we need to export the public key of the client certificate file. You can export this from your Machine Management Console (press the Windows button and search for mmc) Snap-in the Local Machine’s Certificate’s personal store and export the client ssl certificate you want to use without the private key in the base64 format.Export client certWithoug private keybase64 export
Right-click the newly exported certificate and open with notepad. Remove all the line-breaks in the certificate itself.Remove linebreaks
Now copy that into the certificate property field of the mapping and fill out the rest38 add user mapping
IMPORTANT: In order for this to work you need to enter a valid username and password and since my computer is the server, the credentials will be a Windows username and password.
Again, remember to apply the changes.39 apply changes
And there you go, try it out and when prompted choose the certificate you mapped to the user you just mapped.

Creating self signed certificates with makecert.exe for development

If you’ve ever had the need of creating self signed certificates you may start out feeling like it’s not a straightforward stroll in the park, so here is a blog post that might help you to get started. I will be going through the basics of creating self signed X.509 certificates (Root, server & client) using makecert.exe.
For the complete makecert.exe parameter reference click here.
I’m using a PC with Windows 8.1 Pro and Visual Studio Premium 2013.
Certificate Authority (CA)
Normally most companies would just buy their certificates from a trusted third party certificate authority such as GoDaddy or Verisign, but for development and testing, this might not be the first thing one wants to do. Instead you can create your own self signed certificates, starting with a root CA that can be used to sign other certificates. (For example ssl certificates for servers and clients). When you do this, the certificates are not trusted by default. You must therefore add the root CA to your machine’s Trusted Root Certification Authorities Store through the Microsoft Management Console.
NOTE: You can add these two parameters: -sr LocalMachine ^ and -ss Root ^ to the upcoming command batch file, if you want to install the certificate directly into the LocalMachine’s Trusted Root Certification Authorities. BE SURE to run the Developer Command Prompt as administrator or it will fail. We will however go through how to do this manually so you get a more basic understanding.
The ^ symbol I add to the following cmd batch files means “escape the next line”, this makes it more readable instead of one long command string.
Let’s do all of this step by step:
Open an empty notepad document and copy and paste the following into notepad:
This may or may not look a bit frightening or incomprehensive at first, but let me
walk you through what is going on here: First we create a certificate with
makecert.exe, then we use pvk2pfx.exe to copy the public key and private key
information from the .pvk and .cer into a .pfx (personal information exchange) file.
NOTE: Never share your root .pvk or .pfx files if you want to stay secure!
The .pvk file contains your private key for your .cer certificate and the .pfx file contains both the certificate .cer and the private key .pvk, which means that others can sign new certificates with your certificate without your consent. The only file you can share is the .cer file, which only contains the public key.
The makecert.exe parameters:
  • -n “CN=CARoot”  Subject’s certificate name and must be formatted as the standard: “CN=Your CA Name Here”
    You can also add more than one in the -n parameter for example: “-n “CA=CARoot,O=My Organization,OU=Dev,C=Denmark”  and so on. Reference:
    • CN = commonName (for example, “CN=My Root CA”)
    • OU = organizationalUnitName (for example, “OU=Dev”)
    • O = organizationName (for example, “O=Jayway”)
    • L = localityName (for example, “L=San Francisco”)
    • S = stateOrProvinceName (for example, “S=CA”)
    • C = countryName (for example, “C=US”)
  • -r  Indicates that this certificate is self signed
  • -pe  The generated private key is exportable and can be included in the certificate
  • -a sha512  We declare which signature algorithm we will be using
    (DO NOT use the sha1 algoritm, it is no longer secure)
  • -len 4096  The generated key length in bits
  • -cy authority  Specifies that this is a certificate authority
  • -sv CARoot.pvk  The subject’s .pvk private key file
  • CARoot.cer  The certificate file
Optional: install certificate directly into the Trusted Root CA store
  • -sr LocalMachine  The subject’s certificate store location
  • -ss Root  The certificate store name
The pvk2pfx.exe parameters:
  • -pvk CARoot.pvk  The name of the .pvk file
  • -spc CARoot.cer  The name of the .cer file
  • -pfx CARoot.pfx  The name of the -pfx file
  • -po Test123  The password for the .pfx file
Save the document as “CreateCARoot.cmd” which will create a command batch file. (You can call it what you want as long as you remember the .cmd ending which will make it a Windows Command Script)1. CreateCARoot batch file
Open a Visual Studio Developer Command Prompt – this is where makecert.exe lives, and navigate to the folder that contains the batch file and run the cmd file
2. DevPrompt1
It should now prompt you to enter some passwords. (This is where we create and use the .pvk private key, so these need to match for success)
3. DevPrompt24. DevPrompt35. DevPrompt4

6. DevPrompt5
You should now have 3 new files: CARoot.cer, CARoot.pfx and CARoot.pvk in the folder where your batch files are.7. CARootCertfiles
Making It Trusted
(This is a manual walk through if you didn’t include the -sr and -ss parameters)
Open your new CARoot.cer file by double clicking it and see that it is not trusted.
8. UntrustedCert2
To make it trusted on your machine open up the Microsoft Management Console. (Find it by searching for mmc in start)
mmc console
Go to File  Add/Remove Snap-in
Double-click Certificates in the list to the left
9. MMC1
Choose Computer account and just go next, finish and OK
10. MMC2
Open the Trusted Root Certification Authorities  Certificates
Here you can see all of the currently trusted certificates that Windows trusts.
(Alot of them ship with Windows out of the box)
Now right-click the Certificates folder  All tasks  Import…
The certificate Import Wizard will pop up.
Go next  Browse to find the CARoot.cer file we created earlier
MMC CARoot
Keep going next until finish where a message box should appear saying “The import was successful”.
Your CARoot certificate should now be in you Trusted Root Certification Authorities store.
11. MMC3
Open the CARoot (double-click) and see that it is now trusted by your computer.
13. TrustedCert2
Server Certificates
Next up we need a certificate to handle SSL on the server. We will create this with a new command batch file in notepad just like before, this time with these parameters:
NOTE: The CN must match your domain otherwise the browsers won’t trust your SSL certificate and warn the end user not to proceed to your website
You will recognize most of the parameters, but let me explain the new ones:
  • -n “CN=yourdomain.com” for example  Change this to your domain name in order to connect the SSL server certificate to a specific web server domain. (Examples: “CN=www.yourdomain.com”, “CN=yourdomain.com” or the wildcard that will match all urls ending in your domain “CN=*.yourdomain.com”.)
    You can also add more than one in the -n parameter for example: “-n “CA=CARoot,O=My Organization,OU=Dev,C=Denmark”  and so on. Reference:
    • CN = commonName (for example, “CN=My Root CA”)
    • OU = organizationalUnitName (for example, “OU=Dev”)
    • O = organizationName (for example, “O=Jayway”)
    • L = localityName (for example, “L=San Francisco”)
    • S = stateOrProvinceName (for example, “S=CA”)
    • C = countryName (for example, “C=US”)
  • %1  A command line parameter and will be whatever you type in after .cmd, this will be the file name of your .cer, .pvk and .pfx files
  • -iv CARoot.pvk  Issuer’s (The CA that signed it) .pvk private key file
  • -ic CARoot.cer  The issuer’s certificate file
  • -b 01/01/2014  Start of the period where the certificate is valid
  • -e 01/01/2016  End of the valid period
  • -sky exchange  Indicates that the key is for key encryption and key exchange
  • -eku 1.3.6.1.5.5.7.3.1  Server authentication OID (Object Identifier). Identifies that this is an SSL Server certificate.
Optional: Install server certificate directly into the LocalMachine Personal certificate store
NOTE: This will only install the .cer file into the MMC, in order to import the .pfx file you will have to do it manually.
  • -sr LocalMachine  The subject’s certificate store location
  • -ss My  The certificate store name that will store the output certificate
This will create a SSL certificate to use on your server and will be signed by your CARoot authority.
15. ServerSSL cmd
Run it in your Developer Command Prompt the same way as before, only this time type in a name for your certificate after the command. Mine will be: CreateSslServerCert.cmd ServerSSL
14. ServerPrompt
Again it will ask you to create your private key password, use it to verify, also give the issuers password (which is the one you chose when creating your root CA) and lastly the private key password you choose in the first window.
servercert password1servercert password2
servercert password3 servercert password4
…aaand voila you now have the ServerSSL certificate files.
16. ServerSSL Certs
If you didn’t include the -sr and -ss parameters, import the Personal Information Exchange (pfx) certificate into your Personal Certificates in the Microsoft Management Console:
Open the Personal folder  right-click Certificates  Import…
Again the Certificate Import Wizard pops up  Go Next
This time you will Browse for the ServerSSL.pfx file
17. MMCserver
Go next  Type in the password for your pfx file (The -po parameter from the batch file)  Continue going next until finish and the message box with ”The import was successful” appears.
You should now see you newly imported certificate in your  Personal Certificates folder
18. MMCServer2
It is trusted automatically because your CARoot that signed it is trusted and has a private key corresponding to this certificate.
19. TrustedServerCert 20 TrustedServerCertPath
You can now configure your server to use this certificate.
Client Certificates
Last but not least we will create the client certificate which can be used for client certificate authentication. We will again create a command batch file, now with the following parameters:
You may notice that this is almost identical to the server certificate parameters, all except:
  • “CN=%1”  This can be whichever name you like and will be what you type in after .cmd
    You can also add more than one in the -n parameter for example: “-n “CA=%1,O=My Organization,OU=Dev,C=Denmark”  and so on. Reference:
    • CN = commonName (for example, “CN=My Root CA”)
    • OU = organizationalUnitName (for example, “OU=Dev”)
    • O = organizationName (for example, “O=Jayway”)
    • L = localityName (for example, “L=San Francisco”)
    • S = stateOrProvinceName (for example, “S=CA”)
    • C = countryName (for example, “C=US”)
  • -eku 1.3.6.1.5.5.7.3.2  The client authentication OID (Object Identifier).
Optional: install client certificate directly into the CurrentUser Personal certificate store
NOTE: This will only install the .cer file into the MMC, in order to import the .pfx file you will have to do it manually.
  • -sr CurrentUser  The subject’s certificate store location
  • -ss My  The certificate store name
Your batch command will create a SSL certificate to use on your client and will be signed by your CARoot authority.
21. ClientCertCmd
Execute the command batch file in the Developer Command Prompt, again with a name after the cmd. (Mine will be: CreateSslClientCert.cmd ClientCert)
22. PromptClientCert
Enter the passwords in the same pattern as the server certificate and you now have your client certificate.
23. ClientCert
You can now add it to your Current User Personal Certificate store:
In the Microsoft Management Console, click File  Add/Remove Snap-in
Double-click Certificates again, but this time choose My user account
24. MMC client
Open the Personal folder  Right-click Certificates  Import…
Browse for your ClientCert.pfx file
25. MMC client 2
Go next  Type in the password to your pfx file (-po parameter from the batch file)  Continue going next until finish and ”The import was successful” message box appears.
You should now see you newly imported certificate in your Personal  Certificates folder
26. MMC Client3
Again the certificate is trusted because the CARoot is trusted by Windows.
27. TrustedClient 28. TrustedClientPath
You can now configure your client to use this certificate.

https://blog.jayway.com/2014/09/03/creating-self-signed-certificates-with-makecert-exe-for-development/