Skip to content

Instantly share code, notes, and snippets.

@tgfrerer
Forked from jhass/1-Yubikey_session_lock.md
Last active June 14, 2023 11:05
Show Gist options
  • Save tgfrerer/ea11a4d290b0539653378c03ca330ac9 to your computer and use it in GitHub Desktop.
Save tgfrerer/ea11a4d290b0539653378c03ca330ac9 to your computer and use it in GitHub Desktop.
Lock (Gnome) session when removing Yubico U2F key

Setup

  1. Copy 99-u2f_lock_screen.rules to /etc/udev/rules.d.
  2. Copy gnome_lock_all_sessions to /usr/local/bin.
  3. Mark gnome_lock_all_sessions as executable: chmod +x /usr/local/bin/gnome_lock_all_sessions
  4. Reload udev: udevadm control -R

Note

You might have to update the ENV{ID_MODEL_FROM_DATABASE} value in 99-u2f_lock_screen.rules to match the type of Yubikey that you are using. You can query it by issuing:

udevadm monitor --property | grep ID_MODEL_FROM_DATABASE

and noting the value that gets printed out when you unplug the key.

ACTION=="remove", SUBSYSTEM=="usb", ENV{ID_MODEL_FROM_DATABASE}=="Yubikey 4/5 OTP+U2F+CCID", RUN+="/usr/local/bin/gnome_lock_all_sessions"
#!/bin/sh
# List available names
# dbus-send --session --dest=org.freedesktop.DBus --type=method_call --print-reply /org/freedesktop/DBus org.freedesktop.DBus.ListNames
# Lock session (Gnome)
# dbus-send --session --type=method_call --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.Lock
# Unlock session (Gnome)
#dbus-send --session --type=method_call --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.SetActive boolean:false
# Lock session (freedesktop) (no effect?)
# dbus-send --session --type=method_call --dest=org.freedesktop.ScreenSaver /org/freedesktop/ScreenSaver org.freedesktop.ScreenSaver.Lock
for bus in /run/user/*/bus; do
uid=$(basename $(dirname $bus))
if [ $uid -ge 1000 ]; then
user=$(id -un $uid)
export DBUS_SESSION_BUS_ADDRESS=unix:path=$bus
if su -c 'dbus-send --session --dest=org.freedesktop.DBus --type=method_call --print-reply /org/freedesktop/DBus org.freedesktop.DBus.ListNames' $user | grep org.gnome.ScreenSaver; then
su -c 'dbus-send --session --type=method_call --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.Lock' $user
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment