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:
yesorall: allow all forwardingno: disable all forwardinglocal: allow only local forwardingremote: 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
You might also like
SSH Tunnel (SSH Port forwarding)
Guide to SSH tunnels including local, remote, and dynamic port forwarding, plus server and client configuration.
Managing Multiple GPG Keys and YubiKey Setup
A practical guide to managing multiple GPG private keys — exporting, importing, backing up, and securely storing them on a YubiKey for signing, encryption, and SSH authentication.