#!/bin/bash
# RootManage Security Audit for Linux servers.
#
#   READ-ONLY. It never changes a setting, never installs anything and never reads the content of your files.
#   It looks at settings and file permissions, then sends a list of findings (id, title, plain-language fix) to your RootManage dashboard.
#   It never sends passwords, keys, password hashes, file contents or logs. Where a finding names an account or a file, only the NAME is sent.
#   Low CPU: runs at the lowest priority, stops after 170 seconds, and the systemd timer caps it at 10% of one CPU.
#
#   rootmanage-audit --once       run the audit and send the result
#   rootmanage-audit --print      run the audit and print the result here, send nothing
#   rootmanage-audit --report     run the audit and show a readable report here, send nothing (no account needed)
#   rootmanage-audit --poll       ask RootManage whether you pressed "Run audit now" in the dashboard; runs the audit only if you did
#   rootmanage-audit --version
#
# You can read this whole file before you run it. Its SHA-256 is published next to it: <your-site>/agent/rootmanage-audit.sh.sha256
set -u
AUDIT_VERSION="1.2.0"
ENV_FILE="${ROOTMANAGE_ENV:-/etc/rootmanage/agent.env}"
STATE_DIR="/var/lib/rootmanage"
export LC_ALL=C PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

have() { command -v "$1" >/dev/null 2>&1; }
# --poll: one tiny HTTPS request that sends only the server token and gets back "run" or "do not run". The audit starts only if you pressed "Run audit now".
if [[ "${1:-}" == "--poll" ]]; then
  if [[ "$(id -u)" -ne 0 ]]; then echo "Run as root (sudo rootmanage-audit --poll)." >&2; exit 1; fi
  [[ -f "$ENV_FILE" ]] || exit 0
  # shellcheck disable=SC1090
  . "$ENV_FILE"
  [[ -n "${API_URL:-}" && -n "${ANON_KEY:-}" && -n "${AGENT_TOKEN:-}" ]] || exit 0
  case "$API_URL" in https://*) ;; *) exit 0 ;; esac
  have curl || exit 0
  umask 077
  ANSWER="$(printf '{"p_token":"%s"}' "$AGENT_TOKEN" | curl -sS --proto '=https' --tlsv1.2 -m 20 -X POST "${API_URL%/}/rest/v1/rpc/audit_poll" \
    -H "apikey: ${ANON_KEY}" -H "Authorization: Bearer ${ANON_KEY}" -H "Content-Type: application/json" --data-binary @- 2>/dev/null || true)"
  if grep -q '"run" *: *true' <<<"$ANSWER"; then
    unset ROOTMANAGE_AUDIT_CHILD
    exec bash "$(readlink -f "$0" 2>/dev/null || echo "$0")" --once
  fi
  exit 0
fi
# One call each, then plain text matching, so the audit starts very few programs.
ACTIVE_LIST=""; ENABLED_LIST=""
if have systemctl; then
  ACTIVE_LIST="$(systemctl list-units --type=service --type=timer --state=active --no-legend --plain --no-pager 2>/dev/null | awk '{print $1}')"
  ENABLED_LIST="$(systemctl list-unit-files --state=enabled --no-legend --plain --no-pager 2>/dev/null | awk '{print $1}')"
fi
active() { grep -qxF "$1.service" <<<"$ACTIVE_LIST" || grep -qxF "$1" <<<"$ACTIVE_LIST"; }
enabled() { grep -qxF "$1" <<<"$ENABLED_LIST" || grep -qxF "$1.service" <<<"$ENABLED_LIST"; }

# ---------- mode, and start again at the lowest priority with a time limit ----------
MODE="${1:---once}"
case "$MODE" in
  --version) echo "$AUDIT_VERSION"; exit 0 ;;
  --once|--print|--poll|--report) ;;
  *) echo "Usage: rootmanage-audit --once | --print | --report | --poll | --version" >&2; exit 1 ;;
esac
if [[ "$(id -u)" -ne 0 ]]; then echo "Run as root (sudo rootmanage-audit $MODE). The audit reads system settings that only root can see." >&2; exit 1; fi
if [[ "${ROOTMANAGE_AUDIT_CHILD:-}" != "1" ]]; then
  export ROOTMANAGE_AUDIT_CHILD=1
  PRE=""; have ionice && PRE="ionice -c3"
  SELF="$(readlink -f "$0" 2>/dev/null || echo "$0")"
  have timeout && exec timeout 170 nice -n 19 $PRE bash "$SELF" "$MODE"
  exec nice -n 19 $PRE bash "$SELF" "$MODE"
fi
STARTED="$(date +%s%3N 2>/dev/null || echo 0)"

# ---------- JSON helpers (plain bash, no jq or python needed) ----------
jesc() { printf '%s' "$1" | tr '\n\t\r' '   ' | tr -cd '\040-\176' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | cut -c1-500; }
FINDINGS=""; NFIND=0; TXT=""
plain() { printf '%s' "$1" | tr '\n\t\r|' '   /' | tr -cd '\040-\176' | cut -c1-400; }
add() { # id category severity status title detail fix [evidence]
  [[ "$NFIND" -ge 380 ]] && return 0
  FINDINGS+="${FINDINGS:+,}{\"id\":\"$1\",\"cat\":\"$2\",\"sev\":\"$3\",\"st\":\"$4\",\"t\":\"$(jesc "$5")\",\"d\":\"$(jesc "$6")\",\"f\":\"$(jesc "$7")\",\"e\":\"$(jesc "${8:-}")\"}"
  TXT+="$3|$4|$1|$(plain "$5")|$(plain "$7")"$'\n'
  NFIND=$((NFIND + 1))
}
join_first() { # join the first N lines of stdin with ", "
  head -n "${1:-5}" | paste -sd, - | sed 's/,/, /g'
}
count_lines() { grep -c . 2>/dev/null || echo 0; }

# ---------- host facts ----------
OS_ID="unknown"; OS_VER=""; OS_NAME="Linux"
if [[ -r /etc/os-release ]]; then
  OS_ID="$(. /etc/os-release; echo "${ID:-unknown}")"
  OS_VER="$(. /etc/os-release; echo "${VERSION_ID:-}")"
  OS_NAME="$(. /etc/os-release; echo "${PRETTY_NAME:-Linux}")"
fi
OS_ID="${OS_ID,,}"
case "$OS_ID" in
  ubuntu|debian|linuxmint|raspbian|kali|pop) FAMILY="debian" ;;
  rhel|centos|almalinux|rocky|ol|oraclelinux|fedora|amzn|cloudlinux|virtuozzo) FAMILY="rhel" ;;
  sles|opensuse*|suse) FAMILY="suse" ;;
  alpine) FAMILY="alpine" ;;
  arch|manjaro) FAMILY="arch" ;;
  *) FAMILY="other" ;;
esac
KERNEL="$(uname -r 2>/dev/null)"; ARCH="$(uname -m 2>/dev/null)"
VIRT="$(systemd-detect-virt 2>/dev/null || echo unknown)"
CORES="$(nproc 2>/dev/null || echo 1)"
MEM_MB="$(awk '/MemTotal:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)"
UPTIME_DAYS="$(awk '{print int($1/86400)}' /proc/uptime 2>/dev/null || echo 0)"
TODAY="$(date +%Y%m%d)"
HOSTNAME_S="$(hostname 2>/dev/null | cut -c1-60)"

# ---------- control panel detection ----------
PANELS=""; PANEL=""; PANEL_VER=""
panel_add() { PANELS+="${PANELS:+, }$1"; [[ -z "$PANEL" ]] && { PANEL="$1"; PANEL_VER="${2:-}"; }; return 0; }
[[ -f /usr/local/cpanel/version ]] && panel_add "cPanel/WHM" "$(head -c 40 /usr/local/cpanel/version 2>/dev/null | tr -d '\n')"
[[ -f /usr/local/psa/version ]] && panel_add "Plesk" "$(awk '{print $1}' /usr/local/psa/version 2>/dev/null | head -1)"
[[ -x /usr/local/directadmin/directadmin ]] && panel_add "DirectAdmin" "$(timeout 5 /usr/local/directadmin/directadmin v 2>/dev/null | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+' | head -1)"
[[ -d /usr/local/CyberCP ]] && panel_add "CyberPanel" "$(cat /usr/local/CyberCP/version.txt 2>/dev/null | head -c 20)"
{ [[ -d /home/clp ]] || have clpctl; } && panel_add "CloudPanel" ""
[[ -d /usr/local/hestia ]] && panel_add "HestiaCP" "$(grep -Eo "VERSION='[^']+'" /usr/local/hestia/conf/hestia.conf 2>/dev/null | head -1 | tr -d "VERSION='")"
{ [[ -d /etc/webmin/virtual-server ]] || have virtualmin; } && panel_add "Virtualmin" ""
[[ -f /etc/webmin/miniserv.conf ]] && panel_add "Webmin" "$(cat /etc/webmin/version 2>/dev/null | head -c 20)"
[[ -d /www/server/panel ]] && panel_add "aaPanel/BT" ""
[[ -d /usr/local/cwpsrv ]] && panel_add "CentOS Web Panel" ""
[[ -d /usr/local/ispconfig ]] && panel_add "ISPConfig" ""
[[ -d /etc/froxlor || -d /var/www/froxlor ]] && panel_add "Froxlor" ""
HAS_CPANEL=0; [[ "$PANELS" == *cPanel* ]] && HAS_CPANEL=1

# ---------- listening ports (one call, reused) ----------
SS_OUT=""
have ss && SS_OUT="$(timeout 10 ss -Hltn 2>/dev/null)"
listen_public() { # port -> 0 if listening on all interfaces
  awk -v p="$1" '{n=split($4,a,":"); port=a[n]; addr=substr($4,1,length($4)-length(port)-1); if (port==p && (addr=="0.0.0.0" || addr=="*" || addr=="[::]" || addr=="::")) found=1} END{exit found?0:1}' <<<"$SS_OUT"
}
listen_any() { awk -v p="$1" '{n=split($4,a,":"); if (a[n]==p) found=1} END{exit found?0:1}' <<<"$SS_OUT"; }

# =====================================================================
# 1. SYSTEM
# =====================================================================
add SYS-001 system info info "Server facts" "$OS_NAME, kernel $KERNEL, $ARCH, $VIRT. Up $UPTIME_DAYS days, $CORES CPU, ${MEM_MB} MB RAM." "" "${PANELS:-no control panel found}"

eol_os() { # prints the end-of-support date for this system, or nothing when unknown
  case "$OS_ID:$OS_VER" in
    ubuntu:14.04) echo 20190425 ;; ubuntu:16.04) echo 20210429 ;; ubuntu:18.04) echo 20230531 ;; ubuntu:20.04) echo 20250529 ;;
    ubuntu:22.04) echo 20270401 ;; ubuntu:24.04) echo 20290425 ;;
    debian:8*) echo 20180617 ;; debian:9*) echo 20220630 ;; debian:10*) echo 20240630 ;; debian:11*) echo 20260831 ;; debian:12*) echo 20280630 ;;
    centos:6*) echo 20201130 ;; centos:7*) echo 20240630 ;; centos:8*) echo 20211231 ;;
    rhel:7*|almalinux:7*|rocky:7*|ol:7*|cloudlinux:7*) echo 20240630 ;;
    rhel:8*|almalinux:8*|rocky:8*|ol:8*|cloudlinux:8*) echo 20290531 ;;
    rhel:9*|almalinux:9*|rocky:9*|ol:9*|cloudlinux:9*) echo 20320531 ;;
    rhel:10*|almalinux:10*|rocky:10*) echo 20350531 ;;
    amzn:2) echo 20260630 ;;
  esac
}
EOL="$(eol_os)"
if [[ -n "$EOL" ]]; then
  SOON="$(date -d "+180 days" +%Y%m%d 2>/dev/null || echo 99999999)"
  if [[ "$EOL" -le "$TODAY" ]]; then
    add UPD-004 updates critical fail "Operating system is no longer supported" "$OS_NAME reached the end of vendor support (about ${EOL:0:4}-${EOL:4:2}-${EOL:6:2}). It no longer gets normal security fixes." "Plan a move to a supported release. We can migrate the server for you." "$OS_NAME"
  elif [[ "$EOL" -le "$SOON" ]]; then
    add UPD-004 updates medium warn "Operating system support ends soon" "$OS_NAME is supported until about ${EOL:0:4}-${EOL:4:2}-${EOL:6:2}. Dates come from the vendor, so please check yours." "Plan the upgrade or migration before that date." "$OS_NAME"
  else
    add UPD-004 updates low pass "Operating system is still supported" "$OS_NAME is supported until about ${EOL:0:4}-${EOL:4:2}-${EOL:6:2}." "" "$OS_NAME"
  fi
else
  add UPD-004 updates low info "Operating system support date unknown" "The audit has no end-of-support date for $OS_NAME." "Check your vendor's support page." "$OS_NAME"
fi

