#!/bin/bash
set -euo pipefail

# Variant-stage bounded search for CVE-2026-58126.
# Exit 0 = distinct variant/bypass reproduced on a fixed/latest target.
# Exit 1 = no distinct variant/bypass reproduced; checks completed and logs written.

ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs/vuln_variant"
VV="$ROOT/vuln_variant"
mkdir -p "$LOGS" "$VV"
cd "$ROOT"

MAIN_LOG="$LOGS/reproduction_steps.log"
: > "$MAIN_LOG"
exec > >(tee -a "$MAIN_LOG") 2>&1

VARIANT_CONFIRMED=false
VULN_SURFACE_CONFIRMED=false
SERVICE_STATIC_CANDIDATE=false
SERVICE_RUNTIME_CONFIRMED=false
LATEST_CHECK_DONE=false
FIXED_AVAILABLE=false

json_bool() { if [ "$1" = true ]; then printf true; else printf false; fi; }
sha256_file() { python3 - "$1" <<'PY'
import hashlib, sys
p=sys.argv[1]
h=hashlib.sha256()
with open(p,'rb') as f:
    for b in iter(lambda:f.read(1024*1024), b''):
        h.update(b)
print(h.hexdigest())
PY
}

write_runtime_manifest() {
  python3 - "$ROOT" "$VARIANT_CONFIRMED" "$VULN_SURFACE_CONFIRMED" "$SERVICE_STATIC_CANDIDATE" "$SERVICE_RUNTIME_CONFIRMED" "$LATEST_CHECK_DONE" "$FIXED_AVAILABLE" <<'PY'
import json, os, sys, time
root=sys.argv[1]
manifest={
  "entrypoint_kind":"api_remote",
  "entrypoint_detail":"Variant search for PACS Scan Image Exchange .NET Remoting endpoint: parent tcp://127.0.0.1:22222/PGImageExchange plus service-hosted startup candidate",
  "service_started":sys.argv[4].lower()=="true",
  "healthcheck_passed":sys.argv[5].lower()=="true",
  "target_path_reached":sys.argv[3].lower()=="true",
  "variant_confirmed":sys.argv[2].lower()=="true",
  "fixed_or_latest_checked":sys.argv[6].lower()=="true",
  "fixed_available":sys.argv[7].lower()=="true",
  "runtime_stack":["PACS Scan 5.2.1 vendor binaries when present","monodis static IL scan","Wine/.NET service OnStart harness best effort","latest/fixed package URL probes"],
  "proof_artifacts":[
    "logs/vuln_variant/reproduction_steps.log",
    "logs/vuln_variant/vulnerable_static_scan.log",
    "logs/vuln_variant/service_candidate_scan.log",
    "logs/vuln_variant/service_onstart_script.log",
    "logs/vuln_variant/fixed_latest_check.log",
    "logs/vuln_variant/latest_version.txt"
  ],
  "notes":"Negative variant result: service-hosted path is a patch-coverage concern but not a distinct confirmed bypass; no public fixed build was identified."
}
out=os.path.join(root,"vuln_variant","runtime_manifest.json")
os.makedirs(os.path.dirname(out), exist_ok=True)
with open(out,"w") as f: json.dump(manifest,f,indent=2)
PY
}
trap 'write_runtime_manifest' EXIT

PRODUCT_DIR="$ROOT/artifacts/vendor_product/msi_extract/Program Files/Pacsgear/Pacsgear Image Exchange Service"
EXCH_EXE="$PRODUCT_DIR/PGImageExchQueue.exe"
SVC_EXE="$PRODUCT_DIR/PGImageExchangeQueueSvc.exe"

wait_for_port() {
  local port="$1" tries="${2:-15}"
  for _ in $(seq 1 "$tries"); do
    if python3 - "$port" <<'PY' >/dev/null 2>&1
import socket, sys
s=socket.create_connection(('127.0.0.1', int(sys.argv[1])), timeout=0.5)
s.close()
PY
    then return 0; fi
    sleep 1
  done
  return 1
}

