Brainspiritus

Funkenflug aus flammenden Synapsen.

Adding your Yubikey's SSH keys to your agent automatically

Sometimes, systemd makes things reasonably easy:

First of all, we want a new udev rule we can latch onto:

% cat /etc/udev/rules.d/98-yubikey5.rules 
SUBSYSTEMS=="usb", ACTION=="add", ATTRS{idVendor}=="1050", SYMLINK+="yubikey", 
TAG+="systemd"

This will create /dev/yubikey when a USB device from Vendor 0x1050, Yubico, is plugged in. Use udevadm control --reload to enable the new rule.

Now, we can have a user-level systemd unit that is started by this device:

% systemctl --user cat yubissh.service 
# /home/(me)/.config/systemd/user/yubissh.service
[Unit]
Description=Autoload Yubikey SSH keys

BindsTo=dev-yubikey.device
After=dev-yubikey.device

[Service]
RemainAfterExit=true
Type=oneshot
ExecStart = ssh-add -s /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
ExecStop  = ssh-add -e /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so

[Install]
WantedBy=dev-yubikey.device

Enable this with systemctl --user daemon-reload && systemctl --user enable yubissh.service and you should be good to go. (Don't forgot you need some sort of ssh-askpass binary, too!)