#!/usr/bin/env bash
# check-unifi-access.sh: offline, read-only checker for UniFi Access Application against Ubiquiti Security Advisory
# Bulletin 073 (CVE-2026-132802 to CVE-2026-132808). Pack 1.0.0, CybaVerse threat hunt.
#
# It never touches the network, never runs UniFi or package tools, never writes a file and never prints file contents,
# tokens or secrets. It prints only version numbers, file paths and line numbers. It reads only what you give it:
#   --version V   an Access Application version string (for example 4.3.22 or 4.3.9+12130)
#   --file F      a saved text file (dpkg -l, app-list or package output, a log) or a JSON export (auto-detected)
#   --json F      a JSON export of the applications list (UniFi API or UniFi OS output saved to a file)
#   --dir D       an extracted support file (unpack it yourself first; this checker does not unpack archives)
# Options can be repeated; each one is a separate source with its own verdict.
#
# Exit codes:
#   0 FIXED       every source shows Access Application 4.3.24 or later
#   1             not used (reserved for unexpected runtime errors)
#   2 AFFECTED    at least one source shows a version below 4.3.24
#   3 UNKNOWN     no version found, sources disagree inside one source, or a scan was incomplete (REVIEW)
#   5 USAGE OR READ ERROR
set -u
export LC_ALL=C
VERSION_TAG="check-unifi-access 1.0.0"
FIXED_VERSION="4.3.24"
LAST_LISTED="4.3.22"
MAX_FILES=2000
MAX_SIZE=8388608
MAX_DEPTH=12
MAX_FOUND=50
# CVE|CVSS 3.1 (Ubiquiti)|vector|CWE|access needed (bulletin and NVD wording)|impact
DATA='CVE-2026-132802|9.9 Critical|AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H|CWE-59|network access and low privileges|code execution as root on the host device (link resolution)
CVE-2026-132803|9.9 Critical|AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H|CWE-89|network access and low privileges|privilege escalation on the host device (authenticated SQL injection)
CVE-2026-132804|9.9 Critical|AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H|CWE-918|network access and low privileges|privilege escalation within UniFi OS (SSRF)
CVE-2026-132805|8.3 High|AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:L|CWE-918|network access, no privileges stated|information and unauthorised changes on the host device (SSRF)
CVE-2026-132806|8.8 High|AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H|CWE-89|network access and low privileges|information and unauthorised changes in the Access Application (authenticated SQL injection)
CVE-2026-132807|9.0 Critical|AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:H|CWE-295|network access, under certain conditions|information and changes on an adopted Access device (certificate validation)
CVE-2026-132808|9.9 Critical|AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H|CWE-863|network access and low privileges|arbitrary commands on certain adopted Access devices (incorrect authorisation)'

