#!/usr/bin/env python3
"""minaki-scan -- "is my Linux server safe, and what's happening on it?"

Read-only by default. Each finding says, in plain words, what is wrong, why it matters,
and the exact command that fixes it. `--fix` offers the fixes this version knows how to
apply safely, one at a time, and applies each only after you type "yes". Every change is
backed up and logged under /var/lib/minaki-scan/. Nothing leaves this machine.

What it can't do: prove a machine clean. If it finds signs of a kernel-level infection
(rootkit), it tells you to back up your data and reinstall, because nothing running on
an infected kernel can be trusted to report on it.

Usage: minaki-scan [--json] [--fix] [--root DIR]
  --root DIR   scan a mounted disk or test tree instead of / (file checks only)
Exit status: 0 nothing above LOW, 1 MEDIUM, 2 HIGH or CRITICAL, 3 the scan itself failed.
"""
import argparse
import glob
import ipaddress
import json
import os
import pwd
import re
import shutil
import socket
import stat
import subprocess
import sys
import time

# Don't litter the install with __pycache__ (a report-mode run must write nothing outside what it
# scans, and it kept apt purge from removing /usr/share/minaki-scan). Set before any family import.
sys.dont_write_bytecode = True

# Load the per-family modules (indicators + removal only). Done defensively so the
# scanner still imports if run via exec() without __file__ (e.g. a unit test).
try:
    _HERE = os.path.dirname(os.path.abspath(__file__))
except NameError:
    _HERE = os.path.dirname(os.path.abspath(sys.argv[0])) if sys.argv and sys.argv[0] else os.getcwd()
# The modules + the plugin/rule seam sit beside this script in the repo (scan/…) and in the installed
# package under <prefix>/share/minaki-scan. Search the repo dir, /usr/share, /usr/local/share, AND
# <bindir>/../share so BOTH the .deb (/usr) and the tarball/install.sh (/usr/local) paths load them.
_SHARE_DIRS = [_HERE,
               os.path.abspath(os.path.join(_HERE, "..", "share", "minaki-scan")),
               "/usr/share/minaki-scan", "/usr/local/share/minaki-scan"]
_FAMILIES_DIR = next((os.path.join(d, "families") for d in _SHARE_DIRS
                      if os.path.isdir(os.path.join(d, "families"))), None)
if _FAMILIES_DIR and _FAMILIES_DIR not in sys.path:
    sys.path.insert(0, _FAMILIES_DIR)
_CATALOG = os.path.join(_FAMILIES_DIR, "catalog.json") if _FAMILIES_DIR else os.path.join(_HERE, "families", "catalog.json")
try:
    import outlaw as _outlaw
except Exception:
    _outlaw = None
try:
    import sysrv as _sysrv
except Exception:
    _sysrv = None
try:
    import prometei as _prometei
except Exception:
    _prometei = None
_families = {}
for _fn in ("muhstik", "dreambus", "redtail", "mirai"):
    try:
        _families[_fn] = __import__(_fn)
    except Exception:
        _families[_fn] = None
# internal plugin seam (detection plugins run read-only after the built-in checks). Guarded: if the
# seam is absent or errors, the scan proceeds exactly as before. See docs/PLUGIN-ARCHITECTURE.md.
for _pd in _SHARE_DIRS:
    if os.path.isdir(_pd) and _pd not in sys.path:
        sys.path.insert(0, _pd)
try:
    import plugin_api as _plugins
except Exception:
    _plugins = None
try:
    import rule_engine as _rules
except Exception:
    _rules = None
try:
    import hardening as _hardening      # Frontier G6 hardening checks (D78), shipped beside rule_engine.py
except Exception:
    _hardening = None
try:
    import backupcheck as _backupcheck  # Frontier G9 backup check (D79), shipped beside hardening.py
except Exception:
    _backupcheck = None

VERSION = "0.8.6"

# What this program reads, runs, changes and sends: printed by `minaki-scan --privacy` / `minaki privacy`
# and quoted WORD FOR WORD by minaki.io/privacy (site/minaki-io-v2/build_site.py reads this constant
# with ast.literal_eval and refuses to build if the page's "minaki-scan" section differs). Keep it a
# plain literal (no f-strings, no names) so the site can read it without running this file.
# Every sentence is backed by code; the proof table is site/minaki-io-v2/content/CLAIMS-CONTENT.md.
# tests/test_no_network.sh fails if a network-capable call appears anywhere in scan/.
PRIVACY_DISCLOSURE = {
    "title": "What Minaki Scan reads, changes and sends",
    "paragraphs": [
        "Minaki Scan makes no network connections. It sends nothing to us or to anyone else. "
        "Your results, your server's name, its files and its settings stay on your server.",

        "What it reads: SSH settings; the login key files in root's and every user's home folder; "
        "/etc/passwd, /etc/group and /etc/shadow, to find accounts with no password, extra root "
        "accounts and accounts that can control Docker; sudo rules; /etc/ld.so.preload; scheduled "
        "tasks, services, login scripts and /etc/environment; the folders in root's command path; "
        "the running programs and the files they run from; which network ports are listening; the "
        "files in /tmp, /var/tmp and /dev/shm, and at the places its malware list names; the SSH "
        "login log; when the server was first set up; whether updates install automatically "
        "or are waiting for a restart; the firewall rules and which firewall parts the kernel has "
        "loaded; the kernel's network and crash-dump settings; whether the clock is kept right; "
        "which Linux this is (/etc/os-release); whether it is a Proxmox server (/var/lib/dpkg/status and "
        "/etc/pve) and the names of the other servers in its cluster (/etc/pve/corosync.conf), so the "
        "firewall advice fits; the services and scheduled tasks that run restic or borg backups, and "
        "the settings files they name, keeping only where each backup goes and never a password; "
        "and which files in /etc, /usr, /boot, /opt, /srv, "
        "/bin, /sbin, /lib, /lib32 and /lib64 any user can change.",

        "What it runs: sshd, to read and test SSH settings; journalctl, to read the SSH log "
        "when it cannot read a log file and to see when a backup last ran and whether it worked; nft, iptables and ip6tables, to read the firewall rules; ss, "
        "to list the ports the firewall advice must keep open; and timedatectl, to see whether the "
        "clock is kept right. During a fix you approve it also runs systemctl, to reload SSH "
        "or to stop a malware service.",

        "What a scan changes: nothing. A scan only reads, and prints its report on your screen.",

        "What a fix changes: nothing until you type yes. An SSH fix writes "
        "/etc/ssh/sshd_config.d/00-minaki-scan.conf. A malware removal stops the malware's programs "
        "and services, and deletes its files and its lines in scheduled tasks and login key files. "
        "Before a fix edits or deletes a file, it keeps a copy in /var/lib/minaki-scan/, and it "
        "records each fix in /var/lib/minaki-scan/changes.log. These stay on your server.",

        "Updates: Minaki Scan never downloads anything, not even its own updates. You update it "
        "the way you installed it: through your package manager, or by downloading the new "
        "release, checking it against SHA256SUMS and installing it.",

        "License: this version does not check a license. When the check is added, it will run on "
        "your server without contacting us.",
    ],
}


def privacy_text(width=78):
    """The disclosure as printed by --privacy: the title, then each paragraph wrapped."""
    import textwrap
    out = [PRIVACY_DISCLOSURE["title"], ""]
    for p in PRIVACY_DISCLOSURE["paragraphs"]:
        out += textwrap.wrap(p, width, break_on_hyphens=False, break_long_words=False) + [""]
    return "\n".join(out).rstrip("\n")


SEV ={"CRITICAL": 4, "HIGH": 3, "MEDIUM": 2, "LOW": 1, "INFO": 0}
ROOT = "/"
ALLOW_UNSIGNED_PLUGINS = False  # unsigned USER plugins stay off unless --allow-unsigned-plugins
PROGRESS = False  # one overwritten "Checking N of M" line on stderr; terminal only, never with --json

# Process names seen on compromised Linux servers (coin miners and their droppers).
MINER_NAMES = {"xmrig", "xmr-stak", "kdevtmpfsi", "kinsing", "kthreaddi", "dbused", "sysupdate",
               "networkservice", "solrd", "xmrigdaemon", "cpuminer", "minerd", "ccminer",
               "nbminer", "t-rex", "lolminer", "phpguard", "javae", "watchbog", "kerberods"}
