A fresh cloud VM is reachable from the internet within seconds of booting, and automated scanners find it within minutes. Hardening is not one heroic configuration file; it is a short list of boring controls applied the same way every time, ideally by configuration management rather than by hand.

This is the baseline we apply to every new server, written for Ubuntu 24.04 LTS and RHEL 9 (and its rebuilds such as Rocky and AlmaLinux). Each section gives both distributions' commands and a way to verify the control actually took effect. Keep a second SSH session open while you change SSH or firewall settings, so a mistake does not lock you out.

1. Accounts and sudo

  • Create a named account per person. No shared admin or deploy logins for humans.

  • Grant sudo through the group: sudo on Ubuntu, wheel on RHEL.

  • Lock the root password if it is set: sudo passwd -l root.

  • Service accounts get no login shell (/usr/sbin/nologin) and no sudo.

sudo useradd -m -s /bin/bash -G sudo alice      # Ubuntu
sudo useradd -m -s /bin/bash -G wheel alice     # RHEL
sudo install -d -m 700 -o alice -g alice /home/alice/.ssh

2. SSH: keys only, and make it stick

Put your settings in a drop-in file rather than editing the main sshd_config. Both distributions include /etc/ssh/sshd_config.d/*.conf near the top of the main file, and for most options sshd uses the first value it reads. Cloud images often ship a drop-in such as 50-cloud-init.conf that sets PasswordAuthentication yes. Name your file so it sorts first:

# /etc/ssh/sshd_config.d/10-hardening.conf
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding no
AllowGroups sshusers

Create the sshusers group and add each person who needs SSH, or drop the AllowGroups line. Then validate and reload:

sudo sshd -t                                   # syntax check; silent means OK
sudo systemctl reload ssh                      # Ubuntu (unit name is ssh)
sudo systemctl reload sshd                     # RHEL
sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication)'

sshd -T prints the effective configuration after all includes, which is the only reliable way to confirm that no other drop-in overrides yours. Expected output is permitrootlogin no, passwordauthentication no and kbdinteractiveauthentication no.

On Ubuntu 24.04 sshd is socket-activated by default. If you change Port or ListenAddress, run sudo systemctl daemon-reload and sudo systemctl restart ssh.socket so the listening socket picks up the change. On RHEL, a non-standard port also needs an SELinux port label: sudo semanage port -a -t ssh_port_t -p tcp 2222.

Moving SSH to another port reduces log noise but is not a security control; keys-only authentication is.

3. Firewall: default deny inbound

Ubuntu uses ufw as a front end to nftables; RHEL uses firewalld. Use the distribution's tool rather than raw rules, so the next administrator finds what they expect.

Ubuntu (ufw):

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit OpenSSH            # allow SSH, rate-limit repeated connections
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

limit denies an address that opens six or more connections within 30 seconds, which takes the edge off brute-force attempts.

RHEL (firewalld):

sudo systemctl enable --now firewalld
sudo firewall-cmd --get-default-zone            # usually public
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --remove-service=cockpit   # if not used
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

--permanent writes the configuration; --reload applies it. Without --permanent, rules vanish on restart.

Restrict SSH to known sources where you can, either in the cloud security group or with a firewalld rich rule or ufw allow from 198.51.100.0/24 to any port 22. A cloud security group and a host firewall are complementary: the group protects against mistakes on the host, the host firewall protects against a mistake in the group.

Finally, check what is actually listening:

sudo ss -tulpn

Anything listening on 0.0.0.0 or [::] that you did not intend to expose should be bound to localhost or removed.

4. Automatic security updates

Most compromises use known, already-patched vulnerabilities. Apply security updates automatically and schedule reboots, rather than relying on someone to remember.

Ubuntu: unattended-upgrades is installed on server images. Confirm it is enabled and decide on reboots:

sudo dpkg-reconfigure -plow unattended-upgrades     # enables periodic runs
cat /etc/apt/apt.conf.d/20auto-upgrades
// /etc/apt/apt.conf.d/52-local-reboot
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:30";

Check what ran with sudo less /var/log/unattended-upgrades/unattended-upgrades.log, and whether a reboot is pending with ls /var/run/reboot-required.

RHEL: install dnf-automatic, apply security updates only, and enable the timer:

sudo dnf install -y dnf-automatic
sudo sed -i 's/^upgrade_type = .*/upgrade_type = security/; s/^apply_updates = .*/apply_updates = yes/' /etc/dnf/automatic.conf
sudo systemctl enable --now dnf-automatic.timer
systemctl list-timers dnf-automatic.timer
sudo dnf needs-restarting -r        # tells you if a reboot is needed