usage() {
  echo "Usage: check-unifi-access.sh [--version V] [--file FILE] [--json FILE] [--dir DIR] (options can be repeated)"
  echo "  Offline and read only. Exit 0 FIXED, 2 AFFECTED, 3 UNKNOWN or REVIEW, 5 usage or read error."
}
die() { echo "ERROR: $1"; echo "OVERALL: USAGE OR READ ERROR (exit 5)"; exit 5; }
clean() { printf '%s' "$1" | tr -c '[:print:]' '?'; }
isver() { [[ $1 =~ ^[vV]?[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}([+.~-][0-9A-Za-z.+~-]{0,40})?$ ]]; }
norm() { local v=${1#[vV]}; [[ $v =~ ^([0-9]{1,6})\.([0-9]{1,6})\.([0-9]{1,6})([^0-9]|$) ]] && echo "$((10#${BASH_REMATCH[1]})).$((10#${BASH_REMATCH[2]})).$((10#${BASH_REMATCH[3]}))"; }
# vcmp A B: prints -1, 0 or 1 for normalised x.y.z versions
vcmp() {
  local a b i
  IFS=. read -r -a a <<< "$1"; IFS=. read -r -a b <<< "$2"
  for i in 0 1 2; do
    if ((a[i] < b[i])); then echo -1; return; fi
    if ((a[i] > b[i])); then echo 1; return; fi
  done
  echo 0
}
status() { if [ "$(vcmp "$1" "$FIXED_VERSION")" -lt 0 ]; then echo AFFECTED; else echo FIXED; fi; }

[ $# -gt 0 ] || { usage; echo "OVERALL: USAGE OR READ ERROR (exit 5)"; exit 5; }
SRC_KIND=(); SRC_VAL=()
while [ $# -gt 0 ]; do
  case $1 in
    --version|-Version) [ $# -ge 2 ] || die "--version needs a value"; SRC_KIND+=(version); SRC_VAL+=("$2"); shift 2 ;;
    --file|-File) [ $# -ge 2 ] || die "--file needs a value"; SRC_KIND+=(file); SRC_VAL+=("$2"); shift 2 ;;
    --json|-Json) [ $# -ge 2 ] || die "--json needs a value"; SRC_KIND+=(json); SRC_VAL+=("$2"); shift 2 ;;
    --dir|-Dir) [ $# -ge 2 ] || die "--dir needs a value"; SRC_KIND+=(dir); SRC_VAL+=("$2"); shift 2 ;;
    --help|-h|-Help) usage; exit 0 ;;
    *) die "unknown option (see --help)" ;;
  esac
done
[ ${#SRC_KIND[@]} -le 32 ] || die "too many sources (32 at most)"

# Text scan: prints "line<TAB>version" for Access Application version mentions. Never prints line contents.
# shellcheck disable=SC2016  # awk program, expanded by awk not bash
AWK_TEXT='
{
  s = tolower($0); sub(/\r$/, "", s); n = 0
  while (n < 50 && match(s, /(unifi-access|unifi_access|unifi access application|access application)[^a-z0-9]*(version|ver)?[^a-z0-9]*v?[0-9]+\.[0-9]+\.[0-9]+/)) {
    m = substr(s, RSTART, RLENGTH); rest = substr(s, RSTART + RLENGTH)
    if (match(m, /[0-9]+\.[0-9]+\.[0-9]+$/)) { v = substr(m, RSTART, RLENGTH) } else { v = "" }
    if (v != "" && rest !~ /^\.[0-9]/ && length(m) - length(v) <= 64) { print FNR "\t" v; n++ }
    s = rest
  }
}'
# JSON scan: walks objects; an object counts when a name-like key is "access", "unifi-access" or "UniFi Access" (or the
# object sits under such a key) and it has a version-like key. Prints "J<TAB>version", or "W<TAB>reason" for bad JSON.
# shellcheck disable=SC2016  # awk program, expanded by awk not bash
AWK_JSON='
function isname(v) { v = tolower(v); return v ~ /^(unifi[-_ ]?)?access( application)?$/ }
function iskeyname(k) { k = tolower(k); return k ~ /^(name|id|key|app|appname|app_name|displayname|display_name|packagename|package|title|slug)$/ }
function iskeyver(k) { k = tolower(k); return k ~ /^(version|currentversion|current_version|installedversion|installed_version|appversion|app_version)$/ }
function isverval(v) { return v ~ /^[vV]?[0-9]+\.[0-9]+\.[0-9]+/ }
function value(v,  k) {
  if (typ[d] != "o") return
  k = ckey[d]
  if (iskeyname(k) && isname(v)) nm[d] = 1
  if (iskeyver(k) && isverval(v)) ver[d] = v
  if (iskeyver(pk[d]) && tolower(k) ~ /^(current|installed|running|value)$/ && isverval(v)) ver[d] = v
}
function openc(t) { d++; typ[d] = t; nm[d] = 0; ver[d] = ""; ckey[d] = ""; expk[d] = (t == "o"); pk[d] = (d > 1 && typ[d-1] == "o") ? ckey[d-1] : (d > 1 ? pk[d-1] : "") }
function closec(  v) {
  if (d < 1) { bad = "unbalanced"; return }
  if (typ[d] == "o" && ver[d] != "" && (nm[d] || isname(pk[d]))) { v = ver[d]; sub(/^[vV]/, "", v); match(v, /^[0-9]+\.[0-9]+\.[0-9]+/); print "J\t" substr(v, 1, RLENGTH); found++ }
  if (typ[d] == "o" && ver[d] != "" && iskeyver(pk[d]) && d > 1 && ver[d-1] == "") ver[d-1] = ver[d]
  d--
}
{ buf = buf $0 "\n" }
END {
  d = 0; i = 1; L = length(buf); found = 0; bad = ""
  while (i <= L && found < 50) {
    c = substr(buf, i, 1)
    if (c == "\"") {
      j = i + 1; s = ""
      while (j <= L) { e = substr(buf, j, 1); if (e == "\\") { s = s substr(buf, j + 1, 1); j += 2; continue } if (e == "\"") break; s = s e; j++ }
      if (j > L) { bad = "unterminated string"; break }
      if (d > 0 && typ[d] == "o" && expk[d]) { ckey[d] = s; expk[d] = 0 } else if (d > 0) value(s)
      i = j + 1; continue
    }
    if (c == "{") openc("o")
    else if (c == "[") openc("a")
    else if (c == "}" || c == "]") closec()
    else if (c == ",") { if (d > 0 && typ[d] == "o") expk[d] = 1 }
    i++
  }
  if (bad == "" && d != 0) bad = "unbalanced"
  if (bad != "") print "W\t" bad
}'

isjson() { local c; c=$(head -c 4096 -- "$1" | tr -d ' \t\r\n' | head -c 1); [ "$c" = "{" ] || [ "$c" = "[" ]; }
readable() { [ -f "$1" ] && [ -r "$1" ] && head -c 1 -- "$1" > /dev/null 2>&1; }

echo "$VERSION_TAG (UniFi Access Application, Ubiquiti Security Advisory Bulletin 073)"
ANY_AFF=0; ANY_REV=0; SEEN_4323=0
k=0
for idx in "${!SRC_KIND[@]}"; do
  k=$((k+1)); kind=${SRC_KIND[$idx]}; val=${SRC_VAL[$idx]}
  vers=""; warn=""; nfound=0
  add() { # version location
    local v; v=$(norm "$1"); [ -n "$v" ] || return
    nfound=$((nfound+1))
    if [ "$nfound" -le "$MAX_FOUND" ]; then echo "FOUND $2 $v $(status "$v")"; fi
    case " $vers " in *" $v "*) ;; *) vers="$vers $v" ;; esac
    [ "$v" = 4.3.23 ] && SEEN_4323=1
    return 0
  }
  scan_text() { local f=$1 l v
    while IFS=$'\t' read -r l v; do add "$v" "$(clean "$f"):$l"; done < <(awk -- "$AWK_TEXT" < "$f" 2>/dev/null)
  }
  scan_json() { local f=$1 t v
    while IFS=$'\t' read -r t v; do
      if [ "$t" = J ]; then add "$v" "$(clean "$f"):json"; else warn="$warn; $(clean "$f"): JSON $v"; fi
    done < <(awk -- "$AWK_JSON" < "$f" 2>/dev/null)
  }
  case $kind in
    version)
      echo "SOURCE $k: version string"
      isver "$val" || die "unrecognised version string (use 4.3.22 or 4.3.9+12130)"
      add "$val" "version-string" ;;
    file|json)
      readable "$val" || die "cannot read file: $(clean "$val")"
      sz=$(wc -c < "$val"); [ "$sz" -le "$MAX_SIZE" ] || die "file over $MAX_SIZE bytes: $(clean "$val")"
      if [ "$kind" = json ] || isjson "$val"; then echo "SOURCE $k: file $(clean "$val") (JSON)"; scan_json "$val"
      else echo "SOURCE $k: file $(clean "$val") (text)"; scan_text "$val"; fi ;;
    dir)
      if ! { [ -d "$val" ] && [ -r "$val" ] && [ -x "$val" ]; }; then die "cannot read folder: $(clean "$val")"; fi
      echo "SOURCE $k: support-file folder $(clean "$val")"
      nf=0; skipped=0; unread=0
      while IFS= read -r -d '' f; do
        nf=$((nf+1)); if [ "$nf" -gt "$MAX_FILES" ]; then warn="$warn; over $MAX_FILES files, rest not read"; break; fi
        if ! readable "$f"; then unread=$((unread+1)); continue; fi
        sz=$(wc -c < "$f"); if [ "$sz" -gt "$MAX_SIZE" ]; then skipped=$((skipped+1)); continue; fi
        grep -Iq '' -- "$f" 2>/dev/null || continue
        case $f in *.json|*.JSON) scan_json "$f" ;; *) scan_text "$f" ;; esac
      done < <(find "$val" -maxdepth "$MAX_DEPTH" -type f -print0 2>/dev/null | sort -z)
      [ "$unread" = 0 ] || warn="$warn; $unread unreadable file(s)"
      [ "$skipped" = 0 ] || warn="$warn; $skipped file(s) over $MAX_SIZE bytes skipped"
      echo "SCAN: files listed $(( nf > MAX_FILES ? MAX_FILES : nf ))" ;;
  esac
  [ "$nfound" -le "$MAX_FOUND" ] || echo "NOTE: $((nfound - MAX_FOUND)) more mention(s) not listed"
  [ -z "$warn" ] || echo "WARN:${warn#;}"
  naff=0; nfix=0
  for v in $vers; do if [ "$(status "$v")" = AFFECTED ]; then naff=$((naff+1)); else nfix=$((nfix+1)); fi; done
  if [ -z "$vers" ]; then sv="UNKNOWN (no Access Application version found)"; ANY_REV=1
  elif [ "$naff" -gt 0 ] && [ "$nfix" -gt 0 ]; then sv="REVIEW (both affected and fixed versions found:$vers; check which one is installed)"; ANY_REV=1
  elif [ "$naff" -gt 0 ]; then sv="AFFECTED"; ANY_AFF=1
  elif [ -n "$warn" ]; then sv="REVIEW (fixed version found, but the scan was incomplete)"; ANY_REV=1
  else sv="FIXED"; fi
  echo "SOURCE $k VERDICT: $sv"
done

if [ "$ANY_AFF" = 1 ]; then cs=AFFECTED; elif [ "$ANY_REV" = 1 ]; then cs=REVIEW; else cs=FIXED; fi
while IFS='|' read -r cve score vec cwe acc imp; do
  echo "CVE $cve $cs [Ubiquiti CVSS 3.1 $score, $vec; $cwe] needs $acc; $imp"
done <<< "$DATA"
[ "$SEEN_4323" = 0 ] || echo "NOTE: 4.3.23 is not named in the bulletin (it lists $LAST_LISTED and earlier); the CVE records cover every version below $FIXED_VERSION, so it is treated as AFFECTED"
if [ "$cs" != FIXED ]; then echo "FIX: update UniFi Access Application to $FIXED_VERSION or later (Ubiquiti Bulletin 073), then work through the README manual review checklist"; fi
echo "NOTE: no exploitation reported by Ubiquiti or CISA as of 19 Nov 2026; not in CISA KEV (catalogue 2026.11.18). Patch now regardless."
if [ "$ANY_AFF" = 1 ]; then echo "OVERALL: AFFECTED (exit 2)"; exit 2; fi
if [ "$ANY_REV" = 1 ]; then echo "OVERALL: UNKNOWN OR REVIEW (exit 3)"; exit 3; fi
echo "OVERALL: FIXED (exit 0)"; exit 0
