Restrict SSH Access to Specific Users on Ubuntu

Securing an Ubuntu Linux server requires limiting remote access to only authorized personnel. This article provides a quick, step-by-step guide on how to restrict SSH access to specific users or groups by modifying the SSH daemon configuration file. By implementing these changes, you will significantly enhance your server’s security posture and prevent unauthorized login attempts.

Step 1: Open the SSH Configuration File

To begin, edit the SSH daemon configuration file using a text editor with administrative privileges. Run the following command in your terminal:

sudo nano /etc/ssh/sshd_config

Step 2: Define Allowed Users or Groups

Scroll to the bottom of the file and add the rules to restrict access. You can restrict access using either individual usernames or system groups.

Option A: Restrict by Username

To allow only specific users to log in, add the AllowUsers directive followed by the usernames separated by spaces.

AllowUsers alice bob charlie

Note: Any user not explicitly listed here will be denied SSH access, even if they have a valid account on the server.

Option B: Restrict by User Group

If you manage multiple users, it is often easier to restrict access by a user group. Add the AllowGroups directive followed by the group name:

AllowGroups sshusers

(To use this option, ensure you have created the group using sudo addgroup sshusers and added your users to it using sudo usermod -aG sshusers username).

Step 3: Save and Exit

If you are using nano, save your changes by pressing Ctrl + O, hit Enter to confirm, and then press Ctrl + X to exit the editor.

Step 4: Test the Configuration

Before applying the changes, test the SSH configuration file for syntax errors to prevent accidentally locking yourself out of the server:

sudo sshd -t

If this command returns no output, your configuration is correct.

Step 5: Restart the SSH Service

To apply the restrictions, restart the SSH daemon with the following command:

sudo systemctl restart ssh

Important: Do not close your current terminal session. Open a new terminal window and attempt to log in to ensure your configuration works as expected.