compile_service_harness() {
  local outdir="$VV/service_harness"
  mkdir -p "$outdir"
  cat > "$outdir/ServiceOnStartHarness.cs" <<'CS'
using System;
using System.IO;
using System.Reflection;
using System.Threading;
class ServiceOnStartHarness {
  static int Main(string[] args) {
    if (args.Length < 2) { Console.Error.WriteLine("usage: ServiceOnStartHarness <service_exe> <seconds>"); return 2; }
    string exe=Path.GetFullPath(args[0]); int seconds=int.Parse(args[1]);
    Directory.SetCurrentDirectory(Path.GetDirectoryName(exe));
    AppDomain.CurrentDomain.AssemblyResolve += (s,e) => {
      string p = Path.Combine(Path.GetDirectoryName(exe), new AssemblyName(e.Name).Name + ".dll");
      if (File.Exists(p)) return Assembly.LoadFrom(p);
      return null;
    };
    var asm=Assembly.LoadFrom(exe);
    var t=asm.GetType("PGImageExchangeQueueSvc.Service1", true);
    var svc=Activator.CreateInstance(t);
    var m=t.GetMethod("OnStart", BindingFlags.Instance|BindingFlags.NonPublic);
    Console.WriteLine("Invoking " + t.FullName + ".OnStart from " + exe);
    m.Invoke(svc, new object[]{new string[0]});
    Console.WriteLine("OnStart returned; harness alive for " + seconds + " seconds");
    Thread.Sleep(seconds*1000);
    return 0;
  }
}
CS
  if command -v mcs >/dev/null 2>&1; then
    mcs "$outdir/ServiceOnStartHarness.cs" -out:"$outdir/ServiceOnStartHarness.exe"
    echo "$outdir/ServiceOnStartHarness.exe"
  else
    echo "mcs not available" >&2
    return 1
  fi
}

run_vulnerable_checks() {
  echo "================================================================"
  echo "[1/2] Vulnerable target checks: PACS Scan 5.2.1"
  echo "================================================================"
  : > "$LOGS/vulnerable_static_scan.log"
  : > "$LOGS/service_candidate_scan.log"

  if [ ! -f "$EXCH_EXE" ] || [ ! -f "$SVC_EXE" ]; then
    echo "[-] Expected parent reproduction product binaries are not present at: $PRODUCT_DIR"
    echo "    Run bundle/repro/reproduction_steps.sh first, or provide the vendor package under bundle/artifacts/vendor_product." | tee -a "$LOGS/vulnerable_static_scan.log"
    return 0
  fi

  echo "Product directory: $PRODUCT_DIR" | tee -a "$LOGS/vulnerable_static_scan.log"
  echo "PGImageExchQueue.exe sha256=$(sha256_file "$EXCH_EXE")" | tee -a "$LOGS/vulnerable_static_scan.log"
  echo "PGImageExchangeQueueSvc.exe sha256=$(sha256_file "$SVC_EXE")" | tee -a "$LOGS/vulnerable_static_scan.log"

  if command -v monodis >/dev/null 2>&1; then
    monodis "$EXCH_EXE" > "$VV/PGImageExchQueue.variant.il" 2>>"$LOGS/vulnerable_static_scan.log" || true
    monodis "$SVC_EXE" > "$VV/PGImageExchangeQueueSvc.variant.il" 2>>"$LOGS/service_candidate_scan.log" || true

    echo "-- Remoting registration anchors in PGImageExchQueue.exe --" | tee -a "$LOGS/vulnerable_static_scan.log"
    grep -n -E "TcpChannel|RegisterChannel|RegisterWellKnownServiceType|PGImageExchange|RemotingPort" "$VV/PGImageExchQueue.variant.il" | head -80 | tee -a "$LOGS/vulnerable_static_scan.log" || true
    if grep -q "RegisterWellKnownServiceType" "$VV/PGImageExchQueue.variant.il" && grep -q "PGImageExchange" "$VV/PGImageExchQueue.variant.il"; then
      VULN_SURFACE_CONFIRMED=true
      echo "[+] Parent vulnerable remoting surface statically confirmed." | tee -a "$LOGS/vulnerable_static_scan.log"
    fi

    echo "-- Service-hosted candidate anchors in PGImageExchangeQueueSvc.exe --" | tee -a "$LOGS/service_candidate_scan.log"
    grep -n -E "OnStart|Start|ExchangeForm|ServiceBase|ServiceName|PGImageExchange" "$VV/PGImageExchangeQueueSvc.variant.il" | head -120 | tee -a "$LOGS/service_candidate_scan.log" || true
    if grep -q "PGImageExchQueue.ExchangeForm" "$VV/PGImageExchangeQueueSvc.variant.il"; then
      SERVICE_STATIC_CANDIDATE=true
      echo "[+] Service-hosted startup candidate statically confirmed: service creates PGImageExchQueue.ExchangeForm." | tee -a "$LOGS/service_candidate_scan.log"
    fi
  else
    echo "monodis not available; static IL scan skipped" | tee -a "$LOGS/vulnerable_static_scan.log"
  fi

  echo "-- Best-effort service OnStart runtime probe (candidate only) --" | tee "$LOGS/service_onstart_script.log"
  if [ "$SERVICE_STATIC_CANDIDATE" = true ] && command -v wine >/dev/null 2>&1 && command -v xvfb-run >/dev/null 2>&1; then
    local harness
    if harness=$(compile_service_harness); then
      local work="$VV/service_harness/product"
      rm -rf "$work"; mkdir -p "$work"
      cp -a "$PRODUCT_DIR"/. "$work"/
      export WINEDEBUG=-all
      if [ -d "$ROOT/artifacts/vendor_product/wineprefix_dotnet40" ]; then
        export WINEPREFIX="$ROOT/artifacts/vendor_product/wineprefix_dotnet40"
        export WINEDLLOVERRIDES="mscoree,mshtml="
      fi
      (cd "$work" && timeout 35s xvfb-run -a wine "$harness" "$work/PGImageExchangeQueueSvc.exe" 25) >> "$LOGS/service_onstart_script.log" 2>&1 &
      local pid=$!
      if wait_for_port 22222 18; then
        SERVICE_RUNTIME_CONFIRMED=true
        echo "[+] Service-hosted candidate listened on TCP/22222." | tee -a "$LOGS/service_onstart_script.log"
      else
        echo "[-] Service-hosted candidate did not listen on TCP/22222 in this Wine harness; not claiming a runtime variant." | tee -a "$LOGS/service_onstart_script.log"
      fi
      kill "$pid" 2>/dev/null || true
      wait "$pid" 2>/dev/null || true
    fi
  else
    echo "Runtime service harness skipped because Wine/xvfb or static candidate is unavailable." | tee -a "$LOGS/service_onstart_script.log"
  fi
}

run_fixed_latest_checks() {
  echo "================================================================"
  echo "[2/2] Fixed/latest target checks"
  echo "================================================================"
  : > "$LOGS/fixed_latest_check.log"
  : > "$LOGS/latest_version.txt"
  echo "No public CVE-specific fixed PACS Scan build was identified; probing known newer package URLs." | tee -a "$LOGS/fixed_latest_check.log" "$LOGS/latest_version.txt"

  local urls=(
    "https://download.pacsgear.com/download/PacsSCAN5.2.2.zip"
    "https://download.pacsgear.com/download/PacsSCAN5.3.zip"
    "https://download.pacsgear.com/download/PacsSCAN5.3.1.zip"
    "https://download.pacsgear.com/download/PacsSCAN5.3.3.zip"
  )
  for u in "${urls[@]}"; do
    echo "--- HEAD $u" | tee -a "$LOGS/fixed_latest_check.log"
    if command -v curl >/dev/null 2>&1; then
      curl -I -L --connect-timeout 8 --max-time 20 -A 'Pruva variant check' "$u" 2>&1 \
        | awk 'BEGIN{IGNORECASE=1}/HTTP\//||/content-length:/||/content-type:/||/location:/' \
        | tee -a "$LOGS/fixed_latest_check.log" || true
    else
      echo "curl unavailable" | tee -a "$LOGS/fixed_latest_check.log"
    fi
  done

  # If prior exploration already downloaded newer packages, record exact identities and perform cheap structural checks.
  for z in \
    "$VV/probe_5_3/PacsSCAN5.3.zip" \
    "$VV/probe_5_3_1/PacsSCAN5.3.1.zip" \
    "$VV/latest_533/PacsSCAN5.3.3.zip"; do
    if [ -f "$z" ]; then
      echo "--- local newer package: $z" | tee -a "$LOGS/fixed_latest_check.log" "$LOGS/latest_version.txt"
      echo "sha256=$(sha256_file "$z") size=$(stat -c%s "$z")" | tee -a "$LOGS/fixed_latest_check.log" "$LOGS/latest_version.txt"
      if command -v unzip >/dev/null 2>&1; then
        unzip -l "$z" | grep -E "PacsSCAN|setup.exe|PGImageExchQueue|PGImageExchangeQueueSvc" | head -80 | tee -a "$LOGS/fixed_latest_check.log" || true
      fi
      if strings "$z" | grep -q "PGImageExchange"; then
        echo "Package contains PGImageExchange string; full extraction/runtime proof would be required before any bypass claim." | tee -a "$LOGS/fixed_latest_check.log"
      else
        echo "No direct PGImageExchange string found in zip-level scan." | tee -a "$LOGS/fixed_latest_check.log"
      fi
    fi
  done
  LATEST_CHECK_DONE=true
}

run_vulnerable_checks
run_fixed_latest_checks

cat <<EOF
================================================================
RESULT
================================================================
variant_confirmed=$VARIANT_CONFIRMED
vulnerable_surface_confirmed=$VULN_SURFACE_CONFIRMED
service_static_candidate=$SERVICE_STATIC_CANDIDATE
service_runtime_confirmed=$SERVICE_RUNTIME_CONFIRMED
latest_check_done=$LATEST_CHECK_DONE
fixed_available=$FIXED_AVAILABLE
EOF

if [ "$VARIANT_CONFIRMED" = true ]; then
  exit 0
fi
exit 1
