Secure your API with Client-certificate authenatication in NGINX
After a few hours trying to make it work with my current CA, where the Root is stored offline, AIA, OCSP, CRL and all that stuff is done by the book – I gave up. Somehow, the Open Source variant of Nginx does not really like my OCSP setup, no idea why and I have no idea how to troubleshoot that.
Solution? KISS-principle!
I'll write this down, quick and dirty. But hopefully it helps someone.
Lets start with create the private key for the CA that we will create:
openssl genpkey -algorithm RSA -out CA_ROOT.key -aes256
With this command, we have created a private key with AES256. You will be prompted to give a password – write that down. And the following command will create a certificate from the private key, valid for 10 years.
openssl req -x509 -new -nodes -key CA_ROOT.key -sha256 -days 3650 -out CA_ROOT.crt
Fill in the information that the above command wants of you, like country-code, and so on. After that, your CA is done. The crude, ugly and honestly boring CA. But it'll work for this usecase.
Let's create the client-certificate!
First, will start by creating the private.key, and the .csr:
openssl genpkey -algorithm RSA -out client-cert.key
openssl req -new -key client.key -out client-cert.csr
And again, fill out the information wanted by openssl that will populate the .csr. Make it looks pretty. Ideally, the commands shall be run on the client only, so the private-key never leaves the client. The .csr is what the CA will need to sign and create a valid certificate.
Bring the .csr to the CA, and sign it:
openssl x509 -req -in client-cert.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client-cert.crt -days 365 -sha256
This will give you a signed certificate for your client named “client-cert.crt” – you may bring that to the client-machine and install it.
Firefox wants a .pfx:
In order to import the certificate into Firefox, you'll need to convert it to p12/pfx format:
openssl pkcs12 -export -out client-cert.pfx -inkey client-cert.key -in client-cert.crt -certfile CA_ROOT.crt
Please note, that you'll need the CA_ROOT.crt file too that you created.
Configure NGINX to do client-certificate authentication
Navigate to the virtualhost you want to enable client-certificate authentication on, and add the following:
ssl_client_certificate /etc/ssl/private/CA_ROOT.crt;
ssl_verify_client on;
ssl_verify_depth 2;
Please note, that you have to place the CA_ROOT.crt file in /etc/ssl/private/
Restart NGINX and try to visit the site. You'll probably be asked for permission to use client-certificate authentication.