#!/usr/bin/env bash
# check-php2shell.sh - STRICTLY READ-ONLY checker for "PHP2Shell"
#   CVE-2026-109618 (PHP advisory GHSA-w8hw-w9fx-j79w, RCE via OOM corruption)
#   CVE-2026-109619 (PHP advisory GHSA-6wmf-4rv5-p3rp, RCE via stale global state)
# Fixed upstream releases (PHP advisories and ChangeLog, 22 Oct 2026 tags): 8.2.35, 8.3.36, 8.4.27, 8.5.12.
# PHP 8.1 and older: no PHP release (only minimal source backports). Reported as LIKELY VULNERABLE.
#
# What it does: runs `php -v` / `php-fpm -v` / `php-cgi -v` / `-i`, queries the package database and
# reads standard log files. It never writes, restarts, reconfigures or connects to anything.
# It contains no exploit payloads and does no network probing.
#
# Usage:
#   sudo bash check-php2shell.sh                    # discover local PHP binaries (+ log hunt)
#   bash check-php2shell.sh --version "8.4.26"      # assess a version string (or a full `php -v` line)
#   bash check-php2shell.sh --php-v-file out.txt    # assess saved `php -v` output
#   bash check-php2shell.sh --csv inventory.csv     # CSV: host,version[,changelog_cves]  (header optional)
#   bash check-php2shell.sh --bin /opt/php/bin/php  # assess one binary (repeatable)
#   bash check-php2shell.sh --search-dir /opt/x/bin # also discover runtimes in DIR (repeatable)
#   options: --no-logs  --log FILE (repeatable, replaces default log list)  -h|--help
#
# Execution guard: a candidate is only ever run (-v / -i) if its name is a PHP runtime name (php, phpN[.N],
# php-fpm*, php-cgi*, lsphp*, frankenphp), it resolves to a regular file and its first 4 bytes are the ELF
# (7f 45 4c 46) or Mach-O magic. Anything else (phpunit, phpcs, php-cs-fixer, PHP scripts) is skipped with
# a note and never executed.
# PHP2SHELL_TEST_ALLOW_SCRIPTS=1 is TEST-ONLY: it additionally accepts the pack's own mock fixtures (files
# starting with "#!/bin/sh" followed by the "# MOCK php binary for tests only" marker). Never set it in production.
#
# Verdicts / exit codes: PATCHED 0 | LIKELY VULNERABLE 1 | UNKNOWN 2 | error 3
set -u
export LC_ALL=C

CVES='CVE-2026-109618|CVE-2026-109619'
LOG_MAX_LINES=${LOG_LINES:-200000}
VULN=0; UNK=0; PATCHED=0; SUSP=0

say() { printf '%s\n' "$*"; }
hdr() { printf '\n==== %s ====\n' "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 3; }

usage() { sed -n '2,/^set -u/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'; }

status_block() {
  hdr "Exploitation status and hunt reminder"
  say "Exploitation: CONFIRMED EXPLOITED IN THE WILD (publicly reported 26 Oct 2026): remote code"
  say "  execution against an Apache mod_php honeypot running PHP 8.4.26; a memory disclosure was used to"
  say "  bypass address randomisation and the shell command ran about 1.6 ms after the final byte of the execution request."
  say "CISA KEV: BOTH CVEs LISTED - dateAdded 2026-10-26, knownRansomwareCampaignUse Unknown,"
  say "  forensicTriage Yes (KEV catalog 2026.10.26). CVE-2026-115560 is not in KEV."
  say "  CISA due date 29 Oct 2026 (applies to US federal agencies only, under BOD 26-04; patch now regardless)."
  say "REMINDER ONLY (this script does not check any of this): CISA asks for forensic triage. Where feasible,"
  say "  preserve evidence (memory, disk image or snapshot, web/PHP/system logs) before patching or rebuilding,"
  say "  but patch now. Then manually review web-worker shells, new web-root files, new or changed cron jobs,"
  say "  new local users and other persistence (see README.md and the KQL/Sigma content)."
  say "CISA: if you cannot update immediately, or run PHP 8.1 or older, take PHP-based systems offline"
  say "  until they are patched or updated."
  say "PATCHED DOES NOT MEAN CLEAN: hunt for compromise on every host that ran a vulnerable build while"
  say "  exposed - shells/curl/wget spawned by apache2/httpd/php-fpm/php-cgi/lsphp/frankenphp, new .php files"
  say "  in web roots, downloads to /tmp + chmod +x + execute, unusual outbound connections, and bursts of"
  say "  'Allowed memory size' / fatal errors / worker segfaults. See README.md and the KQL/Sigma content."
  say "Restart every PHP worker (FPM, Apache, FrankenPHP, LiteSpeed) after updating."
}

# returns 0 if $1 >= $2 (dotted numeric)
ver_ge() { [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -n1)" = "$2" ]; }

# Extract the version token from a version string or `php -v` line, e.g.
#   "PHP 8.1.2-1ubuntu2.28 (cli) ..." -> "8.1.2-1ubuntu2.28" ;  "8.4.26" -> "8.4.26"
extract_ver() {
  printf '%s' "$1" | grep -Eo '(^|[^0-9.])[0-9]+\.[0-9]+\.[0-9]+[^[:space:](),]*' | head -n1 | sed -E 's/^[^0-9]//'
}

# assess VERSION_TOKEN [CHANGELOG_CVES] [PKG_VERSION] -> sets globals VERDICT, WHY
assess() {
  local tok=$1 cves=${2:-} pkgv=${3:-} base suffix mm fixed rc
  VERDICT=UNKNOWN; WHY=""
  if printf '%s' "$cves" | grep -q 109618 && printf '%s' "$cves" | grep -q 109619; then
    VERDICT=PATCHED; WHY="package changelog references both CVE IDs (vendor backport)"; return
  fi
  base=$(printf '%s' "$tok" | grep -Eo '^[0-9]+\.[0-9]+\.[0-9]+')
  if [ -z "$base" ]; then VERDICT=UNKNOWN; WHY="could not determine the PHP version"; return; fi
  suffix=${tok#"$base"}
  [ -n "$pkgv" ] && ! printf '%s' "$pkgv" | grep -q "^$base" && suffix="${suffix} (package $pkgv)"
  mm=$(printf '%s' "$base" | cut -d. -f1,2)
  case "$mm" in
    8.2) fixed=8.2.35 ;; 8.3) fixed=8.3.36 ;; 8.4) fixed=8.4.27 ;; 8.5) fixed=8.5.12 ;;
    *)
      if ver_ge "$base" 8.6.0; then
        # PHP: 8.6.0 RC4 contains the fixes; earlier 8.6.0 pre-releases do not.
        if [ "$base" = 8.6.0 ] && printf '%s' "$suffix" | grep -Eiq 'alpha|beta|rc'; then
          rc=$(printf '%s' "$suffix" | grep -Eio 'rc[0-9]+' | grep -Eo '[0-9]+')
          if [ -z "$rc" ] || [ "$rc" -lt 4 ]; then
            VERDICT="LIKELY VULNERABLE"; WHY="8.6.0 pre-release $tok predates RC4, the first 8.6 build with the fixes"; return
          fi
        fi
        VERDICT=PATCHED; WHY="$tok is on a branch newer than the fixed releases"; return
      fi
      VERDICT="LIKELY VULNERABLE"
      WHY="PHP $base is unsupported (8.1 or older): no PHP release fixes it. Upgrade, or confirm a vendor backport"
      [ -n "$cves" ] && WHY="$WHY (changelog only mentions: $cves)"
      return ;;
  esac
  if ver_ge "$base" "$fixed"; then VERDICT=PATCHED; WHY="$base >= $fixed (fixed release for $mm)"; return; fi
  if [ -n "$cves" ]; then VERDICT=UNKNOWN; WHY="$base < $fixed but changelog mentions only: $cves; confirm both fixes with the vendor"; return; fi
  if printf '%s' "$suffix" | grep -Eiq '[0-9a-z]*(ubuntu|deb|el[0-9]|sury|\+|~|package)'; then
    VERDICT=UNKNOWN; WHY="vendor build $tok (< $fixed upstream); a backport is possible but not evidenced - check the vendor advisory"; return
  fi
  VERDICT="LIKELY VULNERABLE"; WHY="$base < $fixed (fixed release for $mm)"
}

count() { case "$VERDICT" in PATCHED) PATCHED=$((PATCHED+1)) ;; "LIKELY VULNERABLE") VULN=$((VULN+1)) ;; *) UNK=$((UNK+1)) ;; esac; }

# ---------------- argument parsing ----------------
MODE=local; IN_VERSION=""; IN_FILE=""; IN_CSV=""; DO_LOGS=1
BINS=(); LOGS=(); SEARCH_DIRS=()
while [ $# -gt 0 ]; do
  case "$1" in
    -h|--help) usage; exit 0 ;;
    --version) [ $# -ge 2 ] || die "--version needs a value"; MODE=version; IN_VERSION=$2; shift 2 ;;
    --php-v-file) [ $# -ge 2 ] || die "--php-v-file needs a file"; MODE=phpvfile; IN_FILE=$2; shift 2 ;;
    --csv) [ $# -ge 2 ] || die "--csv needs a file"; MODE=csv; IN_CSV=$2; shift 2 ;;
    --bin) [ $# -ge 2 ] || die "--bin needs a path"; BINS+=("$2"); shift 2 ;;
    --search-dir) [ $# -ge 2 ] || die "--search-dir needs a directory"; [ -d "$2" ] || die "no such directory: $2"; SEARCH_DIRS+=("$2"); shift 2 ;;
    --log) [ $# -ge 2 ] || die "--log needs a file"; LOGS+=("$2"); shift 2 ;;
    --no-logs) DO_LOGS=0; shift ;;
    *) die "unknown argument: $1 (see --help)" ;;
  esac
done

summary_exit() {
  hdr "Summary"
  say "PATCHED=$PATCHED LIKELY_VULNERABLE=$VULN UNKNOWN=$UNK suspicious_log_sources=$SUSP"
  if   [ "$VULN" -gt 0 ]; then ov="LIKELY VULNERABLE"; ec=1
  elif [ "$UNK" -gt 0 ];  then ov="UNKNOWN"; ec=2
  elif [ "$PATCHED" -gt 0 ]; then ov="PATCHED"; ec=0
  else ov="UNKNOWN"; ec=2; fi
  say "OVERALL: $ov"
  [ "$SUSP" -gt 0 ] && say "NOTE: log entries need review (the verdict reflects version only)."
  status_block
  exit "$ec"
}

# ---------------- offline modes ----------------
if [ "$MODE" = version ]; then
  hdr "Version string"
  tok=$(extract_ver "$IN_VERSION"); say "Input: $IN_VERSION"; say "Parsed version: ${tok:-<none>}"
  assess "$tok"; say "VERDICT: $VERDICT - $WHY"; count; summary_exit
fi
if [ "$MODE" = phpvfile ]; then
  if ! { [ -r "$IN_FILE" ] && [ -f "$IN_FILE" ]; }; then die "cannot read $IN_FILE"; fi
  hdr "php -v output: $IN_FILE"
  line=$(grep -m1 -E '^PHP [0-9]' "$IN_FILE"); say "Version line: ${line:-<none>}"
  tok=""; [ -n "$line" ] && tok=$(extract_ver "$line")
  assess "$tok"; say "VERDICT: $VERDICT - $WHY"; count; summary_exit
fi
if [ "$MODE" = csv ]; then
  if ! { [ -r "$IN_CSV" ] && [ -f "$IN_CSV" ]; }; then die "cannot read $IN_CSV"; fi
  hdr "CSV inventory: $IN_CSV"
  rows=0; n=0
  while IFS= read -r raw || [ -n "$raw" ]; do
    n=$((n+1)); raw=${raw%$'\r'}
    [ -z "${raw//[[:space:],]/}" ] && continue
    case "$raw" in '#'*) continue ;; esac
    IFS=, read -r host ver cv _ <<<"$raw"
    host=$(printf '%s' "$host" | tr -d '"' | sed 's/^ *//;s/ *$//')
    ver=$(printf '%s' "${ver:-}" | tr -d '"' | sed 's/^ *//;s/ *$//')
    cv=$(printf '%s' "${cv:-}" | tr -d '"')
    if [ "$n" -eq 1 ] && printf '%s' "$ver" | grep -Eiq '^(php_?)?version$'; then continue; fi
    rows=$((rows+1))
    tok=""; [ -n "$ver" ] && tok=$(extract_ver "$ver")
    cves=$(printf '%s' "$cv" | grep -Eo "$CVES" | sort -u | tr '\n' ' ')
    assess "$tok" "$cves"; count
    say "$host,${ver:-<blank>},$VERDICT,$WHY"
  done < "$IN_CSV"
  [ "$rows" -gt 0 ] || die "no data rows in $IN_CSV"
  summary_exit
fi

# ---------------- local discovery ----------------
hdr "PHP binaries"
declare -A SEEN=()
FOUND=()
SKIPPED=0
# Name allowlist: PHP runtime executables only (never phpunit, phpcs, php-cs-fixer, php-config, phpize, ...).
is_runtime_name() {
  case "$1" in php-config*|phpize*) return 1 ;; esac
  [[ "$1" =~ ^(php|php[0-9]+(\.[0-9]+)?|php-fpm.*|php-cgi.*|lsphp.*|frankenphp)$ ]]
}
# First 4 bytes as hex, read-only (od; bash-builtin fallback is safe because none of the accepted magics contain NUL).
magic_hex() {
  local f=$1 m
  if command -v od >/dev/null 2>&1; then
    od -An -tx1 -N4 -- "$f" 2>/dev/null | tr -d ' \n'
  else
    IFS= LC_ALL=C read -r -d '' -n 4 m < "$f" 2>/dev/null
    printf '%s' "$m" | LC_ALL=C awk 'BEGIN{for(i=0;i<256;i++)o[sprintf("%c",i)]=i}{for(i=1;i<=length($0);i++)printf "%02x",o[substr($0,i,1)]}'
  fi
}
is_mock_fixture() { # TEST-ONLY path, see header
  [ "${PHP2SHELL_TEST_ALLOW_SCRIPTS:-0}" = 1 ] || return 1
  [ "$(head -n1 -- "$1" 2>/dev/null)" = '#!/bin/sh' ] && sed -n 2p -- "$1" 2>/dev/null | grep -q '^# MOCK php binary for tests only'
}
skip_note() { SKIPPED=$((SKIPPED+1)); say "SKIPPED (not executed): $1 - $2"; }
add_bin() {
  local b=$1 r name rname mh
  { [ -e "$b" ] || [ -L "$b" ]; } || return 0   # literal discovery paths that do not exist: silent
  name=$(basename -- "$b")
  if ! is_runtime_name "$name"; then skip_note "$b" "name is not a PHP runtime name"; return 0; fi
  r=$(readlink -f -- "$b" 2>/dev/null || printf '%s' "$b")
  rname=$(basename -- "$r")
  [ -n "${SEEN[$r]:-}" ] && return 0
  if [ ! -f "$r" ] || [ -L "$r" ]; then skip_note "$b" "does not resolve to a regular file"; return 0; fi
  if [ ! -x "$r" ]; then skip_note "$b" "not executable"; return 0; fi
  mh=$(magic_hex "$r")
  case "$mh" in
    7f454c46|feedface|feedfacf|cefaedfe|cffaedfe|cafebabe) : ;;
    *) if is_mock_fixture "$r"; then say "TEST-ONLY: accepting mock fixture $r (PHP2SHELL_TEST_ALLOW_SCRIPTS=1)"
       else skip_note "$b" "not an ELF/Mach-O binary (magic ${mh:-unreadable}${rname:+, target $rname})"; return 0; fi ;;
  esac
  SEEN[$r]=1; FOUND+=("$r")
}
if [ ${#BINS[@]} -gt 0 ]; then
  for b in "${BINS[@]}"; do [ -e "$b" ] || die "no such binary: $b"; add_bin "$b"; done
else
  for n in php php-cgi php-fpm frankenphp lsphp; do
    p=$(command -v "$n" 2>/dev/null) && add_bin "$p"
  done
  for g in /usr/bin/php* /usr/sbin/php-fpm* /usr/local/bin/php* /usr/local/sbin/php-fpm* /usr/local/bin/frankenphp \
           /opt/*/bin/php* /opt/*/sbin/php-fpm* /opt/remi/*/root/usr/bin/php* /opt/remi/*/root/usr/sbin/php-fpm* \
           /opt/cpanel/ea-php*/root/usr/bin/php* /opt/cpanel/ea-php*/root/usr/sbin/php-fpm \
           /opt/plesk/php/*/bin/php* /opt/plesk/php/*/sbin/php-fpm /opt/lampp/bin/php* /opt/bitnami/php/bin/php* \
           /opt/bitnami/php/sbin/php-fpm /usr/local/php*/bin/php* /usr/local/php*/sbin/php-fpm /usr/lib/cgi-bin/php* \
           /usr/local/lsws/lsphp*/bin/lsphp /usr/local/lsws/lsphp*/bin/php; do
    case "$g" in *'*'*) continue ;; esac
    [ -d "$g" ] && continue
    add_bin "$g"
  done
  for pid in $(pgrep -f 'php' 2>/dev/null); do
    e=$(readlink -f "/proc/$pid/exe" 2>/dev/null) || continue
    case "$(basename "$e")" in php*|lsphp*|frankenphp) add_bin "$e" ;; esac
  done
  MODPHP=$(ls /usr/lib/apache2/modules/libphp*.so /usr/lib64/httpd/modules/libphp*.so /etc/httpd/modules/libphp*.so 2>/dev/null)
  [ -n "$MODPHP" ] && say "Apache mod_php module(s) (highest-risk SAPI): $(printf '%s' "$MODPHP" | tr '\n' ' ')- version inferred from the CLI/package of the same branch"
fi
for d in "${SEARCH_DIRS[@]}"; do
  for g in "$d"/*; do { [ -e "$g" ] || [ -L "$g" ]; } || continue; [ -d "$g" ] && continue; add_bin "$g"; done
done
[ "$SKIPPED" -gt 0 ] && say "$SKIPPED candidate(s) skipped by the execution guard (never executed)."
[ ${#FOUND[@]} -eq 0 ] && say "No PHP executables found (PHP may still be bundled inside an appliance or product)."

pkg_of() {
  local f=$1
  if command -v dpkg-query >/dev/null 2>&1; then dpkg -S "$f" 2>/dev/null | head -n1 | cut -d: -f1; return; fi
  if command -v rpm >/dev/null 2>&1; then rpm -qf --qf '%{NAME}\n' "$f" 2>/dev/null | grep -v 'not owned' | head -n1; return; fi
  if command -v apk >/dev/null 2>&1; then apk info -W "$f" 2>/dev/null | awk '/owned by/{print $NF}'; fi
}
pkg_changelog_cves() {
  local p=$1 out="" src d f
  if command -v dpkg-query >/dev/null 2>&1; then
    src=$(dpkg-query -W -f='${source:Package}' "$p" 2>/dev/null)
    for d in "/usr/share/doc/$p" "/usr/share/doc/$src"; do
      for f in "$d"/changelog.Debian.gz "$d"/changelog.gz; do
        [ -r "$f" ] && out="$out $(zcat "$f" 2>/dev/null | grep -Eo "$CVES" | sort -u | tr '\n' ' ')"
      done
    done
  elif command -v rpm >/dev/null 2>&1; then
    out=$(rpm -q --changelog "$p" 2>/dev/null | grep -Eo "$CVES" | sort -u | tr '\n' ' ')
  fi
  printf '%s' "$out" | tr ' ' '\n' | grep -E . | sort -u | tr '\n' ' '
}
pkg_version() {
  if command -v dpkg-query >/dev/null 2>&1; then dpkg-query -W -f='${Version}' "$1" 2>/dev/null
  elif command -v rpm >/dev/null 2>&1; then rpm -q --qf '%{VERSION}-%{RELEASE}' "$1" 2>/dev/null; fi
}
ini_dump() { # phpinfo for that SAPI's php.ini only (FPM pool / Apache php_value / .user.ini not included)
  [ "$2" = frankenphp ] && return 0
  timeout 10 "$1" -i 2>/dev/null | sed -E 's#<tr><td class="e">\s*([^<]*[^< ]) *</td><td class="v">\s*([^<]*[^< ]) *</td>.*#\1 => \2#; s#<i>no value</i>#no value#g'
}
ini_val() { printf '%s\n' "$1" | awk -v k="$2" -F' => ' '$1==k{print $2; exit}'; }

for b in "${FOUND[@]}"; do
  hdr "$b"
  base=$(basename "$b"); kind=cli
  case "$base" in *fpm*) kind=fpm ;; *cgi*) kind=cgi ;; lsphp*) kind=lsapi ;; frankenphp) kind=frankenphp ;; esac
  if [ "$kind" = frankenphp ]; then vline=$(timeout 10 "$b" version 2>/dev/null | grep -m1 -E 'PHP [0-9]')
  else vline=$(timeout 10 "$b" -v 2>/dev/null | head -n1); fi
  case "$vline" in *'(cgi-fcgi)'*) kind=cgi ;; *'(fpm-fcgi)'*) kind=fpm ;; esac
  tok=""; [ -n "$vline" ] && tok=$(printf '%s' "$vline" | grep -Eo 'PHP [0-9]+\.[0-9]+\.[0-9]+[^[:space:]]*' | head -n1 | cut -d' ' -f2)
  say "SAPI: $kind"
  say "Version string: ${vline:-<could not run binary>}"
  pkg=$(pkg_of "$b"); cves=""; pv=""
  if [ -n "$pkg" ]; then
    pv=$(pkg_version "$pkg"); say "Package: $pkg $pv"
    cves=$(pkg_changelog_cves "$pkg"); say "Changelog CVE references: ${cves:-none found}"
  else
    say "Package: not package-managed (source build, vendor bundle or container image)"
  fi
  assess "$tok" "$cves" "$pv"
  info=$(ini_dump "$b" "$kind")
  if [ -n "$info" ]; then
    for k in memory_limit post_max_size session.upload_progress.enabled fatal_error_backtraces session.serialize_handler; do
      v=$(ini_val "$info" "$k"); say "ini $k = ${v:-<not present>}"
    done
    ml=$(ini_val "$info" memory_limit); up=$(ini_val "$info" session.upload_progress.enabled)
    fb=$(ini_val "$info" fatal_error_backtraces); sh_=$(ini_val "$info" session.serialize_handler)
    if [ "$VERDICT" != PATCHED ]; then
      mit=""
      [ "$ml" = "-1" ] && mit="$mit memory_limit=-1(partial,109618)"
      case "$up" in Off|0) mit="$mit upload_progress=Off(partial,109619)" ;; esac
      case "$fb" in On|1) mit="$mit WARNING:fatal_error_backtraces=On" ;; esac
      say "Partial mitigations observed:${mit:- none} (none of these is a fix)"
    fi
    case "$up" in On|1)
      case "$sh_" in php_binary|php_serialize)
        say "CVE-2026-115560 (PHP informational advisory, 23 Oct 2026): config precondition present"
        say "  (session.serialize_handler=$sh_ and upload progress On). Exposure also needs application code that"
        say "  switches the handler to 'php' with ini_set() before session_start(). PHP suggests"
        say "  session.upload_progress.enabled=0 until the next regular release." ;;
      esac ;;
    esac
  else
    say "ini: could not read (FPM pool php_admin_value, Apache php_value and .user.ini are not reflected)"
  fi
  say "VERDICT: $VERDICT - $WHY"; count
done

# ---------------- log hunt (read-only, informational: does not change the exit code) ----------------
if [ "$DO_LOGS" -eq 1 ]; then
  hdr "Log hunt (read-only, informational)"
  USE_JOURNAL=0
  if [ ${#LOGS[@]} -eq 0 ]; then
    USE_JOURNAL=1
    for f in /var/log/php*-fpm*.log* /var/log/php-fpm/*.log* /var/log/php*/*.log* /var/log/apache2/*error*.log* \
             /var/log/httpd/*error*log* /var/log/nginx/*error*.log* /var/log/php_errors.log* /opt/*/logs/*error*log* \
             /usr/local/*/logs/*error*log* /opt/lampp/logs/*.log /usr/local/lsws/logs/*error*log* /var/log/syslog /var/log/messages; do
      [ -r "$f" ] && [ -f "$f" ] && LOGS+=("$f")
    done
  fi
  readlog() { case "$1" in *.gz) zcat "$1" 2>/dev/null | tail -n "$LOG_MAX_LINES" ;; *) tail -n "$LOG_MAX_LINES" "$1" 2>/dev/null ;; esac; }
  PAT_OOM='Allowed memory size of [0-9]+ bytes exhausted|Out of memory|PHP Fatal error'
  PAT_SIG='(child [0-9]+ exited on signal [0-9]+|exited on signal (6|7|11)|exit signal Segmentation fault|SIGSEGV|SIGBUS|SIGABRT|segfault at .* (php|apache2|httpd|frankenphp|lsphp))'
  [ ${#LOGS[@]} -eq 0 ] && say "No readable PHP/web server logs found in standard paths."
  for f in "${LOGS[@]}"; do
    [ -r "$f" ] || { say "cannot read $f (skipped)"; continue; }
    case "$f" in
      */syslog|*/messages)
        o=$(readlog "$f" | grep -i php | grep -Eci "$PAT_OOM"); s=$(readlog "$f" | grep -Ei 'php|httpd|apache2|frankenphp|lsphp' | grep -Eci "$PAT_SIG") ;;
      *) o=$(readlog "$f" | grep -Eci "$PAT_OOM"); s=$(readlog "$f" | grep -Eci "$PAT_SIG") ;;
    esac
    if [ "${o:-0}" -gt 0 ] || [ "${s:-0}" -gt 0 ]; then
      SUSP=$((SUSP+1))
      say "[!] REVIEW $f : memory/fatal errors=$o, worker crash/signal exits=$s"
      readlog "$f" | grep -Ei "$PAT_OOM|$PAT_SIG" | tail -n 5 | sed 's/^/      /'
    fi
  done
  if [ "$USE_JOURNAL" -eq 1 ] && command -v journalctl >/dev/null 2>&1; then
    j=$(journalctl --no-pager -q --since "-14 days" 2>/dev/null | grep -Ei 'php|httpd|apache2|frankenphp|lsphp' | grep -Ei "$PAT_OOM|$PAT_SIG" | tail -n 5)
    [ -n "$j" ] && { SUSP=$((SUSP+1)); say "[!] REVIEW journald (14 days):"; printf '%s\n' "$j" | sed 's/^/      /'; }
  fi
  [ "$SUSP" -eq 0 ] && say "No memory-exhaustion, fatal or worker-crash entries found (absence is NOT proof of safety)."
fi

summary_exit
