Apostolos Papazisis

Laravel Entwickler

AWS Web Services

Vue.Js Entwickler

Shopware 6

Freiberufler

Apostolos Papazisis

Laravel Entwickler

AWS Web Services

Vue.Js Entwickler

Shopware 6

Freiberufler

Blog Post

SSH Port forward

3. August 2022 Allgemein
SSH Port forward

SSH tunneling (also referred to as SSH port forwarding) is simply routing the local network traffic through SSH to remote hosts. This implies that all your connections are secured using encryption. It provides an easy way of setting up a basic VPN (Virtual Private Network), useful for connecting to private networks over unsecure public networks like the Internet.

Local SSH Port Forwarding

This type of port forwarding lets you connect from your local computer to a remote server. Assuming you are behind a restrictive firewall or blocked by an outgoing firewall from accessing an application running on port 3000 on your remote server.

You can forward a local port (e.g 8080) which you can then use to access the application locally as follows. The -L flag defines the port forwarded to the remote host and remote port.

ssh admin@server1.example.com -L 8080:server1.example.com:3000

Adding the -N flag means do not execute a remote command, you will not get a shell in this case.

ssh -N admin@server1.example.com -L 8080:server1.example.com:3000

The -f switch instructs ssh to run in the background.

ssh -f -N admin@server1.example.com -L 8080:server1.example.com:3000

Now, on your local machine, open a browser, instead of accessing the remote application using the address server1.example.com:3000, you can simply use localhost:8080 or 192.168.43.31:8080, as shown in the screenshot below.

Remote SSH Port Forwarding

Remote port forwarding allows you to connect from your remote machine to the local computer. By default, SSH does not permit remote port forwarding. You can enable this using the GatewayPorts directive in your SSHD main configuration file /etc/ssh/sshd_config on the remote host.

Open the file for editing using your favorite command-line editor.

sudo vim /etc/ssh/sshd_config 

Look for the required directive, uncomment it, and set its value to yes, as shown in the screenshot.

GatewayPorts yes

Save the changes and exit. Next, you need to restart sshd to apply the recent change you made.

sudo systemctl restart sshd
OR
sudo service sshd restart 

Next run the following command to forward port 5000 on the remote machine to port 3000 on the local machine.

ssh -f -N admin@server1.example.com -R 5000:localhost:3000

Once you understand this method of tunneling, you can easily and securely expose a local development server, especially behind NATs and firewalls to the Internet over secure tunnels. Tunnels such as Ngrokpagekitelocaltunnel, and many others work in a similar way.