#!/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 ]
