Reverse SSH Connection


This document will show how to make an ssh connection between a client and a server that is behind a firewall.  This is acheived by using an intermediate computer that is located on the internet that you have control over and is not behind a firewall (or at least you have the ability to open ports on its firewall).

Overview diagram

Setting up the Intermediate Machine

The intermediate machine needs to be running sshd to allow the other machines to make a connection to it.  You will also need to alter the sshd config file (/etc/ssh/sshd_config) and add the following line.
GatewayPorts yes
This option allows you to directly connect to the intermediate machine on the bound port that is chosen directly (in our example, port 9876), otherwise you would need to do a normal ssh to the intermediate machine and then connect to localhost on the bound port (ssh target_user@localhost -p 9876).

Setting up the reverse connection

Setting up the reverse connection is straight forward, just issue the following command on the target machine:
ssh -N -f -R 9876:localhost:22 user@intermediate_machine
The options are -N which is do not execute a remote command, -f fork into the background after connection and -R which is to setup the reverse connection.  The arguments for the reverse connection are in our example forwarding traffic from port 22 to port 9876.  Port 22 is the standard port for ssh sessions and 9876 could be any port that you choose.  The rest of the command just specifies how to connect to the intermediate machine.  Because you are not wanting to actually get a command prompt on the intermediate machine you can set the user here to have /bin/false as their shell in /etc/passwd.

Connecting from the client

Now that we have setup target machine to connect to the intermediate we can issue the following command from our client machine.
ssh target_user@intermediate_machine -p 9876
You will now find yourself logged into the target machine as target_user.