Get started with the Nitrokey HSM or SmartCard-HSM

Table of Contents

This is a guide to get started with the Nitrokey HSM (or SmartCard-HSM). It covers what a HSM is and what it can be used for. It also goes over software installation and initializing the device including backups of the device and keys. Finally we do some actual crypto operatons via pkcs11, OpenSSH, Apache and OpenSSL. We also cover usage in Thunderbird (S/MIME), Elementary Files (EF), a Web cluster with Apache and mod_nss and the decryption of the keys.

What is an HSM (Hardware Security Module)

A Hardware Security Module, HSM, is a device where secure key material is stored. This private data only be accessed by the HSM, it can never leave the device. Most HSM devices are also tamper-resistant. This means that when opened, moved or otherwise (software) tampered with, they wipe the key material. HSM's come in a variety of formfactors, ranging from SmartCards and small USB devices, to full size PCI cards and even 19" rackmountable server-like devices. The difference between all those devices is speed and storage capacity. Most commercial HSM's are certified to the FIPS-140-2 standard.

An Eracom HSM PCI card

Since the private key material never leaves the device, all crypto operations are done on the device as well. The software usually communicates via PKCS#11, sometimes named Cryptoki. PKCS#11 is a software API for accessing cryptographic hardware like smart cards or HSM. PKCS#11 is NOT a hardware standard or hardware interface. PKCS#15 is a format of on-card structures that defines a "filesystem layout" for smart cards. PKCS#15 does not define how those structures are generated or written to the card. OpenSSL supports this, as well as CA software like Dogtag/Redhat Certificate System and EJBCA by using a driver/module. The software doesn't use the actual key files themselves but asks the device to do the operation. For example, the software asks the HSM to sign this data with the private key and the HSM returns the signed data. It can also encrypt and decrypt data using the keys. In most HSM's you have one or more so called slots. Each slot can have a keypair, RSA, EC, DSA, depending on the software on the HSM.

An Ultimaco HSM device

For example, when you generate a certificate for your website with OpenSSL you get both a private key and a certificate. The latter might also be called the public key (RSA). By using the public key, others can verify that the connection is signed and encrypted with the private key. The server software, Apache for example, uses the two files directly to do the crypto. Now, when a HSM is used, the webserver has a driver loaded and asks the HSM to do the operation (signing, encrypting) instead of doing it itself. It uses the data the HSM returned, and thus never has access to the private key.

An SafeNet Luna PCI 7000 HSM

All major Certificate Authorities use HSM's to store their private keys. By doing so, they make sure the private keys used to sign certificates never get stolen or leak out. Let's Encrypt uses Gemalto HSM's. I've worked at a dutch certificate authority where Safenet Protectserver devices were used. Actually, Eracom Protectserver, before they got bought up, then Safenet Protectserver. For this dutch CA, it was required to store keying material in an HSM by the CA/Browser forum and the Staat Der Nederlanden CA hierarchy, PKIOverheid. A company doing public traffic transaction management (OV Chipkaart) uses devices by Thales, nShield HSM's.

An SafeNet Luna 19" rack model HSM

As you can see on the pictures, most HSM's have a COM port. These COM ports can be used to attach a smartcard reader. Most HSM's offer the option to backup the keying material inside the HSM to a smartcard.

An Omnikey 3121 USB Smartcard reader

These backups are made in such a way that only another HSM, often only the same type of HSM device, can import these keys with a special password. The Safenet Protectservers called this a Transport Key, which was a long (32 bit) password used to export and import the key.

The Nitrokey is as far as I know one of the few fully open source devices. All the big HSM's I've used were either under NDA or completely closed source. In my opinion a device like this can only be secure when they are open source. The device supports up to 60 ECC GF(p) 256-bit keys and up to 48 RSA 2048-bit keys.

The device came in a sealed bag. The bag has only the device in it and a link to www.nitrokey.com/start printed on it. The size is about that of an AA battery in height and around 1.5 cm width. It is black, the back has the FCC and CE logo's printed in white and the front has the Nitrokey logo and the text "Nitrokey HSM" printed. The device feels like a quality product and is very sturdy. Inserting the device in a USB port also keeps it secure and still, it all fits very well. Not loose or wiggly at all. When the device is inserted a red LED blinks once.

PKCS#11, #15 and OpenSC

PKCS#11 is, as said, a software API for accessing cryptographic hardware like smart cards or HSM. PKCS#11 is NOT a hardware standard or hardware interface. PKCS#15 is a format of on-card structures that defines a "filesystem layout" for smart cards. PKCS#15 does not define how those structures are generated or written to the card.

SO and User Pins

