This is Part 1 of a three-part series on SSH tunneling. Part 2 looks at how attackers abuse tunnels in real intrusions, and Part 3 covers how to detect them.
Most people meet SSH as “the thing you use to get a shell on a Linux box.” That’s true, but it undersells it. An SSH connection is really an encrypted pipe that can carry several independent streams at once, and only one of them has to be your shell. The others can carry database connections, web traffic, RDP sessions or almost anything else that speaks TCP.
That feature is called port forwarding, or more casually, SSH tunneling. It’s one of the most useful tools an admin has, and, as we’ll see in Part 2, one of the favorite tools of attackers who have already found a way in. Understanding exactly how it works is the first step to using it well and spotting it when someone else does.
How SSH tunneling works
When you open an SSH connection, the client and server agree on keys and set up one encrypted transport, usually on TCP port 22. Inside that transport, SSH opens channels. Your interactive shell is one channel. A forwarded port is another. Each new TCP connection that goes through a tunnel gets its own channel, and all of them share the same encrypted connection.
Two details matter a lot in practice:
- Encryption only covers the SSH leg. Traffic is encrypted between the SSH client and the SSH server. Once it leaves the far end of the tunnel and heads to its final destination, it’s whatever protocol it was to begin with, plain text included.
- The far end makes the final connection. When you forward a port to
db.internal:5432, it’s the SSH server that resolves that name and opens the connection. That’s how tunnels reach places your own machine can’t.
The four main ways to tunnel
| Type | Flag | Listener lives on | Traffic exits at | Typical use |
|---|---|---|---|---|
| Local forwarding | -L | SSH client | SSH server | Reach an internal service from outside |
| Remote forwarding | -R | SSH server | SSH client | Expose a service that sits behind NAT |
| Dynamic forwarding | -D | SSH client (SOCKS proxy) | SSH server | Browse or scan many internal hosts |
| Jump host | -J | n/a | Final target | Hop through a bastion to an inner server |
1. Local port forwarding (-L)
Local forwarding is the one you’ll use most. The SSH client opens a listening port on your machine, and anything that connects to it gets carried through the tunnel and delivered to a host and port from the server’s point of view.
# ssh -L [bind_address:]local_port:target_host:target_port user@ssh_server
ssh -N -L 15432:db.internal:5432 alice@bastion.example.com
# then, in another terminal
psql -h localhost -p 15432 -U app_reader appdb

A few things worth knowing:
-Ntells SSH not to run a remote command, so you just get the tunnel. Add-fif you want it to go to the background.- By default the listener binds to the loopback address only, which is what you want. Don’t use
-gor bind to0.0.0.0unless you really mean to let other machines on your network use your tunnel. - Pick a local port that’s free. Using 15432 instead of 5432 avoids clashing with a local PostgreSQL install.
2. Remote port forwarding (-R)
Remote forwarding flips the direction. You ask the SSH server to open a listening port, and connections to it travel back through the tunnel to something reachable from your side. The key point is that your machine starts the connection. Nothing has to be allowed inbound to reach you, which is why this works from behind NAT, and why it gets abused.
# ssh -R [bind_address:]remote_port:target_host:target_port user@ssh_server
ssh -N -R 9000:localhost:3000 alice@vps.example.com

On the server, OpenSSH’s GatewayPorts setting decides who can connect to that remote port. With the default (no), it only listens on the server’s loopback interface, so only users already on the VPS can reach it. Since OpenSSH 7.6, giving -R just a port number (for example -R 1080) creates a reverse SOCKS proxy. Keep that one in mind for Part 2.
3. Dynamic port forwarding (-D)
With -L, each tunnel goes to one fixed destination. Dynamic forwarding removes that limit. The client runs a small SOCKS4/SOCKS5 proxy, and the application tells it where each connection should go. The SSH server then connects wherever it’s asked to.
ssh -N -D 1080 alice@bastion.example.com
# use it from a single tool
curl --socks5-hostname 127.0.0.1:1080 https://wiki.internal/
# or route a whole tool through it with proxychains
proxychains4 nmap -sT -Pn -p 443 10.0.5.0/24

Use --socks5-hostname (or “remote DNS” in your browser’s proxy settings) so that names like wiki.internal are resolved on the far side, not by your local resolver. Also note that SOCKS only carries TCP, so tools that need raw packets, such as an nmap SYN scan, won’t work through it. That’s why the example uses -sT.
4. Jump hosts (-J / ProxyJump)
Sometimes you don’t want a port, you want a shell on a server that’s only reachable from a bastion. The old way was to SSH to the bastion and then SSH again from there, often with agent forwarding (-A) so your key was available on the bastion. ProxyJump, added in OpenSSH 7.3, is cleaner and safer:
ssh -J alice@bastion.example.com alice@app01.internal

Your client builds a second SSH session inside the first one. The bastion only relays TCP, and your private key never leaves your laptop. With agent forwarding, by contrast, anyone with root on the bastion can use your agent to log in as you while you’re connected.
Bonus: full VPN with tun devices (-w)
OpenSSH can also create a layer-3 tunnel between two tun interfaces with -w, which effectively gives you a basic VPN. It needs root on both ends and PermitTunnel enabled on the server, so it’s rarely used for day-to-day work. Today WireGuard is the better choice for that job. It’s worth knowing it exists, mainly so you remember to keep it turned off.
Keeping tunnels stable
Typing long -L strings gets old fast. Put them in ~/.ssh/config instead:
Host bastion
HostName bastion.example.com
User alice
IdentityFile ~/.ssh/id_ed25519
Host db-tunnel
HostName bastion.example.com
User alice
IdentityFile ~/.ssh/id_ed25519
LocalForward 127.0.0.1:15432 db.internal:5432
ExitOnForwardFailure yes
ServerAliveInterval 30
ServerAliveCountMax 3
SessionType none # same as -N (OpenSSH 8.7+)
Host app01
HostName app01.internal
User alice
ProxyJump bastion
Now ssh db-tunnel brings up the database tunnel and ssh app01 hops through the bastion automatically. ExitOnForwardFailure is underrated: without it, SSH happily connects even if the port you wanted is already in use, and you spend ten minutes wondering why nothing works. ServerAliveInterval sends keepalives so idle tunnels don’t get silently dropped by firewalls. For tunnels that must survive network blips, tools like autossh or a small systemd unit can restart them.
Real-world use cases
- Database access for admins. Keep PostgreSQL, MySQL or Redis off the Internet entirely and reach them through a bastion with
-L. This is probably the single most common legitimate tunnel. - Internal web consoles. Grafana, Kibana, a router’s admin page or a Jenkins instance can stay bound to an internal interface and still be reachable when you need them.
- Wrapping old, unencrypted protocols. VNC, legacy SCADA web UIs or anything else that was never designed for hostile networks can ride inside SSH instead of being exposed in plain text.
- Working from untrusted Wi-Fi. A quick
-Dproxy to a server you trust keeps your browsing off a hotel or café network. - Reaching lab gear behind NAT. A Raspberry Pi or test box at home can keep a
-Rtunnel open to a VPS so you can reach it from anywhere. (It’s convenient, but treat that VPS as part of your attack surface.) - Automation through a bastion. Ansible, CI/CD runners and backup jobs can use ProxyJump to reach private servers without each one needing a public IP.
- Penetration testing (with permission). Red teams pivot through compromised hosts with
-Dand-Rexactly the way real attackers do, which is also why defenders should know these patterns cold.
Best practices: locking tunnels down
Out of the box, OpenSSH allows TCP forwarding for every user who can log in. That’s convenient, but it means every SSH account is also a potential pivot point. The safest approach is to turn forwarding off by default and grant it only where it’s needed, with explicit limits on where tunnels can go.
Server side: sshd_config
# /etc/ssh/sshd_config (OpenSSH 7.8 or newer)
# --- Authentication ---
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
# --- Forwarding: off by default ---
AllowTcpForwarding no
GatewayPorts no
PermitTunnel no
X11Forwarding no
AllowAgentForwarding no
# --- Logging: record which key was used for each login ---
LogLevel VERBOSE
# --- Allow a tightly scoped tunnel for one group only ---
Match Group db-tunnel
AllowTcpForwarding local # client-side -L/-D only; no -R listeners
PermitOpen db.internal:5432 # the only destination they can reach
PermitTTY no
ForceCommand /bin/false # no shell; users connect with -N
After editing, always run sshd -t to check the syntax before reloading, and keep a second session open in case you lock yourself out.
AllowTcpForwardingacceptsyes,no,localandremote. Use the narrowest value that works.PermitOpenlimits where-Ltunnels may go.PermitListen(OpenSSH 7.8+) does the same for the ports a-Rtunnel may open on the server.DisableForwarding yesis a one-line kill switch for every kind of forwarding. It’s ideal for SFTP-only accounts.- Remember that disabling forwarding doesn’t stop a user who has a shell from running their own proxy tools. It removes the easy path, but it isn’t a substitute for network controls.
Per-key restrictions: authorized_keys
For service accounts, you can lock a single key to a single tunnel and nothing else. The restrict option turns everything off, and you add back only what you need:
restrict,port-forwarding,permitopen="db.internal:5432" ssh-ed25519 AAAAC3Nza... backup-job@ci
Client side habits
- Bind local listeners to
127.0.0.1explicitly and avoid-g. - Prefer
ProxyJumpover agent forwarding. - Use
ExitOnForwardFailure yesso broken tunnels fail loudly. - Close tunnels when you’re done. A forgotten tunnel is an open door that nobody is watching.
- Protect your keys with a passphrase, or better, a hardware key (
ed25519-sk).
Network and process
- Filter outbound SSH. Servers rarely need to start SSH connections to the Internet. Blocking outbound TCP 22 (and watching for SSH on other ports) shuts down the most common reverse-tunnel trick.
- Funnel access through a bastion. One well-logged, well-patched jump host is much easier to monitor than SSH open everywhere.
- Keep a list of approved tunnels. If you know which tunnels are supposed to exist, anything else stands out immediately.
- Log and alert. Ship sshd logs to your SIEM and alert on forwarding from unexpected hosts. Part 3 of this series goes through the detection rules in detail.
Wrapping up
SSH tunneling is one of those features that feels like magic the first time you use it. A single encrypted connection can replace a VPN, keep databases off the Internet, and get you into a lab sitting behind three layers of NAT. The catch is that the same flexibility works for anyone who gets hold of an SSH client and a set of credentials.
In Part 2, we’ll walk through a real intrusion investigated by CISA, where attackers used a renamed copy of PuTTY’s plink to build a hidden, persistent tunnel out of a U.S. federal agency’s network.

2 thoughts on “SSH Tunneling Explained: Local, Remote, Dynamic Forwarding and How to Do It Safely”