Exploit database

GH-75e2a533cefce0df4e9f96183f43620c

tmespro/php-emergency-mitigations

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

411 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

advisories/2026-10-cve-2026-109618/mitigate.sh

Suggested starting fileShell · 30,898 bytes
#!/usr/bin/env bash
# =============================================================================
# php-emergency-mitigations / advisory 2026-10-cve-2026-109618   v1.0.0
#
# Interim hardening for CVE-2026-109618 and CVE-2026-109619, the two critical
# unauthenticated remote code execution vulnerabilities in PHP disclosed on
# 2026-10-21 (CVSS v4.0 9.2).
#
#   THIS IS NOT A FIX. Updating PHP is the only complete fix:
#   8.5.12 / 8.4.27 / 8.3.36 / 8.2.35, or your vendor's backported package.
#   This script applies the exposure-reducing measures listed in the official
#   advisory: https://www.php.net/archive/2026.php#2026-10-21-5
#
# What it does (each part is skipped when it does not apply):
#   - PHP-FPM pools: session.upload_progress.enabled=off, memory_limit=-1,
#     fatal_error_backtraces=off (PHP 8.5+), conservative input limits.
#     PHP-FPM keeps the FIRST value a pool sets for a directive, so conflicting
#     earlier lines are commented out instead of being silently shadowed.
#   - php.ini snippet in every PHP conf.d directory found.
#   - Apache: request size and header limits; mod_php gets php_admin_* values.
#   - nginx: audit only (its defaults are already strict).
#   - Config tests; a change that fails its test is rolled back automatically.
#   - Graceful reloads, then a live HTTP probe checks the values PHP really uses.
#
# Usage (as root):
#   bash mitigate.sh                     dry run: shows the plan, changes nothing
#   bash mitigate.sh --apply             applies the mitigation
#   bash mitigate.sh --revert --apply    removes it once PHP is updated
#
# Options:
#   --apply              make changes (default is a dry run)
#   --revert             remove a mitigation applied by this script
#   --big-uploads        allow 32M POST / 30M uploads (default 8M / 6M)
#   --keep-memory-limit  do not force memory_limit=-1 (the advisory recommends
#                        -1 together with a container/cgroup memory limit)
#   --no-webserver       do not touch Apache configuration
#   --no-reload          write and test config, but do not reload services
#   --no-probe           do not place a temporary probe file in the web root
#   --force              run even if every PHP build found looks patched
#   -h, --help           show this help
#
# Idempotent. Every modified file is backed up as <file>.bak-<timestamp>.
# Requires bash 4.4+. License: MIT. Provided "as is", without warranty.
# https://github.com/tmespro/php-emergency-mitigations
# =============================================================================
set -Eeuo pipefail

VERSION="1.0.0"
ADVISORY="2026-10-cve-2026-109618"

APPLY=0; REVERT=0; BIG=0; KEEP_MEM=0; NO_WEB=0; NO_RELOAD=0; NO_PROBE=0; FORCE=0
for arg in "$@"; do
  case "$arg" in
    --apply)             APPLY=1 ;;
    --revert)            REVERT=1 ;;
    --big-uploads)       BIG=1 ;;
    --keep-memory-limit) KEEP_MEM=1 ;;
    --no-webserver)      NO_WEB=1 ;;
    --no-reload)         NO_RELOAD=1 ;;
    --no-probe)          NO_PROBE=1 ;;
    --force)             FORCE=1 ;;
    -h|--help)
      sed -n '3,/^# =====/{/^# =====/d;s/^# \{0,1\}//;p;}' "$0"
      exit 0 ;;
    --version)           echo "$ADVISORY $VERSION"; exit 0 ;;
    *)                   echo "Unknown option: $arg (see --help)"; exit 2 ;;
  esac
done

if (( BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 4) )); then
  echo "bash 4.4 or newer is required."; exit 1
fi
if [[ $EUID -ne 0 ]]; then echo "Please run as root."; exit 1; fi

STAMP=$(date +%Y%m%d-%H%M%S)
TAG="CVE-2026-109618/109619 mitigation"
BEGIN_MARK="; >>> $TAG $STAMP (remove after updating PHP)"
END_MARK="; <<< $TAG"
SNIP="zz-cve-2026-109618-mitigation"
INI_NAME="99-cve-2026-109618-mitigation.ini"
POOL_KEYS='session\.upload_progress\.enabled|memory_limit|fatal_error_backtraces|post_max_size|upload_max_filesize|max_input_vars|max_input_nesting_level|max_multipart_body_parts|max_file_uploads'

if (( BIG )); then POST_MAX=32M; UPLOAD_MAX=30M; BODY_BYTES=33554432
else               POST_MAX=8M;  UPLOAD_MAX=6M;  BODY_BYTES=8388608; fi

BACKUPS=(); NEWFILES=(); WARNINGS=(); RESULTS=(); S=()
declare -A BACKED=()
LAST_CHANGED=0
PROBE_FILE=""
trap 'if [[ -n "${PROBE_FILE:-}" ]]; then rm -f "$PROBE_FILE"; fi' EXIT

# ----------------------------------------------------------------- helpers ---
say()  { printf '%s\n' "$*"; }
info() { printf '  %s\n' "$*"; }
warn() { printf '  WARN %s\n' "$*"; WARNINGS+=("$*"); }
plan() { if (( APPLY )); then printf '  DO   %s\n' "$*"; else printf '  PLAN %s\n' "$*"; fi; }

esc_re()  { printf '%s' "$1" | sed 's/[][\.*^$]/\\&/g'; }
ini_val() { sed -E 's/^[^=]*=[[:space:]]*//; s/[[:space:]]*;.*$//; s/[[:space:]]+$//; s/^"(.*)"$/\1/' <<< "$1"; }
norm() {
  local v="${1,,}"
  case "$v" in
    on|1|true|yes)          echo 1 ;;
    off|0|false|no|none|"") echo 0 ;;
    *)                      echo "$v" ;;
  esac
}
to_num() {   # "8M" -> bytes, "1000" -> 1000, anything else -> nothing
  local v="${1^^}" n
  if [[ "$v" =~ ^([0-9]+)([KMG]?)$ ]]; then
    n="${BASH_REMATCH[1]}"
    case "${BASH_REMATCH[2]}" in
      K) echo $((n * 1024)) ;;
      M) echo $((n * 1048576)) ;;
      G) echo $((n * 1073741824)) ;;
      *) echo "$n" ;;
    esac
  fi
}
ver_ge() { [[ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -1)" == "$2" ]]; }
fixed_for() {
  case "$1" in
    8.5.*) echo 8.5.12 ;; 8.4.*) echo 8.4.27 ;; 8.3.*) echo 8.3.36 ;; 8.2.*) echo 8.2.35 ;;
    *) echo "" ;;
  esac
}
ver_status() {   # patched | unpatched | eol | unknown
  local v="$1" f
  if [[ -z "$v" ]]; then echo unknown; return 0; fi
  f=$(fixed_for "$v")
  if [[ -z "$f" ]]; then echo eol; return 0; fi
  if ver_ge "$v" "$f"; then echo patched; else echo unpatched; fi
}
has_multipart() {   # max_multipart_body_parts exists since 8.0.28 / 8.1.16 / 8.2.3
  local v="$1"
  case "$v" in
    8.0.*) ver_ge "$v" 8.0.28 ;;
    8.1.*) ver_ge "$v" 8.1.16 ;;
    8.2.*) ver_ge "$v" 8.2.3 ;;
    8.*|9.*) return 0 ;;
    *) return 1 ;;
  esac
}
path_is_85() { [[ "$1" =~ (/php/8\.5/|php85|lsphp85) ]]; }
proc_running() {   # process name (comm), works without pgrep
  local p c
  for p in /proc/[0-9]*; do
    c=$(cat "$p/comm" 2>/dev/null || true)
    if [[ "$c" == "$1" ]]; then return 0; fi
  done
  return 1
}
find_master() {    # FPM master pid for a given main config path
  local conf="$1" p cmd
  for p in /proc/[0-9]*; do
    cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null || true)
    if [[ "$cmd" == *"master process ($conf)"* ]]; then echo "${p#/proc/}"; return 0; fi
  done
  return 1
}
pool_glob() {      # include= glob of an FPM main config, resolved to an absolute pattern
  local conf="$1" val d
  val=$(sed -nE 's/^[[:space:]]*include[[:space:]]*=[[:space:]]*//p' "$conf" 2>/dev/null | head -1 \
        | sed -E 's/[[:space:]]*;.*$//; s/[[:space:]]+$//; s/^"(.*)"$/\1/' || true)
  if [[ -n "$val" && "$val" != /* ]]; then val="$(dirname "$conf")/../$val"; fi   # relative to the FPM prefix
  if [[ -z "$val" ]]; then
    for d in "$(dirname "$conf")/php-fpm.d" "$(dirname "$conf")/pool.d"; do
      if [[ -d "$d" ]]; then val="$d/*.conf"; break; fi
    done
  fi
  printf '%s' "$val"
}
apache_graceful() {
  # Debian's apache2ctl handles "graceful" itself. RHEL's apachectl hands it to systemctl,
  # which is absent in containers, so fall back to signalling the httpd binary directly.
  if "$APACHECTL" graceful >/dev/null 2>&1; then return 0; fi
  if command -v httpd >/dev/null 2>&1 && httpd -k graceful >/dev/null 2>&1; then return 0; fi
  return 1
}
backup_once() {
  local f="$1"
  if (( ! APPLY )); then return 0; fi
  if [[ ! -e "$f" && ! -L "$f" ]]; then return 0; fi
  if [[ -z "${BACKED[$f]:-}" ]]; then
    cp -a "$f" "$f.bak-$STAMP"
    BACKUPS+=("$f.bak-$STAMP")
    BACKED[$f]=1
  fi
}
undo_file() {      # restore a file changed in this run, or delete one created in this run
  local f="$1" n
  if [[ -n "${BACKED[$f]:-}" && -e "$f.bak-$STAMP" ]]; then cp -a "$f.bak-$STAMP" "$f"; return 0; fi
  for n in "${NEWFILES[@]}"; do
    if [[ "$n" == "$f" ]]; then rm -f "$f"; fi
  done
}
write_file() {     # path, content (idempotent)
  local f="$1" content="$2"
  LAST_CHANGED=0
  if [[ -f "$f" ]] && [[ "$(cat "$f")" == "$content" ]]; then info "OK   $f already up to date"; return 0; fi
  plan "write $f"
  LAST_CHANGED=1
  if (( APPLY )); then
    if [[ -e "$f" ]]; then backup_once "$f"; else NEWFILES+=("$f"); fi
    printf '%s\n' "$content" > "$f"
  fi
}
remove_file() {   # only used for files this script generated: no backup needed
  local f="$1"
  LAST_CHANGED=0
  if [[ ! -e "$f" && ! -L "$f" ]]; then return 0; fi
  plan "remove $f"
  LAST_CHANGED=1
  if (( APPLY )); then rm -f "$f"; fi
}
build_settings() {   # name|directive|value|policy  (FORCE: our value must win, KEEP: keep existing)
  local v="$1"
  S=("session.upload_progress.enabled|php_admin_flag|off|FORCE")
  if (( ! KEEP_MEM )); then S+=("memory_limit|php_admin_value|-1|FORCE"); fi
  if ver_ge "$v" 8.5.0; then S+=("fatal_error_backtraces|php_admin_flag|off|FORCE"); fi
  S+=("post_max_size|php_admin_value|$POST_MAX|KEEP"
      "upload_max_filesize|php_admin_value|$UPLOAD_MAX|KEEP"
      "max_input_vars|php_admin_value|1000|KEEP"
      "max_input_nesting_level|php_admin_value|16|KEEP"
      "max_file_uploads|php_admin_value|10|KEEP")
  if has_multipart "$v"; then S+=("max_multipart_body_parts|php_admin_value|200|KEEP"); fi
}
ini_content() {    # $1 = 1 for PHP 8.5+
  echo "; CVE-2026-109618 / CVE-2026-109619 interim mitigation (php.net advisory, 2026-10-21)."
  echo "; Added by php-emergency-mitigations. Remove once PHP is updated (mitigate.sh --revert --apply)."
  echo "session.upload_progress.enabled = 0"
  if [[ "${1:-0}" == "1" ]]; then echo "fatal_error_backtraces = 0"; fi
}

# ------------------------------------------------------------- detection ---
say "php-emergency-mitigations: $ADVISORY v$VERSION (CVE-2026-109618, CVE-2026-109619)"
say "Host: $(hostname 2>/dev/null || cat /etc/hostname 2>/dev/null || echo unknown)   $(date -u '+%Y-%m-%d %H:%M UTC')"
if (( REVERT )); then MODE="REVERT"; else MODE="MITIGATE"; fi
if (( APPLY )); then say "Mode: $MODE (applying changes)"
else say "Mode: $MODE, DRY RUN: nothing will be changed (add --apply)"; fi

say "== 0. Detection =="
I_BIN=(); I_VER=(); I_CONF=(); I_GLOB=(); I_SCAN=()
declare -A SEEN=()
for b in /usr/sbin/php-fpm /usr/sbin/php-fpm[0-9]* /usr/local/sbin/php-fpm \
         /opt/remi/php*/root/usr/sbin/php-fpm /opt/cpanel/ea-php*/root/usr/sbin/php-fpm \
         /opt/plesk/php/*/sbin/php-fpm; do
  if [[ ! -x "$b" ]]; then continue; fi
  rb=$(readlink -f "$b" 2>/dev/null || echo "$b")
  if [[ -n "${SEEN[$rb]:-}" ]]; then continue; fi
  SEEN[$rb]=1
  ver=$("$b" -v 2>/dev/null | sed -n '1s/^PHP \([0-9][0-9.]*\).*/\1/p' || true)
  tout=$("$b" -t 2>&1 || true)
  conf=$(printf '%s\n' "$tout" | sed -n 's/.*configuration file \(.*\) test is successful.*/\1/p' | head -1 || true)
  if [[ -z "$conf" ]]; then
    warn "$b: its configuration test fails, skipped ($(printf '%s' "$tout" | tail -1))"
    continue
  fi
  glob=$(pool_glob "$conf")
  scan=$("$b" -i 2>/dev/null | sed -n 's/^Scan this dir for additional \.ini files => //p' | head -1 || true)
  if [[ "$scan" == "(none)" ]]; then scan=""; fi
  I_BIN+=("$b"); I_VER+=("$ver"); I_CONF+=("$conf"); I_GLOB+=("$glob"); I_SCAN+=("$scan")
  info "PHP-FPM ${ver:-?}  $b  [$(ver_status "$ver")]"
  info "        config=$conf  pools=${glob:-not found}"
done
if (( ${#I_BIN[@]} == 0 )); then info "no PHP-FPM found"; fi

CLI_VER=""; CLI_SCAN=""
if command -v php >/dev/null 2>&1; then
  CLI_VER=$(php -r 'echo PHP_VERSION;' 2>/dev/null || true)
  CLI_SCAN=$(php --ini 2>/dev/null | sed -n 's/^Scan for additional \.ini files in: //p' | head -1 || true)
  if [[ "$CLI_SCAN" == "(none)" ]]; then CLI_SCAN=""; fi
  info "PHP CLI ${CLI_VER:-?}  $(command -v php)  [$(ver_status "$CLI_VER")]"
fi

INI_DIRS=()
declare -A INI_SEEN=() DIR_IS_85=()
add_ini_dir() {
  local d="$1" v="${2:-}"
  if [[ -z "$d" || ! -d "$d" ]]; then return 0; fi
  d=$(readlink -f "$d")
  if [[ -z "${INI_SEEN[$d]:-}" ]]; then INI_SEEN[$d]=1; INI_DIRS+=("$d"); fi
  if [[ -n "$v" ]] && ver_ge "$v" 8.5.0; then DIR_IS_85[$d]=1; fi
  if path_is_85 "$d"; then DIR_IS_85[$d]=1; fi
}
for i in "${!I_BIN[@]}"; do add_ini_dir "${I_SCAN[$i]}" "${I_VER[$i]}"; done
add_ini_dir "$CLI_SCAN" "$CLI_VER"
for d in /etc/php.d /etc/opt/remi/php*/php.d /etc/php/*/fpm/conf.d /etc/php/*/apache2/conf.d \
         /etc/php/*/cgi/conf.d /etc/php/*/cli/conf.d /usr/local/etc/php/conf.d \
         /opt/cpanel/ea-php*/root/etc/php.d /opt/plesk/php/*/etc/php.d /usr/local/lsws/lsphp*/etc/php.d; do
  add_ini_dir "$d"
done

APACHECTL=""; AROOT=""; A_RUNNING=0; MODPHP=0; ASNIP=""; AMODE=""
if (( ! NO_WEB )); then
  for c in apachectl apache2ctl; do
    if command -v "$c" >/dev/null 2>&1; then APACHECTL=$(command -v "$c"); break; fi
  done
fi
if [[ -n "$APACHECTL" ]]; then
  if proc_running httpd || proc_running apache2; then A_RUNNING=1; fi
  AROOT=$("$APACHECTL" -V 2>/dev/null | sed -n 's/.*HTTPD_ROOT="\(.*\)".*/\1/p' | head -1 || true)
  amods=$("$APACHECTL" -M 2>/dev/null || true)
  if grep -qE '^[[:space:]]*php[0-9]*_module' <<< "$amods"; then MODPHP=1; fi
  if [[ -n "$AROOT" && -d "$AROOT/conf.d" ]]; then ASNIP="$AROOT/conf.d/$SNIP.conf"; AMODE=confd
  elif [[ -n "$AROOT" && -d "$AROOT/conf-available" ]]; then ASNIP="$AROOT/conf-available/$SNIP.conf"; AMODE=debian
  fi
  if (( A_RUNNING )); then
    if (( MODPHP )); then
      info "Apache running ($APACHECTL, root ${AROOT:-?}), mod_php LOADED (highest-risk setup per the advisory)"
    else
      info "Apache running ($APACHECTL, root ${AROOT:-?})"
    fi
  else
    info "Apache installed but not running: left untouched"
  fi
fi

N_RUNNING=0; NGX_DUMP=""
if command -v nginx >/dev/null 2>&1 && proc_running nginx; then
  N_RUNNING=1
  NGX_DUMP=$(nginx -T 2>/dev/null || true)
  info "nginx running"
fi

if (( ${#I_BIN[@]} == 0 && MODPHP == 0 && ${#INI_DIRS[@]} == 0 )); then
  say "No PHP installation found. Nothing to do."; exit 0
fi

NEED=0
declare -A EOL_WARNED=()
for v in "${I_VER[@]}" "$CLI_VER"; do
  case "$(ver_status "$v")" in
    unpatched) NEED=1 ;;
    eol)
      NEED=1
      if [[ -z "${EOL_WARNED[$v]:-}" ]]; then
        EOL_WARNED[$v]=1
        warn "PHP $v has no upstream fix. Use your vendor's backport (check its advisory) or upgrade."
      fi
      ;;
    unknown) if [[ -n "$v" ]]; then NEED=1; fi ;;
  esac
done
if (( MODPHP && A_RUNNING )); then NEED=1; fi
if (( ${#I_BIN[@]} == 0 )) && [[ -z "$CLI_VER" ]]; then NEED=1; fi
if (( ! REVERT && ! NEED && ! FORCE )); then
  say "Every PHP build found reports a patched version. Nothing to do."
  say "(Use --force to apply anyway, or --revert --apply to remove an earlier mitigation.)"
  exit 0
fi
info "Note: distribution packages may carry the fix under an older version number (backports)."

# ------------------------------------------------------------- PHP-FPM -----
declare -A RELOAD_FPM=()
POOL_CHANGED=0; FILES_OF_INSTALL=()

process_pool() {   # file, php version
  local f="$1" v="$2" s name dir want policy lines l c val eff has_admin all_match n a w sections
  local -a to_add=() to_comment=()
  sections=$(grep -cE '^[[:space:]]*\[' "$f" || true)
  if [[ "$sections" != "1" ]]; then
    if grep -qE "^[[:space:]]*php_(admin_)?(value|flag)\[($POOL_KEYS)\]" "$f"; then
      warn "$f: $sections pool sections and relevant settings, skipped (edit it by hand)"
    else
      info "Pool file $f: $sections sections, no relevant settings, left as is"
    fi
    return 0
  fi
  info "Pool $f"
  build_settings "$v"
  for s in "${S[@]}"; do
    IFS='|' read -r name dir want policy <<< "$s"
    lines=$(grep -nE "^[[:space:]]*php_(admin_)?(value|flag)\[$(esc_re "$name")\][[:space:]]*=" "$f" || true)
    if [[ -z "$lines" ]]; then
      to_add+=("${dir}[${name}] = ${want}")
      plan "  $name = $want (added)"
      continue
    fi
    # Effective value: first php_admin_* line wins, otherwise first php_value / php_flag line
    eff=""; has_admin=0; all_match=1
    while IFS= read -r l; do
      c="${l#*:}"
      val=$(ini_val "$c")
      if [[ "$(norm "$val")" != "$(norm "$want")" ]]; then all_match=0; fi
      if [[ "$c" =~ php_admin_ ]]; then
        if (( has_admin == 0 )); then eff="$val"; has_admin=1; fi
      elif (( has_admin == 0 )) && [[ -z "$eff" ]]; then
        eff="$val"
      fi
    done <<< "$lines"
    if [[ "$policy" == "FORCE" ]]; then
      if (( all_match == 1 && has_admin == 1 )); then
        info "  OK   $name = $eff"
      else
        while IFS= read -r l; do to_comment+=("${l%%:*}"); done <<< "$lines"
        to_add+=("${dir}[${name}] = ${want}")
        plan "  $name: '$eff' -> $want (conflicting line(s) commented out)"
      fi
    else
      a=$(to_num "$eff"); w=$(to_num "$want")
      if [[ "$(norm "$eff")" == "$(norm "$want")" ]]; then
        info "  OK   $name = $eff"
      elif [[ "$name" =~ (_size|_filesize)$ && -n "$a" && -n "$w" ]] && (( a == 0 || a > w )); then
        warn "$f: $name = $eff is above the suggested $want. Kept; lower it if your application allows."
      else
        info "  KEEP $name = $eff (existing value kept, suggested $want)"
      fi
    fi
  done
  if (( ${#to_add[@]} == 0 && ${#to_comment[@]} == 0 )); then return 0; fi
  POOL_CHANGED=1
  if (( APPLY )); then
    backup_once "$f"; FILES_OF_INSTALL+=("$f")
    for n in "${to_comment[@]}"; do sed -i "${n}s|^|; [$TAG $STAMP] |" "$f"; done
    if (( ${#to_add[@]} )); then
      { echo; echo "$BEGIN_MARK"; printf '%s\n' "${to_add[@]}"; echo "$END_MARK"; } >> "$f"
    fi
  fi
}

revert_pool() {    # file
  local f="$1"
  if ! grep -qF "$TAG" "$f"; then return 0; fi
  plan "remove mitigation lines from $f"
  POOL_CHANGED=1
  if (( APPLY )); then
    backup_once "$f"; FILES_OF_INSTALL+=("$f")
    # drop each appended block and the single blank line written just before it,
    # then uncomment the lines this script commented out (file inode and mode kept)
    awk -v b="; >>> $TAG" -v e="; <<< $TAG" '
      skip               { if (index($0, e) == 1) skip = 0; next }
      index($0, b) == 1  { skip = 1; pend = 0; next }
      pend               { print ""; pend = 0 }
      $0 == ""           { pend = 1; next }
                         { print }
      END                { if (pend) print "" }' "$f" > "$f.tmp-$STAMP"
    sed -E "s|^; \\[$TAG [0-9-]+\\] ||" "$f.tmp-$STAMP" > "$f"
    rm -f "$f.tmp-$STAMP"
  fi
}

say "== 1. PHP-FPM pools (the first value a pool sets wins) =="
if (( ${#I_BIN[@]} == 0 )); then info "no PHP-FPM, skipped"; fi
for i in "${!I_BIN[@]}"; do
  say "-- PHP-FPM ${I_VER[$i]:-?} (${I_BIN[$i]})"
  if [[ -z "${I_GLOB[$i]}" ]]; then warn "no pool include found in ${I_CONF[$i]}: edit its pools by hand"; continue; fi
  POOL_CHANGED=0; FILES_OF_INSTALL=()
  while IFS= read -r f; do
    if [[ ! -f "$f" ]]; then continue; fi
    if (( REVERT )); then revert_pool "$f"; else process_pool "$f" "${I_VER[$i]}"; fi
  done < <(compgen -G "${I_GLOB[$i]}" | sort || true)
  if (( APPLY && POOL_CHANGED )); then
    if out=$("${I_BIN[$i]}" -t 2>&1); then
      info "config test OK"
      RELOAD_FPM[$i]=1
    else
      warn "config test FAILED for ${I_BIN[$i]}, its changes were rolled back: $(printf '%s' "$out" | tail -1)"
      for f in "${FILES_OF_INSTALL[@]}"; do undo_file "$f"; done
    fi
  fi
done

# ------------------------------------------------------------ php.ini ------
say "== 2. php.ini snippets ($INI_NAME) =="
INI_CHANGED=0
if (( ${#INI_DIRS[@]} == 0 )); then info "no conf.d directory found"; fi
for d in "${INI_DIRS[@]}"; do
  if (( REVERT )); then
    remove_file "$d/$INI_NAME"
  else
    write_file "$d/$INI_NAME" "$(ini_content "${DIR_IS_85[$d]:-0}")"
  fi
  if (( LAST_CHANGED )); then INI_CHANGED=1; fi
done

# -------------------------------------------------------------- Apache -----
say "== 3. Apache =="
A_RELOAD=0; A_ENABLED_NOW=0; A_CHANGED=0
a_where() { # where a php directive is already set in the Apache config (outside our snippet)
  grep -rnsIE --exclude="$SNIP.conf*" "^[[:space:]]*php_(admin_)?(value|flag)[[:space:]]+$(esc_re "$1")([[:space:]]|$)" "$AROOT" \
    | head -3 || true
}
a_has() { [[ -n "$(a_where "$1")" ]]; }
if (( NO_WEB )); then
  info "--no-webserver: skipped"
elif [[ -z "$APACHECTL" || $A_RUNNING -eq 0 ]]; then
  info "Apache not running, skipped"
elif [[ -z "$ASNIP" ]]; then
  warn "Apache config layout not recognized (root: ${AROOT:-?}): add request limits by hand"
elif (( REVERT )); then
  if [[ "$AMODE" == debian && -e "$AROOT/conf-enabled/$SNIP.conf" ]]; then
    plan "a2disconf $SNIP"
    if (( APPLY )); then a2disconf -q "$SNIP" >/dev/null || true; fi
    A_CHANGED=1
  fi
  remove_file "$ASNIP"
  if (( LAST_CHANGED )); then A_CHANGED=1; fi
else
  A_LINES=("# CVE-2026-109618 / CVE-2026-109619 interim mitigation (php.net advisory, 2026-10-21)."
           "# Added by php-emergency-mitigations. Remove once PHP is updated (mitigate.sh --revert --apply)."
           "LimitRequestBody $BODY_BYTES"
           "LimitRequestFields 64"
           "LimitRequestFieldSize 8190"
           "LimitRequestLine 8190")
  other=$(grep -rnsIE --exclude="$SNIP.conf*" '^[[:space:]]*LimitRequestBody[[:space:]]' "$AROOT" || true)
  if [[ -n "$other" ]]; then
    info "Existing LimitRequestBody values (a vhost/directory value overrides this one):"
    printf '%s\n' "$other" | head -5 | sed 's/^/      /'
  fi
  if (( MODPHP )); then
    P=("php_admin_flag session.upload_progress.enabled off")
    if (( ! KEEP_MEM )); then P+=("php_admin_value memory_limit -1"); fi
    for kv in "post_max_size $POST_MAX" "upload_max_filesize $UPLOAD_MAX" "max_input_vars 1000" \
              "max_input_nesting_level 16" "max_file_uploads 10"; do
      key="${kv%% *}"
      if a_has "$key"; then info "KEEP $key (already set in the Apache config)"; else P+=("php_admin_value $kv"); fi
    done
    for key in session.upload_progress.enabled memory_limit; do
      loc=$(a_where "$key")
      if [[ -n "$loc" ]]; then
        warn "Apache config also sets $key; a value inside a vhost or directory block overrides this snippet. Review:"
        printf '%s\n' "$loc" | sed 's/^/      /'
      fi
    done
    for m in php_module php7_module; do
      A_LINES+=("<IfModule $m>")
      for p in "${P[@]}"; do A_LINES+=("    $p"); done
      A_LINES+=("</IfModule>")
    done
  fi
  write_file "$ASNIP" "$(printf '%s\n' "${A_LINES[@]}")"
  A_CHANGED=$LAST_CHANGED
  if [[ "$AMODE" == debian && ! -e "$AROOT/conf-enabled/$SNIP.conf" ]]; then
    plan "a2enconf $SNIP"
    if (( APPLY )); then
      if a2enconf -q "$SNIP" >/dev/null; then A_ENABLED_NOW=1
      else warn "a2enconf $SNIP failed: enable the snippet by hand"; fi
    fi
    A_CHANGED=1
  fi
fi
if (( APPLY && A_CHANGED )); then
  if out=$("$APACHECTL" -t 2>&1); then
    info "Apache config test OK"; A_RELOAD=1
  else
    warn "Apache config test FAILED, change rolled back: $(printf '%s' "$out" | tail -1)"
    if (( A_ENABLED_NOW )); then a2disconf -q "$SNIP" >/dev/null || true; fi
    undo_file "$ASNIP"
  fi
fi

# --------------------------------------------------------------- nginx -----
say "== 4. nginx (audit only) =="
if (( N_RUNNING )); then
  nb=$(grep -E '^[[:space:]]*client_max_body_size[[:space:]]' <<< "$NGX_DUMP" | sed 's/^[[:space:]]*//' | sort -u || true)
  if [[ -z "$nb" ]]; then
    info "OK   client_max_body_size not set (nginx default 1m)"
  else
    info "client_max_body_size values found (keep them as low as your app allows):"
    printf '%s\n' "$nb" | head -10 | sed 's/^/      /'
  fi
  hb=$(grep -E '^[[:space:]]*large_client_header_buffers[[:space:]]' <<< "$NGX_DUMP" | sed 's/^[[:space:]]*//' | sort -u || true)
  if [[ -n "$hb" ]]; then info "large_client_header_buffers: $(printf '%s' "$hb" | tr '\n' ' ')"; fi
else
  info "nginx not running, skipped"
fi

# -------------------------------------------------------------- reload -----
say "== 5. Reload =="
if (( ! APPLY )); then
  info "dry run: nothing reloaded"
elif (( NO_RELOAD )); then
  info "--no-reload: reload PHP-FPM and Apache yourself"
else
  for i in "${!I_BIN[@]}"; do
    if [[ -n "${RELOAD_FPM[$i]:-}" ]] || (( INI_CHANGED )); then
      pid=$(find_master "${I_CONF[$i]}" || true)
      if [[ -n "$pid" ]]; then
        if kill -USR2 "$pid"; then info "reloaded PHP-FPM ${I_VER[$i]} (master pid $pid)"
        else warn "could not reload PHP-FPM ${I_VER[$i]} (pid $pid): reload it yourself"; fi
      else
        info "PHP-FPM ${I_VER[$i]} not running, nothing to reload"
      fi
    fi
  done
  if (( A_RUNNING )) && { (( A_RELOAD )) || (( INI_CHANGED && MODPHP )); }; then
    if apache_graceful; then info "reloaded Apache (graceful)"
    else warn "Apache graceful reload failed: reload it yourself"; fi
  fi
fi

# --------------------------------------------------------------- probe -----
say "== 6. Live check =="
check_probe() {
  local out="$1" where="$2" up ml fb php
  up=$(sed -n 's/^session\.upload_progress\.enabled=//p' <<< "$out")
  ml=$(sed -n 's/^memory_limit=//p' <<< "$out")
  fb=$(sed -n 's/^fatal_error_backtraces=//p' <<< "$out")
  php=$(sed -n 's/^php=//p' <<< "$out")
  info "via $where: PHP $php"
  if [[ "$up" == "" || "$up" == "0" ]]; then RESULTS+=("PASS upload progress off ($php)")
  else RESULTS+=("FAIL session.upload_progress.enabled = '$up' ($php)"); fi
  if (( ! KEEP_MEM )); then
    if [[ "$ml" == "-1" ]]; then RESULTS+=("PASS memory_limit = -1 ($php)")
    else RESULTS+=("FAIL memory_limit = '$ml' ($php)"); fi
  fi
  if [[ "$fb" != "(n/a)" ]]; then
    if [[ "$fb" == "" || "$fb" == "0" ]]; then RESULTS+=("PASS fatal_error_backtraces off ($php)")
    else RESULTS+=("FAIL fatal_error_backtraces = '$fb' ($php)"); fi
  fi
}
if (( ! APPLY || REVERT || NO_PROBE )); then
  info "skipped (runs only with --apply, without --revert / --no-probe)"
elif ! command -v curl >/dev/null 2>&1; then
  warn "curl not found: check the values with a temporary phpinfo() page"
else
  sleep 3
  TARGETS=()
  if (( A_RUNNING )); then
    # RHEL's apachectl wrapper does not always pass -S through: ask httpd directly as a
    # fallback, then read DocumentRoot directives from the configuration itself.
    sout=$("$APACHECTL" -S 2>&1 || true)
    if [[ "$sout" != *"Main DocumentRoot"* ]] && command -v httpd >/dev/null 2>&1; then
      sout=$(httpd -S 2>&1 || true)
    fi
    while IFS= read -r r; do
      if [[ -n "$r" ]]; then TARGETS+=("$r"); fi
    done < <(
      sed -n 's/^Main DocumentRoot: "\(.*\)"$/\1/p' <<< "$sout" | head -1
      if [[ -n "$AROOT" ]]; then
        grep -rhsIE '^[[:space:]]*DocumentRoot[[:space:]]' "$AROOT" | awk '{ r = $2; gsub(/"/, "", r); print r }' | head -5
      fi
    )
  fi
  if (( N_RUNNING )); then
    while IFS= read -r r; do
      if [[ -n "$r" ]]; then TARGETS+=("$r"); fi
    done < <(awk '$1 == "root" { r = $2; sub(/;$/, "", r); print r }' <<< "$NGX_DUMP" | sort -u | head -5)
  fi
  TARGETS+=("/var/www/html")   # common default, tried last
  probed=0
  declare -A TRIED=()
  for dr in "${TARGETS[@]}"; do
    if [[ ! -d "$dr" || -n "${TRIED[$dr]:-}" ]]; then continue; fi
    TRIED[$dr]=1
    name="cve-probe-$RANDOM$RANDOM.php"
    PROBE_FILE="$dr/$name"
    cat > "$PROBE_FILE" <<'EOF'
<?php header('Content-Type: text/plain');
echo "probe=ok\n";
foreach (['session.upload_progress.enabled', 'memory_limit', 'fatal_error_backtraces'] as $k) {
    $v = ini_get($k);
    echo $k, '=', ($v === false ? '(n/a)' : $v), "\n";
}
echo 'php=', PHP_VERSION, ' ', PHP_SAPI, "\n";
EOF
    chmod 644 "$PROBE_FILE"
    out=$(curl -s --max-time 10 "http://127.0.0.1/$name" 2>/dev/null || true)
    rm -f "$PROBE_FILE"; PROBE_FILE=""
    if [[ "$out" == *"probe=ok"* ]]; then check_probe "$out" "$dr"; probed=1; break; fi
  done
  if (( ! probed )); then
    warn "could not reach PHP through http://127.0.0.1/: check the values with a temporary phpinfo() page"
  fi
fi

# ------------------------------------------------- crashes and startup -----
say "== 7. Worker crashes and startup diagnostics =="
for log in /var/log/php-fpm/error.log /var/log/php*-fpm.log /var/opt/remi/php*/log/php-fpm/error.log \
           /opt/cpanel/ea-php*/root/usr/var/log/php-fpm.log /usr/local/var/log/php-fpm.log; do
  if [[ ! -f "$log" ]]; then continue; fi
  info "$log: $(grep -cE 'signal (11|6|7)|SIGSEGV|SIGABRT|SIGBUS' "$log" || true) worker crash line(s)"
done
dm=$(dmesg 2>/dev/null | grep -ciE 'php.*(segfault|general protection)' || true)
info "kernel log: ${dm:-0} PHP segfault line(s)"
for i in "${!I_BIN[@]}"; do
  diag=$("${I_BIN[$i]}" -i 2>&1 | grep -E '^(PHP )?(Warning|Deprecated|Notice|Fatal error)' | head -3 || true)
  if [[ -n "$diag" ]]; then
    warn "PHP-FPM ${I_VER[$i]} emits startup diagnostics (the advisory says to remove invalid or deprecated settings):"
    printf '%s\n' "$diag" | sed 's/^/      /'
  fi
done

# ------------------------------------------------------------- summary -----
say
say "== Summary =="
FAILED=0
if (( ${#RESULTS[@]} )); then
  for r in "${RESULTS[@]}"; do
    info "$r"
    if [[ "$r" == FAIL* ]]; then FAILED=1; fi
  done
fi
if (( FAILED )); then
  say "A FAIL means the live PHP still uses an unsafe value. Fix what the WARN lines point to;"
  say "if you already edited a config by hand, reload PHP-FPM / the web server, then run this again."
fi
if (( ${#WARNINGS[@]} )); then say "Warnings: ${#WARNINGS[@]} (see WARN lines above)"; fi
if (( ! APPLY )); then
  say "Dry run complete: nothing was changed. Run again with --apply to apply this plan."
else
  say "Backups: ${#BACKUPS[@]}   New files: ${#NEWFILES[@]}"
  if (( ${#BACKUPS[@]} || ${#NEWFILES[@]} )); then
    say "Rollback commands:"
    if (( A_ENABLED_NOW )); then info "a2disconf -q $SNIP"; fi
    for b in "${BACKUPS[@]}"; do info "cp -a '$b' '${b%.bak-"$STAMP"}'"; done
    for f in "${NEWFILES[@]}"; do info "rm -f '$f'"; done
    info "then reload PHP-FPM and your web server"
  fi
fi
if (( ! REVERT )); then
  cat <<'EOF'

Notes:
  - This does NOT fix the vulnerabilities. Update PHP as soon as packages are out,
    then remove this mitigation:  bash mitigate.sh --revert --apply
  - With memory_limit=-1, keep a container / cgroup memory limit as the availability
    boundary. Do not use RLIMIT_AS / RLIMIT_DATA (ulimit -v / -d): they can trigger the bug.
  - Do not rely on ini_set() or .user.ini for these settings: they apply too late.
  - Fix attacker-reachable fatal errors and timeouts (uploads, imports, callbacks).
  - LiteSpeed, FrankenPHP, php-cgi: also set memory_limit=-1 in that SAPI's own config.
  - cPanel / Plesk may regenerate PHP-FPM pools: set the values in the panel too.
  - mod_php is the highest-risk setup per the advisory; consider moving to PHP-FPM.
  - Long-running PHP workers (queues, daemons) keep the old binary in memory: restart
    them after you update PHP.
EOF
fi
if (( FAILED )); then exit 3; fi