For fleets, stagger reboots across availability zones or use a livepatch service for kernel fixes, so automatic updates never take down every replica at once.

5. fail2ban for exposed services

With key-only SSH, brute force cannot succeed, but it still fills logs and wastes CPU. fail2ban bans addresses after repeated failures. It is in Ubuntu's main archive and in EPEL for RHEL.

sudo apt install -y fail2ban                     # Ubuntu
sudo dnf install -y fail2ban                     # RHEL family, after enabling EPEL
# /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled  = true
backend  = systemd
maxretry = 5
findtime = 10m
bantime  = 1h
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd

Never edit jail.conf directly; package upgrades overwrite it. Use .local files. Add jails for other exposed services, such as an nginx basic-auth location, with their own filters.

6. auditd: record who changed what

The Linux audit subsystem records security-relevant events in the kernel, independent of application logging. Install it (auditd on Ubuntu, audit is present on RHEL), then add watches for files that matter:

# /etc/audit/rules.d/50-baseline.rules
-w /etc/ssh/sshd_config -p wa -k sshd_config
-w /etc/ssh/sshd_config.d/ -p wa -k sshd_config
-w /etc/sudoers -p wa -k sudoers
-w /etc/sudoers.d/ -p wa -k sudoers
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/group -p wa -k identity
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=unset -k root_cmds
sudo augenrules --load
sudo auditctl -l                      # rules now active
sudo ausearch -k sshd_config -i       # who touched SSH config

The last rule logs every command run as root by a real logged-in user (their login UID survives sudo). It can be noisy on busy hosts; tune it, but keep the file watches. Ship audit logs off the host, because an attacker with root can delete local logs.

7. Reduce what is installed and running

systemctl list-unit-files --state=enabled --type=service
sudo apt purge telnetd rsh-server 2>/dev/null       # Ubuntu, if present
sudo dnf remove -y telnet-server rsh-server 2>/dev/null   # RHEL, if present

Disable anything you cannot name a reason for. Every listening service and every installed package is patching work and attack surface.

Keep time synchronised (chrony on RHEL, systemd-timesyncd or chrony on Ubuntu); accurate timestamps are essential for correlating logs during an investigation.

8. Keep mandatory access control on

RHEL ships SELinux in enforcing mode and Ubuntu ships AppArmor. Leave them on. When something breaks, read the denial and fix the label or policy; do not disable the framework.

getenforce                     # RHEL: Enforcing
sudo aa-status | head          # Ubuntu: profiles in enforce mode

9. Measure against a benchmark

The CIS Benchmarks are the common reference for hardening. Scan with the vendor tooling rather than writing your own checks:

# RHEL: OpenSCAP with the SCAP Security Guide content
sudo dnf install -y openscap-scanner scap-security-guide
sudo oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis_server_l1 \
  --report /tmp/cis-report.html /usr/share/xml/scap/ssg/content/ssg-rhel9-ds.xml

# Ubuntu: Ubuntu Security Guide (requires Ubuntu Pro, free for personal use)
sudo pro enable usg && sudo apt install -y usg
sudo usg audit cis_level1_server

Do not apply a benchmark's remediation blindly to a production server; some rules (for example mounting /tmp with noexec) break real software. Read the report, accept or document exceptions, and bake the accepted changes into your image or configuration management.

Common mistakes

Mistake

Why it hurts

Do this instead

Editing sshd_config only

A cloud-init drop-in wins

10- drop-in file, verify with sshd -T

Firewall rules without --permanent

Lost on reboot

--permanent then --reload

Updates enabled, reboots never

Kernel fixes never load

Scheduled reboots or livepatch

setenforce 0 to fix a denial

Removes a whole security layer

Fix labels and booleans

Hardening by hand

Drift between servers

Configuration management and golden images

Key takeaways

  • Key-only SSH, in a drop-in that sorts first, verified with sshd -T.

  • Default-deny inbound with ufw or firewalld, plus cloud security groups.

  • Automatic security updates are only half done without a reboot plan.

  • auditd watches on identity and SSH files give you a trail; ship it off host.

  • Keep SELinux or AppArmor enforcing and measure against CIS with OpenSCAP or USG.

References