# Services that should never answer the whole internet.
RISKY_PORTS = {2375: "Docker API (no password: anyone can run containers as root)",
               2376: "Docker API over TLS", 6379: "Redis", 27017: "MongoDB",
               9200: "Elasticsearch", 11211: "Memcached", 5432: "PostgreSQL",
               3306: "MySQL/MariaDB", 5984: "CouchDB", 8086: "InfluxDB",
               10250: "Kubernetes kubelet", 2379: "etcd",
               23: "Telnet (sends passwords in plain text; the most attacked port in our captures)",
               21: "FTP (sends passwords in plain text)", 445: "Windows file sharing (SMB/Samba)",
               873: "rsync daemon", 5900: "VNC remote desktop", 3389: "Remote desktop (RDP/xrdp)"}
SUSPICIOUS_CMD = re.compile(r"(curl|wget)[^|;]*\|\s*(ba|da|z)?sh|base64\s+(-d|--decode)|/dev/shm/|/tmp/\.|"
                            r"\bnohup\b.*\b(tmp|shm)\b|chattr\s+\+i|\.onion\b|pastebin\.com|stratum\+tcp")
TEMP_DIRS = ["/tmp", "/var/tmp", "/dev/shm"]
# The same signals minus the bare temp-path ones: for a systemd Exec line, a temp path only
# matters when something RUNS from there (see _exec_runs_from_temp). Stock units that read a
# file in /dev/shm (openSUSE bootmsg.service) or pass /tmp/scrub/ as an argument (xfs_scrub@)
# were false alarms on clean cloud images.
SUSPICIOUS_EXEC = re.compile(r"(curl|wget)[^|;]*\|\s*(ba|da|z)?sh|base64\s+(-d|--decode)|"
                             r"\bnohup\b.*\b(tmp|shm)\b|chattr\s+\+i|\.onion\b|pastebin\.com|stratum\+tcp")
_SHELLS = {"sh", "bash", "dash", "zsh", "ash", "busybox", "python", "python3", "perl", "ruby", "php", "node"}


def _in_temp(path):
    return any(path == d or path.startswith(d + "/") for d in TEMP_DIRS)


def _exec_runs_from_temp(cmd):
    """True if a systemd Exec command runs a program or script that lives in a temp folder: the
    program itself, a script handed to a shell or interpreter, or ./x after cd into one."""
    import shlex
    cmd = cmd.lstrip("-@:+!")
    try:
        argv = shlex.split(cmd)
    except ValueError:
        argv = cmd.split()
    if not argv:
        return False
    if _in_temp(argv[0]):
        return True
    if os.path.basename(argv[0]) in _SHELLS:
        rest = argv[1:]
        if "-c" in rest and rest.index("-c") + 1 < len(rest):
            script = rest[rest.index("-c") + 1]
            in_temp_dir = False
            for part in re.split(r"&&|\|\||[;|&\n]", script):
                words = part.split()
                if not words:
                    continue
                if words[0] == "cd" and len(words) > 1:
                    in_temp_dir = _in_temp(words[1].rstrip("/") or "/")
                    continue
                if _in_temp(words[0]) or (in_temp_dir and words[0].startswith("./")):
                    return True
                if os.path.basename(words[0]) in _SHELLS and len(words) > 1 and _in_temp(words[1]):
                    return True
            return False
        script_args = [a for a in rest if not a.startswith("-")]
        return bool(script_args) and _in_temp(script_args[0])
    return False


def P(path):
    """A path inside the scanned root."""
    return os.path.join(ROOT, path.lstrip("/"))


def disp(full):
    """How a full path inside ROOT is shown to the user."""
    return full if ROOT == "/" else "/" + os.path.relpath(full, ROOT)


def read(path, default=""):
    try:
        with open(P(path), errors="replace") as f:
            return f.read()
    except OSError:
        return default


class Report:
    def __init__(self):
        self.findings = []
        self.skipped = []

    def add(self, sev, check, what, why, fix=None, fix_id=None, evidence=None):
        self.findings.append({"severity": sev, "check": check, "what": what, "why": why,
                              "fix": fix, "fix_id": fix_id, "evidence": evidence or []})

    def skip(self, check, reason):
        self.skipped.append({"check": check, "reason": reason})


# ---------------------------------------------------------------- checks
def sshd_settings():
    """Effective sshd settings: `sshd -T` when scanning the live system, else the files."""
    conf = {}
    if ROOT == "/" and shutil.which("sshd") and os.geteuid() == 0:
        r = subprocess.run(["sshd", "-T"], capture_output=True, text=True)
        if r.returncode == 0:
            for line in r.stdout.splitlines():
                k, _, v = line.partition(" ")
                conf[k.lower()] = v.strip().lower()
            return conf, "sshd -T"
    files = [P("/etc/ssh/sshd_config")] + sorted(glob.glob(P("/etc/ssh/sshd_config.d/*.conf")))
    # sshd uses the FIRST value it sees; included drop-ins are read where the Include line is,
    # which on Debian/Ubuntu is the top of the file, so drop-ins win.
    ordered = files[1:] + files[:1]
    for fp in ordered:
        try:
            text = open(fp, errors="replace").read()
        except OSError:
            continue
        for line in text.splitlines():
            line = line.strip()
            if not line or line.startswith("#") or line.lower().startswith("match "):
                if line.lower().startswith("match "):
                    break
                continue
            k, _, v = line.partition(" ")
            conf.setdefault(k.lower(), v.strip().lower())
    return conf, "config files"


def check_ssh(rep):
    if not os.path.exists(P("/etc/ssh/sshd_config")):
        rep.skip("ssh", "no OpenSSH server config found")
        return
    conf, src = sshd_settings()
    pw = conf.get("passwordauthentication", "yes")
    kbd = conf.get("kbdinteractiveauthentication", conf.get("challengeresponseauthentication", "yes"))
    pam = conf.get("usepam", "no")
    # Two ways sshd takes a password: PasswordAuthentication, or the keyboard-interactive prompt
    # handed to PAM (openSUSE's stock image: PasswordAuthentication no, but KbdInteractive + PAM
    # still ask for one). Keyboard-interactive without PAM has no password backend on Linux.
    pw_routes = (["PasswordAuthentication=yes"] if pw == "yes" else []) + \
        (["KbdInteractiveAuthentication=yes with UsePAM=yes"] if kbd == "yes" and pam == "yes" else [])
    if pw_routes:
        rep.add("HIGH", "ssh-passwords",
                "SSH accepts passwords.",
                "Bots try thousands of passwords a day against every server on the internet. "
                "With keys only, guessing a password gets them nowhere.",
                "Make sure you can log in with an SSH key first, then:\n"
                "  echo 'PasswordAuthentication no' | sudo tee /etc/ssh/sshd_config.d/00-minaki-scan.conf\n"
                "  echo 'KbdInteractiveAuthentication no' | sudo tee -a /etc/ssh/sshd_config.d/00-minaki-scan.conf\n"
                "  sudo sshd -t && sudo systemctl reload ssh",
                fix_id="ssh-no-passwords", evidence=[f"{r} ({src})" for r in pw_routes])
    if conf.get("permitemptypasswords", "no") == "yes":
        rep.add("CRITICAL", "ssh-empty-passwords",
                "SSH lets accounts with no password log in.",
                "Any account without a password can be entered by anyone who knows its name.",
                "  echo 'PermitEmptyPasswords no' | sudo tee -a /etc/ssh/sshd_config.d/00-minaki-scan.conf\n"
                "  sudo sshd -t && sudo systemctl reload ssh",
                fix_id="ssh-no-empty-passwords", evidence=[f"PermitEmptyPasswords=yes ({src})"])
    root = conf.get("permitrootlogin", "prohibit-password")
    if root == "yes" and pw_routes:     # with no password route, root can only use a key
        rep.add("HIGH", "ssh-root",
                "root can log in over SSH with a password.",
                "'root' is the first username every bot tries.",
                "  echo 'PermitRootLogin prohibit-password' | sudo tee -a /etc/ssh/sshd_config.d/00-minaki-scan.conf\n"
                "  sudo sshd -t && sudo systemctl reload ssh",
                fix_id="ssh-root-keys-only", evidence=[f"PermitRootLogin={root} ({src})"] + [f"{r} ({src})" for r in pw_routes])


def _cloud_init_boot():
    """Epoch mtime of cloud-init's first-boot marker (when the server was created), or None."""
    for p in glob.glob(P("/var/lib/cloud/instances/*/boot-finished")) + [P("/var/lib/cloud/instance/boot-finished")]:
        try:
            return os.stat(p).st_mtime
        except OSError:
            pass
    return None


def _created_on(boot):
    import datetime as _dt
    return _dt.datetime.fromtimestamp(boot, _dt.timezone.utc).strftime("%Y-%m-%d") if boot else "its creation date"


def check_authorized_keys(rep):
    recent, keys2, firstboot = [], [], []
    now = time.time()
    boot = _cloud_init_boot()
    files = []
    for home in [P("/root")] + glob.glob(P("/home/*")):
        files += [os.path.join(home, ".ssh", n) for n in ("authorized_keys", "authorized_keys2")]
    for f in files:
        if not os.path.isfile(f):
            continue
        if f.endswith("2"):
            keys2.append(disp(f))
        try:
            open(f, errors="replace").read()
        except OSError:
            rep.skip("ssh-keys", f"{disp(f)} unreadable without root")
            continue
        mt = os.stat(f).st_mtime
        if now - mt < 7 * 86400:
            # a key written within minutes of cloud-init's first boot is the provider's own key,
            # not an intrusion -- note it, don't alarm. Every fresh VPS has this for a week (P3).
            (firstboot if (boot is not None and abs(mt - boot) <= 900) else recent).append(disp(f))
    if recent:
        rep.add("MEDIUM", "ssh-keys-changed",
                "SSH login keys were changed in the last 7 days.",
                "Attackers add their own key so they can come back. If you didn't add a key this week, check it.",
                "Look at each file and remove any key you don't recognise:\n" + "\n".join(f"  cat {r}" for r in recent),
                evidence=recent)
    if firstboot:
        rep.add("INFO", "ssh-keys-firstboot",
                "SSH login keys were set up when this server was first created.",
                f"These were written when the server was created ({_created_on(boot)}, by cloud-init). "
                "If you created it then, this is expected; only a change you didn't make is worth a look.",
                "No action needed if you set this server up. Otherwise review:\n" + "\n".join(f"  cat {r}" for r in firstboot),
                evidence=firstboot)
    if keys2:
        rep.add("MEDIUM", "ssh-keys2",
                "An old-style second SSH key file (authorized_keys2) exists.",
                "Current systems rarely use it, and people rarely look in it, so attackers sometimes put their key there.",
                "If you don't use it, check its keys and then remove it:\n" + "\n".join(f"  cat {r}" for r in keys2),
                evidence=keys2)


def check_accounts(rep):
    """Accounts that can log in with no password at all. Needs root to read /etc/shadow."""
    shadow = read("/etc/shadow", None)
    if shadow is None:
        rep.skip("empty-passwords", "/etc/shadow unreadable without root")
        return
    empty = [l.split(":")[0] for l in shadow.splitlines() if l.count(":") >= 2 and l.split(":")[1] == ""]
    if empty:
        rep.add("CRITICAL", "empty-passwords", f"Accounts with no password: {', '.join(empty)}.",
                "Anyone can log in to these accounts wherever a password login is allowed.",
                "Set a password or lock each one:  sudo passwd -l <name>", evidence=empty)


def check_sudoers(rep):
    """New or changed sudo rules: attackers who got root once give themselves a way back."""
    now = time.time()
    boot = _cloud_init_boot()
    recent, firstboot = [], []
    for f in [P("/etc/sudoers")] + glob.glob(P("/etc/sudoers.d/*")):
        try:
            if not (os.path.isfile(f) and now - os.stat(f).st_mtime < 7 * 86400):
                continue
        except OSError:
            continue
        mt = os.stat(f).st_mtime
        # cloud-init's own 90-cloud-init-users (or anything written at first boot) is the provider
        # granting the default user sudo -- expected on every fresh VPS, not an intrusion (P3).
        if os.path.basename(f) == "90-cloud-init-users" or (boot is not None and abs(mt - boot) <= 900):
            firstboot.append(disp(f))
        else:
            recent.append(disp(f))
    if recent:
        rep.add("MEDIUM", "sudo-changed", "sudo rules were changed in the last 7 days.",
                "A new sudo rule can give an account full root power without a password. "
                "If you didn't change sudo this week, check it.",
                "Read each file and remove any rule you don't recognise (edit with sudo visudo -f <file>):\n"
                + "\n".join(f"  sudo cat {r}" for r in recent), evidence=recent)
    if firstboot:
        rep.add("INFO", "sudo-firstboot",
                "Sudo was set up when this server was first created.",
                f"The default user was given sudo when the server was created ({_created_on(boot)}, by cloud-init). "
                "If you created it then, this is expected.",
                "No action needed if you set this server up.", evidence=firstboot)
    members = [l.split(":")[3] for l in read("/etc/group").splitlines() if l.startswith("docker:") and l.count(":") >= 3]
    users = [u for u in (members[0].split(",") if members else []) if u]
    if users:
        rep.add("INFO", "docker-group", f"These accounts can control Docker: {', '.join(users)}.",
                "Being in the docker group is the same as having root: a docker command can mount the whole disk.",
                "Keep this group to the people who already have sudo:  sudo gpasswd -d <name> docker", evidence=users)


def check_uid0(rep):
    extra = [l.split(":")[0] for l in read("/etc/passwd").splitlines()
             if l.count(":") >= 3 and l.split(":")[2] == "0" and l.split(":")[0] != "root"]
    if extra:
        rep.add("CRITICAL", "uid0", f"Other accounts have full root power: {', '.join(extra)}.",
                "A second root account is a classic way attackers hide a backdoor login.",
                "Unless you created them on purpose: sudo userdel <name>  (and treat the server as compromised)",
                evidence=extra)


def check_ld_preload(rep):
    txt = read("/etc/ld.so.preload").strip()
    if txt:
        rep.add("CRITICAL", "ld-preload", "/etc/ld.so.preload is set.",
                "It loads code into every program on the system. Normal servers leave it empty; "
                "rootkits use it to hide their files and processes from you.",
                "Do not trust this system to report on itself. Back up your data and reinstall.",
                evidence=txt.splitlines()[:5])


def cron_texts():
    paths = [P("/etc/crontab")] + glob.glob(P("/etc/cron.d/*")) + glob.glob(P("/var/spool/cron/crontabs/*")) + \
        glob.glob(P("/var/spool/cron/*")) + glob.glob(P("/etc/cron.*/*"))
    for p in sorted(set(paths)):   # /etc/cron.*/* also matches /etc/cron.d/*
        if os.path.isfile(p):
            try:
                yield disp(p), open(p, errors="replace").read()
            except OSError:
                yield disp(p), None   # unreadable: reported as not checked


def check_persistence(rep):
    hits, unreadable = [], []
    for p, txt in cron_texts():
        if txt is None:
            unreadable.append(p)
            continue
        for line in txt.splitlines():
            if not line.strip().startswith("#") and SUSPICIOUS_CMD.search(line):
                hits.append(f"{p}: {line.strip()[:160]}")
    units = glob.glob(P("/etc/systemd/system/*.service")) + glob.glob(P("/lib/systemd/system/*.service")) + \
        glob.glob(P("/root/.config/systemd/user/*.service")) + glob.glob(P("/home/*/.config/systemd/user/*.service"))
    for unit in units:
        try:
            txt = open(unit, errors="replace").read()
        except OSError:
            unreadable.append(disp(unit))
            continue
        for line in txt.splitlines():
            if line.startswith("Exec") and "=" in line and (
                    _exec_runs_from_temp(line.split("=", 1)[1].strip()) or SUSPICIOUS_EXEC.search(line)):
                hits.append(f"{disp(unit)}: {line.strip()[:160]}")
    # Shell start-up files run at every login: root's, every user's, and the system-wide ones.
    rcs = [P("/etc/rc.local")] + glob.glob(P("/etc/profile.d/*.sh")) + [P("/etc/profile"), P("/etc/bash.bashrc")]
    for home in [P("/root")] + glob.glob(P("/home/*")):
        rcs += [os.path.join(home, n) for n in (".bashrc", ".profile", ".bash_profile", ".bash_login", ".zshrc")]
    for rc in sorted(set(rcs)):
        try:
            txt = open(rc, errors="replace").read()
        except OSError:
            continue
        for line in txt.splitlines():
            if not line.strip().startswith("#") and SUSPICIOUS_CMD.search(line):
                hits.append(f"{disp(rc)}: {line.strip()[:160]}")
    if unreadable:
        rep.skip("persistence", f"{len(unreadable)} startup files unreadable without root, e.g. {unreadable[0]}")
    if hits:
        rep.add("HIGH", "persistence",
                "Something is set to start automatically in a way malware typically uses.",
                "Downloading a script and piping it to a shell, decoding hidden commands, or running from "
                "temporary folders at every boot or every minute is how miners and botnets come back after you kill them.",
                "Read each line below. If you didn't put it there, delete that line or unit, then look for what "
                "it starts (see the process findings).",
                evidence=hits[:20])


def proc_exe(pid):
    try:
        return os.readlink(P(f"/proc/{pid}/exe"))
    except OSError:
        return None


# Hidden folders where ordinary tools install themselves. Any OTHER hidden folder in a
# program's path (~/.configrc, /var/tmp/.x) is how miners and botnets hide.
STANDARD_DOTDIRS = {".local", ".cargo", ".rustup", ".npm", ".nvm", ".pyenv", ".vscode-server",
                    ".cursor-server", ".bun", ".deno", ".volta", ".sdkman", ".asdf", ".linuxbrew"}


def hidden_or_temp(path):
    path = path.replace(" (deleted)", "")
    hidden = [c for c in path.split("/") if c.startswith(".") and c not in STANDARD_DOTDIRS]
    return any(path.startswith(t + "/") for t in TEMP_DIRS) or bool(hidden) or path.count("/") == 1


def check_processes(rep):
    if ROOT != "/":
        rep.skip("processes", "not scanning the live system")
        return
    bad, deleted, temp = [], [], []
    for d in os.listdir("/proc"):
        if not d.isdigit():
            continue
        comm = read(f"/proc/{d}/comm").strip()
        exe = proc_exe(d)
        if comm.lower() in MINER_NAMES or (exe and os.path.basename(exe).lower() in MINER_NAMES):
            bad.append(f"pid {d} {comm} {exe or ''}")
        if exe and exe.endswith(" (deleted)") and not exe.startswith(("/usr/", "/lib", "/opt/")):
            deleted.append(f"pid {d} {comm} {exe}")
        if exe and any(exe.startswith(t + "/") for t in TEMP_DIRS):
            temp.append(f"pid {d} {comm} {exe}")
    if bad:
        rep.add("CRITICAL", "miner", "A known crypto-miner is running.",
                "Someone is using your CPU to mine coins. They got in somehow, and they can come back.",
                "Note the PIDs, find how it starts (persistence finding), remove that, then: sudo kill -9 <pid>. "
                "Change passwords and keys; consider a reinstall.", evidence=bad)
    # A deleted file in a temp or hidden folder is the malware pattern; anywhere else it is
    # usually a program that updated itself while running (seen: Claude Code in ~/.local).
    sneaky = [d for d in deleted if hidden_or_temp(d.split(" ", 3)[3])]
    benign = [d for d in deleted if d not in sneaky]
    if sneaky:
        rep.add("HIGH", "deleted-binary", "A program is running from a deleted file in a temporary or hidden folder.",
                "Malware deletes its own file after starting so you can't find it on disk.",
                "Copy it for analysis before killing: sudo cp /proc/<pid>/exe /root/suspect.bin; then sudo kill <pid>",
                evidence=sneaky)
    if benign:
        rep.add("LOW", "deleted-binary-updated", "A program is still running from a file that has since been replaced or removed.",
                "This is usually a program that updated itself while running, which is harmless. If you don't recognise it, check it.",
                "Restart the program to clear this. To inspect it first: ls -la /proc/<pid>/exe",
                evidence=benign)
    if temp:
        rep.add("HIGH", "temp-exec", "A program is running from a temporary folder.",
                "Real software is installed in /usr or /opt. Droppers run from /tmp and /dev/shm because anyone can write there.",
                "Check what it is (ls -la /proc/<pid>/exe) and kill it if you don't recognise it.", evidence=temp)


def listening():
    out = []
    for fam, f in (("4", "/proc/net/tcp"), ("6", "/proc/net/tcp6")):
        for line in read(f).splitlines()[1:]:
            parts = line.split()
            if len(parts) < 4 or parts[3] != "0A":  # 0A = LISTEN
                continue
            addr, port = parts[1].split(":")
            port = int(port, 16)
            if fam == "4":
                ip = socket.inet_ntop(socket.AF_INET, bytes.fromhex(addr)[::-1])
            else:
                b = bytes.fromhex(addr)
                ip = socket.inet_ntop(socket.AF_INET6, b"".join(b[i:i + 4][::-1] for i in range(0, 16, 4)))
            out.append((ip, port))
    return out


def check_ports(rep):
    exposed = []
    for ip, port in listening():
        if port in RISKY_PORTS and not ipaddress.ip_address(ip).is_loopback:
            exposed.append(f"{RISKY_PORTS[port]} on {ip}:{port}")
    if exposed:
        rep.add("HIGH", "exposed-services", "A database or admin service is listening on a network address.",
                "Exposed Redis, Docker, MongoDB and Elasticsearch are among the most attacked things on the internet; "
                "bots find them within hours and use them to plant miners or steal data.",
                "Bind it to 127.0.0.1 in its config, or block the port with your firewall "
                "(e.g. sudo ufw deny <port>). Check the firewall really applies: Docker-published ports skip ufw.",
                evidence=sorted(set(exposed)))


TEMP_BUDGET_FILES = 20000
TEMP_BUDGET_S = 15


def check_temp_executables(rep):
    """Look for compiled programs in temp folders, within a budget: some servers keep
    millions of files in /tmp, and a scan that never finishes protects nobody. The
    small, high-signal folders go first; a walk cut short says so in "Not checked"."""
    found, suid = [], []
    seen = 0
    t0 = time.time()
    cut = None
    for t in ["/dev/shm", "/var/tmp", "/tmp"]:
        if cut:
            break
        for dirpath, dirs, files in os.walk(P(t)):
            if seen >= TEMP_BUDGET_FILES or time.time() - t0 > TEMP_BUDGET_S:
                cut = f"stopped after {seen} files in {int(time.time() - t0)}s, in {disp(dirpath)}"
                break
            seen += len(files)
            if dirpath.count(os.sep) - P(t).count(os.sep) > 3:
                dirs[:] = []
            for n in files:
                fp = os.path.join(dirpath, n)
                # Only regular files: opening a FIFO blocks forever, and a symlink
                # could point anywhere.
                try:
                    mode = os.lstat(fp).st_mode
                    if not stat.S_ISREG(mode):
                        continue
                    if mode & (stat.S_ISUID | stat.S_ISGID):
                        suid.append(disp(fp))
                    with open(fp, "rb") as f:
                        head = f.read(4)
                except OSError:
                    continue
                if head == b"\x7fELF":
                    found.append(disp(fp))
    if cut:
        rep.skip("temp-binaries", "temp folders too large to finish: " + cut)
    if suid:
        rep.add("CRITICAL", "temp-setuid", "A program in a temporary folder runs with its owner's power (setuid).",
                "A setuid copy of a shell left in /tmp is a well-known way back to root after a break-in.",
                "Remove it (sudo rm <path>), then treat the server as compromised: check the other findings.",
                evidence=suid[:20])
    if found:
        rep.add("MEDIUM", "temp-binaries", "Compiled programs are sitting in temporary folders.",
                "Attackers drop their tools in /tmp, /var/tmp and /dev/shm.",
                "Check each one (file <path>; sha256sum <path>). Delete what you don't recognise.", evidence=found[:20])


def check_bruteforce(rep):
    text = ""
    for f in ("/var/log/auth.log", "/var/log/secure"):
        text += read(f)
    if not text and ROOT == "/" and shutil.which("journalctl"):
        r = subprocess.run(["journalctl", "-q", "--since", "-24h", "-t", "sshd", "-t", "sshd-session", "--no-pager"],
                           capture_output=True, text=True)
        text = r.stdout
    if not text:
        rep.skip("ssh-attempts", "no readable SSH log (run as root)")
        return
    ips = {}
    # Read the log in order: a password accepted AFTER failures from the same address is what a
    # guessed password looks like. A KEY login after a few typos is the owner, not a guess, and an
    # address that already logged in before, or one on a private network, is far more likely the
    # owner mistyping (matches the suite's break-in rules R4-R6).
    seen_ok, failed, guessed = set(), set(), {}
    for m in re.finditer(r"(?:(?:Failed password|Invalid user \S*) .*?from (\S+))|"
                         r"(?:Accepted (password|publickey|keyboard-interactive/pam) for \S+ from (\S+))", text):
        if m.group(1):
            ip = m.group(1)
            ips[ip] = ips.get(ip, 0) + 1
            failed.add(ip)
            continue
        how, ip = m.group(2), m.group(3)
        if how != "publickey" and ip in failed and ip not in guessed:
            guessed[ip] = ip in seen_ok
        seen_ok.add(ip)
    n = sum(ips.values())
    if n:
        top = sorted(ips.items(), key=lambda kv: -kv[1])[:5]
        rep.add("INFO" if n < 100 else "LOW", "ssh-attempts",
                f"{n} failed SSH logins from {len(ips)} addresses in the log.",
                "This is normal background noise for any server on the internet. It only matters if passwords are allowed "
                "(see the ssh-passwords finding) or if one of these addresses also logged in successfully.",
                "Optional: sudo apt install fail2ban",
                evidence=[f"{ip}: {c}" for ip, c in top])
        def _known(ip):
            try:
                a = ipaddress.ip_address(ip)
            except ValueError:
                return False
            return a.is_private or a.is_loopback or a.is_link_local
        strangers = sorted(ip for ip, before in guessed.items() if not before and not _known(ip))
        familiar = sorted(ip for ip in guessed if ip not in strangers)
        if strangers:
            rep.add("HIGH", "login-after-failures", "An address that failed to log in later logged in with a password.",
                    "That's what a successful password guess looks like.",
                    "Check who that was (last -i). If it wasn't you, treat the server as compromised.", evidence=strangers)
        if familiar:
            rep.add("LOW", "login-after-failures",
                    "Someone mistyped a password, then logged in, from an address you use.",
                    "The address had logged in before or is on a private network, so this is most likely you or a colleague.",
                    "Nothing to do if that was you. If not, check it:  last -i", evidence=familiar)


def check_reboot(rep):
    if os.path.exists(P("/var/run/reboot-required")) or os.path.exists(P("/run/reboot-required")):
        pk = read("/run/reboot-required.pkgs") or read("/var/run/reboot-required.pkgs")
        rep.add("LOW", "reboot-required", "Updates are installed but wait for a reboot.",
                "Kernel and system library fixes only protect you after a restart.",
                "Restart when convenient:  sudo reboot", evidence=sorted(set(pk.split()))[:10])


def check_updates(rep):
    if ROOT != "/" or not shutil.which("apt-get"):
        rep.skip("updates", "apt not available")
        return
    if not os.path.exists("/etc/apt/apt.conf.d/20auto-upgrades") or 'Unattended-Upgrade "1"' not in read("/etc/apt/apt.conf.d/20auto-upgrades"):
        rep.add("MEDIUM", "auto-updates", "Security updates are not installed automatically.",
                "Most break-ins use holes that were fixed weeks earlier.",
                "  sudo apt install unattended-upgrades && sudo dpkg-reconfigure -plow unattended-upgrades")


def _catalog_hashes():
    """{sha256: family} for every VERIFIED full hash in the Astra catalog (families dir)."""
    cf = os.environ.get("CATALOG_FILE") or _CATALOG
    try:
        cat = json.load(open(cf))
    except Exception:
        return {}
    out = {}
    for fam in cat:
        for h in fam.get("known_hashes_sha256", []):
            if re.fullmatch(r"[0-9a-f]{64}", h or ""):
                out[h] = fam["family"]
    return out


def check_catalog_hashes(rep):
    """Flag files whose sha256 matches a verified-bad hash in the catalog. High certainty,
    so this is the ONE catalog signal the scanner acts on by itself -- names and paths from
    the catalog are observations, not proof, and are not auto-matched here."""
    known = _catalog_hashes()
    if not known:
        rep.skip("catalog-hash", "no catalog hashes available")
        return
    import hashlib
    seen, hits, n = set(), [], 0
    cands = []
    for t in TEMP_DIRS:
        d = P(t)
        if os.path.isdir(d):
            for dp, _, files in os.walk(d):
                for fn in files:
                    cands.append(os.path.join(dp, fn))
    # plus specific absolute file paths the catalog names (skip templates and directories)
    try:
        cat = json.load(open(os.environ.get("CATALOG_FILE") or _CATALOG))
    except Exception:
        cat = []
    homes = [P("/root")] + glob.glob(P("/home/*"))
    for fam in cat:
        for pth in fam.get("host_footprints", {}).get("paths", []):
            if "<" in pth or pth.endswith("/") or "(" in pth:
                continue
            if pth.startswith("~/"):
                cands += [os.path.join(h, pth[2:]) for h in homes]
            elif pth.startswith("$HOME/"):
                cands += [os.path.join(h, pth[6:]) for h in homes]
            elif pth.startswith("/"):
                cands.append(P(pth))
    for fp in cands:
        if n >= 20000:
            break
        try:
            if os.path.islink(fp) or not os.path.isfile(fp):
                continue
            st = os.stat(fp)
            if st.st_size > 200 * 1024 * 1024 or (st.st_dev, st.st_ino) in seen:
                continue
            seen.add((st.st_dev, st.st_ino)); n += 1
            h = hashlib.sha256()
            with open(fp, "rb") as fh:
                for b in iter(lambda: fh.read(1024 * 1024), b""):
                    h.update(b)
            dg = h.hexdigest()
            if dg in known:
                hits.append(f"{disp(fp)} = {known[dg]} (sha256 {dg[:16]}...)")
        except OSError:
            continue
    if hits:
        rep.add("CRITICAL", "catalog-hash",
                "A file here matches a known-bad malware hash.",
                "This file's exact contents are on our threat catalog's verified-bad list, so this is a "
                "confirmed malware artefact, not a guess by name. The host should be treated as compromised.",
                "Preserve evidence, then follow the removal steps for that family (see scan/families and "
                "docs). Rotate credentials and rebuild if it ran with privilege.",
                evidence=hits[:20])


# Families that are kernel/user-space rootkits, or otherwise cannot be trusted to in-place
# clean: the scanner DETECTS and ADVISES a rebuild and must NEVER offer to remove them
# (Master Plan fix factory: REBUILD-ONLY). This set is the authoritative removability tag
# from the review-queue records (their `removability` field), which OVERRIDES the thinner
# Astra catalog. A family here can never get a removal module, even once approved.
# Kinsing is here (D57 corrected 2026-10-14): the cited record documents an ld.so.preload
# rootkit (/etc/libsystem.so) that hides files/processes. Chaos is here conservatively
# (two records disagree on removability; advise-only until Andrew rules at review).
REBUILD_ONLY = {"Skidmap", "Reptile", "perfctl", "BPFDoor", "Kinsing",
                "XorDDoS", "PwnRig", "HeadCrab", "P2PInfect", "PumaBot", "Chaos"}


def check_rebuild_only(rep):
    """Report-only detect-and-advise for rootkit families. Fires only on corroboration:
    >=2 path-anchored indicators present, OR a kernel module (.ko) at a named path, OR a
    verified-hash file. Never a single ambiguous name. No removal is ever offered."""
    try:
        cat = json.load(open(os.environ.get("CATALOG_FILE") or _CATALOG))
    except Exception:
        rep.skip("rebuild-advise", "catalog not available")
        return
    known = _catalog_hashes()
    import hashlib
    for fam in cat:
        name = fam.get("family")
        if name not in REBUILD_ONLY:
            continue
        hf = fam.get("host_footprints", {})
        cands = [x for x in hf.get("paths", []) if x.startswith("/") and "<" not in x and "(" not in x and not x.endswith("/")]
        cands += [c.split()[0] for c in hf.get("cron", []) if c.startswith("/")]
        hits, kmod, hashhit = [], False, False
        for pth in cands:
            fp = P(pth)
            if os.path.exists(fp):
                hits.append(disp(fp))
                if pth.endswith(".ko"):
                    kmod = True
                if os.path.isfile(fp) and not os.path.islink(fp):
                    try:
                        h = hashlib.sha256()
                        with open(fp, "rb") as fh:
                            for b in iter(lambda: fh.read(1024 * 1024), b""):
                                h.update(b)
                        if h.hexdigest() in known:
                            hashhit = True
                    except OSError:
                        pass
        corroborated = len(hits) >= 2 or kmod or hashhit
        if corroborated:
            rep.add("CRITICAL", "rebuild-advise",
                    f"Signs of {name}, a rootkit-class threat, are present on this host.",
                    f"{name} operates at a level where in-place cleanup cannot be trusted to have "
                    "fully removed it (hidden kernel modules, replaced system tools, or stealth "
                    "persistence). A scan that stops finding it is not proof it is gone. "
                    "(Indicators are a MinakiLabs research draft, pending human review; report-only.)",
                    fix=("Treat this host as compromised: back up your data, REBUILD from trusted "
                         "install media, and rotate every credential and SSH key it held. Do NOT rely "
                         "on deleting these files in place. This tool will not auto-remove a rootkit."),
                    fix_id=None,
                    evidence=hits + ([f"kernel module (.ko) at a named path"] if kmod else [])
                             + ([f"a file matches a verified-bad hash"] if hashhit else []))


def check_outlaw(rep):
    """The Outlaw (Dota/Shellbot) family: detect its footprint with corroboration, offer removal."""
    if _outlaw is None:
        rep.skip("outlaw", "family module not available")
        return
    try:
        r = _outlaw.scan(ROOT)
    except Exception as e:
        rep.skip("outlaw", f"module error: {type(e).__name__}: {e}")
        return
    for f in r["findings"]:
        rep.add(f["severity"], "outlaw-" + f["id"].replace("outlaw", "").strip("-") if f["id"] != "outlaw" else "outlaw",
                f["what"], f["why"],
                fix=("Remove the confirmed Outlaw footprint (keys, cron, payload trees, and any process "
                     "running from inside a tree), then re-scan:\n  sudo minaki-scan --fix"
                     if f.get("confirmed") else
                     "Not confirmed on its own. Corroborate by hand before removing anything."),
                fix_id="outlaw-remove" if f.get("confirmed") else None,
                evidence=f["evidence"])


def check_sysrv(rep):
    """The Sysrv (Sysrv-hello) cryptominer botnet: detect by known-bad hash (with weak
    corroboration), offer removal of ONLY the hash-anchored artefacts."""
    if _sysrv is None:
        rep.skip("sysrv", "family module not available")
        return
    try:
        r = _sysrv.scan(ROOT)
    except Exception as e:
        rep.skip("sysrv", f"module error: {type(e).__name__}: {e}")
        return
    for f in r["findings"]:
        removable = f.get("confirmed") and r.get("removable")
        if removable:
            fix = ("Remove the confirmed Sysrv files and miner processes (hash-anchored only), then "
                   "re-scan:\n  sudo minaki-scan --fix\nThen follow the advice above by hand: review cron, "
                   "SSH keys and web files, and rotate the exposed credentials.")
        elif f.get("confirmed"):
            fix = ("Not safely removable automatically: corroborate the weak signals by hashing the "
                   "suspect files/processes, then clean by hand following the advice above.")
        else:
            # a lone weak sign (INFO note): don't alarm — this is usually legitimate.
            fix = "No action needed unless you don't recognise these files; then check them by hand."
        rep.add(f["severity"],
                "sysrv-" + f["id"].replace("sysrv", "").strip("-") if f["id"] != "sysrv" else "sysrv",
                f["what"], f["why"], fix=fix,
                fix_id="sysrv-remove" if removable else None,
                evidence=f["evidence"] + ["advice: " + a for a in f.get("advice", [])])


def check_prometei(rep):
    """The Prometei botnet (Linux variant): detect by known-bad hash, a structured systemd unit,
    or the exact published cron line; offer gated removal of those anchored artefacts."""
    if _prometei is None:
        rep.skip("prometei", "family module not available")
        return
    try:
        r = _prometei.scan(ROOT)
    except Exception as e:
        rep.skip("prometei", f"module error: {type(e).__name__}: {e}")
        return
    for f in r["findings"]:
        removable = f.get("confirmed") and r.get("removable")
        fix = ("Remove the confirmed Prometei service, cron line, binaries and data (anchored only), then "
               "re-scan:\n  sudo minaki-scan --fix\nThen follow the advice above: review other cron/keys/units "
               "by hand and rotate the exposed credentials."
               if removable else
               "Not safely removable automatically: " + ("corroborate the weak signals" if f.get("confirmed")
               else "corroborate before acting") + ", then clean by hand following the advice above.")
        rep.add(f["severity"],
                "prometei-" + f["id"].replace("prometei", "").strip("-") if f["id"] != "prometei" else "prometei",
                f["what"], f["why"], fix=fix,
                fix_id="prometei-remove" if removable else None,
                evidence=f["evidence"] + ["advice: " + a for a in f.get("advice", [])])


def _check_family(rep, name):
    """Generic wiring for a hash-anchored SAFELY-REMOVABLE family module (muhstik/dreambus/redtail)."""
    mod = _families.get(name)
    if mod is None:
        rep.skip(name, "family module not available")
        return
    try:
        r = mod.scan(ROOT)
    except Exception as e:
        rep.skip(name, f"module error: {type(e).__name__}: {e}")
        return
    for f in r["findings"]:
        removable = f.get("confirmed") and r.get("removable")
        fix = (f"Remove the confirmed {name} artefacts (hash-anchored only), then re-scan:\n"
               "  sudo minaki-scan --fix\nThen follow the advice above by hand and rotate exposed credentials."
               if removable else
               "Not safely removable automatically: " + ("corroborate the weak signals" if f.get("confirmed")
               else "corroborate before acting") + ", then clean by hand following the advice above.")
        rep.add(f["severity"],
                f"{name}-" + f["id"].replace(name, "").strip("-") if f["id"] != name else name,
                f["what"], f["why"], fix=fix,
                fix_id=f"{name}-remove" if removable else None,
                evidence=f["evidence"] + ["advice: " + a for a in f.get("advice", [])])


def check_muhstik(rep):  _check_family(rep, "muhstik")
def check_dreambus(rep): _check_family(rep, "dreambus")
def check_redtail(rep):  _check_family(rep, "redtail")
def check_mirai(rep):    _check_family(rep, "mirai")


def check_world_writable_path(rep):
    """World-writable directories in root's PATH: anyone can drop a program there and have root run
    it by name — a direct path to full control. First-party core check (was the reference plugin;
    moved into the core 2026-10-15 when unsigned plugins were gated off, D71). Read-only."""
    default_path = ["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"]
    dirs = None
    for rel in ("root/.profile", "root/.bashrc", "etc/environment"):
        p = os.path.join(ROOT, rel)
        try:
            for line in open(p, errors="replace"):
                if "PATH=" in line and "/" in line:
                    val = line.split("PATH=", 1)[1].strip().strip('"').strip("'")
                    got = [d for d in val.replace("$PATH", "").split(":") if d.startswith("/")]
                    if got:
                        dirs = got
                        break
        except OSError:
            pass
        if dirs:
            break
    for d in (dirs or default_path):
        full = d if ROOT == "/" else os.path.join(ROOT, d.lstrip("/"))
        try:
            st = os.stat(full)
        except OSError:
            continue
        if not stat.S_ISDIR(st.st_mode):
            continue
        if (st.st_mode & stat.S_IWOTH) and not (st.st_mode & stat.S_ISVTX):
            rep.add("HIGH", "world-writable-path",
                    f"{d} is in root's PATH and is writable by anyone.",
                    "Any user can place a program there and have root run it by that name — a direct "
                    "path to full control of the machine.",
                    fix=f"Remove world-write, or add the sticky bit if it must be shared:\n"
                        f"  sudo chmod o-w {d}    # or: sudo chmod +t {d}",
                    evidence=[f"{d}: mode {oct(st.st_mode & 0o7777)}, world-writable, not sticky"])


def _hardening_check(name):
    """Scan's check for hardening.<name>: the module reads the same --root, and a missing module is said, not hidden."""
    def check(rep):
        if _hardening is None:
            rep.skip(name[6:].replace("_", "-"), "the hardening checks are not installed")
            return
        _hardening.ROOT = ROOT
        getattr(_hardening, name)(rep)
    check.__name__ = name
    return check


check_firewall = _hardening_check("check_firewall")
check_time_sync = _hardening_check("check_time_sync")
check_core_dumps = _hardening_check("check_core_dumps")
check_kernel_network = _hardening_check("check_kernel_network")
check_world_writable_system = _hardening_check("check_world_writable_system")


def check_backups(rep):
    """Frontier G9 (D79): restic/borg jobs, their last run, and whether a copy leaves this server."""
    if _backupcheck is None:
        rep.skip("backups", "the backup check is not installed")
        return
    _backupcheck.ROOT = ROOT
    _backupcheck.check_backups(rep)

# The system-folder walk goes last (D78): on a busy server it is the slowest check after the families, and
# it has its own 10 s budget, so everything else is already in the report if it is cut short.
CHECKS = [check_ssh, check_authorized_keys, check_accounts, check_uid0, check_sudoers, check_ld_preload,
          check_world_writable_path, check_outlaw, check_sysrv, check_prometei, check_muhstik, check_dreambus, check_redtail, check_mirai,
          check_catalog_hashes, check_rebuild_only, check_persistence, check_processes, check_ports, check_temp_executables, check_bruteforce,
          check_reboot, check_updates, check_firewall, check_time_sync, check_core_dumps, check_kernel_network,
          check_backups, check_world_writable_system]


# ---------------------------------------------------------------- fixes (approval required)
STATE = "/var/lib/minaki-scan"
DROPIN = "/etc/ssh/sshd_config.d/00-minaki-scan.conf"
FIX_LINES = {"ssh-no-passwords": ["PasswordAuthentication no", "KbdInteractiveAuthentication no"],
             "ssh-root-keys-only": ["PermitRootLogin prohibit-password"],
             "ssh-no-empty-passwords": ["PermitEmptyPasswords no"]}


def audit(msg):
    os.makedirs(STATE, exist_ok=True)
    with open(os.path.join(STATE, "changes.log"), "a") as f:
        f.write(time.strftime("%Y-%m-%dT%H:%M:%SZ ", time.gmtime()) + msg + "\n")


def apply_ssh_fix(fix_id):
    if not os.path.isdir("/etc/ssh/sshd_config.d") or "Include /etc/ssh/sshd_config.d/" not in read("/etc/ssh/sshd_config"):
        print("  This system's sshd doesn't read /etc/ssh/sshd_config.d; apply the fix by hand.")
        return False
    users = [u for u in pwd.getpwall() if u.pw_uid == 0 or 1000 <= u.pw_uid < 60000]
    if fix_id == "ssh-no-passwords" and not any(os.path.getsize(os.path.join(u.pw_dir, ".ssh/authorized_keys")) > 0
                                                for u in users if os.path.isfile(os.path.join(u.pw_dir, ".ssh/authorized_keys"))):
        print("  Refusing: no account has an SSH key, so turning off passwords would lock you out.")
        return False
    backup = os.path.join(STATE, "backup", time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()))
    os.makedirs(backup, exist_ok=True)
    existed = os.path.exists(DROPIN)
    if existed:
        shutil.copy2(DROPIN, backup)
    old = read(DROPIN) if existed else ""
    new = old + "".join(l + "\n" for l in FIX_LINES[fix_id] if l not in old)
    with open(DROPIN, "w") as f:
        f.write(new)
    if subprocess.run(["sshd", "-t"]).returncode != 0:
        if existed:
            shutil.copy2(os.path.join(backup, os.path.basename(DROPIN)), DROPIN)
        else:
            os.remove(DROPIN)
        print("  sshd rejected the new config; nothing was changed.")
        audit(f"{fix_id} REVERTED: sshd -t failed")
        return False
    unit = "ssh" if subprocess.run(["systemctl", "cat", "ssh"], capture_output=True).returncode == 0 else "sshd"
    subprocess.run(["systemctl", "reload", unit], check=False)
    undo = f"sudo cp {backup}/{os.path.basename(DROPIN)} {DROPIN}" if existed else f"sudo rm {DROPIN}"
    audit(f"{fix_id} applied to {DROPIN}; undo: {undo} && sudo systemctl reload {unit}")
    print(f"  Done. Keep this session open and test a NEW login before closing it.\n  Undo: {undo} && sudo systemctl reload {unit}")
    return True


def offer_fixes(rep):
    """Offer each fix one at a time; apply only on 'yes'. Returns the number of fixes applied, so
    the caller can re-scan and report/exit on the state AFTER the fixes (P5)."""
    applied = [0]
    offered = [0]
    mods = {"outlaw-remove": _outlaw, "sysrv-remove": _sysrv, "prometei-remove": _prometei,
            "muhstik-remove": _families.get("muhstik"), "dreambus-remove": _families.get("dreambus"),
            "redtail-remove": _families.get("redtail"), "mirai-remove": _families.get("mirai")}
    prompts = {
        "outlaw-remove": "Remove the confirmed Outlaw footprint?",
        "sysrv-remove": "Remove the confirmed Sysrv files and miner processes (hash-anchored only; cron/keys left for you)?",
        "prometei-remove": "Remove the confirmed Prometei service, cron, binaries and data (anchored only)?",
        "muhstik-remove": "Remove the confirmed Muhstik artefacts (hash-anchored only; other keys/cron left for you)?",
        "dreambus-remove": "Remove the confirmed DreamBus artefacts (hash-anchored only)?",
        "redtail-remove": "Remove the confirmed RedTail artefacts (hash-anchored only)?",
        "mirai-remove": "Remove the confirmed Mirai artefacts (hash-anchored only)?",
    }
    for fix_id, mod in mods.items():
        fixable = [x for x in rep.findings if x["fix_id"] == fix_id]
        if not fixable or mod is None:
            continue
        if os.geteuid() != 0 and ROOT == "/":
            print(f"\nRun with sudo to apply the {fix_id.split('-')[0]} removal.")
            continue
        for _f in fixable:
            offered[0] += 1
            if input(f"\n{prompts[fix_id]} Type yes to apply: ").strip().lower() == "yes":
                clean, _ = mod.remediate(ROOT, assume_yes=True, log=lambda m: print("  " + m))
                audit(f"{fix_id} on {ROOT}: {'clean' if clean else 'STILL CONFIRMED'}")
                applied[0] += 1
            else:
                print("  Skipped.")

    fixable = [f for f in rep.findings if f["fix_id"] in FIX_LINES]
    if fixable and os.geteuid() != 0:
        print("\nRun with sudo to apply fixes.")
    else:
        for f in fixable:
            offered[0] += 1
            if input(f"\nApply fix for '{f['what']}'? Type yes to apply: ").strip().lower() == "yes":
                if apply_ssh_fix(f["fix_id"]):
                    applied[0] += 1
            else:
                print("  Skipped.")

    if offered[0] == 0:
        print("\nNo automatic fixes apply. Run the commands shown above yourself.")
    return applied[0]


def build_report():
    """Run every check + the rule packs + detection plugins; return a sorted Report. Reusable so
    --fix can re-scan after applying fixes."""
    rep = Report()
    for i, c in enumerate(CHECKS, 1):
        if PROGRESS:
            name = c.__name__[6:] if c.__name__.startswith("check_") else c.__name__
            sys.stderr.write(f"\r\033[K  Checking {i} of {len(CHECKS)}: {name.replace('_', ' ')}...")
            sys.stderr.flush()
        try:
            c(rep)
        except Exception as e:
            rep.skip(c.__name__, f"check failed: {type(e).__name__}: {e}")
    if PROGRESS:
        sys.stderr.write("\r\033[K"); sys.stderr.flush()
    if _rules is not None:
        try:
            for f in _rules.scan(ROOT).get("findings", []):
                rep.add(f.get("severity", "MEDIUM"), "rule:" + f.get("pack", "?"),
                        f.get("what", ""), f.get("why", ""), fix=None, evidence=f.get("evidence"))
        except Exception as e:
            rep.skip("rules", f"rule engine error: {type(e).__name__}: {e}")
    if _plugins is not None:
        try:
            ctx = _plugins.PluginContext(ROOT, _FAMILIES_DIR or os.path.join(_HERE, "families"))
            for f in _plugins.run_detection(ctx, ALLOW_UNSIGNED_PLUGINS):
                rep.add(f.get("severity", "INFO"), "plugin:" + f.get("_plugin", "?"),
                        f.get("what", ""), f.get("why", ""), fix=f.get("fix"), evidence=f.get("evidence"))
        except Exception as e:
            rep.skip("plugins", f"plugin seam error: {type(e).__name__}: {e}")
    rep.findings.sort(key=lambda f: -SEV[f["severity"]])
    return rep


def _worst(rep):
    return max([SEV[f["severity"]] for f in rep.findings], default=0)


TUNER_URL = "https://minakilabs.com/minaki/#tuner"


def _tuner_fits(os_release, machine, kernel):
    """True only where Minaki Tuner is offered (Ubuntu 24.04 LTS, x86_64, the standard 6.8 kernel). The scan never
    contacts anyone: this only decides whether to print one line pointing to it (#5207)."""
    kv = dict(l.split("=", 1) for l in os_release.splitlines() if "=" in l)
    clean = {k: v.strip().strip('"') for k, v in kv.items()}
    return (clean.get("ID") == "ubuntu" and clean.get("VERSION_ID") == "24.04" and machine == "x86_64"
            and kernel.startswith("6.8.0-"))


def _tuner_line():
    try:
        osr = open("/etc/os-release").read()
    except OSError:
        return None
    u = os.uname()
    if not _tuner_fits(osr, u.machine, u.release):
        return None
    return ("Want this server hardened, with proof it still does its job? Minaki Tuner works on a copy of it: "
            + TUNER_URL)


def _verdict(rep):
    # The headline uses the same words as the per-finding labels: CRITICAL = "serious", HIGH = "important".
    crit = sum(1 for f in rep.findings if f["severity"] == "CRITICAL")
    high = sum(1 for f in rep.findings if f["severity"] == "HIGH")
    if not rep.findings:
        return "Result: nothing found by these checks. (That is not proof the machine is clean.)"
    if crit or high:
        n = crit + high
        other = len(rep.findings) - n
        kinds = " and ".join(([f"{crit} serious"] if crit else []) + ([f"{high} important"] if high else []))
        return (f"Result: {kinds} problem{'s' if n != 1 else ''} to deal with"
                + (f" (plus {other} other note{'s' if other != 1 else ''})." if other else "."))
    if _worst(rep) == 0:   # only INFO notes — nothing that needs fixing
        n = len(rep.findings)
        return f"Result: nothing to fix — {n} note{'s' if n != 1 else ''} for your awareness."
    return f"Result: {len(rep.findings)} thing{'s' if len(rep.findings) != 1 else ''} worth a look, nothing marked serious."


def _family_modules_loaded():
    return any([_outlaw, _sysrv, _prometei] + list(_families.values()))


# ---------------------------------------------------------------- output
def main():
    global ROOT
    ap = argparse.ArgumentParser(description="Read-only security check for Linux servers.")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--fix", action="store_true", help="offer fixes, one at a time, after the scan")
    ap.add_argument("--root", default="/")
    ap.add_argument("--list-plugins", action="store_true", help="list discovered plugins and their gate status")
    ap.add_argument("--list-rules", action="store_true", help="list discovered YARA rule packs and their gate status")
    ap.add_argument("--advanced", action="store_true", help="show full evidence, skipped checks, and diagnostics")
    ap.add_argument("--allow-unsigned-plugins", action="store_true",
                    help="also run plugins you placed in a user folder (unsigned). Off by default; these run arbitrary code")
    ap.add_argument("--privacy", action="store_true",
                    help="say exactly what this program reads, changes and sends, then exit")
    ap.add_argument("--version", action="version", version=VERSION)
    a = ap.parse_args()
    if a.privacy:
        print(privacy_text())
        return 0
    ROOT = os.path.abspath(a.root)
    global PROGRESS
    PROGRESS = not a.json and sys.stderr.isatty()
    global ALLOW_UNSIGNED_PLUGINS
    ALLOW_UNSIGNED_PLUGINS = a.allow_unsigned_plugins
    if ALLOW_UNSIGNED_PLUGINS:
        print('WARNING: --allow-unsigned-plugins is set. Minaki Scan will run plugins from your\n'
              '         user folder. They are unsigned and run arbitrary code with this program\'s\n'
              '         privileges. Only use this with plugins you wrote or fully trust.', file=sys.stderr)
    if a.list_plugins:
        rows = _plugins.summary(a.allow_unsigned_plugins) if _plugins else []
        if not rows:
            print("No plugins found." if _plugins else "Plugin seam unavailable.")
        for r in rows:
            print(f"  [{r['type']:11}] {r['name']:24} {r['status']}")
        return 0
    if a.list_rules:
        rows = _rules.summary() if _rules else []
        if not rows:
            print("No rule packs found." if _rules else "Rule engine unavailable.")
        for r in rows:
            print(f"  {r['pack']:24} {str(r['license']):14} {r['status']}")
        return 0
    # P1(c): a tarball/partial install with no family modules must fail loudly, not silently skip.
    if ROOT == "/" and not _family_modules_loaded():
        print("Install is incomplete: the malware-family checks are missing.\n"
              "Reinstall the .deb (apt install ./minaki-scan_*.deb) or use install.sh --local, then re-run.",
              file=sys.stderr)
        return 3
    rep = build_report()
    worst = _worst(rep)
    if a.json:
        print(json.dumps({"version": VERSION, "host": socket.gethostname(), "root": ROOT,
                          "findings": rep.findings, "skipped": rep.skipped}, indent=2))
    else:
        PLAIN = {"CRITICAL": "Serious", "HIGH": "Important", "MEDIUM": "Worth a look",
                 "LOW": "Minor", "INFO": "Note"}
        adv = a.advanced
        print(f"Minaki Scan {VERSION} on {socket.gethostname()}" + ("" if ROOT == "/" else f" (scanning {ROOT})"))
        if os.geteuid() != 0 and ROOT == "/":
            print("Not running as root: some checks see less. For a full scan: sudo minaki-scan")
        print("\n" + _verdict(rep))        # one-line verdict (plain English)
        for f in rep.findings:
            print(f"\n[{PLAIN.get(f['severity'], f['severity'])}] {f['what']}")
            print(f"  Why: {f['why']}")
            for e in f["evidence"][: (50 if adv else 2)]:
                print(f"    - {e}")
            if not adv and len(f["evidence"]) > 2:
                print(f"    - …and {len(f['evidence']) - 2} more (run --advanced to see all)")
            if f["fix"]:
                print("  Fix:\n" + "\n".join("    " + l for l in f["fix"].splitlines()))
        # what-to-do-next footer (beginner), full diagnostics (advanced). Only when something is
        # actually actionable — all-INFO notes need no "run --fix" nudge.
        if rep.findings and (_worst(rep) >= 1 or any(f.get("fix_id") for f in rep.findings)):
            top = rep.findings[0]
            print("\nWhat to do next:")
            print(f"  1. Start with the first item above ({PLAIN.get(top['severity'], top['severity'])}).")
            print("  2. Nothing changes until you approve it: run  sudo minaki-scan --fix")
            if not adv:
                print("  3. Want the raw detail? run  minaki-scan --advanced   (or --json for machines)")
        if adv:
            print(f"\nDiagnostics: root={ROOT}  euid={os.geteuid()}  checks={len(CHECKS)}  "
                  f"plugins={'on' if _plugins else 'off'}")
            if rep.skipped:
                print("Not checked: " + "; ".join(f"{s['check']} ({s['reason']})" for s in rep.skipped))
        elif rep.skipped:
            print(f"\n({len(rep.skipped)} checks couldn't run — see minaki-scan --advanced)")
        if ROOT == "/":                     # only about the machine we are running on, never a mounted disk
            line = _tuner_line()
            if line:
                print("\n" + line)
    if a.fix and not a.json:
        applied = offer_fixes(rep)
        if applied:
            print(f"\nApplied {applied} fix{'es' if applied != 1 else ''}. Checking again…")
            rep = build_report()
            print(_verdict(rep))
            worst = _worst(rep)   # exit on the state AFTER the fixes, not before
    return 2 if worst >= 3 else 1 if worst == 2 else 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        sys.exit(3)