Some functions on the HSM are protected by PIN codes. There are different access levels, most common SO (security officer) and user. Each slot can have a different user pin, but the SO pin remains the same for the HSM. You could say that the SO pin is like the root user.

An HSM needs to be initialized before it can be used. Initialization is a factory reset, where all keys, certificates and data elements are erased and you set up a new SO pin. When you receive an HSM it has factory default settings. For the Nitrokey HSM the SO pin is 3537363231383830. This is not secure since it's a publicly known code. Therefore it needs to be changed to something else. But before we do that, first a few warnings.

Warnings

Please read the below parts. You might render your device bricked if you use it wrong, and there is no way of recovering a blocked/bricked Nitrokey HSM.

The SO pin must be exactly 16 hexadecimal characters. It will be stored internally as an 8-byte key.

Store the SO pin in a safe place.

The user pin can be any length from 4 up to 16 ASCII characters.

You need the SO pin to (re)-initialize the device.

Wrong SO pins are counted. When you have entered 15 wrong SO pins, the device is forever blocked and unusable. This is non-recoverable. The counter can not be reset as well.

HSM firmware versions up to 1.0 will not allow you to change this SO PIN ever again. Check with pkcs11-tool --list-slots.

So, TL;DR: NEVER ENTER THE WRONG SO PIN AND NEVER FORGET THE SO PIN.

HSM Backups with a DKEK

As said earlier, most HSM's offer a backup option. You can export the key material in a specific format readably by other HSM's of that type. The Safenet Protectserver wraps the material with a Transport Key.

The Nitrokey HSM and the SmartCard-HSM use a 'Device Key Encryption Key'. The DKEK is a 256-Bit AES key.

The DKEK must be set during initialization and before any other keys are generated. For a device initialized without a DKEK, keys can never be exported.

A DKEK is imported into a SmartCard-HSM using a preselected number of key shares. Each key share is given to a key custodian and only all key shares together assemble the DKEK. Key shares are individually imported and are assembled within the SmartCard-HSM. Key shares can be imported independently of time and location, allowing to pass a half-initialized device between key custodians until all shares have been imported.

The HSM supports an arbitrary number of DKEK shares. Typical values for the number of shares are:

0: The HSM generates an internal DKEK (no backups).

1: The HSM requests one external DKEK share to be imported.

3: The HSM requests three external DKEK shares to be imported by three different key custodians.

If you want to enable the option to create a backup, you must do so first, before initializing the HSM. In this example I will create one key share, but repeating the commands allows you to create more.

Create a DKEK share with the following command:

sc-hsm-tool --create-dkek-share dkek-share-1.pbe

Output:

Using reader with a card: Nitrokey Nitrokey HSM (010000000000000000000000) 00 00
The DKEK share will be enciphered using a key derived from a user supplied password.
The security of the DKEK share relies on a well chosen and sufficiently long password.
The recommended length is more than 10 characters, which are mixed letters, numbers and
symbols.
Please keep the generated DKEK share file in a safe location. We also recommend to keep a
paper printout, in case the electronic version becomes unavailable. A printable version
of the file can be generated using "openssl base64 -in <filename>".
Enter password to encrypt DKEK share : <long password>
Please retype password to confirm :
Enciphering DKEK share, please wait...
DKEK share created and saved to dkek-share-1.pbe

Backing up and restoring the keys with a DKEK

Now that we have some keys in the HSM, we want to make a backup. Since we've generated a DKEK earlier, we can use that to create a backup of the material in the HSM. If you are restoring a backup to another HSM, make sure you (re)initialize the HSM and import the correct DKEK first.

The backup and restore require that we know the key reference identifier (key ref). We can find that with the pkcs15-dump command:

As described in the two articles, you need to create a small random file and use that as the key to encrypt a file using symmetric encryption. asymmetric encryption like RSA is not suitable for large files. Please make sure you read both the articles to understand the subject, and then use this article to use the HSM.

SSH Keys with the HSM

OpenSSH has support for PKCS#11, so we can use the HSM for SSH Key based authentication. The private key never leaves the HSM so this is more secure than a password on a file. You will know when someone is brute forcing your HSM, because you lost possession of it. When someone steals your private key, you might not even know it. Remember the firefox exploit that steals private keys and passwords? If you are using the HSM this will never be possible.

EC keys to OpenSSH

For EC generated keys the pkcs15-tool doesn't seem to work. However, because all keys can be converted one way or another we can dump the EC public key and convert it into an SSH compatible key. First dump the EC public key to a file. In this case I generated an EC private key with ID 2 and used the following command to get the public key:

