Skip to content

Instantly share code, notes, and snippets.

@MartinBrugnara
Last active November 14, 2024 14:18
Show Gist options
  • Save MartinBrugnara/6b9f0c73d82603c1b31cf75f7c20cc5d to your computer and use it in GitHub Desktop.
Save MartinBrugnara/6b9f0c73d82603c1b31cf75f7c20cc5d to your computer and use it in GitHub Desktop.
Xscreensaver autolock on yubikey remove
# /etc/udev/rules.d/85-yubikey.rules
# https://stackoverflow.com/questions/13699241/passing-arguments-to-shell-script-from-udev-rules-file#14982520
# https://askubuntu.com/questions/635266/use-of-yubikey-neo-for-login-2fa-and-lock-screen#635267
# Bus 001 Device 012: ID 1050:0407 Yubico.com
ACTION=="remove", ENV{ID_VENDOR_ID}=="1050", RUN+="/usr/local/bin/yubikey_lock.sh '%E{ID_SERIAL}' '%E{ID_MODEL_ID}'"
#!/bin/bash
# Providede by UDEV
SERIAL_SHORT=$1
MODEL_ID=$2
logger "[Yubikey_lock] Yubikey $SERIAL_SHORT removed, locking."
# Get users with an active X session
users=$(who -a | grep -E "\(:[0-9][0-9]*\)" | sed 's/ .*(/,/' | sed 's/)//' | sort | uniq)
for session in "$users"; do
username=$(echo $session | cut -d "," -f 1)
screen=$(echo $session | cut -d "," -f 2)
# Avoid double locking
status=$(su $username -c "DISPLAY='$screen' xscreensaver-command -time")
if [[ "$status" =~ "locked" ]]; then
logger "[Yubikey_lock] Sessions already locked for $username on $screen."
continue
fi
# Lock
logger "[Yubikey_lock] Locking for $username on $screen."
if [ -n "${USER-}" ] && [[ "$USER" == "$username" ]]; then
# /usr/bin/gnome-screensaver-command --lock
DISPLAY="$screen" /usr/bin/xscreensaver-command --lock
else
#/bin/su "$username" \
# -c '/usr/bin/gnome-screensaver-command --lock'
/bin/su "$username" -c "DISPLAY='$screen' /usr/bin/xscreensaver-command --lock"
fi
done
#!/bin/bash
# Providede by UDEV
SERIAL_SHORT=$1
MODEL_ID=$2
logger "[Yubikey_lock] Yubikey $SERIAL_SHORT removed, locking."
# Get users with an active X session
# by grepping on common software
# users=$(ps aux | grep "gnome-keyring-daemon" | grep -v "grep" | awk -F' ' '{print $1}' | sort | uniq)
seats=$(dm-tool list-seats | grep "^Seat" | sort | uniq)
for seat in "$seats"; do
# dm (lightdm) requires 2b execute as root
logger "[Yubikey_lock] Locking seat $seat."
XDG_SEAT_PATH="/org/freedesktop/DisplayManager/$seat" dm-tool lock
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment