Advanced SSH, part 1: reach a machine behind a firewall through a bastion host, with every command run for real in a three-machine lab.
▶Prefer to watch? This short video runs this page's main commands in a real three-machine lab, with on-screen captions and a synthetic voiceover (an AI voice trained on the author's own recording). Click to play, or watch it on YouTube.
SSH tunnels: reach what you cannot reach directly, through a machine you can.
ssh -L 8080:intranet:80 bastion local forward: localhost:8080 becomes intranet:80
ssh -D 1080 bastion SOCKS proxy: any program, any inside address
ssh -R 9000:localhost:3000 bastion remote forward: show your laptop's port on the bastion
ssh -J bastion intranet jump host: log in to a machine behind the bastion
SSH does more than log you in. It can carry other traffic inside the same encrypted connection, so a web page on a private network, a database port or a development server can be reached through one SSH login. This is what people mean by an SSH tunnel.
This is part 1 of a series on the advanced features of the ssh command. It covers tunnels and jump hosts. File transfer and mounting (sshfs), keeping tunnels alive, and certificates come in later parts. Keys are in Creating SSH Keys and Passwordless SSH Login, and locking the server down is in the SSH Hardening guide; this page links to them where they matter.
Every command below was run for real, in a lab of three Docker containers on Ubuntu 24.04 with OpenSSH 9.6p1. The screens shown are the real output. The section "What was not run" lists what was not tried.
What tunnels are for
Use a tunnel when the thing you need is reachable from one machine you can log in to, but not from yours:
open an internal web page ssh -L: localhost:8080 shows the intranet site
use a database on a private net ssh -L: point your client at localhost and a local port
browse as if you were inside ssh -D: a SOCKS proxy for the browser or curl
show your work to a server ssh -R: the server reaches a dev server on your laptop
log in to a machine behind a ssh -J (ProxyJump): one command, the middle host only
bastion host passes the bytes along
Why SSH and not a VPN: if you can already ssh to a machine, it costs nothing to set up, it is encrypted, and it needs no software on the far side. The price is that each tunnel is one port, or one proxy, not a whole network. For a whole network, a VPN is the right tool (ssh can also do that with -w, which was not run).
Words used on this page. The laptop is the machine you sit at. The bastion (also called a jump host) is a server you can reach and that can reach the private network. The intranet host is a machine on the private network that only the bastion can see.
The lab
Three containers on two Docker networks, built for this guide:
laptop --[ outside network ]-- bastion --[ inside network ]-- intranet
(you) (both networks) web page on port 80
Both networks are Docker "internal" networks. That is the stand-in for a firewall: the laptop has no route to the inside network, and the intranet host has no route to the laptop. Only the bastion is on both. A real firewall would do the same job with rules, and the tunnels below work the same way.
The laptop holds the only private key (a plain ed25519 key without a passphrase, which is fine for a lab and not for real use). The bastion and the intranet host trust it. The bastion has no private key of its own, on purpose, so that the agent forwarding section has something to show. A small web page ("Intranet portal") runs on the intranet host, and a pretend development server runs on port 3000 of the laptop.
The client has StrictHostKeyChecking accept-new in its system config so the first connection does not stop to ask. Do not copy that line for real servers without thinking about what it skips. The versions:
$ ssh -V
OpenSSH_9.6p1 Ubuntu-3ubuntu13.20, OpenSSL 3.0.13 30 Jan 2024
$ hostname ; ssh bastion hostname
laptop
bastion
The problem: no route
From the laptop, the intranet host cannot be found, by name or by address:
$ curl -sS -m3 http://intranet/ ; echo "exit status $?"
curl: (6) Could not resolve host: intranet
exit status 6
$ curl -sS -m3 http://172.28.0.2/ ; echo "exit status $?"
curl: (7) Failed to connect to 172.28.0.2 port 80 after 0 ms: Couldn't connect to server
exit status 7
The name does not resolve (curl status 6) and the address is not reachable (status 7). The bastion, though, is on the inside network, so from there it works:
$ ssh bastion 'curl -sS -m3 http://intranet/'
<html><body style="font-family:sans-serif"><h1>Intranet portal</h1>
<p>You can only see this from inside the firewall.</p></body></html>
That is the whole situation. The rest of this page is different ways to make the laptop use the bastion's view.
Local forward: ssh -L
-L opens a port on your own machine and sends everything that arrives there, through the SSH connection, to a place the bastion can reach:
ssh -L [bind_address:]port:host:hostport server
Read it from left to right: listen on port on the laptop, and for each connection ask the server to open a connection to host:hostport. In the lab:
$ ssh -f -N -L 8080:intranet:80 bastion
$ ss -ltn | grep 8080
$ curl -sS -m3 localhost:8080
LISTEN 0 128 127.0.0.1:8080 0.0.0.0:*
LISTEN 0 128 [::1]:8080 [::]:*
<html><body style="font-family:sans-serif"><h1>Intranet portal</h1>
<p>You can only see this from inside the firewall.</p></body></html>
-N means "no remote command": ssh only sets up the forward and does not start a shell. -f sends ssh to the background once the login has worked, so the terminal is free. The ssh process keeps running as the tunnel:
$ pgrep -a -x ssh
319 ssh -f -N -L 8080:intranet:80 bastion
Stop it with kill, or with pkill -x ssh (the -x matters: it matches the process name exactly, where pkill -f would also match the shell command that contains the words). The laptop is listening on 127.0.0.1 and ::1, so only programs on the laptop can use it.
The host in the middle is looked up by the bastion, not by the laptop. That is why "intranet" worked here even though the laptop cannot resolve it. It also means that "localhost" in a -L means the bastion itself:
$ ssh -f -N -L 8080:localhost:80 bastion
$ curl -sS -m3 localhost:8080 ; echo "exit status $?"
curl: (56) Recv failure: Connection reset by peer
exit status 56
The tunnel opened, but nothing listens on port 80 of the bastion, so the connection was closed straight away. When a forward "works" and the page does not load, check that the host:port is correct from the server's point of view.
Local forward: ports in use and who can connect
If the local port is taken, ssh warns and carries on with the login anyway. With the tunnel from before still running on 8080:
$ ssh -N -L 8080:intranet:80 bastion (timeout killed it after 4 seconds)
bind [127.0.0.1]:8080: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 8080
Could not request local forwarding.
exit status 124
The login stayed up (status 124 is timeout ending it), but this second tunnel does nothing, which is easy to miss in a script. Add -o ExitOnForwardFailure=yes and ssh gives up instead:
$ ssh -N -o ExitOnForwardFailure=yes -L 8080:intranet:80 bastion
bind [127.0.0.1]:8080: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 8080
Could not request local forwarding.
exit status 255
Who may use the tunnel is decided by the bind address. The default is the loopback address only. From the bastion, the laptop's port 8080 is not reachable:
$ ss -ltn | grep 8080 (on the laptop)
$ ssh bastion 'curl -sS -m3 http://laptop:8080/ ; echo "exit status $?"'
LISTEN 0 128 127.0.0.1:8080 0.0.0.0:*
LISTEN 0 128 [::1]:8080 [::]:*
curl: (7) Failed to connect to laptop port 8080 after 1 ms: Couldn't connect to server
exit status 7
Giving a bind address (or *) in front changes that. With -L 0.0.0.0:8080:intranet:80, the listener is on every address and the bastion can now use the laptop as a door into the intranet:
$ ssh -f -N -L 0.0.0.0:8080:intranet:80 bastion
$ ss -ltn | grep 8080
$ ssh bastion 'curl -sS -m3 http://laptop:8080/'
LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*
<html><body style="font-family:sans-serif"><h1>Intranet portal</h1>
<p>You can only see this from inside the firewall.</p></body></html>
Anyone who can reach the laptop on that port can now reach the intranet page, with no login. Only open a tunnel to all addresses on purpose, on a network you trust.
Dynamic forward: ssh -D
-L is one port to one place. -D turns the SSH connection into a SOCKS proxy: a listener on your machine that any SOCKS-aware program can use to reach any host and port that the bastion can reach.
$ ssh -f -N -D 1080 bastion
$ ss -ltn | grep 1080
LISTEN 0 128 127.0.0.1:1080 0.0.0.0:*
LISTEN 0 128 [::1]:1080 [::]:*
$ curl -sS -m3 --socks5-hostname localhost:1080 http://intranet/
<html><body style="font-family:sans-serif"><h1>Intranet portal</h1>
<p>You can only see this from inside the firewall.</p></body></html>
There is one detail that catches people. curl has two spellings. --socks5-hostname sends the name "intranet" to the proxy, which looks it up on the bastion. Plain --socks5 looks the name up on the laptop first, and fails:
$ curl -sS -m3 --socks5 localhost:1080 http://intranet/ ; echo "exit status $?"
curl: (97) Could not resolve host: intranet
exit status 97
So for a name that only exists inside, use --socks5-hostname (or socks5h:// in a URL, or "proxy DNS" in a browser's settings). The same listener is loopback-only by default, like -L. Pointing a browser at it works the same way; that was not run, only curl.
When to choose which: use -L when you need one service and want a plain localhost address for it. Use -D when you need to reach several inside hosts, or you do not know in advance which.
Remote forward: ssh -R
-R is -L turned around. It opens a port on the server and sends what arrives there back through the connection to something on your side:
ssh -R [bind_address:]port:host:hostport server
In the lab, the laptop runs a pretend dev server on port 3000. This puts it on port 9000 of the bastion:
$ ssh -f -N -R 9000:localhost:3000 bastion
$ ssh bastion 'ss -ltn | grep 9000 ; curl -sS -m3 localhost:9000'
LISTEN 0 128 127.0.0.1:9000 0.0.0.0:*
LISTEN 0 128 [::1]:9000 [::]:*
<h1>Dev server on the laptop</h1>
Here "localhost" in the command is resolved on the laptop (the side the connection ends on), and port 9000 is listening on the bastion. People use this to show a development server to a colleague, to receive a webhook on a laptop, or to let a server reach back through a NAT.
By default the new port on the server listens on loopback only, even if you ask for more. With -R 0.0.0.0:9001:localhost:3000 the bastion still listened on 127.0.0.1, and another machine could not connect:
$ ssh -f -N -R 0.0.0.0:9001:localhost:3000 bastion
$ ssh bastion 'ss -ltn | grep 9001 ; curl -sS -m3 http://bastion:9001/ ; echo "exit status $?"'
LISTEN 0 128 127.0.0.1:9001 0.0.0.0:*
LISTEN 0 128 [::1]:9001 [::]:*
curl: (7) Failed to connect to bastion port 9001 after 0 ms: Couldn't connect to server
exit status 7
The server decides this with the GatewayPorts setting, which is "no" by default. Setting it to "yes" or "clientspecified" on the server lets others use the port; that was not run. Leave it as it is unless you have a reason, because it lets anyone on the server's network use a door into your laptop.
Jump hosts: ssh -J
A tunnel is not always what you want. Often you just want a shell on the machine behind the bastion. Before ProxyJump the usual answer was to log in to the bastion and run ssh from there. ProxyJump does it in one command and in one step for your keys:
$ ssh -J bastion intranet 'hostname ; whoami'
intranet
demo
ssh made two connections for you. It logged in to the bastion, asked the bastion to open a connection to port 22 of the intranet host, and then logged in to the intranet host inside that connection. The verbose output shows the two logins and the helper command that ProxyJump uses (an ssh -W, which forwards the standard input and output to a host and port):
$ ssh -v -J bastion intranet true 2>&1 | grep -E 'Connecting to|Executing proxy|Authenticated to'
debug1: Executing proxy command: exec ssh -v -W '[intranet]:22' bastion
debug1: Connecting to bastion [172.27.0.2] port 22.
Authenticated to bastion ([172.27.0.2]:22) using "publickey".
Authenticated to intranet (via proxy) using "publickey".
The important property: the second login is encrypted from your laptop to the intranet host. The bastion carries the bytes and cannot read them. Your private key stays on the laptop, and the bastion never gets anything it could use to log in as you. That is why ProxyJump is the better choice over agent forwarding (see below). Several jump hosts can be listed with commas (-J a,b); that was not run.
The config file
Typing the options every time is slow. Put them in ~/.ssh/config on the laptop. This is the file used in the lab:
$ cat ~/.ssh/config
Host bastion
User demo
Host intranet
User demo
ProxyJump bastion
Now the jump is part of the name:
$ ssh intranet 'hostname ; whoami'
intranet
demo
Other programs that run ssh underneath (scp, sftp, rsync, git) read the same file, so they should go through the bastion in the same way. Only the ssh command itself was run here.
A forward can live in the file too. Adding LocalForward under the bastion's Host block:
$ cat ~/.ssh/config
Host bastion
User demo
LocalForward 8080 intranet:80
Host intranet
User demo
ProxyJump bastion
$ ssh -f -N bastion ; curl -sS -m3 localhost:8080 ; pgrep -a -x ssh
<html><body style="font-family:sans-serif"><h1>Intranet portal</h1>
<p>You can only see this from inside the firewall.</p></body></html>
535 ssh -f -N bastion
LocalForward, RemoteForward and DynamicForward are the config names for -L, -R and -D. The file is read from the top and the first value found for each option is used, so put specific Host blocks before a general "Host *". The file must not be writable by others (chmod 600 is the usual choice), or ssh refuses it with "Bad owner or permissions on <file>" (the lab hit exactly that message once, on a system config file that had the wrong mode).
Agent forwarding: what it does and why to be careful
A second way to log in from the bastion to the intranet host is to let the bastion use your key through your ssh-agent. This is agent forwarding, ssh -A (or ForwardAgent yes). In the lab the bastion has no key, so without it the second hop fails:
$ ssh bastion 'ssh -o BatchMode=yes intranet hostname' ; echo "exit status $?"
demo@intranet: Permission denied (publickey).
exit status 255
With -A the bastion can ask your agent on the laptop to sign for it:
$ eval $(ssh-agent -s) ; ssh-add ~/.ssh/id_ed25519
$ ssh -A bastion 'ssh intranet hostname'
intranet
That works, and it is the reason people like it. It also gives the bastion a socket that leads to your agent for as long as you are connected:
$ ssh -A bastion 'echo SSH_AUTH_SOCK=$SSH_AUTH_SOCK ; ls -l $SSH_AUTH_SOCK'
SSH_AUTH_SOCK=/tmp/ssh-i0bRepfr0H/agent.655
srwxrwxr-x 1 demo demo 0 Nov 16 19:48 /tmp/ssh-i0bRepfr0H/agent.655
The danger is on the bastion. While a session with -A was open, root on the bastion pointed at that socket and could use the key to log in to the intranet host as the user, with no passphrase and no key file:
$ (as root on the bastion) export SSH_AUTH_SOCK=<the socket> ; ssh-add -l ; ssh demo@intranet 'hostname ; whoami'
socket: /tmp/ssh-4YpBv2bVxx/agent.668
256 SHA256:KRMLuSVKuplgqqPmYsW9wRf0hMVzjimdOoksT4dZM9I demo@laptop (ED25519)
Warning: Permanently added 'intranet' (ED25519) to the list of known hosts.
intranet
demo
(The "Permanently added" line is root's first connection from that account.) The bastion is the machine most likely to be attacked, so this is the wrong place to trust. Prefer ProxyJump, which gives the bastion nothing to borrow. The SSH Hardening guide has a section on the agent and forwarding, with ssh-add -t and -c (a time limit and a confirmation for each use), and the server settings that switch agent forwarding off.
Reuse one connection: ControlMaster
Each ssh command normally makes a new TCP connection and a new login, which takes a moment, and for the same server it is the same work every time. Connection sharing keeps one connection open and lets other ssh commands use it. Without it, five logins in the lab took:
$ time (for i in 1 2 3 4 5; do ssh bastion true; done)
1.532 seconds for 5 connections
Add three lines to the Host block:
$ cat ~/.ssh/config
Host bastion
User demo
ControlMaster auto
ControlPath ~/.ssh/cm-%C
ControlPersist 10m
ControlMaster auto uses an existing master if there is one and makes one if not. ControlPath is the socket the commands use to find it (%C is a short hash of the connection, which keeps the name short enough for the socket). ControlPersist 10m keeps the master running for ten minutes after the last user leaves, so the next command is fast even a while later (the ten minutes were not waited out). The same five logins:
$ time (for i in 1 2 3 4 5; do ssh bastion true; done)
0.359 seconds for 5 connections
The first one made the master (0.279 seconds) and each one after that reused it (0.013 seconds):
$ time ssh bastion true ; time ssh bastion true
0.279 seconds
0.013 seconds
Exit request sent.
The master can be asked about and told things with -O:
$ ssh -O check bastion ; ls ~/.ssh | grep cm-
Master running (pid=630)
cm-24338a401ef0a33ab87b7244aad99dbc6f25ab56
It can also add and remove forwards on a connection that is already open, with no new login:
$ ssh -O forward -L 8081:intranet:80 bastion ; echo "exit status $?"
$ curl -sS -m3 localhost:8081
$ ssh -O cancel -L 8081:intranet:80 bastion ; echo "after cancel:"
$ curl -sS -m3 localhost:8081 ; echo "exit status $?"
exit status 0
<html><body style="font-family:sans-serif"><h1>Intranet portal</h1>
<p>You can only see this from inside the firewall.</p></body></html>
after cancel:
curl: (7) Failed to connect to localhost port 8081 after 0 ms: Couldn't connect to server
exit status 7
And ssh -O exit bastion closes the master:
Exit request sent.
0
(The last line, 0, is the number of control sockets left in ~/.ssh.) A shared connection is one connection, so if the network drops, every session on it drops together. Keeping tunnels alive after a drop is a topic for a later part.
What the server can forbid
Everything above is allowed because the lab's sshd allows it, which is the default. An administrator can turn tunnels off or narrow them. The SSH Hardening guide has the full list of settings; here are two, run on the bastion with the setting changed and sshd reloaded.
AllowTcpForwarding no. The forward still opens on the laptop, because the laptop does not know yet. The refusal comes when something uses it:
$ (timeout 6 ssh -N -L 8080:intranet:80 bastion &) ; curl -sS -m3 localhost:8080 ; echo "curl exit status $?"
channel 2: open failed: administratively prohibited: open failed
curl: (56) Recv failure: Connection reset by peer
curl exit status 56
The first line is ssh telling you the bastion refused the connection. The second is curl seeing the connection closed.
AllowTcpForwarding local with PermitOpen intranet:80. Local forwards are allowed, to that one destination only. Port 80 still worked:
$ curl -sS -m3 localhost:8080 | head -2
<html><body style="font-family:sans-serif"><h1>Intranet portal</h1>
<p>You can only see this from inside the firewall.</p></body></html>
A forward to the SSH port of the same host was refused:
$ ssh -N -L 8022:intranet:22 bastion &
$ ssh -p 8022 demo@localhost true ; echo "exit status $?"
channel 2: open failed: administratively prohibited: open failed
Connection closed by ::1 port 8022
exit status 255
And with "local", remote forwards are refused at the start:
$ ssh -o ExitOnForwardFailure=yes -N -R 9002:localhost:3000 bastion ; echo "exit status $?"
Error: remote port forwarding failed for listen port 9002
exit status 255
When your own tunnel stops working, "administratively prohibited" means the server's settings, not your command. The lab's sshd was restored after these runs and the tunnel test was repeated to prove it:
$ curl -sS -m3 localhost:8080 | head -1
<html><body style="font-family:sans-serif"><h1>Intranet portal</h1>
Cheat sheet
ssh -L 8080:intranet:80 bastion port 8080 here -> intranet:80, looked up from the bastion
ssh -L 0.0.0.0:8080:... listen on all addresses (anyone who can reach you can use it)
ssh -D 1080 bastion SOCKS proxy on 1080; use curl --socks5-hostname for inside names
ssh -R 9000:localhost:3000 bastion port 9000 on the server -> your port 3000 (server loopback only)
ssh -J bastion intranet shell on intranet through bastion; prefer over -A
ssh -A bastion agent forwarding: only for hosts you fully trust
ssh -f -N ... background, no remote command: tunnel only
ssh -o ExitOnForwardFailure=yes ... fail loudly if the forward cannot be opened
ssh -O check|forward|cancel|exit host talk to a ControlMaster
Config names: LocalForward, RemoteForward, DynamicForward, ProxyJump, ControlMaster, ControlPath, ControlPersist.
Stop a background tunnel: pkill -x ssh (all of them) or kill <pid> from pgrep -a -x ssh.
What was not run in the lab
Only OpenSSH 9.6p1 on Ubuntu 24.04 in Docker containers was used. Windows, macOS and the other client programs (PuTTY, Dropbear and so on) were not run. A real firewall was not used; the Docker internal networks stood in for it.
Not run: ssh -w (tun/tap devices, a VPN-like tunnel), several jump hosts in one -J, ProxyCommand and nc, GatewayPorts set to yes or clientspecified, a browser pointed at the SOCKS port, Unix-socket forwards (the path form of -L and -R), X11 forwarding, keepalive options and tunnels that survive a network drop, autossh, Match blocks in sshd_config, and sshd -T to inspect the settings. The ControlPersist timeout was not waited out. Only ed25519 keys without a passphrase were used, which is not how to hold a real key.
Common problems and tips
The page does not load through -L. Check the host:port from the bastion's side: ssh bastion 'curl host:port'. "localhost" in the middle means the bastion.
bind: Address already in use. A tunnel is already running on that local port (pgrep -a -x ssh), or another program has it. Pick another port, or kill the old tunnel. Add -o ExitOnForwardFailure=yes in scripts.
Could not resolve host with --socks5. Use --socks5-hostname (or socks5h://), so the bastion does the lookup.
channel N: open failed: administratively prohibited. The server forbids it (AllowTcpForwarding or PermitOpen). Ask the administrator, or use a different route.
The -R port is not reachable from other machines. It is bound to the server's loopback; that is the default and a safe one.
Permission denied on the second hop. The bastion has no key. Use ProxyJump, or if you must, agent forwarding for that host only.
A tunnel dies when the network drops. Plain ssh does not reconnect; a later part covers that.
Tips. Prefer ProxyJump over -A. Put hosts and forwards in ~/.ssh/config. Use ExitOnForwardFailure in scripts. Use pkill -x ssh, not pkill -f. Keep forwards on loopback unless you know why not. Keep OpenSSH patched: the SSHole advisory on this site is the latest reminder.
Next in the series: sshfs, tunnels that stay up, and certificates.