Back to blog
linux

Linux server security checklist: 20 checks and an audit script

20 read-only checks to prove your Linux server is hardened, with a script to run them all.

Sandeep Sidhu

Sandeep Sidhu · Founder, AlertKick

21 min read
Linux server security checklist: 20 checks and an audit script

Most hardening guides stop at the apply step. You install the package, edit the config, and move on. Config can say one thing while the running daemon does another. Hardening decays: upgrades rewrite files, people re-enable password auth “temporarily”, and containers publish ports around the firewall. A hardening step you never verified is a guess.

This linux server security checklist covers the verify half. Four moves cover most real risk: SSH keys only with root login off, a default-deny firewall, automatic security patching, and something that notices drift. The 20 checks below each include the command that proves the setting is active, and a separate script runs all 20 in one go.

For exact install and config commands per distro, use the distro guides linked in the distro table below. The verify commands here are distro-neutral and run on Ubuntu, Debian, and RHEL-family systems.

The 20 checks at a glance

AreaChecks
AccessNamed admin user, SSH root login off, SSH passwords off
Network exposureDefault-deny firewall, What listens beyond loopback, Docker ports and the docker group
PatchingAutomatic security updates, Pending kernel reboot
Accounts, clock and kernel settingsEmpty passwords and extra UID 0, Synchronized clock, Kernel and network sysctls
Filesystem/tmp mount options, SUID files against a baseline, World-writable files in /etc
Logging, MAC and intrusion signalsauditd running, Persistent journal, SELinux or AppArmor enforcing, File integrity baseline, Brute-force response

Each link jumps to the command that proves the setting. To run all 20 in one go, use the audit script.

Exact commands by distro

The checks below are the same everywhere; the commands to fix a failing check differ, and the distro guides carry them.

Ubuntu 24.04Debian 13RHEL 9, Alma, Rocky
Admin groupsudosudo (minimal installs may lack the sudo package)wheel
SSH service namesshsshsshd
Firewall front-endufwnone preinstalled: ufw or nftablesfirewalld
Automatic updatesunattended-upgradesunattended-upgrades (often missing on minimal installs)dnf-automatic (off by default)
Mandatory access controlAppArmorAppArmorSELinux
auditdinstall itinstall itpreinstalled and running
/tmpon the root filesystemtmpfs with nosuid,nodevon the root filesystem
Full how-toUbuntu 24.04 checklistDebian 13 checklistRHEL 9 family checklist

Every verify command below runs on all three unless it is labelled with a distro. Run them as root or with sudo.

Access: admin user and SSH

Named admin user (admin-user)

A named account in the admin group (sudo or wheel) replaces logging in as root. Shared root credentials remove attribution; sudo writes one log line per privileged action. Prove the named user works before turning off root SSH, or you lock yourself out.

getent group sudo wheel

Expect your named admin user after the last colon. Empty after the colon means root is still the only admin.

SSH root login off (ssh-root-login)

Root is the one username every scanner already knows. PermitRootLogin no closes that door. prohibit-password (printed as without-password by sshd -T) still lets root in with a key.

The verify command reads the effective config from the daemon, not the file. Drop-ins in /etc/ssh/sshd_config.d/ and Match blocks can override the main file; sshd -T shows the result.

sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|permitemptypasswords) '

Expect permitrootlogin no.

SSH passwords off (ssh-passwords)

Password auth is the whole brute-force game; every public auth.log shows thousands of failed attempts. Keyboard-interactive can hand a password prompt to PAM even with PasswordAuthentication no, so check both. The auth.log analyzer shows what has been knocking.

Verify the effective config:

sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|permitemptypasswords) '

Expect no for passwordauthentication, kbdinteractiveauthentication and permitemptypasswords.

Second verify from outside, keep the current session open:

ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password,keyboard-interactive deploy@server

Expect Permission denied (publickey). A password prompt means the change did not take.

Network exposure: firewall, listening ports, containers

Default-deny firewall (firewall)

Inbound default deny blocks all traffic except ports explicitly allowed for the services the server runs. That makes every unexpected listener unreachable by default and turns a surprise port into an early warning rather than an incident.

Verify the firewall state using the tool installed on your distro:

sudo ufw status verbose                              # Ubuntu, Debian with ufw: Status: active, deny (incoming)
sudo firewall-cmd --state && sudo firewall-cmd --list-all   # RHEL family: running, then the allowed services
sudo nft list ruleset | grep 'hook input'            # plain nftables: an input chain with policy drop

RHEL systems often have the default public zone allowing cockpit and dhcpv6-client; --list-all shows them. Then scan from another machine: nmap -Pn your-server. The open set should match your intent exactly.

What listens beyond loopback (listeners)

Every TCP and UDP socket bound to a non-loopback address is attack surface. Anything only local processes use should bind to 127.0.0.1.

sudo ss -tulnp

Expect to name the purpose of every line bound to 0.0.0.0, [::] or a public address. A listener you cannot explain is a reason to stop and read the is my server hacked checklist before deleting anything.

Docker ports and the docker group (docker)

If Docker is present, published container ports and the docker group require attention. -p 8080:80 publishes on all interfaces and Docker’s own iptables rules let that traffic through regardless of ufw. Any member of the docker group is root-equivalent (docker run -v /:/host mounts the host filesystem).

docker ps --format '{{.Names}} {{.Ports}}'
getent group docker

Expect 127.0.0.1 binds, not 0.0.0.0 or [::]; group members you would also trust with sudo.

Patching: automatic updates and pending reboots

Automatic security updates (auto-updates)

Security updates install without anyone logging in. Most real compromises use vulnerabilities that already had a patch. This gives the highest protection per minute of effort on the list.

Verify (distro-specific):

apt-config dump APT::Periodic::Unattended-Upgrade    # Ubuntu, Debian: expect "1"
systemctl is-enabled dnf-automatic.timer             # RHEL family: expect enabled
grep apply_updates /etc/dnf/automatic.conf           # RHEL family: expect apply_updates = yes

Gotcha: on RHEL 9 family, dnf-automatic.timer with the stock config has apply_updates = no. It downloads updates and installs nothing. Tested on rockylinux:9.

Pending kernel reboot (reboot)

The running kernel is the newest installed one. A patched kernel on disk protects nothing while the old one runs. A pending reboot is a task with a deadline.

Verify (any distro):

uname -r
ls /boot/vmlinuz-*

Expect the running version to match the newest file in /boot. Also, /run/reboot-required exists on Ubuntu when a reboot is pending; dnf needs-restarting -r answers the same question on the RHEL family.

Accounts, clock and kernel settings

Empty passwords and extra UID 0 (empty-password, uid0)

No account should have an empty password field. Root is the only UID 0 account. An empty password field lets anyone in through any service that checks passwords. A second UID 0 account is root under another name and a classic backdoor.

sudo awk -F: '$2 == "" {print $1}' /etc/shadow
awk -F: '$3 == 0 {print $1}' /etc/passwd

Expect no output from the first, only root from the second. Lock accounts of people who left; lastlog shows who has logged in.

Synchronized clock (time-sync)

NTP sync must be active. Correlating a login on one box with a file change on another is guesswork if clocks disagree. PCI DSS and SOC 2 audits ask for synchronized time for this reason.

timedatectl show -p NTPSynchronized --value

Expect yes. On chrony hosts chronyc tracking should show Leap status: Normal.

Kernel and network sysctls (sysctl)

Eleven settings, read from the running kernel. ASLR (randomize_va_space=2) makes memory-corruption exploits unreliable. kptr_restrict and dmesg_restrict hide kernel addresses from unprivileged users. yama.ptrace_scope=1 stops a compromised process reading its neighbours’ memory. protected_symlinks and hardlinks block /tmp link tricks. syncookies blunt SYN floods. No redirects or source routing stops traffic steering.

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

Expect 2, 1 or more, 1, 1 or more, 1, 1, 1, then 0 for the four redirect and source-route keys. Exception: routers and some container hosts need redirects or forwarding; know why before you deviate. In all three test containers the kernel settings passed and net.ipv6.conf.all.accept_redirects was 1 (the kernel default).

Filesystem: /tmp, SUID files and /etc permissions

/tmp mount options (tmp-mount)

