#!/usr/bin/env bash
# check-puppet.sh: offline, read-only checker for Puppet report deserialization, CVE-2026-115731 (and the companion
# certname authorization bypass CVE-2026-115732, fixed by the same releases). Pack 1.0.0 (17 Nov 2026).
# It opens no sockets, writes no files and runs no other program except tr and wc. It reads only the files you name
# (and /opt/puppetlabs/puppet/VERSION when no version is given for core or openvox-agent). It never prints file
# content beyond version numbers, the autosign setting, autosign.conf glob entries and certnames. It does not read
# csr_attributes.yaml, eyaml keys, private keys or policy executables, and never prints fingerprints or extensions.
#
# Usage: check-puppet.sh --flavour pe|core|openvox-server|openvox-agent [--version V | --version-file FILE]
#          [--puppet-conf FILE] [--autosign-conf FILE] [--ca-list FILE] [--allowlist FILE]
#   (-Flavour, -Version, -VersionFile, -PuppetConf, -AutosignConf, -CaList and -Allowlist are accepted too)
#   --flavour         pe (Puppet Enterprise), core (Puppet Core / puppet-agent version), openvox-server, openvox-agent
#   --version V       the version string, for example 2025.12.0 or 8.22.1
#   --version-file F  a file whose first line is the version (for example /opt/puppetlabs/puppet/VERSION)
#   --puppet-conf F   the CA server's puppet.conf (only the autosign setting is read)
#   --autosign-conf F the file the autosign setting points to (default $confdir/autosign.conf)
#   --ca-list F       saved text output of: puppetserver ca list --all
#   --allowlist F     your expected certnames, one per line (# starts a comment)
#
# Exit codes:
#   0 OK       version at or above a fixed release, and no autosign or certificate findings
#   1          not used (reserved for unexpected runtime errors)
#   2 AFFECTED version inside a range published by Perforce or OpenVox
#   3 UNKNOWN  no version, or a version outside the published ranges, and no other findings
#   4 REVIEW   not shown as affected, but naive or basic autosign is on, or certificates are outside your allowlist
#   5 USAGE OR READ ERROR
set -u
export LC_ALL=C

# Perforce advisory and CVE record (CNA): PE 2023.8.0 before 2023.8.13, 2025.0.0 before 2025.12.1,
# 2026.0.0 before 2026.0.1; Puppet Core 8.x before 8.22.2 and 9.0.0 before 9.1.3.
PE_RANGES="2023.8.0:2023.8.13:2023.9.0 2025.0.0:2025.12.1:2026.0.0 2026.0.0:2026.0.1:99999.0.0"
CORE_RANGES="8.0.0:8.22.2:9.0.0 9.0.0:9.1.3:99999.0.0"
# OpenVox advisories GHSA-ffr6-rwpm-p5wq and GHSA-q4hm-33rc-572g: server fixed 8.18.0 and 9.2.0, agent 8.32.0 and 9.3.0.
OVS_RANGES="8.0.0:8.18.0:9.0.0 9.0.0:9.2.0:99999.0.0"
OVA_RANGES="8.0.0:8.32.0:9.0.0 9.0.0:9.3.0:99999.0.0"
DEFAULT_VERSION_FILE="/opt/puppetlabs/puppet/VERSION"
REPORT_PATH="/puppet/v3/report"
MAX_SMALL=1048576
MAX_LIST=8388608

