Many system administrators face this common security dilemma: needing to maintain strict key-based authentication for most users while permitting password login for specific privileged accounts. The global PasswordAuthentication no setting in sshd_config doesn't provide the granularity needed for this mixed authentication scenario.
The most elegant solution leverages SSH's Match directive, which allows conditional configuration based on user, group, or connection criteria. Here's the optimal configuration:
# Global setting - default to key-only authentication
PasswordAuthentication no
PubkeyAuthentication yes
# Exception for specific user(s)
Match User justin
PasswordAuthentication yes
AuthenticationMethods publickey,password
For more complex environments, consider these variations:
# Allow password for local connections only
Match Address 192.168.1.0/24
PasswordAuthentication yes
# Multiple user exception
Match User justin,john,admin
PasswordAuthentication yes
After modifying /etc/ssh/sshd_config, always:
sudo sshd -t # Test configuration syntax
sudo systemctl restart sshd
Test connectivity from another terminal before logging out:
ssh -o PreferredAuthentications=password justin@yourserver
- Always combine with fail2ban for brute force protection
- Consider implementing two-factor authentication for password users
- Regularly audit authentication logs (
/var/log/auth.log)
For even more granular control, you can use PAM (Pluggable Authentication Modules):
# In /etc/pam.d/sshd
auth required pam_listfile.so \
item=user sense=allow file=/etc/ssh/password_auth_users onerr=fail
Then maintain the allowed users in /etc/ssh/password_auth_users.
The default SSH configuration doesn't provide granular control over authentication methods per user. When you set PasswordAuthentication no in sshd_config, it disables password auth globally. Here's how to implement per-user authentication policies.
OpenSSH's Match directive allows conditional configuration based on user, group, or other criteria. Add this to your /etc/ssh/sshd_config:
# Global setting - default to key-based auth
PasswordAuthentication no
AuthenticationMethods publickey
# Exception for specific user
Match User justin
PasswordAuthentication yes
AuthenticationMethods publickey,password
For more complex scenarios, consider these variations:
# Allow password for local users only
Match Address 192.168.1.*
PasswordAuthentication yes
# Multiple exception users
Match User justin,john,admin
PasswordAuthentication yes
After modifying the config:
sudo sshd -t # Test config syntax
sudo systemctl restart sshd
Security best practices:
- Always keep
PermitRootLogin no - Combine with
MaxAuthTries 3 - Monitor auth logs:
/var/log/auth.log
If authentication fails:
tail -f /var/log/auth.log
journalctl -u sshd -f
Check for correct file permissions:
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh