Skip to Content

ssh-forwarding-example

There are three type of SSH Tunnel forwarding:

  • Local forwarding
  • Remote forwarding
  • Dynamic forwarding (we do not cover it here)

Local forwarding

Imagine you’re on a private network which doesn’t allow connections to a specific server. Let’s say you’re at work and private.com is being blocked, can only access from the private network.

To get around this we can create a tunnel through a server we-have-access.com which isn’t on our network and thus can access private.com:

    ssh -L 9000:private.com:80 myuser@we-have-access.com

The key here is -L which says we’re doing local port forwarding. Then it says we’re forwarding our local port 9000 to private.com:80, which is the default port for HTTP. Now open your browser and go to http://localhost:9000 you will be able to access the private site at private.com inside the private network!

The great thing is the above connection is encrypted. so nobody can see what you are visiting.

Sometime you need to access a db behind a firewall, let’s say you need to access a MySQL db (private-db:3306) behind a firewall, and we have user on example.com, which can access private-db:3306 directly, then we can do this:

    ssh -L 3308:private-db:3306 myuser@example.com

So you can use any db tool to connect to local 3308 port which will be forwarded to private-db:3306

Remote forwarding

Say that you’re developing an app on your local machine, the app listen on port 8000 and you’d like to show it to a friend. Unfortunately your ISP didn’t provide you with a public IP address, so it’s not possible to connect to your machine directly via the internet.

Sometimes this can be solved by configuring NAT (Network Address Translation) on your router, but this doesn’t always work, and it requires you to change the configuration on your router, which isn’t always possible.

To fix this problem you need to have server, which has publicly IP and you have SSH access on it. then you can do this:

    ssh -R 9080:0.0.0.0:8000 we-have-access.com 

In this example, you forward connection from we-have-access.com:9080 to your local 0.0.0.0:8000, so if your friend can access we-have-access.com:9080, he is fine to access your app on your localhost:8000, which is great!

Please note remember to enable the option in /etc/ssh/sshd_config, by default this is disabled on Centos7:

    GatewayPorts yes

Make sure you add it only once and restart SSH.

    sudo service ssh restart

Tips

You might have noticed that every time we create a tunnel you also SSH into the server and get a shell. This isn’t usually necessary, as you’re just trying to create a tunnel. To avoid this we can run SSH with the -nNT flags, such as the following: (which will cause SSH to not allocate a tty and only do the port forwarding).

    ssh -nNT -L 9000:private-access.com:80 user@we-have-access.com

Read more in “man ssh”, and I enjoy those in my daily life.