SSH Remote Port Forwarding

This is a task that should be extremely simple and minimally frustrating after the first time. The idea behind remote port forwarding is that you want a port on your public remote server to be forwarded to your local computer, which is running a service on a port. This service can then be accessed from anywhere as if it was running on the remoteserver. This enables you to bypass networks that block all incoming connections, get around a router that will not allow you to port forward, and encrypt server traffic from anyone sniffing your (local) network.

First, you’ll want to configure your sshd correctly, which is running on remoteserver. Pop open /etc/sshd/sshd_config, or wherever your sshd_config is stored, and ensure the following lines exist, are correct, and uncommented:

1
2
AllowTcpForwarding yes
GatewayPorts yes
This is particularly important as **GatewayPorts** generally defaults to no as a security feature. With this set to no, only the *remoteserver* will be able to connect to the port and ONLY via its loopback address. When setting this to “yes,” please ensure any services running on the forwarded ports are secure as they will be open to connections from anywhere.

Once this is done, restart or reload your sshd. For example, on CentOS:

1
2
$ /etc/init.d/sshd reload
Reloading sshd: [ OK ]

Using PuTTy on our localcomputer, go to Connection->SSH->Tunnels and configure it like so:

PuTTY Remote Port Forward

In this case, any traffic sent to remoteserver on port 12345 will be forwarded to localcomputer on port 5900. Start the connection and log in to begin forwarding. If you’re on linux, the same can be accomplished via

ssh -R 12345:localhost:5900 remoteserver

Troubleshooting

If you’re failing to connect to localcomputer via remoteserver:port, it is usually one of the following:

  • SSHD has not loaded the new configuration yet(remember that the new configuration will only apply to new connections)
  • A firewall or iptables is configured to block traffic on non-whitelisted ports
  • You may not actually have the service listening on localcomputer

The first two can be solved by searching how to restart SSHD on your specific distro, and how to configure iptables/whatever firewall respectively. For the third, you can check if the service is actually listening by running

netstat -an | grep "LISTENING"

This will allow you to determine if the service is even running correctly.

Also, note, that this only works for TCP connections due to the differences in UDP.