Saturday, July 7, 2012

Reverse SSH tunnel to connect to a machine inaccessible due to firewall or NAT


We cannot directly connect to a machine if it is behind a NAT (Network Address Translation) or a firewall. Almost all large networks (corporate and universities) have firewalls and may also employ NATs. Even home routers are now using some sort of NAT.

We need to create a reverse SSH tunnel to establish a connection. If you are familiar with Hamachi or gotomypc type software do the exact same thing  - they connect to computers behind NAT/Firewalls, only they use their severs as the middle man. We are going to have to find our middle man on our own.

In order for you to create a reverse tunnel you must have SSH access to a middle computer that you can connect to from origin computer.

Step-1:
On the destination computer type the following command. Replaceing middleuser with your name and replacing middle with the domain of the middle computer.
ssh -R 10002:localhost:22 middleuser@middle
This will open port 10002 for listening and forward all future connections to port 22 at destination. This connection must remain on the entire time to ensure that you can access your destination computer whenever you want.

Step-2:
Now if sshd is set to use GatewayPorts you should be able to connect with this:
ssh destinationuser@middle -p 10002
If you are not sure if GatewayPorts is on or you don’t have the access to change it use the following method to connect:

First connect to the middle computer how you would normally.
ssh user@middle
Then connect to the localhost of the middle computer on port 10002.
ssh user@localhost -p 10002
Note: The port 10002 is arbitrary you can use any port you want.

You should now be remotely logged into your computer behind the NAT/Firewall. Enjoy :)

Refer [2] to make the reverse ssh tunnel permanent, and restart automatically if the tunnel gets closed.

Reference:
1. http://www.marksanborn.net/howto/bypass-firewall-and-nat-with-reverse-ssh-tunnel/
2. http://www.clingmarks.com/setup-a-unbreakable-ssh-tunnel/21

No comments:

Post a Comment