Reverse SSH Tunneling, Bypassing Firewalls and NAT
Sometimes we want to connect to a machine using SSH but can't because it is behind some firewall or NAT router. This is a common situation when you want to connect to office computers which are usually behind a firewall or NAT router, from an outside computer. Reverse SSH tunnelling is a way to do so. In this article we will set up a Reverse SSH tunnel.
Reverse SSH tunneling is way to ssh to a remote linux machine that sits behind a firewall or a NAT(Network Address Translation) router. In order to create a reverse SSH tunnel, you must have ssh access to a middle computer you can connect to and that can connect to your desination computer.
Let's assume for simplicity the following 3 computers:
Destination Machine(that we want to connect to) 10.3.3.65.
Middle Machine 192.168.0.15.
Home Computer 172.17.12.84
The middle computer can connect to home as well as the destination computer. But the home computer cannot connect to destination computer directly. We will make it possible using the middle computer. Follow the following steps to do so:
First make sure that the ssh server on the destination machine has GatewayPorts turned on. If you are using an openssh server you can find it in the file /etc/ssh/sshd_config. Open it.
[destination computer]$ vi /etc/ssh/sshd_config
Make sure it has the following line
If its missing then add that line and restart the ssh server(you will have to be root to do so)
[destination computer]$ service sshd restart
First of all type the following command on the Destination(10.3.3.65) computer
[destination computer]$ ssh -R 4040:localhost:22 email@example.com
PS: To use Ports below 1024 you will have to login as root
This will open a port 4040 on the middle machine(192.168.0.15) and all the connections through port 4040 on the middle machine will be forwarded to "localhost" (local for destination computer i.e. destination computer itself) at port 22.
Now we will connect to the middle computer at port 4040. And from Step 1 we have already confirmed that all the traffic on the middle computer through port 4040 will be forwarded to the destination computer using port 22. So, after running the following command from the 3rd computer, home computer you will be connected to the destination computer directly(which was earlier not possible)
[home computer]$ ssh firstname.lastname@example.org -p4040
OR you can connect to middle computer like you normally do.
[home computer]$ ssh email@example.com
and after successfully connecting to your middle computer. Run the following command
[middle computer]$ ssh destination-user@localhost -p4040
destination-user - user on the destination machine(10.3.3.65)
middle-machine-user - user on the middle machine(192.168.0.15)