#!/usr/bin/env -S python3 -X utf8
# summary: Read the computer's security and update status.
"""starchaser security: security status for Settings > Security and > Firewall, without root.

Usage: starchaser security [status | updates]

    starchaser security status      JSON: encryption, TPM unlock, Secure Boot, firewall, SSH, last update
    starchaser security updates     JSON: pending updates (slow: checkupdates syncs a private package database);
                                    "onHold" counts those Updates is holding back for now, with a "note"
                                    "holdUnknown" means Updates must check before the hold status is known
"""
import grp
import ipaddress
import json
import os
import pwd
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path

for _lib in (Path(__file__).resolve().parents[1] / 'system/usr/local/lib/starchaser', Path('/usr/local/lib/starchaser')):
    if (_lib / 'secure_boot.py').is_file():
        sys.path.insert(0, str(_lib))
        break
import secure_boot as signed_boot


def out(*cmd, timeout=10) -> str:
    if not shutil.which(cmd[0]):
        return ""
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout.strip()
    except (OSError, subprocess.TimeoutExpired):
        return ""


def rd(p) -> str:
    try:
        return Path(p).read_text().strip()
    except OSError:
        return ""


def drive_unlock_status():
    try:
        return json.loads(rd("/run/starchaser-drive-unlock.json"))
    except ValueError:
        return {"known": False}


def encryption() -> dict:
    """Is / on LUKS, and is it unlocked by the TPM at boot (rd.luks.options=...tpm2-device...)?"""
    try:
        tree = json.loads(out("lsblk", "-J", "-o", "NAME,TYPE,MOUNTPOINTS"))
    except ValueError:
        # lsblk failed or printed nothing readable: not known, rather than reported as off
        return {"encrypted": False, "tpm": False, "encryptionKnown": False}
    def walk(nodes, crypt=False):
        for n in nodes:
            c = crypt or n.get("type") == "crypt"
            if "/" in (n.get("mountpoints") or []):
                return c
            r = walk(n.get("children") or [], c)
            if r is not None:
                return r
        return None
    found = walk(tree.get("blockdevices", []))
    enc = bool(found)
    cmdline = rd("/proc/cmdline")
    # no device holds / (a container, an odd setup): couldn't tell
    return {"encrypted": enc, "tpm": enc and "tpm2-device" in cmdline, "encryptionKnown": found is not None}


def secure_boot() -> bool | None:
    """True / False, or None when the firmware variable is there but can't be read (shown as "Couldn't check").
    No variable at all (an older BIOS-style start, or firmware without Secure Boot) is off."""
    unknown = False
    for f in Path("/sys/firmware/efi/efivars").glob("SecureBoot-*"):
        try:
            data = f.read_bytes()
            if data:
                return data[-1] == 1
            unknown = True
        except OSError:
            unknown = True
    return None if unknown else False


def tsshd_scopes() -> set:
    """The login-session scopes (session-N.scope, at the top of the cgroup tree) that hold a running tsshd. tsshd
    signs in over SSH, then the SSH connection closes and the terminal keeps going over UDP inside a session logind
    now calls "closing", so a closing SSH session with tsshd in it is still someone signed in. Matched by the program
    file's name (/proc/PID/exe; tsshd installs to /usr/local/bin or the user's ~/.local/bin) where it can be read;
    another account's processes can't be, and fall back to the process name. A look-alike here can only make
    Settings ask once too often, never sign someone out unasked."""
    scopes = set()
    for d in Path("/proc").iterdir():
        if not d.name.isdigit():
            continue
        try:
            m = re.search(r"^0::/user\.slice/user-\d+\.slice/(session-[^/]+\.scope)$", (d / "cgroup").read_text(), re.M)
            if not m:
                continue
            try:
                exe = str((d / "exe").readlink()).removesuffix(" (deleted)")
                hit = exe.rsplit("/", 1)[-1] == "tsshd"
            except PermissionError:
                hit = (d / "comm").read_text().strip() == "tsshd"
        except OSError:
            continue
        if hit:
            scopes.add(m.group(1))
    return scopes


def ssh_sessions() -> int:
    """How many other computers are signed in through remote login now (logind sessions that came in through sshd and
    haven't signed out, or whose SSH connection closed but still hold a tsshd terminal). Settings asks before turning
    remote login off signs them out. -1 when it can't be told (a loginctl call failed, say a session that ended
    between the two calls, or all of them together taking more than about 3 seconds, which held Settings > Security
    blank): Settings then asks too."""
    deadline = time.monotonic() + 3

    def lc(*args):
        left = deadline - time.monotonic()
        if left <= 0:
            return None
        try:
            r = subprocess.run(["loginctl", *args], capture_output=True, text=True, timeout=left)
        except (OSError, subprocess.TimeoutExpired):
            return None
        return None if r.returncode else r.stdout
    listing = lc("list-sessions", "--no-legend")
    if listing is None:
        return -1
    n, tsshd = 0, None
    for line in listing.splitlines():
        sid = (line.split() or [""])[0]
        if not re.fullmatch(r"[\w-]+", sid):
            continue
        shown = lc("show-session", sid, "-p", "Service", "-p", "State")
        info = dict(l.split("=", 1) for l in (shown or "").splitlines() if "=" in l)
        if shown is None or "State" not in info:
            return -1
        if info.get("Service") != "sshd":
            continue
        if info.get("State") != "closing":
            n += 1
            continue
        if tsshd is None:
            tsshd = tsshd_scopes()
        if f"session-{sid}.scope" in tsshd:
            n += 1
    return n


def ssh() -> dict:
    active = out("systemctl", "is-active", "sshd.service") == "active"
    sessions = ssh_sessions() if active else 0
    policy = Path("/etc/ssh/sshd_config.d/00-starchaser-ssh-auth.conf")
    if policy.exists():           # the remote sign-in policy: keys for everyone, a password for one account
        # the password exception is the "Match User" line, which desktop setup fills in with the account's name. Still
        # the placeholder: no account may use a password (keys only, computer-wide). Naming someone else: passwords
        # still work, but only for that account, so the page names it rather than saying "your password" or "keys
        # only". An unreadable file, or one with no Match line, keeps the old answer (your password or a key).
        m = re.search(r"(?mi)^\s*Match\s+User\s+(\S+)", rd(policy))
        if m:
            names = [n for n in m.group(1).split(",") if n and n != "STARCHASER_USER"]
            if not names:
                return {"running": active, "passwords": False, "policy": "keys-only", "sessions": sessions}
            me = os.environ.get("SUDO_USER") if os.getuid() == 0 else None
            me = me or pwd.getpwuid(os.getuid()).pw_name
            if me not in names:
                return {"running": active, "passwords": True, "policy": "other-password",
                        "passwordUsers": names, "sessions": sessions}
        return {"running": active, "passwords": True, "policy": "user-password", "sessions": sessions}
    # password logins: the last word wins in sshd_config.d (first match), so read the drop-ins in order
    pw = None
    files = sorted(Path("/etc/ssh/sshd_config.d").glob("*.conf")) + [Path("/etc/ssh/sshd_config")]
    for f in files:
        m = re.search(r"(?mi)^\s*PasswordAuthentication\s+(yes|no)", rd(f))
        if m:
            pw = m.group(1).lower() == "yes"
            break
    return {"running": active, "passwords": True if pw is None else pw, "sessions": sessions}


def lan() -> list:
    """The networks this computer is on right now (the "home network" a service can be limited to)."""
    nets = []
    try:
        for a in json.loads(out("ip", "-j", "addr")):
            if a.get("ifname", "").startswith(("lo", "virbr", "docker", "br-", "veth", "tailscale", "vnet")):
                continue
            for i in a.get("addr_info", []):
                if i.get("scope") != "global":
                    continue
                n = ipaddress.ip_network(f"{i['local']}/{i['prefixlen']}", strict=False)
                if n.version == 6 and not n.is_private:      # public IPv6 prefixes aren't "home"
                    continue
                nets.append(str(n))
    except (ValueError, KeyError):
        pass
    return sorted(set(nets))


def last_update() -> str:
    """Date of the last completed full system update: its 'starting full system upgrade' timestamp.
    Only that upgrade's completed transaction counts, not later package installs or canceled or failed upgrades."""
    last, pending = "", None
    for line in rd("/var/log/pacman.log").splitlines():
        if "[PACMAN] Running " in line:          # a new pacman command: an earlier start never completed
            pending = None
        elif "starting full system upgrade" in line:
            m = re.match(r"\[([^\]]+)\]", line)
            pending = m.group(1) if m else None
        elif "[ALPM] transaction completed" in line and pending:
            last, pending = pending, None
    return last


def status() -> dict:
    fw = {}
    unreadable = False
    try:
        fw = json.loads(Path("/etc/starchaser/policy.json").read_text())
        unreadable = not isinstance(fw, dict)
    except FileNotFoundError:
        pass
    except (OSError, ValueError):
        unreadable = True
    if unreadable:
        fw = {}
    pending = rd("/run/starchaser-firewall.pending")
    try:
        pending = json.loads(pending) if pending else None
    except ValueError:                                  # half-written or damaged: no countdown, not a crash
        pending = None
    enc = encryption()
    conversion = {}
    if enc.get("encryptionKnown") and not enc["encrypted"]:
        for lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
            if (lib / "drive_unlock.py").exists():
                sys.path.insert(0, str(lib))
                import drive_unlock
                conversion = drive_unlock.encryption_plan()
                break
    return {
        **enc,
        "encryptionPlan": conversion,
        "driveUnlock": drive_unlock_status(),
        "secureBoot": secure_boot(),
        "signedBoot": signed_boot.status(),
        "firewall": fw,
        "policyUnreadable": unreadable,
        # the policy says whether it's on: turning it off deletes the rules and disables the service but leaves the
        # one-shot service "active" until the next restart, so that read "On" after an Off. The service is only the
        # answer for an old setup with no policy file. (`nft list tables` needs root, so it always read empty here.)
        "firewallActive": None if unreadable else bool(fw.get("enabled")) if "enabled" in fw else
                          (out("systemctl", "is-active", "starchaser-firewall.service") == "active"
                           or out("systemctl", "is-enabled", "starchaser-firewall.service") == "enabled"),
        "firewallPending": pending,
        "ssh": ssh(),
        "lan": lan(),
        "lastUpdate": last_update(),
        "hostname": rd("/etc/hostname"),
        "administrator": bool(set(os.getgroups()) & {grp.getgrnam(group).gr_gid for group in ("wheel",) if group in {g.gr_name for g in grp.getgrall()}}) or os.getuid() == 0,
        "adminReady": Path("/usr/local/lib/starchaser/starchaser-admin").exists()
                      and Path("/usr/share/polkit-1/actions/org.starchaser.admin.policy").exists(),
    }


def updates() -> dict:
    if not shutil.which("checkupdates"):
        return {"count": None, "error": "The update checker isn't installed."}
    t = time.time()
    try:
        result = subprocess.run(["checkupdates"], capture_output=True, text=True, timeout=120)
    except subprocess.TimeoutExpired:
        return {"count": None, "error": "The update check took too long. Try again."}
    except OSError:
        return {"count": None, "error": "Couldn't start the update checker. Try again."}
    # checkupdates uses 2 for a successful check with no updates; 1 is a failure.
    if result.returncode not in (0, 2):
        return {"count": None, "error": "Couldn't check for updates. Try again.",
                "details": result.stderr.strip() or result.stdout.strip()}
    lines = [l for l in result.stdout.splitlines() if l.strip()]
    names = [l.split()[0] for l in lines]
    reply = {"count": len(names), "packages": names[:200], "checked": int(t)}
    # Updates holds system updates back until the matching Starchaser desktop update is ready; say so here too, so
    # the two commands don't seem to disagree. The hold comes from the last `starchaser updates check`.
    try:
        saved = json.loads((Path.home() / ".cache/starchaser/updates.json").read_text())
        held = {u["name"] for u in saved["deferred"]} & set(names)
    except (OSError, ValueError, KeyError, TypeError, AttributeError):
        held = set()
        if names:
            reply["holdUnknown"] = True
            reply["note"] = ("These are updates available upstream; their hold status hasn't been checked. "
                             "Run 'starchaser updates check' to see which updates can be installed and which are on hold.")
    if held:
        reply["onHold"] = len(held)
        reply["note"] = saved.get("systemHold") or "Some system updates are on hold until the Starchaser desktop update is ready."
    return reply


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
    if cmd in ("-h", "--help", "help") or any(a in ("-h", "--help") for a in sys.argv[2:]):
        print(__doc__.strip())
        sys.exit(0)
    if cmd not in ("status", "updates"):
        print(f"starchaser security: unknown command {cmd!r}. Run 'starchaser security --help' for more help.", file=sys.stderr)
        sys.exit(2)
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    from starchaser_cli import takes_nothing_after
    if len(sys.argv) > 2:
        sys.exit(takes_nothing_after("starchaser security", cmd, sys.argv[1:]))
    result = updates() if cmd == "updates" else status()
    print(json.dumps(result))
    sys.exit(1 if cmd == "updates" and result.get("error") else 0)
