Exploit database

GH-945bd5267b0d1b94c3f74faf5cda7e5a

blkph0x/cve-2026-83844_poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-83844

5 sources

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

Repository files579
blkph0x/cve-2026-83844_pocRevision 193ed44859da
Next files →

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

lab/trace/export_provenance_outer_frontier.py

Python · 30,299 bytes
#!/usr/bin/env python3
"""Export the bounded old outer-XLBox numeric frontier without private data.

The ignored guest results, raw CDB logs, process IDs, memory addresses, and
WER dump stay local. The exporter rejects changed inputs or incomplete route
evidence rather than promoting an abnormal file-open to a completed result.
"""

from __future__ import annotations

import hashlib
import json
from pathlib import Path
import re
import struct

import pefile

from build_provenance_outer_frontier import PINS, POINTS_FRONTIER
from compare_focus import EXE_SHA256, VERSIONS, sha256, validate_bootstrap
from export_provenance_deep_evidence import (
    MARKER_RE, PID_NORMAL_RE, PID_WARNING_RE, PINNED, ROOT, load_json,
    qwords, register, require,
)
from export_provenance_late_heap_bounds import MODULE_RE, STACK_RETURN_RE, address


TRIAL = "old-xlbox-frontier-01"
CONTROL = "40_official_c2pa_jpeg"
CASES = (
    CONTROL, "outer_xlbox_exact", "outer_xlbox_plus1",
    "outer_xlbox_2pow32", "outer_xlbox_max_minus1",
)
PROFILE_SHA256 = "2d7f830b6c7499ac2bcfec586c5756ec0c00e8047f58ad943026fccb29f679ea"
PROFILE_MANIFEST_SHA256 = "30abd1f20484d2efc629c19aac53568a4c97782c4a96937c673dd00d2285dd9e"
CORPUS_MANIFEST_SHA256 = "1b9a47e67118e63d5e3f96f3dbc79c0bcfe19779c1041d50e52a219531eeb5cf"
PRIVATE_DUMP_SHA256 = "61d4b1f1ac2279318709f217bf24c957ef93d519d82699a1dfe1b8d8d5c778db"
SDK_SHA256 = PINNED["old"]["provenancesdk.dll"]
UINT64_MAX = (1 << 64) - 1

# The expected first read is a count, not an allocation extent. The +1 case
# reports one byte beyond the available physical carrier while returning a
# status-36 error; no downstream read of that byte was sampled.
EXPECTED = {
    CONTROL: ("75a8da33f6eaf1e16bf3b42cd78913b22b2e6a671fda217a508b1ba4230ce864",
              51118, 51118, 51118, 0),
    "outer_xlbox_exact": ("91adf549b43b69b6c53ae9d4375d58325a9252110d4f26346f0f87b118621d6d",
                          51126, 51126, 51126, 0),
    "outer_xlbox_plus1": ("131f3b706393e45dfc161034dcbdc85a35d1c35dd97cfb6bafbcdde44b95bd74",
                          51127, 51126, 51127, 36),
    "outer_xlbox_2pow32": ("0504c642ab5b65b244705df60ed8d0998b103ab5ab5f896ef3e3348aabca9387",
                           1 << 32, 51126, 0, 36),
    "outer_xlbox_max_minus1": ("b717c4ca10de9f41b59681d60913a373925df963a86173a856ad294989b78870",
                               UINT64_MAX - 1, None, None, None),
}
FRONTIER_SITES = {f"frontier_{p.label}": p.rva for p in POINTS_FRONTIER}
COMPLETE_FRONTIER = [
    "frontier_size_local", "frontier_allocation_call",
    "frontier_allocation_return", "frontier_narrow_before",
    "frontier_narrow_after", "frontier_first_copy_bound",
    "frontier_first_copy_call", "frontier_first_copy_return",
    "frontier_reported_size",
]
THROW_FRONTIER = [
    "frontier_size_local", "frontier_allocation_call",
    "frontier_allocation_failure", "frontier_bad_alloc_throw",
]
ROUTE_PREFIX = [
    "image_image_open", "image_decoder", "flow_decoder_return",
    "flow_image_guard", "flow_provenance_call", "provenance_manifest_entry",
    "provdeep_file_reader", "provenance_sdk_validation",
    "provdeep_retrieval_entry",
]
LIST_RE = re.compile(
    r"(?ms)^PAINT_FRONTIER_BREAKPOINT_LIST_BEGIN\r?\n(.*?)^PAINT_FRONTIER_BREAKPOINT_LIST_END\s*$"
)
ENABLED_RE = re.compile(r"^\s*\d+\s+e\s+([0-9a-f`]+)\s+/1\b", re.I)
CHANCE_RE = re.compile(
    r"(?m)^\(([0-9a-f]+)\.([0-9a-f]+)\): C\+\+ EH exception - code "
    r"([0-9a-f]+) \((first chance|!!! second chance !!!)\)\s*$", re.I
)
PARAM_RE = re.compile(r"(?m)^\s*Parameter\[(\d+)\]: ([0-9a-f]+)\s*$", re.I)


def stream_sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def signed_bad_alloc_type() -> dict[str, object]:
    dll = ROOT / "packages/11.2605.81.0/x64/PaintApp/provenancesdk.dll"
    require(sha256(dll) == SDK_SHA256, "Authenticated old SDK differs")
    pe = pefile.PE(str(dll), fast_load=True)
    try:
        require(all(pe.get_data(rva, len(bytes.fromhex(opcode))) == bytes.fromhex(opcode)
                    for rva, opcode in PINS.items()),
                "Frontier signed instruction bytes differ")
        extra = {
            0x3B60: bytes.fromhex("e9ef141a00"),
            0x1A5062: bytes.fromhex("488d15ef8e0900"),
            0x1A506E: bytes.fromhex("e88b0a0000"),
        }
        require(all(pe.get_data(rva, len(opcode)) == opcode
                    for rva, opcode in extra.items()),
                "Signed bad_alloc throw-helper bytes differ")
        throw_info_rva = 0x1A5069 + struct.unpack("<i", extra[0x1A5062][3:7])[0]
        require(throw_info_rva == 0x23DF58,
                "bad_alloc helper throw-info target differs")
        attrs, unwind, forward, array_rva = struct.unpack(
            "<4I", pe.get_data(throw_info_rva, 16))
        require((attrs, unwind, forward, array_rva) == (0, 0x6CC0, 0, 0x23DF78),
                "Signed bad_alloc throw-info differs")
        count, = struct.unpack("<I", pe.get_data(array_rva, 4))
        require(count == 2, "bad_alloc catchable type count differs")
        names = []
        for index in range(count):
            catch_rva, = struct.unpack("<I", pe.get_data(array_rva + 4 + 4 * index, 4))
            type_rva, = struct.unpack("<I", pe.get_data(catch_rva + 4, 4))
            names.append(pe.get_data(type_rva + 16, 64).split(b"\0", 1)[0].decode("ascii"))
        require(names == [".?AVbad_alloc@std@@", ".?AVexception@std@@"],
                "Signed bad_alloc RTTI differs")
    finally:
        pe.close()
    return {"throw_info_rva": "0x23DF58", "primary_type": "std::bad_alloc",
            "catchable_base_type": "std::exception", "signed_sdk_sha256": SDK_SHA256}


def validate_inputs() -> tuple[dict[str, object], dict[str, object]]:
    script = ROOT / "lab/output/provenance-outer-frontier/old.auto.cdb.txt"
    profile_manifest = script.with_suffix(script.suffix + ".json")
    corpus_path = ROOT / "lab/corpus/provenance_outer_frontier/generated/manifest.json"
    require(sha256(script) == PROFILE_SHA256 and
            sha256(profile_manifest) == PROFILE_MANIFEST_SHA256 and
            sha256(corpus_path) == CORPUS_MANIFEST_SHA256,
            "Pinned profile or corpus manifest differs")
    profile = load_json(profile_manifest)
    require(profile.get("profile") == "old" and
            profile.get("version") == VERSIONS["old"] and
            profile.get("diagnostic_mode") == "outer-xlbox-frontier" and
            profile.get("auto_continue") is True and
            profile.get("exception_continuation") == "unhandled" and
            profile.get("signed_sdk_sha256") == SDK_SHA256 and
            profile.get("pinned_instruction_bytes") ==
            {f"0x{k:X}": v for k, v in PINS.items()} and
            {f"{p['path']}_{p['label']}": int(p["rva"], 16)
             for p in profile["checkpoints"] if p["path"] == "frontier"} == FRONTIER_SITES,
            "Pinned old frontier profile differs")
    corpus = load_json(corpus_path)
    require(corpus.get("schema") == "paint-provenance-outer-xlbox-frontier-v1" and
            corpus.get("source_sha256") == EXPECTED[CONTROL][0] and
            corpus.get("fixed_c2pa_marker_shifted_to") == "0x38",
            "Pinned outer XLBox corpus identity differs")
    by_case = {row["id"]: row for row in corpus["cases"]}
    require(set(EXPECTED) - {CONTROL} <= set(by_case), "Frontier fixtures missing")
    for case_id in CASES[1:]:
        row = by_case[case_id]
        digest, size, _, _, _ = EXPECTED[case_id]
        fixture = ROOT / "lab/corpus/provenance_outer_frontier/generated" / str(row["file"])
        require(row.get("file") == case_id + ".jpg" and
                row.get("sha256") == digest and
                int(row["xlbox"], 16) == size and
                row.get("bytes") == 140305 and
                row.get("paint_status") == "not_tested" and
                sha256(fixture) == digest,
                f"Pinned outer XLBox fixture differs: {case_id}")
    control = ROOT / "lab/corpus/generated/40_official_c2pa_jpeg.jpg"
    require(sha256(control) == EXPECTED[CONTROL][0], "Positive control differs")
    stage = load_json(ROOT / "lab/isolation/generated" /
                      f"{TRIAL}.provenance-outer-xlbox-stage.json")
    require(stage.get("schema") == "paint-provenance-outer-xlbox-stage-v1" and
            stage.get("build") == "old" and stage.get("trial_label") == TRIAL and
            stage.get("selected_cases") == list(CASES) and
            stage.get("diagnostic_mode") == "outer-xlbox-frontier" and
            stage.get("networking") == "Enable" and
            stage.get("profile_sha256") == PROFILE_SHA256 and
            stage.get("profile_manifest_sha256") == PROFILE_MANIFEST_SHA256 and
            stage.get("corpus_manifest_sha256") == CORPUS_MANIFEST_SHA256 and
            sha256(ROOT / "lab/isolation/generated" / f"{TRIAL}.wsb") ==
            stage.get("wsb_sha256"),
            "Staged old frontier profile/fixtures differ")
    return profile, stage


def parse_blocks(log: str, expected_pid: int, profile: dict[str, object]
                 ) -> list[tuple[str, str]]:
    markers = list(MARKER_RE.finditer(log))
    pid_rows = sorted(
        [(m.start(), m.group(1), int(m.group(2)), False)
         for m in PID_NORMAL_RE.finditer(log)] +
        [(m.start(), m.group(1), int(m.group(2)), True)
         for m in PID_WARNING_RE.finditer(log)]
    )
    labels = [m.group(1) for m in markers]
    valid = {f"{p['path']}_{p['label']}" for p in profile["checkpoints"]}
    require(labels and labels == [row[1] for row in pid_rows] and
            all(row[2] == expected_pid for row in pid_rows) and
            all(label in valid for label in labels),
            "Old frontier marker/PID/profile sequence differs")
    return [(m.group(1), log[m.end():markers[i + 1].start()
                            if i + 1 < len(markers) else len(log)])
            for i, m in enumerate(markers)]


def check_breakpoints(log: str, module_base: int) -> None:
    listing = LIST_RE.findall(log.replace("\r\n", "\n"))
    require(len(listing) == 1, "Frontier breakpoint list missing/ambiguous")
    for label, rva in FRONTIER_SITES.items():
        lines = [line for line in listing[0].splitlines()
                 if f"PAINT_TRACE_HIT={label}" in line]
        require(len(lines) == 1, f"Frontier breakpoint missing/duplicate: {label}")
        enabled = ENABLED_RE.match(lines[0])
        require(enabled is not None and
                address(enabled.group(1)) == module_base + rva,
                f"Frontier breakpoint not enabled/resolved: {label}")


def sample_case(case_id: str, batch_row: dict[str, object],
                profile: dict[str, object], stage: dict[str, object]
                ) -> dict[str, object]:
    files = list((ROOT / "lab/results" / TRIAL / "focus/old" / case_id)
                 .glob("*/result.json"))
    require(len(files) == 1 and sha256(files[0]) == batch_row.get("result_sha256"),
            f"Private per-file result missing or modified: {case_id}")
    result = load_json(files[0])
    digest, size, copy_count, reported, sdk_status = EXPECTED[case_id]
    complete = case_id != "outer_xlbox_max_minus1"
    expected_status = "complete" if complete else "inconclusive"
    require(result.get("schema") == "paint-ab-focused-cdb-v1" and
            result.get("build") == "old" and result.get("case_id") == case_id and
            result.get("status") == expected_status and
            result.get("installed_package", {}).get("version") == VERSIONS["old"] and
            result.get("installed_exe_sha256") == EXE_SHA256["old"] and
            result.get("fixture", {}).get("file") ==
            ("40_official_c2pa_jpeg.jpg" if case_id == CONTROL else case_id + ".jpg") and
            result.get("fixture", {}).get("sha256") == digest and
            result.get("fixture_source") == ("frozen" if case_id == CONTROL else "followup") and
            result.get("trace_script_sha256") == PROFILE_SHA256 and
            result.get("trace_manifest_sha256") == PROFILE_MANIFEST_SHA256 and
            result.get("fixture_manifest_sha256") ==
            (sha256(ROOT / "lab/corpus/generated/manifest.json") if case_id == CONTROL
             else stage["staged_followup_manifest_sha256"]) and
            result.get("file_open_filename_value_verified") is True and
            result.get("file_open_entry_method") == "win32_file_name_control_1148" and
            result.get("file_open_error") is None and
            result.get("debugger_ready") is True,
            f"Old per-file identity/filename/trace differs: {case_id}")
    installed = {row["module"]: row["sha256"]
                 for row in result.get("installed_module_checks", [])}
    expected_modules = {
        "mspaint.exe": EXE_SHA256["old"],
        "ImageProcessing.dll": sha256(ROOT / "packages/11.2605.81.0/x64/PaintApp/ImageProcessing.dll"),
        **PINNED["old"],
    }
    require(installed == expected_modules,
            f"Installed signed old modules differ: {case_id}")
    pid = result.get("blank_pid")
    require(isinstance(pid, int) and pid > 0 and
            result.get("cdb_initial_pid") == pid and
            result.get("file_open_launch_pid") == pid,
            f"Paint/debugger/file-open PID differs: {case_id}")
    log_path = files[0].with_name("cdb.log")
    require(log_path.is_file() and log_path.stat().st_size < 20_000_000,
            f"Private CDB log missing/oversized: {case_id}")
    log = log_path.read_text(encoding="utf-8-sig", errors="replace")
    blocks = parse_blocks(log, pid, profile)
    labels = [label for label, _ in blocks]
    require(result.get("markers_before_open") == [] and
            labels == result.get("markers_after_open") and
            [row.get("marker") for row in result.get("marker_pid_records", [])] == labels and
            all(row.get("pid") == pid for row in result["marker_pid_records"]) and
            labels[:len(ROUTE_PREFIX)] == ROUTE_PREFIX,
            f"Old route/marker identity differs: {case_id}")
    diagnostic = [(label, body) for label, body in blocks if label.startswith("frontier_")]
    expected_diagnostic = COMPLETE_FRONTIER if complete else THROW_FRONTIER
    require([label for label, _ in diagnostic] == expected_diagnostic,
            f"Frontier marker order differs: {case_id}")
    by_label = dict(diagnostic)
    module_rows = MODULE_RE.findall(diagnostic[0][1])
    require(len(module_rows) == 1, f"SDK base ambiguous: {case_id}")
    module_base = address(module_rows[0])
    check_breakpoints(log, module_base)
    for label, body in diagnostic:
        require(register(body, "rip") == module_base + FRONTIER_SITES[label],
                f"Frontier instruction RVA differs: {case_id}/{label}")
    require(qwords(by_label["frontier_size_local"]) == [size] and
            register(by_label["frontier_allocation_call"], "rcx") == size and
            qwords(by_label["frontier_allocation_call"]) == [size],
            f"Full parsed Size/pre-call argument differs: {case_id}")
    sample: dict[str, object] = {
        "case": case_id,
        "fixture_sha256": digest,
        "private_result_sha256": sha256(files[0]),
        "private_cdb_sha256": sha256(log_path),
        "per_file_status": expected_status,
        "exact_filename_signed_modules_same_pid": True,
        "all_frontier_breakpoints_enabled_resolved": True,
        "frontier_markers_same_paint_pid": True,
        "frontier_marker_rvas_in_order":
            [f"0x{FRONTIER_SITES[label]:X}" for label in expected_diagnostic],
        "parsed_size_and_allocation_pre_call": size,
    }
    cleanup = result.get("cleanup") or {}
    health = result.get("post_close_health") or {}
    require(not health.get("remaining_pids") and not health.get("error") and
            not cleanup.get("remaining_pids") and not cleanup.get("forced_pids"),
            f"Paint health or cleanup differs: {case_id}")
    if complete:
        allocation = register(by_label["frontier_allocation_return"], "rax")
        require(allocation is not None and allocation != 0 and
                qwords(by_label["frontier_allocation_return"]) == [size] and
                register(by_label["frontier_narrow_after"], "r13") ==
                (size & 0xFFFFFFFF) and
                register(by_label["frontier_first_copy_bound"], "rax") == size and
                register(by_label["frontier_first_copy_call"], "r9") == copy_count and
                register(by_label["frontier_first_copy_call"], "rdx") == allocation and
                register(by_label["frontier_first_copy_return"], "rax") == copy_count and
                register(by_label["frontier_reported_size"], "r13") == reported and
                register(by_label["frontier_reported_size"], "rax") == reported,
                f"Allocation/copy/narrow/report values differ: {case_id}")
        # A single APP11 segment cannot enter the continuation site. That
        # non-hit is checked so it cannot be described as a measured wrap.
        require(not any(label.startswith("frontier_continuation_") for label in labels) and
                labels.count("provenance_sdk_init_result") == 1 and
                labels[-1] == "flow_handoff_return" and
                register(dict(blocks)["provenance_sdk_init_result"], "rax", 32) == sdk_status and
                len(result.get("loaded_module_checks") or []) == 4 and
                all(row.get("matches_signed_package") is True
                    for row in result["loaded_module_checks"]) and
                result.get("loaded_module_error") is None and
                result.get("error") is None and
                result.get("blank_pid") in (cleanup.get("close_requested_pids") or []) and
                not health.get("wer_events") and health.get("new_dump_count") == 0,
                f"Completed old route/status/normal-close differs: {case_id}")
        sample.update({
            "allocation_returned_nonzero": True,
            "narrowed_low32_size": size & 0xFFFFFFFF,
            "first_copy_destination_is_allocation": True,
            "first_copy_requested_and_returned_bytes": copy_count,
            "reported_output_length": reported,
            "sdk_init_status": sdk_status,
            "continuation_checkpoint_hit": False,
            "paint_normal_close": True,
            "wer_event_ids": [],
            "new_dump_count": 0,
        })
    else:
        require(register(by_label["frontier_allocation_failure"], "rbx") == size and
                register(by_label["frontier_bad_alloc_throw"], "rbx") == size and
                labels == ROUTE_PREFIX + THROW_FRONTIER and
                result.get("loaded_module_checks") == [] and
                str(result.get("loaded_module_error") or "").startswith(
                    "Cannot find a process with the process identifier ") and
                result.get("observed_paint_processes") == [] and
                not any(cleanup.get(key) for key in
                        ("initial_pids", "close_requested_pids", "forced_pids", "remaining_pids")) and
                sorted(row.get("event_id") for row in health.get("wer_events", [])) ==
                [1000, 1001] and health.get("new_dump_count") == 1,
                "Old bad_alloc throw/abnormal exit differs")
        chances = CHANCE_RE.findall(log)
        require(len(chances) == 2 and
                [row[3].lower() for row in chances] ==
                ["first chance", "!!! second chance !!!"] and
                all(int(row[0], 16) == pid and row[2].lower() == "e06d7363"
                    for row in chances) and
                chances[0][1].lower() == chances[1][1].lower(),
                "C++ first/second chance not linked to Paint process/thread")
        second = re.findall(
            r"(?ms)^PAINT_FRONTIER_SECOND_CHANCE_CPP\s*\n(.*?)^PAINT_FRONTIER_SECOND_CHANCE_END\s*$",
            log.replace("\r\n", "\n"))
        require(len(second) == 1 and
                "ExceptionCode: e06d7363 (C++ EH exception)" in second[0] and
                "VCRUNTIME140!_CxxThrowException+0x97" in second[0],
                "Second-chance C++ exception record missing")
        params = PARAM_RE.findall(second[0])
        require(len(params) == 4 and [int(index) for index, _ in params] ==
                [0, 1, 2, 3] and int(params[0][1], 16) == 0x19930520 and
                address(params[2][1]) - module_base == 0x23DF58 and
                address(params[3][1]) == module_base,
                "C++ throw-info does not match signed bad_alloc RTTI")
        returns = [address(raw) - module_base
                   for raw in STACK_RETURN_RE.findall(second[0])]
        require(returns[:2] == [0x1A3F41, 0xC97A4],
                "Exception stack does not return through allocator/parser")
        dumps = list((ROOT / "lab/results" / TRIAL / "dumps").glob("mspaint.exe.*.dmp"))
        require(len(dumps) == 1 and dumps[0].name == f"mspaint.exe.{pid}.dmp" and
                stream_sha256(dumps[0]) == PRIVATE_DUMP_SHA256,
                "Private bad_alloc dump missing or changed")
        sample.update({
            "allocation_failure_preserved_size": size,
            "non_size_max_bad_alloc_throw_arm_hit": True,
            "exception_type": signed_bad_alloc_type(),
            "exception_code": "e06d7363",
            "first_and_second_chance_same_paint_thread": True,
            "throw_stack_return_rvas": ["0x1A3F41", "0xC97A4"],
            "loaded_module_postcheck": "unavailable_after_paint_exit",
            "wer_event_ids": [1000, 1001],
            "new_dump_count": 1,
            "private_dump_sha256": PRIVATE_DUMP_SHA256,
        })
    return sample


def export() -> dict[str, object]:
    profile, stage = validate_inputs()
    signed_type = signed_bad_alloc_type()
    trial_root = ROOT / "lab/results" / TRIAL
    batches = list(trial_root.glob("focus-batch-old-*.json"))
    require(len(batches) == 1, "Old frontier batch missing/ambiguous")
    batch = load_json(batches[0])
    require(batch.get("schema") == "paint-ab-focus-batch-v1" and
            batch.get("build") == "old" and
            batch.get("selected_cases") == list(CASES) and
            batch.get("status") == "review_required" and
            batch.get("error") is None and
            not (batch.get("failure_cleanup") or {}).get("paint_remaining_pids"),
            "Old frontier batch identity/outcome differs")
    validate_bootstrap(trial_root, batch, "old")
    rows = {row["case_id"]: row for row in batch["cases"]}
    require(set(rows) == set(CASES) and
            all(rows[case_id].get("status") ==
                ("inconclusive" if case_id == "outer_xlbox_max_minus1" else "complete") and
                rows[case_id].get("timed_out") is False and
                rows[case_id].get("child_exited_verified") is True and
                rows[case_id].get("process_exit_code") == 0 and
                rows[case_id].get("parent_cleanup") is None
                for case_id in CASES),
            "Frontier batch per-file results differ")
    samples = [sample_case(case_id, rows[case_id], profile, stage)
               for case_id in CASES]
    require(samples[-1]["exception_type"] == signed_type,
            "Signed bad_alloc type and abnormal sample differ")
    private_pids = [load_json(next((trial_root / "focus/old" / case_id)
                                   .glob("*/result.json")))["blank_pid"]
                    for case_id in CASES]
    require(len(set(private_pids)) == len(CASES),
            "Frontier files did not use separate Paint processes")
    shutdown = list(trial_root.glob("focus-shutdown-old-*.json"))
    require(len(shutdown) == 1 and
            load_json(shutdown[0]).get("exit_code") == 0 and
            load_json(shutdown[0]).get("method") ==
            "normal shutdown /s /t 20; no /f" and
            batch.get("shutdown_method") == "shutdown /s /t 20 (no /f)",
            "Old frontier guest shutdown request differs")
    teardown = load_json(trial_root / "teardown-result.json")
    require(teardown.get("trial_label") == TRIAL and
            teardown.get("state") == "closed" and
            teardown.get("guest_host_exited") is True and
            teardown.get("client_action") ==
            "terminated_leftover_client_after_guest_exit" and
            teardown.get("sandbox_process_count_after") == 0,
            "Old frontier guest teardown differs")
    return {
        "schema": "paint-old-provenance-outer-xlbox-frontier-v1",
        "trial": TRIAL,
        "version": VERSIONS["old"],
        "signed_old_sdk_sha256": SDK_SHA256,
        "profile_sha256": PROFILE_SHA256,
        "profile_manifest_sha256": PROFILE_MANIFEST_SHA256,
        "corpus_manifest_sha256": CORPUS_MANIFEST_SHA256,
        "private_batch_sha256": sha256(batches[0]),
        "cases": samples,
        "guest_host_exited_zero_processes": True,
        "teardown_client_action": teardown.get("client_action"),
        "claim_limit": (
            "The four completed files measure full-size allocation arguments, "
            "first-copy counts, low-32-bit narrowing, and returned lengths; "
            "the max-minus-one file instead reached an unhandled bad_alloc "
            "and remains inconclusive as a per-file result. No continuation "
            "copy, allocation end, invalid read/write, or CVE patch location "
            "was measured. The plus-one result reports an unfilled byte, but "
            "the later status-36 path was not sampled for a read of it."
        ),
    }


def markdown(record: dict[str, object]) -> str:
    cases = {row["case"]: row for row in record["cases"]}
    rows = []
    for case_id in CASES:
        sample = cases[case_id]
        if case_id == "outer_xlbox_max_minus1":
            rows.append(
                "| `outer_xlbox_max_minus1` | 18,446,744,073,709,551,614 | "
                "No allocation return | Not reached | Not reached | "
                "Unhandled `std::bad_alloc`; per-file **inconclusive** |"
            )
        else:
            rows.append(
                f"| `{case_id}` | {sample['parsed_size_and_allocation_pre_call']:,} | "
                f"Nonzero | {sample['first_copy_requested_and_returned_bytes']:,} | "
                f"{sample['reported_output_length']:,} | SDK status "
                f"{sample['sdk_init_status']}; normal Paint close |"
            )
    return "\n".join([
        "# Old outer XLBox numeric frontier: allocation, copy, and throw",
        "",
        "The isolated signed Paint 11.2605.81.0 guest opened the unchanged C2PA",
        "control and four [pinned outer-XLBox fixtures](../corpus/provenance_outer_frontier/PROTOCOL.md)",
        "in separate Paint",
        "processes. This address-free record is generated from the ignored",
        "guest results and raw CDB logs by",
        "[`export_provenance_outer_frontier.py`](../trace/export_provenance_outer_frontier.py).",
        "[The strict JSON](provenance-outer-frontier.json) pins the fixture,",
        "profile, corpus, batch, per-file result, CDB, and private-dump hashes.",
        "It checks exact filename readback, authenticated installed and loaded",
        "modules, one Paint PID per file, all 15 enabled/resolved",
        "module-relative frontier breakpoints, marker order, and guest closure.",
        "",
        "| Input | Parsed XLBox / allocation request | Allocation return | First read into buffer | Reported output length | Outcome |",
        "| --- | ---: | --- | ---: | ---: | --- |",
        *rows,
        "",
        "The normal source control and exact-fit extended control returned SDK",
        "status zero. The one-byte-overdeclared case requested 51,127 bytes",
        "and received a nonzero allocation result,",
        "copied the 51,126 physically present carrier bytes, reported 51,127,",
        "and returned status 36. The trace does not sample a later read of the",
        "unfilled byte. At `2^32`, the allocation returned nonzero, the parser",
        "copied 51,126 bytes, `R13` narrowed to zero, the reported length was",
        "zero, and the SDK returned status 36. This confirms a 32-bit length",
        "truncation in this run, but a single APP11 segment did not reach the",
        "continuation-copy checkpoints or demonstrate memory corruption.",
        "",
        "At `UINT64_MAX-1`, the old allocator's non-`SIZE_MAX` failure arm at",
        "`provenancesdk+0x1A3F3C` was reached with the full declared length in",
        "`RBX`. Signed throw-helper instructions and throw-info RVA `0x23DF58`",
        "identify `std::bad_alloc`. The same Paint thread recorded first- and",
        "second-chance C++ exceptions; WER logged events 1000 and 1001 and",
        "wrote one dump. The process exited before the loaded-module postcheck,",
        "so that file's per-file status remains **inconclusive**. The four",
        "completed Paint processes closed normally. The guest host exited and",
        "the final host/client process count was zero. A leftover client",
        "process was terminated after the guest host had exited.",
        "",
        "This differs from the separately measured `UINT64_MAX` arm, which",
        "throws `std::bad_array_new_length`. The exception type selects an",
        "allocator failure branch; it is not evidence of an invalid memory",
        "access. Neither the allocation's actual extent nor a continuation",
        "write was measured here. The small",
        "[two-APP11 follow-up](../corpus/provenance_app11_split/PROTOCOL.md)",
        "is designed to test continuation arithmetic, while itself remaining",
        "too small to show a write beyond a 4 GiB allocation.",
        "",
    ])


def main() -> None:
    record = export()
    evidence = ROOT / "lab/evidence"
    (evidence / "provenance-outer-frontier.json").write_text(
        json.dumps(record, indent=2) + "\n", encoding="utf-8")
    (evidence / "provenance-outer-frontier.md").write_text(
        markdown(record), encoding="utf-8")
    print("Wrote bounded old outer-XLBox frontier JSON and Markdown")


if __name__ == "__main__":
    main()