#!/usr/bin/env python3
"""
Model of the FortiMail high-availability cluster daemon -- CVE-2026-126148.

WHAT THIS IS
------------
FortiMail (Fortinet) ships a high-availability (HA) cluster feature.  Cluster members
find each other over a fixed port range; the base port is 20000 and the map is

    20000 UDP/TCP   heartbeat
    20001 UDP/TCP   sync control
    20002 TCP       file sync
    20003 TCP       data sync
    20004 TCP       checksum sync
    20005 UDP/TCP   cluster join request     <-- the surface of CVE-2026-126148
    20010-20014 UDP/TCP   group mode

Fortinet PSIRT FG-IR-26-200 (published 2026-11-10) describes the flaw as:

    "An OS command injection vulnerability [CWE-78] in FortiMail may allow an
     unauthenticated remote attacker to execute unauthorized code or commands via
     crafted HA join-request packets."

FortiMail is proprietary and cannot be redistributed, so this file is an explicitly
documented MODEL of the FortiMail HA daemon.  It reproduces the security-relevant
behaviour the CVE is about:

  * the HA port map above, with a join-request listener on UDP and TCP 20005,
  * the modelled FortiMail HA join-request packet (see build_packet / parse_packet),
  * a peer-registration sink that assembles a command line out of the peer identity
    fields carried by the join request and executes it,
  * the processing order that makes the flaw *unauthenticated*: the join request is
    parsed and the peer-registration command is executed BEFORE the cluster digest in
    the packet is compared against the cluster secret,
  * the sibling HA surfaces (group mode, sync control, file sync, data sync, checksum
    sync), all of which route through the same command-construction helper.

The three behaviours (FML_MODE):

  vuln           FortiMail 8.0.1 model.  THE VULNERABLE BUILD.
                 No validation of the peer identity fields.  The command line is
                 assembled by raw interpolation and executed through /bin/sh -c.
                 -> OS command injection (CWE-78).

  fixed          FortiMail 8.0.2 model.  The identity fields are validated against a
                 strict character set and the command is executed WITHOUT a shell
                 (argument vector, shell=False).
                 -> the injection is neutralised by two independent layers.

  fixed-partial  A *hypothetical* remediation shape -- NOT a claim about the vendor's
                 patch.  Only the `hostname` field is validated; `serial`, `peer-ip`
                 and `cluster-id` are still interpolated raw, and the shell-based exec
                 helper is kept.  This arm exists so that the 0-day sweep has a
                 realistic incomplete-remediation target.

Nothing in this file is a real FortiMail implementation; see README.md.
"""

import hmac
import json
import os
import re
import shlex
import socket
import socketserver
import struct
import subprocess
import sys
import threading
import time

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

MODE = os.environ.get("FML_MODE", "vuln")
BIND = os.environ.get("FML_BIND", "0.0.0.0")
RESULTS = os.environ.get("FML_RESULTS", "/results")
SECRET = os.environ.get("FML_HA_SECRET", "fortimail-cluster-shared-secret")
BASE_PORT = int(os.environ.get("FML_BASE_PORT", "20000"))

PRODUCT = "FortiMail"
VERSION = {
    "vuln": "8.0.1",
    "fixed": "8.0.2",
    "fixed-partial": "8.0.2 (partial-remediation model)",
}[MODE]

# The modelled FortiMail HA join-request packet.
MAGIC = b"FMLHA"
PROTO_VERSION = 0x01
HEADER_LEN = 9                     # magic(5) + version(1) + type(1) + length(2)
MAX_PAYLOAD = 8192                 # protocol-level limit on the payload
MAX_PACKET = HEADER_LEN + MAX_PAYLOAD

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

# The strict character set the fixed build enforces on the peer identity fields:
# letters, digits, '-', '.' and '_'.  fullmatch() is used on purpose: '$' would also
# match before a trailing newline, which is the classic validator bypass.
FIELD_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")

# Message types.
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
REPLY = 0x81

# Status codes carried in the reply packet.
ST_OK = 0x00
ST_INVALID_FIELD = 0x01
ST_WRONG_ROLE = 0x02
ST_MALFORMED = 0x03

# (port offset, role, transports)
PORT_MAP = [
    (0, "heartbeat", ("udp", "tcp")),
    (1, "sync-control", ("udp", "tcp")),
    (2, "file-sync", ("tcp",)),
    (3, "data-sync", ("tcp",)),
    (4, "checksum-sync", ("tcp",)),
    (5, "cluster-join", ("udp", "tcp")),
    (10, "group-mode", ("udp", "tcp")),
    (11, "group-mode", ("udp", "tcp")),
    (12, "group-mode", ("udp", "tcp")),
    (13, "group-mode", ("udp", "tcp")),
    (14, "group-mode", ("udp", "tcp")),
]

