20.6. Tunnels and Remote Diagnostics

An SSH connection can carry more than sessions and files: it can listen on one side and reach somewhere else on the other. Local (-L), remote (-R), and dynamic (-D) forwarding are three answers to the same question - who listens, and from which end is the destination reached? - and Section 20.6.2 covers who is allowed to use them. The section closes with the diagnostic side of SSH: what connection failures, authentication refusals, and host-key warnings mean, and what to do about each.

Local, remote, and dynamic SSH forwarding

Figure 20.3. The three forwarding forms. In each, the SSH session itself is the tunnel; the difference is which end holds the listener and which end opens the connection toward the target.

20.6.1. Local, Remote, and Dynamic Port Forwarding

Local forwarding. The client listens locally and the far end connects onward:

$ ssh -N -L 127.0.0.1:10022:192.168.221.20:22 sshjump

-N opens no session - the connection exists purely to forward - and the command normally prints nothing while it runs; the terminal stays occupied by it, so give it a window of its own and stop it later with Ctrl+C. The -L argument is bind_address:port:target:target_port: sshadmin listens on 127.0.0.1:10022, and anything connecting there is carried to sshjump, which opens a connection to 192.168.221.20:22. The target is named from the far end's perspective - an address sshjump can reach even though sshadmin cannot. Confirm the listener, on sshadmin:

$ ss -ltnp | grep :10022
LISTEN 0      128        127.0.0.1:10022      0.0.0.0:*    users:(("ssh",pid=24557,fd=4))

Now sshadmin has a local port that is really sshserver's SSH service:

$ ssh -p 10022 -o HostKeyAlias=sshserver john@127.0.0.1 hostname
sshserver

The server at the end of the tunnel presented sshserver's host key. HostKeyAlias tells the client to check it against the sshserver record rather than treating 127.0.0.1 as a new host - and the check fails closed if the tunnel ever points somewhere else, because the wrong server presents the wrong key.

Remote forwarding. The same mechanism, launched from the other side: the SSH server holds the listener, and connections to it travel back to be opened from the client end. First give the tunnel something to reach - a small web server on sshadmin, bound to loopback, serving a page from the workspace:

$ mkdir -p ~/debian-handbook/ssh/web
$ printf "remote forwarding works\n" > ~/debian-handbook/ssh/web/index.html

Both write silently. Now run python3 -m http.server 8000 --bind 127.0.0.1 --directory ~/debian-handbook/ssh/web in this terminal: it prints its listening address, then serves until stopped with Ctrl+C. Confirm it from a second look at the sockets:

$ ss -ltnp | grep :8000
LISTEN 0      5          127.0.0.1:8000      0.0.0.0:*    users:(("python3",pid=24614,fd=3))

Open the reverse tunnel in its own terminal - it, too, prints nothing while it runs:

$ ssh -N -R 127.0.0.1:10080:127.0.0.1:8000 sshserver

sshserver now listens on 127.0.0.1:10080, and connections to it appear at 127.0.0.1:8000 on sshadmin. Read the page from the server side, on sshserver as john:

$ curl http://127.0.0.1:10080/
remote forwarding works

And see the listener the tunnel left there:

$ ss -ltn | grep 10080
LISTEN 0      128        127.0.0.1:10080      0.0.0.0:*

Note the bind address: loopback. A request from sshjump toward 192.168.221.20:10080 gets nothing: no listener answers on the external address, and curl exits with its connection-failed status (7). Remote forwards bind loopback on the server by default; GatewayPorts (Section 20.6.2) is what would widen them.

Dynamic forwarding. Instead of one fixed target, -D turns the client into a SOCKS proxy whose connections are each opened from the far end. Set up a destination first, on sshserver as john - this one binds all interfaces deliberately, so it is reachable from the jump:

$ mkdir -p ~/debian-handbook/ssh/www
$ printf "dynamic forwarding works\n" > ~/debian-handbook/ssh/www/index.html

The writes are silent. Run python3 -m http.server 8080 --bind 0.0.0.0 --directory ~/debian-handbook/ssh/www in this terminal as the target server - it prints its listening address and serves until Ctrl+C. Verify the bind:

$ ss -ltnp | grep :8080
LISTEN 0      5            0.0.0.0:8080       0.0.0.0:*    users:(("python3",pid=16725,fd=3))

Open the SOCKS tunnel on sshadmin, again in its own terminal and again silent while it runs:

$ ssh -N -D 127.0.0.1:1080 sshjump
$ ss -ltnp | grep :1080
LISTEN 0      128        127.0.0.1:1080      0.0.0.0:*    users:(("ssh",pid=24655,fd=4))

A SOCKS-aware client can now reach internal-network addresses through sshjump:

$ curl --socks5-hostname 127.0.0.1:1080 http://192.168.221.20:8080/
dynamic forwarding works

--socks5-hostname sends the destination name through the proxy too, so DNS resolves at the far end; --socks5 would resolve it locally and send an address instead. Browsers and most HTTP tools take a SOCKS proxy directly, which makes -D the quick way to reach a network through a single relay. It is still per-application TCP forwarding, not a VPN: for full-tunnel needs, use Section 19.5's WireGuard instead.

Everything in this section cleans up with Ctrl+C in each tunnel's and server's own terminal, and the practice files live under ~/debian-handbook/ssh on the two hosts.

20.6.2. Binding Addresses and Limiting Forwarding Privileges

The examples so far bound 127.0.0.1 deliberately. The bind address decides who may use a forward. Bind all interfaces instead - like the other tunnel forms, it prints nothing while it runs:

$ ssh -N -L 0.0.0.0:10024:192.168.221.20:22 sshjump
$ ss -ltnp | grep :10024
LISTEN 0      128          0.0.0.0:10024      0.0.0.0:*    users:(("ssh",pid=24747,fd=4))

Now other hosts can reach it, which sshjump confirms, as john there:

$ nc -z -w 2 192.168.220.10 10024 && echo reachable
Connection to 192.168.220.10 10024 port [tcp/*] succeeded!
reachable

nc -z makes the TCP connection and closes it - a port probe - and && runs the echo only because it succeeded. Two facts to weigh before choosing a bind: a non-loopback bind exposes the forward to every host that can reach it (pair it with a firewall rule, Chapter 18), and a loopback bind is still reachable by every local user of the listening host, not just the one who opened it. For remote forwards, the server-side bind follows GatewayPorts: no (the default) forces the listener onto loopback, which is why the 127.0.0.1:10080 form above stayed private; clientspecified lets the client request another bind address; yes binds all interfaces.

The server can also decide, per configuration or per key, that forwarding happens at all. Two variants of the practice instance's configuration - first, forwarding denied outright:

# /etc/ssh/sshd_config.ch20 (on sshserver) - forwarding denied
Port 2222
AddressFamily inet
ListenAddress 0.0.0.0
HostKey /etc/ssh/ssh_host_ed25519_key
PidFile /run/sshd-ch20.pid
LogLevel VERBOSE
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
AuthenticationMethods publickey
AllowUsers john
AuthorizedKeysFile none
TrustedUserCAKeys /etc/ssh/ch20_user_ca.pub
AllowTcpForwarding no
Subsystem sftp internal-sftp

Install it (replace the file's contents), validate, and reload - on sshserver in the root shell, each step silent, exactly as Section 20.4.2 prescribes:

# /usr/sbin/sshd -t -f /etc/ssh/sshd_config.ch20
# kill -HUP "$(cat /run/sshd-ch20.pid)"

Then ask the instance to relay - from sshadmin, with -W - stdio forwarding, the same primitive ProxyJump uses:

$ ssh -p 2222 -W 192.168.221.20:22 sshserver
channel 0: open failed: administratively prohibited: open failed
stdio forwarding failed

The refusal came from the server: AllowTcpForwarding no blocks every forwarding form - -L, -R, -D, and -W alike. Now the narrower version: forwarding allowed, but only toward one destination and port:

# /etc/ssh/sshd_config.ch20 (on sshserver) - one destination permitted
Port 2222
AddressFamily inet
ListenAddress 0.0.0.0
HostKey /etc/ssh/ssh_host_ed25519_key
PidFile /run/sshd-ch20.pid
LogLevel VERBOSE
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
AuthenticationMethods publickey
AllowUsers john
AuthorizedKeysFile none
TrustedUserCAKeys /etc/ssh/ch20_user_ca.pub
AllowTcpForwarding yes
PermitOpen 192.168.221.20:22
Subsystem sftp internal-sftp

Same procedure on sshserver - install, validate, reload, all silent - then from sshadmin the permitted target works and shows the destination's raw SSH banner:

$ ssh -p 2222 -W 192.168.221.20:22 sshserver
SSH-2.0-OpenSSH_10.0p2 Debian-7+deb13u4

The command relays the destination's protocol and stays attached; interrupt it with Ctrl+C after reading the banner. The disallowed target is prohibited:

$ ssh -p 2222 -W 192.168.221.20:8080 sshserver
channel 0: open failed: administratively prohibited: open failed
stdio forwarding failed
Directive Constrains
AllowTcpForwarding Whether this account may forward at all (yes, no, local for -L/-D only, remote for -R only).
PermitOpen host:port The destinations -L/-D may reach; put several on one line, separated by whitespace (any or none reset the list).
PermitListen The bind addresses -R may create on the server.
DisableForwarding One switch for TCP, Unix-socket, agent, and X11 forwarding together.

These are account-level rules; the same limits exist per key - restrict on an authorized_keys line (Section 20.4.3) and the no-port-forwarding certificate extension - so an automation key can be narrow even on a host that forwards for humans.

20.6.3. Debugging Authentication, Host Key Changes, and Connection Failures

SSH failures come in three layers, and the error strings identify which layer to investigate.

The connection layer. A refused port:

$ ssh -p 2299 -o ConnectTimeout=3 john@192.168.220.30 true
ssh: connect to host 192.168.220.30 port 2299: Connection refused

Something on the path answered and said no - a wrong port, a service down, or a router that cannot deliver the packet any further, as the administration gateway did for the direct attempt in Section 20.5.2. Connection timed out instead means packets vanish - usually a firewall drop (Chapter 18); No route to host and Network is unreachable mean the path itself is missing. The reachability toolkit for separating those is Section 17.7's; -o ConnectTimeout just bounds the wait.

The authentication layer. A key the server will not take. Create one and offer only it:

$ ssh-keygen -t ed25519 -C "john@wrong" -f ~/.ssh/id_ed25519_wrong
Generating public/private ed25519 key pair.
Your identification has been saved in /home/john/.ssh/id_ed25519_wrong
Your public key has been saved in /home/john/.ssh/id_ed25519_wrong.pub
The key fingerprint is:
SHA256:HwTBYOm3UTgmmL1BK0uMy6xVoRbTKYoNI/QfhAdZzk0 john@wrong
The key's randomart image is:
+--[ED25519 256]--+
|..oo*O+Eoo       |
|+ oOO+B.=..      |
|o=+o*=.* o       |
|o+.+.o+ o        |
|  = .. .So       |
| o      .. .     |
|.         .      |
|                 |
|                 |
+----[SHA256]-----+
$ ssh -p 2222 -i ~/.ssh/id_ed25519_wrong -o IdentitiesOnly=yes -o IdentityAgent=none -o ControlMaster=no -o ControlPath=none -o BatchMode=yes sshserver true
john@192.168.221.20: Permission denied (publickey).

The options each remove a way for the test to succeed by accident: IdentitiesOnly and IdentityAgent=none keep the agent's working keys out of the offer, BatchMode prevents a passphrase prompt for the protected key, and ControlMaster=no refuses a cached multiplexed session (Section 20.5.1). The refusal itself names the method list the server would accept - here only publickey. When the reason is not obvious, raise verbosity and read which identities were offered and which the server kept allowing; the Section 20.3.3 excerpt shows the shape:

ssh option Description
-v / -vv / -vvv Progressive debug output: connection, key exchange, authentication detail.
-o ConnectTimeout=seconds Give up on an unresponsive TCP connect instead of waiting out the kernel default.
-o BatchMode=yes Never prompt - fail instead; the honest mode for scripted probes.

On the server side, sshd records its reasons - accepted and refused authentications, forced-command runs, revocation hits - in the system log; read it through the journal as Section 8.4 describes, and in /var/log/auth.log on systems running rsyslog. The client's terse Permission denied is almost always explained by one line there.

The host-key layer. The one warning that must never be dismissed. To meet it safely, give the practice setup a second identity: a third instance, on port 2226, presenting a freshly generated host key - exactly what a reinstalled or rotated server looks like to an old client record. Its configuration:

# /etc/ssh/sshd_config.ch20alt (on sshserver)
Port 2226
AddressFamily inet
ListenAddress 0.0.0.0
HostKey /etc/ssh/ssh_host_ed25519_key_ch20alt
PidFile /run/sshd-ch20alt.pid
LogLevel VERBOSE
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
AllowUsers john
AuthorizedKeysFile none
TrustedUserCAKeys /etc/ssh/ch20_user_ca.pub
Subsystem sftp internal-sftp

Generate the alternate host key - silent with -q - and start the instance, which is also silent, then confirm the listener, on sshserver in the root shell:

# ssh-keygen -q -t ed25519 -N "" -C "alternate host key" -f /etc/ssh/ssh_host_ed25519_key_ch20alt
# /usr/sbin/sshd -f /etc/ssh/sshd_config.ch20alt
# ss -ltnp | grep :2226
LISTEN 0      128          0.0.0.0:2226      0.0.0.0:*    users:(("sshd",pid=16897,fd=6))

Give the client a known-hosts file that still records the original key for that port - the practice records from earlier, under a workspace path:

# ~/debian-handbook/ssh/known_hosts.changed (on sshadmin)
192.168.220.30 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFDj61pe37pck4oCCdxzhvQpI5SRdHMxXUmRF9OKRZMl root@trixie
[192.168.221.20]:2226 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOPGaRkc4eDwxSjbhkH5HfUlxgQ0G4SAur/TuoT3cnE8 root@trixie

Then connect:

$ ssh -p 2226 -o UserKnownHostsFile=~/debian-handbook/ssh/known_hosts.changed -o StrictHostKeyChecking=yes sshserver true
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ED25519 key sent by the remote host is
SHA256:/r9KCsl4VsIFUdzK2uqgZzkPZso8O4XK5usJclLF8a0.
Please contact your system administrator.
Add correct host key in /home/john/debian-handbook/ssh/known_hosts.changed to get rid of this message.
Offending ED25519 key in /home/john/debian-handbook/ssh/known_hosts.changed:2
  remove with:
  ssh-keygen -f '/home/john/debian-handbook/ssh/known_hosts.changed' -R '[192.168.221.20]:2226'
Host key for [192.168.221.20]:2226 has changed and you have requested strict checking.
Host key verification failed.

Read it as a procedure, not an obstacle. The new key's fingerprint is printed - compare it against what the server's administrator or provisioning records say should be there now. A legitimate change (reinstallation, key rotation, a restored image) is verifiable out of band, exactly as the first connection in Section 20.1.3 was. Only after that verification does the removal happen: ssh-keygen -R (the command the warning itself suggests) deletes the stale record, and the next connection is a first connection again - verify the fingerprint at the prompt, accept, and the new record stands in for the old one. A changed key with no explanation behind it is a compromise signal, and the response belongs to Chapter 26, not to a -R flag. What the warning never justifies is disabling the check. Give the same exercise a destination with no record at all - a second scratch file holding only the jump's line:

# ~/debian-handbook/ssh/known_hosts.unknown (on sshadmin)
192.168.220.30 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFDj61pe37pck4oCCdxzhvQpI5SRdHMxXUmRF9OKRZMl root@trixie

The unknown-host refusal behaves the same way and says so plainly:

$ ssh -p 2226 -o UserKnownHostsFile=~/debian-handbook/ssh/known_hosts.unknown -o StrictHostKeyChecking=yes sshserver true
No ED25519 host key is known for [192.168.221.20]:2226 and you have requested strict checking.
Host key verification failed.

The destination failed first-contact verification - the same refusal as Section 20.1.3, seen here from the diagnostic side.

This chapter ends where the rest of the book picks up: every later service chapter assumes this one works. File sharing that behaves like a filesystem is Chapter 21; automated administration over these same connections - Ansible, provisioning, and the client configurations they reuse - is Chapter 27; and the identity scale-out that replaces per-host accounts entirely is Chapter 35. The practice instances and files this chapter created are disposable: stop the instances by the PIDs recorded in their pid files under /run on sshserver, and the workspace holds nothing but the exercise artifacts.