Port forwarding in linux usually requires the use of iptables. Although DigitalOcean’s article provides an excellent guide on how to configure iptables, the rules are not really easy to understand. I end up having to lookup the commands every single time I need to port forward.
SSH tunnels
SSH tunnels allows us to port forward easily with just a single command. Let’s say we have two servers, A and B, and we want to forward all traffic on port 8080 on server A to server B’s port 80:
$ ssh -L 8080:localhost:80 server-b.example.org
Since it’s a tunnel, you can even port forward to a different server. Say server C is only accessible via server B, and we want to forward to server C’s port 80 instead:
What if server B is inside some secure network and cannot be accessed by server A? We can initiate an SSH connection from server B and use an SSH reverse tunnel:
# executing this command from server B$ ssh -R 8080:localhost:80 server-a.example.org
This is great for servers behind a double NAT or for servers that you don’t want to expose to the internet.
Making it persistent
Combine SSH tunnels with autossh, you can make sure the connection is restarted automatically when the SSH connection is disconnected:
Enabling external connections to access the port forwards
Port forwards are generally bound to localhost by default (ie. you can only access the port forward locally). To access the port forward from outside, you’ll need to make sure GatewayPorts is enabled in your sshd_config:
If you’re using reverse tunnel, you’ll need to allow the client to specify an address:
GatewayPorts clientspecified
Pros and Cons
Pros
Easy one liner to port forward
Port forwarding is only in effect when connection can be established (port closes automatically if connection is closed)
Cons
Need to expose SSH port 22, in which it could be security risk
Adwin Ying
Self-taught full-stack web dev based in Tokyo.
Occasionally wrecks servers through
self-hosting
and
homelab-ing.