SSH port forwarding

Isn’t SSH great? It’s secure and it can do lots of cool things, as providing access to services to local machines that are only available to the remote machines (that you can connect through SSH). This is called port forwarding.

Windows with Putty

So, you are on your local windows box and got ssh access to a remote machine, let’s call it “Remote” and from there you can access a service in another machine, let’s call it “Far”. The problem is that from your local windows box you can’t directly access “Far” (most times because the good people of network, and their strong sense of security…, vpn’s, etc).

So:
Localbox -> Remote (ok)
Localbox -> Far (not ok)
Localbox -> Remote -> Far (ok)

and it would be nice to test the service (lets say HTTP to exemplify) running on Far with your nice Localbox browser, instead of the console based Lynx browser that you have on Remote.

Enter the black magic of ssh port forwarding. With Putty (the SSH client for Windows) it’s pretty easy. Just open your connection normally, but before pressing the Open button, go to Connection -> SSH -> Tunnels:

The source port will be the port on your Localbox, i usually put there the localhost ip:port combination (127.0.0.1:80).  You should check with “netstat -an” if you have this free, if there is some service (IIS, Apache) already running on this ip:port stop it. The destination is the Far ip:port that you want to get access (far_ip:80). Click “Add”.  And open the connection normally and login to the Remote console. On the Localbox check again with “netstat -an” and you should have an entry like this

TCP    127.0.0.1:80           0.0.0.0:0              LISTENING

And there you go! You have an open tunnel from Localbox to Far. Now just open the browser on localbox and point it to 127.0.0.1, your request is being sent to Far. If you need an hostname to access the service correctly just put it on the hosts file:

127.0.0.1 hostname

Linux

Pretty easy… just with the ssh -L switch.
-L localport:foreig_ip:foreign_port

To make this clear, an example. On my production server i run a MySQL server instance, but it only listens to localhost (127.0.0.1) but i want to use a GUI to manage it. I have the GUI in my linux box, so it would be impossible to connect the GUI to the MySQL server… not with ssh around…

ssh user@mysqlhost -L 3306:127.0.0.1:3306

after the ssh connection is made i can access the MySQL server as if it was running on my Linux localhost. We can even check with netstat.

netstat -an | grep 3306 | grep LISTEN

it should get something like:
tcp    0    0    127.0.0.1:3306    0.0.0.0:*    LISTEN
tcp6    0    0    ::1:3306    :::*    LISTEN

There, a no-brainer sometimes very useful.

Leave a Reply