#!/usr/bin/env bash
# check-nginx.sh: offline, read-only checker for the NGINX 18 Nov 2026 security release
# (CVE-2026-123007 HTTP/2 and nine related CVEs). Pack 1.0.0, CybaVerse threat hunt.
#
# It never runs nginx, never touches the network, never writes a file and never prints file contents. It reads only:
#   a saved "nginx -V" output (--version-file) or a version string (--nginx-version, --plus-version);
#   nginx.conf and the files it includes (--conf, with --prefix for a mounted image or root filesystem);
#   /proc (only with --proc, or a saved copy with --proc-root) to see whether a running master runs a replaced binary.
# The ALPN probe is a network step and is NOT in this checker (see README, manual step).
#
# Usage:
#   check-nginx.sh [--version-file FILE] [--nginx-version 1.31.8] [--plus-version 37.2.0.1|R36]
#                  [--conf /etc/nginx/nginx.conf] [--prefix /mnt/image] [--proc | --proc-root DIR]
#
# Exit codes:
#   0 NOT AFFECTED      version is fixed for every CVE in the release and no replaced binary is running
#   1                   not used (reserved for unexpected runtime errors)
#   2 VULNERABLE        the version is in an affected range for at least one CVE
#   3 REVIEW            version unknown or sources disagree, a file was unreadable, or an include was missing
#   4 RESTART NEEDED    version fixed, but a running master still runs a deleted or replaced binary
#   5 USAGE OR READ ERROR
set -u
export LC_ALL=C
VERSION_TAG="check-nginx 1.0.0"
OSS_FIX="1.31.9 (mainline) or 1.30.7 (stable)"
PLUS_FIX="37.3.0.1 or 37.0.8.1"
MAX_FILES=256
MAX_SIZE=4194304
MAX_DEPTH=16
CLK_TCK=100
# CVE|OSS lowest affected|extra OSS|Plus fix 37.1+|Plus fix 37.0|Plus lowest|CVSS 4.0 (F5)|CVSS 3.1 (F5)|nginx.org|feature|summary
DATA='CVE-2026-123007|1.9.5|-|37.3.0.1|37.0.8.1|37.0.0|9.2 Critical|8.1 High|major|http2|HTTP/2 flow control memory corruption
CVE-2026-123633|1.19.7|-|37.2.0.1|37.0.7.1|37.0.0|9.2 Critical|8.1 High|medium|http2|HTTP/2 use-after-free (worker_connections)
CVE-2026-123634|0.6.18|-|37.3.0.1|37.0.8.1|37.0.0|9.2 Critical|8.1 High|medium|resolver|resolver use-after-free (subrequests)
CVE-2026-121810|1.25.0|-|37.3.0.1|37.0.8.1|37.0.0|9.2 Critical|8.1 High|medium|http3|HTTP/3 use-after-free
CVE-2026-113425|0.5.33|-|37.3.0.1|37.0.8.1|37.0.0|9.2 Critical|8.1 High|major|mail|mail proxy use-after-free
CVE-2026-118899|1.13.0|-|37.3.0.1|37.0.8.1|37.0.0|8.7 High|7.5 High|major|tls|TLS 1.3 request body endless loop
CVE-2026-125283|0.9.6|-|37.3.0.1|37.0.8.1|37.0.0|6.9 Medium|5.3 Medium|minor|tryfiles_alias|try_files with alias overflow
CVE-2026-120993|1.31.4|1.30.6|37.3.0.1|-|37.2.0|6.9 Medium|5.3 Medium|minor|stream_pp|PROXY protocol v2 NULL dereference
CVE-2026-123640|1.15.2|-|37.2.0.1|37.0.7.1|37.0.0|6.9 Medium|5.3 Medium|minor|ssl_preread|ssl_preread ClientHello parsing
CVE-2026-120967|1.25.5|-|37.3.0.1|37.0.8.1|37.0.0|6.3 Medium|4.8 Medium|medium|stream_verify|stream SNI client certificate bypass'

usage() {
  sed -n '2,/^set -u/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'
}
die() { echo "ERROR: $*"; exit 5; }

VFILE=""; OSSV=""; PLUSV=""; CONF=""; PREFIX=""; PROC=0; PROC_ROOT="/proc"
[ $# -gt 0 ] || { usage; exit 5; }
while [ $# -gt 0 ]; do
  case $1 in
    --version-file|-VersionFile) [ $# -ge 2 ] || die "$1 needs a value"; VFILE=$2; shift 2 ;;
    --nginx-version|-NginxVersion) [ $# -ge 2 ] || die "$1 needs a value"; OSSV=$2; shift 2 ;;
    --plus-version|-PlusVersion) [ $# -ge 2 ] || die "$1 needs a value"; PLUSV=$2; shift 2 ;;
    --conf|-Conf) [ $# -ge 2 ] || die "$1 needs a value"; CONF=$2; shift 2 ;;
    --prefix|-Prefix) [ $# -ge 2 ] || die "$1 needs a value"; PREFIX=${2%/}; shift 2 ;;
    --proc|-Proc) PROC=1; shift ;;
    --proc-root|-ProcRoot) [ $# -ge 2 ] || die "$1 needs a value"; PROC=1; PROC_ROOT=${2%/}; shift 2 ;;
    -h|--help|-Help) usage; exit 5 ;;
    *) die "unknown option: $1 (see --help)" ;;
  esac
done
[ -n "$VFILE$OSSV$PLUSV$CONF" ] || [ "$PROC" = 1 ] || die "nothing to check (see --help)"
[ -z "$PREFIX" ] || [ -d "$PREFIX" ] || die "prefix not found: $PREFIX"

REVIEW=0; VULN=0; STALE=0
OUT=""
say() { OUT="$OUT$*
"; }

# Version compare: prints -1, 0 or 1. Up to four numeric parts.
vcmp() {
  local IFS=. i x y
  # shellcheck disable=SC2206  # split on dots on purpose
  local a=($1) b=($2)
  for i in 0 1 2 3; do
    x=${a[$i]:-0}; y=${b[$i]:-0}
    if ((10#$x < 10#$y)); then echo -1; return; fi
    if ((10#$x > 10#$y)); then echo 1; return; fi
  done
  echo 0
}
isver() { [[ $1 =~ ^[0-9]{1,4}(\.[0-9]{1,4}){1,3}$ ]]; }

# --- version input ---
DISTRO=""; PLUS_HINT=0
if [ -n "$VFILE" ]; then
  if [ ! -f "$VFILE" ] || [ ! -r "$VFILE" ]; then die "cannot read version file: $VFILE"; fi
  [ "$(wc -c < "$VFILE")" -le "$MAX_SIZE" ] || die "version file too large: $VFILE"
  vline=$(tr -d '\r' < "$VFILE" | grep -m1 -aiE 'nginx version:' || true)
  [ -n "$vline" ] || die "no 'nginx version:' line in $VFILE"
  if [[ $vline =~ nginx/([0-9]+(\.[0-9]+){1,3}) ]]; then [ -n "$OSSV" ] || OSSV=${BASH_REMATCH[1]}; fi
  if [[ $vline =~ \(nginx-plus-[rR]([0-9]{1,3})(-p[0-9]+)?\) ]]; then [ -n "$PLUSV" ] || PLUSV="R${BASH_REMATCH[1]}"; PLUS_HINT=1
  elif [[ $vline =~ nginx-plus ]]; then PLUS_HINT=1; fi
  if [[ $vline =~ \((Ubuntu|Debian|Red\ Hat|Alpine|SUSE)\) ]]; then DISTRO=${BASH_REMATCH[1]}; fi
  mods=""
  for m in http_v2_module http_v3_module mail stream stream_ssl_preread_module; do
    if tr -d '\r' < "$VFILE" | grep -aqE -- "--with-$m( |$|=)"; then mods="$mods --with-$m"; fi
  done
  say "BUILD: version line read from $VFILE; built with:${mods:- (none of the http_v2, http_v3, mail, stream or ssl_preread options)}"
fi

KIND=""
if [ -n "$PLUSV" ]; then
  KIND=plus
  if [[ $PLUSV =~ ^[rR]([0-9]{1,3})$ ]]; then PLUSR=${BASH_REMATCH[1]}
  elif isver "$PLUSV"; then PLUSR=""
  else die "unrecognised --plus-version: $PLUSV (use 37.2.0.1 or R36)"; fi
elif [ "$PLUS_HINT" = 1 ]; then
  say "REVIEW: NGINX Plus build without a recognised release; pass --plus-version"; REVIEW=1
elif [ -n "$OSSV" ]; then
  KIND=oss; isver "$OSSV" || die "unrecognised nginx version: $OSSV"
elif [ "$PLUS_HINT" = 1 ]; then
  say "REVIEW: NGINX Plus build without a recognised release; pass --plus-version"; REVIEW=1
fi

# OSS status for one CVE: AFFECTED, FIXED or REVIEW
oss_status() { # lo extra
  local v=$OSSV lo=$1 extra=$2 maj min
  IFS=. read -r maj min _ <<< "$v"
  if [ "$extra" != - ] && [ "$(vcmp "$v" "$extra")" = 0 ]; then echo AFFECTED; return; fi
  if [ "$lo" = 1.31.4 ] && [ "$maj" = 1 ] && [ "$min" = 30 ]; then
    if [ "$(vcmp "$v" 1.30.7)" -ge 0 ]; then echo REVIEW; else echo FIXED; fi; return
  fi
  [ "$(vcmp "$v" "$lo")" -ge 0 ] || { echo FIXED; return; }
  if [ "$maj" = 1 ] && [ "$min" = 31 ]; then [ "$(vcmp "$v" 1.31.9)" -ge 0 ] && echo FIXED || echo AFFECTED; return; fi
  if [ "$maj" = 1 ] && [ "$min" = 30 ]; then [ "$(vcmp "$v" 1.30.7)" -ge 0 ] && echo FIXED || echo AFFECTED; return; fi
  if [ "$(vcmp "$v" 1.32.0)" -ge 0 ]; then echo FIXED; return; fi
  echo AFFECTED
}
plus_status() { # fixnew fixold lowest
  local v=$PLUSV
  if [ -n "$PLUSR" ]; then
    if ((10#$PLUSR >= 33 && 10#$PLUSR <= 36)); then echo AFFECTED; else echo REVIEW; fi; return
  fi
  local maj min; IFS=. read -r maj min _ <<< "$v"
  if [ "$maj" != 37 ]; then echo REVIEW; return; fi
  [ "$(vcmp "$v" "$3")" -ge 0 ] || { echo FIXED; return; }
  if [ "$min" = 0 ]; then
    [ "$2" = - ] && { echo FIXED; return; }
    [ "$(vcmp "$v" "$2")" -ge 0 ] && echo FIXED || echo AFFECTED
  else
    [ "$(vcmp "$v" "$1")" -ge 0 ] && echo FIXED || echo AFFECTED
  fi
}

# --- config scan ---
NFILES=0; FEATS=""; SEEN=""
# shellcheck disable=SC2016  # awk program, expanded by awk only
AWK_SCAN='
function flush() { if (hastok) { nw++; w[nw] = tok; if (nw == 1) sline = FNR; tok = ""; hastok = 0 } }
function feat(k, l, d) { print "FEAT\t" k "\t" l "\t" d }
function inside(n,  i) { if (index("/" ctx "/", "/" n "/")) return 1; for (i = 1; i <= depth; i++) if (bn[i] == n) return 1; return 0 }
function path(  i, p) { p = ctx; for (i = 1; i <= depth; i++) p = p "/" bn[i]; return p }
function args(  i, s) { s = ""; for (i = 2; i <= nw; i++) s = s " " w[i]; return s }
function hasarg(a,  i) { for (i = 2; i <= nw; i++) if (tolower(w[i]) == a) return 1; return 0 }
function markloc(k,  i) { for (i = depth; i >= 1; i--) if (bn[i] == "location") { if (k == "t") lt[i] = 1; else la[i] = 1; return } }
function stmt(  d, ih, is, im) {
  if (nw == 0) return
  d = tolower(w[1]); is = inside("stream"); im = inside("mail"); ih = inside("http") && !is && !im
  if (d == "include" && nw >= 2) print "INC\t" sline "\t" path() "\t" w[2]
  else if (d == "listen") {
    if (ih && hasarg("http2")) feat("http2", sline, "listen with relevant protocol option")
    if (ih && hasarg("quic")) feat("http3", sline, "listen with relevant protocol option")
    if (hasarg("ssl") || hasarg("quic")) feat("tls", sline, "listen with relevant protocol option")
    if (is && hasarg("proxy_protocol")) feat("stream_pp", sline, "listen with relevant protocol option")
  }
  else if (d == "http2" && nw >= 2) { if (tolower(w[2]) == "on") feat("http2", sline, "http2 on"); else feat("http2_off", sline, "http2 off or unrecognised value") }
  else if (d == "http3" && nw >= 2 && tolower(w[2]) == "on") feat("http3_on", sline, "http3 on")
  else if (d == "resolver") feat("resolver", sline, "resolver")
  else if ((d == "ssi" && tolower(w[2]) == "on") || (d == "mirror" && tolower(w[2]) != "off")) feat("ssi_mirror", sline, d)
  else if (d == "try_files") { markloc("t"); feat("try_files", sline, "try_files") }
  else if (d == "alias") { markloc("a"); feat("alias", sline, "alias") }
  else if (d == "ssl_preread" && is && tolower(w[2]) == "on") feat("ssl_preread", sline, "ssl_preread on")
  else if (d == "ssl_verify_client" && is && tolower(w[2]) != "off") feat("stream_verify", sline, "ssl_verify_client enabled")
  nw = 0
}
function openb(  n) {
  n = (nw >= 1) ? tolower(w[1]) : "?"
  depth++; bn[depth] = n; bl[depth] = (nw >= 1) ? sline : FNR; lt[depth] = 0; la[depth] = 0
  if (n == "mail" && depth == 1 && ctx == "main") feat("mail", bl[depth], "mail block")
  if (n == "stream" && depth == 1 && ctx == "main") feat("stream", bl[depth], "stream block")
  nw = 0
}
function closeb() {
  if (depth == 0) { feat("parse_warn", FNR, "unbalanced }"); return }
  if (bn[depth] == "location" && lt[depth] && la[depth]) feat("tryfiles_alias", bl[depth], "location with try_files and alias")
  depth--
}
BEGIN { depth = 0; nw = 0; tok = ""; hastok = 0; inq = 0 }
{
  n = length($0); i = 1
  while (i <= n) {
    c = substr($0, i, 1)
    if (inq) {
      if (c == "\\") { tok = tok substr($0, i + 1, 1); i += 2; continue }
      if (c == q) inq = 0; else tok = tok c
      i++; continue
    }
    if (c == "#" && !hastok) break
    if (c == "\"" || c == "\047") { inq = 1; q = c; hastok = 1; i++; continue }
    if (c == " " || c == "\t" || c == "\r") { flush(); i++; continue }
    if (c == ";") { flush(); stmt(); i++; continue }
    if (c == "{") { flush(); openb(); i++; continue }
    if (c == "}") { flush(); stmt(); closeb(); i++; continue }
    tok = tok c; hastok = 1; i++
  }
  if (inq) tok = tok "\n"; else flush()
}
END {
  if (inq) feat("parse_warn", FNR, "unterminated quote")
  if (depth > 0) feat("parse_warn", FNR, "unclosed block")
}'

scan_conf() { # file ctx depth
  local f=$1 ctx=$2 d=$3 key out rec k l det pat base m matched
  if [ "$d" -gt "$MAX_DEPTH" ]; then say "REVIEW: include depth over $MAX_DEPTH at $f"; REVIEW=1; return; fi
  if [ ! -f "$f" ] || [ ! -r "$f" ]; then say "REVIEW: cannot read config file: $f"; REVIEW=1; return; fi
  key=$(readlink -f -- "$f" 2>/dev/null || printf '%s' "$f")
  case "
$SEEN" in *"
$key
"*) return ;; esac
  SEEN="$SEEN$key
"
  NFILES=$((NFILES + 1))
  if [ "$NFILES" -gt "$MAX_FILES" ]; then say "REVIEW: more than $MAX_FILES config files; stopped"; REVIEW=1; return; fi
  if [ "$(wc -c < "$f")" -gt "$MAX_SIZE" ]; then say "REVIEW: config file over $MAX_SIZE bytes, not scanned: $f"; REVIEW=1; return; fi
  out=$(awk -v ctx="$ctx" "$AWK_SCAN" "$f" 2>/dev/null) || { say "REVIEW: could not parse $f"; REVIEW=1; return; }
  while IFS= read -r rec; do
    [ -n "$rec" ] || continue
    IFS=$'\t' read -r k l det m <<< "$rec"
    if [ "$k" = INC ]; then
      pat=$m
      case $pat in /*) pat="$PREFIX$pat" ;; *) pat="$CONFDIR/$pat" ;; esac
      matched=0
      if [[ $pat == *[\*\?\[]* ]]; then
        shopt -s nullglob
        local IFS=
        # shellcheck disable=SC2206  # glob expansion (no word splitting) of the include pattern on purpose
        local list=($pat)
        unset IFS
        shopt -u nullglob
        for base in "${list[@]}"; do [ -f "$base" ] && { matched=1; scan_conf "$base" "$det" $((d + 1)); }; done
      elif [ -e "$pat" ]; then
        matched=1; scan_conf "$pat" "$det" $((d + 1))
      else
        say "REVIEW: include not found: $pat (from $f:$l)"; REVIEW=1
      fi
      [ "$matched" = 1 ] || [[ $pat != *[\*\?\[]* ]] || say "NOTE: include pattern matched no files: $pat (from $f:$l)"
    elif [ "$k" = FEAT ]; then
      FEATS="$FEATS$l
"
      say "FEAT $l $f:$det $m"
      [ "$l" != parse_warn ] || REVIEW=1
    fi
  done <<< "$out"
}
hasfeat() { case "
$FEATS" in *"
$1
"*) return 0 ;; esac; return 1; }

if [ -n "$CONF" ]; then
  MAIN="$PREFIX$CONF"
  if [ ! -f "$MAIN" ] || [ ! -r "$MAIN" ]; then die "cannot read config: $MAIN"; fi
  CONFDIR=$(dirname -- "$MAIN")
  scan_conf "$MAIN" main 0
  if hasfeat try_files && hasfeat alias && ! hasfeat tryfiles_alias; then
    FEATS="${FEATS}tryfiles_alias
"
    say "FEAT tryfiles_alias $MAIN:0 try_files and alias both present (possible inherited or included combination; REVIEW scope)"
  fi
  say "CONFIG: files read $NFILES"
fi

# --- running master binary (read only) ---
if [ "$PROC" = 1 ]; then
  [ -d "$PROC_ROOT" ] || die "proc root not found: $PROC_ROOT"
  btime=$(awk '$1 == "btime" { print $2; exit }' "$PROC_ROOT/stat" 2>/dev/null || true)
  hz=$CLK_TCK
  masters=0
  for pd in "$PROC_ROOT"/[0-9]*; do
    [ -d "$pd" ] || continue
    pid=${pd##*/}
    cmd=$(tr '\0' ' ' < "$pd/cmdline" 2>/dev/null || true)
    case $cmd in "nginx: master process"*) ;; *) continue ;; esac
    masters=$((masters + 1))
    if ! exe=$(readlink -- "$pd/exe" 2>/dev/null) || [ -z "$exe" ]; then
      say "REVIEW: pid $pid nginx master: cannot read the exe link (run as root to check)"; REVIEW=1; continue
    fi
    case $exe in *" (deleted)")
      say "STALE: pid $pid nginx master runs a deleted binary ($exe): restart or binary upgrade needed"; STALE=1; continue ;;
    esac
    st=$(cat -- "$pd/stat" 2>/dev/null || true); rest=${st##*) }
    # shellcheck disable=SC2086  # split stat fields on purpose
    set -- $rest
    start=${20:-}
    mt=$(stat -L -c %Y -- "$pd/exe" 2>/dev/null || true)
    if ! [[ $btime =~ ^[0-9]{1,12}$ && $start =~ ^[0-9]{1,18}$ && $mt =~ ^[0-9]{1,12}$ ]]; then
      say "REVIEW: pid $pid nginx master: start time or binary time unreadable"; REVIEW=1; continue
    fi
    started=$((btime + start / hz))
    if [ "$mt" -gt $((started + 1)) ]; then
      say "STALE: pid $pid nginx master started before its binary $exe was replaced: restart or binary upgrade needed"; STALE=1
    else
      say "PROC: pid $pid nginx master binary $exe is not newer than the process"
    fi
  done
  say "PROC: nginx masters found $masters"
fi

# --- verdict per CVE ---
if [ -n "$KIND" ]; then
  if [ "$KIND" = oss ]; then say "VERSION: NGINX Open Source $OSSV${DISTRO:+ ($DISTRO build)}"
  else say "VERSION: NGINX Plus $PLUSV"; fi
  while IFS='|' read -r cve lo extra pn po pmin s4 s3 sev ft sum; do
    if [ "$KIND" = oss ]; then st=$(oss_status "$lo" "$extra"); else st=$(plus_status "$pn" "$po" "$pmin"); fi
    if [ -n "$CONF" ]; then
      if hasfeat "$ft"; then cf="config: $ft seen"; else cf="config: $ft not seen"; fi
    else cf="config: not scanned"; fi
    note=""
    [ "$st" = AFFECTED ] && VULN=1
    if [ "$st" = REVIEW ]; then
      REVIEW=1
      if [ "$KIND" = oss ]; then note=" (1.30 branch: F5/CNA list a fix; nginx.org and CHANGES-1.30 do not. REVIEW)"
      else note=" (release not evaluated by F5)"; fi
    fi
    say "CVE $cve $st [F5 CVSS 4.0 $s4, CVSS 3.1 $s3; nginx.org $sev] $sum; $cf$note"
  done <<< "$DATA"
  if [ "$KIND" = oss ]; then
    if [ "$VULN" = 1 ]; then say "FIX: upgrade to $OSS_FIX, then do a full restart or binary upgrade (a reload keeps the old binary)"; fi
    case $OSSV in 1.30.6) say "NOTE: CVE-2026-120993 on 1.30.6 is listed by F5 and the CVE record but not by nginx.org" ;; esac
    if [ -n "$DISTRO" ]; then say "NOTE: $DISTRO builds can carry backported fixes; check the package version against the distribution tracker (none fixed on 18 Nov 2026)"; fi
    if [ "$(vcmp "$OSSV" 1.32.0)" -ge 0 ]; then say "NOTE: version is later than the fix releases and is assumed to include the fixes"; fi
  else
    if [ "$VULN" = 1 ]; then
      if [ -n "$PLUSR" ]; then say "FIX: F5 lists no fix for R33 to R36; move to $PLUS_FIX"
      else say "FIX: upgrade to $PLUS_FIX, then do a full restart or binary upgrade"; fi
    fi
  fi
elif [ -n "$CONF$VFILE" ] && [ "$PLUS_HINT" = 0 ]; then
  say "REVIEW: no version given; pass --version-file or --nginx-version"; REVIEW=1
elif [ "$PLUS_HINT" = 0 ]; then
  say "NOTE: no version given; only running binaries were checked"
fi
if hasfeat http2 && [ "$VULN" = 1 ]; then
  say "MITIGATION: until patched, remove http2 from listen and set http2 off; (CERT-EU: mitigates CVE-2026-123007 and CVE-2026-123633)"
fi

printf '%s\n' "$VERSION_TAG (read only, offline)"
printf '%s' "$OUT"
if [ "$VULN" = 1 ]; then echo "OVERALL: VULNERABLE (exit 2)"; exit 2; fi
if [ "$STALE" = 1 ]; then echo "OVERALL: RESTART NEEDED (exit 4)"; exit 4; fi
if [ "$REVIEW" = 1 ]; then echo "OVERALL: REVIEW (exit 3)"; exit 3; fi
echo "OVERALL: NOT AFFECTED (exit 0)"; exit 0
