Introduction to SSH tunnels

(Please note this post was originally published in the Spanish version of Security Art Work last 19th Jul 2012)

All of us have at some time found that the service we wanted to access is on a computer unreachable from our network or other similar problems. If we have SSH access we can easily solve problems like this using SSH tunnels.

We propose a first scenario, in which we have a database server protected by a firewall that prevents us directly interact with the database but that can be accessed by SSH (assuming MySQL, which uses port 3306).

In this case, to gain local access to the database, we will make all traffic going to local port X to be redirected through the SSH connection to local port 3306 of the machine to which we are connecting, using the tt>-L switch:

ssh -L X:localhost:3306 172.16.1.100

Now, if we have an application that uses that database server, we simply must tell the app that that the database is on our local computer on port X. Similarly, if the database it is in a third computer, to which we do not have access from our local computer but we do from the server to which we connect through SSH, the order would be:

ssh -L X:172.16.1.111:3306 172.16.1.100

We may also want just the opposite: that a remote server can access a resource or service provided by our computer or our local network.

In this case, we will redirect to port Z of our computer all the traffic that the remote server sends to its Y port, using the -R switch:

ssh -R Y:localhost:Z 172.16.1.100

Just as in the previous case, if the computer that provides the service that we want to connect to is different from ours, we will change localhost with the IP address of that computer. For example:

ssh -R Y:192.168.0.123:Z 172.16.1.100

As an extra, note that SSH servers offer another interesting feature, which consists of creating a SOCKS proxy on the local computer. With this we can do that all requests that are sent to the X port on the local computer to be redirected to the remote computer and sent to their destination as if the remote computer would have sent them:

ssh -D X 172.16.1.100

This is especially useful since there are many applications whose traffic can be forwarded through a SOCKS proxy. The best example of this are modern browsers, such as Firefox, for example:

We hope you enjoyed this small post.