Create a remote port forwarding connection using SSH

Published at 26 Sep 2024 ·

A tunnel in SSH allows you to access another device in the network using a secure connection.

A remote port forwarding connection allows you to redirect all traffic a device receives at a specific port to your computer. Using it we can grant temporary access to anyone in the world to a computer that is not directly exposed to the internet, behind a NAT for example.

You can also redirect the incoming traffic to another device in your local network, this is useful if you need to have access to a local server, for example, but the internet provider is having an outage.

In order to create a reverse forwarding connection, we need two devices with SSH installed, one with the server and another with the client installation.

Server-side configuration

We need to perform some configurations on the server side in order to be able to create it.

vi /etc/ssh/sshd_config

We need to find the property "AllowTcpForwarding" and change its value to "yes".

AllowTcpForwarding yes

By doing this we will allow the creation of remote port forwarding connections through our server.

Once we changed this configuration we must restart the SSHD service.

systemctl restart sshd.service

Remote port forwarding (Local)

Now that we've got our server configured we can try creating a new connection in order to test out if it's working correctly

For example, we want to make our port 80 (local website) accessible from outside our network using port 8080 of our public server.

ssh -R 8080:127.0.0.1:80 [email protected]

If we now try to access port 8080 of our server, http://sertxudeveloper.com:8080, we will see the page of our local website.

Let's explain the different parameters of this command:

Remote port forwarding (Remote)

Using the same command as the previous example, we can redirect all the incoming forwarded traffic to a local device that has not initialized the SSH connection.

Let's see an example where this can be useful:

This is a real example that occurred to me once.

By connecting the laptop to the local wired network and using my mobile phone as a Wi-Fi hotspot we can access the internet and the local network at the same time.

With this configuration, we can create a remote port forwarding connection, so by connecting to the remote port using Remote Desktop we can access the windows server that has no direct connection to the internet.

I used the following command in order to create this remote port forwarding connection:

ssh -R 13389:192.168.1.254:3389 [email protected]

Using Windows Remote Desktop connecting to the sertxudeveloper.com:13389 host we will be able to connect successfully to our Windows server until the internet outage is over.

Let's explain the different parameters of this command: