How to harden SSH on Ubuntu 24.04 without locking yourself out
In this article10 sections
SSH is the front door of a Linux server. Every public server is probed constantly: open the log of any new machine and within an hour you will see strangers trying root, admin and ubuntu with common passwords. Most of those attempts fail, but “most” is not a security policy.
The good news is that hardening SSH takes ten minutes. The bad news is that the most common way to fail is locking yourself out of your own server. This guide gives you the changes that matter, the order that keeps you safe, and the one detail on Ubuntu images that makes people think they hardened SSH when they did not.
Before you change anything
Do these three things first. They are what turns a mistake into a minor annoyance.
- Keep your current SSH session open for the whole process. Do not close it until the last test passes. An existing session survives a reload of the SSH service.
- Find the out-of-band console. Every provider has some way to reach the machine without SSH: a web console, VNC or a rescue mode. Open it and make sure you can log in there. If you cannot, stop and sort that out first.
- Take a snapshot if your provider offers one. It costs nothing and gives you a clean way back.
Step 1: Use a normal user with sudo, and a key
Do not work as root. Create a named user, give it sudo, and log in with a key.
On your own computer, create a key if you do not have one:
ssh-keygen -t ed25519 -C "you@laptop"
Copy the public half to the server:
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@your-server
On the server, if the user does not exist yet:
sudo adduser deploy
sudo usermod -aG sudo deploy
Now open a second terminal and prove the key works before touching any setting:
ssh deploy@your-server
sudo whoami
You should get in without a password prompt for the login, and sudo whoami should answer root. If this does not work, fix it now. Everything below assumes it does.
Step 2: Write the hardening in a drop-in file
Ubuntu reads /etc/ssh/sshd_config and then every file in /etc/ssh/sshd_config.d/. Do not edit the main file; add your own.
Name the file so that it is read first. SSH uses the first value it finds for each setting, and files in the drop-in folder are read in alphabetical order. Many cloud images ship a file such as 50-cloud-init.conf that can set PasswordAuthentication yes. If your file is called 99-hardening.conf, the image’s value is read first and wins, and your setting is silently ignored. Name yours 00-hardening.conf.
sudo nano /etc/ssh/sshd_config.d/00-hardening.conf
Contents:
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
AllowUsers deploy
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding no
What each line does:
PermitRootLogin no: nobody logs in as root directly. Administrators log in as themselves and usesudo, which leaves a record of who did what.PasswordAuthentication noandKbdInteractiveAuthentication no: passwords are not accepted at all, so guessing them becomes pointless. Both lines matter: keyboard-interactive is a second route that can still ask for a password.PubkeyAuthentication yesandAuthenticationMethods publickey: a key is the only way in.AllowUsers deploy: only the named accounts may log in. List several names separated by spaces. Anyone not on the list is refused even with a valid key.MaxAuthTries 3andLoginGraceTime 30: fewer guesses per connection and less time to hold a connection open.X11Forwarding no: a graphical forwarding feature a server rarely needs.
Step 3: Test the configuration before applying it
SSH can check its own syntax:
sudo sshd -t
No output means the syntax is fine. Then ask SSH what it will actually use, after all files are merged. This is the check that catches the cloud-init trap:
sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|allowusers|authenticationmethods) '
You should see:
permitrootlogin no
passwordauthentication no
kbdinteractiveauthentication no
authenticationmethods publickey
allowusers deploy
If passwordauthentication yes shows up, a file read earlier is overriding yours. Find it:
sudo grep -rn "PasswordAuthentication" /etc/ssh/sshd_config /etc/ssh/sshd_config.d/
Change the value in that file too, or make sure your file sorts before it.
Step 4: Apply with a reload, then test from a new session
sudo systemctl reload ssh
On Ubuntu the service is called ssh (not sshd). A reload applies the new settings to new connections without cutting off the ones already open, which is exactly why your first session is your safety net.
Now, from a third terminal, test that the door is closed to what should be refused and open to what should work:
# Should succeed
ssh deploy@your-server
# Should fail with "Permission denied (publickey)"
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password deploy@your-server
# Should fail: root is not allowed
ssh root@your-server
Only when all three behave correctly may you close your original session. If the first one fails, use that still-open session to undo the change by removing or editing the file, then run sudo systemctl reload ssh again.
Step 5: Add a firewall and a brute-force guard
SSH settings protect the login; a firewall controls who can reach the port at all.
sudo ufw allow OpenSSH
sudo ufw allow 80,443/tcp
sudo ufw enable
sudo ufw status verbose
Allow SSH before you enable the firewall, or you will lock yourself out in a different way. If you always connect from a fixed address, you can go further and allow SSH only from there:
sudo ufw delete allow OpenSSH
sudo ufw allow from 203.0.113.10 to any port 22 proto tcp
(Replace the example address with your own, and only do this if you are certain the address is stable.)
For everyone else, fail2ban bans addresses that fail repeatedly:
sudo apt install fail2ban
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd
On a server where passwords are disabled, fail2ban is mostly about keeping the logs quiet and the CPU free, because the guesses cannot succeed anyway. It is still worth having.
A note on changing the port
Moving SSH to a different port reduces noise in the logs and does nothing for real security: any scanner finds it in seconds. If you do it, know that Ubuntu 24.04 starts SSH through a systemd socket, so editing Port in the SSH configuration alone does not behave as you expect. The listening port is set on the socket:
sudo systemctl edit ssh.socket
Add:
[Socket]
ListenStream=
ListenStream=2222
Then restart the socket (sudo systemctl restart ssh.socket), allow the new port in the firewall first, and test from a second session. If you do not have a reason to change the port, leave it alone.
Keep the keys healthy
- Use a passphrase on your private key, and an agent so you type it once per session.
- One key per person and per device, with a comment that says whose it is. When someone leaves, you remove one line from
authorized_keys. - Review
authorized_keysnow and then.cat ~/.ssh/authorized_keysfor each user that can log in. Any key you do not recognise needs an explanation. - Protect the file permissions. SSH ignores keys if the folder or file is too open:
chmod 700 ~/.sshandchmod 600 ~/.ssh/authorized_keys. - Back up your private key somewhere safe. A lost key on a key-only server is a locked door, and the provider console is the only way back.
Verify from outside
The best test is how an outsider sees your server. From another machine:
nmap -p 22 -sV your-server
ssh -v -o PreferredAuthentications=password -o PubkeyAuthentication=no deploy@your-server 2>&1 | tail -5
You should see port 22 open, and the second command should end with Permission denied (publickey). If it offers a password prompt, a setting did not take effect: go back to sshd -T.
When it is worth getting help
SSH hardening is a good thing to learn. The risk is rarely the settings: it is doing it on a production server that a business depends on, with no console access, at the end of a long day. If you have a server like that, or several, and you would rather have it done and checked once, I do exactly this kind of work: a named admin account, key-only access, firewall, brute-force protection, and a short written record of what changed and how to undo it.
You can see my profile on Upwork, or read about the server hardening service. For a wider checklist beyond SSH, there is the Ubuntu server hardening checklist.