Tunneling a local port via SSH to a publicly accessible host

Tobias Böse
NEW IT Engineering
Published in
2 min readFeb 28, 2019

For learning purposes we have a RaspberryPi Cluster in our office. Anyone who wants to work/play on this machine needs to be physically in our office till now, as we do not have the possibility to open a port in our router/firewall.

We had to come up with an idea how to access our little Cube from outside.

Using a VPN would be an option but I wanted to keep it as simple as possible for me and my teammates to access our Cluster. I decided to use Remote Port Forwarding over a SSH tunnel instead.

How does SSH Remote Port Forwarding works?

(Source : https://de.wikipedia.org/wiki/Datei:Ssh-R-tunnel.svg)

The remotehost allows a SSH connection on port 22 (or any other port you like for SSH).

Your host will open a SSH connection to the remotehost and tell it to open a port (in this example 123) your localhost will then establish the SSH tunnel and will wait for incoming connections on the remotehost, if there is one it will forward all traffic to nearhost on port 456.

What needs to be done?

What is needed:

  • A server which is accessible over the internet (I’ve used Amazon Lightsail as we already had an AWS-Account)
  • Configure ssh-server to accept gateway-ports
  • Public key authentication (optional)
  • SSH client on your local maschine

To configure the server to accept connections from the internet on the opened remote ports we need to modify the sshd_config (usually located in /etc/ssh/ or /etc/sshd/), make sure you have the following line in your config file:

GatewayPorts clientspecified

Restart the SSH daemon.

If you want to run the remote port forwarding automatically (e.g. as a service) you should setup public key authentication so you don’t have to login each time you want to tunnel something.

Check out https://www.ssh.com/ssh/key/ for how to setup a public key authentication.

Make sure that your firewall on your server is allowing your desired port.

Now you can establish a SSH tunnel on your local machine with the following command:

ssh -R 123:nearhost:456 remotehost

the -R option tells the SSH client you want to forward all traffic from port 123 on remotehost to port 456 on nearhost.

This also works for Windows clients, tell me in the comment if you need a little advice on how to do this with putty.

--

--