#!/usr/bin/env bash
# Read-only checker for the unpatched Cacti remote code execution issue disclosed 26-27 Nov 2026
# (tracked in news coverage as 4HTTP2SHELL / 4HTTP2ROOT; no CVE assigned as of 27 Nov 2026).
# It compares a version you supply, or the official include/cacti_version file, with Cacti Core 1.2.31
# and an operator-supplied guest-account flag. No network, no database, no file writes, no payloads.
# It never contacts a Cacti server and never opens include/config.php (database credentials).
# Exit: 0 FIXED, 2 AFFECTED, 3 REVIEW, 5 usage or read error. Pack 1.0.0.
# Usage: check-cacti-unpatched-rce.sh [--version V] [--version-file FILE] [--root DIR] [--csv FILE]
#   [--guest enabled|disabled|unknown] [--fix none|shipped] [--host NAME]
#   --version V          Cacti version, for example 1.2.31
#   --version-file F     saved copy of include/cacti_version (a single version token)
#   --root DIR           Cacti install root; reads only DIR/include/cacti_version
#   --csv FILE           inventory CSV with header host,version,guest,fix
#   --guest VALUE        enabled, disabled or unknown (default unknown)
#   --fix VALUE          none (default; no official fix as of 27 Nov 2026) or shipped
#   --host NAME          label for a single-row run
set -u
export LC_ALL=C

usage() {
  echo 'usage: check-cacti-unpatched-rce.sh [--version V] [--version-file FILE] [--root DIR] [--csv FILE] [--guest enabled|disabled|unknown] [--fix none|shipped] [--host NAME]'
  exit 5
}
esc() {
  local s=$1 o='' c i h
  for ((i = 0; i < ${#s}; i++)); do
    c=${s:i:1}
    if [[ $c == [A-Za-z0-9._/-] ]]; then o+=$c; else printf -v h '\\x%02X' "'$c"; o+=$h; fi
  done
  printf '%s' "$o"
}

is_denied_file() {
  local b
  b=$(basename -- "$1")
  case $b in
    config.php|config.php.dist|csrf_secret.php) return 0;;
  esac
  return 1
}

VSTR=''; VFILE=''; ROOT=''; CSV=''; GUEST='unknown'; FIX='none'; HOST=''
gv=0; gf=0; gr=0; gc=0; gg=0; gx=0; gh=0
while [ $# -gt 0 ]; do
  case $1 in
    --version) [ $# -ge 2 ] || usage; [ "$gv" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; gv=1; VSTR=$2; shift 2;;
    --version-file) [ $# -ge 2 ] || usage; [ "$gf" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; gf=1; VFILE=$2; shift 2;;
    --root) [ $# -ge 2 ] || usage; [ "$gr" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; gr=1; ROOT=$2; shift 2;;
    --csv) [ $# -ge 2 ] || usage; [ "$gc" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; gc=1; CSV=$2; shift 2;;
    --guest) [ $# -ge 2 ] || usage; [ "$gg" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; gg=1; GUEST=$2; shift 2;;
    --fix) [ $# -ge 2 ] || usage; [ "$gx" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; gx=1; FIX=$2; shift 2;;
    --host) [ $# -ge 2 ] || usage; [ "$gh" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; gh=1; HOST=$2; shift 2;;
    -h|--help) usage;;
    *) echo "ERROR: unknown option: $(esc "$1")"; exit 5;;
  esac
done
[ "$gv$gf$gr$gc" != 0000 ] || usage
# Only one of csv or a single-row input.
src=$((gv + gf + gr))
if [ "$gc" = 1 ] && [ "$src" -ne 0 ]; then echo 'ERROR: use only one of --csv or --version/--version-file/--root'; exit 5; fi
if [ "$src" -gt 1 ]; then echo 'ERROR: use only one of --csv or --version/--version-file/--root'; exit 5; fi

norm_guest() {
  local e; e=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
  case $e in
    ''|unknown|unk) printf 'unknown';;
    enabled|enable|on|yes) printf 'enabled';;
    disabled|disable|off|no) printf 'disabled';;
    *) printf 'bad';;
  esac
}
norm_fix() {
  local e; e=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
  case $e in
    ''|none|no|unpatched) printf 'none';;
    shipped|yes|patched|fixed) printf 'shipped';;
    *) printf 'bad';;
  esac
}

GUEST=$(norm_guest "$GUEST")
FIX=$(norm_fix "$FIX")
[ "$GUEST" != bad ] || { echo 'ERROR: --guest must be enabled, disabled or unknown'; exit 5; }
[ "$FIX" != bad ] || { echo 'ERROR: --fix must be none or shipped'; exit 5; }

if [ "$gf" = 1 ]; then
  if is_denied_file "$VFILE"; then echo 'ERROR: refused to open a Cacti config or secret file'; exit 5; fi
  if [ ! -f "$VFILE" ] || [ ! -r "$VFILE" ]; then echo 'ERROR: version file missing or unreadable'; exit 5; fi
fi
if [ "$gr" = 1 ]; then
  if [ ! -d "$ROOT" ]; then echo 'ERROR: root directory missing or unreadable'; exit 5; fi
  VFILE="$ROOT/include/cacti_version"
  if is_denied_file "$VFILE"; then echo 'ERROR: refused to open a Cacti config or secret file'; exit 5; fi
  if [ ! -f "$VFILE" ] || [ ! -r "$VFILE" ]; then echo 'ERROR: version file missing or unreadable'; exit 5; fi
fi
if [ "$gc" = 1 ]; then
  if is_denied_file "$CSV"; then echo 'ERROR: refused to open a Cacti config or secret file'; exit 5; fi
  if [ ! -f "$CSV" ] || [ ! -r "$CSV" ]; then echo 'ERROR: csv missing or unreadable'; exit 5; fi
fi

# Official include/cacti_version is a three-part token such as 1.2.31.
VRX='^([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{1,3})$'

extract_ver() {
  local s=$1 t
  s=$(printf '%s' "$s" | tr -d '\r')
  t=$(printf '%s' "$s" | tr -d '[:space:]')
  t=${t#[vV]}
  if [[ $t =~ $VRX ]]; then printf '%s' "$t"; return; fi
  if [[ $s =~ [Cc]acti[[:space:]]+(Core[[:space:]]+)?([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}) ]]; then
    printf '%s' "${BASH_REMATCH[2]}"; return
  fi
  if [[ $s =~ (^|[[:space:]])([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3})($|[[:space:]]) ]]; then
    printf '%s' "${BASH_REMATCH[2]}"; return
  fi
  printf ''
}

showver() {
  local v=$1
  if [ -z "$v" ]; then printf '(not shown)'; else printf '%s' "$v"; fi
}

# Compare with 1.2.31. Returns eq, earlier or later, or bad.
rel_of() {
  local v=$1
  if ! [[ $v =~ $VRX ]]; then echo bad; return; fi
  local a=$((10#${BASH_REMATCH[1]})) b=$((10#${BASH_REMATCH[2]})) c=$((10#${BASH_REMATCH[3]}))
  if [ "$a" -gt 1 ]; then echo later; return; fi
  if [ "$a" -lt 1 ]; then echo earlier; return; fi
  if [ "$b" -gt 2 ]; then echo later; return; fi
  if [ "$b" -lt 2 ]; then echo earlier; return; fi
  if [ "$c" -gt 31 ]; then echo later; return; fi
  if [ "$c" -lt 31 ]; then echo earlier; return; fi
  echo eq
}

# No official fixed release as of 27 Nov 2026. A later version is FIXED only when the operator
# asserts that Cacti has shipped a fix (--fix shipped).
verdict_of() {
  local v=$1 guest=$2 fix=$3 rel
  rel=$(rel_of "$v")
  if [ "$rel" = bad ]; then echo REVIEW; return; fi
  if [ "$fix" = shipped ]; then
    if [ "$rel" = later ]; then echo FIXED; else echo REVIEW; fi
    return
  fi
  if [ "$rel" = eq ] && [ "$guest" = enabled ]; then echo AFFECTED; return; fi
  echo REVIEW
}

note_row() {
  local v=$1 guest=$2 fix=$3 verd=$4 rel
  rel=$(rel_of "$v")
  if [ "$verd" = FIXED ]; then
    echo 'NOTE: operator asserted that a Cacti fix has shipped and this version is later than 1.2.31. Confirm against the official Cacti release notes before you rely on that.'
    return
  fi
  if [ "$fix" = shipped ] && [ "$rel" != later ]; then
    echo 'NOTE: a vendor fix was asserted, but 1.2.31 and earlier were the confirmed or unverified streams as of 27 Nov 2026. Confirm the fixed release with Cacti.'
  fi
  if [ "$rel" = eq ] && [ "$guest" = enabled ]; then
    echo 'NOTE: Cacti Core 1.2.31 with the guest account enabled is the confirmed affected configuration in allowed news coverage.'
  elif [ "$rel" = eq ] && [ "$guest" = disabled ]; then
    echo 'NOTE: guest account reported disabled. That is the current mitigation advised in news coverage, not a vendor fix. Confirm the setting in the Cacti UI or with the manual SQL in the README.'
  elif [ "$rel" = eq ] && [ "$guest" = unknown ]; then
    echo 'NOTE: Cacti Core 1.2.31 is the confirmed affected release when the guest account is enabled. Guest state was not given, so this row stays REVIEW.'
  elif [ "$rel" = earlier ]; then
    echo 'NOTE: whether versions earlier than 1.2.31 are affected is unverified. If the guest account is enabled, treat this host as potentially impacted until Cacti publishes a range.'
  elif [ "$rel" = later ]; then
    echo 'NOTE: this version is later than 1.2.31. No official fixed release was published as of 27 Nov 2026. Confirm with Cacti before treating it as fixed.'
  fi
}

NA=0; NF=0; NR=0
tally() { case $1 in AFFECTED) NA=$((NA + 1));; FIXED) NF=$((NF + 1));; *) NR=$((NR + 1));; esac; }
rank() { case $1 in 2) echo 3;; 3) echo 2;; 0) echo 1;; *) echo 0;; esac; }
code_of() { case $1 in AFFECTED) echo 2;; FIXED) echo 0;; *) echo 3;; esac; }

echo 'Cacti unpatched RCE (4HTTP2SHELL) checker (read only; no network, no database, no file writes, no secrets printed)'
echo 'NOTE: no exploitation reported by BleepingComputer or Cacti as of 27 Nov 2026; not listed in CISA KEV as of 27 Nov 2026 (catalogue 2026.11.25).'
echo 'NOTE: CISA KEV due dates bind US federal agencies only (BOD 26-04). Apply mitigations/patch now regardless.'
echo 'FIXED RELEASE: none published by Cacti as of 27 Nov 2026. Latest official release checked was Cacti Core 1.2.31. Disable the guest account and restrict the web UI to trusted networks until a vendor fix is available.'

WORST=-1
add_row() { # host shown_ver guest fix
  local h=$1 shown=$2 guest=$3 fix=$4 ev=$5 verd rc
  if [ -z "$ev" ]; then
    verd=REVIEW
    shown='(not shown)'
  else
    verd=$(verdict_of "$ev" "$guest" "$fix")
  fi
  tally "$verd"
  rc=$(code_of "$verd")
  if [ "$WORST" -lt 0 ] || [ "$(rank "$rc")" -gt "$(rank "$WORST")" ]; then WORST=$rc; fi
  if [ "$h" = input ]; then
    echo "VERSION: $shown GUEST: $guest FIX: $fix $verd"
  else
    echo "VERSION: $h $shown GUEST: $guest FIX: $fix $verd"
  fi
  note_row "$ev" "$guest" "$fix" "$verd"
}

if [ "$gc" = 1 ]; then
  head -n1 "$CSV" | tr -d '\r' | sed 's/^\xef\xbb\xbf//' | tr '[:upper:]' '[:lower:]' | grep -qxF 'host,version,guest,fix' || { echo 'ERROR: CSV header must be: host,version,guest,fix'; exit 5; }
  n=0
  while IFS= read -r line || [ -n "$line" ]; do
    line=${line%$'\r'}
    [ -z "$line" ] && continue
    case $line in \#*) continue;; esac
    IFS=, read -r h ver gst fx rest <<< "$line"
    h=$(printf '%s' "$h" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
    [ -n "$h" ] || h='host not given'
    ver=$(printf '%s' "$ver" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
    gst=$(printf '%s' "$gst" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
    fx=$(printf '%s' "$fx" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
    [ -n "$gst" ] || gst=unknown
    [ -n "$fx" ] || fx=none
    gst=$(norm_guest "$gst")
    fx=$(norm_fix "$fx")
    if [ "$gst" = bad ] || [ "$fx" = bad ]; then
      echo "VERSION: $h (not shown) GUEST: unknown FIX: none REVIEW"
      echo 'NOTE: guest or fix value not recognised (use enabled|disabled|unknown and none|shipped).'
      tally REVIEW
      if [ "$WORST" -lt 0 ] || [ "$(rank 3)" -gt "$(rank "$WORST")" ]; then WORST=3; fi
      n=$((n + 1))
      continue
    fi
    ev=$(extract_ver "$ver")
    add_row "$h" "$(showver "$ev")" "$gst" "$fx" "$ev"
    n=$((n + 1))
  done < <(tail -n +2 "$CSV")
  [ "$n" -gt 0 ] || { echo 'ERROR: CSV has no rows'; exit 5; }
elif [ "$gf" = 1 ] || [ "$gr" = 1 ]; then
  ev=''; found=0
  while IFS= read -r line || [ -n "$line" ]; do
    line=${line%$'\r'}
    case $line in \#*) continue;; esac
    t=$(extract_ver "$line")
    if [ -n "$t" ]; then ev=$t; found=1; break; fi
  done < "$VFILE"
  h=${HOST:-input}
  if [ "$found" = 0 ]; then
    add_row "$h" '(not shown)' "$GUEST" "$FIX" ''
  else
    add_row "$h" "$(showver "$ev")" "$GUEST" "$FIX" "$ev"
  fi
else
  ev=$(extract_ver "$VSTR")
  h=${HOST:-input}
  add_row "$h" "$(showver "$ev")" "$GUEST" "$FIX" "$ev"
fi

N=$((NA + NF + NR))
case $WORST in
  0) w=FIXED;;
  2) w=AFFECTED;;
  *) w=REVIEW; WORST=3;;
esac
echo "RESULT: $w ($N checked: $NF FIXED, $NA AFFECTED, $NR REVIEW) (exit $WORST)"
exit "$WORST"
