GuestbookSign our guestbook ContactGet in touch with the authors ArchiveAll unixwerk articles since 2003
August 16, 2016

SSH Agent Forwarding

 

SSH agent forwarding is an easy way to connect to a host A with your SSH key and from there connect to another host B with that same key without the need to store your private key on host A. This obviously is only needed if you cannot connect to host B directly from your workstation. You should only use SSH agent forwarding on hosts you trust¹.

Contents

  1. Setup
  2. Automation
  3. Test
  4. Using Agent Forwarding with ssh

 

1. Setup

First we need to start the key agent itself:

$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-J9mtJc0fZ7Dg/agent.33226848; export SSH_AUTH_SOCK;
SSH_AGENT_PID=5243126; export SSH_AGENT_PID;
echo Agent pid 5243126;

Then we have to paste the output above into the running shell and add our private key (~/.ssh/id_rsa):

$ SSH_AUTH_SOCK=/tmp/ssh-J9mtJc0fZ7Dg/agent.33226848; export SSH_AUTH_SOCK;
$ SSH_AGENT_PID=5243126; export SSH_AGENT_PID;
$ ssh-add

If you want the shell to automatically pick up the variables from the output you could use eval:

$ eval "$(ssh-agent)"
$ ssh-add

 

2. Automation

Of course we don't want to manually start the key agent and add our key(s) every time we login to our jumpserver So we add the below lines to our ~/.profile:

# Start SSH Key Agent
ps -fu $USER | grep [s]sh-agent > /dev/null \
   && $HOME/.ssh-agent \
   || { ssh-agent > $HOME/.ssh-agent 2>&1 ; \
        . $HOME/.ssh-agent ; \
        ssh-add ; \
      }

The above code only starts an ssh agent when there is not another one already running. In both cases it adds your private key.

 

3. Test

$ ssh-add -l
2048 a6:d2:c4:12:a7:40:32:19:81:2c:14:8c:27:47:ea:56 /home/user/.ssh/id_rsa (RSA)

If you see something like above the key agent is running and your key has been added to the agent.

 

4. Using Agent Forwarding with ssh

You need to enable agent forwarding for ssh. This can be either done by using ssh with the -A option

$ ssh -A jumpserver

or by adding the line 'ForwardAgent yes'  to your ~/.ssh/config for all hosts you want to use ssh agent forwarding:

Host jumpserver
   ForwardAgent yes

 

 


References
¹ https://support.ssh.com/manuals/server-zos-admin/55/Disabling_Agent_Forwarding.html