# Which message types each role accepts.  The peer-membership roles (cluster-join and
# group-mode) share the join handler -- that shared dispatcher is the sibling call
# site the 0-day sweep looks for.
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},
}

# The command-construction sink for every role that executes something.
# The template is a token list; a "{field}" token is replaced by the raw value that
# arrived in the packet.  The command line of the FortiMail 8.0.1 model is
#
#     fml_ha peer add --cluster <cluster-id> --serial <serial> --name <hostname> --ip <peer-ip>
#
COMMANDS = {
    MSG_JOIN: (
        ["fml_ha", "peer", "add", "--cluster", "{cluster-id}", "--serial", "{serial}",
         "--name", "{hostname}", "--ip", "{peer-ip}"],
        ["cluster-id", "serial", "hostname", "peer-ip"],
    ),
    MSG_GROUP_JOIN: (
        ["fml_ha", "group", "add", "--cluster", "{cluster-id}", "--name", "{hostname}",
         "--ip", "{peer-ip}", "--serial", "{serial}"],
        ["cluster-id", "hostname", "peer-ip", "serial"],
    ),
    MSG_SYNC_CONTROL: (
        ["fml_ha", "sync", "control", "--peer", "{peer-ip}", "--cluster", "{cluster-id}"],
        ["peer-ip", "cluster-id"],
    ),
    MSG_FILE_SYNC: (
        ["fml_ha", "file", "sync", "--peer", "{peer-ip}", "--dir", "{hostname}"],
        ["peer-ip", "hostname"],
    ),
    MSG_DATA_SYNC: (
        ["fml_ha", "data", "sync", "--peer", "{peer-ip}", "--serial", "{serial}"],
        ["peer-ip", "serial"],
    ),
    MSG_CHECKSUM_SYNC: (
        ["fml_ha", "checksum", "sync", "--peer", "{peer-ip}", "--cluster", "{cluster-id}"],
        ["peer-ip", "cluster-id"],
    ),
}

_lock = threading.Lock()


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


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


def results_dir(*parts):
    d = os.path.join(RESULTS, *parts)
    try:
        os.makedirs(d, exist_ok=True)
        os.chmod(d, 0o777)
    except OSError:
        pass
    return d


def append_line(path, line):
    with _lock:
        with open(path, "a", encoding="utf-8", errors="replace") as fh:
            fh.write(line.rstrip("\n") + "\n")
        try:
            os.chmod(path, 0o666)
        except OSError:
            pass


def append_jsonl(path, obj):
    append_line(path, json.dumps(obj, sort_keys=True))


def printable(text):
    """Escape the control characters of an executed command line.

    The command line contains the bytes that arrived in the packet, so it can carry
    NUL bytes, newlines and carriage returns.  The log stays a readable text file.
    """
    out = []
    for ch in text:
        code = ord(ch)
        if ch == "\n":
            out.append("\\n")
        elif ch == "\r":
            out.append("\\r")
        elif ch == "\t":
            out.append("\\t")
        elif code < 0x20 or code == 0x7F:
            out.append("\\x%02x" % code)
        else:
            out.append(ch)
    return "".join(out)


def log_event(event, **kw):
    rec = {"ts": now(), "mode": MODE, "version": VERSION, "event": event}
    rec.update(kw)
    append_jsonl(os.path.join(RESULTS, "ha-events.jsonl"), rec)


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


def build_packet(msg_type, fields, version=PROTO_VERSION):
    """Assemble a modelled FortiMail HA join-request packet.

    header : b"FMLHA" | version(1) | message type(1) | payload length(2, big endian)
    payload: five length-prefixed fields, in the order of FIELDS.  Each field is
             uint16 big-endian length followed by that many raw bytes.
    """
    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_packet(data):
    """Return (msg_type, fields) or raise ValueError."""
    if len(data) < HEADER_LEN:
        raise ValueError("short header")
    if data[:5] != MAGIC:
        raise ValueError("bad magic")
    version = data[5]
    if version != PROTO_VERSION:
        raise ValueError("unsupported version 0x%02x" % version)
    msg_type = data[6]
    plen = struct.unpack(">H", data[7:9])[0]
    if plen > MAX_PAYLOAD:
        raise ValueError("payload too large (%d bytes)" % plen)
    payload = data[9:9 + plen]
    if len(payload) != plen:
        raise ValueError("truncated payload")
    fields = {}
    off = 0
    for name in FIELDS:
        if off + 2 > len(payload):
            raise ValueError("truncated field header")
        flen = struct.unpack(">H", payload[off:off + 2])[0]
        off += 2
        if off + flen > len(payload):
            raise ValueError("truncated field value")
        fields[name] = payload[off:off + flen]
        off += flen
    return msg_type, fields


def build_reply(status, digest_ok, message):
    body = bytes([status & 0xFF, 1 if digest_ok else 0]) + message.encode("utf-8", "replace")
    return MAGIC + bytes([PROTO_VERSION, REPLY]) + struct.pack(">H", len(body)) + body


# ------------------------------------------------------------------- the policy


def validated_fields(msg_type):
    """The field names this build validates before it executes anything.

    vuln           -> none.  The peer identity is trusted as it arrives.
    fixed          -> every field the command line is built from.
    fixed-partial  -> only `hostname`.  This is the hypothetical remediation shape.
    """
    used = COMMANDS[msg_type][1]
    if MODE == "fixed":
        return list(used)
    if MODE == "fixed-partial":
        return [f for f in used if f == "hostname"]
    return []


def field_ok(value):
    """Strict character-set check: letters, digits, '-', '.' and '_', 1..64 bytes."""
    return FIELD_RE.fullmatch(value) is not None


def build_argv(msg_type, fields):
    """Replace the {field} tokens with the raw values that arrived in the packet."""
    template = COMMANDS[msg_type][0]
    argv = []
    for tok in template:
        if tok.startswith("{") and tok.endswith("}"):
            name = tok[1:-1]
            argv.append(fields[name].decode("latin-1"))
        else:
            argv.append(tok)
    return argv


# ------------------------------------------------------------------------- the sink


def execute(msg_type, fields, port, transport, peer):
    """The command-construction sink.

    Returns (status, digest_ok, message, executed).
    """
    used = COMMANDS[msg_type][1]

    # ---- layer 1: the validation layer.
    bad = []
    for name in validated_fields(msg_type):
        value = fields[name].decode("latin-1")
        if not field_ok(value):
            bad.append(name)
    if bad:
        append_line(
            os.path.join(RESULTS, "ha-reject-log.txt"),
            "%s mode=%s version=%s port=%d transport=%s peer=%s:%d rejected_fields=%s reason=character-set"
            % (now(), MODE, VERSION, port, transport, peer[0], peer[1], ",".join(bad)),
        )
        log_event("rejected", port=port, transport=transport, peer="%s:%d" % peer,
                  fields=bad, reason="character-set")
        return ST_INVALID_FIELD, False, "rejected: invalid peer identity field(s): %s" % ",".join(bad), False

    argv = build_argv(msg_type, fields)
    cmdline = " ".join(argv)

    # ---- layer 2: the execution layer.
    if MODE == "fixed":
        # FortiMail 8.0.2 model: no shell, argument vector only.
        exec_kind = "argv"
        out, err, rc = subprocess_run(argv)
        logged_cmd = shlex.join(argv)
    else:
        # FortiMail 8.0.1 model and the partial-remediation shape: the command line is
        # handed to a shell.
        exec_kind = "shell"
        out, err, rc = subprocess_run(["/bin/sh", "-c", cmdline])
        logged_cmd = cmdline

    append_line(
        os.path.join(RESULTS, "ha-command-log.txt"),
        "%s mode=%s version=%s port=%d transport=%s peer=%s:%d exec=%s exit=%d command=%s"
        % (now(), MODE, VERSION, port, transport, peer[0], peer[1], exec_kind, rc, printable(logged_cmd)),
    )
    log_event("executed", port=port, transport=transport, peer="%s:%d" % peer,
              exec_kind=exec_kind, command=printable(logged_cmd), exit_code=rc,
              fields_used=used)

    # ---- the cluster digest is compared only now: the peer-registration command has
    # ---- already run.  That ordering is what makes the flaw *unauthenticated* (PR:N).
    digest_ok = hmac.compare_digest(fields["admin-digest"], SECRET.encode("latin-1"))

    if not digest_ok:
        msg = "executed; peer not trusted (cluster digest mismatch)"
    else:
        msg = "executed; peer trusted"
    return ST_OK, digest_ok, msg, True


def subprocess_run(argv):
    """Run the helper and return (stdout, stderr, exit code).

    An embedded NUL byte makes the exec call fail outright; that is reported as an
    execution error rather than being silently truncated.
    """
    try:
        proc = subprocess.run(
            argv,
            shell=False,
            capture_output=True,
            timeout=20,
        )
    except Exception as exc:
        return "", "exec failed: %r" % (exc,), -1
    out = proc.stdout.decode("utf-8", "replace") if proc.stdout else ""
    err = proc.stderr.decode("utf-8", "replace") if proc.stderr else ""
    return out, err, proc.returncode


# ---------------------------------------------------------------------- dispatcher


def dispatch(data, role, transport, peer, port):
    try:
        msg_type, fields = parse_packet(data)
    except ValueError as exc:
        log_event("malformed", port=port, transport=transport, peer="%s:%d" % peer, reason=str(exc))
        return build_reply(ST_MALFORMED, False, "malformed packet: %s" % exc)

    if msg_type not in ROLE_TYPES.get(role, set()):
        log_event("wrong-role", port=port, transport=transport, peer="%s:%d" % peer,
                  role=role, msg_type=msg_type)
        return build_reply(ST_WRONG_ROLE, False, "message type 0x%02x is not handled by the %s role"
                           % (msg_type, role))

    if msg_type == MSG_HEARTBEAT:
        # The heartbeat role never builds a command line.
        log_event("heartbeat", port=port, transport=transport, peer="%s:%d" % peer)
        return build_reply(ST_OK, True, "heartbeat")

    status, digest_ok, message, executed = execute(msg_type, fields, port, transport, peer)
    return build_reply(status, digest_ok, message)


# --------------------------------------------------------------------- the servers


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


class TCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        sock = self.request
        sock.settimeout(30)
        while True:
            hdr = recv_exact(sock, 4)
            if hdr is None:
                return
            n = struct.unpack(">I", hdr)[0]
            if n == 0 or n > MAX_PACKET:
                return
            data = recv_exact(sock, n)
            if data is None:
                return
            reply = dispatch(data, self.server.role, "tcp", self.client_address, self.server.port)
            try:
                sock.sendall(struct.pack(">I", len(reply)) + reply)
            except OSError:
                return


class UDPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        data = self.request[0]
        reply = dispatch(data, self.server.role, "udp", self.client_address, self.server.port)
        try:
            self.request[1].sendto(reply, self.client_address)
        except OSError:
            pass


class ThreadedTCP(socketserver.ThreadingTCPServer):
    allow_reuse_address = True
    daemon_threads = True


class ThreadedUDP(socketserver.ThreadingUDPServer):
    allow_reuse_address = True
    daemon_threads = True


def main():
    os.umask(0)
    results_dir()
    results_dir("marker")
    for name in ("ha-command-log.txt", "ha-reject-log.txt", "ha-events.jsonl"):
        p = os.path.join(RESULTS, name)
        if not os.path.exists(p):
            open(p, "a").close()
            try:
                os.chmod(p, 0o666)
            except OSError:
                pass

    servers = []
    for offset, role, transports in PORT_MAP:
        port = BASE_PORT + offset
        if "tcp" in transports:
            s = ThreadedTCP((BIND, port), TCPHandler)
            s.role = role
            s.port = port
            servers.append(s)
        if "udp" in transports:
            s = ThreadedUDP((BIND, port), UDPHandler)
            s.role = role
            s.port = port
            servers.append(s)

    for s in servers:
        t = threading.Thread(target=s.serve_forever, daemon=True)
        t.start()

    manifest = {
        "product": PRODUCT,
        "version": VERSION,
        "mode": MODE,
        "protocol_version": PROTO_VERSION,
        "magic": MAGIC.decode(),
        "fields": FIELDS,
        "validated_fields": sorted({f for m in COMMANDS for f in validated_fields(m)}),
        "exec_layer": "argv" if MODE == "fixed" else "shell",
        "listeners": [
            {"port": s.port, "role": s.role, "transport": "udp" if isinstance(s, ThreadedUDP) else "tcp"}
            for s in servers
        ],
        "pid": os.getpid(),
        "uid": os.getuid(),
    }
    with open(os.path.join(RESULTS, "ha-manifest.json"), "w", encoding="utf-8") as fh:
        json.dump(manifest, fh, indent=2, sort_keys=True)
    # The results volume is shared by the three models, so the manifest is also written
    # under a per-mode name.
    with open(os.path.join(RESULTS, "ha-manifest-%s.json" % MODE), "w", encoding="utf-8") as fh:
        json.dump(manifest, fh, indent=2, sort_keys=True)

    print("[fortimail-ha] product=%s version=%s mode=%s results=%s" % (PRODUCT, VERSION, MODE, RESULTS),
          flush=True)
    for s in servers:
        print("[fortimail-ha] listening %s:%d role=%s"
              % ("udp" if isinstance(s, ThreadedUDP) else "tcp", s.port, s.role), flush=True)

    try:
        while True:
            time.sleep(3600)
    except KeyboardInterrupt:
        pass
    finally:
        for s in servers:
            s.shutdown()


if __name__ == "__main__":
    main()