usage() {
  echo 'Usage: check-puppet.sh --flavour pe|core|openvox-server|openvox-agent [--version V | --version-file FILE] [--puppet-conf FILE] [--autosign-conf FILE] [--ca-list FILE] [--allowlist FILE]'
  echo 'Offline and read-only. Exit codes: 0 OK, 2 AFFECTED, 3 UNKNOWN, 4 REVIEW, 5 USAGE OR READ ERROR (1 is not used).'
}
die() { echo "ERROR: $*"; exit 5; }
clean_path() { printf '%s' "$1" | tr -c '[:print:]' '?'; }
show() { if [[ "$1" =~ ^[A-Za-z0-9._*-]{1,253}$ ]]; then printf '%s' "$1"; else printf '(value withheld: unexpected characters)'; fi; }
trim() { local s=$1; s="${s#"${s%%[![:space:]]*}"}"; s="${s%"${s##*[![:space:]]}"}"; printf '%s' "$s"; }
ver_cmp() {
  local IFS=. i x y; local -a a b; read -ra a <<< "$1"; read -ra b <<< "$2"
  for i in 0 1 2; do x=$((10#${a[i]:-0})); y=$((10#${b[i]:-0})); if [ "$x" -lt "$y" ]; then echo -1; return; elif [ "$x" -gt "$y" ]; then echo 1; return; fi; done
  echo 0
}
VER_RE='^[0-9]{1,5}(\.[0-9]{1,4}){0,2}$'
# read_lines FILE MAX: fills LINES with the file's lines (NUL becomes space, trailing CR dropped).
read_lines() {
  local f=$1 max=$2 sz l
  { [ -f "$f" ] && [ -r "$f" ]; } || die "file not found or unreadable: $(clean_path "$f")"
  sz=$(wc -c < "$f" 2>/dev/null) || die "file unreadable: $(clean_path "$f")"
  [ "$sz" -le "$max" ] || die "file too large: $(clean_path "$f")"
  LINES=()
  while IFS= read -r l || [ -n "$l" ]; do LINES+=("${l%$'\r'}"); done < <(tr '\000' ' ' < "$f")
}

FLAVOUR=""; OPT_VER=""; VFILE=""; PCONF=""; ACONF=""; CALIST=""; ALLOW=""
need() { [ "$1" -ge 2 ] || die "$2 option needs a value"; }
while [ $# -gt 0 ]; do
  case $1 in
    --flavour|-Flavour) need $# flavour; FLAVOUR=$2; shift 2;;
    --version|-Version) need $# version
      [[ "$2" =~ $VER_RE ]] || die "version must be numbers and dots, for example 2025.12.1 or 8.22.2"
      OPT_VER=$2; shift 2;;
    --version-file|-VersionFile) need $# version-file; VFILE=$2; [ -n "$VFILE" ] || die "version-file option needs a value"; shift 2;;
    --puppet-conf|-PuppetConf) need $# puppet-conf; PCONF=$2; [ -n "$PCONF" ] || die "puppet-conf option needs a value"; shift 2;;
    --autosign-conf|-AutosignConf) need $# autosign-conf; ACONF=$2; [ -n "$ACONF" ] || die "autosign-conf option needs a value"; shift 2;;
    --ca-list|-CaList) need $# ca-list; CALIST=$2; [ -n "$CALIST" ] || die "ca-list option needs a value"; shift 2;;
    --allowlist|-Allowlist) need $# allowlist; ALLOW=$2; [ -n "$ALLOW" ] || die "allowlist option needs a value"; shift 2;;
    -h|--help|-Help) usage; exit 5;;
    *) die "unknown option: $(clean_path "$1")";;
  esac
done
case $FLAVOUR in
  pe) RANGES=$PE_RANGES; FNAME="Puppet Enterprise"; SRC="Perforce";;
  core) RANGES=$CORE_RANGES; FNAME="Puppet Core (puppet-agent)"; SRC="Perforce";;
  openvox-server) RANGES=$OVS_RANGES; FNAME="OpenVox Server"; SRC="OpenVox";;
  openvox-agent) RANGES=$OVA_RANGES; FNAME="OpenVox Agent"; SRC="OpenVox";;
  "") usage; exit 5;;
  *) die "flavour must be pe, core, openvox-server or openvox-agent";;
esac
[ -n "$OPT_VER" ] && [ -n "$VFILE" ] && die "give --version or --version-file, not both"

echo "PRODUCT: $FNAME"
VER=""; VSRC=""
if [ -n "$OPT_VER" ]; then VER=$OPT_VER; VSRC="--version"
else
  if [ -z "$VFILE" ] && { [ "$FLAVOUR" = core ] || [ "$FLAVOUR" = openvox-agent ]; } && [ -f "$DEFAULT_VERSION_FILE" ]; then VFILE=$DEFAULT_VERSION_FILE; fi
  if [ -n "$VFILE" ]; then
    read_lines "$VFILE" "$MAX_SMALL"
    raw=$(trim "${LINES[0]:-}")
    if [[ "$raw" =~ $VER_RE ]]; then VER=$raw; VSRC=$(clean_path "$VFILE")
    else echo "NOTE: the version file's first line is not a plain version number (value withheld)."; fi
  fi
fi
if [ -n "$VER" ]; then echo "VERSION: $VER (from $VSRC)"; else echo "VERSION: not found"; fi

VSTATE=unknown; FIXREL=""
if [ -n "$VER" ]; then
  for r in $RANGES; do
    IFS=: read -r lo fx hi <<< "$r"
    if [ "$(ver_cmp "$VER" "$lo")" -ge 0 ] && [ "$(ver_cmp "$VER" "$hi")" -lt 0 ]; then
      FIXREL=$fx
      if [ "$(ver_cmp "$VER" "$fx")" -lt 0 ]; then VSTATE=affected; else VSTATE=fixed; fi
    fi
  done
  [ "$VSTATE" = unknown ] && VSTATE=outside
fi
case $VSTATE in
  affected) echo "RANGE: affected ($SRC: fixed in $FIXREL for this release line)";;
  fixed) echo "RANGE: at or above the fixed release $FIXREL for this release line ($SRC)"
    echo "NOTE: restart the Puppet or OpenVox server after upgrading so the fixed code is loaded (Perforce, OpenVox).";;
  outside) echo "RANGE: outside the ranges $SRC publishes; not verified either way"
    [ "$FLAVOUR" = pe ] && echo "NOTE: the CVE record marks unlisted Puppet Enterprise versions as affected by default; move to 2023.8.13, 2025.12.1 or 2026.0.1."
    [ "$FLAVOUR" = core ] && echo "NOTE: OpenVox states all known Puppet implementations are vulnerable and open source Puppet gets no more updates (UNVERIFIED by Perforce).";;
  *) echo "RANGE: unknown (no version)";;
esac

