From a5d59943ce0bf7ebbfa739a201786170fe1bd3d8 Mon Sep 17 00:00:00 2001 From: Eric Nielsen Date: Mon, 10 Sep 2018 11:35:29 -0500 Subject: [PATCH] [ssh] Update init.zsh based on https://stackoverflow.com/a/48509425/2654518, which is based on http://rabexc.org/posts/pitfalls-of-ssh-agents Current code has a few issues: depends on `SSH_AUTH_SOCK` and `SSH_AGENT_PID` env variables, which might not be available in every shell session; and tries to create a new socket for agent-forwarding by checking `SSH_AUTH_SOCKET` instead of `SSH_AUTH_SOCK`. Also, it's safer to create the env file with 066 flags and in the user home directory. --- modules/ssh/init.zsh | 40 ++++++++++++++-------------------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/modules/ssh/init.zsh b/modules/ssh/init.zsh index 4411406..0b6b735 100644 --- a/modules/ssh/init.zsh +++ b/modules/ssh/init.zsh @@ -7,40 +7,28 @@ if (( ! ${+commands[ssh-agent]} )); then return 1 fi -# use a sane temp dir; creating 1k ssh-* files in /tmp is crazy -if [[ ${TMPDIR} ]]; then - local ssh_env=${TMPDIR}/ssh-agent.env - local ssh_sock=${TMPDIR}/ssh-agent.sock -else - # create a sane tmp dir at /tmp/username - mkdir -p /tmp/${USER} - local ssh_env=/tmp/${USER}/ssh-agent.env - local ssh_sock=/tmp/${USER}/ssh-agent.sock -fi +ssh-add -l &>/dev/null +if (( ? == 2 )); then + # Unable to contact the authentication agent -# start ssh-agent if not already running -if [[ ! -S ${SSH_AUTH_SOCK} ]]; then - # read environment if possible - source ${ssh_env} 2> /dev/null + # Load stored agent connection info + local ssh_env="${HOME}/.ssh-agent" + [[ -r ${ssh_env} ]] && source ${ssh_env} >/dev/null - if ! ps -U ${LOGNAME} -o pid,ucomm | grep -q -- "${SSH_AGENT_PID:--1} ssh-agent"; then - eval "$(ssh-agent | sed '/^echo /d' | tee ${ssh_env})" + ssh-add -l &>/dev/null + if (( ? == 2 )); then + # Start agent and store agent connection info + (umask 066; ssh-agent >! ${ssh_env}) + source ${ssh_env} >/dev/null fi fi -# create socket -if [[ -S ${SSH_AUTH_SOCKET} && ${SSH_AUTH_SOCKET} != ${ssh_sock} ]]; then - ln -sf ${SSH_AUTH_SOCKET} ${ssh_sock} - export SSH_AUTH_SOCK=${ssh_sock} -fi - -# load ids -if ssh-add -l 2>&1 | grep -q 'no identities'; then +# Load identities +ssh-add -l &>/dev/null +if (( ? == 1 )); then if (( ${#zssh_ids} > 0 )); then ssh-add "${HOME}/.ssh/${^zssh_ids[@]}" 2> /dev/null else ssh-add 2> /dev/null fi fi - -unset ssh_{sock,env}