SSH Tunnel (SSH Port forwarding)

1. Local Forwarding

Make Remote resource accessible on your local system.

Forward a port from the client machine to the server machine. SSH Client listens for connections on a local configured port, and when it receives a connection, it tunnels the connection to an SSH Server. The server connects to a configured destination port, possibly on a different machine than SSH Server.

$ ssh -L 3000:RemoteAppServer:4000 user@RemoteSSHServer:22

2. Remote Forwarding

Make Local resource accessible on a remote system.

Open port on the remote SSH server, any connection to the port on remote SSH server will be tunneled back to the client host, client host will forward connection to local resource.

$ ssh -R 5000:LocalAppIp:3000 user@SshServer:22

By default, OpenSSH only allows connecting to remote forwarded ports from the server host. However, the GatewayPorts option in the server configuration file sshd_config can be used to control this:

GatewayPorts no             # Prevents connecting to forwarded ports from outside the server
GatewayPorts yes            # Allow anyone to connect to forwarded ports from outside the server
GatewayPorts clientspecified # Client can specify IP address allowed
$ ssh -R RemoteClientIp:5000:localhost:3000 user@SshServer:22

Multiple remote port forwarding can be done in one command line:

$ ssh -R 5000:LocalAppIp0:3000 -R 5001:LocalAppIp1:3001 user@SshServer:22

3. Dynamic Port Forwarding: Use SSH Server as proxy

Dynamic port forwarding works similar to a proxy or VPN. The SSH client creates a SOCKS proxy you can configure applications to use. All traffic sent through the proxy will be sent through the SSH Server.

Examples:

  • Using public Wi-Fi securely by tunneling through home SSH server.
  • Accessing a home network media server with only SSH exposed.
$ ssh -D local_port username@server.com

4. SSH Server configuration

AllowTcpForwarding must be enabled on the server to allow port forwarding.

Possible values:

  • yes or all: allow all forwarding
  • no: disable all forwarding
  • local: allow only local forwarding
  • remote: allow only remote forwarding

5. SSH client options

ssh -fNT -R remote_port:local_server:local_port user@ssh_server

-f  Requests ssh to go to background before execution
-N  Do not execute a remote command
-T  Disable pseudo-tty allocation

References