Sub topic 10
Harden the SSH daemon safely
This chapter assumes you can log in to a Linux server over SSH, edit files with a terminal editor, and use sudo. You should also have finished the previous chapter, so that your key pair works and your public key is in the admin user's ~/.ssh/authorized_keys file. Hardening the SSH daemon (sshd, the program that accepts SSH connections) is the step where a small mistake can lock you out of your own server. The goal here is to make the change in an order that lets you undo it.
What you are changing and why
A server with a public address receives automated password-guessing attempts within minutes. Two settings remove most of that exposure:
- Password logins off. An attacker cannot guess a key the way they can guess a password.
- Root login off. Every attacker knows the account name
rootexists. Logging in as a named admin user and usingsudoalso leaves a better audit trail.
You will set these in a drop-in file, then validate, reload, and test before you close anything.
How sshd reads its configuration
The main file is /etc/ssh/sshd_config. Most current distributions ship it with a line like this near the top:
Include /etc/ssh/sshd_config.d/*.confThat line loads every .conf file in the sshd_config.d directory. This lets you keep your changes in one small file and leave the packaged file untouched, so package upgrades do not overwrite your settings or ask you to merge changes.
Two rules about precedence cause most confusion:
- For most settings, the first value sshd reads wins, not the last. Files in the drop-in directory are read in alphabetical order, so
10-hardening.confis read before50-cloud-init.conf. - Because the
Includeline sits at the top of the main file, drop-in values come before the main file's own values and therefore override them.
This matters on cloud images. Many ship a file such as /etc/ssh/sshd_config.d/50-cloud-init.conf containing PasswordAuthentication yes. If your file is named 10-hardening.conf, yours is read first and wins. If you named it 99-hardening.conf, the cloud file would win and your change would silently do nothing.
Older systems may not have the Include line or the directory. In that case, edit /etc/ssh/sshd_config directly and keep a backup copy first.
The hardening file
Create the drop-in file with the settings below.
# /etc/ssh/sshd_config.d/10-hardening.conf
PasswordAuthentication no
PermitRootLogin no
PubkeyAuthentication yesWhat each line does:
| Setting | Effect | Note |
|---|---|---|
| `PasswordAuthentication no` | Rejects password logins over SSH | Does not affect console logins or `sudo` passwords |
| `PermitRootLogin no` | Rejects all SSH logins for `root` | `prohibit-password` would allow root with a key |
| `PubkeyAuthentication yes` | Allows key-based login | Already the default, set explicitly for clarity |
Turning off password authentication over SSH does not remove the password from the account. Your admin user still needs it for sudo unless you configured passwordless sudo, and you still need it at the console.
Apply the change in a safe order
Follow this sequence every time you change SSH settings.
- Keep your current session open. An established SSH connection stays alive when the daemon reloads. This open session is your way back in if something goes wrong.
- Validate the syntax. The
-toption checks the configuration without applying it. - Reload, do not restart. A reload re-reads the configuration and leaves existing connections alone.
- Test from a second terminal. Open a new connection. Only when it succeeds should you close the first one.
# Check the configuration for errors, then reload the daemon
sudo sshd -t
sudo systemctl reload ssh # Debian/Ubuntu service name
# sudo systemctl reload sshd # RHEL family service name
# Keep the current session open and test a new login from a second terminal
ssh [email protected]If sshd -t prints nothing and exits with status 0, the syntax is valid. If it prints an error, fix it before reloading. A reload with a broken file leaves the running daemon on its old configuration in most cases, but you should not rely on that.
The service is named ssh on Debian and Ubuntu and sshd on the RHEL family. If you get "Unit not found", try the other name.
Confirm what sshd is actually using
Reading the file is not proof. Ask the daemon for its effective configuration:
sudo sshd -T | grep -Ei 'passwordauthentication|permitrootlogin|pubkeyauthentication'sshd -T prints the merged settings after all includes are processed, in lowercase. You should see:
permitrootlogin no
pubkeyauthentication yes
passwordauthentication noIf passwordauthentication still shows yes, another file is setting it first. Find it with:
sudo grep -ri 'PasswordAuthentication' /etc/ssh/sshd_config /etc/ssh/sshd_config.d/Rename your file so it sorts before the other one, or remove the conflicting line.
You can also prove that password login is refused from your workstation. This forces SSH to try only a password:
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password [email protected]The expected result is Permission denied (publickey). and no password prompt.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `Permission denied (publickey)` on a normal login | Key not installed, wrong user, or wrong permissions | Check `~/.ssh` is mode `700` and `authorized_keys` is mode `600`, owned by the user |
| Setting has no effect after reload | An earlier-sorted file sets the same option | Use `sshd -T` and `grep` to find it |
| `Unit ssh.service not found` | Service name differs by family | Use `sshd` on RHEL-family systems |
| `Bad configuration option` from `sshd -t` | Typo or unsupported option | Fix the spelling, check the man page `sshd_config(5)` |
| Connection refused after change | Daemon failed, or a firewall blocks the port | Use the console, run `systemctl status ssh` and `journalctl -u ssh` |
| New session hangs, old one works | Another problem such as DNS or a firewall rule | Compare with `ssh -v` output |
When a login fails, run the client in verbose mode. Each extra v adds detail.
ssh -vvv [email protected]Look for lines that say which keys were offered and which methods the server accepted.
Extra settings worth considering
The three settings above are the core. These are optional and each has a cost, so add them one at a time.
AllowUsers adminlimits SSH to named accounts. If you later add another administrator and forget this line, they cannot log in.MaxAuthTries 3reduces guesses per connection. Keys offered by an agent each count as a try, so users with many keys may be rejected before the right one is tried.X11Forwarding nodisables graphical forwarding, which a server rarely needs.- Changing the port from 22 reduces log noise but is not a security control. If you do change it, update the firewall first, or you will block yourself. On systems with SELinux enforcing, you must also label the new port.
Fail2ban or similar tools that ban repeated failures are separate packages. With password login off, they mostly reduce log volume rather than risk.
Recovery plan
Know your way back in before you start.
- Virtual machine or cloud server: use the provider's web console or serial console, which does not go through SSH.
- Physical server: use the keyboard and monitor, or the out-of-band management interface.
- If you saved a backup, restore it with
sudo cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config. For a drop-in file, delete it withsudo rm /etc/ssh/sshd_config.d/10-hardening.conf, runsudo sshd -t, and reload.
The following diagram shows the safe sequence and where you branch on a failure.
Exercises
Exercise
You created /etc/ssh/sshd_config.d/99-hardening.conf with "PasswordAuthentication no", reloaded sshd, and password login still works. A file named 50-cloud-init.conf in the same directory contains "PasswordAuthentication yes". Why does your setting not apply, and how do you fix it?
Show answer
sshd uses the first value it reads for most options, and drop-in files are read in alphabetical order. 50-cloud-init.conf sorts before 99-hardening.conf, so its "yes" wins. Rename your file to something that sorts earlier, such as 10-hardening.conf (or remove the conflicting line), run "sudo sshd -t", reload, and confirm with "sudo sshd -T | grep passwordauthentication".
Exercise
Why should you reload rather than restart sshd, and why test from a second terminal before closing the first one?
Show answer
A reload applies the new configuration while leaving existing connections open, so your current session survives even if the new settings turn out to be wrong. The second terminal proves that a fresh login works under the new rules. If it fails, the still-open first session lets you revert the change without needing the console.
Exercise
Name the command that shows the settings sshd is actually using after all included files are merged, and the command that checks a configuration file for syntax errors without applying it.
Show answer
"sudo sshd -T" prints the effective configuration. "sudo sshd -t" checks the syntax and prints nothing if it is valid.