Advanced · 12 min · practise every command in the built-in terminal

Harden SSH — Keys Only

Every server on the internet gets password-guessing attempts within minutes of going online. This one too:

sudo grep "Failed password" /var/log/auth.log | tail -5

A long random key can't be guessed. So the rules are: log in with keys only, and never straight in as root.

1. First: is your key there?

Turn passwords off before your key works, and you've locked yourself out. Check:

cat ~/.ssh/authorized_keys
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIvSk1t9… student@laptop

That's your laptop's public key (ssh-copy-id put it there). Logins with it keep working.

2. What does sshd use now?

sudo sshd -T | grep -E 'passwordauthentication|permitrootlogin'
permitrootlogin without-password
passwordauthentication yes

sshd -T prints every setting as the server would use it.

3. Your settings — in a file of their own

Debian's /etc/ssh/sshd_config begins with:

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

…and for each setting, sshd keeps the first value it reads. The files in sshd_config.d/ are read in name order — and this server has one already, from the cloud image:

cat /etc/ssh/sshd_config.d/50-cloud-init.conf
PasswordAuthentication yes

So give yours a name that comes first:

sudo nano /etc/ssh/sshd_config.d/10-hardening.conf
PasswordAuthentication no
PermitRootLogin no

4. Test, then reload

sudo sshd -t
sudo systemctl reload ssh

sshd -t prints nothing when the configuration is fine — and Bad configuration option for a typo, which would have stopped the reload. reload, not restart: the logged-in sessions, yours included, stay.

sudo sshd -T | grep -E 'passwordauthentication|permitrootlogin'
SettingMeans
PasswordAuthentication nokeys only
PermitRootLogin nolog in as yourself, then sudo
AllowUsers student deployonly these accounts may log in
Port 2222fewer bots in the log — not real security

⚠️ On a real server, keep your session open and try a new login from a second terminal before you close it.

Practice tasks

  1. Make sure your key is in place before anything else
  2. See whether the SSH server takes passwords now
  3. Write /etc/ssh/sshd_config.d/10-hardening.conf: no passwords, no root login
  4. Test the configuration
  5. Make the running SSH server read it
  6. Check what it uses now

Commands in this lesson

Server Security