Ssh-agent key timeout with screen or tmux on bastion host

gnu-screensshssh-agenttmux

Normally I have ssh-agent running, I ssh to my bastion host then open a tmux session and connect to other boxes through that. Key forwarding works for any sessions that I open from that point forward.

If I resume my tmux session after closing terminal, sleeping my laptop, whatever, my key forwarding on my bastion sessions still work, as does forwarding on any new sessions. Existing ones don't work, though.

I have a little thing in my bashrc that keeps key forwarding working when I resume tmux, but I am having trouble figuring out how to get it to keep working for sessions open within tmux.

For example, I have bastion01, dbhost01, dbhost02, webhost01, and webhost02.

If I open a connection to bastion01, start tmux there, and then connect to dbhost01 and webhost01 forwarding works. If I close that connection, reconnect and attach my existing tmux session, then add connections to dbhost02 and webhost02, key forwarding works on the 02 boxes, but does not on the 01.

Please help!

Best Answer

Each time you ssh into bastion01, a different socket is opened to handle the key forwarding. You can see the filename in the environment variable SSH_AUTH_SOCK. When you start tmux, the value of that environment variable is included in tmux's global environment, which is inherited by any shells started in that session.

Now, when you reconnect to bastion01 later, a different socket is allocated to handle your key forwarding (since it's a new ssh session). You can see this by examining the value of SSH_AUTH_SOCK before you re-attach to your tmux session and after. In order for key forwarding to work inside tmux, you need to update the value of SSH_AUTH_SOCK inside tmux to the name of the socket being used by the current ssh session.

A quick-and-dirty way to do this is to write a short script that will save this new value to a file, and execute that inside any tmux window where you will be ssh-ing from.

#!/bin/bash

echo "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK" > ~/.auth_ssh

Execute that script as soon as you ssh into bastion01, but before you re-attach to your tmux session. Then, before you try to ssh anywhere from inside tmux, run the following:

source ~/.auth_ssh

Each tmux window has its own environment, so you'll need to run that in each window where you try to run ssh. For simplicity, you can alias ssh to do it for you:

alias ssh="source ~/.auth_ssh; ssh"

Note: this is a gross oversimplification of a script we use at work to update the SSH authorization information. If it doesn't work quite right, I hope this at least gives you enough information to google a better solution (or someone else posts a better solution here).

Related Question