FIND=0
# puppet.conf: autosign in [server], then [master], then [main] (OUR READING of the documented section order).
AS_SERVER=""; AS_MASTER=""; AS_MAIN=""; AUTOSIGN=""; AS_SET=0
if [ -n "$PCONF" ]; then
  read_lines "$PCONF" "$MAX_SMALL"
  sec=main
  for l in "${LINES[@]}"; do
    if [[ "$l" =~ ^\[([A-Za-z0-9_]+)\] ]]; then sec=${BASH_REMATCH[1]}; continue; fi
    t=$(trim "$l")
    if [[ "$t" =~ ^autosign[[:space:]]*=(.*)$ ]]; then
      v=$(trim "${BASH_REMATCH[1]}")
      case $sec in server) AS_SERVER="=$v";; master) AS_MASTER="=$v";; main) AS_MAIN="=$v";; esac
    fi
  done
  if [ -n "$AS_SERVER" ]; then AUTOSIGN=${AS_SERVER#=}; AS_SET=1
  elif [ -n "$AS_MASTER" ]; then AUTOSIGN=${AS_MASTER#=}; AS_SET=1
  elif [ -n "$AS_MAIN" ]; then AUTOSIGN=${AS_MAIN#=}; AS_SET=1; fi
fi
lc=$(printf '%s' "$AUTOSIGN" | tr '[:upper:]' '[:lower:]')
if [ -z "$PCONF" ] && [ -z "$ACONF" ]; then echo "AUTOSIGN: not checked (no --puppet-conf or --autosign-conf)"
elif [ "$AS_SET" = 1 ] && [ "$lc" = false ]; then echo "AUTOSIGN: disabled (autosign = false)"
elif [ "$AS_SET" = 1 ] && [ "$lc" = true ]; then FIND=1
  echo "AUTOSIGN: NAIVE (autosign = true): every certificate request is signed, so anyone who can reach the CA can get a certificate"
else
  if [ "$AS_SET" = 1 ]; then echo "AUTOSIGN: setting points to a file: $(clean_path "$AUTOSIGN")"
  elif [ -n "$PCONF" ]; then echo "AUTOSIGN: setting not found in puppet.conf (default is \$confdir/autosign.conf)"; fi
  if [ -z "$ACONF" ]; then echo "AUTOSIGN: file not checked (pass --autosign-conf)"
  elif [ ! -e "$ACONF" ]; then echo "AUTOSIGN: autosign.conf not found (an absent file is an empty allowlist)"
  elif [ -f "$ACONF" ] && [ -x "$ACONF" ]; then
    echo "AUTOSIGN: POLICY EXECUTABLE (contents not read); safe only if it verifies a per-node pre-shared secret"
  else
    read_lines "$ACONF" "$MAX_SMALL"
    n=0; g=0; GL=()
    for l in "${LINES[@]}"; do
      t=$(trim "$l"); [ -n "$t" ] || continue; [[ "$t" == '#'* ]] && continue
      n=$((n + 1)); [[ "$t" == *'*'* ]] && { g=$((g + 1)); GL+=("$t"); }
    done
    if [ "$n" = 0 ]; then echo "AUTOSIGN: autosign.conf is empty (no requests autosigned)"
    elif [ "$g" -gt 0 ]; then FIND=1
      echo "AUTOSIGN: BASIC WITH GLOBS ($n entries, $g globs): any host can ask for a matching certname"
      for t in "${GL[@]}"; do echo "AUTOSIGN GLOB: $(show "$t")"; done
    else FIND=1
      echo "AUTOSIGN: BASIC ($n exact certnames): any host can ask for a listed certname"
    fi
  fi
fi

# puppetserver ca list --all: certname is the first field of each indented line under a section heading.
if [ -n "$CALIST" ]; then
  read_lines "$CALIST" "$MAX_LIST"
  SIGNED=(); REQ=(); sec=""
  for l in "${LINES[@]}"; do
    case $l in
      'Requested Certificates:'*) sec=req; continue;;
      'Signed Certificates:'*) sec=signed; continue;;
      'Revoked Certificates:'*|'Missing Certificates:'*) sec=other; continue;;
    esac
    if [[ "$l" =~ ^[[:space:]]+([^[:space:]]+) ]]; then
      case $sec in signed) SIGNED+=("${BASH_REMATCH[1]}");; req) REQ+=("${BASH_REMATCH[1]}");; esac
    fi
  done
  echo "CERTS: ${#SIGNED[@]} signed, ${#REQ[@]} requested (pending)"
  for c in "${REQ[@]}"; do echo "PENDING REQUEST: $(show "$c")"; done
  if [ -n "$ALLOW" ]; then
    read_lines "$ALLOW" "$MAX_SMALL"
    declare -A OK=(); AL=()
    for l in "${LINES[@]}"; do t=$(trim "$l"); [ -n "$t" ] || continue; [[ "$t" == '#'* ]] && continue; OK["$t"]=1; AL+=("$t"); done
    echo "ALLOWLIST: ${#AL[@]} certnames"
    out=0
    for c in "${SIGNED[@]}" "${REQ[@]}"; do
      [ -n "${OK["$c"]:-}" ] && continue
      out=$((out + 1)); FIND=1; echo "NOT IN ALLOWLIST: $(show "$c")"
      for a in "${AL[@]}"; do
        if [[ "$c" == *".$a" ]] || [[ "$a" == *".$c" ]]; then echo "NAME COLLISION: $(show "$c") extends or shortens allowlisted $(show "$a") (the CVE-2026-115732 pattern)"; fi
      done
    done
    [ "$out" = 0 ] && echo "ALLOWLIST: every signed and requested certificate is listed"
  else echo "ALLOWLIST: not checked (pass --allowlist)"; fi
elif [ -n "$ALLOW" ]; then echo "ALLOWLIST: not checked (pass --ca-list as well)"; fi

case $VSTATE in
  affected) rc=2;;
  *) if [ "$FIND" = 1 ]; then rc=4; elif [ "$VSTATE" = fixed ]; then rc=0; else rc=3; fi;;
esac
case $rc in
  0) msg="OK: fixed release and no autosign or certificate findings";;
  2) msg="AFFECTED: upgrade now (Puppet Enterprise 2023.8.13, 2025.12.1 or 2026.0.1; Puppet Core 8.22.2 or 9.1.3; OpenVox Server 8.18.0 or 9.2.0) and restart the server; until then restrict port 8140 and turn off naive or basic autosign";;
  4) msg="REVIEW: tighten autosign (policy executable with a pre-shared secret, or manual signing) and review certificates outside your allowlist; reports reach $REPORT_PATH with any signed certificate";;
  *) msg="UNKNOWN: version not established or not in a published range; confirm it from the package manager or console";;
esac
echo "RESULT: $msg (exit $rc)"
exit "$rc"