/tmp is world-writable by default. That is where dropped payloads land. Mount it separately with nosuid, nodev, and noexec. noexec stops a downloaded crypto miner from running in place. A few installers build helpers in /tmp; point TMPDIR elsewhere for that one command instead of dropping noexec.

findmnt -no OPTIONS /tmp

Expect nosuid, nodev and noexec in the list. No output means /tmp is not a separate mount. Debian 13 mounts /tmp as tmpfs with nosuid,nodev but not noexec; Ubuntu 24.04 and RHEL 9 keep /tmp on the root filesystem.

SUID files against a baseline (suid)

A SUID binary runs as its owner (usually root) whoever starts it. A new one is either a package update or persistence. The count alone tells you little; the diff tells you what changed.

sudo find / -xdev -type f -perm -4000 2>/dev/null | sort > /root/suid-baseline.txt    # once, on a known-good box
sudo find / -xdev -type f -perm -4000 2>/dev/null | sort | comm -13 /root/suid-baseline.txt -

Expect no output from the second command. Each line is a SUID file that was not there when you saved the baseline. The three test containers each had 10 SUID files.

World-writable files in /etc (world-writable)

One world-writable config file lets any account rewrite system behaviour.

sudo find /etc -xdev -type f -perm -0002

Expect no output.

Logging, MAC and intrusion signals

auditd running (auditd)

“Who ran what, when” is only answerable if the recorder ran beforehand. The kernel audit daemon (auditd) is preinstalled and running on RHEL family systems; you must install it on Ubuntu and Debian.

sudo auditctl -s | grep enabled

Expect enabled 1 (or 2, which means locked and also fine).

Persistent journal (journal)

A volatile journal loses the evidence the moment someone reboots the box. journald must keep logs on disk across reboots to survive a crash or forced restart.

ls -d /var/log/journal
journalctl --list-boots | head -n 3

Expect the directory to exist (with the default Storage=auto that makes the journal persistent) and more than one boot listed after a reboot.

SELinux or AppArmor enforcing (mac)

Mandatory access control contains a compromised service to what its policy allows. The common mistake is turning the whole thing off to silence one denial; fix the denial instead (the RHEL guide shows how).

getenforce                  # RHEL family: Enforcing
sudo aa-status | head -n 4  # Ubuntu, Debian: profiles in enforce mode

Expect Enforcing on RHEL, or profiles listed in enforce mode on Ubuntu/Debian.

File integrity baseline (fim)

The checks above define a known-good state; a File Integrity Monitoring (FIM) tool tells you when it changed (sshd_config, /etc/passwd, a new binary). Scheduled-scan limits and the eBPF alternative: AIDE vs Tripwire vs eBPF.

sudo ls /var/lib/aide/

Expect aide.db (Debian, Ubuntu) or aide.db.gz (RHEL family). A FIM that never caught a planted test change is untested.

Brute-force response (brute-force)

fail2ban (or similar) matters where password logins exist. With SSH passwords off there is nothing to brute-force, so fail2ban is optional for SSH; it still matters for mail or web logins. A jail reading an empty log file on a journal-only system does nothing; such systems need backend = systemd.

sudo fail2ban-client status sshd

Expect a non-zero Total failed on any internet-facing host. Zero on a public box means it reads the wrong log.

Run every check at once

The script runs the verify step of all 20 checks above and prints one line per check: PASS, WARN or FAIL plus a reason. It is read-only: no writes, no installs, no network calls. It uses POSIX sh, so it works with dash (Ubuntu, Debian /bin/sh) and bash (RHEL /bin/sh). Read it before you run it.

Download and run:

curl -fsSLO https://alertkick.com/tools/linux-security-checklist-audit.sh
less linux-security-checklist-audit.sh
sudo sh linux-security-checklist-audit.sh

Optional SUID diff: sudo SUID_BASELINE=/root/suid-baseline.txt sh linux-security-checklist-audit.sh.

Exit code 0 when nothing FAILs, 1 otherwise, so cron or CI can act on it.

Without root, checks that need root (sshd -T, /etc/shadow, firewall state, full find) print WARN instead of guessing. WARN means look at it, not necessarily wrong (for example a listener that is intended, a missing baseline).

Tested in docker containers ubuntu:24.04, debian:trixie and rockylinux:9 with only openssh-server and iproute installed and sshd started: Ubuntu 7 pass / 9 warn / 4 fail; Debian 6 / 10 / 4; Rocky 5 / 10 / 5. The four shared FAILs on stock images: SSH password auth on, no firewall, no automatic updates, no auditd. Containers are not servers: no /boot kernel, no time sync daemon, AppArmor of the host.

Sample output from the stock ubuntu:24.04 container:

host 81e0eea80582 | Ubuntu 24.04.5 LTS | kernel 7.0.0-43-generic | uid 0

PASS  admin-user      sudo/wheel members: ubuntu
WARN  ssh-root-login  PermitRootLogin without-password: root can still log in with a key
FAIL  ssh-passwords   PasswordAuthentication yes, KbdInteractiveAuthentication no
FAIL  firewall        no default-deny inbound policy found (ufw, firewalld, nftables, iptables)
PASS  listeners       only sshd listens beyond loopback: tcp/22(sshd)
PASS  docker          docker not installed
FAIL  auto-updates    unattended-upgrades missing or APT::Periodic::Unattended-Upgrade is not "1"
WARN  reboot          no kernel in /boot to compare with running 7.0.0-43-generic
PASS  empty-password  no account has an empty password field
PASS  uid0            only root has UID 0
WARN  time-sync       no answer from timedatectl or chronyc
WARN  sysctl          differs: net.ipv6.conf.all.accept_redirects=1(want 0)
WARN  tmp-mount       /tmp is not a separate mount, so it cannot carry nosuid,nodev,noexec
WARN  suid            10 SUID files, no baseline to diff (set SUID_BASELINE, see the post)
PASS  world-writable  no world-writable files in /etc
FAIL  auditd          auditd is not running
PASS  journal         /var/log/journal exists (Storage=auto)
WARN  mac             AppArmor enabled, profile list not readable (needs root on the host)
WARN  fim             no AIDE database found (if another FIM tool runs here, check that instead)
WARN  brute-force     fail2ban not running while SSH accepts passwords

7 pass, 9 warn, 4 fail

The full script (download):

#!/bin/sh
# linux-security-checklist-audit.sh - read-only audit for the
# Linux server security checklist: https://alertkick.com/blog/linux-server-security-checklist/
#
# Runs the verify step of every check and prints PASS, WARN or FAIL with a
# one-line reason. It changes nothing, installs nothing and makes no network
# calls. Works on Ubuntu, Debian and RHEL-family (RHEL, Alma, Rocky).
#
#   sudo sh linux-security-checklist-audit.sh
#   sudo SUID_BASELINE=/root/suid-baseline.txt sh linux-security-checklist-audit.sh
#
# Exit code: 0 when nothing FAILs, 1 otherwise (handy for cron).

PATH=/usr/sbin:/usr/bin:/sbin:/bin:$PATH
LC_ALL=C
export PATH LC_ALL
pass=0 warn=0 fail=0 pa="" ki=""

out() { # STATUS check-id reason
  printf '%-4s  %-15s %s\n' "$1" "$2" "${3% }"
  case $1 in
    PASS) pass=$((pass + 1)) ;;
    WARN) warn=$((warn + 1)) ;;
    FAIL) fail=$((fail + 1)) ;;
  esac
}
have() { command -v "$1" >/dev/null 2>&1; }
running() { grep -qsx "$1" /proc/[0-9]*/comm; }
isroot() { [ "$(id -u)" -eq 0 ]; }

os=$(. /etc/os-release 2>/dev/null && echo "$PRETTY_NAME")
echo "host $(uname -n) | ${os:-unknown OS} | kernel $(uname -r) | uid $(id -u)"
isroot || echo "not root: checks that read root-only state will WARN"
echo

# 1. Named admin user
admins=$(getent group sudo wheel 2>/dev/null | awk -F: '$4 != "" { gsub(",", " ", $4); printf "%s ", $4 }' | sed 's/ $//')
if [ -n "$admins" ]; then out PASS admin-user "sudo/wheel members: $admins"
else out WARN admin-user "sudo/wheel group is empty: root is the only admin"; fi

# 2-3. SSH effective config
if have sshd; then
  if ! isroot; then
    out WARN ssh "sshd -T needs root"
  elif cfg=$(sshd -T 2>&1); then
    v() { printf '%s\n' "$cfg" | awk -v k="$1" '$1 == k { print $2; exit }'; }
    r=$(v permitrootlogin)
    case $r in
      no) out PASS ssh-root-login "PermitRootLogin no" ;;
      prohibit-password | without-password | forced-commands-only)
        out WARN ssh-root-login "PermitRootLogin $r: root can still log in with a key" ;;
      *) out FAIL ssh-root-login "PermitRootLogin $r" ;;
    esac
    pa=$(v passwordauthentication)
    ki=$(v kbdinteractiveauthentication)
    [ -n "$ki" ] || ki=$(v challengeresponseauthentication)
    if [ "$(v permitemptypasswords)" = yes ]; then
      out FAIL ssh-passwords "PermitEmptyPasswords yes"
    elif [ "$pa" = no ] && [ "$ki" = no ]; then
      out PASS ssh-passwords "PasswordAuthentication no, KbdInteractiveAuthentication no"
    else
      out FAIL ssh-passwords "PasswordAuthentication $pa, KbdInteractiveAuthentication $ki"
    fi
  else
    out WARN ssh "sshd -T failed: $(printf '%s\n' "$cfg" | head -n 1)"
  fi
else
  out PASS ssh "sshd not installed"
fi

# 4. Firewall: default-deny inbound
fw() {
  if have ufw && ufw status verbose 2>/dev/null | grep -q '^Status: active'; then
    if ufw status verbose | grep -Eq '(deny|reject) \(incoming\)'; then
      out PASS firewall "ufw active, default deny incoming"
    else out FAIL firewall "ufw active but default incoming is allow"; fi
    return
  fi
  if have firewall-cmd && [ "$(firewall-cmd --state 2>/dev/null)" = running ]; then
    out PASS firewall "firewalld running, zone $(firewall-cmd --get-default-zone): $(firewall-cmd --list-services)"
    return
  fi
  if have nft && nft list ruleset 2>/dev/null | grep -q 'hook input.*policy drop'; then
    out PASS firewall "nftables input chain has policy drop"; return
  fi
  if have iptables && iptables -S INPUT 2>/dev/null | grep -q '^-P INPUT DROP'; then
    out PASS firewall "iptables INPUT policy DROP"; return
  fi
  if isroot; then out FAIL firewall "no default-deny inbound policy found (ufw, firewalld, nftables, iptables)"
  else out WARN firewall "run as root to read firewall state"; fi
}
fw

