SSH Remote Port Forwarding

  • Posted Saturday, September 17, 2016
  • 2 minute read

Getting access to services behind firewalls is easy when you have SSH access to a server within that network. All you need to do is use a few SSH flags. Using those flags you can forward ports of services hosted locally on a remote server to your local machine, and do the same with servers you can reach from that SSH server.

Forwarding local services

VNC is a good example to show local service port forwarding, since it’s a service that uses it a lot. VNC is an unencrypted protocol usually available at port 5900. Since VNC is unencrypted, it’s usually not exposed to the public internet to prevent interception and sniffing. So in order to securely connect to VNC, you usually have to conenct to it through an SSH tunnel.

Using an SSH tunnel would accomplish two things. It would allow you to securely connect to the server securely using keys, rather than passwords, and it would also allow you to encrypt the insecure VNC traffic through a secure SSH tunnel.

In order to connect to VNC you would run the following command:

ssh -N -L5900:localhost:5900 [email protected]

This would create an SSH tunnel that would bind port 5900 of the connecting computer to port 5900 of localhost, which in this case is server.com.

local service ssh tunnel

What this means, that if on your local machine you connect to localhost:5900, you won’t be connecting to your local computer, that connection will actually be tunnelled to server.com.

Forwarding Remote Services

Using the same command, you can also forward connections not only from the server you have SSH access to, but to external servers it has access too. This is a great way of accessing servers that are behind strict firewalls.

In the diagram below, there is your personal computer, a private network which contains a server you have SSH access to, and a database which is not accessible because of firewall rules.

private network with ssh server and database

In order to connect to the Database, which is accessible within the private network at database.com:1521, you would run the following command:

ssh -N -L1521:database.com:1521 [email protected]

This would bind the 1521 port of your personal computer through an ssh tunnel to server.com, which also forwards its connection to port 1521 to database.com:1521. Wew. This is modelled in the diagram below.

private network with ssh server and database accessible with ssh tunnel

This would allow you to use a database management application to connect and work with the database. When setting up the database you would connect to it as if the database were hosted on on your local machine at port 1521.


comments powered by Disqus