Configuring and hardening sshd

SSH · Advanced · 12 min

Internet-facing SSH servers are attacked constantly; a few sshd_config lines remove most of the risk.

The server reads /etc/ssh/sshd_config. Many distributions include /etc/ssh/sshd_config.d/*.conf at the top of it, and like the client, sshd uses the first value obtained for each keyword, so a drop-in file wins over later lines in the main file.

A sensible baseline once your key login works:

  • PasswordAuthentication no and KbdInteractiveAuthentication no: keys only, which defeats password-guessing bots.
  • PermitRootLogin no (the default is prohibit-password, which still allows root with a key). Log in as a user and use sudo.
  • AllowUsers deploy alice or AllowGroups ssh-users to restrict who can log in at all.
  • AuthenticationMethods publickey to be explicit; MaxAuthTries 3 to limit guesses per connection.
  • X11Forwarding no, and AllowTcpForwarding no on hosts that do not need tunnels.

Apply changes safely. Run sudo sshd -t to check syntax, keep your current session open, reload (systemctl reload ssh on Debian/Ubuntu, sshd on RHEL/Fedora), and test a new login from another terminal before closing the old one. Locking yourself out of a remote server is the classic mistake.

Match blocks apply settings conditionally: Match User backup followed by ForceCommand /usr/local/bin/backup-receiver restricts one account. sshd -T prints the effective configuration. Rate limiting tools (fail2ban, firewall rules) complement, but do not replace, key-only auth.

Example

# /etc/ssh/sshd_config.d/10-hardening.conf
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
AllowGroups ssh-users
MaxAuthTries 3
X11Forwarding no

Match User backup
    ForceCommand /usr/local/bin/backup-receiver
    AllowTcpForwarding no

# apply safely (keep your current session open!)
# sudo sshd -t && sudo systemctl reload ssh
# sudo sshd -T | grep -i passwordauthentication

Remember

  • Keys only: PasswordAuthentication no, KbdInteractiveAuthentication no
  • PermitRootLogin no and AllowUsers/AllowGroups limit who gets in
  • sshd -t, reload, test a new login before closing the old session

Watch out for

  • Disabling passwords before confirming key login works for your account, then losing access.

Check yourself

  1. You disabled password authentication and reloaded sshd. What should you do before closing your current session?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man.openbsd.org/sshd_config