CentOS / RHEL : How to restrict SSH login by time of day

Question:

How to enforce a policy that allows new ssh logins at perticular time of the day only. Outside these access windows no new ssh logins are to be permitted.

Solution :

PAM Resource Description

Login times can be controlled using the Linux Plugin Authentication Method (PAM) pam_time.so module. The pam_time.so module enforces the login restrictions specified in the file /etc/security/time.conf. So the desired login windows must be defined in that file.

Example Policy
Using an example is the best way to explain the functioning of the pam_time.so module. We would like to limit user john remote login to the system to only between 13:00 and 14:00 any day. To do this, add the line below to the /etc/security/time.conf file:

# vi /etc/security/time.conf
sshd;*;john;Al1300-1400

Fields are separated by a semicolon (;) character. The fields are:

  1. The service name to be controller, here sshd is used.
  2. The tty terminal which is being controlled. This field allows us to limit the restriction to a certain terminal, for example. The “*” wildcard means apply the restriction regardless of the terminal used for the login attempt.
  3. A list of the users to whom this limitation applies. Our example restriction applies only to the john user.
  4. A list of times to which the restriction applies. Each time range is an optional exclamation mark (!) to negate the time range, followed by one or more two-letter day names, followed by a time range using a 24-hour clock. The name Wk means any weekday; the name Wd means a week-end day; and Al means any day. Our example grants permission between 13:00 and 14:00, any day of the week.

Activate The Policy
Add a line to the /etc/pam.d/sshd service file which reads:

# vi /etc/pam.d/sshd
account required pam_time.so

The line should be grouped with other account lines. The line order in PAM authentication files is important: items are applied in the order the lines appear in the file. Add the new line as the last account line. This ensures information about a time-based enforcement is not leaked to outsiders. In our example:

# vim /etc/pam.d/sshd
#%PAM-1.0
...
# Additionally, check for any account-based restrictions using pam_time.so
account required pam_nologin.so
account include password-auth
account required pam_time.so
...
Use extreme caution when making changes to the PAM configuration files. A wrong edit, or a typo, can open the system completely to any user, or can lock every user (including root) out of the system.
Related Post