Exploit database

GH-ad695569e25c782a3214d9269093a719

pt-act/node2shell-cve-2026-111497

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-111497

62 sources

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

Repository files4
pt-act/node2shell-cve-2026-111497Revision df32e1275c78

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

watch/lab_consumer.py

Python · 9,477 bytes
#!/usr/bin/env python3
"""
lab_consumer.py — the local verifier half of the audit kit.

Reads the watcher's candidate queue and runs a **user-supplied** malformed
Brotli test vector against the artifact's own decoder:

    Z_BUF_ERROR (-5)                     -> CONFIRMED_VULNERABLE
    ERR__ERROR_FORMAT_BLOCK_SWITCH (-17) -> CONFIRMED_FIXED
    anything else / timeout              -> INCONCLUSIVE

Local-only. The kit ships no trigger and no exploit payload; pass the vector
with --trigger. Docker probes run with `--network none --pull=never`; local
Node binaries run directly under a timeout. Brew rows carry no executable
path, so they are INCONCLUSIVE by design.

It is read-only with respect to the artifact: it only asks the decoder to
decompress a file. Docker is the isolation boundary for images; local Node
runs are process-isolated by timeout, not a full sandbox.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent
DEFAULT_QUEUE = ROOT / "candidates.jsonl"
DEFAULT_VERDICTS = ROOT / "verdicts.jsonl"

NODE_SCRIPT = (
    "const fs=require('fs'),z=require('zlib');"
    "const d=fs.readFileSync(process.argv[1]);"
    "try{z.brotliDecompressSync(d);"
    "console.log(JSON.stringify({result:'success'}));}"
    "catch(e){console.log(JSON.stringify({result:'error',"
    "code:e.code||null,errno:(typeof e.errno==='number'?e.errno:null),"
    "message:(e.message||'').slice(0,160)}));}"
)


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


def run(cmd: list[str], timeout: float) -> tuple[int | None, str, str, float]:
    started = time.monotonic()
    try:
        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
        return proc.returncode, proc.stdout.strip(), proc.stderr.strip(), time.monotonic() - started
    except subprocess.TimeoutExpired:
        return None, "", "timeout", time.monotonic() - started
    except (FileNotFoundError, OSError) as exc:
        return None, "", str(exc), time.monotonic() - started


def parse_probe(rc: int | None, out: str, err: str) -> dict[str, Any]:
    if rc is None:
        return {"result": "error", "message": err or "execution failed"}
    if not out:
        return {"result": "error", "message": (err or "no output")[:160]}
    try:
        return json.loads(out.splitlines()[-1])
    except json.JSONDecodeError:
        return {"result": "error", "message": out[:160]}


def classify(probe: dict[str, Any]) -> tuple[str, str]:
    if probe.get("result") == "success":
        return "INCONCLUSIVE", "decoder accepted the stream"
    code = str(probe.get("code") or "")
    errno = probe.get("errno")
    if errno == -5 or "Z_BUF_ERROR" in code:
        return "CONFIRMED_VULNERABLE", f"{code or 'Z_BUF_ERROR'} ({errno})"
    if errno == -17 or "BLOCK_SWITCH" in code:
        return "CONFIRMED_FIXED", f"{code or 'BLOCK_SWITCH'} ({errno})"
    message = str(probe.get("message") or "unexpected probe result")
    return "INCONCLUSIVE", message[:160]


def probe_node(binary: str, trigger: Path, timeout: float) -> tuple[dict[str, Any], float]:
    rc, out, err, elapsed = run([binary, "-e", NODE_SCRIPT, str(trigger)], timeout)
    return parse_probe(rc, out, err), elapsed


def probe_docker(image: str, trigger: Path, timeout: float) -> tuple[dict[str, Any], float]:
    if not shutil.which("docker"):
        return {"result": "error", "message": "docker not found"}, 0.0
    # --rm does not remove a container whose create succeeded but whose start
    # never completed; name it and force-remove after every attempt.
    container = "p6-probe-" + hashlib.sha1(image.encode()).hexdigest()[:12]
    cmd = [
        "docker", "run", "--rm", "--name", container,
        "--network", "none", "--pull=never",
        "--platform", "linux/amd64",
        "--entrypoint", "node",
        "-v", f"{trigger}:/p6-trigger.br:ro",
        image, "-e", NODE_SCRIPT, "/p6-trigger.br",
    ]
    rc, out, err, elapsed = run(cmd, timeout)
    run(["docker", "rm", "-f", container], timeout=10)
    return parse_probe(rc, out, err), elapsed


def load_candidates(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        raise SystemExit(f"error: queue not found: {path}")
    latest: dict[str, dict[str, Any]] = {}
    order: list[str] = []
    with path.open(encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError:
                continue
            if row.get("verdict") not in {"SUSPICIOUS", "UNKNOWN"}:
                continue
            key = f"{row.get('kind')}|{row.get('name')}"
            if key not in latest:
                order.append(key)
            latest[key] = row
    return [latest[k] for k in order]


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Verify watcher candidates with a locally supplied Brotli test vector",
    )
    parser.add_argument("--queue", default=str(DEFAULT_QUEUE),
                        help="watcher candidates.jsonl (default: ./candidates.jsonl)")
    parser.add_argument("--trigger", required=True,
                        help="user-supplied malformed Brotli test vector (the kit ships none)")
    parser.add_argument("--verdicts", default=str(DEFAULT_VERDICTS),
                        help="append-only verdict output (default: ./verdicts.jsonl)")
    parser.add_argument("--timeout", type=float, default=60.0,
                        help="per local Node probe (default 60s)")
    parser.add_argument("--docker-timeout", type=float, default=180.0,
                        help="per Docker probe (default 180s)")
    parser.add_argument("--limit", type=int, default=0,
                        help="stop after N candidates (default: all)")
    parser.add_argument("--kind", action="append", choices=["node", "docker", "brew"],
                        help="only this kind (repeatable)")
    parser.add_argument("--dry-run", action="store_true",
                        help="show what would run; write nothing")
    parser.add_argument("--json", action="store_true", help="emit verdicts as JSON lines")
    parser.add_argument("--quiet", action="store_true", help="no table output")
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    queue = Path(args.queue).expanduser().resolve()
    trigger = Path(args.trigger).expanduser().resolve()
    verdicts = Path(args.verdicts).expanduser().resolve()

    if not trigger.exists():
        print(f"error: trigger not found: {trigger}", file=sys.stderr)
        return 1

    candidates = load_candidates(queue)
    if args.kind:
        wanted = set(args.kind)
        candidates = [r for r in candidates if r.get("kind") in wanted]
    if args.limit > 0:
        candidates = candidates[: args.limit]

    print(f"queue: {queue}")
    print(f"trigger: {trigger} ({trigger.stat().st_size} bytes)")
    print(f"candidates: {len(candidates)}")
    if args.dry_run:
        for row in candidates:
            print(f"  would probe {row.get('kind')}:{row.get('name')}")
        return 0

    results = []
    for row in candidates:
        kind = row.get("kind")
        name = str(row.get("name"))
        if kind == "node":
            probe, elapsed = probe_node(name, trigger, args.timeout)
        elif kind == "docker":
            probe, elapsed = probe_docker(name, trigger, args.docker_timeout)
        else:
            probe, elapsed = ({"result": "error",
                               "message": "no executable path in queue"},
                              0.0)

        lab_verdict, evidence = classify(probe)
        record = {
            "ts": now(),
            "artifact": f"{kind}:{name}",
            "kind": kind,
            "name": name,
            "queue_verdict": row.get("verdict"),
            "lab_verdict": lab_verdict,
            "evidence": evidence,
            "duration_s": round(elapsed, 2),
            "trigger": str(trigger),
        }
        results.append(record)

        if not args.quiet and not args.json:
            marker = {"CONFIRMED_VULNERABLE": "!", "CONFIRMED_FIXED": ".",
                      "INCONCLUSIVE": "?"}[lab_verdict]
            print(f"{marker} {lab_verdict:<22} {kind:<6} {name:<50} {evidence}")

    if args.json:
        for record in results:
            print(json.dumps(record, sort_keys=True))

    if not args.quiet and not args.json:
        vuln = sum(1 for r in results if r["lab_verdict"] == "CONFIRMED_VULNERABLE")
        fixed = sum(1 for r in results if r["lab_verdict"] == "CONFIRMED_FIXED")
        incon = sum(1 for r in results if r["lab_verdict"] == "INCONCLUSIVE")
        print(f"\nconfirmed vulnerable: {vuln}  confirmed fixed: {fixed}  "
              f"inconclusive: {incon}")

    with verdicts.open("a", encoding="utf-8") as handle:
        for record in results:
            handle.write(json.dumps(record, sort_keys=True) + "\n")
    print(f"verdicts: {verdicts}")

    return 2 if any(r["lab_verdict"] == "CONFIRMED_VULNERABLE" for r in results) else 0


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