#!/usr/bin/env bash
# Read-only checker for Django CVE-2026-132092 (SQL injection in range and in lookups),
# part of the 2 Dec 2026 Django security releases 6.1.4, 6.0.11 and 5.2.20 (seven CVEs).
# It compares a version you supply, or a saved django/__init__.py, PyPI METADATA/PKG-INFO or
# requirements.txt file, with the fixed releases. No network, no file writes, no payloads,
# never executes Python, never opens settings.py or .env files, never prints secrets.
# Exit: 0 FIXED, 2 AFFECTED, 3 REVIEW, 5 usage or read error. Pack 1.0.0.
# Usage: check-django-cve-2026-132092.sh [--version V] [--version-file FILE] [--root DIR] [--csv FILE] [--host NAME]
#   --version V          Django version, for example 6.1.3 or 6.1.4
#   --version-file F     saved django/__init__.py, METADATA, PKG-INFO or requirements.txt
#   --root DIR           read only DIR/django/__init__.py, DIR/METADATA, DIR/PKG-INFO or DIR/requirements.txt
#   --csv FILE           inventory CSV with header host,version
#   --host NAME          label for a single --version, --version-file or --root row
set -u
export LC_ALL=C

usage() {
  echo 'usage: check-django-cve-2026-132092.sh [--version V] [--version-file FILE] [--root DIR] [--csv FILE] [--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"
}

# Refuse files that commonly hold SECRET_KEY, database passwords or other secrets.
is_refused() {
  local b
  b=$(basename -- "$1")
  b=$(printf '%s' "$b" | tr '[:upper:]' '[:lower:]')
  case $b in
    settings.py|local_settings.py|secrets.py|credentials.py|.env|.env.local|.env.prod|.env.production|.env.development|.env.test)
      return 0;;
  esac
  return 1
}

VSTR=''; VFILE=''; ROOT=''; CSV=''; HOST=''; gv=0; gf=0; gr=0; gc=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;;
    --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
ninputs=$((gv + gf + gr + gc))
[ "$ninputs" -eq 1 ] || { echo 'ERROR: use only one of --csv or --version/--version-file/--root'; exit 5; }
[ "$gc" = 1 ] && [ "$gh" = 1 ] && { echo 'ERROR: use only one of --csv or --version/--version-file/--root'; exit 5; }

resolve_root() {
  local d=$1 f
  [ -d "$d" ] || { echo 'ERROR: root directory missing or unreadable'; exit 5; }
  for f in "$d/django/__init__.py" "$d/METADATA" "$d/PKG-INFO" "$d/requirements.txt"; do
    if [ -f "$f" ] && [ -r "$f" ]; then
      if is_refused "$f"; then echo 'ERROR: refused to open a settings or secrets file'; exit 5; fi
      printf '%s' "$f"
      return
    fi
  done
  echo 'ERROR: no django/__init__.py, METADATA, PKG-INFO or requirements.txt under the root'; exit 5
}

if [ "$gr" = 1 ]; then
  VFILE=$(resolve_root "$ROOT")
  gf=1
fi

if [ "$gf" = 1 ]; then
  if is_refused "$VFILE"; then echo 'ERROR: refused to open a settings or secrets file'; exit 5; fi
  if [ ! -f "$VFILE" ] || [ ! -r "$VFILE" ]; then echo 'ERROR: version file missing or unreadable'; exit 5; fi
fi
if [ "$gc" = 1 ] && { [ ! -f "$CSV" ] || [ ! -r "$CSV" ]; }; then echo 'ERROR: csv missing or unreadable'; exit 5; fi

# Official Django versions are major.minor.micro, optionally with a, b or rc (from get_version
# on the official VERSION tuple in django/__init__.py). Four-part IPv4-like values are not Django versions.
VRX='^([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{1,3})((a|b|rc)([0-9]{1,3}))?$'
VRX2='^([0-9]{1,2})\.([0-9]{1,2})$'

showver() { if [[ $1 =~ $VRX ]] || [[ $1 =~ $VRX2 ]]; then printf '%s' "$1"; else printf '(not shown)'; fi; }

# Canonical X.Y.Z or X.Y.Z plus official pre-release suffix, or empty.
extract_ver() {
  local s=$1 t
  s=$(printf '%s' "$s" | tr -d '\r')
  # Official django/__init__.py: VERSION = (6, 1, 4, "final", 0)
  if [[ $s =~ VERSION[[:space:]]*=[[:space:]]*\(([0-9]{1,2})[[:space:]]*,[[:space:]]*([0-9]{1,2})[[:space:]]*,[[:space:]]*([0-9]{1,3})[[:space:]]*,[[:space:]]*[\"\']([A-Za-z]+)[\"\'][[:space:]]*,[[:space:]]*([0-9]+) ]]; then
    local a=${BASH_REMATCH[1]} b=${BASH_REMATCH[2]} c=${BASH_REMATCH[3]} st=${BASH_REMATCH[4]} se=${BASH_REMATCH[5]}
    st=$(printf '%s' "$st" | tr '[:upper:]' '[:lower:]')
    case $st in
      final) printf '%s.%s.%s' "$a" "$b" "$c"; return;;
      alpha) printf '%s.%s.%sa%s' "$a" "$b" "$c" "$se"; return;;
      beta) printf '%s.%s.%sb%s' "$a" "$b" "$c" "$se"; return;;
      rc) printf '%s.%s.%src%s' "$a" "$b" "$c" "$se"; return;;
      *) printf '%s.%s.%s' "$a" "$b" "$c"; return;;
    esac
  fi
  # Official-style __version__ = "6.1.4" or __version__ = '6.1.4'
  if [[ $s =~ __version__[[:space:]]*=[[:space:]]*[\"\']([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}((a|b|rc)[0-9]{1,3})?)[\"\'] ]]; then
    printf '%s' "${BASH_REMATCH[1]}"; return
  fi
  # PyPI METADATA / PKG-INFO: Version: 6.1.4
  if [[ $s =~ [Vv]ersion:[[:space:]]*([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}((a|b|rc)[0-9]{1,3})?) ]]; then
    printf '%s' "${BASH_REMATCH[1]}"; return
  fi
  # requirements.txt: Django==6.1.3 or django[argon2]==6.1.3 (first Django pin on the line)
  if [[ $s =~ [Dd]jango(\[[A-Za-z0-9,_-]+\])?==(=)?([0-9]{1,2}\.[0-9]{1,2}(\.[0-9]{1,3}((a|b|rc)[0-9]{1,3})?)?) ]]; then
    printf '%s' "${BASH_REMATCH[3]}"; return
  fi
  t=$(printf '%s' "$s" | tr -d '[:space:]')
  t=${t#[vV]}
  if [[ $t =~ $VRX ]] || [[ $t =~ $VRX2 ]]; then printf '%s' "$t"; return; fi
  printf ''
}

# Returns FIXED, AFFECTED or REVIEW.
# Fixed releases: 5.2.20, 6.0.11, 6.1.4. Later series (6.2 and above) are treated as FIXED
# because the official patches were also applied to Django main. Unsupported series before
# 5.2 (including 5.1.x, 5.0.x and 4.2.x) were not evaluated and are REVIEW.
verdict_of() {
  local v=$1 pre=0
  if [[ $v =~ $VRX2 ]]; then
    v="${v}.0"
  fi
  if ! [[ $v =~ $VRX ]]; then echo REVIEW; return; fi
  local a=$((10#${BASH_REMATCH[1]})) b=$((10#${BASH_REMATCH[2]})) c=$((10#${BASH_REMATCH[3]}))
  if [ -n "${BASH_REMATCH[4]}" ]; then pre=1; fi
  if [ "$a" -lt 1 ] || [ "$a" -gt 20 ]; then echo REVIEW; return; fi
  # Unsupported older series: not evaluated, may also be affected.
  if [ "$a" -lt 5 ]; then echo REVIEW; return; fi
  if [ "$a" -eq 5 ] && [ "$b" -lt 2 ]; then echo REVIEW; return; fi
  # Unknown 5.x after 5.2 (for example 5.3) is not in the advisory range.
  if [ "$a" -eq 5 ] && [ "$b" -gt 2 ]; then echo REVIEW; return; fi
  # 6.2+ and 7+ : patches applied to main, treat as FIXED.
  if [ "$a" -gt 6 ]; then echo FIXED; return; fi
  if [ "$a" -eq 6 ] && [ "$b" -ge 2 ]; then echo FIXED; return; fi
  # 6.1.x
  if [ "$a" -eq 6 ] && [ "$b" -eq 1 ]; then
    if [ "$c" -gt 4 ]; then echo FIXED; return; fi
    if [ "$c" -eq 4 ] && [ "$pre" -eq 0 ]; then echo FIXED; return; fi
    echo AFFECTED; return
  fi
  # 6.0.x
  if [ "$a" -eq 6 ] && [ "$b" -eq 0 ]; then
    if [ "$c" -gt 11 ]; then echo FIXED; return; fi
    if [ "$c" -eq 11 ] && [ "$pre" -eq 0 ]; then echo FIXED; return; fi
    echo AFFECTED; return
  fi
  # 5.2.x
  if [ "$a" -eq 5 ] && [ "$b" -eq 2 ]; then
    if [ "$c" -gt 20 ]; then echo FIXED; return; fi
    if [ "$c" -eq 20 ] && [ "$pre" -eq 0 ]; then echo FIXED; return; fi
    echo AFFECTED; return
  fi
  echo REVIEW
}

note_verdict() {
  local verd=$1 ver=$2
  if [ "$verd" = REVIEW ]; then
    if [[ $ver =~ $VRX2 ]]; then ver="${ver}.0"; fi
    if [[ $ver =~ $VRX ]]; then
      local a=$((10#${BASH_REMATCH[1]})) b=$((10#${BASH_REMATCH[2]}))
      if [ "$a" -lt 5 ] || { [ "$a" -eq 5 ] && [ "$b" -lt 2 ]; }; then
        echo 'NOTE: CVE.org says earlier unsupported Django series (such as 5.1.x, 5.0.x, and 4.2.x) were not evaluated and may also be affected. Upgrade to 5.2.20, 6.0.11 or 6.1.4, or to a later supported release.'
      fi
    fi
  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 'Django CVE-2026-132092 checker (read only; no network, no file writes, no Python execution, no secrets printed)'
echo 'NOTE: no exploitation reported by Django as of 2 Dec 2026; not listed in CISA KEV as of 2 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: Django 6.1.4, 6.0.11 or 5.2.20 (2 Dec 2026 security releases). CVE.org rates CVE-2026-132092 CVSS 3.1 9.8 Critical and CVSS 4.0 9.3 Critical; Django rates it high under its own security policy.'

WORST=-1
add_row() {
  local h=$1 shown=$2 verd=$3 raw=$4 rc
  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 $verd"
  else
    echo "VERSION: $h $shown $verd"
  fi
  note_verdict "$verd" "$raw"
}

extract_from_file() {
  local ev='' t 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 < "$1"
  if [ "$found" = 1 ]; then printf '%s' "$ev"; fi
}

if [ "$gc" = 1 ]; then
  head -n1 "$CSV" | tr -d '\r' | sed 's/^\xef\xbb\xbf//' | tr '[:upper:]' '[:lower:]' | grep -qxF 'host,version' || { echo 'ERROR: CSV header must be: host,version'; 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 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:]]*$//')
    ev=$(extract_ver "$ver")
    if [ -z "$ev" ]; then add_row "$h" '(not shown)' REVIEW ''; else add_row "$h" "$(showver "$ev")" "$(verdict_of "$ev")" "$ev"; fi
    n=$((n + 1))
  done < <(tail -n +2 "$CSV")
  [ "$n" -gt 0 ] || { echo 'ERROR: CSV has no rows'; exit 5; }
elif [ "$gf" = 1 ]; then
  ev=$(extract_from_file "$VFILE")
  h=${HOST:-input}
  if [ -z "$ev" ]; then add_row "$h" '(not shown)' REVIEW ''; else add_row "$h" "$(showver "$ev")" "$(verdict_of "$ev")" "$ev"; fi
else
  ev=$(extract_ver "$VSTR")
  h=${HOST:-input}
  if [ -z "$ev" ]; then add_row "$h" '(not shown)' REVIEW ''; else add_row "$h" "$(showver "$ev")" "$(verdict_of "$ev")" "$ev"; fi
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"
