Search code examples
sshopensshsystem-administration

ClientAliveInterval is not closing the idle connection


I have the task to close the idle ssh connection if they are idle for more than 5 minutes. I have tried setting these value on sshd_config

TCPKeepAlive no
ClientAliveInterval 300
ClientAliveCountMax 0

But nothing seems to work the idle remains active and does not get lost even after 5 minutes of idle time.

Then I came across this https://bbs.archlinux.org/viewtopic.php?id=254707 they guys says

These are not for user-idle circumstances, they are - as that man page excerpt notes - for unresponsive SSH clients. The client will be unresponsive if the client program has frozen or the connection has been broken. The client should not be unresponsive simply because the human user has stepped away from the keyboard: the ssh client will still receive packets sent from the server.

I can't even use TMOUT because there are ssh client scripts that do not run bash program.

How to achieve this?

Openssh version OpenSSH_8.2p1 Ubuntu-4ubuntu0.4, OpenSSL 1.1.1f 31 Mar 2020


Solution

  • close the idle ssh connection if they are idle for more than 5 minutes

    This task is surprisingly difficult. OpenSSH itself has no functionality to set a idle-timeout on shell commands, probably for a good reason: killing "idle" shells itself is non-trivial:

    • There's multiple ways to define "idleness", e.g., no stdin, no stdout, no I/O activity whatsoever, no CPU consumption etc
    • Even when a process is deemed "idle", it's difficult to kill the process and all its child processes that have possibly been created.

    Given that, it's not surprising that there's only few solutions for killing idle shell sessions in general. Those that I could find with (little) research rely on background daemons that check the idle status of all processes running on a system (e.g., doinkd/idled, idleout).

    One possible solution is to check if any of those solutions can be adapted to enforce an idle timeout on a specific shell session.

    Another option is to adapt the OpenSSH source code to support your specific requirement. In principle, OpenSSH should be able to easily access console I/O activity and session duration, so assessing the "idle" property is probably relative easy. As for "killing" the shell and all involved children, running (and killing) the remote shell in a PID namespace is an effective option on Linux systems.

    Both options a relatively complex -- so before pursuing them further, I'd further check if there's existing solutions to enforce an idle timeout on a shell session. Using them under OpenSSH will be straightforward.