Port tunneling with SSH
Here is another quick one that is also easy to forget. One of the many uses of SSH is local and remote port forwarding. Using local port forwarding, you can set up a socket between a port in your local machine and your SSH server. Whenever a communication is established on that local port, it will be forwarded to the server and then, made. This has some interesting use cases, such as connecting to local services (web administration panels, databases…) or acting as a jump server or just a proxy server.
The syntax unfortunately may require reading the command a few times to understand:
ssh -L [local port]:[destination]:[remote port] [SSH server]
And this behaves as follows:
After starting the SSH connection, port [local port] will be listening on your local (laptop, desktop) computer. Communications made through this port will be sent to your SSH server, and then forwarded to [destination]:[remote port].
Keep in mind the port order. First you write the port you want to open client-side, on your laptop or wherever you are running the SSH command. And then, you write the port you want your server to connect to.
I’m providing an example to show interesting use cases for this:
There is a local web service running on a server binded to the loopback interface listening at http://127.0.0.1:8080. We want to connect to the web service remotely outside the local network but we’d rather not open that web service to the public Internet. If we had SSH access to that server, we could use the following command:
ssh -L 9000:localhost:8080 firstname.lastname@example.org
Now, if we open our browser and navigate to http://localhost:9000 in our local machine, that web request will be forwarded to our SSH server, and our SSH server, acting like a proxy 1, will forward again that request to localhost:8080. Because now it’s the server the one that is making the request, localhost is relative to the server, so it will connect to our web service, and because the request is coming via the local interface, it will work.
The response will be forwarded securely to our computer and we will see it in our web browser like if we had the service in our own machines. And because this is all using SSH tunneling, to outsiders or evil attackers it will look like regular and encrypted SSH traffic.
This is useful for database consoles, printer dashboards and almost any software that opens TCP connections.
Trigger warning. It is not exactly a proxy, although it works similar. ↩