2

We are currently using SSH for our project, and we need to implement a feature where SSH users are logged off after 1 minute of inactivity. Below are excerpts from our ssh_config and sshd_config files:

ssh_config


# This is the ssh client system-wide configuration file.  See
# ssh_config(5) for more information.  This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
#  1. command line options
#  2. user-specific file
#  3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options.  For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

Host *
  ForwardAgent yes
  ForwardX11 yes
#   RhostsRSAAuthentication no
#   RSAAuthentication yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
#   StrictHostKeyChecking ask
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   IdentityFile ~/.ssh/id_ecdsa
#   IdentityFile ~/.ssh/id_ed25519
#   Port 22
#   Protocol 2
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,[email protected]
#   EscapeChar ~
#   Tunnel no
#   TunnelDevice any:any
#   PermitLocalCommand no
#   VisualHostKey no
#   ProxyCommand ssh -q -W %h:%p gateway.example.com
#   RekeyLimit 1G 1h
StrictHostKeyChecking no
UserKnownHostsFile /dev/null

sshd_conf


# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile      .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes
#PermitEmptyPasswords no
# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#PermitUserEnvironment no
Compression no
ClientAliveInterval 15
ClientAliveCountMax 4
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem       sftp    /usr/libexec/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

sshd_config_readonly


# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::


# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile      .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#PermitUserEnvironment no
Compression no
ClientAliveInterval 1m
ClientAliveCountMax 0
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem       sftp    /usr/libexec/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server
HostKey /var/run/ssh/ssh_host_rsa_key
HostKey /var/run/ssh/ssh_host_ecdsa_key
HostKey /var/run/ssh/ssh_host_ed25519_key

Below are the things i have changed in sshd_config file

ClientAliveInterval 1m
ClientAliveCountMax 0

After setting ClientAliveInterval to 1 minute and ClientAliveCountMax to 0, we expected users to be logged off after 1 minute of inactivity. However, we are facing an issue where users are unable to log off.

Here is the output for sshd -T && echo OK

addressfamily any
listenaddress [::]:22
listenaddress 0.0.0.0:22
usepam yes
logingracetime 120
x11displayoffset 10
maxauthtries 6
maxsessions 10
clientaliveinterval 0
clientalivecountmax 3
streamlocalbindmask 0177
permitrootlogin yes
ignorerhosts yes
ignoreuserknownhosts no
hostbasedauthentication no
hostbasedusesnamefrompacketonly no
pubkeyauthentication yes
passwordauthentication yes
kbdinteractiveauthentication no
challengeresponseauthentication no
printmotd yes
printlastlog yes
x11forwarding no
x11uselocalhost yes
permittty yes
permituserrc yes
strictmodes yes
tcpkeepalive yes
permitemptypasswords no
compression no
gatewayports no
usedns no
allowtcpforwarding yes
allowagentforwarding yes
disableforwarding no
allowstreamlocalforwarding yes
streamlocalbindunlink no
fingerprinthash SHA256
exposeauthinfo no
pidfile /var/run/sshd.pid
xauthlocation /usr/bin/xauth
ciphers [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
macs [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
banner none
forcecommand none
chrootdirectory none
trustedusercakeys none
revokedkeys none
securitykeyprovider internal
authorizedprincipalsfile none
versionaddendum none
authorizedkeyscommand none
authorizedkeyscommanduser none
authorizedprincipalscommand none
authorizedprincipalscommanduser none
hostkeyagent none
kexalgorithms curve25519-sha256,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256
casignaturealgorithms ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],ssh-ed25519,[email protected],rsa-sha2-512,rsa-sha2-256
hostbasedacceptedkeytypes [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],ssh-ed25519,[email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa
hostkeyalgorithms [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],ssh-ed25519,[email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa
pubkeyacceptedkeytypes [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],ssh-ed25519,[email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa
rdomain none
loglevel VERBOSE
syslogfacility AUTH
authorizedkeysfile .ssh/authorized_keys
hostkey /etc/ssh/ssh_host_rsa_key
hostkey /etc/ssh/ssh_host_ecdsa_key
hostkey /etc/ssh/ssh_host_ed25519_key
setenv TMOUT=60
authenticationmethods any
subsystem sftp /usr/libexec/sftp-server
maxstartups 10:30:100
permittunnel no
ipqos af21 cs1
rekeylimit 0 0
permitopen any
permitlisten any
permituserenvironment no
pubkeyauthoptions none
OK

Any insights or suggestions on what might be causing this problem would be greatly appreciated.

Thank you!

3
  • 1
    As Kamil pointed out in his answer (why the downvotes, btw?) that's not what those values are there for. You may want to look at BASH's TMOUT and set that globally from one of bash's /etc files ... Commented Jan 22, 2024 at 17:16
  • Does the inverse of How to keep idle session from exiting answer your question? Commented Jan 22, 2024 at 19:40
  • @tink my default shell is /bin/sh Commented Jan 24, 2024 at 2:05

2 Answers 2

3

ClientAlive* are not designed to terminate healthy connections. It's a myth they are. Please read this other answer of mine to learn what the options are really for. In a nutshell, they are for:

  • allowing the SSH server to detect when a client silently disappears from the network;
  • renewing a healthy connection that is otherwise idle, so network nodes between the server and the client do not discard it because of the idleness.

The options you need are ChannelTimeout and UnusedConnectionTimeout. They are designed to detect inactivity (as opposed to disappearance of the client detected by ClientAlive*).

ChannelTimeout
Specifies whether and how quickly sshd(8) should close inactive channels. Timeouts are specified as one or more type=interval pairs separated by whitespace, where the type must be the special keyword global or a channel type name from the list below, optionally containing wildcard characters.

(source)

UnusedConnectionTimeout
Specifies whether and how quickly sshd(8) should close client connections with no open channels. […]

Note that this timeout starts when the client connection completes user authentication but before the client has an opportunity to open any channels. Caution should be used when using short timeout values, as they may not provide sufficient time for the client to request and open its channels before terminating the connection.

(source)

This is an example setup (in /etc/ssh/sshd_config):

ChannelTimeout *=1m
UnusedConnectionTimeout 1m

Notes:

  • The options work server-side (in sshd_config on the server), but there is also ChannelTimeout for the client side (e.g. in ~/.ssh/config on the client machine). Each end (sshd or ssh) may monitor the channels and close them according to its own settings.

  • ChannelTimeout *=1m is not equivalent to ChannelTimeout global=1m.

  • The client may easily generate artificial activity (e.g. in an interactive shell session the user can run watch date or so).

  • If the server terminates the last channel due to ChannelTimeout, usually the client will terminate the whole connection by itself, so UnusedConnectionTimeout is not that relevant. Some options of the client (e.g. ControlPersist) may cause the client to want to keep the connection even without channels and then UnusedConnectionTimeout will be relevant.

  • The packets generated by ClientAlive* do not belong to any channel, so they will not reset the timeouts. This means you can use ChannelTimeout+UnusedConnectionTimeout for what you want to do and simultaneously you can use ClientAlive* for what it was designed for. (Note that setting ClientAliveCountMax to zero (like you did) disables the functionality.)

  • ChannelTimeout and UnusedConnectionTimeout are relatively new inventions (OpenSSH 9.2, 2023-02-02). Online resources that predate these options try to achieve similar results with other means, some of them use ClientAlive* and spread the myth.

  • In general you may also find StopIdleSessionSec= in /etc/systemd/logind.conf useful. It's not specific to SSH, it's specific to the systemd login manager. See man 5 logind.conf.

8
  • Thanks for the quick reply , but when we include ChannelTimeout *=1m UnusedConnectionTimeout 1m The ssh simply refuses our connection by giving ssh_exchange_identification: Connection closed by remote host Commented Jan 23, 2024 at 9:09
  • @karkator On the server, does sudo sshd -T && echo OK print OK at the end? If not, what exactly does it print? Commented Jan 23, 2024 at 10:57
  • if i give ssh -v on linux to establish a ssh connection on the host i am getting debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.10 ssh_exchange_identification: read: Connection reset by peer and output for sshd -T && echo OK is /etc/ssh/sshd_config: line 119: Bad configuration option: ChannelTimeout /etc/ssh/sshd_config: line 120: Bad configuration option: UnusedConnectionTimeout /etc/ssh/sshd_config: terminating, 2 bad configuration options Commented Jan 24, 2024 at 1:45
  • I have also given output for sshd -T && echo OK in the question , please review it ! Commented Jan 24, 2024 at 2:07
  • @karkator Sigh… You are using OpenSSH_7.2p2. My answer clearly states the relevant options are "relatively new inventions (OpenSSH 9.2, 2023-02-02)". You need 9.2 or later, you have 7.2. Your sshd does not know these options at all. This is why you got Bad configuration option for each. Commented Jan 24, 2024 at 5:00
0

Assuming your users have bash shells, add to your sshd_config:

SetEnv TMOUT=60

This will terminate interactive shells after one minute of inactivity at the prompt.

It's just an environment variable, so users can adjust their own timeout value. One minute is pretty harsh though, certainly with password logins. Of course,

sleep 300

works great to find your terminal still alive after going for a coffee, but is unworkable for many common use cases, such as users working in multiple screens.

Unless you're expecting seriously many concurrent idle users (and why?) I'd think about usability first. Is the 1mn logout really needed and not intended to pester users?

2
  • Hi @zwets my default shell is /bin/sh , we have tried SetEnv TMOUT=60 but it does not work , I have edited my question again by giving output of sshd -T && echo OK please review it. Commented Jan 24, 2024 at 2:00
  • @karkator the TMOUT variable is a feature of bash, and not present in e.g. dash. You can set a user's shell with the chsh ccommand. chsh -s /bin/bash would do this for your own account. Commented Jan 24, 2024 at 9:23

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.