sudo with yubikey

Yubikeys offer one of the strongest, enterprise-grade, practical account security tools to end-users without the cognitive overhead. Cost-effective, portable, and robust; I’ve been using them for over a decade now.1

It’s handy to pair it with sudo2; here’s a how-to.

  1. Install pre-requisite software

    sudo apt install libpam-u2f
    
  2. Create a config folder

    mkdir -p ~/.config/Yubico
    
  3. Generate key mapping

    pamu2fcfg > ~/.config/Yubico/u2f_keys
    
    • Enter key PIN when prompted
    • Touch the flashing Yubikey (to complete key registration)

    To register another key, use the following command, followed by entering PIN and touching the key when prompted:

    pamu2fcfg >> ~/.config/Yubico/u2f_keys
    

    Using >> in the above command appends u2f_keys file — registering the new key, without removing previously registered keys.

  4. Configure PAM for sudo

    sudo nvim /etc/pam.do/sudo
    

    Add one of the following line above the @include common-auth line — depending upon your convenience-to-security preference:

    • Option 1 (good): For passwordless sudo:

      auth sufficient pam_u2f.so cue [cue=Tap security key]
      
    • Option 2 (better): For 2FA (password + Yubikey):

      auth required pam_u2f.so cue [cue=Tap security key]
      
  5. For Raspberry Pi OS, under 1. System Options > S10 Admin Password > Enable

  6. Test with the following:

    sudo echo "Success"
    

Common sense recommends registering multiple keys, if in case you lose a key (or two). Unregister lost key(s) from your account using a backup key.3


I’ve got a 14-year old MacBook that’s now just a dumb terminal and the process for this was nearly same as above. I installed pam-u2f using MacPorts, and added the following at the top of the file /etc/pam.d/sudo:

auth  sufficient  /opt/local/bin/pam/pam_u2f.so cue

Be sure to check if the file in the path above exists before saving; could be different if installed via brew. sudo command prompts to tap the key, if found in the USB port; if not, it will ask for the password.


  1. For a bunch of services from commercial entities and Government, privately owned computers, and servers, etc. 

  2. To temporarily run commands with admin privileges. 

  3. The beauty of hardware keys is (a) something you know (like a password), (b) something you have (like a yubikey), and/or (c) something you are (e.g. biometry). Without the appropriate combination, access becomes impracticable.