How to Restrict SSH Access to Certain Users in Linux

OpenSSH (Secure Shell) is a standard connectivity program for logging into a remote machine using the SSH protocol for executing commands on the remote machine. It encrypts all network traffic between client and server to eradicate eavesdropping, connection hijacking, and other attacks.

[ You might also like: How to Disable SSH Login to Specific User in Linux ]

In addition, OpenSSH offers a large suite of secure tunneling capabilities, various authentication methods, and sophisticated configuration options. One such security feature is limiting or restricting the SSH access to certain users using the AllowUsers keyword that accepts SSH connections from the list of specified local accounts in the SSH configuration file.

In this article, you will learn how to restrict or whitelist certain user accounts to access SSH incoming connections on your Linux server.

Restricting SSH Access to User Accounts

To limit ssh access for a user called ‘linuxshelltips‘, use the sshd ’s AllowUsers keyword in /etc/ssh/sshd_config file.

$ sudo vi /etc/ssh/sshd_config
OR
$ sudo nano /etc/ssh/sshd_config

To allow SSH connections from user ‘linuxshelltips‘ account, but no other accounts.

AllowUsers linuxshelltips

You can add multiple user accounts separated by spaces, for example:

AllowUsers user1 user2 user3

You can confirm this by running the following command.

$ cat /etc/ssh/sshd_config | grep -i allowusers
Limit SSH Access to User Accounts
Limit SSH Access to User Accounts

After modifying sshd_config, make sure to restart sshd to incorporate your changes.

$ sudo systemctl restart sshd

Verify SSH Access to User Accounts

Now try to connect to a Linux system using a different user account called ‘ravi‘ who is not mentioned in the SSH allowed list so he cannot receive SSH connections.

$ ssh ravi@192.168.0.175

ravi@192.168.0.141's password: 
Permission denied, please try again.

Furthermore, you can also confirm this by checking the ssh logs at /var/log/secure file.

$ cat /var/log/secure | grep -i allowusers
Check SSH Logs
Check SSH Logs

Now try to log in with a user 'linuxshelltips' who is allowed to connect into the system because it’s in the allowed user’s list.

$ ssh linuxsheltips@192.168.0.175
$ su -
$ cat /var/log/secure | grep -i linuxshelltips
Confirm SSH User Login
Confirm SSH User Login

Got something to say? Join the discussion.