Locking the screen when removing a Yubikey

In this blogpost I'll share a small guide on how to automatically lock your screen when you remove your Yubikey.

I have my Yubikey on my key ring, so whenever I leave my computer, I have to remove the Yubikey. So why not lock the screen automatically?

For this to work, we have to accomplish two things:

  • Notice when the Yubikey is removed using udev.
  • Lock the screen with xscreensaver-command --lock

We will solve the first point by writing our own udev rule.

Create a new file /etc/udev/rules.d/20-yubikey.rules with the following content:

ACTION=="remove", ENV{ID_BUS}=="usb", ENV{ID_MODEL_ID}=="0407", ENV{ID_VENDOR_ID}=="1050", ENV{ID_SERIAL_SHORT}=="XXXXXX", RUN+="/usr/local/bin/lockscreen.sh"

The rule will execute the locking script /usr/local/bin/lockscreen.sh when an USB device with the vendor-ID 1050 (Yubico) and model-ID 0407 (Yubikey 4) and my (specific?) serial-ID is removed. To find out what model and/or serial ID your Yubikey has, do the following:

  • Plug in your Yubikey
  • Run udevadm monitor --environment --udev
  • Remove your Yubikey
  • Analyse the output of the above command.

The output is sometimes quite long and a bit confusing, but you will eventually find a block with parameters similar to mine.

If you are confident that the chosen parameters are correct, you have to tell udev to reload the rules:

$> sudo udevadm control --reload-rules

The script is executed as root, and that is why we have to figure out which xserver session is active and should be locked. I have slightly modified a script and placed it at /usr/local/bin/lockscreen.sh:

Last, but not leat: Do not forget to make it executable with chmod +x /usr/local/bin/lockscreen.sh.