Skip to content

Instantly share code, notes, and snippets.

@coconut49
Forked from dtaylor84/gpg-agent-forward.sh
Created May 15, 2017 07:10
Show Gist options
  • Save coconut49/362557e8e75bc1abb07e2eab2f52e9b2 to your computer and use it in GitHub Desktop.
Save coconut49/362557e8e75bc1abb07e2eab2f52e9b2 to your computer and use it in GitHub Desktop.
Cygwin GPG Agent Forwarding Script (for use with Gpg4Win 3, requires openssh and ssh-pageant)
#!/bin/bash -e
remote="$1@$2"
echo -ne '\e]0;wait... '"$remote"'\a'
eval $(/usr/bin/ssh-pageant -r -a "/tmp/.ssh-pageant-$USERNAME")
localdir="$(cygpath -u "$APPDATA")/gnupg"
extrasock="$localdir/S.gpg-agent.extra" # file containing "PORT\nNONCE"
rdir='$HOME/.gnupg' # remote prefix
rinsock="$rdir/S.gpg-agent" # listen on this socket on server
rfwdsockname="S.gpg-agent.fwd"
rfwdsock="$rdir/$rfwdsockname" # write to this socket on server
rfwdsockrelative=".gnupg/$rfwdsockname" # relative to $HOME
rnonce="$rdir/nonce/gpg-agent-nonce" # store NONCE here on server
port=$(head -n1 "$extrasock") # forward server socket to this port on client
src="UNIX-LISTEN:$rinsock,fork" # parent listens to $rinsock, forks filter
dest="UNIX-CONNECT\\:$rfwdsock" # filter writes to $rfwdsock N.B. escape colon!
# write NONCE to client, then establish bidirectional communication
filter="SYSTEM:cat \\\"$rnonce\\\" - <&3 | socat STDIO \\\"$dest\\\" >&4,fdin=3,fdout=4"
settitle="echo -ne '\e]0;gpg-agent $remote\a'"
prompt="echo 'Enter to quit:'"
cleanup='kill -9 $(jobs -p)'
# First, clear any old sockets, write NONCE, echo $HOME
rprecommand="rm -f $rinsock $rfwdsock; cat > $rnonce; echo \$HOME"
# Then establish socat magic (in background) and wait for enter, then kill socat
rcommand="socat \"$src\" \"$filter\"& $settitle; $prompt; read; $cleanup"
remotehome=$(tail -n+2 "$extrasock" | ssh "$remote" "$rprecommand")
ssh -t -R "$remotehome/$rfwdsockrelative:localhost:$port" "$remote" "$rcommand"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment