Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Security

Linux server hardening: audit what you already run

A Linux server hardening audit with commands: effective SSH settings, accounts and sudo, listening services, pending restarts, systemd sandboxing and Lynis.

CloudSat teamNovember 18, 20267 min read
Abstract illustration of a magnifying lens sweeping across stacked server layers, each layer lighting up with a small check mark
On this page1. What sshd really uses

Hardening checklists tell you what to change. On a server that has been running for months, the more useful question is what is actually in effect right now: config files get overridden, packages add services, and "temporary" accounts stay. This audit takes an afternoon. Each section gives a command that checks one area and the fix if the answer is wrong. It assumes the basics are in place (automatic updates, a host firewall, key-based SSH) and looks for what slips through.

Run everything with sudo from an account you are sure of, keep a second session open, and take a snapshot before you fix anything.

1. What sshd really uses

Config files can contradict each other, and drop-ins in /etc/ssh/sshd_config.d/ are read in name order. sshd -T prints the settings the daemon will actually apply:

sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|x11forwarding|allowtcpforwarding|allowagentforwarding|maxauthtries|allowusers|allowgroups) '

Good answers: passwordauthentication no, permitrootlogin prohibit-password or no, x11forwarding no on a server without a desktop. If only a few people should ever log in, AllowGroups ssh-users limits SSH to one group, so a service account created by a package can never be used for a shell.

Then look at who holds keys:

sudo find /root /home -name authorized_keys -print -exec ssh-keygen -lf {} \;

The output prints each file, then one line per key with its fingerprint and comment. A key you cannot name belongs to someone who still has access. Remove its line.

2. Accounts that can log in

awk -F: '$7 !~ /(nologin|false)$/ {print $1, $7}' /etc/passwd
awk -F: '$3 == 0 {print $1}' /etc/passwd
getent group sudo wheel
sudo grep -rhE '^[^#].*NOPASSWD' /etc/sudoers /etc/sudoers.d/

The first line lists accounts with a real shell, the second every account with user ID 0 (it must print only root), the third who may use sudo, and the last any rule that grants root without a password. Lock accounts nobody uses with sudo usermod -L -e 1 olduser, which also expires them, or delete them with sudo userdel -r olduser once you are sure nothing runs as that user. Passwordless sudo belongs only to automation accounts that need it, scoped to the exact commands they run.

3. Services that listen

Every listening port is code reachable from somewhere:

sudo ss -tulpn
systemctl list-unit-files --type=service --state=enabled

For each port, ask whether it must be reachable from the internet, from other servers only, or only from the machine itself. Databases, caches and admin panels usually belong on 127.0.0.1 or a private interface. Disable what you do not use with sudo systemctl disable --now <unit> and remove the package, so an update cannot bring it back. Tracing each port to its process is covered in detail in check open and listening ports with ss and lsof.

4. Updates that installed but are not running

Automatic updates install new packages; they do not always replace the code in memory. A patched library stays vulnerable in every process that loaded the old copy, and a new kernel does nothing until a reboot.

uname -r                                  # running kernel
ls /boot/vmlinuz-*                        # installed kernels
cat /var/run/reboot-required 2>/dev/null  # Debian and Ubuntu flag
sudo needrestart -r l                     # services still using old libraries
sudo dnf needs-restarting -r              # RHEL family: is a reboot needed?

needrestart ships with Ubuntu Server and lists services to restart; -r l only lists them. Schedule a regular reboot window so kernel fixes actually take effect.

5. Sandbox your own services with systemd

Packages from the distribution usually come with some confinement. Services you wrote yourself, or installed from a tarball, usually come with none: they can read the whole file system and write anywhere their user can. systemd scores each unit:

systemd-analyze security
systemd-analyze security myapp.service

The overview rates every service from "OK" to "UNSAFE", and the detailed view lists each protection with its effect. Add the protections that fit with a drop-in, created by sudo systemctl edit myapp.service:

[Service]
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ReadWritePaths=/var/lib/myapp
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX

ProtectSystem=strict makes the whole file system read-only for the service except the paths in ReadWritePaths. ProtectHome=yes hides home directories. Restart the service and test it properly: a protection that blocks something the app needs shows up as a permission error in journalctl -u myapp. Add options one or two at a time.

6. Kernel and network settings

Current distributions set most of these well already, so check before you write anything:

sysctl net.ipv4.conf.all.accept_redirects net.ipv6.conf.all.accept_redirects \
  net.ipv4.conf.all.send_redirects net.ipv4.conf.all.accept_source_route \
  net.ipv4.tcp_syncookies kernel.kptr_restrict kernel.dmesg_restrict \
  fs.protected_hardlinks fs.protected_symlinks

On a server that does not route traffic, put any that differ into /etc/sysctl.d/90-hardening.conf and load them with sudo sysctl --system:

net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.tcp_syncookies = 1
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1

Leave forwarding alone on hosts that run Docker, a VPN or a router: they need it.

7. Mandatory access control is enforcing

AppArmor on Ubuntu and Debian, and SELinux on the RHEL family, confine services even when they run as root. Check that they are on and enforcing:

sudo aa-status | head -5     # Ubuntu and Debian
getenforce                   # RHEL, AlmaLinux, Rocky Linux

If SELinux was turned off to "fix" an app, the app most likely needed a file label or a boolean instead. SELinux on AlmaLinux and Rocky Linux shows how to find and fix the real cause.

8. Files that changed or should not exist

sudo find / -xdev -type f -perm -0002 2>/dev/null | head -20
sudo find / -xdev -type f \( -perm -4000 -o -perm -2000 \) 2>/dev/null
sudo dpkg --verify        # Debian and Ubuntu
sudo rpm -Va              # RHEL family

The first command finds world-writable files, the second set-user-ID and set-group-ID programs, which run with the rights of their owner or group rather than the caller's. Check each unfamiliar one with dpkg -S <path> or rpm -qf <path>: a SUID binary that belongs to no package needs an explanation. The last two compare installed files with the package checksums and list what was modified; changed config files are expected, changed binaries are not. For continuous checks, AIDE records hashes of system files and reports changes against that baseline.

9. Logs that outlive the server

An intruder with root can edit local logs. Send them somewhere else, and make sure the journal at least survives a reboot:

journalctl --disk-usage
ls -d /var/log/journal 2>/dev/null || echo "journal is not persistent"

If the journal is not persistent, set Storage=persistent in /etc/systemd/journald.conf and restart systemd-journald. For changes to sensitive files, an audit rule records who touched them, for example -w /etc/sudoers -p wa -k sudoers in /etc/audit/rules.d/sudoers.rules.

10. Cross-check with Lynis

Lynis runs hundreds of local checks and prints a list of suggestions with a hardening index. It is packaged for Debian and Ubuntu, and for the RHEL family through EPEL:

sudo apt install lynis
sudo lynis audit system

Read the Warnings first, then the Suggestions. Treat the score as a to-do list, not a target: some suggestions do not fit a given server, and the point is that each item is a decision rather than an accident.

When the audit finds something you cannot explain

An unknown key, account, SUID file or listening process means the server may already be compromised. Cleaning it in place is guesswork. Rebuild from a clean image and restore data from backups taken before the problem: on CloudSat, Rebuild reinstalls the operating system and keeps the server's IP addresses (Rebuild a server). Then rotate every key and password the old server held.

FAQ

How often should I run this audit?

Once after building the server, after any large change, and then every few months. Section 4 is worth a weekly look.

Will hardening make a server impossible to break into?

No setting does that. Hardening shrinks what an attacker can reach and what a compromised service can do. Prompt patching, monitoring and tested backups are the rest of the job.

Should I apply a full CIS Benchmark instead?

The CIS Benchmarks are a solid reference, especially where an auditor asks for one. Apply them selectively: a few items break common software, so test each change the same way you would test any other.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.