Chapter 3 · 3.2
Disabling password login and root login
Every server on the internet soon gets visits from programs that guess passwords. If you can only log in with a key, they don't stand a chance. You'll set that up now.
Please note: Can you log in with your key as anna (see Your own user with sudo)? Then first make a snapshot (see Snapshots: a safety net for every major change) and keep a session open during these steps. If something goes wrong anyway, you can get in through the console (see The console: your VPS in your browser).
Your own settings file
On Debian and Ubuntu, the SSH server first reads the files in /etc/ssh/sshd_config.d/, in alphabetical order. For each setting, the first value it finds counts. That's why you give your own file a name that comes first:
anna@web1:~$ sudo nano /etc/ssh/sshd_config.d/00-eigen.conf
Add this to it:
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
PasswordAuthentication no: no more passwords over SSH.KbdInteractiveAuthentication no: no password prompt through a back door either.PermitRootLogin no: root can no longer log in over SSH, not even with a key. You work as anna with sudo. Want to keep allowing root with a key? Then useprohibit-password.
Checking and applying
anna@web1:~$ sudo sshd -t
anna@web1:~$ sudo sshd -T | grep -Ei '^(passwordauthentication|kbdinteractiveauthentication|permitrootlogin)'
passwordauthentication no
kbdinteractiveauthentication no
permitrootlogin no
anna@web1:~$ sudo systemctl restart ssh
sshd -t says nothing if the file is correct. sshd -T shows which values actually apply. Does it still show passwordauthentication yes? Then another file in sshd_config.d is turning it back on, often 50-cloud-init.conf. Your 00-eigen.conf comes before it and wins, so check that the name is right.
On AlmaLinux and Rocky Linux the service is called sshd: sudo systemctl restart sshd.
Test before you close your session
Open a new window and try:
ssh anna@203.0.113.10
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no anna@203.0.113.10
anna@203.0.113.10: Permission denied (publickey).
ssh root@203.0.113.10
root@203.0.113.10: Permission denied (publickey).
The first one should work. The other two should be refused. All good? Then delete the snapshot.
Tip: A port number other than 22 keeps your log quieter, but doesn't make your server any safer. The key does the work. If you change the port anyway, open it in your firewall first (see A firewall with ufw (or nftables)).
