blob: 69ff3dbf93862bca278b591f313f45b42f63f667 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#!/usr/bin/env bash
#
# gpg-forward - Forward local gpg-agent socket to remote machine
#
# GPG operations (like git commit signing) require access to a gpg-agent socket.
# When working on a remote machine, we want to use the yubikey connected to our
# local machine. This requires forwarding the local gpg-agent socket to the remote
# machine.
#
# This script establishes ONLY the socket forwarding via ssh, without a terminal.
# Run this in a separate terminal when you need gpg operations to work on the
# remote machine (e.g. when using et/eternal-terminal).
#
if [ -z "$1" ]; then
echo "Usage: gpg-forward [hostname]"
exit 1
fi
HOST=$1
echo "Forwarding gpg-agent to $HOST..."
# kill any existing ControlMaster connection
ssh -O exit "$HOST" 2>/dev/null || true
# first, clean up any stale socket on the remote
ssh -o "ControlMaster=no" "$HOST" "rm -f /run/user/1000/gnupg/S.gpg-agent"
# -N = no remote commands (no shell)
# -T = disable pseudo-terminal allocation
# -o ExitOnForwardFailure=yes = exit if forwarding fails instead of connecting anyway
# -o StreamLocalBindUnlink=yes = remove existing socket on remote if present
ssh -N -T \
-o "ExitOnForwardFailure=yes" \
-o "StreamLocalBindUnlink=yes" \
-R "/run/user/1000/gnupg/S.gpg-agent:/run/user/1000/gnupg/S.gpg-agent.extra" \
"$HOST" &
# capture the ssh process id
SSH_PID=$!
# wait a moment for connection to establish
sleep 1
# check if ssh process is still running (connection succeeded)
if kill -0 $SSH_PID 2>/dev/null; then
echo "Connection established. GPG agent forwarded successfully."
echo "Forwarding will continue until you press Ctrl-C"
# wait for ssh process to exit (when user presses Ctrl-C)
wait $SSH_PID
else
echo "Failed to establish connection!"
exit 1
fi
echo "GPG agent forwarding stopped."
|