How to Configure SSH to restrict Users/Groups with allow and deny directives

Question: How can we restrict user/group access to a system using ssh?

SSH uses specific files for configuration to achieve these various restrictions. Inbound ssh sessions (into the host) are handled by sshd (the ssh daemon). This process has its own configuration file, /etc/ssh/sshd_config. The parameters in the /etc/ssh/sshd_config file that apply are AllowGroups, AllowUsers, DenyGroups, and DenyUsers. If these parameters are set, it will affect all users from all hosts.

To restrict groups, the option AllowGroups and DenyGroups are useful. The said options will allow or disallow users whose primary group or supplementary group matches one of the group patterns.

Example

1. To allow SSH connections from anywhere to access the mary and jerry accounts, but no other accounts::

# vi /etc/ssh/sshd_config
AllowUsers mary jerry

2. To allow SSH connections from s01.geeklab.com to the john account, but no other incoming SSH connections:

AllowUsers john@s01.geeklab.com

3. To Deny SSH connection from anywhere to all the users of ‘finance’:

DenyGroups finance

Viewing failed login attempts

You can always review the login records at any time by typing:

# cat /var/log/secure | grep 'sshd'

The output of which will look like this:

May  3 13:57:24 centos7 sshd[2479]: pam_unix(sshd:session): session closed for user root
May  3 13:57:28 centos7 sshd[3313]: Accepted password for root from 192.168.1.17 port 51093 ssh2
May  3 13:57:28 centos7 sshd[3313]: pam_unix(sshd:session): session opened for user root by (uid=0)

And, should you wish to view a list of failed attempts, you could try the following:

# cat /var/log/secure | grep 'sshd.*Failed'

Accepted login attempts can be viewed with:

# cat /var/log/secure | grep 'sshd.*Accepted'
Related Post