Security Basics — SSH, TLS and Certificates›06 · Hardening an SSH server

Lesson 06 of 16 · SSH

Hardening an SSH server

Harden an SSH server without locking yourself out: the settings that matter in sshd_config, the drop-in directory trap where the first value wins, testing with sshd -t and sshd -T, keeping a second session open, then fail2ban, firewall rules, whether to change the port, MFA, and SSH certificates for larger fleets.

Practitioner
Key wordsSSH hardeningsshd_configsshd_config.dPermitRootLoginPasswordAuthenticationKbdInteractiveAuthenticationAllowGroupsMaxAuthTriessshd -tsshd -Tfail2banufwport changessh.socketSSH certificatesMFA

Before you change anything

Locking yourself out of a remote server is the classic hardening mistake. Follow this routine every time:

  1. Make sure key login works for your admin user (lesson 5) and that user can sudo.
  2. Keep your current SSH session open the whole time.
  3. Edit, then test the configuration: sudo sshd -t.
  4. Reload (existing sessions survive): sudo systemctl reload ssh.
  5. Open a new terminal and log in again. Only close the old session when the new one works.
  6. Have a console fallback (the cloud provider's serial or web console) for emergencies.

The settings that matter

Put your settings in a drop-in file, for example /etc/ssh/sshd_config.d/00-hardening.conf:

# Who can log in, and how
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
AllowGroups sshusers

# Limit guessing and idle sessions
MaxAuthTries 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2

# Turn off what you don't use
X11Forwarding no
AllowAgentForwarding no
PermitEmptyPasswords no
Setting Why
PermitRootLogin no Attackers always try root; admins log in as themselves and use sudo (an audit trail per person)
PasswordAuthentication no, KbdInteractiveAuthentication no Ends password guessing completely
AllowGroups sshusers Only members of this group may log in, even if other accounts exist. Add yourself first: sudo usermod -aG sshusers asha
MaxAuthTries 3, LoginGraceTime 30 Fewer guesses per connection, less time holding a connection open
ClientAlive… Drop dead sessions
X11Forwarding no, AllowAgentForwarding no Remove features that add risk if unused

Hardening SSH is like securing the front door: nobody can use the master key (root), the door only opens for real keys, not for people guessing the code (passwords), only people on the list get in (AllowGroups), and after three wrong tries you're sent away.

The drop-in trap: first value wins

On Ubuntu and Debian, the main /etc/ssh/sshd_config starts with:

Include /etc/ssh/sshd_config.d/*.conf

For most options, sshd uses the first value it reads. Files in sshd_config.d/ are read first, in alphabetical order. Cloud images often ship 50-cloud-init.conf containing PasswordAuthentication yes. If you only edit the main file, that earlier value wins and your change is silently ignored.

Always check the effective value, not the file:

$ sudo sshd -t                     # syntax check: no output means OK
$ sudo sshd -T | grep -Ei '^(passwordauthentication|permitrootlogin|kbdinteractiveauthentication)'
passwordauthentication no
permitrootlogin no
kbdinteractiveauthentication no

Naming your file 00-hardening.conf makes it load before 50-cloud-init.conf.

fail2ban: ban repeat offenders

fail2ban reads the SSH log and temporarily blocks IPs that fail too often. With key-only login, guessing cannot succeed anyway, but fail2ban cuts the noise and slows scanners. Ubuntu's package enables the sshd jail; tune it in /etc/fail2ban/jail.local:

[sshd]
enabled  = true
maxretry = 5
findtime = 10m
bantime  = 1h

Check it with sudo fail2ban-client status sshd.

Firewall: who may reach port 22 at all

The strongest step is not to expose SSH to the whole internet:

  • allow SSH only from your office or VPN range: sudo ufw allow from 203.0.113.0/24 to any port 22 proto tcp;
  • or reach servers only through a bastion or a VPN (lesson 5, ProxyJump);
  • in the cloud, do the same in the security group or firewall rules.

Changing the port

Moving SSH to, say, port 2222 cuts bot noise in the logs but is not a security control: a port scan finds it in seconds. If you do it, remember to open the new port in the firewall first. On Ubuntu 24.04, SSH may be started by socket activation (ssh.socket): after changing Port, run sudo systemctl daemon-reload && sudo systemctl restart ssh.socket.

Going further

  • MFA: add a one-time code with a PAM module (for example Google Authenticator's PAM module) and AuthenticationMethods publickey,keyboard-interactive, or use FIDO2 hardware keys (ed25519-sk, lesson 5).
  • SSH certificates for fleets: instead of copying public keys to hundreds of servers, servers trust one user CA (TrustedUserCAKeys). A short-lived certificate (for example 8 hours) is issued to each person after they sign in with company SSO. Leavers simply stop getting certificates. The same works the other way with host certificates, which removes the "unknown host" prompt.
  • Keep OpenSSH updated: for example CVE-2024-6387 ("regreSSHion") allowed remote code execution on unpatched servers.
  • Watch the logs: journalctl -u ssh for successful logins from unexpected places.

Recap

  • Keep a session open, sshd -t, reload, test a new login, then close the old one.
  • Key-only login, no root login, AllowGroups, few tries, unused features off.
  • First value wins with drop-ins; verify with sshd -T.
  • Add fail2ban, restrict port 22 with a firewall or bastion; a port change is only noise reduction.
  • For larger estates: MFA and SSH certificates.

This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.