SSH keep-alives and idle timeouts
What ServerAliveInterval, ClientAliveInterval and TCPKeepAlive do, which side each one belongs on, and why an SSH session can still drop.
OpenSSH has two separate keep-alive mechanisms. They detect a dead connection. They cannot bring a dropped one back. To restart a tunnel after a drop, see Keep an SSH tunnel running: autossh, ServerAliveInterval and systemd.
The two mechanisms
SSH alive messages are sent inside the encrypted SSH channel.
- The client sends them with
ServerAliveIntervalandServerAliveCountMax(ssh_config). - The server sends them with
ClientAliveIntervalandClientAliveCountMax(sshd_config).
If no data has arrived for the interval, one side sends a message and expects an answer. If the other side does not answer after CountMax messages in a row, the sender closes the session. The interval defaults to 0, which means no messages are sent. The count defaults to 3.
TCP keep-alive is TCPKeepAlive, set on either side. It asks the operating system to send TCP probes. The default is on (transport). OpenSSH documents two drawbacks: the probes can be spoofed, and a short network interruption can end the connection.
Examples
# client: ~/.ssh/config
Host *
ServerAliveInterval 15
ServerAliveCountMax 3
With these values, if the server stops answering, ssh disconnects after about 45 seconds (3 × 15).
# server: /etc/ssh/sshd_config
ClientAliveInterval 15
ClientAliveCountMax 3
The same numbers on the server drop an unresponsive client after about 45 seconds. A ClientAliveCountMax of 0 turns off the disconnect.
Only the server's administrator can change sshd_config. The client setting works with any server.
What these settings do not do
- They do not stop a firewall or phone network from ending the connection. If the link is cut, the session cannot continue, and keep-alives only end it sooner.
- A short interval makes the session end sooner on a poor link, because the count runs out faster.
- They cannot restore a session. To keep work running through a drop, run the program inside
tmuxon the host (see Shell and tmux basics) or use Mosh, which survives network changes (see Mosh or SSH?). To close a session that has already frozen, see Kill a frozen SSH session with Enter ~. (OpenSSH escape sequences).
Phones and tablets
Apps do not read ~/.ssh/config. See The ssh config file for how the same options map to profile screens in apps that offer them. Phones can also pause an app in the background. See Background sessions for what this app does with SSH sessions then. For what this app sends while a session is idle, see Why a session disconnects when it sits idle.
Related
- The ssh config file
- SSH: how it works
- SSH problems
- Why a session disconnects when it sits idle
- Why did my session disconnect?
- SSH ControlMaster: reuse one connection with ControlPath and ControlPersist
- Kill a frozen SSH session with Enter ~. (OpenSSH escape sequences)
- Keep an SSH tunnel running: autossh, ServerAliveInterval and systemd