# 5. What listens beyond loopback (multicast and link-local skipped)
if have ss; then
  pub=$(ss -Htulnp 2>/dev/null | awk '
    $5 ~ /^(127\.|\[::1\]|\[::ffff:127\.|22[4-9]\.|23[0-9]\.|\[ff|\[fe80)/ || $5 ~ /%lo:/ { next }
    { port = $5; sub(/.*:/, "", port)
      p = $7; sub(/^users:\(\("/, "", p); sub(/".*/, "", p); if (p == "") p = "?"
      print $1 "/" port "(" p ")" }' | sort -u)
  n=$(printf '%s\n' "$pub" | grep -c .)
  list=$(printf '%s\n' "$pub" | head -n 8 | tr '\n' ' ' | sed 's/ $//')
  [ "$n" -gt 8 ] && list="$list+$((n - 8)) more"
  if [ "$n" -eq 0 ]; then out PASS listeners "nothing listens beyond loopback"
  elif ! printf '%s\n' "$pub" | grep -qv '(sshd)$'; then out PASS listeners "only sshd listens beyond loopback: $list"
  else out WARN listeners "confirm each is intended: $list"; fi
else
  out WARN listeners "ss not found (iproute2)"
fi

# 6. Docker: published ports and the docker group
if have docker; then
  members=$(getent group docker | cut -d: -f4)
  if ports=$(docker ps --format '{{.Names}} {{.Ports}}' 2>/dev/null); then
    open=$(printf '%s\n' "$ports" | grep -E '0\.0\.0\.0:|\[::\]:|:::' | cut -d' ' -f1 | tr '\n' ' ')
    if [ -n "$open" ] || [ -n "$members" ]; then
      out WARN docker "ports on all interfaces: ${open:-none}; docker group (root-equivalent): ${members:-empty}"
    else out PASS docker "no container publishes on all interfaces, docker group empty"; fi
  else
    out WARN docker "docker ps failed (daemon down or no permission)"
  fi
else
  out PASS docker "docker not installed"
fi

# 7. Automatic security updates
if have apt-config; then
  if have unattended-upgrade && apt-config dump APT::Periodic::Unattended-Upgrade 2>/dev/null | grep -q '"1"'; then
    out PASS auto-updates "unattended-upgrades enabled"
  else
    out FAIL auto-updates "unattended-upgrades missing or APT::Periodic::Unattended-Upgrade is not \"1\""
  fi
elif have dnf; then
  timers=$(ls /etc/systemd/system/timers.target.wants/ 2>/dev/null | grep '^dnf-automatic')
  case " $(echo $timers) " in
    *" dnf-automatic-install.timer "*) out PASS auto-updates "dnf-automatic-install.timer enabled" ;;
    *" dnf-automatic.timer "*)
      if grep -Eq '^[[:space:]]*apply_updates[[:space:]]*=[[:space:]]*(yes|true|1)' /etc/dnf/automatic.conf 2>/dev/null; then
        out PASS auto-updates "dnf-automatic.timer enabled, apply_updates = yes"
      else out WARN auto-updates "dnf-automatic.timer enabled but apply_updates is not yes (downloads only)"; fi ;;
    "  ") out FAIL auto-updates "no dnf-automatic timer enabled" ;;
    *) out WARN auto-updates "only $(echo $timers) enabled: updates are not installed" ;;
  esac
else
  out WARN auto-updates "neither apt nor dnf found"
fi

# 8. Pending kernel reboot
rk=$(uname -r)
nk=$(ls /boot 2>/dev/null | sed -n 's/^vmlinuz-//p' | grep -v rescue | sort -V | tail -n 1)
if [ -e /run/reboot-required ]; then out WARN reboot "/run/reboot-required is present"
elif [ -z "$nk" ]; then out WARN reboot "no kernel in /boot to compare with running $rk"
elif [ "$nk" = "$rk" ]; then out PASS reboot "running the newest installed kernel ($rk)"
else out WARN reboot "running $rk, newest installed is $nk"; fi

# 9-10. Accounts: empty passwords, extra UID 0
if [ -r /etc/shadow ]; then
  e=$(awk -F: '$2 == "" { printf "%s ", $1 }' /etc/shadow)
  if [ -n "$e" ]; then out FAIL empty-password "empty password field: $e"
  else out PASS empty-password "no account has an empty password field"; fi
else
  out WARN empty-password "run as root to read /etc/shadow"
fi
u=$(awk -F: '$3 == 0 && $1 != "root" { printf "%s ", $1 }' /etc/passwd)
if [ -n "$u" ]; then out FAIL uid0 "UID 0 besides root: $u"
else out PASS uid0 "only root has UID 0"; fi

# 11. Time sync
s=$(timedatectl show -p NTPSynchronized --value 2>/dev/null)
if [ "$s" = yes ]; then out PASS time-sync "clock synchronized (timedatectl)"
elif [ "$s" = no ]; then out FAIL time-sync "timedatectl: NTPSynchronized=no"
elif chronyc tracking 2>/dev/null | grep -q '^Leap status *: Normal'; then out PASS time-sync "chrony tracking, leap status normal"
else out WARN time-sync "no answer from timedatectl or chronyc"; fi

# 12. Kernel and network sysctls (values from the running kernel)
bad=""
want() { # key op value
  f=/proc/sys/$(echo "$1" | tr . /)
  [ -r "$f" ] || return 0
  val=$(cat "$f")
  case $2 in
    eq) [ "$val" = "$3" ] || bad="$bad $1=$val(want $3)" ;;
    ge) [ "$val" -ge "$3" ] 2>/dev/null || bad="$bad $1=$val(want >=$3)" ;;
  esac
}
want kernel.randomize_va_space eq 2
want kernel.kptr_restrict ge 1
want kernel.dmesg_restrict eq 1
want kernel.yama.ptrace_scope ge 1
want fs.protected_symlinks eq 1
want fs.protected_hardlinks eq 1
want net.ipv4.tcp_syncookies eq 1
want net.ipv4.conf.all.accept_redirects eq 0
want net.ipv4.conf.all.send_redirects eq 0
want net.ipv4.conf.all.accept_source_route eq 0
want net.ipv6.conf.all.accept_redirects eq 0
if [ -z "$bad" ]; then out PASS sysctl "all 11 kernel and network settings as expected"
else out WARN sysctl "differs:$bad"; fi

# 13. /tmp mount options
o=$(awk '$2 == "/tmp" { o = $4 } END { print o }' /proc/self/mounts)
if [ -z "$o" ]; then
  out WARN tmp-mount "/tmp is not a separate mount, so it cannot carry nosuid,nodev,noexec"
else
  miss=""
  for x in nosuid nodev noexec; do
    case ",$o," in *",$x,"*) ;; *) miss="$miss $x" ;; esac
  done
  if [ -z "$miss" ]; then out PASS tmp-mount "/tmp mounted nosuid,nodev,noexec"
  elif [ "$miss" = " noexec" ]; then out WARN tmp-mount "/tmp has nosuid,nodev but not noexec"
  else out FAIL tmp-mount "/tmp is missing:$miss"; fi
fi

# 14. SUID inventory against a baseline
if isroot; then
  suid=$(find / -xdev -type f -perm -4000 2>/dev/null | sort)
  n=$(printf '%s\n' "$suid" | grep -c .)
  if [ -n "${SUID_BASELINE:-}" ] && [ -r "$SUID_BASELINE" ]; then
    new=$(printf '%s\n' "$suid" | grep -vxF -f "$SUID_BASELINE" | tr '\n' ' ')
    if [ -z "$new" ]; then out PASS suid "$n SUID files, none outside $SUID_BASELINE"
    else out FAIL suid "SUID files not in baseline: $new"; fi
  else
    out WARN suid "$n SUID files, no baseline to diff (set SUID_BASELINE, see the post)"
  fi
else
  out WARN suid "run as root to search the whole filesystem"
fi

# 15. World-writable files in /etc
ww=$(find /etc -xdev -type f -perm -0002 2>/dev/null | tr '\n' ' ')
if [ -n "$ww" ]; then out FAIL world-writable "world-writable in /etc: $ww"
else out PASS world-writable "no world-writable files in /etc"; fi

# 16. auditd
if running auditd; then
  if isroot && have auditctl && st=$(auditctl -s 2>/dev/null); then
    case $(printf '%s\n' "$st" | awk '$1 == "enabled" { print $2 }') in
      1 | 2) out PASS auditd "auditd running, auditing enabled" ;;
      *) out FAIL auditd "auditd running but auditing is disabled (auditctl -s)" ;;
    esac
  else out PASS auditd "auditd running"; fi
else
  out FAIL auditd "auditd is not running"
fi

# 17. Persistent journal
if have journalctl; then
  stor=$(cat /etc/systemd/journald.conf /usr/lib/systemd/journald.conf.d/*.conf \
    /etc/systemd/journald.conf.d/*.conf 2>/dev/null | sed -n 's/^[[:space:]]*Storage=//p' | tail -n 1)
  case ${stor:-auto} in
    persistent) out PASS journal "Storage=persistent" ;;
    volatile | none) out FAIL journal "Storage=$stor: logs are lost on reboot" ;;
    *) if [ -d /var/log/journal ]; then out PASS journal "/var/log/journal exists (Storage=${stor:-auto})"
       else out FAIL journal "no /var/log/journal: the journal is volatile"; fi ;;
  esac
else
  out WARN journal "journalctl not found"
fi

# 18. SELinux or AppArmor enforcing
if [ -r /sys/fs/selinux/enforce ]; then
  if [ "$(cat /sys/fs/selinux/enforce)" = 1 ]; then out PASS mac "SELinux enforcing"
  else out FAIL mac "SELinux is permissive"; fi
elif [ "$(cat /sys/module/apparmor/parameters/enabled 2>/dev/null)" = Y ]; then
  if n=$(grep -c '(enforce)' /sys/kernel/security/apparmor/profiles 2>/dev/null) || [ "$n" = 0 ]; then
    if [ "$n" -gt 0 ]; then out PASS mac "AppArmor enabled, $n profiles in enforce mode"
    else out WARN mac "AppArmor enabled but no profile is in enforce mode"; fi
  else
    out WARN mac "AppArmor enabled, profile list not readable (needs root on the host)"
  fi
else
  out FAIL mac "neither SELinux nor AppArmor is active"
fi

# 19. File integrity baseline (AIDE)
db=$(ls /var/lib/aide/aide.db /var/lib/aide/aide.db.gz 2>/dev/null | head -n 1)
if [ -n "$db" ]; then out PASS fim "AIDE database at $db"
else out WARN fim "no AIDE database found (if another FIM tool runs here, check that instead)"; fi

# 20. Brute-force response
if running fail2ban-server; then out PASS brute-force "fail2ban running"
elif [ "$pa" = no ] && [ "$ki" = no ]; then out PASS brute-force "fail2ban not running; optional because SSH passwords are off"
elif [ "$pa" = yes ] || [ "$ki" = yes ]; then out WARN brute-force "fail2ban not running while SSH accepts passwords"
else out WARN brute-force "fail2ban not running and SSH password auth is not confirmed off"; fi

echo
echo "$pass pass, $warn warn, $fail fail"
[ "$fail" -eq 0 ]

Checks no script can run for you

The audit script reads local state; these checks need another machine, a restore, or a person.

Logs off the box

An attacker with root edits local logs. Forward with rsyslog or an agent. Verify: logger "offbox-test-$(hostname)-$(date +%s)" then find that string on the log host.

Backups you have restored

At least one copy the server cannot delete (pull-based or object-lock storage), and a restore you ran yourself. Verify by restoring to a scratch path and diffing against the live files. Put a heartbeat on the backup job so a silent failure is noticed.

TLS and headers from outside

Check from outside with the SSL checker and the security headers checker. Certificate expiry belongs in monitoring because renewal automation fails silently.

Alerts on change, not just downtime

Uptime checks say the box is up, not that it is still yours. Events worth a page: a new listening port, an SSH login from a new address, a system binary changing, a rootkit indicator.

Re-audit on a schedule

Hardening decays: upgrades rewrite configs, people re-enable password auth “temporarily”. Run the audit script from cron monthly; exit code 1 means something FAILed.

AlertKick’s eBPF agent watches the controls above continuously: SSH logins, new listening ports, file integrity, config drift, and pages you when reality diverges from the checklist. Install takes about a minute, and the free tier needs no card. Harden the box with the list above, then put a watcher on the hardening.

Frequently asked questions

What is the first thing to do to secure a Linux server?
Create a named admin user in the sudo or wheel group, disable root SSH login, enable a default-deny firewall, and turn on automatic security updates. These four moves cover most real risk.
How do I check if my Linux server is secure?
Run the individual verify commands for each check, such as `sshd -T` for SSH settings or `ss -tulnp` for listening ports. Alternatively, download and run the provided audit script to check all 20 items at once. The script prints PASS, WARN, or FAIL for each check with a one-line reason.
Is the audit script safe to run on production?
Yes, the script is read-only and makes no network calls or installs. It uses POSIX sh and works with dash or bash. You should read the script before running it to verify its behavior.
Should I change the default SSH port?
Changing the SSH port is noise reduction, not a security control. It does not prevent targeted attacks or brute-force attempts. Focus on disabling root login and password authentication instead.
Do I still need fail2ban if password authentication is off?
Fail2ban is optional for SSH if password authentication is off, as there is nothing to brute-force. It remains useful for other services that accept password logins, such as mail or web applications.
Should I disable SELinux or AppArmor?
No, do not disable mandatory access control to silence denials. Instead, fix the specific denial by updating the policy. Turning off SELinux or AppArmor removes a layer of defense that contains compromised services.
linux security checklist hardening ssh