Skip to main content

First steps to secure an Ubuntu 24.04 VPS

Harden a fresh Ubuntu 24.04 VPS: sudo user, SSH keys with ssh.socket, ufw firewall, Fail2ban on journald, and unattended security updates.

Updated 9 min readMarkdown

Within minutes of bringing an Ubuntu 24.04 LTS VPS online with a public IPv4 address, automated scanners start trying passwords against port 22. Running a clean baseline before installing Docker, n8n, or any application closes that attack surface without locking yourself out.

Ubuntu 24.04 introduced a change that breaks older guides: OpenSSH uses systemd socket activation (ssh.socket) with BindIPv6Only=ipv6-only. Editing Port in sshd_config alone leaves port 22 active, and writing only ListenStream=2222 in a socket override binds IPv6 only and refuses every IPv4 connection. This walkthrough covers the complete baseline verified on Ubuntu 24.04.5 LTS (x86_64): a sudo user, key-only SSH via ssh.socket, ufw, fail2ban reading journald, and automatic security upgrades.

Baseline security layers on an Ubuntu 24.04 VPS: UFW blocking inbound traffic except SSH on port 2222, 80 and 443, Fail2ban reading journald with backend systemd, ssh.socket bound on IPv4 and IPv6, key-only OpenSSH and unattended-upgrades

Keep a second SSH session open while testing changes. Never close your existing terminal until you verify in a separate window that your new user can log in on the new port and run sudo. If you ever lose SSH access on a Nuvits Linux VPS, rescue mode in the control panel lets you recover, but testing in parallel avoids downtime.

1. Generate an Ed25519 SSH key on your workstation

If you ordered the VPS with your SSH public key already installed, skip straight to creating the deploy user. If you still log in with a root password, generate an Ed25519 key pair on your local machine (not on the VPS):

ssh-keygen -t ed25519 -C "ops@yourdomain.com"

Press Enter to accept the default path (~/.ssh/id_ed25519) and protect the private key with a strong passphrase. Your public key is saved at ~/.ssh/id_ed25519.pub.

2. Create a non-root sudo user

Connect to the VPS as root, create your operational user (deploy below), grant sudo, and copy your authorized public key with strict permissions:

adduser deploy
usermod -aG sudo deploy
install -d -m 700 -o deploy -g deploy /home/deploy/.ssh
install -m 600 -o deploy -g deploy /root/.ssh/authorized_keys /home/deploy/.ssh/authorized_keys

If /root/.ssh/authorized_keys does not exist yet (because you signed in with a password), paste your local ~/.ssh/id_ed25519.pub directly into /home/deploy/.ssh/authorized_keys and fix ownership (chown deploy:deploy) and mode (chmod 600).

Confirm that only deploy can read the file:

ls -la /home/deploy/.ssh/authorized_keys

Expected output:

-rw------- 1 deploy deploy 98 Nov 28 09:31 /home/deploy/.ssh/authorized_keys

Open a second terminal on your workstation and test both SSH login and sudo before changing anything else:

ssh deploy@YOUR_VPS_IP 'whoami && id -Gn && sudo whoami'

Proceed only after you see deploy and root (from sudo whoami) returned cleanly.

3. Harden OpenSSH and change the port via ssh.socket

Instead of editing /etc/ssh/sshd_config directly (which triggers merge prompts on openssh-server upgrades), create a drop-in configuration at /etc/ssh/sshd_config.d/99-hardening.conf:

PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
X11Forwarding no
AllowUsers deploy

Be careful with AllowUsers. Only listed usernames can sign in over SSH. If other team members or automation jobs need separate accounts, list every account on that same line (for example AllowUsers deploy backup).

Why Ubuntu 24.04 requires an ssh.socket override

Inspect the stock socket unit on Ubuntu 24.04 (cat /usr/lib/systemd/system/ssh.socket):

[Socket]
ListenStream=0.0.0.0:22
ListenStream=[::]:22
BindIPv6Only=ipv6-only
Accept=no
FreeBind=yes

Because systemd opens the socket with BindIPv6Only=ipv6-only, two mistakes break SSH port changes on Ubuntu 24.04 (see also the Ubuntu Server OpenSSH documentation):

  • Setting only Port 2222 in sshd_config: ssh.socket ignores it and keeps listening on port 22.
  • Setting only ListenStream=2222 in the ssh.socket override: because of BindIPv6Only=ipv6-only, systemd binds only [::]:2222 and refuses all IPv4 connections on port 2222.

The working override clears the inherited list with an empty ListenStream= and explicitly declares both IPv4 and IPv6. Create the drop-in (replace 2222 if you pick another port):

sudo mkdir -p /etc/systemd/system/ssh.socket.d
[Socket]
ListenStream=
ListenStream=0.0.0.0:2222
ListenStream=[::]:2222

Validate SSH configuration before restarting

Test syntax first. If you are running from a console before any SSH connection has triggered ssh.service, create /run/sshd first so sshd -t does not exit with Missing privilege separation directory: /run/sshd:

sudo install -d -m 755 /run/sshd
sudo sshd -t
sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|maxauthtries|x11forwarding|allowusers)'

The effective configuration must reflect every hardening directive:

