#!/usr/bin/env python3
"""fortigate_config_check.py: read an exported FortiGate configuration and report the settings that the
FBI / US Secret Service advisory on FortiBleed (JCSA-20261006-01, 6 October 2026) asks owners to review.

Runs offline. Standard library only. It reads the file you give it and prints a report; it sends nothing anywhere.

    python3 fortigate_config_check.py fortigate.conf

What it reads: interfaces, admins, API users, local users, SSL-VPN settings, local-in policies, firewall policies.
What it cannot tell you: anything that is not in the export (sessions, logs, source addresses, hit counts), and
whether a setting was changed by you or by someone else. A clean report is not evidence that a firewall was never
accessed. Source: https://www.ic3.gov/CSA/2026/261006.pdf

From CyberTwin (https://cybertwin.io). MIT licence.
"""
import re
import sys

# Usernames the advisory lists as found on compromised devices (Table 2). "admin" is on the list too, but it is
# also the default name, so its presence says nothing either way and it is reported separately.
ADVISORY_NAMES = {
    "adminin", "fortiadmin", "forticloud-sync", "fgtsecure", "pakedge", "forticloud-tech", "districtadmin",
    "system_config", "gttadmin", "roadmin", "itadmin", "technical_support", "adminsslvpn", "it_manager",
    "my_admin", "support_fortinet", "fgtsec", "forti_support2",
}
ADMIN_SERVICES = {"https", "http", "ssh", "telnet"}


def tokens(line):
    """Split a config line into words, keeping quoted strings whole."""
    return [a if a else b for a, b in re.findall(r'"([^"]*)"|(\S+)', line)]


def parse(text):
    """Return {section path: {entry name: {key: [values]}}} for 'config ... edit ... set ... next end' blocks.
    Nested config blocks inside an entry are stored under the key 'config <name>' as a list of their set lines."""
    sections = {}
    stack = []          # open 'config' names
    entry = None        # current entry dict at depth 1
    for raw in text.splitlines():
        t = tokens(raw.strip())
        if not t:
            continue
        if t[0] == "config":
            stack.append(" ".join(t[1:]))
            if len(stack) == 1:
                sections.setdefault(stack[0], {})
                entry = None
            elif entry is not None:
                entry.setdefault("config " + stack[-1], [])
        elif t[0] == "end":
            if stack:
                stack.pop()
            if not stack:
                entry = None
        elif t[0] == "edit" and len(stack) == 1:
            entry = sections[stack[0]].setdefault(t[1] if len(t) > 1 else "", {})
        elif t[0] == "next" and len(stack) == 1:
            entry = None
        elif t[0] == "set" and len(t) >= 2:
            if len(stack) == 1:
                target = entry if entry is not None else sections[stack[0]].setdefault("", {})
                target[t[1]] = t[2:]
            elif entry is not None:
                entry["config " + stack[-1]].append(t[1:])
    return sections


def main(path):
    with open(path, encoding="utf-8", errors="replace") as f:
        text = f.read()
    cfg = parse(text)
    findings, notes = [], []

    def finding(title, items, why):
        if items:
            findings.append((title, items, why))

    first = text.splitlines()[0] if text else ""
    m = re.match(r"#config-version=([^:]+)", first)
    notes.append("Model and firmware (top line of the file): " + (m.group(1) if m else "not found in this file"))

    # 1. Admin services on internet-facing interfaces
    exposed = []
    for name, e in cfg.get("system interface", {}).items():
        services = ADMIN_SERVICES & {v.lower() for v in e.get("allowaccess", [])}
        outside = e.get("role", [""])[0].lower() == "wan" or re.search(r"wan|internet|outside|isp|untrust", name, re.I)
        if services and outside:
            exposed.append(f'{name}: set allowaccess {" ".join(e["allowaccess"])}')
    finding("Admin services on an internet-facing interface", exposed,
            "The advisory: restrict external management (trusted hosts, a local-in policy, or no internet administration).")

    # 2-4. Administrators
    admins = cfg.get("system admin", {})
    finding("Administrators with no trusted hosts", [n for n, e in admins.items() if not any(k.startswith("trusthost") or k.startswith("ip6-trusthost") for k in e)],
            "An admin with no trusthost line can log in from anywhere the login page is reachable.")
    finding("Administrators with no second factor", [n for n, e in admins.items() if e.get("two-factor", ["disable"])[0] == "disable" and "remote-auth" not in e],
            "The advisory: require multifactor authentication on all administrative users. (Admins who sign in through a remote server are not listed here; check the second factor on that side.)")
    finding("Administrator names that appear in the advisory's list", [n for n in admins if n.lower() in ADVISORY_NAMES],
            "These names were found on compromised devices. If you did not create the entry, start incident response before changing anything.")
    if "admin" in {n.lower() for n in admins}:
        notes.append('An administrator named "admin" exists. It is the default name and is also on the advisory\'s list, so this tells you nothing either way.')
    notes.append(f"Administrators in the file ({len(admins)}): " + (", ".join(sorted(admins)) or "none found") + ". Each should be one you can name.")

    # 5. API users
    api = cfg.get("system api-user", {})
    finding("API users with no trusted hosts", [n for n, e in api.items() if not e.get("config trusthost")],
            "The advisory: review every REST API key, remove the ones nobody can explain, refresh the rest.")
    if api:
        notes.append(f"API users in the file ({len(api)}): " + ", ".join(sorted(api)) + ". Each key should have an owner and a purpose.")

    # 6. SSL-VPN
    vpn = cfg.get("vpn ssl settings", {}).get("", {})
    if vpn.get("source-interface"):
        src = [v.lower() for v in vpn.get("source-address", [])]
        if not src or "all" in src:
            finding("SSL-VPN login answers every address", [f'source-interface {" ".join(vpn["source-interface"])}, source-address {" ".join(vpn.get("source-address", ["(not set: all)"]))}'],
                    "The password guessing in this campaign happens at exposed VPN portals. List the countries or ranges your users connect from.")

    # 7. Local users
    users = cfg.get("user local", {})
    finding("Local users with a password and no second factor", [n for n, e in users.items() if e.get("type", ["password"])[0] == "password" and e.get("two-factor", ["disable"])[0] == "disable" and e.get("status", ["enable"])[0] != "disable"],
            "The advisory: require multifactor authentication on all remote access. Users who sign in through RADIUS or SAML are checked on that side.")
    if users:
        notes.append(f"Local users in the file: {len(users)}. Read the list for names you do not expect.")

    # 8. Local-in policy
    if not cfg.get("firewall local-in-policy"):
        notes.append("No local-in policy in the file. The advisory rates a local-in policy above trusted hosts for restricting management access.")

    # 9. Policies
    anyany, nolog = [], []
    for pid, e in cfg.get("firewall policy", {}).items():
        if e.get("action", ["deny"])[0] != "accept" or e.get("status", ["enable"])[0] == "disable":
            continue
        label = f'policy {pid}' + (f' "{e["name"][0]}"' if e.get("name") else "") + f' ({" ".join(e.get("srcintf", []))} to {" ".join(e.get("dstintf", []))})'
        if all("all" in [v.lower() for v in e.get(k, [])] for k in ("srcaddr", "dstaddr", "service")):
            anyany.append(label)
        if e.get("logtraffic", [""])[0] == "disable":
            nolog.append(label)
    finding("Policies that allow any source, any destination and any service", anyany,
            "If someone does get in, these decide how far they can go.")
    finding("Accept policies that log nothing", nolog,
            "The advisory asks you to review logs for unusual access; these rules leave none.")

    print(f"FortiGate config check: {path}")
    print("Based on the FBI / US Secret Service advisory JCSA-20261006-01 (FortiBleed), 6 October 2026.\n")
    if findings:
        print(f"{len(findings)} thing(s) to look at:\n")
        for i, (title, items, why) in enumerate(findings, 1):
            print(f"{i}. {title} ({len(items)})")
            for it in items[:25]:
                print(f"     - {it}")
            if len(items) > 25:
                print(f"     ... and {len(items) - 25} more")
            print(f"   Why: {why}\n")
    else:
        print("Nothing on this list was found in the file.\n")
    print("Also worth knowing:")
    for n in notes:
        print(f" - {n}")
    print("\nNot in the export, so not checked: active sessions, logs, source addresses, password hash strength,")
    print("and whether any setting was changed by someone else. The advisory also asks you to terminate all admin")
    print("and VPN sessions, reset all VPN and admin passwords, and review logs against the addresses it lists.")
    print("\nWhich of these rules let the internet reach internal systems, and the one change that closes the most")
    print("routes: https://cybertwin.io/firewall-audit/fortinet-fortigate")
    return 1 if findings else 0


if __name__ == "__main__":
    if len(sys.argv) != 2 or sys.argv[1] in ("-h", "--help"):
        print(__doc__)
        sys.exit(2)
    sys.exit(main(sys.argv[1]))
