#!/usr/bin/env bash
# =============================================================================
#  US Digital Sciences Corp - Security Operations
#  php2shell-check.sh - exposure check for CVE-2026-109618 / CVE-2026-109619 (PHP2Shell)
# =============================================================================
#
# Read-only. Run as root for full package/config visibility.
#   ./php2shell-check.sh            scan this host
#   ./php2shell-check.sh --probe    print a PHP probe to drop in a web root (DELETE IT after)
#
# Exit codes: 0 = nothing vulnerable found, 2 = at least one vulnerable binary, 1 = no PHP found
# Fixed upstream: 8.5.12, 8.4.27, 8.3.36, 8.2.35. 7.4-8.1: source backports / vendor only.
# Source: https://www.php.net/archive/2026.php (advisory 2026-10-21)

set -u
FIXED_85=8.5.12; FIXED_84=8.4.27; FIXED_83=8.3.36; FIXED_82=8.2.35
CVES='CVE-2026-10961[89]'

if [ -t 1 ]; then R=$'\e[31m'; Y=$'\e[33m'; G=$'\e[32m'; B=$'\e[1m'; N=$'\e[0m'; else R= Y= G= B= N=; fi

# Mitigation check, run inside PHP. Works on PHP 5.4+. Values are for the ini it's run against.
read -r -d '' MITIG_PHP <<'EOF'
function p2s_b($s){$s=trim((string)$s);if($s==='')return 0;$n=(int)$s;switch(strtolower(substr($s,-1))){case 'g':$n*=1024;case 'm':$n*=1024;case 'k':$n*=1024;}return $n;}
$r=array();
$m=ini_get('memory_limit');
$r[]=array('[109618] memory_limit = '.$m.' (want -1)', $m==='-1');
$pm=ini_get('post_max_size');$p=p2s_b($pm);$u=p2s_b(ini_get('upload_max_filesize'));
$r[]=array('[109618] post_max_size = '.$pm.' (want 8M, or 32M if uploads needed)', $p>0 && $p<=33554432);
$r[]=array('[109618] upload_max_filesize = '.ini_get('upload_max_filesize').' (want below post_max_size)', $u>0 && $u<$p);
$s=ini_get('session.upload_progress.enabled');
$r[]=array('[109619] session.upload_progress.enabled = '.($s===false?'n/a (no session ext)':($s?'On':'Off')).' (want Off)', !$s || strtolower($s)==='off');
if(version_compare(PHP_VERSION,'8.5.0','>=')){$f=ini_get('fatal_error_backtraces');$r[]=array('[109619] fatal_error_backtraces = '.($f?'On':'Off').' (want Off, 8.5 only)', !$f || strtolower($f)==='off');}
foreach($r as $x) echo ($x[1]?"      [ok]   ":"      [MISS] "),$x[0],"\n";
EOF

if [ "${1:-}" = "--probe" ]; then
  printf '<?php\n// US Digital Sciences Corp - PHP2Shell mitigation probe - DELETE AFTER USE\nheader("Content-Type: text/plain");\necho "US Digital Sciences Corp - PHP2Shell probe\\n";\necho "PHP ", PHP_VERSION, " SAPI ", PHP_SAPI, "\\n";\n%s\n' "$MITIG_PHP"
  exit 0
fi

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

pkg_of() {  # print owning package of a binary, if any
  local b; b=$(readlink -f "$1")
  if command -v rpm >/dev/null 2>&1 && rpm -qf "$b" >/dev/null 2>&1; then rpm -qf "$b"; return; fi
  if command -v dpkg >/dev/null 2>&1; then dpkg -S "$b" 2>/dev/null | head -n1 | cut -d: -f1; fi
}

pkg_has_fix() {  # 0 if the package changelog mentions the CVEs (distro backport)
  local p=$1
  [ -z "$p" ] && return 1
  if command -v rpm >/dev/null 2>&1 && rpm -q "$p" >/dev/null 2>&1; then
    rpm -q --changelog "$p" 2>/dev/null | grep -Eq "$CVES" && return 0
  fi
  local f=/usr/share/doc/$p/changelog.Debian.gz
  [ -f "$f" ] && zgrep -Eq "$CVES" "$f" && return 0
  return 1
}

find_bins() {
  { command -v php php-cgi php-fpm lsphp 2>/dev/null
    ls -d /usr/bin/php* /usr/sbin/php-fpm* /usr/local/bin/php* /usr/local/sbin/php-fpm* \
          /opt/remi/php*/root/usr/bin/php* /opt/remi/php*/root/usr/sbin/php-fpm \
          /opt/cpanel/ea-php*/root/usr/bin/php* /opt/cpanel/ea-php*/root/usr/sbin/php-fpm \
          /opt/alt/php*/usr/bin/php* /opt/alt/php*/usr/sbin/php-fpm \
          /usr/local/lsws/lsphp*/bin/lsphp 2>/dev/null
  } | while read -r b; do
        [ -f "$b" ] && [ -x "$b" ] || continue
        case "$(basename "$b")" in
          php|php[0-9]*|php-cgi|php-cgi[0-9]*|php-fpm|php-fpm[0-9]*|lsphp) readlink -f "$b" ;;
        esac
      done | sort -u
}

C=; [ -n "$B" ] && C=$'\e[36m'
printf '%s' "$C$B"
cat <<'BANNER'
  _   _ ____    ____  _       _ _        _
 | | | / ___|  |  _ \(_) __ _(_) |_ __ _| |
 | | | \___ \  | | | | |/ _` | | __/ _` | |
 | |_| |___) | | |_| | | (_| | | || (_| | |
  \___/|____/  |____/|_|\__, |_|\__\__,_|_|
                        |___/
          S  C  I  E  N  C  E  S     C  O  R  P
 ==============================================================
BANNER
printf '%s' "$N"
echo "  ${B}PHP2Shell Exposure Check${N}  |  CVE-2026-109618 / CVE-2026-109619"
echo "  Security Operations  |  host: $(hostname)  |  $(date -u +%FT%TZ)"
echo " =============================================================="

# mod_php is the highest-risk configuration per the advisory
for c in apachectl apache2ctl httpd; do
  command -v "$c" >/dev/null 2>&1 && "$c" -M 2>/dev/null | grep -qi 'php' && {
    echo "${R}${B}!! Apache mod_php is loaded ($c -M) - HIGHEST RISK per advisory, patch first${N}"; break; }
done

BINS=$(find_bins)
[ -z "$BINS" ] && { echo "No PHP binaries found."; exit 1; }

VULN=0
while read -r bin; do
  [ -z "$bin" ] && continue
  raw=$("$bin" -v 2>/dev/null | head -n1 | awk '{print $2}')
  [ -z "$raw" ] && { echo "${Y}?  $bin - could not read version${N}"; continue; }
  v=${raw%%[-+~]*}; mm=$(echo "$v" | cut -d. -f1,2)
  pkg=$(pkg_of "$bin"); src=${pkg:-"no package (source/container/vendor build)"}

  case "$mm" in
    8.5) fixed=$FIXED_85 ;; 8.4) fixed=$FIXED_84 ;; 8.3) fixed=$FIXED_83 ;; 8.2) fixed=$FIXED_82 ;;
    8.1|8.0|7.4) fixed=backport ;;
    8.6) fixed=prerelease ;;
    *) fixed=none ;;
  esac

  if [ "$fixed" = prerelease ]; then
    status="${Y}UNKNOWN - pre-release 8.6, check the RC includes the fix${N}"
  elif [ "$fixed" != backport ] && [ "$fixed" != none ] && ver_ge "$v" "$fixed"; then
    status="${G}PATCHED (>= $fixed)${N}"
  elif pkg_has_fix "$pkg"; then
    status="${G}PATCHED (vendor backport - CVE found in $pkg changelog)${N}"
  else
    VULN=1
    case "$fixed" in
      backport) status="${R}VULNERABLE - EOL branch; use vendor package or php-src PHP-$mm-CVE-2026-109618-109619 backport${N}" ;;
      none)     status="${R}VULNERABLE - no upstream fix for $mm; vendor backport, upgrade, or isolate${N}" ;;
      *)        status="${R}VULNERABLE - update to $fixed and restart all workers${N}" ;;
    esac
  fi

  echo
  echo "${B}$bin${N}  PHP $raw"
  echo "   source: $src"
  case "$bin$pkg" in *remi*) echo "   ${Y}note: Remi repo will NOT have updates today - switch to distro packages or build from source${N}" ;; esac
  echo "   status: $status"

  # Mitigation values are only directly readable from a CLI binary (and reflect the CLI ini)
  case "$(basename "$bin")" in
    php|php[0-9]*)
      echo "   mitigations (CLI ini - web SAPI may differ, use --probe to confirm):"
      "$bin" -r "$MITIG_PHP" 2>/dev/null || echo "      (could not evaluate)"
      # Debian/Ubuntu layout: evaluate the fpm/apache2 ini with this binary
      for sapi in fpm apache2 cgi; do
        d=/etc/php/$mm/$sapi
        [ -f "$d/php.ini" ] || continue
        echo "   mitigations ($d/php.ini, before pool/vhost overrides):"
        PHP_INI_SCAN_DIR="$d/conf.d" "$bin" -c "$d/php.ini" -r "$MITIG_PHP" 2>/dev/null || echo "      (could not evaluate)"
      done ;;
  esac
done <<< "$BINS"

# Per-pool / per-vhost overrides that change the effective web values
echo
echo "${B}FPM pool / Apache overrides of the mitigation settings:${N}"
grep -RhsnE '^[[:space:]]*php_(admin_)?(value|flag)[[:space:]]*\[?[[:space:]]*(memory_limit|post_max_size|upload_max_filesize|session\.upload_progress\.enabled|fatal_error_backtraces)' \
  /etc/php* /etc/php-fpm.d /etc/opt/remi /opt/cpanel/ea-php*/root/etc /opt/alt/php*/etc \
  /etc/httpd /etc/apache2 /usr/local/apache/conf 2>/dev/null | sed 's/^/   /' || true
echo "   (none listed = no overrides found in standard locations)"

echo
echo "Notes:"
echo " - Mitigations reduce exposure only; updating is the only complete fix. Restart every php-fpm/Apache worker after changes."
echo " - Set mitigations in php.ini, FPM pool, or server config - not ini_set() or .user.ini."
echo " - Containers: run this inside each image/container; host scan won't see them."
echo " - Vendor backports keep old version numbers; if status says VULNERABLE on a distro package, confirm against the vendor advisory."

exit $((VULN * 2))
