#!/usr/bin/env bash
# check-geoserver-cve-2026-120705.sh: offline, read-only triage of one GeoServer installation for the five-step chain
# GeoServer published on 23 Nov 2026 (CVE-2026-129244, CVE-2026-129243, CVE-2026-120705, CVE-2026-129245,
# CVE-2026-129242) and the related JDBC advisory CVE-2026-120704. Pack 1.0.0.
# Version check: GeoServer and GeoTools jar names (gs-main, gs-ows, gs-wfs, gs-wfs-core, gs-sec-jdbc, gt-metadata, the
# Maven artefacts named in the GeoServer advisories), a version string, or a saved MANIFEST.MF text file.
# Data directory audit: stored query files (wfs/query, workspaces/*/wfs/query), JDBC user/group, role and authentication
# services, users.xml files, the remember-me filter and key in security/config.xml, security/masterpw.info,
# security/services.properties, and executable or database files. It prints presence, counts and cleaned relative paths
# only: never a password, digest, key, connection URL or file contents. It never connects to anything, never writes a
# file and runs no program other than find, grep, sort, head, wc and tr. Bash and PowerShell (Check-GeoServerCve2026120705.ps1) give
# the same output and exit code.
set -u
export LC_ALL=C

usage() {
  echo 'Usage: check-geoserver-cve-2026-120705.sh [--lib DIR] [--version V] [--manifest FILE] [--data-dir DIR]'
  echo 'Offline and read-only. DIR for lib is a folder holding GeoServer jars, such as webapps/geoserver/WEB-INF/lib (searched recursively). V is a GeoServer version such as 2.28.5. FILE is a MANIFEST.MF saved as text. DIR for data-dir is the GeoServer data directory (GEOSERVER_DATA_DIR). Give at least one option. Exit codes: 0 FIXED, 2 AFFECTED, 3 REVIEW, 5 USAGE OR READ ERROR (1 and 4 are not used).'
}
die() { echo "ERROR: $*"; exit 5; }
clean() { printf '%s' "$1" | tr -c 'A-Za-z0-9._/-' '?'; }
VRX='^[0-9]{1,3}\.[0-9]{1,3}(\.[0-9]{1,3})?(-[A-Za-z0-9]{1,20})?$'
showver() { if [[ $1 =~ $VRX ]]; then printf '%s' "$1"; else printf '(not shown)'; fi; }

LIB=""; VSTR=""; MAN=""; DD=""; HASL=0; HASV=0; HASM=0; HASD=0
while [ $# -gt 0 ]; do
  case $1 in
    --lib|-Lib) { [ $# -ge 2 ] && [ -n "$2" ]; } || die "lib option needs a value"; [ "$HASL" = 0 ] || die "give each option once"; LIB=$2; HASL=1; shift 2;;
    --version|-Version) [ $# -ge 2 ] || die "version option needs a value"; [ "$HASV" = 0 ] || die "give each option once"; VSTR=$2; HASV=1; shift 2;;
    --manifest|-Manifest) { [ $# -ge 2 ] && [ -n "$2" ]; } || die "manifest option needs a value"; [ "$HASM" = 0 ] || die "give each option once"; MAN=$2; HASM=1; shift 2;;
    --data-dir|-DataDir) { [ $# -ge 2 ] && [ -n "$2" ]; } || die "data-dir option needs a value"; [ "$HASD" = 0 ] || die "give each option once"; DD=$2; HASD=1; shift 2;;
    -h|--help|-Help) usage; exit 5;;
    *) die "unknown option: $(clean "${1##*/}" | head -c 64)";;
  esac
done
[ $((HASL + HASV + HASM + HASD)) -gt 0 ] || { usage; exit 5; }
[ "$HASL" = 0 ] || [ -d "$LIB" ] || die "lib folder not found or not a folder"
[ "$HASD" = 0 ] || [ -d "$DD" ] || die "data directory not found or not a folder"
if [ "$HASM" = 1 ]; then { [ -f "$MAN" ] && [ -r "$MAN" ]; } || die "manifest file not found or not readable"; fi

ALLCVE='CVE-2026-129244, CVE-2026-129243, CVE-2026-120705, CVE-2026-129245, CVE-2026-129242, CVE-2026-120704'
NA=0; NF=0; NR=0
# GeoServer x.y.z: affected up to 2.27.6, 2.28.0 to 2.28.5 and 3.0.0 to 3.0.1; fixed 2.27.7, 2.28.6, 3.0.2.
gs_class() {
  local v=$1 a b c
  [[ $v =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || { echo REVIEW; return; }
  a=${v%%.*}; b=${v#*.}; c=${b#*.}; b=${b%%.*}; a=$((10#$a)); b=$((10#$b)); c=$((10#$c))
  if [ "$a" -lt 2 ] || { [ "$a" = 2 ] && [ "$b" -lt 27 ]; } || { [ "$a" = 2 ] && [ "$b" = 27 ] && [ "$c" -le 6 ]; }; then echo AFFECTED
  elif [ "$a" = 2 ] && [ "$b" = 27 ]; then echo FIXED
  elif [ "$a" = 2 ] && [ "$b" = 28 ]; then if [ "$c" -le 5 ]; then echo AFFECTED; else echo FIXED; fi
  elif [ "$a" = 3 ] && [ "$b" = 0 ]; then if [ "$c" -le 1 ]; then echo AFFECTED; else echo FIXED; fi
  else echo REVIEW; fi
}
# GeoTools gt-metadata x.y: affected up to 33.6, 34.0 to 34.5 and 35.0 to 35.1; fixed 33.7, 34.6, 35.2.
gt_class() {
  local v=$1 a b
  [[ $v =~ ^[0-9]{1,3}\.[0-9]{1,3}$ ]] || { echo REVIEW; return; }
  a=$((10#${v%%.*})); b=$((10#${v#*.}))
  if [ "$a" -lt 33 ] || { [ "$a" = 33 ] && [ "$b" -le 6 ]; }; then echo AFFECTED
  elif [ "$a" = 33 ]; then echo FIXED
  elif [ "$a" = 34 ]; then if [ "$b" -le 5 ]; then echo AFFECTED; else echo FIXED; fi
  elif [ "$a" = 35 ]; then if [ "$b" -le 1 ]; then echo AFFECTED; else echo FIXED; fi
  else echo REVIEW; fi
}
tally() { case $1 in AFFECTED) NA=$((NA + 1));; FIXED) NF=$((NF + 1));; *) NR=$((NR + 1));; esac; }
art_cves() {
  case $1 in
    gs-main) echo 'CVE-2026-129245';; gs-ows) echo 'CVE-2026-129243';; gs-wfs) echo 'CVE-2026-129244';;
    gs-wfs-core) echo 'CVE-2026-120705, CVE-2026-129244';; gs-sec-jdbc) echo 'CVE-2026-129242, CVE-2026-120704';;
    gt-metadata) echo 'CVE-2026-120705';;
  esac
}
# list_files ROOT: NUL-separated paths of regular files under ROOT, any depth
list_files() { find -H "$1" -type f -print0 2>/dev/null; }
show_list() { # stdin: cleaned relative paths, one per line; prints at most 20, sorted
  local n=0 l
  while IFS= read -r l; do n=$((n + 1)); [ "$n" -le 20 ] && echo "    $l"; done < <(sort)
  [ "$n" -le 20 ] || echo "    ... and $((n - 20)) more"
}

echo 'GeoServer CVE-2026-120705 chain checker, pack 1.0.0 (offline, read only)'
echo 'NOTE: exploitation of CVE-2026-120705 and CVE-2026-129243 reported by security researchers (via The Hacker News) as of 25 Nov 2026: probes that create and run stored queries, not use of the full chain.'
echo 'NOTE: none of the five chain CVEs nor CVE-2026-120704 is in CISA KEV (catalogue 2026.11.24; KEV due dates bind US federal agencies only, BOD 26-04). Patch now regardless.'
echo 'FIXED RELEASES: GeoServer 2.27.7, 2.28.6 and 3.0.2 (released 19 Oct 2026); GeoTools gt-metadata 33.7, 34.6 and 35.2'

if [ "$HASV" = 1 ]; then
  r=$(gs_class "$VSTR"); tally "$r"
  echo "VERSION OPTION: $(showver "$VSTR") $r ($ALLCVE)"
fi

if [ "$HASM" = 1 ]; then
  mv=$(grep -aE '^Project-Version:' "$MAN" 2>/dev/null | head -n 1 | tr -d '\r')
  [ -n "$mv" ] || mv=$(grep -aE '^Implementation-Version:' "$MAN" 2>/dev/null | head -n 1 | tr -d '\r')
  if [ -z "$mv" ]; then NR=$((NR + 1)); echo 'MANIFEST: no Project-Version or Implementation-Version line REVIEW'
  else
    k=${mv%%:*}; v=${mv#*:}; v=${v#"${v%%[! ]*}"}; v=${v%"${v##*[! ]}"}
    r=$(gs_class "$v"); tally "$r"
    echo "MANIFEST: $k $(showver "$v") $r ($ALLCVE)"
  fi
fi

JRX='^(gs-main|gs-ows|gs-wfs-core|gs-wfs|gs-sec-jdbc|gt-metadata)-([0-9][^/]*)\.jar$'
if [ "$HASL" = 1 ]; then
  L=$LIB; while [[ $L == */ ]]; do L=${L%/}; done; [ -n "$L" ] || L=/
  out=""; n=0
  while IFS= read -r -d '' f; do
    b=${f##*/}
    [[ $b =~ $JRX ]] || continue
    art=${BASH_REMATCH[1]}; v=${BASH_REMATCH[2]}
    if [ "$art" = gt-metadata ]; then r=$(gt_class "$v"); else r=$(gs_class "$v"); fi
    tally "$r"; n=$((n + 1))
    rel=${f#"$L"}; rel=${rel#/}
    out+="  JAR: $(clean "$rel") $art $(showver "$v") $r ($(art_cves "$art"))"$'\n'
  done < <(list_files "$LIB")
  echo "LIBRARY FOLDER: $n matching jar(s)"
  if [ "$n" = 0 ]; then NR=$((NR + 1)); echo '  JAR: none of gs-main, gs-ows, gs-wfs, gs-wfs-core, gs-sec-jdbc, gt-metadata found REVIEW'
  else printf '%s' "$out" | sort; fi
fi

DR=0
if [ "$HASD" = 1 ]; then
  D=$DD; while [[ $D == */ ]]; do D=${D%/}; done; [ -n "$D" ] || D=/
  echo 'DATA DIRECTORY AUDIT (presence and counts only; no file contents, passwords, digests or keys are printed)'
  sq=""; nsq=0; nsx=0
  while IFS= read -r -d '' f; do
    rel=${f#"$D"}; rel=${rel#/}
    [[ $rel =~ ^(wfs/query|workspaces/[^/]+/wfs/query)/[^/]+$ ]] || continue
    nsq=$((nsq + 1)); sq+="$(clean "$rel")"$'\n'
    if grep -aqiE 'xi:include|xinclude|<!doctype|<!entity|file:' "$f" 2>/dev/null; then nsx=$((nsx + 1)); fi
  done < <({ [ -d "$D/wfs/query" ] && list_files "$D/wfs/query"; [ -d "$D/workspaces" ] && find -H "$D/workspaces" -mindepth 4 -maxdepth 4 -type f -print0 2>/dev/null; } | sort -z)
  echo "  STORED QUERY FILES: $nsq (wfs/query and workspaces/*/wfs/query)"
  [ "$nsq" = 0 ] || { printf '%s' "$sq" | show_list; DR=$((DR + 1)); }
  echo "  STORED QUERY FILES WITH XINCLUDE, DOCTYPE, ENTITY OR FILE: TEXT: $nsx"
  [ "$nsx" = 0 ] || DR=$((DR + 1))
  jd=""
  for kind in usergroup role auth; do
    ns=0; nj=0
    if [ -d "$D/security/$kind" ]; then
      while IFS= read -r -d '' f; do
        rel=${f#"$D"}; rel=${rel#/}
        [[ $rel =~ ^security/$kind/[^/]+/config\.xml$ ]] || continue
        ns=$((ns + 1))
        grep -aqiE '<className>[^<]*jdbc[^<]*</className>' "$f" 2>/dev/null || continue
        nj=$((nj + 1))
        s=no; h=no; l=no; p=no
        grep -aqiE '<driverClassName>[^<]*sqlite' "$f" 2>/dev/null && s=yes
        grep -aqiE '<driverClassName>[^<]*hsqldb' "$f" 2>/dev/null && h=yes
        grep -aqiE 'enable_load_extension' "$f" 2>/dev/null && l=yes
        grep -aqE '<propertyFileName(DML|DDL)>[[:space:]]*(/|\\\\|[A-Za-z]:)' "$f" 2>/dev/null && p=yes
        if [ "$s$h$l$p" != nononono ]; then DR=$((DR + 1)); fi
        jd+="  JDBC SERVICE: $(clean "$rel") SQLite driver=$s HSQLDB driver=$h load_extension=$l absolute DML/DDL path=$p"$'\n'
      done < <(find -H "$D/security/$kind" -mindepth 2 -maxdepth 2 -type f -print0 2>/dev/null)
    fi
    case $kind in usergroup) label='USER/GROUP SERVICES';; role) label='ROLE SERVICES';; auth) label='AUTHENTICATION PROVIDERS';; esac
    echo "  $label: $ns config.xml, $nj JDBC"
  done
  [ -z "$jd" ] || printf '%s' "$jd" | sort
  nu=0; ne=0
  if [ -d "$D/security/usergroup" ]; then
    while IFS= read -r -d '' f; do
      rel=${f#"$D"}; rel=${rel#/}
      [[ $rel =~ ^security/usergroup/[^/]+/users\.xml$ ]] || continue
      nu=$((nu + 1)); c=$(grep -aoE '<user[[:space:]>/]' "$f" 2>/dev/null | wc -l); ne=$((ne + c))
    done < <(find -H "$D/security/usergroup" -mindepth 2 -maxdepth 2 -type f -print0 2>/dev/null)
  fi
  echo "  USERS.XML FILES: $nu (user entries: $ne)"
  C="$D/security/config.xml"
  if [ -f "$C" ]; then
    echo '  SECURITY CONFIG (security/config.xml): present'
    if grep -aqE '<filter>[[:space:]]*rememberme[[:space:]]*</filter>' "$C" 2>/dev/null; then rf=yes; else rf=no; fi
    if grep -aqE '<key>[^<]*</key>' "$C" 2>/dev/null; then kp=present; else kp=absent; fi
    if grep -aqE '<key>[[:space:]]*geoserver[[:space:]]*</key>' "$C" 2>/dev/null; then kd=yes; DR=$((DR + 1)); else kd=no; fi
    echo "  REMEMBER-ME FILTER IN A CHAIN: $rf"
    echo "  REMEMBER-ME KEY ELEMENT: $kp (shipped default: $kd)"
  else
    echo '  SECURITY CONFIG (security/config.xml): absent'
  fi
  if [ -f "$D/security/masterpw.info" ]; then echo '  MASTERPW.INFO: present'; DR=$((DR + 1)); else echo '  MASTERPW.INFO: absent'; fi
  S="$D/security/services.properties"
  if [ -f "$S" ]; then
    nw=$(grep -acE '^[[:space:]]*wfs(\.[A-Za-z]+)?[[:space:]]*=' "$S" 2>/dev/null); nw=${nw:-0}; cr=no; dr=no
    grep -aqE '^[[:space:]]*wfs\.CreateStoredQuery[[:space:]]*=' "$S" 2>/dev/null && cr=yes
    grep -aqE '^[[:space:]]*wfs\.DropStoredQuery[[:space:]]*=' "$S" 2>/dev/null && dr=yes
    echo "  SERVICE RULES (security/services.properties): $nw WFS rule(s); CreateStoredQuery rule: $cr; DropStoredQuery rule: $dr"
  else
    echo '  SERVICE RULES (security/services.properties): absent'
  fi
  XRX='\.([Jj][Ss][Pp]|[Jj][Ss][Pp][Xx]|[Ww][Aa][Rr]|[Jj][Aa][Rr]|[Cc][Ll][Aa][Ss][Ss]|[Ss][Oo]|[Dd][Ll][Ll]|[Dd][Yy][Ll][Ii][Bb]|[Ee][Xx][Ee]|[Ss][Hh]|[Pp][Ss]1|[Bb][Aa][Tt]|[Cc][Mm][Dd]|[Pp][Hh][Pp]|[Aa][Ss][Pp][Xx])$'
  BRX='\.([Dd][Bb]|[Ss][Qq][Ll][Ii][Tt][Ee]3?|[Ss][Cc][Rr][Ii][Pp][Tt]|[Ll][Oo][Bb][Ss])$'
  ex=""; nx=0; db=""; nb=0
  while IFS= read -r -d '' f; do
    rel=${f#"$D"}; rel=${rel#/}; b=${rel##*/}
    if [[ $b =~ $XRX ]]; then nx=$((nx + 1)); ex+="$(clean "$rel")"$'\n'; fi
    case $rel in security/*) if [[ $b =~ $BRX ]]; then nb=$((nb + 1)); db+="$(clean "$rel")"$'\n'; fi;; esac
  done < <(list_files "$D")
  echo "  EXECUTABLE OR SCRIPT FILES IN DATA DIRECTORY: $nx"
  [ "$nx" = 0 ] || { printf '%s' "$ex" | show_list; DR=$((DR + 1)); }
  echo "  DATABASE FILES UNDER security/: $nb"
  [ "$nb" = 0 ] || { printf '%s' "$db" | show_list; DR=$((DR + 1)); }
  echo "  DATA DIRECTORY ITEMS TO REVIEW: $DR"
fi

echo "SUMMARY: versions affected $NA, fixed $NF, review $NR"
if [ "$NA" -gt 0 ]; then echo 'RESULT: AFFECTED (exit 2)'; exit 2; fi
if [ "$NR" -gt 0 ] || [ "$DR" -gt 0 ] || [ $((NF)) = 0 ]; then echo 'RESULT: REVIEW (exit 3)'; exit 3; fi
echo 'RESULT: FIXED (exit 0)'; exit 0