# =====================================================================
# 2. UPDATES
# =====================================================================
case "$FAMILY" in
  debian)
    if have apt-get; then
      UA=/var/lib/update-notifier/updates-available
      if [[ -f "$UA" && -n "$(find "$UA" -mtime -3 2>/dev/null)" ]]; then
        # Ubuntu keeps these numbers up to date by itself, so reading them costs nothing.
        TOTAL="$(grep -Eo '^[0-9]+ (update|package)s? can be' "$UA" | grep -Eo '^[0-9]+' | head -1)"; TOTAL="${TOTAL:-0}"
        SEC="$(grep -Eo '^[0-9]+ of these updates are standard security' "$UA" | grep -Eo '^[0-9]+' | head -1)"; SEC="${SEC:-0}"
      else
        SIM="$(timeout 40 apt-get -s -o Debug::NoLocking=true upgrade 2>/dev/null | grep '^Inst ')"
        TOTAL="$(grep -c . <<<"$SIM")"; SEC="$(grep -ci 'security' <<<"$SIM")"
      fi
      if [[ "$SEC" -ge 10 ]]; then add UPD-001 updates high fail "Many security updates are waiting" "$SEC security updates and $TOTAL updates in total are not installed." "Install the updates (apt update && apt upgrade) in a quiet hour, after a backup." "$SEC security, $TOTAL total"
      elif [[ "$SEC" -ge 1 ]]; then add UPD-001 updates medium fail "Security updates are waiting" "$SEC security updates are not installed." "Install the updates (apt update && apt upgrade)." "$SEC security, $TOTAL total"
      elif [[ "$TOTAL" -ge 1 ]]; then add UPD-001 updates low warn "Updates are waiting" "$TOTAL updates are not installed. None are marked as security fixes." "Install them at your next maintenance window." "$TOTAL total"
      else add UPD-001 updates medium pass "System packages are up to date" "No pending updates found in the package list." ""; fi
    fi
    if [[ -f /var/run/reboot-required ]]; then add UPD-002 updates medium warn "A restart is needed" "Updates were installed that need a restart (usually a new kernel)." "Restart the server in a quiet hour, then run the audit again." "$(head -c 60 /var/run/reboot-required.pkgs 2>/dev/null | tr '\n' ' ')"
    else add UPD-002 updates medium pass "No restart pending" "The running kernel matches the installed one." ""; fi
    if dpkg -s unattended-upgrades >/dev/null 2>&1 && grep -Eqs 'Unattended-Upgrade\s+"1"' /etc/apt/apt.conf.d/20auto-upgrades; then add UPD-003 updates medium pass "Automatic security updates are on" "unattended-upgrades is installed and enabled." ""
    else add UPD-003 updates medium warn "Automatic security updates are off" "Security fixes are not installed by themselves." "Install and enable unattended-upgrades, or make sure someone applies updates every week." ""; fi
    ;;
  rhel)
    PM=""; have dnf && PM=dnf; [[ -z "$PM" ]] && have yum && PM=yum
    if [[ -n "$PM" ]]; then
      SECL="$(timeout 60 $PM -q -C check-update --security 2>/dev/null | grep -E '^[A-Za-z0-9_.+-]+\.[A-Za-z0-9_]+[[:space:]]' | wc -l)"
      ALLL="$(timeout 60 $PM -q -C check-update 2>/dev/null | grep -E '^[A-Za-z0-9_.+-]+\.[A-Za-z0-9_]+[[:space:]]' | wc -l)"
      if [[ "$SECL" -ge 10 ]]; then add UPD-001 updates high fail "Many security updates are waiting" "$SECL security updates are not installed (from the cached package list)." "Install the updates ($PM update) in a quiet hour, after a backup." "$SECL security, $ALLL total"
      elif [[ "$SECL" -ge 1 ]]; then add UPD-001 updates medium fail "Security updates are waiting" "$SECL security updates are not installed (from the cached package list)." "Install the updates ($PM update)." "$SECL security, $ALLL total"
      elif [[ "$ALLL" -ge 1 ]]; then add UPD-001 updates low warn "Updates are waiting" "$ALLL updates are not installed (from the cached package list)." "Install them at your next maintenance window." "$ALLL total"
      else add UPD-001 updates medium pass "System packages are up to date" "No pending updates in the cached package list. The list is refreshed by your package manager, not by this audit." ""; fi
    fi
    LATEST="$(rpm -q kernel --last 2>/dev/null | head -1 | awk '{print $1}' | sed 's/^kernel-//')"
    if [[ -n "$LATEST" && "$KERNEL" != "$LATEST"* && "$LATEST" != "$KERNEL"* ]]; then add UPD-002 updates medium warn "A newer kernel is installed but not running" "Running $KERNEL, installed $LATEST." "Restart the server in a quiet hour." "$KERNEL"
    else add UPD-002 updates medium pass "Running the newest installed kernel" "No restart is pending for the kernel." ""; fi
    if enabled dnf-automatic.timer || enabled dnf-automatic-install.timer || enabled yum-cron.service; then add UPD-003 updates medium pass "Automatic security updates are on" "An automatic update service is enabled." ""
    else add UPD-003 updates medium warn "Automatic security updates are off" "Security fixes are not installed by themselves." "Enable dnf-automatic (or yum-cron), or make sure someone applies updates every week. On cPanel servers, cPanel updates itself but the operating system still needs this." ""; fi
    ;;
  *) add UPD-001 updates low info "Updates were not checked" "This audit checks apt and dnf/yum based systems." "Check updates with your package manager." "$OS_ID" ;;
esac
if [[ "$UPTIME_DAYS" -gt 365 ]]; then add UPD-005 updates low warn "Very long uptime" "The server has run for $UPTIME_DAYS days without a restart, so it is probably running an old kernel." "Plan a restart in a quiet hour." "$UPTIME_DAYS days"; fi

# =====================================================================
# 3. SSH
# =====================================================================
SSHD_T=""
have sshd && SSHD_T="$(timeout 10 sshd -T 2>/dev/null)"
sv() { awk -v k="$1" 'tolower($1)==k {print tolower($2); exit}' <<<"$SSHD_T"; }
if [[ -n "$SSHD_T" ]]; then
  ROOTL="$(sv permitrootlogin)"; PASSA="$(sv passwordauthentication)"; EMPTY="$(sv permitemptypasswords)"
  if [[ "$ROOTL" == "yes" && "$PASSA" == "yes" ]]; then add SSH-001 ssh critical fail "Root can log in with a password" "SSH allows the root account with a password. This is the most attacked login on the internet." "Set PermitRootLogin to prohibit-password (or no), use SSH keys, and restart sshd. Keep a second session open while you test." "PermitRootLogin yes, PasswordAuthentication yes"
  elif [[ "$ROOTL" == "yes" ]]; then add SSH-001 ssh medium fail "Root can log in over SSH" "SSH allows direct root login (with keys only)." "Use a normal user with sudo and set PermitRootLogin no." "PermitRootLogin yes"
  else add SSH-001 ssh high pass "Root login over SSH is restricted" "PermitRootLogin is $ROOTL." "" "PermitRootLogin $ROOTL"; fi
  if [[ "$PASSA" == "yes" ]]; then add SSH-002 ssh medium fail "SSH accepts passwords" "Passwords can be guessed. Keys cannot." "Switch to SSH keys, then set PasswordAuthentication no. Until then protect SSH with Fail2ban or CSF." "PasswordAuthentication yes"
  else add SSH-002 ssh medium pass "SSH password login is off" "Only keys can log in." ""; fi
  if [[ "$EMPTY" == "yes" ]]; then add SSH-003 ssh critical fail "SSH allows empty passwords" "Accounts without a password could log in." "Set PermitEmptyPasswords no." "PermitEmptyPasswords yes"; fi
  MAXT="$(sv maxauthtries)"; if [[ "${MAXT:-6}" -gt 4 ]]; then add SSH-004 ssh low warn "Many login tries allowed per connection" "MaxAuthTries is $MAXT." "Set MaxAuthTries 3 or 4." "MaxAuthTries $MAXT"; else add SSH-004 ssh low pass "Login tries are limited" "MaxAuthTries is ${MAXT:-default}." ""; fi
  if [[ "$(sv x11forwarding)" == "yes" ]]; then add SSH-005 ssh low warn "X11 forwarding is on" "It is rarely needed on a server." "Set X11Forwarding no." "X11Forwarding yes"; fi
  WEAK="$(grep -Ei '^(ciphers|macs) ' <<<"$SSHD_T" | grep -Eio '3des-cbc|arcfour|hmac-md5|aes128-cbc|aes192-cbc|aes256-cbc' | sort -u | paste -sd, -)"
  if [[ -n "$WEAK" ]]; then add SSH-006 ssh low warn "Old SSH ciphers are allowed" "The server accepts old algorithms." "Remove the old ciphers and MACs from sshd_config (or update OpenSSH)." "$WEAK"; else add SSH-006 ssh low pass "Only modern SSH ciphers" "No old ciphers or MACs were found." ""; fi
  if [[ -n "$(sv allowusers)$(sv allowgroups)" ]]; then add SSH-007 ssh low pass "SSH is limited to named users or groups" "AllowUsers or AllowGroups is set." ""; else add SSH-007 ssh low info "SSH is open to every account" "AllowUsers and AllowGroups are not set." "Limit SSH to the accounts that need it." ""; fi
