Hardening an OpenSSH server comes down to removing the login methods you never intended to allow and proving the change before it takes effect. On OpenSSH 9.x the defaults are already reasonable — password auth is on but root password login is not — so the work is deliberate tightening: turn off password and keyboard-interactive auth, refuse root logins outright, limit who may connect with AllowUsers, trim the crypto to modern algorithms, and cap the login grace window. The one rule that matters more than any directive is procedural: validate with sshd -t, keep your current session open, and open a fresh session to test before you trust the change. Do that and a mistake costs you a retry, not a locked-out box.
What you’ll accomplish
- A single
/etc/ssh/sshd_config.d/99-hardening.confdrop-in that holds every change, leaving the vendorsshd_configuntouched. - Public-key-only authentication with root login and password login both refused.
- A connection allowlist so only named users (or a group) can even attempt to log in.
- A modern cipher, key-exchange, and MAC set, plus tightened
MaxAuthTriesandLoginGraceTime. - A validated, tested reload — you confirm the new session works before the old one closes.
Prerequisites
- OpenSSH 8.x or 9.x. Check with
ssh -Von the server. - Root or sudo on the host.
- A working key-based login you have already tested. Before you change anything, confirm you can log in with your key from a second terminal. If key auth is not working yet, stop and fix that first — this checklist assumes it works.
- Keep that second session open the entire time you edit. Every reload is validated by opening a third session; if it fails, you still have the working session to roll back from.
- The drop-in directory
/etc/ssh/sshd_config.d/must exist and be included from the main config. On current Debian, Ubuntu, RHEL, and their derivatives it is included by default via anInclude /etc/ssh/sshd_config.d/*.confline near the top of/etc/ssh/sshd_config.
How it works
When a client connects, sshd offers a set of authentication methods and the client tries them in order. A hardened server narrows that set to one: public key. The decision path is a series of gates. Root logins are refused by PermitRootLogin no regardless of method. Password and keyboard-interactive attempts are refused by PasswordAuthentication no and KbdInteractiveAuthentication no. A public key only succeeds if it is present in the user’s ~/.ssh/authorized_keys (with correct file permissions) and PubkeyAuthentication yes is set. Finally, AllowUsers filters by account name — even a valid key for an account not on the list is refused. Only a request that clears every gate reaches a session.
Configuration precedence matters. sshd reads the main file top to bottom and, for most directives, the first value set wins. The Include line pulls in the drop-in directory early, and files there are read in lexical order — which is why the 99- prefix is deliberate. It loads after any lower-numbered vendor drop-in (such as the cloud-image 50-cloud-init.conf), so your value is the first one seen for that keyword and takes effect. Putting everything in one clearly named drop-in also means a package upgrade that rewrites sshd_config never clobbers your policy.
Step-by-step
1. Confirm key login works before touching anything. From a second terminal, log in with your key and verify the method:
ssh -v you@server 2>&1 | grep -i "Authentication succeeded"
Expected — the line names publickey:
debug1: Authentication succeeded (publickey).
If it says password, fix key auth first. Do not proceed until this reads publickey.
2. Create the drop-in file. Keep every change in one place:
sudo install -m 600 -o root -g root /dev/null /etc/ssh/sshd_config.d/99-hardening.conf
sudo nano /etc/ssh/sshd_config.d/99-hardening.conf
3. Refuse root logins and passwords, require keys. Paste the core policy block. Replace the sample account and group with yours:
# Authentication policy
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthenticationMethods publickey
# Who may connect
AllowUsers deploy alice
# Or, prefer a group:
# AllowGroups sshusers
AuthenticationMethods publickey makes the intent explicit and blocks any method not listed even if a future edit re-enables it. Use either AllowUsers or AllowGroups, not both unless you understand that a user must satisfy every allow list present.
4. Set login limits. Add the grace and attempt caps to the same file:
# Login limits
MaxAuthTries 3
LoginGraceTime 20
MaxSessions 4
MaxStartups 10:30:60
LoginGraceTime 20 gives 20 seconds to authenticate before the connection is dropped; the default is 120. MaxAuthTries 3 cuts the per-connection attempts from the default 6.
5. Restrict the crypto. Pin a modern algorithm set. These are all current OpenSSH 9.x algorithms and drop the weakest defaults:
# Modern algorithms
KexAlgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
The ETM (encrypt-then-MAC) variants are preferred over their plain counterparts. This list is deliberately tight; the Troubleshooting section covers what to do if an old client cannot negotiate it.
6. Validate the syntax. This is the step that saves you. sshd -t parses the full config and exits non-zero on any error, changing nothing:
sudo sshd -t && echo "config OK"
Expected:
config OK
If it prints a line like /etc/ssh/sshd_config.d/99-hardening.conf: line 4: Bad configuration option, fix it and rerun. Do not reload until this passes cleanly.
7. Inspect the effective config. sshd -T prints the fully resolved runtime configuration — what sshd will actually enforce after all includes and precedence:
sudo sshd -T | grep -Ei 'permitrootlogin|passwordauthentication|pubkeyauthentication|allowusers|maxauthtries'
Expected:
permitrootlogin no
pubkeyauthentication yes
passwordauthentication no
maxauthtries 3
allowusers deploy alice
If a value is not what you set, a lower-numbered drop-in is winning — check the file order in /etc/ssh/sshd_config.d/.
8. Reload, do not restart. reload re-reads the config without dropping existing connections, so your open session survives even if something is wrong:
sudo systemctl reload ssh
On distributions where the unit is named sshd, use sudo systemctl reload sshd instead. A restart would kill active sessions and could strand you — reload is the safe verb here.
9. Test a new session before closing the old one. From a fresh terminal, open a brand-new connection. Keep the editing session open until this succeeds:
ssh -v you@server
Once you have a working prompt in the new session, the change is proven. Only then close the original session.
Validate it works
From a new terminal, confirm each gate behaves. Public key is accepted:
ssh -v you@server 2>&1 | grep -i "Authentication succeeded"
Expected: debug1: Authentication succeeded (publickey).
A password attempt is refused — force password auth and confirm sshd rejects it:
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no you@server
Expected: Permission denied (publickey). — the server offers only publickey.
A root login is refused:
ssh -v root@server
Expected: Permission denied (publickey).
Finally, confirm the effective policy on the server once more:
sudo sshd -T | grep -Ei 'permitrootlogin|passwordauthentication'
Expected: permitrootlogin no and passwordauthentication no.
Troubleshooting
Locked out after a reload you did not test. This is the classic mistake: reload, close every session, then discover key auth was misconfigured. If you still hold any open session, revert the drop-in and reload again. If you have no session, recover through the provider’s serial or web console, or boot to rescue and remove /etc/ssh/sshd_config.d/99-hardening.conf. The prevention is the procedure above — never close the working session before a new one connects.
Key rejected because of file permissions. sshd ignores an authorized_keys file that is group- or world-writable, silently falling back to failure. The home directory, ~/.ssh, and ~/.ssh/authorized_keys must not be writable by group or other. Fix with chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys. On SELinux systems (RHEL family) a file restored from a backup may carry the wrong context; restorecon -Rv ~/.ssh relabels it. Add -v to your ssh and check the server’s journal with journalctl -u ssh -e to see the exact rejection reason.
AllowUsers left off your own account. If AllowUsers names only service accounts and not the human account you log in as, every login is refused with Permission denied. sudo sshd -T | grep allowusers shows the effective list — your account must appear on it. This is exactly why you keep a session open: add your account, sshd -t, reload, test.
Service name is ssh on one distro, sshd on another. Debian and Ubuntu ship the unit as ssh (with an sshd.service alias on newer releases); RHEL, Fedora, and their derivatives use sshd. If systemctl reload ssh reports Unit ssh.service not found, use sshd. Confirm with systemctl list-units '*ssh*'.
Cipher list too strict for an old client. A client on an ancient OpenSSH or a locked-down appliance may fail with no matching cipher found or no matching key exchange method found. Confirm the client’s offer with ssh -vv, then either update the client or, as a scoped exception, add the one algorithm it needs back to the list rather than widening the policy for everyone. Prefer fixing the client.
When this is the wrong approach
Per-host sshd_config hardening is right for servers you administer directly. It is the wrong tool when the fleet is large enough that editing files by hand does not scale, or when SSH is not really the front door:
- Bastion or jump host with a central identity provider. If access flows through one hardened bastion backed by an IdP and short-lived certificates, put the policy there and centralize it. A certificate authority replaces per-host
authorized_keyssprawl entirely. - Ephemeral cloud instances under config management. Machines that live for hours and are rebuilt from an image should get this config baked in by Ansible, cloud-init, or a golden image — not hand-edited. Hand edits vanish on the next rebuild.
- SSH should be off entirely. If instances are reachable through AWS Systems Manager Session Manager or an equivalent agent, closing port 22 at the firewall beats hardening it. The most hardened SSH daemon is the one not listening.
For the earlier steps that get you to key-only auth in the first place, see switching SSH to key-only authentication and, once you are locked down, Fail2ban for SSH to shed brute-force noise. The authoritative reference for every directive is the sshd_config manual.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.