Skip to content

Instantly share code, notes, and snippets.

@bitglue
Last active June 15, 2020 05:16
Show Gist options
  • Save bitglue/1ee09039ba0b01175db38dc7d1a2a4f9 to your computer and use it in GitHub Desktop.
Save bitglue/1ee09039ba0b01175db38dc7d1a2a4f9 to your computer and use it in GitHub Desktop.
Automatically add/remove PKCS11 provider from ssh-agent based on Yubikey presence
# Install in /etc/udev/rules.d/
# Reload with: udevadm control --reload-rules
# You might need additional model IDs here, depending on your particular Yubikey
ACTION=="add", SUBSYSTEM=="usb", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0407|0115", TAG+="systemd", ENV{SYSTEMD_ALIAS}="/sys/subsystem/usb/yubikey"
# See https://github.com/systemd/systemd/issues/7587
# Interestingly, this also fixes smartcard.target, which seems otherwise broken.
ACTION=="remove", SUBSYSTEM=="usb", ENV{PRODUCT}=="1050/407/*|1050/115/*", TAG+="systemd"

Not-so-terrible Yubikey PIV SSH authentication

See https://developers.yubico.com/PIV/Guides/SSH_with_PIV_and_PKCS11.html for the basics.

The trouble is running ssh-add -s /long/path/to/some/pkcs11_provider.so is a pain in the ass.

Also if the Yubikey is removed, ssh-add -l will still indicate the key is available, even though it's not, until the provider is removed with ssh-add -e /path/to/pkcs11_provider.so

And if the Yubikey is subsequently re-inserted, the ssh agent won't re-prompt for the pin, and so authentication will fail until the provider is removed and re-added.

Fortunately it's possible to automate these actions based on the insertion/removal of the Yubikey.

# Install in ~/.config/systemd/user/
# systemd --user daemon-reload
# systemd --user enable yubikey-ssh-agent.service
[Service]
Type=simple
RemainAfterExit=yes
ExecStart=/home/indigo/add-to-agent
ExecStop=/home/indigo/add-to-agent remove
[Unit]
Description=Add the Yubikey to ssh-agent
StopWhenUnneeded=yes
[Install]
WantedBy=sys-subsystem-usb-yubikey.device
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment