Strovent SystemsSign in
Reference

Keep an SSH tunnel running: autossh, ServerAliveInterval and systemd

A tunnel stays up when ssh exits as soon as the link dies and something restarts it. Use ServerAliveInterval, ExitOnForwardFailure, and autossh or systemd.

An SSH tunnel is an ordinary ssh process. When the network drops, it either exits or, worse, hangs on a connection that no longer works. Nothing brings it back on its own. A tunnel that keeps running needs two things:

  • ssh must notice a dead connection and exit, instead of waiting forever.
  • Something must start it again after it exits.

Make ssh exit when the tunnel is broken

Put the tunnel in ~/.ssh/config on the machine that starts it:

Host tunnel-db
  HostName host.example.com
  User user1
  LocalForward 5432 localhost:5432
  ServerAliveInterval 30
  ServerAliveCountMax 3
  ExitOnForwardFailure yes
  BatchMode yes

What each line does:

  • ServerAliveInterval 30 and ServerAliveCountMax 3: if nothing arrives from the server for 30 seconds, ssh sends a check through the encrypted channel. After 3 unanswered checks it disconnects, so a dead link ends the process after about 90 seconds. The interval defaults to 0, which turns the checks off. See SSH keep-alives and idle timeouts.
  • ExitOnForwardFailure yes: if a forward cannot be set up, for example because its port is taken, ssh exits instead of staying connected without it. See SSH "remote port forwarding failed for listen port".
  • BatchMode yes: no password or host-key prompts. An unattended tunnel cannot answer them, so it needs key login with a key that does not ask for a passphrase, or an agent that already holds the key. Connect once by hand first, so the host key is saved.

Start it without a remote shell:

ssh -N tunnel-db

-N runs no remote command, which is what you want for a tunnel that only forwards ports. When something goes wrong, ssh exits with status 255.

Restart it with autossh

autossh starts ssh for you and starts it again when it dies:

autossh -M 0 -N tunnel-db

-M 0 turns off autossh's own monitoring connection. autossh then restarts ssh only when ssh exits, and the server alive checks above make sure it exits when the link is dead. The autossh manual suggests this combination with a recent OpenSSH. Without -M 0, autossh sends test data around a pair of extra forwarded ports (the given port and the next one), and nothing else may use those ports.

Behaviour worth knowing:

  • If ssh fails with exit status 1 on the very first try, or fails within the first 30 seconds, autossh assumes the setup is wrong and gives up rather than retrying. The time is set with the AUTOSSH_GATETIME environment variable. AUTOSSH_GATETIME=0 turns this off, so autossh keeps retrying even when the first attempt fails.
  • After repeated quick failures, autossh waits longer and longer between attempts, up to its poll time (10 minutes by default). Send it SIGHUP to make it retry now.
  • autossh -f runs it in the background. Then ssh cannot ask for passwords or passphrases, and the starting-gate time is 0.
  • To stop it, send SIGTERM to the autossh process (for example pkill -x autossh). autossh then ends its ssh too. Killing only the ssh process just makes autossh start a new one.
  • If ssh exits normally, for example because someone typed exit in an interactive session, autossh exits too.

Or let systemd restart it

On a Linux machine with systemd you do not need autossh. A service unit restarts plain ssh when it exits. Save this as /etc/systemd/system/tunnel-db.service:

[Unit]
Description=SSH tunnel to host.example.com
After=network-online.target
Wants=network-online.target

[Service]
User=user1
ExecStart=/usr/bin/ssh -N tunnel-db
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

Then run sudo systemctl daemon-reload and sudo systemctl enable --now tunnel-db.

  • Restart=on-failure restarts the service when the process exits with an error, which includes the 255 that ssh returns. The systemd manual recommends on-failure for long-running services.
  • RestartSec=10 waits 10 seconds between attempts. The default is 100 ms, which can hit systemd's start rate limit (StartLimitIntervalSec and StartLimitBurst) during a long outage, after which systemd stops trying.
  • After= and Wants=network-online.target delay the first start until the network is up.
  • User=user1 runs ssh as that user, so it reads ~user1/.ssh/config and that user's key.

Check it with systemctl status tunnel-db and journalctl -u tunnel-db.

When the remote end keeps the old port

A reverse tunnel (RemoteForward or ssh -R) that reconnects quickly can be refused because the server still holds the port for the dead session. The server frees it when it notices the old session is gone. Setting ClientAliveInterval on the server shortens that wait. See SSH "remote port forwarding failed for listen port".

Sources

Spotted a mistake? Email [email protected].