Skip to content

Instantly share code, notes, and snippets.

@bdd
Last active July 28, 2022 15:32
Show Gist options
  • Save bdd/4729695 to your computer and use it in GitHub Desktop.
Save bdd/4729695 to your computer and use it in GitHub Desktop.
Reset SSH agent socket and Kerberos credentials cache environment variables.
# -*- mode: shell-script -*-
#
# reset-auth.zsh
#
# When reattaching to a tmux (or screen session) authentication forwarding and
# delegation environment variables needs to be reset.
#
# Shell functions below can reset forwarded SSH Agent socket and Kerberos
# credentials cache environment variables by discovering and testing validity
# (ssh-agent only) on the remote machine.
#
# These functions rely on zsh's expansion features, making them ZSH only.
# Though it they could be ported to other shells by simply relying on `find`.
function reset-auth () {
reset-ssh-agent
reset-krb-cc
}
function reset-ssh-agent () {
local exportcmd sock
# ZSH filename expansion:
# "=": file is a socket,
# "U": owned by $USER,
# "N": ...and expand to null if there are no matches.
#
# SSH agent sockets, owned by user, sorted by receny (newest first).
for sock in $(stat --format='%Z:%n' /tmp/ssh-*/*(=UN) 2> /dev/null | \
sort -rn | cut -d : -f 2)
do
# Multiple SSH connections will create different forwardings and we can't
# assure the remote detects and cleans up dead connection's forwarding
# socket immediately. We may have stales. Test if there's a live ssh-agent
# on the client side of the socket by simply requesting a key list.
SSH_AUTH_SOCK=$sock ssh-add -l > /dev/null 2>&1
if [[ $? == 0 ]]; then
exportcmd="export SSH_AUTH_SOCK=$sock"
eval $exportcmd && echo $exportcmd
break
fi
done
}
function reset-krb-cc () {
local exportcmd f
# ZSH filename expansion:
# ".": file is a regular file,
# "U": owned by $USER,
# "N": ...and expand to null if there are no matches.
#
# Kerberos 5 credentials cache files, owned by user, sorted by receny.
#
# Unlike SSH agent forwarding, we don't have a chance to test the validity of
# a KRB5CC so just use the most recent one.
for f in $(stat --format='%Z:%n' /tmp/krb5cc_*(.UN) 2> /dev/null | \
sort -rn | head -n 1 | cut -d : -f 2)
do
exportcmd="export KRB5CCNAME=FILE:$f"
eval $exportcmd && echo $exportcmd
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment