Allow/Deny SSH Access To a Particular User Or Group In Linux
If you’ve ever had a rogue employee or a bot that keeps hitting your servers, this is the quick‑fix you need. I’ll walk you through two practical ways to lock down SSH so only whitelisted folks get in, and show how to test it without locking yourself out.
Prerequisites and Safety Net
1. Back up sshd_config
sudo cp /etc/ssh/sshd_config ~/sshd_config.bak – A copy is your safety net if you break the file.
2. Make sure you’re logged in via a separate session (e.g., console or another SSH user) – You’ll need that to recover if you lock yourself out.
3. Know your OpenSSH version
ssh -V – Some directives only work on newer releases (≥8.2).
Using the UserAllow Directive (OpenSSH 8.2+)
# Edit sshd_config sudo nano /etc/ssh/sshd_config # Add the following at the end: UserAllow: alice,bob
UserAllow is a one‑liner that tells SSH to accept connections from only the listed users. It’s cleaner than juggling multiple AllowUsers/DenyUsers entries, and it leaves the rest of your config untouched.
Using DenyUsers / AllowUsers (Legacy Approach)
If you’re on an older distro or just prefer the classic method:
# In sshd_config AllowUsers alice bob@example.com DenyUsers badguy
- AllowUsers explicitly whitelists accounts; everything else is blocked.
- DenyUsers can be used to block a rogue account without touching the whitelist.
> Scenario: I once had a script on a shared server that automatically added a new user “tmpuser” after every failed login attempt, and it kept showing up in /var/log/auth.log. By adding DenyUsers tmpuser, I stopped those noise logs instantly.
Group‑Based Control with Match Group
If you’re managing many users, grouping them makes sense:
# In sshd_config
Match Group developers
AllowUsers alice bob
The Match block lets you apply settings only to a specific group. It’s handy if your server hosts multiple environments (dev, prod) and you want tighter rules per environment.
Reloading sshd Without Dropping Sessions
sudo systemctl reload sshd
or, on older systems:
sudo service ssh reload
A reload applies the new config while keeping existing connections alive. If you used a hard restart (systemctl restart sshd), every active session would drop—no fun.
Verifying Your Changes
1. Open a fresh terminal or another SSH user.
2. Try logging in as an allowed user: ssh alice@yourserver. It should work.
3. Attempt a denied user: ssh badguy@yourserver. You’ll see “Permission denied (publickey).”
If you’re unsure, check the logs:
sudo tail -f /var/log/auth.log
You’ll notice entries for allowed and denied attempts in real time.
That’s it. Pick the method that fits your OpenSSH version and your team structure, tweak sshd_config, reload, and you’ve tightened SSH access with minimal fuss.