Skip to content

Instantly share code, notes, and snippets.

@anroots
Last active March 28, 2018 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anroots/64725de8f3338c4cdae50449824dad6f to your computer and use it in GitHub Desktop.
Save anroots/64725de8f3338c4cdae50449824dad6f to your computer and use it in GitHub Desktop.
.bashrc snippet to automatically start ssh-agent and load it with a key from YubiKey PKCS storage
# Tested on Ubuntu 17.10
# Put this into your .bashrc or similar file
# It will ensure each new terminal window has ssh-agent accessible
# and loaded with YubiKey SSH key
# Built upon work from https://stackoverflow.com/a/18915067/401554
SSH_ENV=$HOME/.ssh/environment
PKCS_PATH=/usr/lib/x86_64-linux-gnu/pkcs11/opensc-pkcs11.so
function start_agent {
# Don't start the agent if YubiKey is not in the reader
yubico-piv-tool -a version > /dev/null 2>&1 || return 1
echo -n "Initializing new SSH agent..."
/usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}" || return 1
echo " [ok]"
chmod 600 "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
echo "Adding YubiKey to the agent, enter your PIN"
/usr/bin/ssh-add -t 36000 -s $PKCS_PATH
}
if [ -f "${SSH_ENV}" ]; then
. "${SSH_ENV}" > /dev/null
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
start_agent;
}
else
start_agent;
fi
# Run this command when you have physically removed and re-inserted
# your YubiKey - it will re-add your PKCS key to the agent
alias re-yubi="ssh-add -e $PKCS_PATH && ssh-add -s $PKCS_PATH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment