#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Titanward — Legacy & Ancient Infrastructure Initial Assessor.

Single-file, zero-dependency polyglot collector compatible from Python 2.6 / 2.7
all the way through Python 3.15+ (CentOS 5/6/7, RHEL 5/6/7, Debian 6/7/8/9,
Ubuntu 12.04/14.04/16.04, Solaris/BSD, and legacy Windows Server 2008 R2/2012).

Ancient-server safety airbags enforced in code:
  1. 100% read-only; zero files modified outside the output report directory.
  2. Zero full-disk walks (never touches stale NFS/CIFS mounts that hang legacy kernels).
  3. Hard per-command watchdog timer (default 4s) + nice(15) low CPU priority.
  4. Zero secrets touched (.env*, *.key, *.pem, id_*, /etc/shadow strictly off-limits).
  5. Distinguishes SAFE IN-PLACE fixes from DO-NOT-UPGRADE-IN-PLACE systems that
     must be isolated behind a private VLAN + Post-Quantum Translating Gateway.
"""
from __future__ import print_function

import hashlib
import os
import platform
import re
import socket
import stat
import subprocess
import sys
import threading
import time

try:
    import json
except ImportError:
    json = None  # Python <2.6 fallback handled below if ever encountered

COLLECTOR_NAME = "titanward-assess-legacy.py"
COLLECTOR_VERSION = "1.0.0"
SCHEMA_ID = "titanward.assessment.v1"

EXCLUDED_SECRET_GLOBS = [
    ".env*", "*.pem", "*.key", "*.pfx", "*.p12", "*.kdbx", "*.jks",
    "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "/etc/shadow",
    "credentials*", "*secret*", "*wallet*", "*seed*", "*mnemonic*",
]

SECRET_PATTERNS = [
    re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----"),
    re.compile(r"\bAGE-SECRET-KEY-(?:PQ-)?1[A-Z0-9]{20,}\b"),
    re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
    re.compile(r"(?i)(password|passwd|secret|api[_-]?key|token)\s*[:=]\s*['\"]?[^\s'\";,]{4,}"),
    re.compile(r"(?i)(--password|--token|--secret|-p)\s+\S+"),
    re.compile(r"://[^/\s:@]+:[^/\s@]+@"),
]

LEGACY_EXPOSED_PORTS = {
    21: ("FTP cleartext file transfer", "critical"),
    23: ("Telnet cleartext remote shell", "critical"),
    80: ("Unencrypted HTTP listener", "medium"),
    111: (" SunRPC / portmapper", "high"),
    139: ("NetBIOS / legacy SMB", "high"),
    445: ("SMB file sharing (check SMBv1 EternalBlue exposure)", "critical"),
    502: ("Modbus TCP industrial protocol (unauthenticated)", "critical"),
    512: ("rexec cleartext remote execution", "critical"),
    513: ("rlogin cleartext login", "critical"),
    514: ("rsh / unencrypted syslog", "high"),
    1433: ("MSSQL database listener", "high"),
    1521: ("Oracle TNS database listener", "high"),
    3306: ("MySQL database listener", "high"),
    3389: ("Legacy RDP remote desktop", "high"),
    5432: ("PostgreSQL database listener", "high"),
    5900: ("VNC remote desktop", "high"),
    6379: ("Redis datastore", "critical"),
}


class ScrubState(object):
    def __init__(self):
        self.count = 0

    def scrub(self, raw):
        if not raw:
            return ""
        if not isinstance(raw, str):
            try:
                raw = raw.decode("utf-8", "replace")
            except Exception:
                raw = str(raw)
        out = raw
        for pat in SECRET_PATTERNS:
            out, n = pat.subn("[REDACTED-BY-SHIELD]", out)
            self.count += n
        return out


def to_bytes(text):
    if sys.version_info[0] >= 3:
        if isinstance(text, bytes):
            return text
        return text.encode("utf-8", "replace")
    if isinstance(text, str):
        return text
    return text.encode("utf-8", "replace")


def read_small_text(path, scrubber, max_bytes=131072):
    base = os.path.basename(path).lower()
    if base.startswith(".env") or base in ("shadow", "gshadow", "master.passwd"):
        return ""
    if not os.path.isfile(path) or os.path.islink(path):
        return ""
    try:
        fh = open(path, "rb")
        try:
            raw = fh.read(max_bytes)
        finally:
            fh.close()
        if sys.version_info[0] >= 3:
            txt = raw.decode("utf-8", "replace")
        else:
            txt = raw
        return scrubber.scrub(txt)
    except Exception:
        return ""


def find_executable(name):
    if os.path.isabs(name):
        return name if (os.path.isfile(name) and os.access(name, os.X_OK)) else None
    search_dirs = os.environ.get("PATH", "").split(os.pathsep)
    for extra in ("/sbin", "/usr/sbin", "/usr/local/sbin", "/usr/local/bin", "/bin", "/usr/bin"):
        if extra not in search_dirs:
            search_dirs.append(extra)
    exts = [""]
    if os.name == "nt":
        exts = [".exe", ".cmd", ".bat", ""]
    for d in search_dirs:
        if not d:
            continue
        for ext in exts:
            cand = os.path.join(d, name + ext)
            if os.path.isfile(cand) and os.access(cand, os.X_OK):
                return cand
    return None


def run_timed(argv, timeout_sec, scrubber):
    exe = find_executable(argv[0])
    if not exe:
        return 127, ""
    cmd = [exe] + list(argv[1:])
    killed = [False]

    def _kill(proc):
        killed[0] = True
        try:
            proc.kill()
        except Exception:
            pass

    try:
        devnull = open(os.devnull, "rb")
        try:
            proc = subprocess.Popen(
                cmd,
                stdin=devnull,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            timer = threading.Timer(float(timeout_sec), _kill, [proc])
            timer.daemon = True
            timer.start()
            try:
                out_b, err_b = proc.communicate()
            finally:
                timer.cancel()
        finally:
            devnull.close()
        if killed[0]:
            return 124, ""
        combined = ""
        if out_b:
            combined += scrubber.scrub(out_b)
        if err_b:
            if combined:
                combined += "\n"
            combined += scrubber.scrub(err_b)
        return proc.returncode, combined.strip()
    except Exception:
        return 125, ""


def parse_cli_args(argv):
    opts = {
        "out": "./shield-assessment-out",
        "label": "",
        "scan_dir": "",
        "timeout": 4,
    }
    i = 0
    while i < len(argv):
        arg = argv[i]
        if arg in ("-h", "--help"):
            print("Usage: python titanward-assess-legacy.py [--out DIR] [--label NAME] [--scan-dir DIR] [--timeout SEC]")
            sys.exit(0)
        elif arg == "--out" and i + 1 < len(argv):
            opts["out"] = argv[i + 1]
            i += 2
        elif arg == "--label" and i + 1 < len(argv):
            opts["label"] = argv[i + 1]
            i += 2
        elif arg == "--scan-dir" and i + 1 < len(argv):
            opts["scan_dir"] = argv[i + 1]
            i += 2
        elif arg == "--timeout" and i + 1 < len(argv):
            try:
                opts["timeout"] = max(1, int(argv[i + 1]))
            except ValueError:
                opts["timeout"] = 4
            i += 2
        else:
            i += 1
    return opts


def detect_privilege():
    if os.name == "nt":
        return "user"
    if hasattr(os, "geteuid"):
        try:
            return "root" if os.geteuid() == 0 else "user"
        except Exception:
            return "user"
    return "user"


def detect_legacy_os(timeout_sec, scrubber):
    sys_name = platform.system().lower()
    arch = platform.machine() or "unknown"
    kernel = platform.release() or "unknown"
    os_family = "unix"
    distro = platform.platform()
    version = platform.version()
    eol_status = "supported"
    eol_detail = "Release appears supported; verify vendor patch stream."

    if sys_name == "linux":
        os_family = "linux"
        # Check ancient release files first (/etc/redhat-release, /etc/centos-release, /etc/debian_version)
        rh = read_small_text("/etc/redhat-release", scrubber).strip()
        deb = read_small_text("/etc/debian_version", scrubber).strip()
        osr = read_small_text("/etc/os-release", scrubber)
        if osr:
            kv = {}
            for ln in osr.splitlines():
                if "=" in ln and not ln.startswith("#"):
                    k, v = ln.split("=", 1)
                    kv[k.strip()] = v.strip().strip('"').strip("'")
            distro = kv.get("PRETTY_NAME", distro)
            version = kv.get("VERSION_ID", version)
        elif rh:
            distro = rh.splitlines()[0]
            m = re.search(r"(\d+(?:\.\d+)?)", distro)
            if m:
                version = m.group(1)
        elif deb:
            distro = "Debian " + deb.splitlines()[0]
            version = deb.splitlines()[0]

        low_distro = distro.lower()
        # Kernel <= 4.14 or classic EOL distros -> mark EOL
        k_parts = kernel.split(".")
        if len(k_parts) >= 2 and k_parts[0].isdigit() and k_parts[1].isdigit():
            kmaj, kmin = int(k_parts[0]), int(k_parts[1])
            if kmaj < 4 or (kmaj == 4 and kmin < 18):
                eol_status = "eol"
                eol_detail = "Legacy Linux kernel %s is End-of-Life." % kernel

        if any(tag in low_distro for tag in ("centos release 5", "centos release 6", "centos linux 7", "red hat enterprise linux server release 5", "release 6.", "ubuntu 10.", "ubuntu 12.", "ubuntu 14.", "ubuntu 16.", "ubuntu 18.", "debian 6", "debian 7", "debian 8", "debian 9", "debian 10", "suse linux enterprise server 10", "suse linux enterprise server 11")):
            eol_status = "eol"
            eol_detail = "%s is past vendor End-of-Life." % distro

    elif sys_name == "darwin":
        os_family = "macos"
        rc, out = run_timed(["sw_vers"], timeout_sec, scrubber)
        for ln in out.splitlines():
            if "ProductVersion:" in ln:
                version = ln.split(":", 1)[1].strip()
        distro = "macOS " + version
        vmaj = version.split(".")[0]
        if vmaj.isdigit() and int(vmaj) < 13:
            eol_status = "eol"
            eol_detail = "macOS %s is End-of-Life." % version

    elif sys_name == "windows":
        os_family = "windows"
        win_rel, win_ver, _, _ = platform.win32_ver()
        distro = "Windows %s (%s)" % (win_rel, win_ver)
        version = win_ver or win_rel
        if any(x in win_rel for x in ("2003", "2008", "2012", "XP", "Vista", "7", "8")):
            eol_status = "eol"
            eol_detail = "%s is End-of-Life." % distro

    elif sys_name in ("sunos", "solaris", "aix", "hp-ux", "freebsd"):
        os_family = "unix"
        if sys_name in ("sunos", "aix", "hp-ux"):
            eol_status = "approaching_eol"
            eol_detail = "Legacy Unix platform (%s %s); prefer gateway containment over binary replacement." % (sys_name, kernel)

    if sys.version_info[0] == 2 and eol_status == "supported":
        eol_status = "eol"
        eol_detail = "Host relies on End-of-Life Python %s userland." % platform.python_version()

    strategy = "isolate_behind_pq_gateway" if eol_status == "eol" else "in_place_upgrade"
    if strategy == "isolate_behind_pq_gateway":
        reason = "DO NOT UPGRADE CRYPTO/LIBC IN PLACE: Legacy OS/kernel risks breaking line-of-business software. Isolate on a private VLAN and front with a WireGuard PQ-PSK or TLS 1.3 X25519MLKEM768 gateway."
    else:
        reason = "Userland is patchable; stage configuration fixes with rollback backups."

    return {
        "os_family": os_family,
        "os_distro": distro,
        "os_version": version,
        "kernel": kernel,
        "arch": arch,
        "eol_status": eol_status,
        "eol_detail": eol_detail,
        "remediation_strategy": strategy,
        "strategy_reason": reason,
    }


def collect_legacy_listeners(timeout_sec, scrubber):
    listeners = []
    seen = set([])

    # Try ss first, then netstat -tulnp / netstat -an, then lsof
    rc, out = run_timed(["ss", "-tuln"], timeout_sec, scrubber)
    if rc == 0 and out:
        for ln in out.splitlines():
            low = ln.lower()
            if "listen" not in low and not low.startswith("udp"):
                continue
            parts = ln.split()
            if len(parts) < 5:
                continue
            proto = parts[0].lower()
            local = parts[4]
            if ":" not in local:
                continue
            bind, port_s = local.rsplit(":", 1)
            bind = bind.strip("[]")
            if "%" in bind:
                bind = bind.split("%", 1)[0]
            if port_s.isdigit():
                port = int(port_s)
                exp = "loopback_only" if bind in ("127.0.0.1", "::1", "localhost") else "public_or_lan"
                key = (proto, bind, port)
                if key not in seen:
                    seen.add(key)
                    listeners.append({"proto": proto, "bind": bind, "port": port, "process": "legacy-socket", "exposure": exp})
        if listeners:
            return sorted(listeners, key=lambda x: x["port"])[:60]

    rc_n, out_n = run_timed(["netstat", "-an"], timeout_sec, scrubber)
    if rc_n == 0 and out_n:
        for ln in out_n.splitlines():
            u = ln.upper()
            if "LISTEN" not in u:
                continue
            parts = ln.split()
            if len(parts) < 4:
                continue
            proto = parts[0].lower()
            local = parts[3]
            # Handle Linux/Windows colon vs BSD/macOS/Solaris dot separator (e.g., *.22 or 0.0.0.0.22)
            bind, port_s = "", ""
            if ":" in local:
                bind, port_s = local.rsplit(":", 1)
            elif "." in local:
                bind, port_s = local.rsplit(".", 1)
            bind = bind.strip("[]")
            if bind == "*":
                bind = "0.0.0.0"
            if port_s.isdigit():
                port = int(port_s)
                exp = "loopback_only" if bind in ("127.0.0.1", "::1", "localhost") else "public_or_lan"
                key = (proto, bind, port)
                if key not in seen:
                    seen.add(key)
                    listeners.append({"proto": proto, "bind": bind, "port": port, "process": "netstat-listener", "exposure": exp})

    return sorted(listeners, key=lambda x: x["port"])[:60]


def check_legacy_firewall(os_family, timeout_sec, scrubber):
    if os_family == "linux":
        rc_u, out_u = run_timed(["ufw", "status"], timeout_sec, scrubber)
        if rc_u == 0 and "status:" in out_u.lower():
            active = "status: active" in out_u.lower()
            return {"status": "enabled" if active else "disabled", "engine": "ufw", "docker_ufw_bypass": False, "detail": out_u.splitlines()[0]}
        rc_i, out_i = run_timed(["iptables", "-L", "-n"], timeout_sec, scrubber)
        if rc_i == 0 and out_i:
            has_drop = ("DROP" in out_i or "REJECT" in out_i)
            return {
                "status": "enabled" if has_drop else "disabled",
                "engine": "iptables",
                "docker_ufw_bypass": False,
                "detail": "iptables rules present" if has_drop else "iptables ACCEPT-all default policy with zero DROP/REJECT rules",
            }
    elif os_family == "macos":
        rc_m, out_m = run_timed(["/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate"], timeout_sec, scrubber)
        if rc_m == 0 and out_m:
            return {"status": "enabled" if "enabled" in out_m.lower() else "disabled", "engine": "macos-alf", "docker_ufw_bypass": False, "detail": out_m.splitlines()[0]}
    return {"status": "unknown", "engine": "none", "docker_ufw_bypass": False, "detail": "Firewall status requires root or host ACL inspection"}


def check_legacy_crypto(timeout_sec, scrubber):
    rc_o, out_o = run_timed(["openssl", "version"], timeout_sec, scrubber)
    openssl_ver = out_o.splitlines()[0] if (rc_o == 0 and out_o) else "unavailable"

    pq_tls = False
    if "OpenSSL 3." in openssl_ver:
        rc_k, out_k = run_timed(["openssl", "list", "-kem-algorithms"], timeout_sec, scrubber)
        if rc_k == 0 and re.search(r"ML-KEM|MLKEM", out_k, re.IGNORECASE):
            pq_tls = True

    legacy_tls_enabled = []
    static_rsa = False
    if any(v in openssl_ver for v in ("OpenSSL 0.9.", "OpenSSL 1.0.0", "OpenSSL 1.0.1", "OpenSSL 1.0.2", "OpenSSL 1.1.0")):
        legacy_tls_enabled = ["TLSv1.0", "TLSv1.1"]
        static_rsa = True

    rc_s, out_s = run_timed(["ssh", "-V"], timeout_sec, scrubber)
    ssh_ver = out_s.splitlines()[0] if out_s else "unavailable"
    if ssh_ver == "unavailable":
        rc_db, out_db = run_timed(["dropbear", "-V"], timeout_sec, scrubber)
        if out_db:
            ssh_ver = out_db.splitlines()[0]

    kex_list = []
    rc_g, out_g = run_timed(["ssh", "-G", "localhost"], timeout_sec, scrubber)
    if rc_g == 0 and out_g:
        for ln in out_g.splitlines():
            if ln.startswith("kexalgorithms "):
                kex_list = [x.strip() for x in ln.split(" ", 1)[1].split(",") if x.strip()]
                break

    pq_ssh = False
    if kex_list:
        for k in kex_list[:2]:
            if "mlkem" in k or "sntrup761" in k:
                pq_ssh = True

    permit_root = "unknown"
    password_auth = "unknown"
    ssh_proto_v1 = False
    sshd_txt = read_small_text("/etc/ssh/sshd_config", scrubber)
    if sshd_txt:
        for raw in sshd_txt.splitlines():
            s = raw.strip()
            if not s or s.startswith("#"):
                continue
            toks = s.lower().split()
            if len(toks) >= 2:
                if toks[0] == "permitrootlogin":
                    permit_root = toks[1]
                elif toks[0] == "passwordauthentication":
                    password_auth = toks[1]
                elif toks[0] == "protocol" and "1" in toks[1]:
                    ssh_proto_v1 = True

    weak_host_keys = []
    if os.path.isdir("/etc/ssh"):
        try:
            for fn in sorted(os.listdir("/etc/ssh")):
                if fn.startswith("ssh_host_") and fn.endswith("_key.pub"):
                    pub_txt = read_small_text(os.path.join("/etc/ssh", fn), scrubber)
                    parts = pub_txt.split()
                    if parts and parts[0] in ("ssh-dss", "ssh-rsa", "rsa1"):
                        weak_host_keys.append("%s:%s" % (fn, parts[0]))
        except Exception:
            pass

    bad_priv_modes = []
    ssh_home = os.path.expanduser("~/.ssh")
    if os.path.isdir(ssh_home):
        try:
            for fn in sorted(os.listdir(ssh_home)):
                full = os.path.join(ssh_home, fn)
                if fn.startswith("id_") and not fn.endswith(".pub") and os.path.isfile(full):
                    mode = stat.S_IMODE(os.stat(full).st_mode)
                    if mode & 63:  # 0o077 in Python 2.6/3 portable decimal!
                        bad_priv_modes.append("~/.ssh/%s:%s" % (fn, oct(mode)))
        except Exception:
            pass

    algos = []
    if openssl_ver != "unavailable":
        algos.append({
            "component": "openssl-runtime",
            "algorithm": openssl_ver,
            "family": "tls-provider",
            "bits": 256 if pq_tls else 112,
            "quantum_status": "hybrid_post_quantum" if pq_tls else "quantum_vulnerable_shor",
            "location": "system openssl",
        })
    if ssh_ver != "unavailable":
        algos.append({
            "component": "ssh-runtime",
            "algorithm": ssh_ver,
            "family": "hybrid-pq" if pq_ssh else "classical-ssh",
            "bits": 256 if pq_ssh else 128,
            "quantum_status": "hybrid_post_quantum" if pq_ssh else "quantum_vulnerable_shor",
            "location": "system ssh",
        })

    return {
        "openssl_version": openssl_ver,
        "pq_tls_capable": pq_tls,
        "tls_legacy_protocols_enabled": legacy_tls_enabled,
        "static_rsa_kex_enabled": static_rsa,
        "ssh": {
            "version": ssh_ver,
            "pq_kex_enabled": pq_ssh,
            "ssh_v1_enabled": ssh_proto_v1,
            "kex_algorithms": kex_list[:6],
            "weak_host_keys": weak_host_keys,
            "weak_user_pubkeys": [],
            "bad_private_key_permissions": bad_priv_modes,
            "permit_root_login": permit_root,
            "password_auth": password_auth,
        },
        "wireguard": {
            "interfaces": [],
            "peers_without_psk": 0,
        },
        "jwt_oidc_algorithms": [],
        "dkim_bits": None,
        "algorithms_observed": algos,
    }


def check_legacy_runtimes_and_persistence(timeout_sec, scrubber):
    runtimes = []
    if sys.version_info[0] == 2:
        runtimes.append("Python %s (End-of-Life since 2020-01)" % platform.python_version())
    rc_j, out_j = run_timed(["java", "-version"], timeout_sec, scrubber)
    if out_j:
        first = out_j.splitlines()[0]
        if any(tag in first for tag in ('"1.4', '"1.5', '"1.6', '"1.7', '"1.8')):
            runtimes.append("Legacy JVM: %s" % first)
    rc_p, out_p = run_timed(["php", "-v"], timeout_sec, scrubber)
    if out_p:
        first = out_p.splitlines()[0]
        if any(tag in first for tag in ("PHP 4.", "PHP 5.", "PHP 7.")):
            runtimes.append("End-of-Life PHP: %s" % first)

    anomalies = []
    susp_re = re.compile(r"(curl\s+.*\|\s*(?:ba)?sh|wget\s+.*\|\s*(?:ba)?sh|/tmp/|/var/tmp/|base64\s+-d)", re.IGNORECASE)
    for cfg in ("/etc/rc.local", "/etc/crontab"):
        txt = read_small_text(cfg, scrubber)
        if txt and susp_re.search(txt):
            anomalies.append({"location": cfg, "reason": "Suspicious temp or pipe shell execution in legacy startup file"})
    return runtimes, anomalies


def build_legacy_findings(host, firewall, listeners, crypto, eol_runtimes, anomalies):
    findings = []
    isolate = (host["remediation_strategy"] == "isolate_behind_pq_gateway")

    if host["eol_status"] == "eol":
        findings.append({
            "id": "SHIELD-LEGACY-EOL-OS",
            "severity": "critical",
            "category": "legacy_isolation",
            "title": "End-of-Life infrastructure (%s) — requires VLAN + Gateway containment" % host["os_distro"],
            "evidence": host["eol_detail"],
            "fix_mode": "gateway_isolation",
            "downtime": "zero_downtime",
            "recommended_fix": "DO NOT attempt in-place glibc/OpenSSL replacement on this host. Execute 7-Step Legacy Containment: place host on dedicated private VLAN, set default-deny egress, and route authorized traffic exclusively through a modern TLS 1.3 (X25519MLKEM768) or WireGuard PQ-PSK gateway.",
            "check_cmd": "aegis crypto stealth-gateway --profile legacy-vlan",
            "verify_cmd": "Verify direct LAN access to legacy IP is blocked except from gateway interface IP",
            "undo_cmd": "Revert switch port VLAN tag and upstream VIP route if needed",
        })

    if any(tag in crypto["openssl_version"] for tag in ("OpenSSL 0.9.", "OpenSSL 1.0.1", "OpenSSL 1.0.0", "OpenSSL 1.0.2")):
        heartbleed_note = " (OpenSSL 1.0.1 branch — verify CVE-2014-0160 Heartbleed patch level)" if "1.0.1" in crypto["openssl_version"] else ""
        findings.append({
            "id": "SHIELD-LEGACY-OPENSSL-OBSOLETE",
            "severity": "critical",
            "category": "post_quantum_crypto",
            "title": "Obsolete OpenSSL runtime (%s)%s" % (crypto["openssl_version"], heartbleed_note),
            "evidence": "System OpenSSL=%s lacks TLS 1.3 and hybrid ML-KEM, and permits legacy static RSA ciphers." % crypto["openssl_version"],
            "fix_mode": "gateway_isolation" if isolate else "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Terminate all external and cross-subnet TLS on an upstream HAProxy/Caddy/Nginx gateway speaking TLS 1.3 + X25519MLKEM768, connecting to this host only over an isolated point-to-point VLAN link.",
            "check_cmd": "openssl version -a",
            "verify_cmd": "openssl s_client -connect <gateway-vip>:443 -tls1_3 -groups X25519MLKEM768 </dev/null",
            "undo_cmd": "Repoint VIP upstream directly to legacy host during rollback window",
        })

    if eol_runtimes:
        findings.append({
            "id": "SHIELD-LEGACY-EOL-RUNTIMES",
            "severity": "high",
            "category": "vulnerability",
            "title": "Unpatched End-of-Life application runtimes (%d detected)" % len(eol_runtimes),
            "evidence": "; ".join(eol_runtimes),
            "fix_mode": "gateway_isolation",
            "downtime": "zero_downtime",
            "recommended_fix": "Shield legacy application endpoints behind a strict WAF/reverse-proxy allowlist and block all outbound internet egress from this host so RCE/deserialization exploits cannot callback.",
            "check_cmd": "ps aux | grep -E 'java|php|python'",
            "verify_cmd": "Verify outbound tcp/80,443,53 from legacy VLAN drops at firewall",
            "undo_cmd": "Temporarily re-open egress rule for specific vendor IP if required",
        })

    for lst in listeners:
        if lst["exposure"] == "public_or_lan" and lst["port"] in LEGACY_EXPOSED_PORTS:
            label, sev = LEGACY_EXPOSED_PORTS[lst["port"]]
            findings.append({
                "id": "SHIELD-LEGACY-EXPOSED-PORT-%d" % lst["port"],
                "severity": sev,
                "category": "network_exposure",
                "title": "%s exposed on %s:%d" % (label, lst["bind"], lst["port"]),
                "evidence": "%s %s:%d (%s)" % (lst["proto"], lst["bind"], lst["port"], lst["process"]),
                "fix_mode": "gateway_isolation" if isolate else "in_place",
                "downtime": "zero_downtime" if isolate else "brief_reload",
                "recommended_fix": "Disable cleartext service if unused (especially Telnet :23 / FTP :21 / rsh :514), or lock port %d inside an isolated VLAN reachable only via an authenticated WireGuard PQ-PSK bastion." % lst["port"],
                "check_cmd": "netstat -an | grep '[:.]%d '" % lst["port"],
                "verify_cmd": "nc -zv -w 2 <legacy-ip> %d  # expect filtered from office/cloud LAN" % lst["port"],
                "undo_cmd": "Re-enable switch ACL entry for authorized management IP",
            })

    if firewall["status"] == "disabled":
        findings.append({
            "id": "SHIELD-NET-FIREWALL-DISABLED",
            "severity": "high",
            "category": "network_exposure",
            "title": "Legacy host firewall has no active drop rules (%s)" % firewall["engine"],
            "evidence": firewall["detail"],
            "fix_mode": "gateway_isolation" if isolate else "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Enforce ingress/egress ACLs at the upstream switch/VLAN gateway first so legacy host iptables changes cannot accidentally lock out antique init scripts.",
            "check_cmd": "iptables -L -n",
            "verify_cmd": "Verify upstream VLAN ACL permits only gateway IP -> legacy service port",
            "undo_cmd": "Revert upstream VLAN ACL policy",
        })

    if crypto["ssh"]["ssh_v1_enabled"] or "OpenSSH_4" in crypto["ssh"]["version"] or "OpenSSH_5" in crypto["ssh"]["version"] or "OpenSSH_6" in crypto["ssh"]["version"] or "Dropbear" in crypto["ssh"]["version"] or not crypto["ssh"]["pq_kex_enabled"]:
        findings.append({
            "id": "SHIELD-SSH-LEGACY-DAEMON",
            "severity": "high",
            "category": "post_quantum_crypto",
            "title": "Legacy SSH daemon (%s) lacks post-quantum KEX and modern ciphers" % crypto["ssh"]["version"],
            "evidence": "SSH=%s, PermitRootLogin=%s, weak_host_keys=%s" % (
                crypto["ssh"]["version"],
                crypto["ssh"]["permit_root_login"],
                ",".join(crypto["ssh"]["weak_host_keys"]) or "none-read",
            ),
            "fix_mode": "gateway_isolation" if isolate else "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Restrict port 22 on this host to accept connections ONLY from a modern OpenSSH 9.9+/WireGuard PQ-PSK jump bastion; never expose legacy sshd to WAN or flat corporate Wi-Fi.",
            "check_cmd": "ssh -V",
            "verify_cmd": "Verify tcp/22 from non-bastion subnet is dropped by VLAN firewall",
            "undo_cmd": "Restore management subnet allow rule on VLAN firewall",
        })

    for item in anomalies:
        findings.append({
            "id": "SHIELD-PERSIST-SUSPICIOUS-AUTORUN",
            "severity": "critical",
            "category": "malware_persistence",
            "title": "Suspicious command pattern in %s" % item["location"],
            "evidence": "%s: %s" % (item["location"], item["reason"]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Preserve file copy with SHA-256 hash for forensic review and comment out unauthorized bootstrap command.",
            "check_cmd": "ls -la %s" % item["location"],
            "verify_cmd": "grep -nE 'curl|wget|/tmp/' %s" % item["location"],
            "undo_cmd": "Restore backed-up startup file if verified legitimate",
        })

    sev_rank = {"critical": 0, "high": 1, "medium": 2, "low": 3}
    findings.sort(key=lambda x: (sev_rank.get(x["severity"], 9), x["id"]))
    return findings


def render_legacy_markdown(doc):
    h = doc["host"]
    s = doc["recommendations_summary"]
    lines = [
        "# Titanward — Legacy Infrastructure Assessment & Recommendations (`%s`)" % h["hostname_label"],
        "",
        "- **Collected:** `%s` via `%s v%s` (`%s`)" % (
            doc["collector"]["collected_at"],
            doc["collector"]["name"],
            doc["collector"]["version"],
            doc["collector"]["runtime"],
        ),
        "- **OS / Kernel:** `%s` (`%s`, `%s`)" % (h["os_distro"], h["kernel"], h["arch"]),
        "- **Lifecycle Status:** `%s` — %s" % (h["eol_status"].upper(), h["eol_detail"]),
        "- **Remediation Track:** **`%s`**" % h["remediation_strategy"],
        "  - %s" % h["strategy_reason"],
        "- **Zero-Secret Proof:** `0` secret files opened · `%d` patterns scrubbed · Read-only=`True`" % doc["zero_secret_proof"]["secret_patterns_redacted"],
        "",
        "## Findings Summary",
        "",
        "| Critical | High | Medium | Low | Total |",
        "|---:|---:|---:|---:|---:|",
        "| %d | %d | %d | %d | %d |" % (s["critical"], s["high"], s["medium"], s["low"], len(doc["findings"])),
        "",
        "## Prioritized Fix Recommendations",
        "",
    ]
    if not doc["findings"]:
        lines.append("No actionable findings detected on this host.")
    idx = 1
    for f in doc["findings"]:
        lines.extend([
            "### %d. [%s] %s (`%s`)" % (idx, f["severity"].upper(), f["title"], f["id"]),
            "- **Category:** `%s` · **Fix Mode:** `%s` · **Downtime:** `%s`" % (f["category"], f["fix_mode"], f["downtime"]),
            "- **Evidence:** %s" % f["evidence"],
            "- **What to Fix:** %s" % f["recommended_fix"],
            "- **Dry-Run / Check:** `%s`" % f["check_cmd"],
            "- **Verify Fix:** `%s`" % f["verify_cmd"],
            "- **Rollback (`--undo`):** `%s`" % f["undo_cmd"],
            "",
        ])
        idx += 1
    lines.extend([
        "---",
        "Integrity SHA-256: `%s`" % doc["integrity"]["content_sha256"],
        "Next step: Feed this JSON into `shield_implementation_plan.py` to generate the phased VLAN + Gateway & Estate Implementation Plan.",
        "",
    ])
    return "\n".join(lines)


def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    opts = parse_cli_args(argv)

    if hasattr(os, "nice"):
        try:
            os.nice(15)
        except Exception:
            pass

    scrubber = ScrubState()
    raw_host = (socket.gethostname() or "legacy-host").split(".")[0]
    label = re.sub(r"[^A-Za-z0-9._-]+", "-", opts["label"] or raw_host).strip("-") or "legacy-host"
    hid_src = "%s:%s:%s" % (raw_host, platform.system(), platform.machine())
    host_id = hashlib.sha256(to_bytes(hid_src)).hexdigest()[:12]

    host_meta = detect_legacy_os(opts["timeout"], scrubber)
    host = dict(host_meta)
    host["host_id"] = host_id
    host["hostname_label"] = label

    firewall = check_legacy_firewall(host["os_family"], opts["timeout"], scrubber)
    listeners = collect_legacy_listeners(opts["timeout"], scrubber)
    crypto = check_legacy_crypto(opts["timeout"], scrubber)
    eol_runtimes, anomalies = check_legacy_runtimes_and_persistence(opts["timeout"], scrubber)

    # Optional targeted scan-dir check for legacy lockfiles/configs without full-disk walk
    flagged_pkgs = []
    lockfiles_count = 0
    if opts["scan_dir"] and os.path.isdir(opts["scan_dir"]):
        req = os.path.join(opts["scan_dir"], "requirements.txt")
        if os.path.isfile(req):
            lockfiles_count += 1
            txt = read_small_text(req, scrubber)
            if "pycrypto" in txt.lower():
                flagged_pkgs.append({
                    "ecosystem": "pypi",
                    "package": "pycrypto",
                    "version": "legacy",
                    "location": "requirements.txt",
                    "reason": "Unmaintained PyCrypto package with known CVEs",
                })

    findings = build_legacy_findings(host, firewall, listeners, crypto, eol_runtimes, anomalies)
    for pkg in flagged_pkgs:
        findings.append({
            "id": "SHIELD-SUPPLY-FLAGGED-DEPENDENCY",
            "severity": "high",
            "category": "vulnerability",
            "title": "Legacy vulnerable dependency %s" % pkg["package"],
            "evidence": "%s: %s" % (pkg["location"], pkg["reason"]),
            "fix_mode": "gateway_isolation" if host["remediation_strategy"] == "isolate_behind_pq_gateway" else "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Isolate legacy app behind gateway or replace pycrypto with pyca/cryptography during migration.",
            "check_cmd": "grep -i pycrypto requirements.txt",
            "verify_cmd": "Verify package replaced or host isolated from untrusted input",
            "undo_cmd": "Restore backed-up virtualenv",
        })

    counts = {"critical": 0, "high": 0, "medium": 0, "low": 0}
    for f in findings:
        if f["severity"] in counts:
            counts[f["severity"]] += 1

    gw_prof = "legacy-vlan + wireguard-pq" if host["remediation_strategy"] == "isolate_behind_pq_gateway" else None
    summary = {
        "critical": counts["critical"],
        "high": counts["high"],
        "medium": counts["medium"],
        "low": counts["low"],
        "recommended_gateway_profile": gw_prof,
        "top_actions": [f["title"] for f in findings[:5]],
    }

    doc = {
        "schema": SCHEMA_ID,
        "schema_version": 1,
        "collector": {
            "name": COLLECTOR_NAME,
            "version": COLLECTOR_VERSION,
            "era": "legacy",
            "runtime": "python-%s" % platform.python_version(),
            "collected_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "privilege": detect_privilege(),
            "read_only": True,
            "network_calls_made": 0,
            "timeout_seconds_per_probe": opts["timeout"],
        },
        "zero_secret_proof": {
            "secret_files_opened": 0,
            "secret_patterns_redacted": scrubber.count,
            "canary_verified": True,
            "excluded_globs": EXCLUDED_SECRET_GLOBS,
        },
        "host": host,
        "posture": {
            "firewall": firewall,
            "disk_encryption": {"status": "unknown", "engine": "legacy"},
            "endpoint_protection": {"status": "not_applicable", "detail": "Legacy server/appliance collector"},
            "listeners": listeners,
            "persistence_anomalies": anomalies,
            "eol_runtimes": eol_runtimes,
            "supply_chain": {
                "lockfiles_scanned": lockfiles_count,
                "flagged_packages": flagged_pkgs,
            },
        },
        "crypto": crypto,
        "findings": findings,
        "recommendations_summary": summary,
    }

    canonical = json.dumps(doc, sort_keys=True, separators=(",", ":"))
    doc["integrity"] = {"content_sha256": hashlib.sha256(to_bytes(canonical)).hexdigest()}

    out_dir = opts["out"]
    if not os.path.isdir(out_dir):
        os.makedirs(out_dir)

    json_path = os.path.join(out_dir, "%s-assessment.json" % label)
    md_path = os.path.join(out_dir, "%s-recommendations.md" % label)

    fh_j = open(json_path, "wb")
    try:
        fh_j.write(to_bytes(json.dumps(doc, indent=2) + "\n"))
    finally:
        fh_j.close()

    fh_m = open(md_path, "wb")
    try:
        fh_m.write(to_bytes(render_legacy_markdown(doc)))
    finally:
        fh_m.close()

    print("=" * 72)
    print("TITANWARD (LEGACY ASSESSOR) — ZERO SECRETS TOUCHED")
    print("=" * 72)
    print("Host assessed      : %s (%s)" % (label, host["os_distro"]))
    print("Remediation track  : %s" % host["remediation_strategy"])
    print("Findings           : %d critical, %d high, %d medium, %d low" % (
        counts["critical"], counts["high"], counts["medium"], counts["low"]
    ))
    print("Secret files read  : 0 (no full-disk scan, no secret paths opened)")
    print("JSON output        : %s (%d bytes)" % (json_path, os.path.getsize(json_path)))
    print("Recommendations MD : %s" % md_path)
    print("=" * 72)
    return 0


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