SaferComputing.com

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.

Published
Updated
Applies to
Ubuntu Server 22.04 LTS and 24.04 LTS

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:

Your own computer: Linux, macOS, or Windows PowerShell
ssh-keygen -t ed25519 -C "laptop-2026"

Copy the public key to the server:

Your own computer: Linux or macOS
ssh-copy-id -i ~/.ssh/id_ed25519.pub USER@SERVER_IP

Windows does not include ssh-copy-id; this does the same job:

Your own computer: Windows PowerShell
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:

Your own computer
ssh -i ~/.ssh/id_ed25519 USER@SERVER_IP

If you only have the root account, create an administrator first and repeat the key copy for it:

Ubuntu, as root
adduser admin
usermod -aG sudo admin

Step 2: turn off password sign-in

How Ubuntu reads SSH settings

  • /etc/ssh/sshd_config includes every .conf file 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.conf with PasswordAuthentication yes. Cloud images set up with cloud-init's ssh_pwauth: true have it, and so do some 24.04 installs from the ISO image. Because it is read before the main file, it overrides a PasswordAuthentication no you put there.

See what is set where:

Ubuntu
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:

Ubuntu
sudo nano /etc/ssh/sshd_config.d/00-hardening.conf
Contents of /etc/ssh/sshd_config.d/00-hardening.conf
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
PermitRootLogin no
MaxAuthTries 3
X11Forwarding no
AllowUsers admin
  • Change admin in AllowUsers to your administrator's user name, or leave that line out. Any account not listed is refused.
  • Use PermitRootLogin prohibit-password instead of no if a backup or automation tool must log in as root with a key. On Ubuntu 24.04, sshd -T prints that value as without-password, its older name.
  • MaxAuthTries 3 counts every key your computer offers: in a test, a computer that offered three other keys before the right one was disconnected with Too many authentication failures. If you hold several keys, name the right one, as in ssh -o IdentitiesOnly=yes -i ~/.ssh/id_ed25519 USER@SERVER_IP, or leave the line out.

Test, apply and confirm

Ubuntu
sudo sshd -t
sudo sshd -T | grep -Ei '^(port|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|permitrootlogin|maxauthtries|allowusers) '
sudo systemctl restart ssh

sshd -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:

Your own computer
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=keyboard-interactive,password USER@SERVER_IP
ssh USER@SERVER_IP

The 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.

Ubuntu
sudo ufw allow 2222/tcp comment 'SSH'

Add the port to your hardening file:

Add to /etc/ssh/sshd_config.d/00-hardening.conf
Port 2222

How 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 Port setting into the socket's configuration. Reload systemd and restart the socket:
Ubuntu 24.04
sudo sshd -t
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
  • Ubuntu 22.04: SSH runs as an ordinary service:
Ubuntu 22.04
sudo sshd -t
sudo systemctl restart ssh

Check that the new port is listening, then log in on it from a second terminal before you close anything:

Ubuntu
sudo ss -tlnp | grep -E ':(22|2222)\b'
Your own computer
ssh -p 2222 USER@SERVER_IP

Only 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.

Ubuntu
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 verbose
  • limit refuses 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:
Ubuntu
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:
Ubuntu
sudo ufw status numbered
sudo ufw delete RULE_NUMBER
  • IPv6 is covered as long as IPV6=yes is 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:

Ubuntu
sudo ss -tulpn
systemctl list-units --type=service --state=running
systemctl list-sockets

For each one you do not need, stop it and keep it from starting at boot:

Ubuntu
sudo systemctl disable --now SERVICE_NAME

Check 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

Ubuntu
systemctl --failed
journalctl -u UNIT_NAME -b --no-pager -n 50

Fix the cause, then clear the failed state so the list is empty again:

Ubuntu
sudo systemctl reset-failed UNIT_NAME

A 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:
Ubuntu
cat /etc/apt/apt.conf.d/20auto-upgrades

Both 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:
Ubuntu
cat /var/run/reboot-required /var/run/reboot-required.pkgs 2>/dev/null
  • On 24.04, needrestart automatically 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 to 0 in a new file in /etc/needrestart/conf.d/ rather than editing needrestart.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:

Ubuntu
dpkg-query -W openssh-server

The 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:

Ubuntu
sudo apt install fail2ban
sudo fail2ban-client status sshd

If you moved SSH to another port, tell Fail2ban in /etc/fail2ban/jail.local:

Contents of /etc/fail2ban/jail.local
[sshd]
port = 2222

Then run sudo systemctl restart fail2ban.

Checklist

  • Key sign-in works for a non-root administrator.
  • sshd -T shows passwordauthentication no, kbdinteractiveauthentication no and permitrootlogin 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.0 unless intended.
  • Unused services are disabled; systemctl --failed is 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