In previous post I’ve discusses how to setup 2FA using Yubikey with any Ubuntu box gnome login.

This time we will discuss about how to lock screen when Yubikey will be removed. This is a mandatory security requirement while using Yubikey to complete secure your box.

First of all we will need to install finger and gnome-screensaver packages.

The following script need to be placed into /usr/local/bin/gnome-screensaver-lock:

#!/bin/sh

getXuser() {
        user=`finger| grep -m1 ":$displaynum " | awk '{print $1}'`

        if [ x"$user" = x"" ]; then
                user=`finger| grep -m1 ":$displaynum" | awk '{print $1}'`
        fi
        if [ x"$user" != x"" ]; then
                userhome=`getent passwd $user | cut -d: -f6`
                export XAUTHORITY=$userhome/.Xauthority
        else
                export XAUTHORITY=""
        fi
}

for x in /tmp/.X11-unix/*; do
    displaynum=`echo $x | sed s#/tmp/.X11-unix/X##`
    getXuser
    if [ x"$XAUTHORITY" != x"" ]; then
        # extract current state
   export DISPLAY=":$displaynum"
    fi
done

logger "YubiKey Removed - Locking Workstation"
su $user -c "/usr/bin/gnome-screensaver-command --lock"

Then add the following rule to udev:

ACTION=="remove", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0407", RUN+="/usr/local/bin/gnome-screensaver-lock"

This rule tells to system to execute upper script when it is removed.

Now you will need to reload udev rules and make the script executable then you can use it to lock screen when it will be removed.

Looking for strong authentication and endpoint security for your Linux systems?
→ Check out our PKI Infrastructure Services

Categories: Blog

1 Comment

Michel · January 24, 2025 at 12:27 pm

I use Keepass and it looks like this triggers the remove if you unlock it. So I added some Code at the End:

sleep 1
if ! lsusb | grep -q “1050:0407”; then
logger “YubiKey Removed – Locking Workstation”
su $user -c “/usr/bin/gnome-screensaver-command –lock”
fi

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *