29 April 2015

Port forwarding (tunneling), especially the local port forwarding, is a very handy feature of SSH. This blog explains local port forwarding in detail first. After that, this blog then introduces remote port forwarding and dynamic port forwarding briefly.

How local port forwarding works

Before getting started, let us assume we have the following three hosts and want to forward all traffics to port 80 of my pc to the port 8080 of target host.

local-port-forwarding-1.png

This is a case which SSH local port forwarding applies. The command to set the tunnel is:

ssh ssh_server -L 80:target:8080

This command set up a SSH connection between my PC and the SSH server. This connection, in addition to working as usual, also acts a tunnel.

local-port-forwarding-2.png

When traffics arrive at port 80 of my pc, they will then go through the tunnel.

local-port-forwarding-3.png

Jump three hops

Note that in fact a traffic can be originated from a forth machine. That is, you can "jump 3 hops" with a single SSH tunnel.

local-port-forwarding-4.png

According to man page, the listening port will, by default, be bond to the loop back interface only. To forward traffics from other machines, one must

  1. Set GatewayPorts in /etc/ssh/sshd_config to "yes".
  2. Specify bind address. For instance (empty or * for any), on ssh client run the following command:
    ssh -L :80:ssh_server:8080 target
    

But according to my test,

  1. GatewayPorts does not take effect.
  2. Remote port forward bind to all interface by default.

Option '-N'

Do not execute a remote command. This is useful for just forwarding ports (protocol version 2 only).

Remote Port Forwarding

As the name indicates, remote port forwarding is the reverse of local port forwarding. This time, the traffic arrives at the "remote" side will be forwarded to the host on local side.

ssh ssh_server -R :8888:target:8080
ssh ssh_server -R :8888:localhost:8080

remote-port-forwarding.png

Dynamic Port Forwarding

Yet another kind of port forwarding turns your local machine to a socket proxy. For instance, assume that your local machine locates behind firewall and all outgoing HTTP requests are filtered by the firewall. A way to circumvent this restriction is to set up an ssh server outside the firewall and employ the dynamic port forwarding technique.

  1. Run the following command to set up ssh tunnel.
    ssh ssh_server -D 8000
    
  2. Then, in web browser, set proxy as "SOCKS Host" localhost:8000.

Exercise: study the following picture and compare dynamic port forwarding with local port forwarding.

dynamic-port-forwarding.png



blog comments powered by Disqus