Using a YubiKey (or other security key) for sudo via pam

A quick reminder for me, on how to configure pam to use a YubiKey or other hardware security key, if present, for passwordless sudo.

If you have a security key in your machine when you run sudo, you’ll be prompted to tap it, to sudo. If you don’t have a security key in, it reverts to asking for a password.

Install dependencies

sudo apt install libpam-u2f -y

Set up the security key for pam

Set up the folder

mkdir ~/.config/Yubico

(If you do not want the directory to be called “Yubico”, I think you can name it whatever you want, as long as you then pass it as “authfile” within your pam.d config (below). e.g. auth required pam_u2f.so cue authfile=/directory_path/file_name). I have not tried this.)

Add your security keys

pamu2fcfg > ~/.config/Yubico/u2f_keys

(You won’t see anything at the prompt; just tap your security key, and you’ll be returned to the prompt. If you want to add further security keys: pamu2fcfg -n >> ~/.config/Yubico/u2f_keys)

Configure pam

sudo vim /etc/pam.d/sudo, and add, above the other entries already there:

auth sufficient pam_u2f.so cue [cue_prompt=Tap YubiKey]

Use :w to write the file, but don’t quit it yet.

Test it

Open another terminal window, and try a sudo command (e.g. sudo bash). You should see “Tap YubiKey”. Tap it, and you should now have a shell with elevated privileges.

Assuming it works, you can quit vim (:q), and exit the terminals.

Want MFA rather than passwordless sudo?

If you wanted both password and security key, change /etc/pam.d/sudo to include:

@include common-auth
auth       required   pam_u2f.so