Port forwarding: local, remote, dynamic
Local, remote and dynamic forwarding: what each does, the syntax, and the limits.
Port forwarding carries other TCP traffic through the encrypted SSH connection. It is defined in RFC 4254.
Local forwarding (-L)
Listens on your device and sends the traffic to a host the SSH server can reach.
ssh -L 5433:db.internal:5432 jsmith@gateway
Now localhost:5433 on your device reaches db.internal:5432. Use it for a database or a web page that is only visible inside the network.
Remote forwarding (-R)
The opposite: the server listens and sends the traffic back to you.
ssh -R 8080:localhost:3000 jsmith@server
Anything that connects to port 8080 on the server arrives at port 3000 on your device. By default the server only listens on its own loopback address. GatewayPorts on the server changes that.
Dynamic forwarding (-D)
Opens a SOCKS proxy on your device. Programs set to use it send all their traffic through the SSH server.
ssh -D 1080 jsmith@server
Rules to know
- A forward lives as long as the SSH connection does.
- The listening address is localhost unless you say otherwise. Binding to all addresses lets other devices on the network use your tunnel.
- The server can forbid forwarding (
AllowTcpForwarding no) or limit it withPermitOpen. - A forwarded port that is already in use fails. Pick another local port. When the server refuses an
-Rforward, see SSH "remote port forwarding failed for listen port": why ssh -R is refused. - Mosh does not forward ports. Use SSH.
Related
- Jump hosts
- SSH problems
- App guide: Port forwarding
- SSH port forwarding through a jump host: -J with -L
- SSH "remote port forwarding failed for listen port": why ssh -R is refused
- Keep an SSH tunnel running: autossh, ServerAliveInterval and systemd
- bind_address in ssh -L and ssh -R: localhost, * and GatewayPorts
- ssh -R with port 0: let the server pick the port, and find out which one