A Yubikey allows you to add a physical security layer for any remote access (applications, servers, SaaS. We will see today how to secure an SSH access to a server with a Yubikey. In my case the reason is that I have two professional computers, and that I may want to access my servers from other computers. We know that the simple use of a password is really not recommended. I still have the option of a RSA key pair, but that implies carrying it around and the risk of it being copied. So I took the 2FA option for a password authentication with a Yubikey.

Client ID and Secret Key

To start, you’ll have to generate a client ID and a Secret Key using the Yubico API. Go to this page https://upgrade.yubico.com/getapikey/. You just have to fill in your email address and generate an OTP code by activating the Yubikey. Save the Client ID and the Secret Key in a safe place.

Yubico Library

You have to access your server and install the Yubico library allowing authentication and API requests

sudo apt-get install libpam-yubico

Then we edit the sshd file :

sudo nano /etc/pam.d/sshd

Under the line @include common-auth we add

auth required pam_yubico.so id=CLIENT-ID key=SECRET-KEY url=https://api.yubico.com/wsapi/2.0/verify?id=%d&otp=%s

Make a user/Yubikey link

The method is well known, you just have to link each user to one or several Yubikeys. The difference is that here the information must be stored in ~/.yubico/authorized_yubikeys

If like me you are on Mac or Linux, plug your key and in a terminal copy the following line to get the ID of your key:

read -p "Enter a YubiKey OTP: " s && echo 'The key id is' ${s:0:12}

On the server side, let’s create the directory and the necessary file :

mkdir ~/.yubico
nano ~/.yubico/authorized_yubikeys

And let’s make the link between a user and his key (in the example we give two keys):


Finally we reload with a good old sshd reload service
Keep your terminal open in case it fails and open a second connection to your server. You will be asked for a password and then a code generated by your Yubikey.