Skip to content

Instantly share code, notes, and snippets.

@anroots
Last active September 14, 2022 14:06
Show Gist options
  • Save anroots/25c82171f49aa09390f3a22cf29254db to your computer and use it in GitHub Desktop.
Save anroots/25c82171f49aa09390f3a22cf29254db to your computer and use it in GitHub Desktop.
Load SSH key into ssh-agent from a veracrypt-encrypted drive when it's plugged in
ACTION=="add", KERNEL=="sd?", ATTRS{serial}=="SERIAL_NUMBER_OF_USB", RUN+="/usr/local/bin/load-ssh-keys"
#!/bin/bash
# load-ssh-keys.sh
# Author Ando Roots <ando@sqroot.eu> 2016
# Licence: MIT
# Requirements: VeraCrypt and `ssh-agent` installed, Ubuntu environment
# Known problems: notify-send might not always work. All open nautilus windows will be killed.
#
# The following program is meant to be run by udev when a Veracrypt-encrypted USB drive
# is inserted. The script mounts the drive, prompts for passwords and loads SSH keys into ss-agent.
#
# Customize as needed. More at https://sqroot.eu/2016/securing-ssh-keys
#
# The braces and '&' "group" the enclosed program into one logical unit and send it to the background.
# This is done because the scripts run by udev should be very quick to exit, for it has a timeout value
# (and this script calls for user input).
{
# The DISPLAY variable tells VeraCrypt where to display the password prompt window
export DISPLAY=:0
# Change this to your UNIX username
LOGNAME=ando
# Xauthority is needed to be "authorized" to display something on the screen (password prompt)
export XAUTHORITY=/home/$LOGNAME/.Xauthority
# This tells us the address to a ssh-agent socket (how one can connect to ssh-agent)
export SSH_AUTH_SOCK=`find /tmp -type s -name agent.\* 2>/dev/null`
# DBUS address is needed to display notify-send messages
GNOME_PID=$(pgrep gnome-session)
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$GNOME_PID/environ|cut -d= -f2-)
# Script execution, in order:
#
# - mount the encrypted drive (prompt for password)
# - close the Nautilus window that pops up for a new mounted device
# - add the SSH key to ssh-agent (prompt for password)
# - unmount the encrypted drive
# - display a notification that the key is loaded
#
# if any of the above steps failed, display a failure notification
veracrypt -m ro $DEVNAME /media/keyring && \
killall nautilus && \
ssh-add -c -t 8h /media/keyring/work/id_rsa && \
veracrypt -d $DEVNAME && \
sudo -u $LOGNAME notify-send -i media-removable 'SSH keys loaded' "`ssh-add -l`" && \
exit
sudo -u $LOGNAME notify-send -i emblem-unreadable 'Failed to load SSH keys' 'Investigate manually'
} &
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment