#!/usr/bin/env bash
# Read-only checker for Joomla! Core CVE-2026-133347 (advisory [20261201], PHP object injection
# through file cache guard handling). Compares a version you supply, or official Version.php
# constants, with the affected ranges 1.5.0-5.4.11 and 6.0.0-6.2.1, and the fixed releases
# 5.4.12 and 6.2.2. No network, no file writes, no payloads.
# It never contacts a Joomla! server and never opens configuration.php (database, SMTP and secret values).
# Exit: 0 FIXED, 2 AFFECTED, 3 REVIEW, 5 usage or read error. Pack 1.0.0.
# Usage: check-joomla-cve-2026-133347.sh [--version V] [--version-file FILE] [--root DIR] [--csv FILE]
#   [--cache-handler VALUE] [--list-cache] [--host NAME]
#   --version V            Joomla! version, for example 5.4.11 or 6.2.2
#   --version-file F       saved copy of libraries/src/Version.php (or the 2.5 path)
#   --root DIR             Joomla! install root; reads only DIR/libraries/src/Version.php
#                          or DIR/libraries/cms/version/version.php if the first is absent
#   --csv FILE             inventory CSV with header host,version,cache_handler
#   --cache-handler VALUE  file, unknown, or a non-file handler (for example redis or memcached)
#   --list-cache           with --root, list names, types and timestamps under cache/
#                          and administrator/cache/ (never opens file contents)
#   --host NAME            label for a single-row run
set -u
export LC_ALL=C

usage() {
  echo 'usage: check-joomla-cve-2026-133347.sh [--version V] [--version-file FILE] [--root DIR] [--csv FILE] [--cache-handler VALUE] [--list-cache] [--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
    configuration.php|configuration.php-dist|configuration.php.dist) return 0;;
  esac
  return 1
}

VSTR=''; VFILE=''; ROOT=''; CSV=''; HANDLER='unknown'; LIST=0; HOST=''
gv=0; gf=0; gr=0; gc=0; ghnd=0; gh=0; gl=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;;
    --cache-handler) [ $# -ge 2 ] || usage; [ "$ghnd" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; ghnd=1; HANDLER=$2; shift 2;;
    --list-cache) [ "$gl" = 0 ] || { echo 'ERROR: give each option once'; exit 5; }; gl=1; LIST=1; shift;;
    --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
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
if [ "$LIST" = 1 ] && [ "$gr" != 1 ]; then echo 'ERROR: --list-cache requires --root'; exit 5; fi

norm_handler() {
  local e; e=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
  case $e in
    ''|unknown|unk) printf 'unknown';;
    file|files|filesystem) printf 'file';;
    redis|memcached|memcache|apcu|apc|wincache|xcache|rediscluster) printf 'other';;
    *) printf 'other';;
  esac
}

# Return a canonical x.y.z or empty.
extract_ver() {
  local s=$1
  s=$(printf '%s' "$s" | tr -d '\r')
  if printf '%s' "$s" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
    printf '%s' "$s"
    return
  fi
  # A lone line that is already x.y.z with optional leftover suffix we do not accept.
  return 0
}

# Parse official Version.php (constants or 2.5 properties). Never execute PHP.
parse_version_file() {
  local f=$1 maj='' min='' pat='' rel='' dev=''
  local line t
  while IFS= read -r line || [ -n "$line" ]; do
    line=${line%$'\r'}
    case $line in \#*|//*) continue;; esac
    if t=$(printf '%s' "$line" | sed -n 's/.*MAJOR_VERSION[[:space:]]*=[[:space:]]*\([0-9][0-9]*\).*/\1/p'); then
      [ -n "$t" ] && maj=$t
    fi
    if t=$(printf '%s' "$line" | sed -n 's/.*MINOR_VERSION[[:space:]]*=[[:space:]]*\([0-9][0-9]*\).*/\1/p'); then
      [ -n "$t" ] && min=$t
    fi
    if t=$(printf '%s' "$line" | sed -n 's/.*PATCH_VERSION[[:space:]]*=[[:space:]]*\([0-9][0-9]*\).*/\1/p'); then
      [ -n "$t" ] && pat=$t
    fi
    if t=$(printf '%s' "$line" | sed -n "s/.*\$RELEASE[[:space:]]*=[[:space:]]*'\\([0-9][0-9]*\\.[0-9][0-9]*\\)'.*/\\1/p"); then
      [ -n "$t" ] && rel=$t
    fi
    if t=$(printf '%s' "$line" | sed -n "s/.*RELEASE[[:space:]]*=[[:space:]]*'\\([0-9][0-9]*\\.[0-9][0-9]*\\)'.*/\\1/p"); then
      [ -n "$t" ] && rel=$t
    fi
    if t=$(printf '%s' "$line" | sed -n "s/.*\$DEV_LEVEL[[:space:]]*=[[:space:]]*'\\([0-9][0-9]*\\)'.*/\\1/p"); then
      [ -n "$t" ] && dev=$t
    fi
    if t=$(printf '%s' "$line" | sed -n "s/.*DEV_LEVEL[[:space:]]*=[[:space:]]*'\\([0-9][0-9]*\\)'.*/\\1/p"); then
      [ -n "$t" ] && dev=$t
    fi
  done < "$f"
  if [ -n "$maj" ] && [ -n "$min" ] && [ -n "$pat" ]; then
    printf '%s.%s.%s' "$maj" "$min" "$pat"
    return
  fi
  if [ -n "$rel" ] && [ -n "$dev" ]; then
    printf '%s.%s' "$rel" "$dev"
    return
  fi
}

# Compare dotted triples: echo -1, 0, 1 for a<b, a==b, a>b. Missing parts treated as 0 after split.
cmp_ver() {
  local a=$1 b=$2
  local IFS=.
  # shellcheck disable=SC2086
  set -- $a
  local a1=${1:-0} a2=${2:-0} a3=${3:-0}
  # shellcheck disable=SC2086
  set -- $b
  local b1=${1:-0} b2=${2:-0} b3=${3:-0}
  if [ "$a1" -lt "$b1" ]; then echo -1; return; fi
  if [ "$a1" -gt "$b1" ]; then echo 1; return; fi
  if [ "$a2" -lt "$b2" ]; then echo -1; return; fi
  if [ "$a2" -gt "$b2" ]; then echo 1; return; fi
  if [ "$a3" -lt "$b3" ]; then echo -1; return; fi
  if [ "$a3" -gt "$b3" ]; then echo 1; return; fi
  echo 0
}

# Return FIXED, AFFECTED or empty (unparseable).
base_verdict() {
  local v=$1
  [ -n "$v" ] || { printf ''; return; }
  local c15 c5411 c50 c60 c621
  c15=$(cmp_ver "$v" 1.5.0)
  c5411=$(cmp_ver "$v" 5.4.11)
  c50=$(cmp_ver "$v" 5.0.0)
  # 1.5.0 through 5.4.11 inclusive
  if [ "$c15" -ge 0 ] && [ "$c5411" -le 0 ]; then
    printf 'AFFECTED'
    return
  fi
  # 5.4.12 and later on 5.x (5.4.12, 5.4.13, 5.5.0, ...)
  if [ "$c50" -ge 0 ] && [ "$(cmp_ver "$v" 6.0.0)" -lt 0 ]; then
    if [ "$(cmp_ver "$v" 5.4.12)" -ge 0 ]; then
      printf 'FIXED'
      return
    fi
  fi
  c60=$(cmp_ver "$v" 6.0.0)
  c621=$(cmp_ver "$v" 6.2.1)
  if [ "$c60" -ge 0 ] && [ "$c621" -le 0 ]; then
    printf 'AFFECTED'
    return
  fi
  # 6.2.2 and later on 6.x, and any later 6.x minor
  if [ "$c60" -ge 0 ] && [ "$(cmp_ver "$v" 7.0.0)" -lt 0 ]; then
    if [ "$(cmp_ver "$v" 6.2.2)" -ge 0 ]; then
      printf 'FIXED'
      return
    fi
  fi
  printf ''
}

no_in_branch_fix() {
  local v=$1
  [ -n "$v" ] || return 1
  # 1.5.0-4.x, 5.0.0-5.3.x, 6.0.0-6.1.x have no patched release named in the advisory
  if [ "$(cmp_ver "$v" 1.5.0)" -ge 0 ] && [ "$(cmp_ver "$v" 5.0.0)" -lt 0 ]; then return 0; fi
  if [ "$(cmp_ver "$v" 5.0.0)" -ge 0 ] && [ "$(cmp_ver "$v" 5.4.0)" -lt 0 ]; then return 0; fi
  if [ "$(cmp_ver "$v" 6.0.0)" -ge 0 ] && [ "$(cmp_ver "$v" 6.2.0)" -lt 0 ]; then return 0; fi
  return 1
}

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

rank() {
  case $1 in
    2) echo 3;;
    3) echo 2;;
    0) echo 1;;
    *) echo 0;;
  esac
}

NA=0; NF=0; NR=0; N=0; WORST=-1
tally() {
  case $1 in
    AFFECTED) NA=$((NA + 1));;
    FIXED) NF=$((NF + 1));;
    *) NR=$((NR + 1));;
  esac
}

note_row() {
  local ev=$1 handler=$2 verd=$3
  if [ "$verd" = FIXED ]; then
    echo 'NOTE: this version is 5.4.12 or later on 5.x, or 6.2.2 or later on 6.x, the fixed releases named in Joomla! advisory [20261201]. Confirm against the official release notes.'
    return
  fi
  if [ "$verd" = AFFECTED ]; then
    echo 'NOTE: this version is in the affected range in Joomla! advisory [20261201] (1.5.0-5.4.11 or 6.0.0-6.2.1). Upgrade to 5.4.12 or 6.2.2.'
    if no_in_branch_fix "$ev"; then
      echo 'NOTE: there is no patched release in this branch. Upgrade to Joomla! 5.4.12 or 6.2.2. Joomla! 5.4 receives security fixes only until 12 October 2027.'
    fi
    return
  fi
  if [ "$handler" = other ]; then
    echo 'NOTE: a non-file cache handler was reported. Switching the Cache Handler away from File is the official workaround in advisory [20261201], not a vendor upgrade. Confirm the setting in Global Configuration (do not print configuration.php).'
  fi
  if [ -n "$ev" ] && no_in_branch_fix "$ev"; then
    echo 'NOTE: there is no patched release in this branch. Upgrade to Joomla! 5.4.12 or 6.2.2. Joomla! 5.4 receives security fixes only until 12 October 2027.'
  fi
  if [ -z "$ev" ]; then
    echo 'NOTE: the version could not be parsed as x.y.z, so this row stays REVIEW.'
  elif [ "$(cmp_ver "$ev" 7.0.0)" -ge 0 ]; then
    echo 'NOTE: this version is later than the 6.x stream named in the advisory. Confirm with Joomla! before treating it as fixed.'
  fi
}

add_row() {
  local h=$1 shown=$2 handler=$3 ev=$4
  local base verd
  base=$(base_verdict "$ev")
  if [ -z "$base" ]; then
    verd=REVIEW
    shown='(not shown)'
    # If ev was unparseable we already pass empty; if ev is out of range (e.g. 7.x or 1.0.x) base is empty but ev is set.
    if [ -n "$ev" ]; then
      shown=$ev
    fi
  elif [ "$base" = AFFECTED ] && [ "$handler" = other ]; then
    verd=REVIEW
  else
    verd=$base
  fi
  tally "$verd"
  local rc
  case $verd in
    AFFECTED) rc=2;;
    FIXED) rc=0;;
    *) rc=3;;
  esac
  if [ "$WORST" -lt 0 ] || [ "$(rank "$rc")" -gt "$(rank "$WORST")" ]; then WORST=$rc; fi
  if [ "$h" = input ]; then
    echo "VERSION: $shown CACHE_HANDLER: $handler $verd"
  else
    echo "VERSION: $h $shown CACHE_HANDLER: $handler $verd"
  fi
  note_row "$ev" "$handler" "$verd"
  N=$((N + 1))
}

list_cache_dir() {
  local root=$1 rel=$2
  local dir=$root/$rel
  if [ ! -d "$dir" ]; then
    echo "CACHE LIST: $rel (directory not present)"
    return
  fi
  # Read-only listing: names, types and timestamps only. Never open file contents. Do not follow links.
  # Sorted by relative path so bash and PowerShell match.
  find -P "$dir" \( -type f -o -type d -o -type l \) -printf '%y\t%TY-%Tm-%Td %TH:%TM:%TS\t%p\n' 2>/dev/null \
    | sort -t $'\t' -k3,3 \
    | while IFS=$'\t' read -r typ ts path; do
        ts=${ts%.*}
        relp=${path#"$root"/}
        case $relp in
          *configuration.php*) continue;;
        esac
        case $typ in
          f) typ='file';;
          d) typ='dir';;
          l) typ='link';;
        esac
        echo "CACHE LIST: $typ $ts $relp"
      done
}

# Validate inputs that open files
if [ "$gf" = 1 ]; then
  if is_denied_file "$VFILE"; then echo 'ERROR: refused to open a Joomla! configuration 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
  if is_denied_file "$ROOT"; then echo 'ERROR: refused to open a Joomla! configuration or secret file'; exit 5; fi
fi
if [ "$gc" = 1 ]; then
  if is_denied_file "$CSV"; then echo 'ERROR: refused to open a Joomla! configuration or secret file'; exit 5; fi
  if [ ! -f "$CSV" ] || [ ! -r "$CSV" ]; then echo 'ERROR: csv missing or unreadable'; exit 5; fi
fi

HANDLER=$(norm_handler "$HANDLER")

echo 'Joomla! CVE-2026-133347 checker (read only; no network, no file writes, no secrets printed)'
echo 'NOTE: no exploitation reported by Joomla! as of 1 Dec 2026; not listed in CISA KEV as of 1 Dec 2026 (catalogue 2026.11.30).'
echo 'NOTE: CISA KEV due dates bind US federal agencies only (BOD 26-04). Patch now regardless.'
echo 'FIXED RELEASE: Joomla! 5.4.12 and 6.2.2 (advisory [20261201]). Workaround: use a Cache Handler other than File in Global Configuration. CVE.org CVSS 4.0 9.4 Critical (PR:H).'

if [ "$gc" = 1 ]; then
  head -n1 "$CSV" | tr -d '\r' | sed 's/^\xef\xbb\xbf//' | tr '[:upper:]' '[:lower:]' | grep -qxF 'host,version,cache_handler' || { echo 'ERROR: CSV header must be: host,version,cache_handler'; 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 hnd 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:]]*$//')
    hnd=$(printf '%s' "$hnd" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
    [ -n "$hnd" ] || hnd=unknown
    hnd=$(norm_handler "$hnd")
    ev=$(extract_ver "$ver")
    add_row "$h" "$(showver "$ev")" "$hnd" "$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
  if [ "$gr" = 1 ]; then
    if [ -f "$ROOT/libraries/src/Version.php" ]; then
      VFILE="$ROOT/libraries/src/Version.php"
    elif [ -f "$ROOT/libraries/cms/version/version.php" ]; then
      VFILE="$ROOT/libraries/cms/version/version.php"
    else
      echo 'ERROR: version file missing or unreadable'
      exit 5
    fi
    if is_denied_file "$VFILE"; then echo 'ERROR: refused to open a Joomla! configuration or secret file'; exit 5; fi
  fi
  ev=$(parse_version_file "$VFILE")
  ev=$(extract_ver "$ev")
  h=${HOST:-input}
  if [ -z "$ev" ]; then
    add_row "$h" '(not shown)' "$HANDLER" ''
  else
    add_row "$h" "$(showver "$ev")" "$HANDLER" "$ev"
  fi
  if [ "$LIST" = 1 ]; then
    echo 'CACHE LIST: filenames, types and timestamps only; file contents were not opened.'
    list_cache_dir "$ROOT" 'cache'
    list_cache_dir "$ROOT" 'administrator/cache'
  fi
else
  ev=$(extract_ver "$VSTR")
  h=${HOST:-input}
  if [ -z "$ev" ]; then
    add_row "$h" '(not shown)' "$HANDLER" ''
  else
    add_row "$h" "$(showver "$ev")" "$HANDLER" "$ev"
  fi
fi

w=REVIEW
case $WORST in
  0) w=FIXED;;
  2) w=AFFECTED;;
  3) w=REVIEW;;
esac
echo "RESULT: $w ($N checked: $NF FIXED, $NA AFFECTED, $NR REVIEW) (exit $WORST)"
echo 'Patch now regardless.'
exit "$WORST"
