#!/usr/bin/env bash
# check-zyxel-cpe-ont.sh, pack v1.0.0 (17 Nov 2026): CVE-2026-79614 and CVE-2026-86676 in Zyxel DSL/Ethernet CPE, fibre ONTs and
# wireless extenders.
# STRICTLY OFFLINE AND READ-ONLY. It compares a model and firmware string you supply (arguments or a CSV inventory) with the
# model tables in Zyxel's advisory of 17 Nov 2026, transcribed in data/zyxel-2026-11-17-models.csv. It never contacts a device,
# opens no network connection, writes no files and runs nothing it reads. It prints only the model, the parsed firmware string
# and an optional sanitised name; every other CSV column (for example passwords or serial numbers) is ignored and never printed.
# Exit codes: 0 every device FIXED; 1 any AFFECTED; 3 any UNKNOWN (ISP-supplied, unreadable, a build not in Zyxel's table, or no
# devices), none AFFECTED; 5 only FIXED and NOT LISTED devices (review); 4 usage, input or data file error.
set -u
export LC_ALL=C
DATA="$(cd "$(dirname "$0")/.." && pwd)/data/zyxel-2026-11-17-models.csv"

banner() {
  echo "check-zyxel-cpe-ont v1.0.0: offline, read-only firmware check against Zyxel's advisory of 17 Nov 2026 (CVE-2026-79614, CVE-2026-86676). No network, no device contact, no writes."
  echo "CVE-2026-79614 (Zyxel as CNA): out-of-bounds write in libclinkc.so; an unauthenticated attacker could elevate privileges and potentially execute arbitrary commands with a crafted HTTP request. Zyxel as CNA scores it CVSS 3.1 9.8, Critical (shown on NVD). CWE-787."
  echo "CVE-2026-86676 (Zyxel as CNA): post-authentication command injection in the Description parameter of a CGI program; needs administrator privileges. Zyxel as CNA scores it CVSS 3.1 7.2, High (shown on NVD). CWE-78."
  echo "Zyxel: WAN access is disabled by default on these devices. CISA KEV (catalog 2026.11.13, checked 17 Nov 2026): neither CVE is listed."
}
usage() {
  cat <<'U'
Usage:
  check-zyxel-cpe-ont.sh --model <MODEL> --firmware <FIRMWARE> [--isp] [--name <NAME>]
  check-zyxel-cpe-ont.sh --inventory <FILE.csv>
    CSV header must name the columns model and firmware; optional columns name and supplied_by (value isp marks an
    ISP-supplied unit). Other columns are ignored and never printed. Fields must not contain commas.
  Options may also be written -Model, -Firmware, -Isp, -Name, -Inventory.
Exit codes: 0 every device FIXED; 1 any AFFECTED; 3 any UNKNOWN, none AFFECTED; 5 only FIXED and NOT LISTED (review);
  4 usage, input or data file error.
U
}
die() { echo "ERROR: $1"; usage; exit 4; }
upper() { printf '%s' "$1" | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; }
lower() { printf '%s' "$1" | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'; }
nospace() { printf '%s' "$1" | tr -d ' \t\n\v\f\r'; }
trimq() { local s=$1; s=${s#"${s%%[! $'\t']*}"}; s=${s%"${s##*[! $'\t']}"}; s=${s#\"}; s=${s%\"}; printf '%s' "$s"; }

# Model data.
declare -A AFF PAT SCOPE
n79=0; n86=0
[ -r "$DATA" ] || { banner; die "model data file missing: data/zyxel-2026-11-17-models.csv"; }
while IFS= read -r l || [ -n "$l" ]; do
  case $l in ''|'#'*|cve,*) continue;; esac
  IFS=',' read -r c _ m a p _ x <<< "$l"
  [ -z "${x-}" ] || { banner; die "model data file damaged: data/zyxel-2026-11-17-models.csv"; }
  case $c in
    CVE-2026-79614) n79=$((n79+1)); [ "${a% and earlier}" != "$a" ] || { banner; die "model data file damaged: data/zyxel-2026-11-17-models.csv"; }; SCOPE["$c|$m"]=earlier;;
    CVE-2026-86676) n86=$((n86+1)); SCOPE["$c|$m"]=listed;;
    *) banner; die "model data file damaged: data/zyxel-2026-11-17-models.csv";;
  esac
  AFF["$c|$m"]=$a; PAT["$c|$m"]=$p
done < "$DATA"
if [ "$n79" -ne 48 ] || [ "$n86" -ne 30 ]; then banner; die "model data file damaged: data/zyxel-2026-11-17-models.csv (expected 48 and 30 rows)"; fi

# fwparse STRING -> "MAJ MIN CODE BUILD C" (BUILD dot separated), or nothing if not a Zyxel firmware string.
fwparse() {
  local s; s=$(upper "$(nospace "$1")"); s=${s#V}
  if [[ $s =~ ^([0-9]{1,3})\.([0-9]{1,3})\(([A-Z]{4})\.([0-9]{1,4}(\.[0-9]{1,4}){0,4})\)C([0-9]{1,3})$ ]]; then
    echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]} ${BASH_REMATCH[4]} ${BASH_REMATCH[6]}"
  fi
}
# fwcmp "A" "B" (fwparse output, same line) -> -1, 0 or 1
fwcmp() {
  local -a a b x y; read -r -a a <<< "$1"; read -r -a b <<< "$2"
  IFS=. read -r -a x <<< "${a[3]}"; IFS=. read -r -a y <<< "${b[3]}"
  local i n=${#x[@]} u v; [ ${#y[@]} -gt "$n" ] && n=${#y[@]}
  for ((i=0; i<n; i++)); do
    u=$((10#${x[i]:-0})); v=$((10#${y[i]:-0}))
    if [ "$u" -lt "$v" ]; then echo -1; return; elif [ "$u" -gt "$v" ]; then echo 1; return; fi
  done
  u=$((10#${a[4]})); v=$((10#${b[4]}))
  if [ "$u" -lt "$v" ]; then echo -1; elif [ "$u" -gt "$v" ]; then echo 1; else echo 0; fi
}
sameline() { local -a a b; read -r -a a <<< "$1"; read -r -a b <<< "$2"; [ $((10#${a[0]})) -eq $((10#${b[0]})) ] && [ $((10#${a[1]})) -eq $((10#${b[1]})) ] && [ "${a[2]}" = "${b[2]}" ]; }
fline() { local -a a; read -r -a a <<< "$1"; printf '%s.%s(%s)' "${a[0]}" "${a[1]}" "${a[2]}"; }
canon() { local -a a; read -r -a a <<< "$1"; printf '%s.%s(%s.%s)C%s' "${a[0]}" "${a[1]}" "${a[2]}" "${a[3]}" "${a[4]}"; }

na=0; nf=0; nu=0; nn=0; nd=0
ZYX_GET="Zyxel: contact your Zyxel sales representative or support team to obtain the file."
ISP_TXT="Zyxel's tables do not include customized models specifically designed for ISP customers, and Zyxel advises end-users who acquired the device from an ISP to contact the ISP's support team. Ask the ISP whether this unit runs fixed firmware."
check() { # who model firmware isp(0|1)
  local who=$1 m fw="" mm="(unreadable model)" f v c st txt parts="" worst=FIXED fix=""
  nd=$((nd+1))
  m=$(upper "$(nospace "$2")"); m=${m#ZYXEL}
  [[ $m =~ ^[A-Z0-9][A-Z0-9-]{0,31}$ ]] && mm=$m || m=""
  f=$(fwparse "$3"); [ -n "$f" ] && fw=$(canon "$f")
  local shown="$mm ${fw:-(unreadable firmware)}"
  local inT=""; [ -n "$m" ] && { [ -n "${PAT["CVE-2026-79614|$m"]+x}" ] || [ -n "${PAT["CVE-2026-86676|$m"]+x}" ]; } && inT=1
  if [ "$4" = 1 ]; then
    nu=$((nu+1)); txt=""
    if [ -n "$inT" ]; then txt=" The same model name is in Zyxel's table (patch ${PAT["CVE-2026-79614|$m"]:-${PAT["CVE-2026-86676|$m"]}})."; fi
    echo "UNKNOWN: $who $shown: supplied by an ISP. $ISP_TXT$txt"; return
  fi
  if [ -z "$m" ]; then nu=$((nu+1)); echo "UNKNOWN: $who $shown: no readable model name; expected a Zyxel model such as DX3301-T0."; return; fi
  if [ -z "$inT" ]; then nn=$((nn+1)); echo "NOT LISTED: $who $shown: not in Zyxel's tables for CVE-2026-79614 or CVE-2026-86676. Zyxel: any product currently on the market that is not listed in the tables is not affected. The tables exclude ISP-customised models and list only products still within their vulnerability support period, so confirm this is a standard retail unit in support."; return; fi
  if [ -z "$fw" ]; then nu=$((nu+1)); echo "UNKNOWN: $who $shown: no readable firmware version; expected a Zyxel firmware string such as ${PAT["CVE-2026-79614|$m"]:-${PAT["CVE-2026-86676|$m"]}}."; return; fi
  for c in CVE-2026-79614 CVE-2026-86676; do
    [ -n "${PAT["$c|$m"]+x}" ] || continue
    local av=${AFF["$c|$m"]} pv=${PAT["$c|$m"]} pa pp
    pa=$(fwparse "${av% and earlier}"); pp=$(fwparse "$pv")
    if ! sameline "$f" "$pp"; then st=UNKNOWN; txt="$c unknown: firmware line $(fline "$f") does not match Zyxel's line for $m (patch $pv); it may be ISP or other firmware"
    elif [ "$(fwcmp "$f" "$pp")" != -1 ]; then st=FIXED; txt="$c fixed: at or after the patch $pv"
    else
      v=$(fwcmp "$f" "$pa")
      if [ "$v" = 0 ] || { [ "$v" = -1 ] && [ "${SCOPE["$c|$m"]}" = earlier ]; }; then st=AFFECTED; txt="$c affected: Zyxel lists $av for $m"; fix=$pv
      elif [ "$v" = -1 ]; then st=UNKNOWN; txt="$c unknown: earlier than the one build Zyxel's Table 2 lists for $m ($av); Zyxel does not say whether earlier builds are affected"
      else st=UNKNOWN; txt="$c unknown: after the affected build ($av) but before the patch ($pv); this build is not in Zyxel's table"; fi
    fi
    parts="${parts:+$parts; }$txt"
    case $st in AFFECTED) worst=AFFECTED;; UNKNOWN) [ "$worst" = AFFECTED ] || worst=UNKNOWN;; esac
  done
  case $worst in
    AFFECTED) na=$((na+1)); echo "AFFECTED: $who $shown: $parts. Fix: install $fix or later. $ZYX_GET";;
    UNKNOWN) nu=$((nu+1)); echo "UNKNOWN: $who $shown: $parts.";;
    *) nf=$((nf+1)); echo "FIXED: $who $shown: $parts.";;
  esac
}
name_ok() { [[ $1 =~ ^[A-Za-z0-9._-]{1,40}$ ]]; }

model=""; fwa=""; isp=0; name=""; inv=(); have_m=0; have_f=0
[ $# -gt 0 ] || { usage; exit 4; }
while [ $# -gt 0 ]; do
  o=$(lower "$1")
  case $o in
    --model|-model) [ $# -ge 2 ] || { banner; die "--model needs a value"; }; model=$2; have_m=1; shift 2;;
    --firmware|-firmware) [ $# -ge 2 ] || { banner; die "--firmware needs a value"; }; fwa=$2; have_f=1; shift 2;;
    --isp|-isp) isp=1; shift;;
    --name|-name) [ $# -ge 2 ] || { banner; die "--name needs a value"; }; name=$2; shift 2;;
    --inventory|-inventory) [ $# -ge 2 ] || { banner; die "--inventory needs a file"; }; inv+=("$2"); shift 2;;
    --help|-help|-h) usage; exit 0;;
    *) banner; die "unknown option (options are --model, --firmware, --isp, --name, --inventory)";;
  esac
done
banner
[ "$have_m" = "$have_f" ] || die "--model and --firmware go together"
[ "$have_m" = 1 ] || [ ${#inv[@]} -gt 0 ] || die "give --model and --firmware, or --inventory"
[ "$have_m" = 1 ] || [ "$isp" = 0 ] || die "--isp goes with --model and --firmware"
for f in "${inv[@]}"; do if [ ! -f "$f" ] || [ ! -r "$f" ]; then die "cannot read inventory file"; fi; done
if [ "$have_m" = 1 ]; then w="input"; [ -n "$name" ] && name_ok "$name" && w="input ($name)"; check "$w" "$model" "$fwa" "$isp"; fi
for f in "${inv[@]}"; do
  hdr=""; row=0; im=-1; ifw=-1; ina=-1; isu=-1; first=1
  while IFS= read -r l || [ -n "$l" ]; do
    if [ "$first" = 1 ]; then l=${l#$'\xef\xbb\xbf'}; first=0; fi
    l=${l%$'\r'}
    case $(trimq "$l") in ''|'#'*) continue;; esac
    IFS=',' read -r -a F <<< "$l"
    if [ -z "$hdr" ]; then
      hdr=1
      for i in "${!F[@]}"; do case $(lower "$(trimq "${F[i]}")") in model) im=$i;; firmware) ifw=$i;; name) ina=$i;; supplied_by) isu=$i;; esac; done
      if [ "$im" -lt 0 ] || [ "$ifw" -lt 0 ]; then die "inventory header must name the model and firmware columns"; fi
      continue
    fi
    row=$((row+1)); w="row $row"
    if [ "$ina" -ge 0 ]; then nm=$(trimq "${F[ina]-}"); name_ok "$nm" && w="row $row ($nm)"; fi
    s=0; if [ "$isu" -ge 0 ] && [ "$(lower "$(trimq "${F[isu]-}")")" = isp ]; then s=1; fi
    check "$w" "$(trimq "${F[im]-}")" "$(trimq "${F[ifw]-}")" "$s"
  done < "$f"
  [ -n "$hdr" ] || die "inventory file has no header"
done
if [ "$nd" -eq 0 ]; then echo "UNKNOWN: no devices read."; fi
sumtxt="devices read: $nd; $na affected, $nf fixed, $nu unknown, $nn not listed"
if [ "$na" -gt 0 ]; then echo "RESULT: AFFECTED ($sumtxt)"; exit 1
elif [ "$nu" -gt 0 ] || [ "$nd" -eq 0 ]; then echo "RESULT: UNKNOWN ($sumtxt)"; exit 3
elif [ "$nn" -gt 0 ]; then echo "RESULT: REVIEW ($sumtxt)"; exit 5
else echo "RESULT: FIXED ($sumtxt)"; exit 0; fi
