#!/usr/bin/env python3
"""
CVE-2026-126147 -- model of the FortiMail management-interface API
(Fortinet PSIRT FG-IR-26-199, CWE-22 path traversal).

FortiMail is proprietary.  Nothing of Fortinet is redistributed here.  What this file
is, is a *model* of the security-relevant behaviour of the FortiMail management
interface: a set of unauthenticated API endpoints that accept a caller-supplied path
component and write a file underneath a restricted data directory.

The behaviour is selected with FML_MODE so that the vulnerable and the patched build
differ only in the target component:

    FML_MODE=vuln           FortiMail 8.0.1 model -- the caller-supplied path is
                            joined to the restricted root without normalisation, so
                            "../" escapes the directory (CVE-2026-126147).
    FML_MODE=fixed          FortiMail 8.0.2 model -- the resolved path is compared
                            against the restricted root and every write and read that
                            leaves it is refused.
    FML_MODE=fixed-partial  A remediation *shape* that compares the un-normalised
                            joined path against the root with a string prefix test.
                            The prefix test passes for "store/../../etc/x" and the
                            traversal survives.  This arm exists to give the sweep a
                            real target; it is not a claim about the vendor's patch.

The endpoints modelled here:

    GET  /                                  the management interface root
    GET  /api/v1/version                   the version banner
    POST /api/v1/attachment/upload         JSON  {"filename": ..., "content_b64": ...}
    POST /api/v1/config/import             multipart/form-data, "filename" part
    POST /api/v1/ibe/key                   JSON  {"name": ..., "content_b64": ...}
    GET  /api/v1/attachment/download?path= the read direction of the same class

The write endpoints are unauthenticated: the advisory rates the flaw
AV:N/AC:L/PR:N/UI:N, and the model reproduces that by serving the API without an
authentication gate.

Two details of the model are worth calling out, because both of them are properties of
the appliance rather than of the exploit:

  * the interface decodes the caller-supplied path a second time before using it, so
    a percent-encoded traversal is decoded twice in total;
  * the restricted data directory contains a linked data directory ("shared-link")
    that points at the appliance's script directory.

The appliance is modelled as running its service account as root, which is the case on
the real product, and a file that lands in the appliance's script directory is executed
by the maintenance task runner.  That is the execution sink that turns the path
traversal into "execute unauthorized code or commands".
"""

import base64
import binascii
import json
import os
import re
import ssl
import subprocess
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs, unquote

MODE = os.environ.get("FML_MODE", "vuln")
ROOT = os.environ.get("FML_ROOT", "/opt/lab/store")
EXEC_DIR = os.environ.get("FML_EXEC_DIR", "/opt/lab/exec")
RESULTS = os.environ.get("FML_RESULTS", "/results")
PORT = int(os.environ.get("FML_PORT", "443"))
PORT_ALT = int(os.environ.get("FML_PORT_ALT", "8080"))
CERT = os.environ.get("FML_CERT", "/opt/lab/server.pem")

VERSION = {"vuln": "8.0.1", "fixed": "8.0.2", "fixed-partial": "8.0.2"}[MODE]

ACCESS_LOG = os.path.join(RESULTS, "http-access.log")
EXEC_LOG = os.path.join(RESULTS, "exec-log.txt")
WRITE_LOG = os.path.join(RESULTS, "write-log.txt")
SECRET_FILE = "/opt/lab/outside-secret.txt"
SECRET = b"FORTIMAIL-OUTSIDE-SECRET"
UPLOAD_PATH = "/api/v1/attachment/upload"
IBE_PATH = "/api/v1/ibe/key"
IMPORT_PATH = "/api/v1/config/import"
DOWNLOAD_PATH = "/api/v1/attachment/download"

_lock = threading.Lock()


def log_line(path, text):
    try:
        with _lock:
            with open(path, "a") as fh:
                fh.write(text.rstrip("\n") + "\n")
    except OSError:
        pass


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


# --------------------------------------------------------------------------- paths
#
# The three path handlers below are the whole of the vulnerability.  They are kept
# side by side so that the difference between the vulnerable build and the patched
# build is one screen of code.


def _decode(name):
    """The management interface decodes the caller-supplied path a second time
    before using it, and the path handling truncates at a NUL byte the way a C
    implementation of it does."""
    if not isinstance(name, str):
        return ""
    name = unquote(name)
    idx = name.find("\x00")
    if idx >= 0:
        name = name[:idx]
    return name


def _inside(path):
    try:
        root = os.path.realpath(ROOT)
        real = os.path.realpath(path)
    except (OSError, ValueError):
        return False
    return real == root or real.startswith(root + os.sep)


def resolve_write(name):
    """Return (target_path, error) for a caller-supplied file name.

    vuln           -> no normalisation at all; the traversal is carried through to
                      the file system.
    fixed          -> the path is resolved and must stay inside the restricted root.
    fixed-partial  -> the *un-normalised* joined path is compared with a string
                      prefix test, which "store/../../etc/x" passes.
    """
    name = _decode(name)
    if MODE == "vuln":
        # FortiMail 8.0.1 model: the caller-supplied name is appended to the
        # restricted root and handed to the file system as it is.
        try:
            return os.path.join(ROOT, name), None
        except (OSError, ValueError) as exc:
            return None, "invalid path: %s" % exc

    if MODE == "fixed-partial":
        # Remediation shape: a prefix test on the joined string.
        target = os.path.join(ROOT, name)
        if not target.startswith(ROOT):
            return None, "path outside the restricted directory"
        return target, None

    # FortiMail 8.0.2 model: resolve, then require containment.
    try:
        target = os.path.realpath(os.path.join(ROOT, name))
    except (OSError, ValueError) as exc:
        return None, "invalid path: %s" % exc
    if not _inside(target):
        return None, "path outside the restricted directory"
    return target, None


def resolve_read(name):
    """The read direction of the same class.  The fix has to cover it too."""
    name = _decode(name)
    if MODE == "vuln":
        try:
            return os.path.join(ROOT, name), None
        except (OSError, ValueError) as exc:
            return None, "invalid path: %s" % exc
    if MODE == "fixed-partial":
        target = os.path.join(ROOT, name)
        if not target.startswith(ROOT):
            return None, "path outside the restricted directory"
        return target, None
    try:
        target = os.path.realpath(os.path.join(ROOT, name))
    except (OSError, ValueError) as exc:
        return None, "invalid path: %s" % exc
    if not _inside(target):
        return None, "path outside the restricted directory"
    return target, None


def write_file(target, data):
    parent = os.path.dirname(target)
    try:
        if parent:
            os.makedirs(parent, exist_ok=True)
        with open(target, "wb") as fh:
            fh.write(data)
    except (OSError, ValueError) as exc:
        return "write failed: %s" % exc
    return None


def record_write(route, name, target, err):
    resolved = target
    escaped = False
    if target:
        try:
            resolved = os.path.realpath(target)
        except (OSError, ValueError):
            pass
        escaped = not _inside(target)
    log_line(WRITE_LOG, json.dumps({
        "ts": now(),
        "route": route,
        "path": name,
        "resolved": resolved,
        "escaped": escaped,
        "error": err,
    }, sort_keys=True))


def run_if_executed(target):
    """The appliance's maintenance task runner executes what lands in the script
    directory.  This is the sink that turns the traversal into code execution."""
    try:
        real = os.path.realpath(target)
        execroot = os.path.realpath(EXEC_DIR)
    except OSError:
        return
    if not (real.startswith(execroot + os.sep) or real == execroot):
        return
    try:
        proc = subprocess.run(
            ["/bin/sh", real],
            capture_output=True,
            timeout=20,
        )
        out = proc.stdout.decode("utf-8", "replace")
        err = proc.stderr.decode("utf-8", "replace")
        rc = proc.returncode
    except Exception as exc:  # pragma: no cover
        out, err, rc = "", repr(exc), -1
    log_line(EXEC_LOG, "executed %s rc=%s" % (real, rc))
    log_line(EXEC_LOG, "--- stdout of %s ---\n%s" % (real, out))
    log_line(EXEC_LOG, "--- stderr of %s ---\n%s" % (real, err))


# ---------------------------------------------------------------------- multipart


def parse_multipart(body, content_type):
    """Minimal multipart/form-data parser: returns {part-name: (filename, bytes)}."""
    m = re.search(r'boundary="?([^";]+)"?', content_type or "", re.I)
    if not m:
        return None
    boundary = ("--" + m.group(1)).encode()
    fields = {}
    for chunk in body.split(boundary):
        chunk = chunk.strip(b"\r\n")
        if not chunk or chunk == b"--":
            continue
        head, sep, data = chunk.partition(b"\r\n\r\n")
        if not sep:
            continue
        headers = head.decode("utf-8", "replace")
        name = None
        filename = None
        for line in headers.splitlines():
            if line.lower().startswith("content-disposition:"):
                nm = re.search(r'name="([^"]*)"', line)
                fn = re.search(r'filename="([^"]*)"', line)
                if nm:
                    name = nm.group(1)
                if fn:
                    filename = fn.group(1)
        if name is None:
            continue
        fields[name] = (filename, data)
    return fields


# ------------------------------------------------------------------------- handler


class Handler(BaseHTTPRequestHandler):
    server_version = "FortiMail/" + VERSION
    sys_version = ""

    def log_message(self, fmt, *args):  # silence the default stderr logging
        pass

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

    def _json(self, code, obj):
        body = json.dumps(obj, indent=2, sort_keys=True).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Server", self.server_version)
        self.end_headers()
        self.wfile.write(body)

    def _read_body(self):
        length = int(self.headers.get("Content-Length") or 0)
        return self.rfile.read(length) if length else b""

    def _record(self, note):
        log_line(ACCESS_LOG, "%s %s %s %s" % (
            self.command, self.path, note, self.headers.get("User-Agent", "-")))

    # -- GET -------------------------------------------------------------------

    def do_GET(self):
        parsed = urlparse(self.path)
        route = parsed.path

        if route == "/":
            body = (
                "<html><head><title>FortiMail %s</title></head><body>"
                "<h1>FortiMail %s</h1><p>Web admin interface.</p>"
                "</body></html>" % (VERSION, VERSION)
            ).encode()
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Server", self.server_version)
            self.end_headers()
            self.wfile.write(body)
            return

        if route == "/api/v1/version":
            self._record("version")
            self._json(200, {"product": "FortiMail", "version": VERSION, "mode": MODE})
            return

        if route == DOWNLOAD_PATH:
            params = parse_qs(parsed.query)
            name = (params.get("path") or params.get("filename") or [""])[0]
            self._record("download name=%r" % name)
            if not name:
                self._json(400, {"error": "missing path"})
                return
            target, err = resolve_read(name)
            if err:
                self._json(403, {"error": err, "path": name})
                return
            try:
                with open(target, "rb") as fh:
                    data = fh.read()
            except (OSError, ValueError) as exc:
                self._json(404, {"error": "not readable: %s" % exc, "path": name})
                return
            self._json(200, {"path": name, "size": len(data),
                             "content_b64": base64.b64encode(data).decode()})
            return

        self._json(404, {"error": "not found"})

    # -- POST ------------------------------------------------------------------

    def do_POST(self):
        parsed = urlparse(self.path)
        route = parsed.path
        body = self._read_body()

        if route in (UPLOAD_PATH, IBE_PATH):
            key = "name" if route == IBE_PATH else "filename"
            name, data, err = self._json_upload(body, key=key)
            if err:
                self._record("%s %s" % (route, err))
                self._json(400, {"error": err})
                return
            self._record("%s name=%r bytes=%d" % (route, name, len(data)))
            target, perr = resolve_write(name)
            record_write(route, name, target, perr)
            if perr:
                self._json(403, {"error": perr, "path": name})
                return
            werr = write_file(target, data)
            if werr:
                self._json(500, {"error": werr})
                return
            run_if_executed(target)
            self._json(200, {"stored": name, "bytes": len(data)})
            return

        if route == IMPORT_PATH:
            fields = parse_multipart(body, self.headers.get("Content-Type"))
            if not fields or "filename" not in fields:
                self._record("import malformed")
                self._json(400, {"error": "multipart form with a filename part is required"})
                return
            filename = fields["filename"][0] or ""
            data = fields.get("content", (None, b""))[1]
            self._record("import name=%r bytes=%d" % (filename, len(data)))
            target, perr = resolve_write(filename)
            record_write(route, filename, target, perr)
            if perr:
                self._json(403, {"error": perr, "path": filename})
                return
            werr = write_file(target, data)
            if werr:
                self._json(500, {"error": werr})
                return
            run_if_executed(target)
            self._json(200, {"imported": filename, "bytes": len(data)})
            return

        self._json(404, {"error": "not found"})

    # -- body helpers ----------------------------------------------------------

    def _json_upload(self, body, key="filename"):
        try:
            doc = json.loads(body.decode("utf-8", "replace"))
        except ValueError as exc:
            return None, b"", "invalid json: %s" % exc
        if not isinstance(doc, dict):
            return None, b"", "json object expected"
        name = doc.get(key)
        if not isinstance(name, str) or not name:
            return None, b"", "'%s' is required" % key
        raw = doc.get("content_b64")
        if isinstance(raw, str):
            try:
                data = base64.b64decode(raw, validate=False)
            except (binascii.Error, ValueError) as exc:
                return None, b"", "invalid base64: %s" % exc
        elif raw is None:
            data = b""
        else:
            data = str(raw).encode()
        return name, data, None


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

def make_server(port):
    httpd = ThreadingHTTPServer(("0.0.0.0", port), Handler)
    httpd.daemon_threads = True
    return httpd


def main():
    os.makedirs(ROOT, exist_ok=True)
    os.makedirs(EXEC_DIR, exist_ok=True)
    os.makedirs(os.path.join(RESULTS, "marker"), exist_ok=True)

    # a file that lives outside the restricted directory: the read-direction probe
    with open(SECRET_FILE, "wb") as fh:
        fh.write(SECRET)

    # the linked data directory: a symlink inside the store that points at the
    # appliance script directory
    link = os.path.join(ROOT, "shared-link")
    if not os.path.lexists(link):
        try:
            os.symlink(EXEC_DIR, link)
        except OSError:
            pass

    servers = []
    srv = make_server(PORT_ALT)
    servers.append(srv)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    sys.stdout.write("[fml] mode=%s version=%s listening on :%d (plain)\n"
                     % (MODE, VERSION, PORT_ALT))
    sys.stdout.flush()

    if os.path.exists(CERT):
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        ctx.load_cert_chain(CERT)
        srv = make_server(PORT)
        srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
        servers.append(srv)
        threading.Thread(target=srv.serve_forever, daemon=True).start()
        sys.stdout.write("[fml] mode=%s version=%s listening on :%d (tls)\n"
                         % (MODE, VERSION, PORT))
    else:
        sys.stdout.write("[fml] mode=%s version=%s: no certificate at %s, "
                         "TLS listener not started\n" % (MODE, VERSION, CERT))
    sys.stdout.flush()

    while True:
        threading.Event().wait(3600)


if __name__ == "__main__":
    main()
