Guide 5 · Linux
Lock down a public Ubuntu server: SSH keys, UFW and services
Key-only SSH, an optional non-default port that works with Ubuntu 24.04's socket activation, UFW rules that do not lock you out, unused services removed, failed units checked and updates confirmed.
Before you change anything
Stop Keep a way back in
- Keep your current SSH session open until you have logged in again through a second, new session.
- Make sure you can reach the server's console through your hosting provider's web panel. If SSH breaks, that is the only way in.
- Take a snapshot or backup first if your provider offers one.
Commands below run on the server as a user with sudo unless the label says otherwise.
Step 1: set up key sign-in
Create a key pair on the computer you connect from. Ed25519 keys are short and strong:
ssh-keygen -t ed25519 -C "laptop-2026"Copy the public key to the server:
ssh-copy-id -i ~/.ssh/id_ed25519.pub USER@SERVER_IPWindows does not include ssh-copy-id; this does the same job:
type $env:USERPROFILE\.ssh\id_ed25519.pub | ssh USER@SERVER_IP "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"Open a new terminal and confirm you can log in with the key before going further:
ssh -i ~/.ssh/id_ed25519 USER@SERVER_IPIf you only have the root account, create an administrator first and repeat the key copy for it:
adduser admin
usermod -aG sudo adminStep 2: turn off password sign-in
How Ubuntu reads SSH settings
/etc/ssh/sshd_configincludes every.conffile in/etc/ssh/sshd_config.d/at the top, so those files override the main file.- For each setting, the first value OpenSSH reads wins. Between the included files, the one whose name sorts first wins.
- Ubuntu installs can contain
/etc/ssh/sshd_config.d/50-cloud-init.confwithPasswordAuthentication yes. Cloud images set up with cloud-init'sssh_pwauth: truehave it, and so do some 24.04 installs from the ISO image. Because it is read before the main file, it overrides aPasswordAuthentication noyou put there.
See what is set where:
sudo grep -ri -e passwordauthentication -e permitrootlogin /etc/ssh/sshd_config /etc/ssh/sshd_config.d/Write the settings in a file that is read first
Create /etc/ssh/sshd_config.d/00-hardening.conf. The 00- prefix makes it sort before 50-cloud-init.conf:
sudo nano /etc/ssh/sshd_config.d/00-hardening.confPasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
PermitRootLogin no
MaxAuthTries 3
X11Forwarding no
AllowUsers admin- Change
admininAllowUsersto your administrator's user name, or leave that line out. Any account not listed is refused. - Use
PermitRootLogin prohibit-passwordinstead ofnoif a backup or automation tool must log in as root with a key. On Ubuntu 24.04,sshd -Tprints that value aswithout-password, its older name. MaxAuthTries 3counts every key your computer offers: in a test, a computer that offered three other keys before the right one was disconnected withToo many authentication failures. If you hold several keys, name the right one, as inssh -o IdentitiesOnly=yes -i ~/.ssh/id_ed25519 USER@SERVER_IP, or leave the line out.
Test, apply and confirm
sudo sshd -t
sudo sshd -T | grep -Ei '^(port|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|permitrootlogin|maxauthtries|allowusers) '
sudo systemctl restart sshsshd -t checks the files for errors and prints nothing when they are valid. If it prints an error, fix the file before you restart: Ubuntu's SSH service runs the same check when it starts, and does not start while the check fails. sshd -T prints the settings that will actually apply. Restarting the SSH service does not drop sessions that are already open.
From a second terminal, confirm that password sign-in is refused and your key still works:
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=keyboard-interactive,password USER@SERVER_IP
ssh USER@SERVER_IPThe first command should fail with "Permission denied (publickey)". If it asks for a password instead, password sign-in still works, usually through keyboard-interactive authentication: check KbdInteractiveAuthentication. The second command should log you in. See SSH password sign-in for every case.
Step 3: move SSH off port 22 (optional)
A different port does not make SSH more secure, but it cuts the volume of automated login attempts in your logs. If you do it, open the new port in the firewall first.
sudo ufw allow 2222/tcp comment 'SSH'Add the port to your hardening file:
Port 2222How you apply it depends on the release:
- Ubuntu 24.04: SSH is started by systemd socket activation, which Ubuntu introduced in 22.10, and on 24.04 a generator turns the
Portsetting into the socket's configuration. Reload systemd and restart the socket:
sudo sshd -t
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket- Ubuntu 22.04: SSH runs as an ordinary service:
sudo sshd -t
sudo systemctl restart sshCheck that the new port is listening, then log in on it from a second terminal before you close anything:
sudo ss -tlnp | grep -E ':(22|2222)\b'ssh -p 2222 USER@SERVER_IPOnly then remove the old rule (Step 4 shows how to list rules by number).
Note If you created an ssh.socket override before
Older advice for Ubuntu 22.10 and 23.04 was to edit the socket with systemctl edit ssh.socket. On 24.04 the generator reads the port from the SSH configuration, so an old override can conflict with it. Check with systemctl cat ssh.socket.
Step 4: firewall rules with UFW
Set the defaults, allow SSH and the web ports, then turn the firewall on. The commands in this step use port 2222 from Step 3. If SSH is still on port 22, write 22 in place of 2222: otherwise the firewall blocks new SSH connections as soon as it is on.
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit 2222/tcp comment 'SSH'
sudo ufw allow 80,443/tcp comment 'Web'
sudo ufw enable
sudo ufw status verboselimitrefuses an address that opens 6 or more connections within 30 seconds, which slows down password-guessing tools.- If you only ever connect from known addresses, allow SSH from those alone and drop the general rule:
sudo ufw allow from 203.0.113.0/24 to any port 2222 proto tcp comment 'SSH from office'- UFW checks rules in order and uses the first match. List them by number, and delete one by its number:
sudo ufw status numbered
sudo ufw delete RULE_NUMBER- IPv6 is covered as long as
IPV6=yesis set in/etc/default/ufw, which is the Ubuntu default.
Warning Docker bypasses UFW
Ports published by Docker are routed before UFW's rules see them, so a container published on 0.0.0.0 is reachable whatever UFW says. Publish containers on 127.0.0.1 or filter them in Docker's DOCKER-USER chain.
Step 5: stop services you do not use
Every listening service is something to keep patched. List what is listening and what is running:
sudo ss -tulpn
systemctl list-units --type=service --state=running
systemctl list-socketsFor each one you do not need, stop it and keep it from starting at boot:
sudo systemctl disable --now SERVICE_NAMECheck what a service is before disabling it with systemctl status SERVICE_NAME. Do not disable ssh, or the units for your firewall and your web server.
Step 6: check for failed units
systemctl --failed
journalctl -u UNIT_NAME -b --no-pager -n 50Fix the cause, then clear the failed state so the list is empty again:
sudo systemctl reset-failed UNIT_NAMEA unit that fails every day and is left that way hides the next failure: when the list is never empty, nobody notices a new entry.
Step 7: updates and restarts
- Ubuntu Server installs and runs
unattended-upgrades, which by default installs security updates every day. Confirm it is on:
cat /etc/apt/apt.conf.d/20auto-upgradesBoth lines should set the value to "1".
- Some updates, such as a new kernel, only take effect after a restart. Check whether one is waiting and which packages asked for it:
cat /var/run/reboot-required /var/run/reboot-required.pkgs 2>/dev/null- On 24.04,
needrestartautomatically restarts services affected by a library update, including during unattended upgrades. To keep a service from being restarted, Ubuntu's documentation says to set its$nrconf{override_rc}entry to0in a new file in/etc/needrestart/conf.d/rather than editingneedrestart.conf: see Silent failures on an Ubuntu server.
OpenSSH version numbers
The regreSSHion flaw, CVE-2024-6387, was fixed upstream in OpenSSH 9.8p1. Ubuntu backported the fix without changing the version number: 22.04 has it from package version 1:8.9p1-3ubuntu0.10 and 24.04 from 1:9.6p1-3ubuntu13.3. Check the package version rather than ssh -V:
dpkg-query -W openssh-serverThe same applies to later fixes: OpenSSH released 10.6 on 6 October 2026 and 10.6p2 on 5 November 2026, but Ubuntu ships the fixes in its own package versions. Follow Ubuntu's security notices.
Optional: Fail2ban
Fail2ban reads the SSH log and blocks addresses that fail to log in repeatedly. After installing it, confirm that its SSH jail is running:
sudo apt install fail2ban
sudo fail2ban-client status sshdIf you moved SSH to another port, tell Fail2ban in /etc/fail2ban/jail.local:
[sshd]
port = 2222Then run sudo systemctl restart fail2ban.
Checklist
- Key sign-in works for a non-root administrator.
sshd -Tshowspasswordauthentication no,kbdinteractiveauthentication noandpermitrootlogin no.- Password sign-in is refused when tested from another terminal.
- UFW is active with default deny incoming and only the ports you need.
- No Docker container is published on
0.0.0.0unless intended. - Unused services are disabled;
systemctl --failedis empty. - Unattended upgrades are on, and pending restarts are scheduled.
Quick lookups
One-line checks and fixes for the ports, files and settings in this guide, one page each.
Sources
- Ubuntu 24.04 release notes: SSH socket activation
- Ubuntu Discourse: sshd uses socket-based activation on 22.10 and later
- Launchpad bug 2069041: changing the SSH port on 24.04
- OpenBSD manual: sshd
- Ubuntu manual: sshd_config
- Launchpad bug 1873528: order of sshd_config.d files
- Ubuntu bug mail: bug 2088207, cloud-init enables SSH password authentication in an unexpected config file
- Launchpad bug 2049860, comment 15: 50-cloud-init.conf on a 22.04 cloud image
- Docker: packet filtering and firewalls
- Debian manual: ufw
- Canonical: best practices for updating Ubuntu
- Ubuntu Server documentation: automatic updates and needrestart
- Ubuntu security: CVE-2024-6387
- OpenSSH release notes