maxauthtries 3
permitrootlogin no
pubkeyauthentication yes
passwordauthentication no
kbdinteractiveauthentication no
x11forwarding no
allowusers deploy

Check earlier drop-in files under /etc/ssh/sshd_config.d/. OpenSSH applies first match wins in alphabetical order. If your VPS image includes a file such as 50-cloud-init.conf setting PasswordAuthentication yes, remove or comment that line there (or name your drop-in 01-hardening.conf), and always verify with sudo sshd -T.

4. Enable the ufw firewall before switching ports

Allow your new SSH port (2222/tcp), plus HTTP (80/tcp) and HTTPS/HTTP3 (443) if you plan to host web services, before turning on ufw and restarting ssh.socket (see the Ubuntu Server firewall guide):

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 2222/tcp comment 'SSH'
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443 comment 'HTTPS/HTTP3'
sudo ufw enable
sudo ufw status verbose

Answer y when ufw enable prompts for confirmation. Then reload systemd, restart ssh.socket, and verify that both IPv4 and IPv6 are listening on 2222:

sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
sudo ss -tlnp | grep -E ':(22|2222)\b'

Output recorded on Ubuntu 24.04.5 LTS:

LISTEN 0      4096         0.0.0.0:2222      0.0.0.0:*    users:(("systemd",pid=1,fd=53))
LISTEN 0      4096            [::]:2222         [::]:*    users:(("systemd",pid=1,fd=55))

In a new terminal on your local machine, verify all three checks before closing your original session:

# 1. Must succeed
ssh -p 2222 deploy@YOUR_VPS_IP 'whoami && sudo whoami'

# 2. Root must be refused even with a valid key
ssh -p 2222 root@YOUR_VPS_IP 'whoami'

# 3. Password login must be refused
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no -p 2222 deploy@YOUR_VPS_IP 'whoami'

In our test, deploy logged in over port 2222 immediately, root was disconnected, password login failed with Permission denied (publickey)., and old port 22 timed out under ufw.

Note if you run Docker on this VPS. Docker writes DNAT rules ahead of ufw whenever a container publishes a port without a bind address (ports: ["5432:5432"]). Bind internal databases, Redis, or admin UIs to 127.0.0.1: or keep them strictly on the internal Compose network. See Why Docker ports stay open with ufw.

5. Install and configure Fail2ban on journald

Changing the SSH port cuts generic scanner noise, but targeted probes still happen. Fail2ban automatically blocks IP addresses that rack up failed authentication attempts.

On Ubuntu 24.04, set backend = systemd and banaction = ufw explicitly in /etc/fail2ban/jail.local. Reading journald directly works on both minimal images without /var/log/auth.log and servers with rsyslog, and banaction = ufw keeps active bans visible inside ufw status:

sudo apt update
sudo apt install -y fail2ban

Create /etc/fail2ban/jail.local (never edit /etc/fail2ban/jail.conf, which package updates overwrite):

[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5
backend = systemd
banaction = ufw

[sshd]
enabled = true
port = 2222
mode = aggressive

If you connect from a static office or VPN address, add ignoreip = 127.0.0.1/8 ::1 YOUR_STATIC_IP under [DEFAULT] to prevent accidental self-bans. Enable and verify the jail:

sudo systemctl enable --now fail2ban
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

During testing with Fail2ban v1.0.2, sending 6 failed SSH authentication attempts from another host triggered an immediate ban and inserted a REJECT IN rule at the top of ufw:

Status for the jail: sshd
|- Filter
|  |- Currently failed:	0
|  |- Total failed:	15
|  `- Journal matches:	_SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned:	1
   |- Total banned:	1
   `- Banned IP list:	192.0.2.50

sudo ufw status numbered confirmed the live firewall block (shown with a documentation IP):

[ 1] Anywhere                   REJECT IN   192.0.2.50                 # by Fail2Ban after 5 attempts against sshd
[ 2] 2222/tcp                   ALLOW IN    Anywhere                   # SSH

If someone on your team gets banned by mistake, unban the address with:

sudo fail2ban-client set sshd unbanip 192.0.2.50

6. Turn on automatic security updates

Keeping kernel, OpenSSL, and base library security patches current prevents exposure to already-fixed vulnerabilities. Install unattended-upgrades and enable the daily job following the Ubuntu Server automatic updates documentation:

sudo apt install -y unattended-upgrades

Create or review /etc/apt/apt.conf.d/20auto-upgrades:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";

Run a dry-run check to confirm clean configuration and zero broken packages:

sudo unattended-upgrade --dry-run --debug | tail -n 10

When the system is healthy and up to date, the output ends with All upgrades installed and BrokenCount=0. Check /var/run/reboot-required (ls /var/run/reboot-required) periodically to know when a kernel patch calls for a planned reboot.

Final checklist before deploying workloads

Run this quick audit block before installing Docker or production services:

sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|allowusers)'
sudo ss -tlnp | grep -E ':(22|2222)\b'
sudo ufw status
sudo fail2ban-client status sshd

Once root and password logins show no, ssh.socket listens on both 0.0.0.0:2222 and [::]:2222, ufw is active with only required ports open, and the sshd jail is running in Fail2ban, your VPS baseline is ready.

Next steps


Originally published on the Nuvits blog.

No comments yet. Be the first to comment.