else
  add SSH-001 ssh low info "SSH settings could not be read" "sshd is not installed, or its settings could not be read." "" ""
fi
if [[ -s /root/.ssh/authorized_keys ]]; then NK="$(grep -Ecv '^\s*(#|$)' /root/.ssh/authorized_keys 2>/dev/null)"; add SSH-008 ssh low info "Keys that can log in as root" "$NK SSH key(s) are listed for root." "Remove keys of people who no longer need access." "$NK keys"; fi

# =====================================================================
# 4. ACCOUNTS
# =====================================================================
EMPTYP="$(awk -F: '($2==""){print $1}' /etc/shadow 2>/dev/null | join_first 5)"
if [[ -n "$EMPTYP" ]]; then add ACC-001 accounts critical fail "Accounts with no password" "These accounts have an empty password field." "Lock them (passwd -l name) or set a long password." "$EMPTYP"; else add ACC-001 accounts critical pass "No account has an empty password" "Every account has a password hash or is locked." ""; fi
UID0="$(awk -F: '($3==0 && $1!="root"){print $1}' /etc/passwd 2>/dev/null | join_first 5)"
if [[ -n "$UID0" ]]; then add ACC-002 accounts critical fail "Another account has root rights" "These accounts have user ID 0, the same as root." "Remove them unless you created them on purpose. This is a common sign of a break-in." "$UID0"; else add ACC-002 accounts critical pass "Only root has user ID 0" "No hidden root-level accounts." ""; fi
NOPW="$(grep -rEls '^[^#]*NOPASSWD' /etc/sudoers /etc/sudoers.d 2>/dev/null | join_first 4)"
NOPW_OTHER="$(tr ',' '\n' <<<"${NOPW//, /,}" | grep -v 'cloud-init' | grep -c .)"
if [[ -n "$NOPW" && "$NOPW_OTHER" -eq 0 ]]; then add ACC-003 accounts low info "Cloud image sudo rule" "The only password-free sudo rule comes from the cloud image setup (cloud-init). This is normal for cloud servers." "Keep it only if you use that account. Remove it if you do not." "$NOPW"
elif [[ -n "$NOPW" ]]; then add ACC-003 accounts medium warn "Sudo without a password" "Some sudo rules do not ask for a password." "Remove NOPASSWD unless a script truly needs it, and limit it to one command." "$NOPW"; else add ACC-003 accounts medium pass "Sudo asks for a password" "No NOPASSWD rules were found." ""; fi
SYSSH="$(awk -F: '$3<1000 && $3>0 && $1!~/^(sync|shutdown|halt)$/ && $7!~/(nologin|false)$/ && $7!="" {print $1}' /etc/passwd 2>/dev/null | join_first 5)"
if [[ -n "$SYSSH" ]]; then add ACC-004 accounts low warn "System accounts with a login shell" "These system accounts can open a shell." "Set their shell to /sbin/nologin unless they need it." "$SYSSH"; fi
SUDOERS="$( (getent group sudo; getent group wheel; getent group admin) 2>/dev/null | awk -F: '{print $4}' | tr ',' '\n' | sort -u | grep -c . )"
add ACC-005 accounts info info "Accounts with administrator rights" "$SUDOERS account(s) are in the sudo, wheel or admin group." "Keep this list short and review it every few months." "$SUDOERS accounts"
FAILED="$(timeout 8 lastb 2>/dev/null | grep -c . )"
if [[ "${FAILED:-0}" -gt 2000 ]]; then add ACC-006 accounts low info "Many failed logins" "About $FAILED failed logins are recorded. Public servers are always guessed at, but this is a lot." "Use SSH keys and a tool that blocks repeat failures (Fail2ban, CSF or CrowdSec)." "$FAILED failures"; fi

# =====================================================================
# 5. FIREWALL AND NETWORK
# =====================================================================
FW=""
if have ufw && ufw status 2>/dev/null | grep -qi "Status: active"; then FW="ufw"
elif active firewalld; then FW="firewalld"
elif [[ -x /usr/sbin/csf ]] && ! grep -qs '^TESTING = "1"' /etc/csf/csf.conf && active lfd; then FW="csf"
elif have nft && [[ "$(timeout 5 nft list ruleset 2>/dev/null | grep -c 'chain ')" -gt 0 ]]; then FW="nftables"
elif have iptables && [[ "$(timeout 5 iptables -S 2>/dev/null | grep -vc '^-P')" -gt 0 ]]; then FW="iptables"; fi
if [[ -n "$FW" ]]; then add FW-001 firewall high pass "A firewall is running" "Found: $FW." "" "$FW"
else add FW-001 firewall high fail "No firewall found on the server" "No active host firewall was found." "Turn on a firewall (ufw, firewalld or CSF) and allow only the ports you use. A cloud firewall at your provider is a good extra layer, but not a replacement." ""; fi

DBPORTS=""
for p in 3306 5432 27017 6379 11211 9200 5984 1433 9042 7474 8086; do listen_public "$p" && DBPORTS+="${DBPORTS:+, }$p"; done
if [[ -n "$DBPORTS" ]]; then add NET-001 network high fail "Database or cache ports listen on every interface" "These ports accept connections from all addresses: $DBPORTS. Databases on the open internet are found and attacked quickly." "Bind them to 127.0.0.1 (or a private address), or block them in the firewall. Never expose a database to everyone." "$DBPORTS"; else add NET-001 network high pass "Databases are not open to every address" "No common database or cache port listens on all interfaces." ""; fi
if listen_public 2375 || listen_public 2376; then add NET-002 network critical fail "The Docker API is open" "Docker listens on the network. Anyone who can reach it can take over the server." "Turn off the TCP socket, or protect it with TLS client certificates and a firewall." "2375/2376"; fi
OLDSV=""
for p in 23 513 514 69; do listen_public "$p" && OLDSV+="${OLDSV:+, }$p"; done
listen_public 21 && OLDSV+="${OLDSV:+, }21 (FTP)"
if [[ -n "$OLDSV" ]]; then add NET-003 network medium fail "Old, unencrypted services are open" "These ports are open on all interfaces: $OLDSV. They send passwords without encryption." "Use SFTP or FTPS instead of FTP, and remove telnet, rsh and tftp." "$OLDSV"; else add NET-003 network medium pass "No old unencrypted services" "Telnet, rsh and tftp are not listening." ""; fi
SHARE=""
for p in 111 139 445 2049; do listen_public "$p" && SHARE+="${SHARE:+, }$p"; done
if [[ -n "$SHARE" ]]; then add NET-004 network medium fail "File sharing ports are open to everyone" "These ports are open on all interfaces: $SHARE (RPC, Samba or NFS)." "Block them in the firewall or bind them to a private address." "$SHARE"; fi
PORTSN="$(awk '{n=split($4,a,":"); print a[n]}' <<<"$SS_OUT" | sort -un | grep -c .)"
add NET-005 network info info "Listening ports" "$PORTSN different ports are listening." "Close what you do not use." "$PORTSN ports"
PANELPORTS=""
for p in 2082 2083 2086 2087 8443 8447 2222 8090 7080 8083 10000 7800 8888 2030 2031 8080; do listen_public "$p" && PANELPORTS+="${PANELPORTS:+, }$p"; done
if [[ -n "$PANELPORTS" ]]; then add NET-006 network low info "Panel or admin ports are reachable by everyone" "Control panel ports ($PANELPORTS) accept connections from all addresses." "Where you can, limit them to your own IP addresses in the firewall, or reach them through a VPN. Keep two-step login on." "$PANELPORTS"; fi
SYSN=""
chk() { local v; v="$(sysctl -n "$1" 2>/dev/null)"; [[ -n "$v" && "$v" != "$2" ]] && SYSN+="${SYSN:+, }$1=$v"; return 0; }
chk net.ipv4.tcp_syncookies 1; chk net.ipv4.conf.all.accept_redirects 0; chk net.ipv4.conf.all.accept_source_route 0; chk net.ipv4.icmp_echo_ignore_broadcasts 1
if [[ -n "$SYSN" ]]; then add NET-007 network low warn "Network kernel settings can be tighter" "These settings differ from the usual safe values: $SYSN." "Set them in /etc/sysctl.d/ and run sysctl --system." "$SYSN"; else add NET-007 network low pass "Network kernel settings look safe" "SYN cookies and redirect protection are in place." ""; fi

# =====================================================================
# 6. KERNEL AND PROTECTION
# =====================================================================
ASLR="$(sysctl -n kernel.randomize_va_space 2>/dev/null)"
if [[ -n "$ASLR" ]]; then if [[ "$ASLR" == "2" ]]; then add KRN-001 kernel medium pass "Address randomisation is on" "kernel.randomize_va_space is 2." ""; else add KRN-001 kernel medium fail "Address randomisation is weak" "kernel.randomize_va_space is $ASLR." "Set kernel.randomize_va_space = 2." "$ASLR"; fi; fi
KP=""
chk2() { local v; v="$(sysctl -n "$1" 2>/dev/null)"; [[ -n "$v" && "$v" != "$2" ]] && KP+="${KP:+, }$1=$v"; return 0; }
chk2 fs.protected_symlinks 1; chk2 fs.protected_hardlinks 1; chk2 fs.suid_dumpable 0
if [[ -n "$KP" ]]; then add KRN-002 kernel low warn "Kernel protections can be tighter" "These settings differ from the usual safe values: $KP." "Set them in /etc/sysctl.d/ and run sysctl --system." "$KP"; else add KRN-002 kernel low pass "Kernel file protections are on" "Symlink, hardlink and core dump protections are set." ""; fi
if [[ "$FAMILY" == "rhel" ]] && have getenforce; then
  SE="$(getenforce 2>/dev/null)"
  if [[ "$SE" == "Enforcing" ]]; then add KRN-003 kernel medium pass "SELinux is enforcing" "SELinux is on." ""
  elif [[ "$HAS_CPANEL" == "1" ]]; then add KRN-003 kernel low info "SELinux is $SE" "cPanel does not support SELinux enforcing, so this is expected." ""
  else add KRN-003 kernel medium warn "SELinux is $SE" "SELinux gives a second layer of protection." "Set SELinux to enforcing if your software supports it." "$SE"; fi
elif [[ "$FAMILY" == "debian" ]]; then
  if [[ "$(cat /sys/module/apparmor/parameters/enabled 2>/dev/null)" == "Y" ]]; then add KRN-003 kernel low pass "AppArmor is on" "AppArmor profiles are active." ""; else add KRN-003 kernel low info "AppArmor is off" "AppArmor gives a second layer of protection." "Enable it if your software supports it." ""; fi
fi

# =====================================================================
# 7. FILES
# =====================================================================
perm_ok() { # file maxmode owner
  [[ -e "$1" ]] || return 0
  local m o; m="$(stat -c '%a' "$1" 2>/dev/null)"; o="$(stat -c '%U' "$1" 2>/dev/null)"
  [[ "$o" == "root" ]] || { echo "$1 owned by $o"; return 0; }
  [[ $((8#$m & 8#$2)) -eq 0 ]] || echo "$1 mode $m"
}
BADP="$( { perm_ok /etc/shadow 037; perm_ok /etc/gshadow 037; perm_ok /etc/passwd 022; perm_ok /etc/ssh/sshd_config 022; perm_ok /etc/sudoers 227; } | join_first 4)"
if [[ -n "$BADP" ]]; then add FIL-001 files high fail "Important files have loose permissions" "$BADP" "Fix with chmod: /etc/shadow 640 or 600, /etc/passwd 644, sshd_config 600 or 644, owned by root." "$BADP"; else add FIL-001 files high pass "Important system files are protected" "Password and SSH files have safe permissions." ""; fi
WW="$(timeout 20 find /etc -xdev -type f -perm -0002 2>/dev/null | join_first 5)"
if [[ -n "$WW" ]]; then add FIL-002 files high fail "Files in /etc that anyone can change" "$WW" "Remove world-write permission (chmod o-w) and find out why it was set." "$WW"; else add FIL-002 files high pass "No world-writable files in /etc" "" ""; fi
NOSTICKY=""
for d in /tmp /var/tmp /dev/shm; do [[ -d "$d" && ! -k "$d" ]] && NOSTICKY+="${NOSTICKY:+, }$d"; done
if [[ -n "$NOSTICKY" ]]; then add FIL-003 files medium fail "Shared temp folders have no sticky bit" "$NOSTICKY lets users delete each other's files." "Run chmod +t on these folders." "$NOSTICKY"; else add FIL-003 files medium pass "Shared temp folders are protected" "The sticky bit is set." ""; fi
TMPOPT="$(findmnt -no OPTIONS /tmp 2>/dev/null)"
if [[ -n "$TMPOPT" ]]; then if [[ "$TMPOPT" == *noexec* ]]; then add FIL-004 files low pass "/tmp does not allow programs to run" "/tmp is mounted with noexec." ""; else add FIL-004 files low info "/tmp allows programs to run" "Attackers often run their tools from /tmp." "Mount /tmp with noexec,nosuid,nodev if your software allows it." "$TMPOPT"; fi
else add FIL-004 files low info "/tmp is part of the main disk" "It is not a separate mount, so it cannot be locked with noexec." "Consider a separate /tmp mount with noexec,nosuid,nodev." ""; fi
EXE="$(timeout 20 find /tmp /var/tmp /dev/shm -xdev -maxdepth 3 -type f -perm /111 2>/dev/null | grep -Ev 'systemd-private|/\.X11|/hsperfdata|/npm-|/pip-|/ccache' | join_first 5)"
if [[ -n "$EXE" ]]; then add FIL-005 files high warn "Programs sit in temp folders" "Executable files were found in temp folders. Crypto miners and backdoors often hide there. Many are harmless installers." "Check each one. If you do not recognise it, treat the server as possibly hacked and ask for a malware check." "$EXE"; else add FIL-005 files high pass "No programs in temp folders" "No executable files in /tmp, /var/tmp or /dev/shm." ""; fi
SUID="$(timeout 25 find /home /tmp /var/tmp /dev/shm /var/www -xdev -maxdepth 4 -type f -perm -4000 2>/dev/null | join_first 4)"
if [[ -n "$SUID" ]]; then add FIL-006 files high fail "SUID programs in user or web folders" "Files that run with root rights sit in places where users or websites can write." "Remove the SUID bit (chmod u-s) unless you put it there on purpose. This is a common backdoor." "$SUID"; else add FIL-006 files high pass "No SUID programs in user or web folders" "" ""; fi
EXPOSE="$(timeout 25 find /var/www /home -xdev -maxdepth 4 \( -name .git -type d -o -name .env -type f -o -name '*.sql' -type f -o -name '*.sql.gz' -type f \) 2>/dev/null | join_first 4)"
if [[ -n "$EXPOSE" ]]; then add FIL-007 files medium warn "Source, settings or database files in web folders" "These may be downloadable from the internet: $EXPOSE." "Move them out of the web folders, or block them in the web server settings." "$EXPOSE"; else add FIL-007 files medium pass "No .git, .env or database dumps in web folders" "" ""; fi
for m in $(df -P -x tmpfs -x devtmpfs -x squashfs -x overlay 2>/dev/null | awk 'NR>1 {print $6":"$5}'); do :; done
FULL="$(df -P -x tmpfs -x devtmpfs -x squashfs -x overlay 2>/dev/null | awk 'NR>1 {gsub(/%/,"",$5); if ($5+0>=90) print $6" "$5"%"}' | join_first 4)"
FULLI="$(df -Pi -x tmpfs -x devtmpfs -x squashfs -x overlay 2>/dev/null | awk 'NR>1 {gsub(/%/,"",$5); if ($5+0>=90) print $6" "$5"%"}' | join_first 4)"
if [[ -n "$FULL" ]]; then add RES-001 system high fail "A disk is almost full" "$FULL. A full disk stops databases, mail and websites." "Free space now: logs, old backups, caches. Then watch disk use with an alert." "$FULL"; else add RES-001 system high pass "Disks have free space" "No disk is above 90%." ""; fi
if [[ -n "$FULLI" ]]; then add RES-002 system medium fail "Inodes are almost used up" "$FULLI. The disk cannot hold more files." "Find folders with millions of small files (sessions, caches, mail) and clean them." "$FULLI"; fi

# =====================================================================
# 8. SERVICES, LOGGING, BACKUPS
# =====================================================================
BF=""
active fail2ban && BF="Fail2ban"; active crowdsec && BF+="${BF:+, }CrowdSec"; active sshguard && BF+="${BF:+, }SSHGuard"; active lfd && BF+="${BF:+, }CSF/LFD"; [[ -e /var/cpanel/hulkd/enabled ]] && BF+="${BF:+, }cPHulk"
if [[ -n "$BF" ]]; then add SVC-001 services medium pass "Repeated failed logins are blocked" "Found: $BF." "" "$BF"; else add SVC-001 services medium warn "Nothing blocks repeated failed logins" "No Fail2ban, CSF, CrowdSec or cPHulk was found." "Install and enable Fail2ban (or CSF on cPanel servers)." ""; fi
if active chronyd || active chrony || active ntpd || active systemd-timesyncd || active ntp; then add SVC-002 services low pass "The clock is kept in sync" "A time service is running." ""; else add SVC-002 services low warn "No time service is running" "A wrong clock breaks logs, certificates and logins." "Enable chrony or systemd-timesyncd." ""; fi
AV=""
for s in clamd clamav-daemon imunify360 imunify-antivirus maldet; do active "$s" && AV+="${AV:+, }$s"; done
[[ -x /opt/rootscan/bin/rootscan || -d /opt/rootscan ]] && AV+="${AV:+, }RootScan"; have rkhunter && AV+="${AV:+, }rkhunter"; have maldet && AV+="${AV:+, }maldet"
if [[ -n "$AV" ]]; then add SVC-003 services low pass "A malware scanner is installed" "Found: $AV." "" "$AV"; else add SVC-003 services low info "No malware scanner found" "A scanner finds hacked websites early." "Use RootScan (free for cPanel/WHM), ClamAV or Imunify." ""; fi
if have auditctl || active auditd; then add SVC-004 services low pass "Audit logging is available" "auditd is present." ""; fi
if active rsyslog || active syslog-ng || [[ -d /var/log/journal ]]; then add LOG-001 logging low pass "Logs are kept" "System logs are written to disk." ""; else add LOG-001 logging low warn "Logs may not survive a restart" "No syslog service or persistent journal was found." "Enable rsyslog or create /var/log/journal." ""; fi
[[ -f /etc/logrotate.conf ]] && add LOG-002 logging low pass "Log rotation is set up" "logrotate is installed." ""
BK=""
have restic && BK+="${BK:+, }restic"; have borg && BK+="${BK:+, }borg"; have rsnapshot && BK+="${BK:+, }rsnapshot"; have duplicity && BK+="${BK:+, }duplicity"
[[ -x /usr/local/bin/rootmanage-backup ]] && BK+="${BK:+, }RootManage Backup"; [[ -d /usr/local/jetapps ]] && BK+="${BK:+, }JetBackup"
grep -qEs "BACKUPENABLE=.?yes" /var/cpanel/backups/config 2>/dev/null && BK+="${BK:+, }cPanel backups"
[[ -d /usr/local/psa/PMM ]] && BK+="${BK:+, }Plesk backup"
grep -qiE 'backup' <<<"$ENABLED_LIST" && BK+="${BK:+, }backup service or timer"
grep -rqiEs 'backup' /etc/crontab /etc/cron.d /etc/cron.daily /etc/cron.weekly /var/spool/cron /var/spool/cron/crontabs 2>/dev/null && BK+="${BK:+, }scheduled backup job"
if [[ -n "$BK" ]]; then add BAK-001 backup high pass "A backup tool is set up" "Found: $BK. This audit cannot tell if the backups restore. Test a restore every month." "" "$BK"; else add BAK-001 backup high fail "No backup tool found" "No backup program or panel backup was found on this server." "Set up backups to another system and test a restore. RootManage Backup does this for you." ""; fi

# =====================================================================
# 9. SCHEDULED JOBS
# =====================================================================
SUSP="$(grep -rEsl '(curl|wget)[^|;]*\|[[:space:]]*(ba)?sh|base64[[:space:]]+(-d|--decode)|/dev/shm/|/tmp/\.[A-Za-z0-9]' /etc/crontab /etc/cron.d /etc/cron.hourly /etc/cron.daily /var/spool/cron /var/spool/cron/crontabs 2>/dev/null | join_first 4)"
if [[ -n "$SUSP" ]]; then add CRN-001 cron high fail "Scheduled jobs that look like malware" "These job files download and run code, decode hidden text or run from hidden temp folders: $SUSP." "Open each file and remove what you did not create. Then change passwords and look for how it got in. We can help." "$SUSP"; else add CRN-001 cron high pass "Scheduled jobs look normal" "No job downloads and runs code or hides in temp folders." ""; fi

# =====================================================================
# 10. WEB, PHP, DATABASE
# =====================================================================
php_eol() { case "$1" in 5.*|7.0|7.1|7.2|7.3) echo 20200101 ;; 7.4) echo 20221128 ;; 8.0) echo 20231126 ;; 8.1) echo 20251231 ;; 8.2) echo 20261231 ;; 8.3) echo 20271231 ;; 8.4) echo 20281231 ;; esac; }
PHPV=""
for d in /opt/cpanel/ea-php* /opt/alt/php* /opt/plesk/php/* /opt/remi/php*; do [[ -d "$d" ]] || continue; v="$(basename "$d" | grep -Eo '[0-9]{2,3}$' | head -1)"; [[ -n "$v" ]] && PHPV+=" ${v:0:1}.${v:1}"; done
have php && PHPV+=" $(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;' 2>/dev/null)"
for p in /usr/bin/php[0-9]* /usr/sbin/php[0-9]*; do [[ -x "$p" ]] && PHPV+=" $(basename "$p" | grep -Eo '[0-9]\.[0-9]' | head -1)"; done
PHPV="$(tr ' ' '\n' <<<"$PHPV" | grep -E '^[0-9]\.[0-9]$' | sort -uV | tr '\n' ' ')"
if [[ -n "$PHPV" ]]; then
  OLDP=""; SOONP=""
  for v in $PHPV; do e="$(php_eol "$v")"; [[ -n "$e" && "$e" -le "$TODAY" ]] && OLDP+="${OLDP:+, }$v"; [[ -n "$e" && "$e" -gt "$TODAY" && "$e" -le "$(date -d '+180 days' +%Y%m%d 2>/dev/null || echo 0)" ]] && SOONP+="${SOONP:+, }$v"; done
  if [[ -n "$OLDP" ]]; then add WEB-001 web high fail "Old PHP versions are installed" "PHP $OLDP no longer gets security fixes (installed: $PHPV)." "Move sites to a supported PHP version and remove the old ones. Test each site first." "$OLDP"
  elif [[ -n "$SOONP" ]]; then add WEB-001 web medium warn "A PHP version is close to its end" "PHP $SOONP loses security support within about six months (installed: $PHPV)." "Plan the upgrade." "$SOONP"
  else add WEB-001 web medium pass "PHP versions are supported" "Installed: $PHPV." "" "$PHPV"; fi
fi
if have mysql || have mariadb || have mysqld; then
  DBV="$( (mariadb --version 2>/dev/null || mysql --version 2>/dev/null) | head -1)"
  DBN="$(grep -Eio 'mariadb|mysql' <<<"$DBV" | head -1 | tr 'A-Z' 'a-z')"; DBNUM="$(grep -Eo '[0-9]+\.[0-9]+(\.[0-9]+)?' <<<"$DBV" | head -1)"
  if [[ "$DBV" == *MariaDB* ]]; then DBN=mariadb; fi
  case "$DBN:${DBNUM%.*}" in
    mysql:5.*|mysql:4.*) add DBS-001 database high fail "Old MySQL version" "$DBV is out of vendor support." "Upgrade to a supported release after a backup and a test." "$DBNUM" ;;
    mysql:8.0) add DBS-001 database medium warn "MySQL 8.0 support has ended or is ending" "MySQL 8.0 reached its end of life in April 2026." "Plan the move to a newer release." "$DBNUM" ;;
    mariadb:10.[0-5]|mariadb:5.*) add DBS-001 database high fail "Old MariaDB version" "$DBV is out of vendor support." "Upgrade to a supported release after a backup and a test." "$DBNUM" ;;
    mariadb:10.6) add DBS-001 database medium warn "MariaDB 10.6 support ends in 2026" "MariaDB 10.6 reaches its end of life in July 2026." "Plan the move to 10.11 or 11.4." "$DBNUM" ;;
    *) [[ -n "$DBNUM" ]] && add DBS-001 database low info "Database version" "$DBV." "Check your vendor for its support date." "$DBNUM" ;;
  esac
fi
CERTS=""
for c in /etc/letsencrypt/live/*/cert.pem; do [[ -f "$c" ]] || continue; openssl x509 -checkend 1209600 -noout -in "$c" >/dev/null 2>&1 || CERTS+="${CERTS:+, }$(basename "$(dirname "$c")")"; done
if [[ -n "$CERTS" ]]; then add WEB-002 web medium fail "Certificates expire within 14 days" "$CERTS." "Check that automatic renewal works (certbot renew --dry-run) and renew now if it does not." "$CERTS"; elif ls /etc/letsencrypt/live/*/cert.pem >/dev/null 2>&1; then add WEB-002 web medium pass "Certificates are not close to expiry" "No Let's Encrypt certificate expires within 14 days." ""; fi

# =====================================================================
# 11. CONTROL PANELS
# =====================================================================
cfg() { grep -Eis "^[[:space:]]*$2[[:space:]]*=" "$1" 2>/dev/null | head -1 | sed -E 's/^[^=]*=[[:space:]]*//; s/["'"'"']//g' | tr -d '\r '; }
if [[ "$HAS_CPANEL" == "1" ]]; then
  U="$(cfg /etc/cpupdate.conf UPDATES)"
  case "$U" in daily) add PNL-001 panel high pass "cPanel updates itself" "UPDATES is daily." "" "UPDATES=daily" ;; manual|never) add PNL-001 panel high fail "cPanel does not update itself" "UPDATES is $U, so security fixes are not applied." "In WHM go to Update Preferences and choose daily updates." "UPDATES=$U" ;; *) add PNL-001 panel medium info "cPanel update setting not found" "" "Check WHM, Update Preferences." "" ;; esac
  T="$(cfg /etc/cpupdate.conf CPANEL)"; [[ "$T" == "edge" || "$T" == "current" ]] && add PNL-002 panel low info "cPanel uses the $T release tier" "Edge and current get new features first and are less tested." "Use the stable or release tier on production servers." "CPANEL=$T"
  if [[ -e /var/cpanel/hulkd/enabled ]]; then add PNL-003 panel medium pass "cPHulk brute-force protection is on" "" ""; else add PNL-003 panel medium warn "cPHulk is off" "cPHulk blocks repeated failed logins to cPanel, WHM, mail and SSH." "Enable cPHulk in WHM (Security Center), or use CSF/LFD." ""; fi
  if rpm -qa 2>/dev/null | grep -qiE 'mod_security2|modsec' || dpkg -l 2>/dev/null | grep -qi 'modsecurity\|mod-security'; then add PNL-004 panel medium pass "ModSecurity is installed" "A web application firewall is available." ""; else add PNL-004 panel medium warn "ModSecurity is not installed" "ModSecurity blocks many attacks on websites." "Install ModSecurity with a maintained rule set from WHM (Security Center)." ""; fi
  if [[ -f /var/cpanel/backups/config ]]; then if grep -qE "BACKUPENABLE=.?yes" /var/cpanel/backups/config; then add PNL-005 panel high pass "cPanel backups are enabled" "" ""; else add PNL-005 panel high fail "cPanel backups are off" "The built-in backup is disabled." "Enable backups in WHM (Backup Configuration) and store a copy off the server." ""; fi; fi
  if [[ "$(cfg /var/cpanel/conf/pureftpd/main NoAnonymous)" == "no" ]]; then add PNL-006 panel medium fail "Anonymous FTP is allowed" "" "Turn off anonymous FTP in WHM, FTP Server Configuration." ""; fi
fi
if [[ "$PANELS" == *Plesk* ]]; then
  PV="$(awk '{print $1}' /usr/local/psa/version 2>/dev/null | cut -d. -f1)"
  if [[ -n "$PV" && "$PV" -lt 18 ]]; then add PNL-010 panel high fail "Old Plesk version" "Plesk $PV is no longer supported." "Upgrade to Plesk Obsidian." "Plesk $PV"; else add PNL-010 panel medium pass "Plesk is a supported generation" "Plesk $(cat /usr/local/psa/version 2>/dev/null | awk '{print $1}')." ""; fi
  if active fail2ban || [[ -e /usr/local/psa/var/modules/fail2ban ]]; then add PNL-011 panel medium pass "Plesk brute-force protection found" "Fail2ban is available for Plesk." ""; else add PNL-011 panel medium warn "Plesk brute-force protection not found" "" "Turn on Fail2ban in Plesk (Tools and Settings, IP Address Banning)." ""; fi
fi
if [[ "$PANELS" == *DirectAdmin* ]]; then
  DA=/usr/local/directadmin/conf/directadmin.conf
  [[ "$(cfg "$DA" ssl)" == "0" ]] && add PNL-020 panel high fail "DirectAdmin runs without SSL" "The panel sends passwords unencrypted." "Set ssl=1 in directadmin.conf and restart DirectAdmin." "ssl=0"
  [[ "$(cfg "$DA" brute_force_log_scanner)" == "0" ]] && add PNL-021 panel medium fail "DirectAdmin brute-force scanner is off" "" "Set brute_force_log_scanner=1." "brute_force_log_scanner=0"
  [[ -z "$(cfg "$DA" ssl)$(cfg "$DA" brute_force_log_scanner)" ]] || true
fi
if [[ "$PANELS" == *Webmin* || "$PANELS" == *Virtualmin* ]]; then
  [[ "$(cfg /etc/webmin/miniserv.conf ssl)" == "0" ]] && add PNL-030 panel high fail "Webmin runs without SSL" "" "Set ssl=1 in /etc/webmin/miniserv.conf." "ssl=0"
fi
if [[ -n "$PANELS" && "$PANELS" != *cPanel* && "$PANELS" != *Plesk* && "$PANELS" != *DirectAdmin* ]]; then
  add PNL-099 panel low info "Control panel found" "Found: $PANELS. The audit checks the system under it, and open panel ports." "Keep the panel updated and limit its port to trusted addresses." "$PANELS"
fi

# =====================================================================
# output
# =====================================================================
FINISHED="$(date +%s%3N 2>/dev/null || echo 0)"
build_payload() {
  local dur=$(( ${FINISHED:-0} - ${STARTED:-0} )); [[ "$dur" -lt 0 || "$dur" -gt 900000 ]] && dur=0
  printf '{"agent_version":"%s","duration_ms":%s,"host":{"os":"%s","os_version":"%s","kernel":"%s","arch":"%s","virt":"%s","family":"%s","panel":"%s","panel_version":"%s","panels":"%s","hostname":"%s","uptime_days":%s,"cpu_cores":%s,"mem_mb":%s},"findings":[%s]}' \
    "$AUDIT_VERSION" "$dur" "$(jesc "$OS_ID")" "$(jesc "$OS_VER")" "$(jesc "$KERNEL")" "$(jesc "$ARCH")" "$(jesc "$VIRT")" "$FAMILY" "$(jesc "$PANEL")" "$(jesc "$PANEL_VER")" "$(jesc "$PANELS")" "$(jesc "$HOSTNAME_S")" "${UPTIME_DAYS:-0}" "${CORES:-1}" "${MEM_MB:-0}" "$FINDINGS"
}

if [[ "$MODE" == "--report" ]]; then
  # A readable report on this screen. Nothing is sent anywhere.
  printf '%s' "$TXT" | awk -F'|' -v host="$HOSTNAME_S" -v os="$OS_NAME" -v secs="$(( (${FINISHED:-0} - ${STARTED:-0}) / 1000 ))" '
    BEGIN { split("critical high medium low", ORD, " "); loss = 0; pass = 0; info = 0; total = 0 }
    NF >= 5 {
      sev = $1; st = $2; total++
      if (st == "pass") { pass++; next }
      if (st == "info") { info++; next }
      base = (sev == "critical" ? 15 : sev == "high" ? 8 : sev == "medium" ? 4 : sev == "low" ? 1.5 : 0)
      loss += (st == "warn" ? base / 2 : base)
      c[sev]++; k = c[sev]
      line[sev, k] = "  [" $3 "] " $4 (st == "warn" ? "  (to review)" : "")
      fix[sev, k] = $5
    }
    END {
      score = int(100 - loss + 0.5); if (score < 0) score = 0; if (score > 100) score = 100
      grade = (score >= 90 ? "A" : score >= 80 ? "B" : score >= 65 ? "C" : score >= 50 ? "D" : "F")
      printf "\nRootManage security audit: %s (%s)\n", host, os
      printf "Score %d/100, grade %s. %d checks: %d passed, %d for your information, %d to fix or review. Took %d s.\n", score, grade, total, pass, info, total - pass - info, secs
      for (i = 1; i <= 4; i++) {
        s = ORD[i]
        if (c[s] > 0) {
          printf "\n%s (%d)\n", toupper(s), c[s]
          for (j = 1; j <= c[s]; j++) { print line[s, j]; if (fix[s, j] != "") print "      Fix: " fix[s, j] }
        }
      }
      if (loss == 0) print "\nNothing needs action."
      print "\nThis is a review of settings, not a penetration test or a certification. It only read your system; nothing was changed and nothing was sent."
      print "Every check is explained at https://rootmanage.com/agent/audit"
    }'
  exit 0
fi

PAYLOAD="$(build_payload)"
if [[ "$MODE" == "--print" ]]; then
  printf '%s\n' "$PAYLOAD"
  echo "Audit finished: $NFIND checks in $(( (${FINISHED:-0} - ${STARTED:-0}) / 1000 )) s. Nothing was sent." >&2
  exit 0
fi

# ---------- send ----------
if [[ ! -f "$ENV_FILE" ]]; then echo "missing $ENV_FILE (install the audit agent from your RootManage dashboard)" >&2; exit 1; fi
# shellcheck disable=SC1090
. "$ENV_FILE"
if [[ -z "${API_URL:-}" || -z "${ANON_KEY:-}" || -z "${AGENT_TOKEN:-}" ]]; then echo "API_URL, ANON_KEY and AGENT_TOKEN are required in $ENV_FILE" >&2; exit 1; fi
case "$API_URL" in https://*) ;; *) echo "refusing to send over a connection that is not HTTPS" >&2; exit 1 ;; esac
mkdir -p "$STATE_DIR"; umask 077
BODY="$STATE_DIR/audit.body.json"; RESP="$STATE_DIR/audit.resp.json"
printf '{"p_token":"%s","p_payload":%s}' "$AGENT_TOKEN" "$PAYLOAD" > "$BODY"
HTTP="$(curl -sS --proto '=https' --tlsv1.2 -m 40 -o "$RESP" -w '%{http_code}' -X POST "${API_URL%/}/rest/v1/rpc/report_audit_run" \
  -H "apikey: ${ANON_KEY}" -H "Authorization: Bearer ${ANON_KEY}" -H "Content-Type: application/json" --data-binary "@$BODY" 2>/dev/null || echo 000)"
rm -f "$BODY"
if grep -q '"ok" *: *true' "$RESP" 2>/dev/null; then
  SCORE="$(grep -Eo '"score" *: *[0-9]+' "$RESP" | grep -Eo '[0-9]+' | head -1)"; GRADE="$(grep -Eo '"grade" *: *"[A-F]"' "$RESP" | grep -Eo '[A-F]' | head -1)"
  echo "RootManage audit sent: score ${SCORE:-?}/100 (grade ${GRADE:-?}), $NFIND checks. See ${API_URL%/}/dashboard/audit"
  rm -f "$RESP"; exit 0
fi
REASON="$(grep -Eo '"reason" *: *"[a-z_]+"' "$RESP" 2>/dev/null | head -1 | sed 's/.*: *//; s/"//g')"
case "$REASON" in
  too_soon) echo "An audit was sent a few minutes ago. Wait 5 minutes and run it again." >&2 ;;
  inactive) echo "This server is not Active. The security audit is part of the paid plans." >&2 ;;
  unknown_token|invalid_token) echo "The server token was not accepted. Copy the install line again from your dashboard." >&2 ;;
  *) echo "The audit could not be sent (HTTP $HTTP${REASON:+, $REASON})." >&2 ;;
esac
rm -f "$RESP"; exit 2