If I try to login without specifying the HSM I will be prompted for a password or be rejected:

When we tell OpenSSH to use the HSM, we get asked for the HSM pin and are logged in:

$ ssh -o "PKCS11Provider opensc-pkcs11.so" root@testdroplet
C_GetAttributeValue failed: 18
Enter PIN for 'SmartCard-HSM (UserPIN)': <648219>
Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-22-generic x86_64)
* Documentation: https://help.ubuntu.com/
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
root@hsmtest:~#

If you add the below line to the top of your ~/.ssh/config file, OpenSSH will automatically use the HSM if needed:

# vim ~/.ssh/config
PKCS11Provider opensc-pkcs11.so

A short form for the command line is the -I flag, which is the same as the long -o flag:

ssh -I opensc-pkcs11.so root@testdroplet

You can also add the key to your ssh-agent if you happen to use an agent:

ssh-add -s opensc-pkcs11.so

Output:

Enter passphrase for PKCS#11: <648219>
Card added: opensc-pkcs11.so

The passphrase is the user pin. You can now login to machines without entering the HSM pin every time. Check all the keys in the agent with the following command:

Note the extra emailAddress value in the certificate subject. Make sure that the CN domain is the same as the domain in the email addres. Also make sure you specify the correct slot:id, in our case, slot 1 and ID 40.

You can now send this certificate signing request to a certificate authority and get an actual certificate back. Comodo and Globalsign provide certificates for S/MIME.

If you want to generate a self singed certificate you can do that as well:

If you have completed the validation of the certificate at the certificate provider or you have the self signed certificate ready, we can proceed to load the certificate into the HSM. We need to load the certificate in the HSM so that Thunderbird is able to use it. Otherwise there would just be a public key.

The HSM only accepts DER format, so first convert the PEM file you generated or received from your CA to DER:

Start up Thunderbird and go to the Settings/Preferences menu. Open the Advanced tab and select the Security Tab. Click the Security Devices button:

Select the SmartCard-HSM (UserPIN) under opensc and click the Login button. Enter the User PIN (648219). The status should change from Not logged in to Logged in Click the OK button.

To view the certificate, select the View Certificates button. Your certificate should be loaded under the Your Certificates tab, with SmartCard-HSM as it's Security Device.

Open up the Account Settings window and under the correct email account, select Security. Under Digital Signing and Encryption select the correct certificate in the HSM:

Save all settings and send yourself a test email. You should be able to sign (or encrypt if you have someone elses S/MIME key) the message and while sending your HSM LED turns on.

Deleting objects from the HSM

If you are done with testing or want to free up space on the HSM you can remove objects from it. You can delete certificates and the private keys, either by ID or label. For example, when your S/MIME certificate is expired and you need to load up a new one, delete the old one first.

Apache with mod_nss

There is a different module you can use next to the OpenSC module, named sc-hsm-embedded. This module provides fast, read only access to the HSM, and is better suited for production use, since on a production machine you don't need to manage keys on the HSM, you do that on your offline management workstation.

The guide for mod_nss, Apache and the read-only-module sc-hsm-embedded is on a seperate page as well.

Decrypting the private keys of the HSM

This is a guide which shows you how to extract private RSA key material from the Nitrokey HSM / SmartCard-HSM using the DKEK. This way you can get the private key out of the HSM in an unencrypted form. It does require access to the HSM device, all the DKEK share and their passwords. Do note that doing this defeats the entire purpose of a HSM, namely that you never have access to the keys. In the article I'll go over some explanation why this might be a feature you need and why it might be a case of security over convinience.

*** This is not a vulnerability, zero day or exploit. The HSM provides a way to do secure backups of private key material and we utilize that in this article. To decrypt the keys you need to have all the DKEK files used when the HSM was initialized, know all the DKEK passwords and have access to the HSM itself. **

You can prevent decryption by not setting up a DKEK, thus using the random internal DKEK of the HSM.

Storing arbitraty data in Elementary Files (EF)

This is a guide which shows you how to write small elementary files to a nitrokey HSM. This can be usefull if you want to securely store data protected by a user pin. You can enter the wrong pin only three times, so offline brute forcing is out of the picture.

You could for example, store a file in the HSM and send it via the old-fashioned mail to someone, without sending the required pin. You send that via a different channel, preferably privately in person. The other person then can read the file of the HSM using the PIN. Since you only have 3 tries for the correct PIN, you know that an offline brute force attack is not likely to happen. If you encrypted a file an placed it on a regular USB drive, the post could be intercepted and stored for offline cracking by a government agency, without you knowing it. Because the pin entries are recorded, you know immidiately when the device has been tampered with.