Sub topic 12
SSH tunnels for single services
This chapter assumes you know TCP versus UDP, basic IP addressing, and how to use a Linux shell. It also assumes you have read the earlier chapters on encapsulation and key exchange. A VPN carries whole IP packets. An SSH tunnel carries individual TCP connections, one service at a time, over a connection you probably already have.
What an SSH tunnel is
SSH (Secure Shell) is a protocol for encrypted remote login. A single SSH connection can carry many independent channels. One channel might be your shell. Others can be forwarded TCP connections.
SSH port forwarding works like this:
- A program on one end of the SSH session listens on a TCP port.
- When an application connects to that port, the program opens a new channel inside the SSH session.
- The SSH program on the other end opens an ordinary TCP connection to a destination and copies bytes between that connection and the channel.
This differs from GRE, IPsec or WireGuard in several ways:
- There is no tunnel interface and there are no routes to change. The application must be pointed at the local listening port, or at a SOCKS proxy.
- Each forwarded connection is terminated at both ends and re-created. Your TCP connection to
localhost:8080is not the one that reaches the web server. Because of this, MTU and fragmentation problems from earlier chapters rarely appear. TCP over a TCP-based tunnel also does not cause the stalls that raw IP-over-TCP tunnels can. - Only TCP is forwarded. UDP, ICMP and arbitrary IP protocols are not.
- Authentication reuses what SSH already has: host keys for the server and public keys or passwords for the user.
Local forwarding with -L
Local forwarding exposes a remote service on a local port. This is the example from the chapter plan:
ssh -L 8080:intranet.example.com:80 [email protected]The format is -L [bind_address:]local_port:destination_host:destination_port. After the login succeeds, a browser pointed at http://localhost:8080 reaches port 80 on intranet.example.com.
The destination is resolved and connected from the SSH server's side. Two consequences follow:
intranet.example.comonly has to resolve and be reachable from the bastion, not from your laptop.- If you write
-L 8080:localhost:80,localhostmeans the bastion itself, not your laptop.
By default the client listens only on the loopback address 127.0.0.1. Other machines on your network cannot use the forward. Writing -L 0.0.0.0:8080:... opens it to everyone who can reach your machine, which is rarely what you want.
For a tunnel with no interactive shell, add these options:
ssh -N -f -o ExitOnForwardFailure=yes \
-L 8080:intranet.example.com:80 [email protected]-Nruns no remote command, so the session only holds forwards.-fmoves ssh to the background after authentication.ExitOnForwardFailure=yesmakes ssh exit if it cannot bind the local port. Without it, ssh can stay connected with the forward silently missing.
Remote forwarding with -R
Remote forwarding reverses the direction. The SSH server listens, and connections to that port are carried back to a destination reachable from the client:
ssh -N -R 9000:localhost:3000 [email protected]Now a connection to port 9000 on the bastion arrives at port 3000 on your laptop. People use this to show a development server to someone else, or to reach a machine behind NAT that can make outbound connections but accepts no inbound ones.
The server decides how widely the port is exposed. By default sshd binds remote forwards to loopback only. The GatewayPorts setting in sshd_config changes that, and it should stay off unless you need it.
Dynamic forwarding with -D
Local forwarding fixes one destination per forwarded port. Dynamic forwarding turns ssh into a SOCKS proxy, where the application chooses the destination for each connection:
ssh -N -D 1080 [email protected]
curl --socks5-hostname localhost:1080 http://intranet.example.com/SOCKS (Socket Secure) is a proxy protocol that lets a client ask the proxy to connect somewhere on its behalf. --socks5-hostname sends the hostname to the proxy, so the name is resolved on the bastion. With plain --socks5, curl resolves the name locally. That would fail for internal names, and it would leak the lookup to your local resolver.
Browsers have a similar setting. Firefox has a "Proxy DNS when using SOCKS v5" option. Without it, the browser's DNS queries bypass the tunnel.
Jump hosts and configuration
A jump host (bastion) is a hardened server that is the only way into a private network. Modern OpenSSH can chain through one with -J:
ssh -J [email protected] [email protected]The connection to the inner host is itself tunnelled through the bastion, and the inner host's keys are checked end to end. Forwards can be stored in ~/.ssh/config:
Host intranet-tunnel
HostName bastion.example.com
User user
LocalForward 8080 intranet.example.com:80
ServerAliveInterval 30
ServerAliveCountMax 3
ExitOnForwardFailure yesssh -N intranet-tunnel then opens the forward. The keepalive options send a probe every 30 seconds, and ssh exits after three missed replies. A dead session from a NAT timeout or a lost link is then noticed instead of hanging.
Comparison with a VPN
| Property | SSH forwarding | WireGuard or IPsec VPN |
|---|---|---|
| Unit carried | One TCP connection | Whole IP packets |
| Protocols | TCP only | TCP, UDP, ICMP, anything over IP |
| Client setup | One command, no privileges | Interface and routes, usually root |
| Application changes | Must target the local port or SOCKS proxy | None, routing sends traffic into the tunnel |
| Server needs | An SSH account | A VPN endpoint and address plan |
| Scope of access | Only the forwards you open | Whatever the routes and firewall allow |
| MTU concerns | Rare | Common |
SSH tunnels suit a small number of known services and ad hoc access. For many services, UDP, or transparent access for every application, use a VPN. SSH also offers -w for layer 3 tunnel devices (PermitTunnel must be enabled on the server). That mode carries IP over a TCP connection and brings back the performance problems of TCP over TCP, so most deployments choose a real VPN instead.
Security considerations
- Only the SSH leg is protected. In the
-Lexample, traffic from the bastion tointranet.example.com:80is plain HTTP. Anyone on that network segment can read it. - Forwards can bypass your firewall. A user who may log in to a server can often open a path to any host that server can reach. Administrators restrict this with
AllowTcpForwarding noorPermitOpeninsshd_config, or withrestrict,port-forwarding,permitopen="..."options on a key inauthorized_keys. - A listening local port is open to local users. Any process on your machine can connect to
127.0.0.1:8080and use the tunnel. On a shared host, that is a real exposure. - Check the host key. The first-connection fingerprint prompt is the only protection against a man-in-the-middle attacker at that point. A changed-key warning means stop and investigate.
Troubleshooting forwards
Start by checking that the listener exists:
ss -ltn | grep 8080Then read the error messages. Running ssh with -v shows each channel open and failure.
| Message | Meaning | What to check |
|---|---|---|
| `bind [127.0.0.1]:8080: Address already in use` | Another process owns the local port | Pick another port or find the process with `ss -ltnp` |
| `channel 2: open failed: connect failed: Connection refused` | The bastion reached the destination host, but nothing listens on that port | Test from the bastion: `nc -vz intranet.example.com 80` |
| `channel 2: open failed: connect failed: Name or service not known` | The bastion cannot resolve the destination name | Use an IP address, or fix the bastion's DNS |
| `channel 2: open failed: administratively prohibited` | The server forbids this forward | Look at `AllowTcpForwarding` and `PermitOpen` |
| Forward works, then hangs after idle time | A NAT or firewall dropped the idle session | Set `ServerAliveInterval` |
| Browser works but internal names fail | DNS is resolved locally, not through the proxy | Use remote DNS with SOCKS5 |
The connection-refused case is a common mistake. The tunnel itself is fine, and the problem is the second leg, from the bastion to the destination. Test that leg directly from the bastion before changing any tunnel options.
Exercise
You run ssh -N -L 5432:localhost:5432 [email protected]. A colleague asks why psql -h localhost -p 5432 on your laptop connects to a database that is not running on your laptop. Which machine does the second localhost in the command refer to, and what would you change to reach a database on a separate host db1.internal that the gateway can see?
Show answer
The destination localhost:5432 is resolved on the SSH server, so it means db-gateway.example.com itself. Your local psql connects to the local listening port 5432, and the gateway then connects to its own port 5432. To reach db1.internal, use -L 5432:db1.internal:5432. The name db1.internal only has to resolve from the gateway.
Exercise
You start ssh -N -D 1080 [email protected] and use it as a SOCKS proxy for a browser. Internal site names fail to load, although the same names work from the bastion. What is the likely cause, and what is the fix?
Show answer
The browser is resolving names locally instead of sending them through the proxy, so the local resolver cannot find the internal names. Enable remote DNS over SOCKS5 in the browser (for curl, use --socks5-hostname). The bastion then resolves the names.