Home SSH Port Forwarding
Post
Cancel

SSH Port Forwarding

Guide for basic SSH usage and SSH Port Forwarding.

  1. Basic SSH
  2. SSH Port Forwarding

Basic SSH

Connect to Host

1
ssh [email protected]_IP -p 2222
  • -p to specify the port (22 is default)

Connect to Host with Private Key

1
ssh -i PRIVATE_KEY [email protected]_IP

Copy Files to Host

1
scp local_file.txt [email protected]_IP:/tmp/remote_file.txt

Copy Files from Host

1
scp [email protected]_IP:/tmp/remote_file.txt local_file.txt 

Connect to Host with Certain KeyExchange & Cipher

1
ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 -c aes256-ctr [email protected]_IP


SSH Port Forwarding

Local SSH Port Forward

Let’s say a remote host has an application listening on localhost:3000 and you want to connect to it from your local computer. Perhaps it’s a database listening on localhost and you don’t want it exposed to the network/internet.

Using a Local Port Forward we can setup a listener on our local computer, which when we connect to will go through the SSH tunnel to the listener on the remote host.

Here is the command that will allow us to do that:

1
ssh -L 1337:localhost:3000 [email protected]_HOST_IP

This command will setup a listener on your local machine on localhost:1337. Connecting to this will be the same as if you connected to localhost:3000 on the remote host.

Remote SSH Port Forward

Let’s say you have an application listening on localhost:9595 on your local computer and your friend wants to connect to your application. However, both you and your friend home networks are behind CGNAT so you can’t directly connect to each other or setup normal router port forwards.

With an additional internet facing server (VPS such as an EC2 instance), you can do the following:

On your computer:

1
ssh -R 9000:localhost:9595 [email protected]_HOST_IP

This command will setup a listener on the remote host on localhost:9000. Connecting to the remote host on localhost:9000 will be the same as if you connected to localhost:9595 on your local machine.

This situation is now the same as a Local Port Forward. The remote host is now listening on localhost:9000. Your friend can now create a new listener on their computer using a Local Port Forward.

On your friends computer:

1
ssh -L 1337:localhost:9000 [email protected]_HOST_IP

Gateway Ports

For the above example we had todo two port forwards, this isn’t ideal is some cases. Ideally we would like to setup a listen on a specific interface or on 0.0.0.0. However, when we do an SSH Port Forward, the default listener is on 127.0.0.1. To change this and allow it to listen on all interfaces, we need to enabled the GatewayPorts options on the SSH Server and restart it.

This post is licensed under CC BY 4.0 by the author.