#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
문단속 서버 점검 (mundansok-server.py)

내 리눅스 서버의 기본 보안 설정을 서버 안에서 점검한다.

원칙
  1. 읽기만 한다. 설정·파일·서비스를 하나도 바꾸지 않는다. 고치는 명령은 안내로만 보여준다.
  2. 아무것도 전송하지 않는다. 네트워크 요청을 하지 않는다. 결과는 화면과 (선택 시) 내 컴퓨터의 파일에만 남는다.
  3. 비밀 값을 출력하지 않는다. 비밀번호 해시, 키, 설정의 비밀 값은 "있다/없다"만 쓴다.
  4. 명령마다 5초, 전체 60초 안에 끝난다. 디스크 전체를 훑지 않는다.

사용
  sudo python3 mundansok-server.py              # 화면 보고서
  sudo python3 mundansok-server.py --html 보고서.html
  sudo python3 mundansok-server.py --json
  root가 아니면 가능한 항목만 점검하고, 건너뛴 항목을 알려준다.

종료 코드: 위험 항목이 있으면 2, 주의 항목이 있으면 1, 그 외 0.
대상: Ubuntu/Debian, RHEL 계열(Rocky, AlmaLinux, CentOS). Python 3.6 이상, 표준 라이브러리만 사용.
"""
import argparse
import glob
import grp
import gzip
import base64
import binascii
import hashlib
import html
import ipaddress
import json
import os
import platform
import pwd
import re
import shutil
import socket
import stat
import subprocess
import sys
import time
from datetime import date, datetime

VERSION = "1.4.1"
SITE_BASE = "https://mundansok.kr"
GUIDE_BASE = SITE_BASE + "/guide/"
CMD_TIMEOUT = 5
TOTAL_LIMIT = 60
START = time.monotonic()

# RULES-BEGIN — 문단속 보안 브리핑의 점검 규칙. tools/sync_rules.py가 briefings.py에서 써 넣는다. 손으로 고치지 않는다.
RULES_DATE = '2026-11-16'
RULES = [{'id': 'adv_apache_http2',
  'type': 'package',
  'product': 'Apache 웹 서버',
  'title': 'Apache 웹 서버 HTTP/2 원격 코드 실행 취약점',
  'slug': 'apache-http2-2026-11',
  'fixed': {'2.4': '2.4.71'},
  'binaries': [['apache2', '-v'], ['httpd', '-v'], ['/usr/sbin/apache2', '-v'], ['/usr/sbin/httpd', '-v']],
  'deb': '^apache2',
  'rpm': '^(httpd|mod_http2)',
  'cve': 'CVE-2026-119618',
  'restart': '^(apache2|httpd)',
  'restart_cmd': 'sudo systemctl restart apache2 (RHEL 계열: httpd)',
  'affected_from': '2.4.55',
  'changelog_pkgs': ['apache2', 'mod_http2'],
  'note': 'HTTP/2를 켜지 않았다면 해당하지 않으며, RHEL 8 계열과 Ubuntu 18.04 이하는 영향을 받지 않습니다. HTTP/2 사용 여부는 브리핑의 확인 명령으로 '
          '보세요'},
 {'id': 'adv_php2shell',
  'type': 'package',
  'product': 'PHP',
  'title': 'PHP 원격 코드 실행 취약점(PHP2Shell)',
  'slug': 'php2shell-2026-10',
  'fixed': {'8.2': '8.2.35', '8.3': '8.3.36', '8.4': '8.4.27', '8.5': '8.5.12'},
  'eol_below': '8.2',
  'binaries': [['php', '-r', 'echo PHP_VERSION;'],
               ['/usr/sbin/php-fpm*', '-v'],
               ['/usr/sbin/php*-fpm*', '-v']],
  'deb': '^(php|libapache2-mod-php)',
  'rpm': '^php',
  'cve': 'CVE-2026-109618',
  'restart': '^(php|lsphp|frankenphp|apache2|httpd)',
  'restart_cmd': 'sudo systemctl restart php8.3-fpm (버전에 맞게) 또는 apache2/httpd'}]
# RULES-END
RULES_STALE_DAYS = 30

LEVELS = ("danger", "warn", "info", "pass")
LEVEL_KO = {"danger": "위험", "warn": "주의", "info": "정보", "pass": "양호"}
CATEGORIES = [
    ("vuln", "알려진 취약점 (보안 브리핑)"), ("intrusion", "침해 흔적"), ("os", "운영체제"), ("ssh", "SSH"), ("account", "계정"), ("network", "방화벽·포트"),
    ("perm", "파일 권한"), ("web", "웹 폴더"), ("service", "서비스 설정"), ("misc", "기타"),
]
LIMITS = [
    "루트킷처럼 깊이 숨은 침해 (웹셸, 업로드 폴더의 실행 파일, 수상한 예약 작업·프로세스·SSH 키 같은 흔한 흔적만 봅니다)",
    "애플리케이션(게시판, 쇼핑몰 등) 코드의 취약점",
    "클라우드·호스팅 콘솔의 방화벽(보안그룹) 설정 — 서버 밖에 있어 보이지 않습니다",
    "백업이 실제로 복구되는지",
    "웹 폴더 깊숙한 곳(5단계 아래)과 정해진 웹 폴더 밖의 파일",
]

TITLES = {
    "srv_webshell": "웹셸 의심 파일",
    "srv_upload_exec": "업로드 폴더의 실행 파일",
    "srv_recent_php": "최근 바뀐 웹 프로그램 파일",
    "srv_ssh_keys": "등록된 SSH 키",
    "srv_cron_suspicious": "수상한 예약 작업",
    "srv_suspicious_proc": "수상한 프로세스",
    "srv_os_eol": "운영체제 지원 기간",
    "srv_updates": "밀린 보안 업데이트",
    "srv_reboot": "재부팅 필요",
    "srv_autoupdate": "자동 보안 업데이트",
    "srv_ssh_root": "SSH root 로그인",
    "srv_ssh_password": "SSH 비밀번호 로그인",
    "srv_ssh_empty": "SSH 빈 비밀번호 허용",
    "srv_ssh_misc": "SSH 기타 설정",
    "srv_uid0": "root 권한(UID 0) 계정",
    "srv_accounts": "로그인 가능한 계정",
    "srv_empty_password": "빈 비밀번호 계정",
    "srv_sudo_nopasswd": "비밀번호 없는 sudo",
    "srv_firewall": "서버 방화벽",
    "srv_ports": "외부에 열린 포트",
    "srv_bruteforce": "무차별 대입 방어",
    "srv_perm_system": "시스템 파일 권한",
    "srv_perm_cron": "예약 작업(cron) 권한",
    "srv_web_files": "웹 폴더의 민감한 파일",
    "srv_web_writable": "누구나 쓸 수 있는 웹 폴더",
    "srv_cms": "웹 프로그램 버전",
    "srv_php": "PHP 설정",
    "srv_advisories": "알려진 취약점",
    "srv_rules_age": "점검 규칙 기준일",
    "srv_restart": "업데이트 뒤 재시작 안 한 서비스",
    "srv_mysql": "MySQL·MariaDB 접속 주소",
    "srv_redis": "Redis 설정",
    "srv_docker": "Docker",
    "srv_disk": "디스크 사용량",
    "srv_time": "시간 동기화",
}


def finding(fid, cat, level, detail, fix=None, title=None, url=None):
    f = {"id": fid, "cat": cat, "level": level, "title": title or TITLES.get(fid, fid),
         "detail": detail, "fix": list(fix or [])}
    if url:
        f["url"] = url
    return f


def more_url(f):
    return f.get("url") or GUIDE_BASE + f["id"]


def worst(levels):
    for lv in LEVELS:
        if lv in levels:
            return lv
    return "pass"


# ---------------------------------------------------------------- 시스템 읽기 (읽기 전용)

def time_left():
    return TOTAL_LIMIT - (time.monotonic() - START)


def which(name):
    exe = shutil.which(name)
    if exe:
        return exe
    for d in ("/usr/sbin", "/sbin", "/usr/bin", "/bin", "/usr/local/sbin", "/usr/local/bin"):
        p = os.path.join(d, name)
        if os.path.isfile(p) and os.access(p, os.X_OK):
            return p
    return None


def run(cmd, timeout=CMD_TIMEOUT):
    """명령을 실행해 (종료코드, 출력)을 돌려준다. 없거나 시간 초과면 None."""
    exe = which(cmd[0])
    if not exe or time_left() <= 0:
        return None
    env = dict(os.environ, LC_ALL="C", LANG="C")
    try:
        p = subprocess.run([exe] + list(cmd[1:]), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE, timeout=min(timeout, max(1, time_left())),
                           env=env, encoding="utf-8", errors="replace")
    except (subprocess.TimeoutExpired, OSError):
        return None
    return p.returncode, p.stdout


def read_text(path, limit=2 * 1024 * 1024):
    try:
        with open(path, "r", encoding="utf-8", errors="replace") as f:
            return f.read(limit)
    except (OSError, UnicodeError):
        return None


def read_tail(path, size=5 * 1024 * 1024):
    try:
        with open(path, "rb") as f:
            f.seek(0, 2)
            end = f.tell()
            f.seek(max(0, end - size))
            return f.read().decode("utf-8", "replace")
    except OSError:
        return None


def service_active(name):
    r = run(["systemctl", "is-active", name])
    return bool(r and r[1].strip() == "active")


def service_enabled(name):
    r = run(["systemctl", "is-enabled", name])
    return bool(r and r[1].strip() in ("enabled", "enabled-runtime", "static", "alias"))


# ---------------------------------------------------------------- 판정 (순수 함수, 테스트 가능)

def parse_os_release(text):
    out = {}
    for line in (text or "").splitlines():
        m = re.match(r'^([A-Z_]+)=(.*)$', line.strip())
        if m:
            out[m.group(1)] = m.group(2).strip().strip('"').strip("'")
    return out


OS_EOL = {  # 보안 지원 종료 (대략적 날짜). Ubuntu는 표준 지원, Debian은 LTS 기준.
    ("ubuntu", "16.04"): "2021-04-30", ("ubuntu", "18.04"): "2023-05-31", ("ubuntu", "20.04"): "2025-05-31",
    ("ubuntu", "22.04"): "2027-04-30", ("ubuntu", "24.04"): "2029-04-30", ("ubuntu", "23.10"): "2024-07-11",
    ("ubuntu", "24.10"): "2025-07-10", ("ubuntu", "25.04"): "2026-01-15", ("ubuntu", "25.10"): "2026-07-15",
    ("debian", "9"): "2022-06-30", ("debian", "10"): "2024-06-30", ("debian", "11"): "2026-08-31",
    ("debian", "12"): "2028-06-30", ("debian", "13"): "2030-06-30",
    ("rhel", "7"): "2024-06-30", ("rhel", "8"): "2029-05-31", ("rhel", "9"): "2032-05-31",
    ("centos", "7"): "2024-06-30", ("centos", "8"): "2021-12-31",
    ("centos-stream", "8"): "2024-05-31", ("centos-stream", "9"): "2027-05-31",
    ("rocky", "8"): "2029-05-31", ("rocky", "9"): "2032-05-31",
    ("almalinux", "8"): "2029-05-31", ("almalinux", "9"): "2032-05-31",
}


def os_family(osr):
    ids = (osr.get("ID", "") + " " + osr.get("ID_LIKE", "")).lower().split()
    if any(i in ("debian", "ubuntu") for i in ids):
        return "debian"
    if any(i in ("rhel", "centos", "fedora", "rocky", "almalinux") for i in ids):
        return "rhel"
    return "other"


def judge_os_eol(osr, today):
    oid = osr.get("ID", "").lower()
    ver = osr.get("VERSION_ID", "")
    name = osr.get("PRETTY_NAME") or (oid + " " + ver)
    if oid == "centos" and "stream" in osr.get("NAME", "").lower():
        oid = "centos-stream"
    key = ver if oid == "ubuntu" else ver.split(".")[0]
    eol = OS_EOL.get((oid, key))
    if not eol:
        return finding("srv_os_eol", "os", "info", "{}: 지원 종료일 정보가 없어 확인하지 못했습니다.".format(name))
    end = datetime.strptime(eol, "%Y-%m-%d").date()
    days = (end - today).days
    when = "{}년 {}월경".format(end.year, end.month)
    extra = " Ubuntu Pro(ESM)에 가입했다면 연장 지원을 받고 있을 수 있습니다." if oid == "ubuntu" else ""
    if days < 0:
        return finding("srv_os_eol", "os", "danger",
                       "{}의 보안 지원이 {} 끝났습니다. 새 취약점이 나와도 패치되지 않습니다.{}".format(name, when, extra),
                       ["지원 중인 버전으로 업그레이드하거나 새 서버로 옮길 계획을 세우세요."])
    if days <= 180:
        return finding("srv_os_eol", "os", "warn",
                       "{}의 보안 지원이 {} 끝납니다 ({}일 남음).{}".format(name, when, days, extra),
                       ["업그레이드 일정을 잡으세요."])
    return finding("srv_os_eol", "os", "pass", "{}는 {}까지 보안 지원을 받습니다.".format(name, when))


def judge_apt_updates(sim_output, list_age_days):
    inst = [l for l in (sim_output or "").splitlines() if l.startswith("Inst ")]
    sec = [l for l in inst if re.search(r"-security|Debian-Security", l)]
    names = sorted({l.split()[1] for l in sec})
    age = ""
    if list_age_days is not None and list_age_days > 7:
        age = " 패키지 목록이 {}일 전 것이라 실제로는 더 많을 수 있습니다 (apt update 뒤 다시 점검하세요).".format(list_age_days)
    fix = ["sudo apt update && sudo apt upgrade"]
    if sec:
        sample = ", ".join(names[:8]) + (" 외" if len(names) > 8 else "")
        return finding("srv_updates", "os", "warn",
                       "적용되지 않은 보안 업데이트가 {}개 있습니다: {}.{}".format(len(names), sample, age), fix)
    if list_age_days is not None and list_age_days > 30:
        return finding("srv_updates", "os", "warn",
                       "패키지 목록을 {}일 동안 갱신하지 않아 업데이트 여부를 알 수 없습니다.".format(list_age_days), fix)
    if inst:
        return finding("srv_updates", "os", "info",
                       "보안 업데이트는 없고, 일반 업데이트가 {}개 있습니다.{}".format(len(inst), age), fix)
    return finding("srv_updates", "os", "pass", "밀린 업데이트가 없습니다.{}".format(age))


def judge_dnf_updates(rc, output):
    if rc not in (0, 100):
        return finding("srv_updates", "os", "info", "보안 업데이트 목록을 읽지 못했습니다 (dnf 캐시가 없을 수 있습니다).",
                       ["sudo dnf check-update --security"])
    lines = [l for l in (output or "").splitlines() if re.search(r"(RHSA|RLSA|ALSA|CESA|FEDORA)-", l)]
    pkgs = sorted({l.split()[-1] for l in lines})
    if pkgs:
        return finding("srv_updates", "os", "warn",
                       "적용되지 않은 보안 업데이트가 {}개 패키지에 있습니다.".format(len(pkgs)),
                       ["sudo dnf upgrade --security"])
    return finding("srv_updates", "os", "pass", "밀린 보안 업데이트가 없습니다 (마지막으로 받아 둔 목록 기준).")


def judge_reboot(required, pkgs_text):
    if required:
        pkgs = [p for p in (pkgs_text or "").split() if p]
        why = " ({} 등)".format(", ".join(pkgs[:4])) if pkgs else ""
        return finding("srv_reboot", "os", "warn",
                       "업데이트가 설치됐지만 재부팅 전이라 아직 적용되지 않았습니다{}.".format(why),
                       ["점검 시간에 sudo reboot"])
    return finding("srv_reboot", "os", "pass", "재부팅이 필요한 업데이트가 없습니다.")


def judge_autoupdate_debian(installed, apt_conf_texts):
    value = None
    for _, text in sorted(apt_conf_texts.items()):
        for m in re.finditer(r'^\s*APT::Periodic::Unattended-Upgrade\s+"(\d+)"', text or "", re.M):
            value = m.group(1)
    if installed and value and value != "0":
        return finding("srv_autoupdate", "os", "pass", "unattended-upgrades로 보안 업데이트가 자동 설치됩니다.")
    fix = ["sudo apt install unattended-upgrades", "sudo dpkg-reconfigure -plow unattended-upgrades"]
    if not installed:
        return finding("srv_autoupdate", "os", "warn", "자동 보안 업데이트(unattended-upgrades)가 설치돼 있지 않습니다.", fix)
    return finding("srv_autoupdate", "os", "warn", "unattended-upgrades는 있지만 자동 실행이 꺼져 있습니다.", fix)


def judge_autoupdate_rhel(install_timer, download_timer, apply_updates):
    if install_timer or (download_timer and apply_updates):
        return finding("srv_autoupdate", "os", "pass", "dnf-automatic으로 업데이트가 자동 설치됩니다.")
    fix = ["sudo dnf install dnf-automatic", "sudo systemctl enable --now dnf-automatic-install.timer"]
    if download_timer:
        return finding("srv_autoupdate", "os", "info", "dnf-automatic이 업데이트를 내려받기만 하고 설치하지 않습니다.", fix)
    return finding("srv_autoupdate", "os", "warn", "자동 업데이트(dnf-automatic)가 켜져 있지 않습니다.", fix)


SSH_DEFAULTS = {"permitrootlogin": "prohibit-password", "passwordauthentication": "yes",
                "permitemptypasswords": "no", "maxauthtries": "6", "x11forwarding": "no",
                "kbdinteractiveauthentication": "yes", "usepam": "no", "port": "22"}


def parse_sshd_t(text):
    out = {}
    for line in (text or "").splitlines():
        parts = line.strip().split(None, 1)
        if len(parts) == 2 and parts[0].lower() not in out:
            out[parts[0].lower()] = parts[1].strip().lower()
    return out


def parse_sshd_config(path, depth=0, out=None):
    """sshd_config를 읽어 키마다 처음 나온 값을 쓴다 (OpenSSH 규칙). Match 블록부터는 무시."""
    out = {} if out is None else out
    text = read_text(path)
    if text is None or depth > 3:
        return out
    for raw in text.splitlines():
        line = raw.split("#", 1)[0].strip()
        if not line:
            continue
        parts = line.split(None, 1)
        key = parts[0].lower()
        val = parts[1].strip() if len(parts) > 1 else ""
        if key == "match":
            out["__match__"] = "yes"
            break
        if key == "include":
            for pat in val.split():
                if not pat.startswith("/"):
                    pat = os.path.join("/etc/ssh", pat)
                for inc in sorted(glob.glob(pat)):
                    parse_sshd_config(inc, depth + 1, out)
                    if out.get("__match__"):
                        return out
            continue
        if key == "challengeresponseauthentication":
            key = "kbdinteractiveauthentication"
        out.setdefault(key, val.lower())
    return out


def judge_ssh(cfg, source):
    c = dict(SSH_DEFAULTS)
    c.update({k: v for k, v in cfg.items() if not k.startswith("__")})
    note = " (실제 적용값)" if source == "sshd -T" else " (설정 파일 기준 추정 — root로 실행하면 실제 적용값을 봅니다)"
    pw = c["passwordauthentication"] == "yes" or (c["kbdinteractiveauthentication"] == "yes" and c["usepam"] == "yes")
    out = []
    root = c["permitrootlogin"]
    fix_root = ["/etc/ssh/sshd_config.d/00-hardening.conf 에 PermitRootLogin no",
                "먼저 sudo 권한이 있는 일반 계정으로 접속되는지 확인한 뒤 적용 (sudo sshd -t && sudo systemctl reload ssh)"]
    if root == "yes":
        lvl = "danger" if pw else "warn"
        why = "비밀번호로 root에 바로 로그인할 수 있습니다" if pw else "root 계정으로 바로 로그인할 수 있습니다"
        out.append(finding("srv_ssh_root", "ssh", lvl, "PermitRootLogin yes — {}{}.".format(why, note), fix_root))
    elif root in ("prohibit-password", "without-password"):
        out.append(finding("srv_ssh_root", "ssh", "pass",
                           "root는 키로만 로그인할 수 있습니다 (PermitRootLogin {}){}.".format(root, note)))
    else:
        out.append(finding("srv_ssh_root", "ssh", "pass", "root 직접 로그인이 막혀 있습니다 (PermitRootLogin {}){}.".format(root, note)))
    if pw:
        lvl = "danger" if root == "yes" else "warn"
        out.append(finding("srv_ssh_password", "ssh", lvl,
                           "비밀번호로 SSH 로그인할 수 있습니다{}. 비밀번호를 맞히려는 자동 공격의 대상이 됩니다.".format(note),
                           ["모든 사용자가 SSH 키로 접속되는지 먼저 확인",
                            "/etc/ssh/sshd_config.d/00-hardening.conf 에 PasswordAuthentication no 와 KbdInteractiveAuthentication no",
                            "sudo sshd -t && sudo systemctl reload ssh"]))
    else:
        out.append(finding("srv_ssh_password", "ssh", "pass", "SSH는 키로만 로그인할 수 있습니다{}.".format(note)))
    if c["permitemptypasswords"] == "yes":
        out.append(finding("srv_ssh_empty", "ssh", "danger", "비밀번호가 빈 계정도 SSH로 로그인할 수 있습니다{}.".format(note),
                           ["sshd_config 에 PermitEmptyPasswords no"]))
    else:
        out.append(finding("srv_ssh_empty", "ssh", "pass", "빈 비밀번호 로그인이 막혀 있습니다."))
    misc, lvls = [], []
    try:
        tries = int(c["maxauthtries"])
    except ValueError:
        tries = 6
    if tries > 6:
        misc.append("MaxAuthTries {} (6 이하 권장)".format(tries))
        lvls.append("warn")
    if c["x11forwarding"] == "yes":
        misc.append("X11Forwarding yes (쓰지 않으면 no 권장)")
        lvls.append("info")
    misc.append("포트 {}".format(c["port"]))
    lvl = worst(lvls) if lvls else "pass"
    out.append(finding("srv_ssh_misc", "ssh", lvl, ", ".join(misc) + "."))
    return out


NOLOGIN = ("nologin", "false", "sync", "halt", "shutdown")


def parse_passwd(text):
    users = []
    for line in (text or "").splitlines():
        p = line.split(":")
        if len(p) >= 7 and not line.startswith("#"):
            try:
                users.append({"name": p[0], "uid": int(p[2]), "home": p[5], "shell": p[6]})
            except ValueError:
                continue
    return users


def judge_uid0(users):
    extra = [u["name"] for u in users if u["uid"] == 0 and u["name"] != "root"]
    if extra:
        return finding("srv_uid0", "account", "danger",
                       "root가 아닌데 root 권한(UID 0)을 가진 계정이 있습니다: {}. 공격자가 남긴 뒷문일 수 있습니다.".format(", ".join(extra)),
                       ["누가 왜 만든 계정인지 확인하고, 모르는 계정이면 침해를 의심하세요."])
    return finding("srv_uid0", "account", "pass", "root 권한(UID 0) 계정은 root 하나뿐입니다.")


def judge_login_accounts(users):
    names = [u["name"] for u in users if not any(u["shell"].endswith(x) for x in NOLOGIN) and u["shell"]]
    return finding("srv_accounts", "account", "info",
                   "로그인 셸이 있는 계정 {}개: {}. 모르는 계정이 없는지 확인하세요.".format(len(names), ", ".join(names[:15])))


def judge_shadow(text):
    """빈 비밀번호 계정 이름만 돌려준다. 해시는 어디에도 쓰지 않는다."""
    empty = []
    for line in (text or "").splitlines():
        p = line.split(":")
        if len(p) >= 2 and p[0] and p[1] == "":
            empty.append(p[0])
    if empty:
        return finding("srv_empty_password", "account", "danger",
                       "비밀번호가 비어 있는 계정이 있습니다: {}.".format(", ".join(empty)),
                       ["sudo passwd -l 계정이름   # 잠그기", "또는 sudo passwd 계정이름   # 비밀번호 설정"])
    return finding("srv_empty_password", "account", "pass", "비밀번호가 비어 있는 계정이 없습니다.")


def judge_sudoers(texts, password_auth):
    hits = []
    for path, text in sorted(texts.items()):
        for raw in (text or "").splitlines():
            line = raw.strip()
            if not line or line.startswith("#") or line.lower().startswith("defaults"):
                continue
            if "NOPASSWD" in line:
                hits.append("{} ({})".format(line.split()[0], os.path.basename(path)))
    if not hits:
        return finding("srv_sudo_nopasswd", "account", "pass", "비밀번호 없이 sudo를 쓰는 설정이 없습니다.")
    lvl = "warn" if password_auth else "info"
    why = (" SSH 비밀번호 로그인이 켜져 있어, 이 계정 비밀번호가 털리면 곧바로 root 권한까지 넘어갑니다." if password_auth
           else " 클라우드 기본 이미지에서 흔한 설정이며, SSH가 키 전용이면 위험이 낮습니다.")
    return finding("srv_sudo_nopasswd", "account", lvl,
                   "비밀번호 없이 sudo를 쓸 수 있는 계정·그룹: {}.{}".format(", ".join(hits[:8]), why),
                   ["sudo visudo -f 해당파일 로 NOPASSWD 제거 (키 전용 접속이면 유지해도 됨)"])


def judge_firewall(is_root, ufw_out, firewalld_active, nft_out, iptables_out, family):
    if ufw_out and re.search(r"^Status:\s*active", ufw_out, re.M):
        return finding("srv_firewall", "network", "pass", "ufw 방화벽이 동작 중입니다."), True
    if firewalld_active:
        return finding("srv_firewall", "network", "pass", "firewalld 방화벽이 동작 중입니다."), True
    if nft_out and re.search(r"hook input[^;]*;\s*policy (drop|reject)", nft_out):
        return finding("srv_firewall", "network", "pass", "nftables가 들어오는 연결을 기본 차단합니다."), True
    if iptables_out and (re.search(r"^-P INPUT (DROP|REJECT)", iptables_out, re.M)
                         or re.search(r"^-A INPUT .*-j (DROP|REJECT)\s*$", iptables_out, re.M)):
        return finding("srv_firewall", "network", "pass", "iptables가 들어오는 연결을 차단합니다."), True
    if not is_root:
        return finding("srv_firewall", "network", "info", "방화벽 상태는 root 권한이 있어야 확인할 수 있습니다."), None
    fix = (["sudo ufw allow 22/tcp   # SSH 먼저 허용 (포트가 다르면 그 번호)", "sudo ufw allow 80,443/tcp", "sudo ufw enable"]
           if family == "debian" else
           ["sudo systemctl enable --now firewalld", "sudo firewall-cmd --permanent --add-service=ssh --add-service=http --add-service=https",
            "sudo firewall-cmd --reload"])
    return finding("srv_firewall", "network", "warn",
                   "서버 자체 방화벽이 꺼져 있거나 들어오는 연결을 기본 허용합니다. 호스팅 콘솔 방화벽이 있다면 1차 방어는 되지만, 서버에도 켜 두는 것이 좋습니다.",
                   fix), False


RISKY_PORTS = {
    21: ("FTP", "warn"), 23: ("Telnet", "danger"), 111: ("rpcbind", "warn"), 161: ("SNMP", "warn"),
    445: ("SMB 파일공유", "warn"), 2375: ("Docker API(암호화 없음)", "danger"), 2376: ("Docker API", "warn"),
    3306: ("MySQL/MariaDB", "danger"), 3389: ("원격 데스크톱", "warn"), 5432: ("PostgreSQL", "danger"),
    5900: ("VNC", "warn"), 6379: ("Redis", "danger"), 9200: ("Elasticsearch", "danger"),
    11211: ("Memcached", "danger"), 27017: ("MongoDB", "danger"),
}


def parse_ss(text):
    out, seen = [], set()
    for line in (text or "").splitlines():
        f = line.split()
        if len(f) < 4:
            continue
        if f[0] in ("tcp", "tcp6", "udp", "udp6") and f[1].isdigit():  # netstat 형식
            proto = f[0].rstrip("6")
            if proto == "tcp" and (len(f) < 6 or f[5] != "LISTEN"):
                continue
            f = [proto, "LISTEN" if proto == "tcp" else "UNCONN", f[1], f[2], f[3]] + f[4:]
            m = re.search(r"\d+/(\S+)", line)
            if m:
                line = line + ' users:(("{}"'.format(m.group(1))
        if len(f) < 5 or f[0] not in ("tcp", "udp"):
            continue
        if f[0] == "tcp" and f[1] != "LISTEN":
            continue
        local = f[4]
        if ":" not in local:
            continue
        host, port = local.rsplit(":", 1)
        if not port.isdigit():
            continue
        iface = ""
        if "%" in host:
            host, iface = host.split("%", 1)
        host = host.strip("[]")
        proc = ""
        m = re.search(r'users:\(\("([^"]+)"', line)
        if m:
            proc = m.group(1)
        key = (f[0], int(port), host)
        if key in seen:
            continue
        seen.add(key)
        out.append({"proto": f[0], "port": int(port), "host": host, "iface": iface, "proc": proc})
    return out


def scope_of(host, iface):
    if iface == "lo":
        return "local"
    if host in ("*", "0.0.0.0", "::", ""):
        return "any"
    try:
        ip = ipaddress.ip_address(host)
    except ValueError:
        return "any"
    if ip.is_loopback:
        return "local"
    if getattr(ip, "ipv4_mapped", None) and ip.ipv4_mapped.is_loopback:
        return "local"
    if ip.is_private or ip.is_link_local:
        return "private"
    return "any"


def judge_ports(listeners, firewall_on):
    ext = [l for l in listeners if scope_of(l["host"], l["iface"]) != "local"]
    shown, risky, lvls = [], [], []
    for l in sorted(ext, key=lambda x: (x["proto"], x["port"])):
        tag = "{}/{}".format(l["proto"], l["port"]) + ("({})".format(l["proc"]) if l["proc"] else "")
        if tag not in shown:
            shown.append(tag)
        if l["port"] in RISKY_PORTS and (l["proto"] == "tcp" or l["port"] in (111, 161, 11211)):
            name, lvl = RISKY_PORTS[l["port"]]
            note = ""
            if scope_of(l["host"], l["iface"]) == "private":
                note = " 사설망 주소({})에만 열림".format(l["host"])
                lvl = "warn" if lvl == "danger" else "info"
            elif firewall_on:
                lvl = "warn" if lvl == "danger" else lvl
            risky.append("{} {}{}".format(name, l["port"], note))
            lvls.append(lvl)
    if not ext:
        return finding("srv_ports", "network", "pass", "외부 주소에 열린 포트가 없습니다.")
    listing = "외부 주소에 열린 포트: " + ", ".join(shown[:20]) + "."
    if risky:
        fw = " 서버 방화벽이 막고 있다면 바깥에서는 안 보일 수 있지만, 방화벽 설정이 바뀌는 순간 바로 노출됩니다." if firewall_on else ""
        return finding("srv_ports", "network", worst(lvls),
                       "DB·관리용 서비스가 모든 주소에서 연결을 받습니다: {}. {}{}".format(", ".join(risky), listing, fw),
                       ["해당 서비스 설정에서 접속 주소(bind)를 127.0.0.1 로 바꾸기",
                        "다른 서버에서 접속해야 한다면 방화벽으로 그 서버 IP만 허용"])
    common = {22, 80, 443}
    lvl = "pass" if all(l["port"] in common or l["proto"] == "udp" for l in ext) else "info"
    return finding("srv_ports", "network", lvl, listing + " 각 포트가 필요한 서비스인지 확인하세요.")


SSH_FAIL = re.compile(r"sshd\[\d+\]: (Failed password|Invalid user|Connection closed by authenticating user|authentication failure)")


def count_ssh_failures(log_text):
    return len(SSH_FAIL.findall(log_text or ""))


def judge_bruteforce(f2b, sshguard, password_auth, failures):
    seen = " 최근 로그에서 SSH 로그인 실패 {}건.".format(failures) if failures is not None else ""
    if f2b or sshguard:
        return finding("srv_bruteforce", "network", "pass",
                       "{}이(가) 반복 로그인 실패를 차단합니다.{}".format("fail2ban" if f2b else "sshguard", seen))
    fix = ["sudo apt install fail2ban   # RHEL 계열: sudo dnf install epel-release fail2ban", "sudo systemctl enable --now fail2ban"]
    if password_auth:
        return finding("srv_bruteforce", "network", "warn",
                       "비밀번호 로그인이 켜져 있는데 반복 실패를 막는 장치(fail2ban 등)가 없습니다.{}".format(seen), fix)
    return finding("srv_bruteforce", "network", "info",
                   "fail2ban 등이 없지만 SSH가 키 전용이라 위험은 낮습니다.{}".format(seen), fix)


def judge_system_perms(stats):
    """stats: {path: (mode, uid)}"""
    bad, lvls = [], []
    rules = {
        "/etc/shadow": (0o004 | 0o002, "danger"), "/etc/gshadow": (0o004 | 0o002, "danger"),
        "/etc/passwd": (0o002, "danger"), "/etc/group": (0o002, "danger"),
        "/etc/sudoers": (0o002 | 0o004, "danger"), "/etc/ssh/sshd_config": (0o002, "danger"),
    }
    for path, (mask, lvl) in rules.items():
        if path in stats and stats[path][0] & mask:
            bad.append("{} ({})".format(path, oct(stats[path][0] & 0o777)))
            lvls.append(lvl)
    ww = [p for p, (mode, _) in stats.items() if p not in rules and mode & 0o002]
    if ww:
        bad.append("누구나 쓸 수 있는 /etc 파일: " + ", ".join(sorted(ww)[:8]))
        lvls.append("warn")
    if bad:
        return finding("srv_perm_system", "perm", worst(lvls), "권한이 너무 넓은 시스템 파일: " + "; ".join(bad) + ".",
                       ["sudo chmod 640 /etc/shadow   # 배포판 기본값에 맞추기 (Ubuntu 640, RHEL 000)",
                        "sudo chmod 644 /etc/passwd /etc/group", "sudo chmod o-w 해당파일"])
    return finding("srv_perm_system", "perm", "pass", "주요 시스템 파일 권한이 적절합니다.")


def judge_cron_perms(stats):
    bad, lvls = [], []
    for path, (mode, uid) in sorted(stats.items()):
        if mode & 0o002 or mode & 0o020:
            bad.append("{} ({})".format(path, oct(mode & 0o777)))
            lvls.append("danger")
        elif uid != 0 and path.startswith("/etc/"):
            bad.append("{} (소유자 UID {})".format(path, uid))
            lvls.append("warn")
    if bad:
        return finding("srv_perm_cron", "perm", worst(lvls),
                       "root로 실행되는 예약 작업 파일을 다른 사용자가 고칠 수 있습니다: {}. 권한 상승 통로가 됩니다.".format(", ".join(bad[:8])),
                       ["sudo chown root:root 해당파일 && sudo chmod go-w 해당파일"])
    return finding("srv_perm_cron", "perm", "pass", "예약 작업(cron) 파일 권한이 적절합니다.")


WEB_ROOT_GLOBS = ["/var/www", "/usr/share/nginx/html", "/srv/www", "/srv/http", "/home/*/public_html", "/home/*/www"]
SENSITIVE_FILE = re.compile(
    r"^(\.env(\.(?!example$|sample$|dist$|template$)[\w.-]+)?|.*\.sql(\.gz)?|.*\.(bak|old|orig|swp)|.*~|phpinfo\.php|info\.php|"
    r".*\.(zip|tar\.gz|tgz|7z|rar)|sftp\.json|\.htpasswd|wp-config\.php\.\w+)$", re.I)
SKIP_DIRS = {"node_modules", "vendor", ".cache", "__pycache__"}


def walk_web_roots(roots, max_depth=5, max_entries=30000):
    """웹 폴더를 얕게 훑어 (민감 파일, .git 폴더, 누구나 쓰기 가능 폴더) 경로를 모은다. 파일 내용은 읽지 않는다."""
    files, gits, writable, count = [], [], [], 0
    stack = [(r, 0) for r in roots]
    while stack and count < max_entries and time_left() > 5:
        path, depth = stack.pop()
        try:
            st = os.lstat(path)
        except OSError:
            continue
        if not stat.S_ISDIR(st.st_mode):
            continue
        if st.st_mode & 0o002 and not st.st_mode & stat.S_ISVTX:
            writable.append(path)
        try:
            entries = list(os.scandir(path))
        except OSError:
            continue
        for e in entries:
            count += 1
            try:
                if e.is_symlink():
                    continue
                if e.is_dir():
                    if e.name == ".git":
                        gits.append(e.path)
                    elif e.name not in SKIP_DIRS and depth < max_depth:
                        stack.append((e.path, depth + 1))
                elif SENSITIVE_FILE.match(e.name):
                    files.append(e.path)
            except OSError:
                continue
    return files, gits, writable, count >= max_entries


def judge_web(roots, files, gits, writable, truncated):
    out = []
    if not roots:
        return [finding("srv_web_files", "web", "info", "알려진 웹 폴더(/var/www 등)가 없어 건너뛰었습니다.")]
    part = " (항목이 많아 일부만 확인)" if truncated else ""
    items = ["{} (.git 폴더)".format(g) for g in gits[:6]] + files[:10]
    if items:
        out.append(finding("srv_web_files", "web", "warn",
                           "웹 폴더 안에 내려받히면 안 되는 파일이 있습니다{}: {}. 웹에서 실제로 열리는지는 문서 루트 설정에 따라 다르니 문단속 사이트 점검으로 확인하세요."
                           .format(part, "; ".join(items)),
                           ["필요 없는 백업·덤프는 웹 폴더 밖으로 옮기거나 지우기",
                            ".env·.git이 노출됐다면 그 안의 비밀번호·키를 모두 바꾸기"]))
    else:
        out.append(finding("srv_web_files", "web", "pass", "웹 폴더({})에서 민감한 파일을 찾지 못했습니다{}.".format(", ".join(roots[:4]), part)))
    if writable:
        out.append(finding("srv_web_writable", "web", "warn",
                           "누구나 쓸 수 있는(777) 웹 폴더가 있습니다: {}. 다른 계정이나 침입한 프로세스가 악성 파일을 심을 수 있습니다.".format(", ".join(writable[:8])),
                           ["sudo chmod 775 폴더  (웹서버 계정이 써야 하면 소유자를 웹서버 계정으로: sudo chown www-data 폴더)"]))
    else:
        out.append(finding("srv_web_writable", "web", "pass", "누구나 쓸 수 있는 웹 폴더가 없습니다."))
    return out


# ---------------------------------------------------------------- 침해 흔적 (읽기 전용, 흔한 흔적만)

SCRIPT_EXT = re.compile(r"\.(php[0-9s]?|phtml|pht|phar|inc|jsp|jspx|aspx?|cgi)$", re.I)
UPLOAD_DIR = re.compile(r"(^|/)(wp-content/uploads|uploads?|data/file|data/editor|userfiles?|attach(ments)?)(/|$)", re.I)
CACHE_DIR = re.compile(r"(^|/)(cache|caches|tmp|temp|sessions?|storage/framework|wp-content/upgrade)(/|$)", re.I)
# 요청 값을 바로 실행하는 코드 — 정상 프로그램에는 거의 없다
SHELL_SIGS = [
    (re.compile(r"\b(eval|assert|system|exec|shell_exec|passthru|popen|proc_open|pcntl_exec)\s*\(\s*@?\s*\$_(GET|POST|REQUEST|COOKIE)\b"),
     "요청 값을 바로 실행"),
    (re.compile(r"\$_(GET|POST|REQUEST|COOKIE)\s*\[[^\]]{1,40}\]\s*\(\s*\$_(GET|POST|REQUEST|COOKIE)"), "요청 값으로 함수를 골라 실행"),
    (re.compile(r"\b(FilesMan|c99shell|r57shell|b374k|IndoXploit)\b"), "알려진 웹셸 이름"),
]
# 숨긴 코드를 풀어 실행 — 일부 상용 플러그인도 쓰므로 '주의'
OBFUS_SIGS = [
    (re.compile(r"\b(eval|assert)\s*\(\s*@?\s*(base64_decode|gzinflate|gzuncompress|gzdecode|str_rot13)\s*\("), "숨긴 코드를 풀어 실행"),
    (re.compile(r"[A-Za-z0-9+/]{4000,}={0,2}"), "아주 긴 인코딩 문자열"),
]


def classify_script(text):
    """('shell'|'obfus', 이유) 또는 None. 웹셸 판정은 흔적일 뿐 확정이 아니다."""
    for rx, why in SHELL_SIGS:
        if rx.search(text):
            return ("shell", why)
    hits = [why for rx, why in OBFUS_SIGS if rx.search(text)]
    if "숨긴 코드를 풀어 실행" in hits:
        return ("obfus", " + ".join(hits))
    if hits and re.search(r"\b(eval|assert|create_function)\s*\(", text):
        return ("obfus", hits[0] + " + 실행 함수")
    return None


def scan_web_tree(roots, since, max_depth=6, max_files=40000, read_limit=256 * 1024):
    """웹 폴더의 프로그램 파일을 훑는다. → {'shells', 'obfus', 'upload_exec', 'recent', 'scanned', 'truncated'}"""
    res = {"shells": [], "obfus": [], "upload_exec": [], "recent": [], "scanned": 0, "truncated": False}
    stack = [(r, 0) for r in roots]
    seen = 0
    while stack:
        if seen >= max_files or time_left() <= 8:
            res["truncated"] = True
            break
        path, depth = stack.pop()
        try:
            entries = list(os.scandir(path))
        except OSError:
            continue
        for e in entries:
            seen += 1
            try:
                if e.is_symlink():
                    continue
                if e.is_dir():
                    if e.name not in SKIP_DIRS and e.name != ".git" and depth < max_depth:
                        stack.append((e.path, depth + 1))
                    continue
                if not SCRIPT_EXT.search(e.name):
                    continue
                st = e.stat()
            except OSError:
                continue
            rel = e.path
            for r in roots:
                if e.path.startswith(r.rstrip("/") + "/"):
                    rel = e.path[len(r.rstrip("/")) + 1:]
                    break
            if UPLOAD_DIR.search(os.path.dirname(rel)) and not (e.name.lower() == "index.php" and st.st_size < 200):
                res["upload_exec"].append(e.path)
            if st.st_mtime >= since and not CACHE_DIR.search(os.path.dirname(rel)):
                res["recent"].append((st.st_mtime, e.path))
            if st.st_size > 4 * 1024 * 1024:
                continue
            text = read_text(e.path, read_limit)
            if text is None:
                continue
            res["scanned"] += 1
            kind = classify_script(text)
            if kind:
                res["shells" if kind[0] == "shell" else "obfus"].append((e.path, kind[1]))
    res["recent"].sort(reverse=True)
    return res


REPORT_HINT = "침해가 확인되면 KISA 보호나라(boho.or.kr) 또는 국번 없이 118로 신고·상담할 수 있습니다."


def judge_intrusion_web(roots, res):
    if not roots:
        return [finding("srv_webshell", "intrusion", "info", "알려진 웹 폴더(/var/www 등)가 없어 건너뛰었습니다.")]
    out, part = [], (" (파일이 많아 일부만 확인)" if res["truncated"] else "")
    keep = ["바로 지우기 전에 파일을 다른 곳에 복사해 두기 (원인 분석에 필요)",
            "그 파일이 언제 생겼는지 확인: stat 파일경로 — 같은 시각의 웹 접속 기록(access.log)을 보면 들어온 경로를 찾을 수 있습니다",
            "관리자·FTP·DB 비밀번호를 모두 바꾸고, CMS와 플러그인을 최신으로 올리기", REPORT_HINT]
    if res["shells"]:
        items = ["{} ({})".format(p, why) for p, why in res["shells"][:10]]
        out.append(finding("srv_webshell", "intrusion", "danger",
                           "웹셸로 의심되는 파일이 있습니다{}: {}. 요청 값을 그대로 실행하는 코드는 정상 프로그램에 거의 없습니다.".format(part, "; ".join(items)), keep))
    elif res["obfus"]:
        items = ["{} ({})".format(p, why) for p, why in res["obfus"][:10]]
        out.append(finding("srv_webshell", "intrusion", "warn",
                           "숨긴 코드를 풀어 실행하는 파일이 있습니다{}: {}. 일부 유료 플러그인도 이렇게 만들지만, 침입자가 심은 파일도 흔히 이렇습니다.".format(part, "; ".join(items)),
                           ["설치한 플러그인·테마에 들어 있는 파일인지 원본과 비교하기", "모르는 파일이면 위험 단계와 같이 다루기"] + keep[1:]))
    else:
        out.append(finding("srv_webshell", "intrusion", "pass",
                           "웹 폴더의 프로그램 파일 {}개에서 흔한 웹셸 흔적을 찾지 못했습니다{}.".format(res["scanned"], part)))
    if res["upload_exec"]:
        out.append(finding("srv_upload_exec", "intrusion", "danger",
                           "업로드 폴더 안에 실행 가능한 프로그램 파일이 있습니다: {}. 업로드 폴더에는 그림·문서만 있어야 합니다.".format(", ".join(res["upload_exec"][:10])),
                           ["직접 둔 파일이 아니면 침입 흔적으로 보고 위 웹셸 항목처럼 조치",
                            "업로드 폴더에서 PHP 실행 막기 (Apache: 그 폴더 .htaccess에 php_flag engine off 또는 <FilesMatch \"\\.ph(p[0-9]?|tml|ar)$\"> Require all denied </FilesMatch>)",
                            "Nginx: location ~* /uploads/.*\\.php$ { deny all; }"]))
    else:
        out.append(finding("srv_upload_exec", "intrusion", "pass", "업로드 폴더에서 실행 가능한 프로그램 파일을 찾지 못했습니다."))
    if res["recent"]:
        items = ["{} ({})".format(p, datetime.fromtimestamp(t).strftime("%m-%d %H:%M")) for t, p in res["recent"][:10]]
        more = " 외 {}개".format(len(res["recent"]) - 10) if len(res["recent"]) > 10 else ""
        out.append(finding("srv_recent_php", "intrusion", "info",
                           "최근 7일 안에 바뀐 프로그램 파일이 {}개 있습니다: {}{}. 업데이트나 직접 고친 것이 아니라면 확인하세요.".format(
                               len(res["recent"]), "; ".join(items), more)))
    return out


KEY_RE = re.compile(r"(ssh-(?:rsa|ed25519|dss)|ecdsa-sha2-nistp\d+|sk-(?:ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)\s+([A-Za-z0-9+/=]{20,})(?:\s+(.*))?$")


def parse_authorized_keys(text):
    """→ [(종류, 설명, 지문)] — 지문은 ssh-keygen -lf와 같은 SHA256 형식"""
    keys = []
    for raw in (text or "").splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        m = KEY_RE.search(line)
        if not m:
            continue
        try:
            blob = base64.b64decode(m.group(2).encode("ascii"), validate=True)
        except (ValueError, binascii.Error):
            continue
        fp = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode("ascii").rstrip("=")
        keys.append((m.group(1), (m.group(3) or "").strip()[:60], fp))
    return keys


def judge_ssh_keys(entries, now, is_root):
    """entries: [(계정, 파일 경로, 수정 시각, 누구나 쓰기 가능?, [(종류, 설명, 지문)])]"""
    if not entries:
        msg = "등록된 SSH 키(authorized_keys)가 없습니다."
        if not is_root:
            msg += " (root로 실행하지 않아 다른 계정의 키는 보지 못했습니다)"
        return finding("srv_ssh_keys", "intrusion", "pass", msg)
    bad = [p for _, p, _, ww, _ in entries if ww]
    recent = [u for u, _, mt, _, _ in entries if now - mt < 7 * 86400]
    lines = []
    for user, path, mt, ww, keys in entries:
        desc = ", ".join("{} {}".format(c or "(설명 없음)", fp[:20] + "…") for _, c, fp in keys[:4])
        lines.append("{} {}개({})".format(user, len(keys), desc + (" 외" if len(keys) > 4 else "")))
    detail = "SSH 키로 들어올 수 있는 계정: " + "; ".join(lines) + "."
    if recent:
        detail += " 최근 7일 안에 키 파일이 바뀐 계정: {}.".format(", ".join(sorted(set(recent))))
    fix = ["모르는 키가 있으면 그 줄을 지우기: 파일을 열어 설명(이메일·PC 이름)과 지문으로 구분 — 지문 보기: ssh-keygen -lf 파일경로",
           "침입자는 다시 들어오려고 키를 몰래 추가하곤 합니다. 지운 뒤에는 비밀번호도 바꾸세요."]
    if bad:
        return finding("srv_ssh_keys", "intrusion", "danger",
                       "누구나 고칠 수 있는 SSH 키 파일이 있습니다: {}. 아무 계정이나 키를 넣어 그 계정으로 들어올 수 있습니다. {}".format(", ".join(bad), detail),
                       ["sudo chmod 600 파일경로 && sudo chmod 700 그_계정의/.ssh"] + fix)
    return finding("srv_ssh_keys", "intrusion", "info", detail, fix)


CRON_SIGS = [
    (re.compile(r"\b(curl|wget)\b[^|;\n]*\|\s*(sudo\s+)?(ba|da|z)?sh\b"), "인터넷에서 받은 내용을 바로 실행"),
    (re.compile(r"base64\s+(-d|--decode)\b"), "base64로 숨긴 명령"),
    (re.compile(r"/dev/tcp/"), "외부로 셸을 연결"),
    (re.compile(r"\bnc(at)?\b[^\n]*\s-[a-z]*e\s"), "nc로 셸을 연결"),
    (re.compile(r"xmrig|stratum\+tcp|minerd|cpuminer|kdevtmpfsi|kinsing", re.I), "암호화폐 채굴 프로그램"),
    (re.compile(r"authorized_keys"), "SSH 키 파일을 고침"),
]
TMP_EXEC = re.compile(r"^(?:nohup\s+|sudo\s+|(?:ba|da|z)?sh\s+)*(/tmp|/var/tmp|/dev/shm)/\S+")


def cron_commands(path, text):
    """crontab 형식 파일에서 (줄 번호, 명령) — 시간 필드와 사용자 필드를 뗀다."""
    sys_fmt = path == "/etc/crontab" or path.startswith("/etc/cron.d/")
    out = []
    for n, raw in enumerate((text or "").splitlines(), 1):
        line = raw.strip()
        if not line or line.startswith("#") or re.match(r"^[A-Za-z_][A-Za-z0-9_]*\s*=", line):
            continue
        parts = line.split()
        skip = (1 if parts[0].startswith("@") else 5) + (1 if sys_fmt else 0)
        if len(parts) > skip:
            out.append((n, " ".join(parts[skip:])))
    return out


def judge_cron_suspicious(entries):
    """entries: [(경로, 내용, crontab 형식인가)]"""
    hits = []
    for path, text, is_tab in entries:
        lines = cron_commands(path, text) if is_tab else [
            (n, l.strip()) for n, l in enumerate((text or "").splitlines(), 1) if l.strip() and not l.strip().startswith("#")]
        for n, cmd in lines:
            why = [w for rx, w in CRON_SIGS if rx.search(cmd)]
            if is_tab and any(TMP_EXEC.match(seg.strip()) for seg in re.split(r"[;&|]+", cmd)):
                why.append("임시 폴더의 프로그램 실행")
            if why:
                hits.append("{}:{} ({})".format(path, n, ", ".join(why)))
    if hits:
        return finding("srv_cron_suspicious", "intrusion", "danger",
                       "수상한 예약 작업이 있습니다: {}. 침입자가 다시 들어오거나 채굴 프로그램을 돌리려고 흔히 남기는 형태입니다.".format("; ".join(hits[:10])),
                       ["해당 줄을 직접 확인: sudo sed -n '줄번호p' 파일경로  (사용자 예약 작업은 sudo crontab -l -u 계정)",
                        "직접 넣은 것이 아니면 그 줄을 지우기 전에 내용을 따로 저장해 두기", REPORT_HINT])
    return finding("srv_cron_suspicious", "intrusion", "pass", "예약 작업에서 흔한 침입 흔적(내려받아 실행, 숨긴 명령, 채굴 등)을 찾지 못했습니다.")


SUSPICIOUS_PROC = re.compile(r"xmrig|kdevtmpfsi|kinsing|minerd|cpuminer|xmr-stak", re.I)


def judge_suspicious_procs(entries, is_root):
    """entries: [(pid, 이름, 실행 파일 경로)]"""
    hits = []
    for pid, comm, exe in entries:
        path = (exe or "").replace(" (deleted)", "")
        why = None
        if re.match(r"^(/tmp|/var/tmp|/dev/shm)/", path):
            why = "임시 폴더에서 실행 중" + (" (파일은 지워짐)" if exe and exe.endswith(" (deleted)") else "")
        elif SUSPICIOUS_PROC.search(comm or "") or SUSPICIOUS_PROC.search(os.path.basename(path)):
            why = "채굴 프로그램 이름"
        if why:
            hits.append("PID {} {} ({}: {})".format(pid, comm, why, path or "?"))
    if hits:
        return finding("srv_suspicious_proc", "intrusion", "danger",
                       "수상한 프로세스가 돌고 있습니다: {}. 정상 서비스는 임시 폴더에서 실행되지 않습니다.".format("; ".join(hits[:8])),
                       ["어떤 프로그램인지 확인: sudo ls -l /proc/PID/exe, sudo cat /proc/PID/cmdline | tr '\\0' ' '",
                        "모르는 프로세스면 바로 끄기 전에 위 정보를 저장하고, 예약 작업·SSH 키 항목도 함께 확인", REPORT_HINT])
    msg = "임시 폴더에서 실행 중이거나 채굴 프로그램으로 보이는 프로세스가 없습니다."
    if not is_root:
        msg += " (root로 실행하지 않아 다른 계정의 프로세스는 일부만 봤습니다)"
    return finding("srv_suspicious_proc", "intrusion", "pass", msg)


PHP_EOL = {(5, 6): "2018-12-31", (7, 0): "2019-01-10", (7, 1): "2019-12-01", (7, 2): "2020-11-30",
           (7, 3): "2021-12-06", (7, 4): "2022-11-28", (8, 0): "2023-11-26", (8, 1): "2025-12-31",
           (8, 2): "2026-12-31", (8, 3): "2027-12-31", (8, 4): "2028-12-31", (8, 5): "2029-12-31"}


def parse_ini(text):
    out = {}
    for raw in (text or "").splitlines():
        line = raw.strip()
        if not line or line[0] in ";#[":
            continue
        if "=" in line:
            k, v = line.split("=", 1)
            out[k.strip().lower()] = v.split(";")[0].strip().strip('"').lower()
    return out


def judge_php(versions, sapi_ini, today):
    """versions: ['8.3', ...], sapi_ini: {'fpm 8.3': {...ini}}"""
    if not versions and not sapi_ini:
        return None
    msgs, lvls, fix = [], [], []
    for v in sorted(set(versions)):
        try:
            major, minor = (int(x) for x in v.split(".")[:2])
        except ValueError:
            continue
        eol = PHP_EOL.get((major, minor)) or ("2018-12-31" if (major, minor) < (5, 6) else None)
        if not eol:
            continue
        days = (datetime.strptime(eol, "%Y-%m-%d").date() - today).days
        if days < 0:
            msgs.append("PHP {} 보안 지원 종료({})".format(v, eol))
            lvls.append("danger")
            fix.append("지원 중인 PHP(8.3 이상)로 업그레이드 — 사이트 호환성을 먼저 확인")
        elif days <= 90:
            msgs.append("PHP {} 지원 종료 임박({})".format(v, eol))
            lvls.append("warn")
    for sapi, ini in sorted(sapi_ini.items()):
        if ini.get("allow_url_include") in ("on", "1", "true", "yes"):
            msgs.append("{}: allow_url_include On".format(sapi))
            lvls.append("danger")
            fix.append("php.ini: allow_url_include = Off")
        if ini.get("display_errors") in ("on", "1", "true", "yes", "stdout") and not sapi.startswith("cli"):
            msgs.append("{}: display_errors On (오류에 경로·쿼리가 노출됨)".format(sapi))
            lvls.append("warn")
            fix.append("php.ini: display_errors = Off, log_errors = On")
        if ini.get("expose_php") in ("on", "1", "true", "yes") and not sapi.startswith("cli"):
            msgs.append("{}: expose_php On (버전 노출)".format(sapi))
            lvls.append("info")
            fix.append("php.ini: expose_php = Off")
    if not msgs:
        return finding("srv_php", "service", "pass", "PHP {}: 위험한 설정을 찾지 못했습니다.".format(", ".join(sorted(set(versions))) or ""))
    fix.append("바꾼 뒤 PHP-FPM 또는 웹서버 재시작 (예: sudo systemctl restart php8.3-fpm)")
    return finding("srv_php", "service", worst(lvls), "; ".join(msgs) + ".", sorted(set(fix), key=fix.index))


# ---------------------------------------------------------------- 알려진 취약점 (보안 브리핑 규칙)

def vtuple(text):
    m = re.match(r"\s*v?(\d+(?:[.p]\d+)*)", text or "")
    return tuple(int(x) for x in re.split(r"[.p]", m.group(1))) if m else None


def vjoin(t):
    return ".".join(str(x) for x in t)


def fixed_for(rule, v):
    """버전 v가 속한 갈래의 해결 버전 (가장 긴 키가 맞는 것). 해당 갈래가 없으면 None."""
    best = None
    for k, fx in (rule.get("fixed") or {}).items():
        kt = vtuple(k) if k else ()
        if kt is None or v[:len(kt)] != kt:
            continue
        if best is None or len(kt) > len(best[0]):
            best = (kt, vtuple(fx))
    return best[1] if best else None


def rule_url(rule):
    return SITE_BASE + "/briefing/" + rule["slug"]


def pending_security(family, updates_raw, rule):
    """밀린 보안 업데이트 목록에서 규칙의 패키지 이름 패턴에 맞는 것. 목록을 못 읽었으면 None."""
    if updates_raw is None:
        return None
    pat = rule.get("deb") if family == "debian" else rule.get("rpm")
    if not pat:
        return []
    names = set()
    for line in updates_raw.splitlines():
        pkg = None
        if family == "debian" and line.startswith("Inst ") and re.search(r"-security|Debian-Security", line):
            pkg = line.split()[1]
        elif family == "rhel" and re.search(r"(RHSA|RLSA|ALSA|CESA)-", line):
            pkg = line.split()[-1]
        if pkg and re.search(pat, pkg):
            names.add(pkg)
    return sorted(names)


def judge_package(rule, installs, pending):
    """installs: [(이름, 버전문자열, 패키지로 설치됐는가, 변경기록에 CVE가 있는가 True/False/None)]
    pending: 밀린 보안 업데이트 중 해당 패키지 이름 목록 또는 None. 설치된 것이 없으면 None."""
    if not installs:
        return None
    msgs, lvls, confirmed, unaffected = [], [], [], []
    eol = vtuple(rule.get("eol_below") or "")
    since = vtuple(rule.get("affected_from") or "")
    cve = rule.get("cve", "")
    for name, vtext, packaged, patched in installs:
        m = re.search(r"(\d+(?:\.\d+)+)(\S*)", vtext or "")
        if not m:
            continue
        v = vtuple(m.group(1))
        label = "{} {}{}".format(name, m.group(1), m.group(2)[:24])
        fixed = fixed_for(rule, v)
        if since and v < since and not packaged:
            # 직접 설치한 프로그램은 번호가 곧 실제 버전. 배포판 패키지는 새 코드를 옛 번호에 넣기도 해서 이 판단을 하지 않는다
            unaffected.append(label)
            continue
        if eol and v < eol:
            if packaged and patched:
                confirmed.append(label)
            else:
                msgs.append("{}: {} 쪽 패치가 없는 지원 종료 버전".format(label, rule["product"]))
                lvls.append("danger")
        elif fixed is None:
            continue
        elif packaged and patched:
            confirmed.append(label)
        elif packaged:
            if pending:
                msgs.append("{}: 보안 업데이트가 설치되지 않았습니다 ({})".format(label, ", ".join(pending[:4])))
                lvls.append("danger")
            elif v < fixed and patched is False:
                msgs.append("{}: 배포판 패키지 변경 기록에서 이 취약점 패치({})를 찾지 못했습니다. 배포판이 아직 패치를 내지 않았거나, "
                            "지원이 끝난 배포판일 수 있습니다".format(label, cve))
                lvls.append("warn")
            elif v < fixed:
                msgs.append("{}: 배포판 패키지라 번호로 판단할 수 없고, 변경 기록도 확인하지 못했습니다".format(label))
                lvls.append("warn" if pending is None else "info")
        elif v < fixed:
            msgs.append("{}: 해결 버전 {}보다 낮습니다".format(label, vjoin(fixed)))
            lvls.append("danger")
    title, url = rule["title"], rule_url(rule)
    if not msgs:
        if unaffected and not confirmed:
            return finding(rule["id"], "vuln", "pass", "설치된 {}은(는) 영향 받는 버전이 아닙니다: {}.".format(rule["product"], ", ".join(unaffected)),
                           title=title, url=url)
        how = " (배포판 패키지 변경 기록에서 패치 확인: {})".format(", ".join(confirmed)) if confirmed else ""
        return finding(rule["id"], "vuln", "pass", "설치된 {}에 이 취약점의 패치가 적용돼 있습니다{}.".format(rule["product"], how),
                       title=title, url=url)
    lvl = worst(lvls)
    if rule.get("note") and lvl != "danger":
        msgs.append(rule["note"])
    fix = ["업데이트: sudo apt update && sudo apt upgrade   (RHEL 계열: sudo dnf upgrade)"]
    if rule.get("restart_cmd"):
        fix.append("반드시 재시작: " + rule["restart_cmd"])
    if lvl in ("info", "warn") and cve and not any("해결 버전" in m or "설치되지 않았" in m for m in msgs):
        fix = ["패치 확인 (Ubuntu·Debian): zgrep -m1 {} /usr/share/doc/<패키지>/changelog.Debian.gz".format(cve),
               "패치 확인 (RHEL 계열): rpm -q --changelog <패키지> | grep -m1 {}".format(cve)]
    fix.append("브리핑: " + url)
    return finding(rule["id"], "vuln", lvl, "; ".join(msgs) + ".", fix, title=title, url=url)


def judge_app(rule, found):
    """found: [(설치 위치, 버전 문자열)] — 워드프레스·게시판처럼 번호가 곧 실제 버전인 프로그램. 없으면 None."""
    if not found:
        return None
    msgs, lvls, ok = [], [], []
    eol = vtuple(rule.get("eol_below") or "")
    for where, vtext in found:
        v = vtuple(vtext)
        if not v:
            continue
        label = "{} ({} {})".format(where, rule["product"], vtext)
        fixed = fixed_for(rule, v)
        if eol and v < eol:
            msgs.append("{}: 패치가 나오지 않는 지원 종료 버전".format(label))
            lvls.append("danger")
        elif fixed is None:
            ok.append(label)
        elif v < fixed:
            msgs.append("{}: 해결 버전 {}보다 낮습니다".format(label, vjoin(fixed)))
            lvls.append("danger")
        else:
            ok.append(label)
    title, url = rule["title"], rule_url(rule)
    if not msgs:
        if not ok:
            return None
        return finding(rule["id"], "vuln", "pass", "해결 버전 이상입니다: {}.".format(", ".join(ok[:5])), title=title, url=url)
    return finding(rule["id"], "vuln", worst(lvls), "; ".join(msgs[:6]) + ".",
                   ["관리 화면이나 공식 배포본으로 최신 버전으로 업데이트 (먼저 백업)", "브리핑: " + url], title=title, url=url)


def judge_rules_age(rules_date, today, stale_days=RULES_STALE_DAYS):
    try:
        d = datetime.strptime(rules_date, "%Y-%m-%d").date()
    except (TypeError, ValueError):
        return None
    days = (today - d).days
    if days <= stale_days:
        return None
    return finding("srv_rules_age", "vuln", "info",
                   "이 스크립트의 알려진 취약점 규칙은 {} 기준입니다 ({}일 전). 그 뒤 나온 취약점은 점검하지 못하니 "
                   "새로 받아 실행하세요: {}/server".format(rules_date, days, SITE_BASE), url=SITE_BASE + "/server")


def find_installs(roots, relpath, max_depth=3, limit=50):
    """웹 폴더 아래(얕게)에서 relpath 파일이 있는 설치 폴더를 찾는다."""
    out, stack = [], [(r, 0) for r in roots]
    while stack and len(out) < limit and time_left() > 5:
        path, depth = stack.pop()
        if os.path.isfile(os.path.join(path, relpath)):
            out.append(path)
        if depth >= max_depth:
            continue
        try:
            for e in os.scandir(path):
                if e.is_dir(follow_symlinks=False) and e.name not in SKIP_DIRS and not e.name.startswith("."):
                    stack.append((e.path, depth + 1))
        except OSError:
            continue
    return sorted(out)


def read_wp_core(base):
    m = re.search(r"\$wp_version\s*=\s*['\"]([0-9][0-9.]*)['\"]", read_text(os.path.join(base, "wp-includes/version.php"), 16384) or "")
    return m.group(1) if m else None


def read_wp_plugin(base, plugin):
    """플러그인 주 파일 머리의 Version: 값. 없으면 readme.txt의 Stable tag."""
    d = os.path.join(base, "wp-content", "plugins", plugin)
    if not os.path.isdir(d):
        return None
    cands = [os.path.join(d, plugin + ".php")] + sorted(glob.glob(os.path.join(d, "*.php")))[:20]
    for path in cands:
        head = read_text(path, 8192) or ""
        if "Plugin Name:" in head:
            m = re.search(r"(?im)^[ \t/*#@]*Version:\s*([0-9][0-9.]*)", head)
            if m:
                return m.group(1)
    m = re.search(r"(?im)^\s*Stable tag:\s*([0-9][0-9.]*)", read_text(os.path.join(d, "readme.txt"), 20000) or "")
    return m.group(1) if m else None


# ---------------------------------------------------------------- 웹 프로그램(CMS) 버전
# 이 스크립트는 아무것도 전송하지 않으므로 '최신 버전이 몇인지'는 모른다. 설치된 버전과 코어 파일 날짜를 보여 주고,
# 오래 방치된 것만 주의로 띄운다. 업데이트하면 버전 파일이 새로 써지므로 그 날짜가 곧 마지막 업데이트 무렵이다.
CMS_STALE_DAYS = 365       # 코어가 이보다 오래 그대로면 주의
PLUGIN_STALE_DAYS = 730    # 워드프레스 플러그인이 이보다 오래 그대로면 주의 (개발이 멈췄을 가능성)
CMS_MARKERS = ("wp-includes/version.php", "bbs/board.php", "config/config.inc.php", "common/constants.php")


def file_mtime(path):
    try:
        return os.stat(path).st_mtime
    except OSError:
        return None


def wp_plugin_info(base, plugin):
    """→ (버전 또는 None, 주 파일 수정 시각 또는 None)."""
    d = os.path.join(base, "wp-content", "plugins", plugin)
    cands = [os.path.join(d, plugin + ".php")] + sorted(glob.glob(os.path.join(d, "*.php")))[:20]
    for path in cands:
        head = read_text(path, 8192) or ""
        if "Plugin Name:" in head:
            m = re.search(r"(?im)^[ \t/*#@]*Version:\s*([0-9][0-9.]*)", head)
            return (m.group(1) if m else None), file_mtime(path)
    return None, None


def read_wp_plugins(base, limit=80):
    d = os.path.join(base, "wp-content", "plugins")
    out = []
    try:
        names = sorted(e.name for e in os.scandir(d) if e.is_dir(follow_symlinks=False) and not e.name.startswith("."))
    except OSError:
        return out
    for name in names[:limit]:
        ver, mt = wp_plugin_info(base, name)
        if mt is not None:
            out.append({"name": name, "version": ver, "mtime": mt})
    return out


def read_cms(base):
    """설치 폴더의 웹 프로그램 → {kind, base, version, mtime, plugins}. 알아보지 못하면 None."""
    vf = os.path.join(base, "wp-includes", "version.php")
    if os.path.isfile(vf):
        return {"kind": "워드프레스", "base": base, "version": read_wp_core(base), "mtime": file_mtime(vf),
                "plugins": read_wp_plugins(base)}
    cf = os.path.join(base, "common", "constants.php")  # 라이믹스는 XE 계열이라 먼저 본다
    m = re.search(r"define\(\s*['\"]RX_VERSION['\"]\s*,\s*['\"]([0-9][0-9.]*)", read_text(cf, 65536) or "")
    if m:
        return {"kind": "라이믹스", "base": base, "version": m.group(1), "mtime": file_mtime(cf), "plugins": []}
    cf = os.path.join(base, "config", "config.inc.php")
    m = re.search(r"define\(\s*['\"]__XE_VERSION__['\"]\s*,\s*['\"]([0-9][0-9.]*)", read_text(cf, 65536) or "")
    if m:
        return {"kind": "XE", "base": base, "version": m.group(1), "mtime": file_mtime(cf), "plugins": []}
    if os.path.isfile(os.path.join(base, "bbs", "board.php")):
        cf = os.path.join(base, "config.php")
        text = read_text(cf, 65536) or ""
        g = re.search(r"G5_GNUBOARD_VER['\"]\s*,\s*['\"]([0-9][0-9.]*)", text)
        y = re.search(r"G5_YOUNGCART_VER['\"]\s*,\s*['\"]([0-9][0-9.]*)", text)
        shop = os.path.isdir(os.path.join(base, "shop"))
        kind = "영카트" if (y or shop) else "그누보드"
        ver = y.group(1) if y else (g.group(1) if g else None)
        return {"kind": kind, "base": base, "version": ver, "mtime": file_mtime(cf) if text else None, "plugins": []}
    return None


def find_cms(roots, limit=20):
    bases = set()
    for marker in CMS_MARKERS:
        bases.update(find_installs(roots, marker))
    out = []
    for b in sorted(bases)[:limit]:
        c = read_cms(b)
        if c:
            out.append(c)
    return out


def _age(mtime, now):
    days = int((now - mtime) // 86400)
    if days < 60:
        return "{}일 전".format(max(days, 0))
    if days < 730:
        return "약 {}개월 전".format(days // 30)
    return "약 {}년 전".format(days // 365)


def judge_cms(roots, installs, now):
    if not roots:
        return None
    if not installs:
        return finding("srv_cms", "web", "info",
                       "웹 폴더({})에서 알려진 웹 프로그램(워드프레스, 그누보드·영카트, XE, 라이믹스)을 찾지 못했습니다.".format(", ".join(roots[:4])))
    lines, stale, kinds = [], False, []
    for c in installs:
        kinds.append(c["kind"])
        line = "{} {} ({})".format(c["kind"], c["version"] or "(버전 확인 못 함)", c["base"])
        if c["mtime"]:
            age = (now - c["mtime"]) / 86400
            day = time.strftime("%Y-%m-%d", time.localtime(c["mtime"]))
            line += " — 코어 파일 날짜 {} ({})".format(day, _age(c["mtime"], now))
            if age > CMS_STALE_DAYS:
                stale = True
                line += ", 1년 넘게 업데이트하지 않은 것으로 보입니다"
        old = [p for p in c["plugins"] if (now - p["mtime"]) / 86400 > PLUGIN_STALE_DAYS]
        if c["plugins"]:
            line += ". 플러그인 {}개".format(len(c["plugins"]))
            if old:
                stale = True
                line += ", 그중 2년 넘게 바뀌지 않은 플러그인 {}개: {}".format(
                    len(old), ", ".join("{} {}".format(p["name"], p["version"] or "") .strip() for p in old[:8]))
        lines.append(line)
    fix = []
    if "워드프레스" in kinds:
        fix += ["워드프레스: 먼저 전체 백업 → 관리자 화면 알림판 > 업데이트에서 코어·플러그인·테마 업데이트",
                "워드프레스(wp-cli): cd 설치폴더 && sudo -u www-data wp core update && sudo -u www-data wp plugin update --all",
                "2년 넘게 바뀌지 않은 플러그인은 개발이 멈췄을 수 있습니다. 쓰지 않으면 지우고, 쓰면 대체 플러그인을 찾으세요"]
    if "그누보드" in kinds or "영카트" in kinds:
        fix.append("그누보드·영카트: 먼저 전체 백업 → 공식 배포처(sir.kr)의 최신 버전·보안 패치를 확인해 적용")
    if "XE" in kinds:
        fix.append("XE: 공식 배포처의 최신 버전을 확인하고, 업데이트가 끊겼다면 같은 계열의 라이믹스(Rhymix)로 옮기는 것도 방법")
    if "라이믹스" in kinds:
        fix.append("라이믹스: 먼저 전체 백업 → 공식 저장소의 최신 버전 적용")
    lead = "설치된 웹 프로그램: " if not stale else "오래 업데이트하지 않은 웹 프로그램이 있습니다: "
    tail = ("" if stale else " 최신 버전인지는 각 프로그램의 공식 사이트에서 확인하세요 (이 스크립트는 인터넷에 접속하지 않습니다).")
    return finding("srv_cms", "web", "warn" if stale else "info", lead + "; ".join(lines) + "." + tail, fix)


def changelog_has(family, pkg, cve):
    """패키지 변경 기록(로컬 파일)에 CVE 번호가 있으면 True, 없으면 False, 확인할 수 없으면 None."""
    if family == "debian":
        for path in ("/usr/share/doc/{}/changelog.Debian.gz".format(pkg), "/usr/share/doc/{}/changelog.gz".format(pkg)):
            try:
                with gzip.open(path, "rb") as f:
                    return cve.encode() in f.read(8 * 1024 * 1024)
            except (OSError, EOFError):
                continue
        return None
    if family == "rhel":
        r = run(["rpm", "-q", "--changelog", pkg])
        if not r or r[0] != 0:
            return None
        return cve in r[1]
    return None


DELETED_IGNORE = re.compile(r"^(/dev/|/memfd:|/tmp/|/var/tmp/|/run/|/SYSV|/proc/|/home/|/root/)")


def find_stale(proc_entries):
    """proc_entries: [(pid, comm, exe_link, maps_text)] → 지워진(업데이트로 교체된) 실행 파일·라이브러리를 쓰는 프로세스"""
    stale = {}
    for pid, comm, exe, maps in proc_entries:
        reason = None
        if exe and exe.endswith(" (deleted)") and not DELETED_IGNORE.match(exe):
            reason = os.path.basename(exe[:-10])
        else:
            for line in (maps or "").splitlines():
                if not line.endswith(" (deleted)"):
                    continue
                path = line.split(None, 5)[-1][:-10] if len(line.split(None, 5)) == 6 else ""
                if path.startswith("/") and not DELETED_IGNORE.match(path) and (".so" in path or "/bin/" in path or "/sbin/" in path):
                    reason = os.path.basename(path)
                    break
        if reason:
            stale.setdefault(comm, []).append((pid, reason))
    return stale


def unit_of(cgroup_text):
    m = re.search(r"/([\w@.:-]+\.service)\b", cgroup_text or "")
    return m.group(1) if m else None


def judge_restart(stale, is_root, units=None, watch=None):
    """watch: [(제품 이름, 프로세스 이름 정규식)] — 알려진 취약점 규칙의 재시작 대상"""
    units = units or {}
    watch = watch if watch is not None else [(r["product"], r["restart"]) for r in RULES if r.get("restart")]
    if not stale:
        if not is_root:
            return finding("srv_restart", "service", "info", "다른 계정의 프로세스는 root 권한이 있어야 확인할 수 있습니다.")
        return finding("srv_restart", "service", "pass", "업데이트된 프로그램을 옛 버전으로 계속 쓰는 프로세스가 없습니다.")
    hit = sorted({prod for c in stale for prod, pat in watch if re.search(pat, c)})
    items = ["{}({})".format(c, stale[c][0][1]) for c in sorted(stale)][:10]
    svc = sorted({units[c] for c in stale if units.get(c)})
    lvl = "danger" if hit else "warn"
    why = (" 알려진 취약점이 있었던 {}을(를) 업데이트한 뒤 재시작하지 않으면 메모리의 옛 버전이 계속 돌아가 여전히 취약합니다."
           .format(", ".join(hit)) if hit else "")
    return finding("srv_restart", "service", lvl,
                   "업데이트로 바뀐 파일을 옛 버전으로 계속 쓰고 있는 프로세스: {}.{}".format(", ".join(items), why),
                   (["sudo systemctl restart " + " ".join(svc[:8])] if svc else ["해당 프로그램을 다시 시작"]) +
                   ["어느 서비스인지 모르겠으면 점검 시간에 sudo reboot",
                    "Ubuntu·Debian: sudo apt install needrestart 로 업데이트 때마다 자동 안내"])


def parse_mycnf(texts):
    bind, skip = None, False
    for _, text in texts:
        section = ""
        for raw in (text or "").splitlines():
            line = raw.split("#", 1)[0].strip()
            if line.startswith("["):
                section = line.strip("[]").lower()
                continue
            if section not in ("mysqld", "mariadb", "server", "mariadbd") and not section.startswith("mariadb-"):
                continue
            k = line.split("=", 1)[0].strip().lower().replace("_", "-")
            if k == "bind-address" and "=" in line:
                bind = line.split("=", 1)[1].strip()
            if k == "skip-networking":
                skip = "=" not in line or line.split("=", 1)[1].strip().lower() in ("1", "on", "true", "")
    return bind, skip


def judge_mysql(bind, skip_networking, listening_scope):
    if skip_networking:
        return finding("srv_mysql", "service", "pass", "네트워크 접속을 끄고(skip-networking) 로컬 소켓으로만 접속합니다.")
    if listening_scope == "any" or (listening_scope is None and bind in (None, "0.0.0.0", "*", "::")):
        cur = bind or "설정 없음(모든 주소)"
        return finding("srv_mysql", "service", "warn",
                       "MySQL·MariaDB가 모든 주소에서 접속을 받습니다 (bind-address: {}). 비밀번호 대입 공격과 취약점 공격 대상이 됩니다.".format(cur),
                       ["설정 파일 [mysqld] 에 bind-address = 127.0.0.1", "sudo systemctl restart mysql   # 또는 mariadb"])
    return finding("srv_mysql", "service", "pass", "MySQL·MariaDB가 내부 주소에서만 접속을 받습니다 (bind-address: {}).".format(bind or "기본값"))


def parse_redis(text):
    cfg = {"bind": None, "protected-mode": "yes", "requirepass": False}
    for raw in (text or "").splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        parts = line.split(None, 1)
        k = parts[0].lower()
        v = parts[1].strip() if len(parts) > 1 else ""
        if k == "bind":
            cfg["bind"] = v
        elif k == "protected-mode":
            cfg["protected-mode"] = v.lower()
        elif k == "requirepass":
            cfg["requirepass"] = bool(v.strip('"'))  # 값은 저장하지 않는다
    return cfg


def judge_redis(cfg, listening_scope):
    bind = cfg["bind"]
    external = listening_scope == "any" or (listening_scope is None and (
        bind is None or any(b in ("0.0.0.0", "*", "::", "-::*") for b in bind.split())))
    if not external:
        return finding("srv_redis", "service", "pass", "Redis가 내부 주소에서만 접속을 받습니다 (bind: {}).".format(bind or "기본값"))
    fix = ["/etc/redis/redis.conf: bind 127.0.0.1 -::1", "/etc/redis/redis.conf: protected-mode yes",
           "외부 접속이 꼭 필요하면 requirepass 또는 ACL로 비밀번호 설정 + 방화벽으로 허용 IP 제한", "sudo systemctl restart redis-server   # 또는 redis"]
    if not cfg["requirepass"] and cfg["protected-mode"] == "no":
        return finding("srv_redis", "service", "danger",
                       "Redis가 모든 주소에서 비밀번호 없이 접속을 받습니다 (protected-mode no). 누구나 데이터를 읽고 지우고, 서버 장악에 악용할 수 있습니다.", fix)
    if not cfg["requirepass"]:
        return finding("srv_redis", "service", "warn",
                       "Redis가 모든 주소에서 접속을 받는데 비밀번호(requirepass)가 없습니다. protected-mode가 외부 접속을 막고 있지만 설정 하나로 바로 노출됩니다.", fix)
    return finding("srv_redis", "service", "info", "Redis가 모든 주소에서 접속을 받습니다. 비밀번호는 설정돼 있습니다.", fix[:1])


def parse_docker_ps(text):
    out = []
    for line in (text or "").splitlines():
        if "|" not in line:
            continue
        name, ports = line.split("|", 1)
        for m in re.finditer(r"(0\.0\.0\.0|::|\[::\]):(\d+)->(\d+)/(tcp|udp)", ports):
            out.append((name.strip(), int(m.group(2)), m.group(4)))
    return out


def judge_docker(sock_mode, published, group_members, ps_ok):
    msgs, lvls = [], []
    fix = []
    if sock_mode is not None and sock_mode & 0o002:
        msgs.append("docker.sock을 누구나 쓸 수 있습니다 ({}) — 모든 계정이 사실상 root".format(oct(sock_mode & 0o777)))
        lvls.append("danger")
        fix.append("sudo chmod 660 /var/run/docker.sock")
    if group_members:
        msgs.append("docker 그룹(사실상 root 권한): {}".format(", ".join(group_members)))
        lvls.append("info")
    risky = sorted({(n, p) for n, p, proto in published if p in RISKY_PORTS})
    pub = sorted({"{}:{}".format(n, p) for n, p, proto in published})
    if risky:
        msgs.append("DB 등 위험 포트가 모든 주소로 게시됨: {}".format(", ".join("{}:{}".format(n, p) for n, p in risky)))
        lvls.append("warn")
        fix.append("docker run -p 127.0.0.1:3306:3306 처럼 게시 주소를 127.0.0.1로 지정")
    if pub:
        msgs.append("모든 주소로 게시된 포트: {} — Docker가 게시한 포트는 ufw 규칙을 우회합니다".format(", ".join(pub[:10])))
        lvls.append("info")
    if not ps_ok:
        msgs.append("컨테이너 목록을 읽지 못했습니다 (Docker가 꺼져 있거나, root·docker 그룹 권한이 없음)")
        lvls.append("info")
    if not msgs:
        return finding("srv_docker", "service", "pass", "Docker 소켓 권한과 게시 포트에 문제가 없습니다.")
    return finding("srv_docker", "service", worst(lvls), "; ".join(msgs) + ".", fix)


def judge_disk(usages):
    """usages: [(mount, percent)]"""
    full = [(m, p) for m, p in usages if p >= 90]
    if full:
        lvl = "danger" if any(p >= 97 for _, p in full) else "warn"
        return finding("srv_disk", "misc", lvl,
                       "디스크가 거의 찼습니다: {}. 가득 차면 로그 기록·업데이트·DB가 멈춥니다.".format(", ".join("{} {}%".format(m, p) for m, p in full)),
                       ["sudo du -xh --max-depth=1 / | sort -h | tail", "sudo journalctl --vacuum-size=200M"])
    return finding("srv_disk", "misc", "pass", "디스크 여유가 있습니다 ({}).".format(", ".join("{} {}%".format(m, p) for m, p in usages)))


def judge_time(synced):
    if synced is True:
        return finding("srv_time", "misc", "pass", "시간이 자동으로 맞춰지고 있습니다.")
    if synced is False:
        return finding("srv_time", "misc", "warn", "시간 동기화가 되지 않고 있습니다. 로그 시각이 틀어지면 사고 조사와 인증서 검증이 어려워집니다.",
                       ["sudo timedatectl set-ntp true"])
    return finding("srv_time", "misc", "info", "시간 동기화 상태를 확인하지 못했습니다.")


# ---------------------------------------------------------------- 수집 (시스템을 읽어 판정 함수에 넘긴다)

def probe_package(rule, family):
    """규칙의 실행 파일에 버전을 묻고, 배포판 패키지인지와 변경 기록의 CVE 여부를 본다."""
    installs, seen = [], set()
    for spec in rule.get("binaries", []):
        pat, args = spec[0], list(spec[1:])
        exes = sorted(glob.glob(pat)) if "/" in pat else [x for x in [which(pat)] if x]
        for exe in exes:
            real = os.path.realpath(exe)
            if real in seen or not os.access(real, os.X_OK):
                continue
            seen.add(real)
            r = run([exe] + args)
            if not r or r[0] != 0 or not r[1].strip():
                continue
            packaged, patched = False, None
            if family == "debian":
                q = run(["dpkg", "-S", real])
                packaged = bool(q and q[0] == 0)
                if packaged and rule.get("cve"):
                    patched = changelog_has(family, q[1].split(":")[0].strip(), rule["cve"])
            elif family == "rhel":
                q = run(["rpm", "-qf", "--qf", "%{NAME}\n", real])
                packaged = bool(q and q[0] == 0)
                if packaged and rule.get("cve"):
                    patched = changelog_has(family, q[1].strip().splitlines()[0], rule["cve"])
            if packaged and patched is not True and rule.get("cve"):
                # 패치가 다른 패키지에 들어가는 경우 (예: RHEL은 Apache HTTP/2 패치가 mod_http2 패키지에)
                for extra in rule.get("changelog_pkgs", []):
                    if changelog_has(family, extra, rule["cve"]):
                        patched = True
                        break
            installs.append((os.path.basename(exe), r[1].strip().splitlines()[0], packaged, patched))
    return installs


def collect(today=None):
    today = today or date.today()
    is_root = os.geteuid() == 0
    osr = parse_os_release(read_text("/etc/os-release") or read_text("/usr/lib/os-release"))
    family = os_family(osr)
    F = []
    skipped = []

    def step(name, fn):
        if time_left() <= 0:
            skipped.append(name)
            return
        try:
            res = fn()
        except Exception as e:  # 한 항목의 실패가 전체를 멈추지 않게
            res = finding("srv_" + name, "misc", "info", "확인 중 오류가 나 건너뛰었습니다 ({}).".format(type(e).__name__))
        if res is None:
            return
        if isinstance(res, list):
            F.extend(res)
        else:
            F.append(res)

    # 운영체제
    step("os_eol", lambda: judge_os_eol(osr, today))

    upd = {"raw": None}

    def updates():
        if family == "debian":
            r = run(["apt-get", "-s", "-o", "Debug::NoLocking=1", "upgrade"], timeout=15)
            if not r:
                return finding("srv_updates", "os", "info", "apt 업데이트 목록을 읽지 못했습니다.")
            upd["raw"] = r[1]
            age = None
            for p in ("/var/lib/apt/periodic/update-success-stamp", "/var/cache/apt/pkgcache.bin", "/var/lib/apt/lists"):
                try:
                    age = int((time.time() - os.stat(p).st_mtime) // 86400)
                    break
                except OSError:
                    continue
            return judge_apt_updates(r[1], age)
        if family == "rhel":
            r = run(["dnf", "-q", "--cacheonly", "updateinfo", "list", "--security"], timeout=15)
            if r and r[0] in (0, 100):
                upd["raw"] = r[1]
            return judge_dnf_updates(r[0] if r else -1, r[1] if r else "")
        return finding("srv_updates", "os", "info", "이 배포판의 업데이트 확인 방법을 모릅니다.")
    step("updates", updates)

    def reboot():
        if family == "debian":
            return judge_reboot(os.path.exists("/var/run/reboot-required"), read_text("/var/run/reboot-required.pkgs"))
        r = run(["needs-restarting", "-r"])
        if r is None:
            return None
        return judge_reboot(r[0] == 1, "")
    step("reboot", reboot)

    def autoupdate():
        if family == "debian":
            r = run(["dpkg-query", "-W", "-f=${Status}", "unattended-upgrades"])
            installed = bool(r and "install ok installed" in r[1])
            texts = {p: read_text(p) for p in glob.glob("/etc/apt/apt.conf.d/*")}
            return judge_autoupdate_debian(installed, texts)
        if family == "rhel":
            conf = parse_ini(read_text("/etc/dnf/automatic.conf"))
            return judge_autoupdate_rhel(service_enabled("dnf-automatic-install.timer"),
                                         service_enabled("dnf-automatic.timer"), conf.get("apply_updates") == "yes")
        return None
    step("autoupdate", autoupdate)

    # SSH
    ssh_state = {"password": True}

    def ssh():
        if not which("sshd") and not os.path.exists("/etc/ssh/sshd_config"):
            ssh_state["password"] = False
            return finding("srv_ssh_misc", "ssh", "info", "SSH 서버가 설치돼 있지 않습니다.")
        cfg, src = {}, "config"
        if is_root:
            r = run(["sshd", "-T"])
            if r and r[0] == 0 and r[1].strip():
                cfg, src = parse_sshd_t(r[1]), "sshd -T"
        if not cfg:
            cfg = parse_sshd_config("/etc/ssh/sshd_config")
        res = judge_ssh(cfg, src)
        ssh_state["password"] = any(f["id"] == "srv_ssh_password" and f["level"] != "pass" for f in res)
        return res
    step("ssh", ssh)

    # 계정
    users = parse_passwd(read_text("/etc/passwd"))
    step("uid0", lambda: judge_uid0(users))
    step("accounts", lambda: judge_login_accounts(users))

    def shadow():
        text = read_text("/etc/shadow")
        if text is None:
            return finding("srv_empty_password", "account", "info", "root 권한이 있어야 확인할 수 있습니다.")
        return judge_shadow(text)
    step("empty_password", shadow)

    def sudoers():
        paths = ["/etc/sudoers"] + sorted(glob.glob("/etc/sudoers.d/*"))
        texts = {p: read_text(p) for p in paths}
        if all(v is None for v in texts.values()):
            return finding("srv_sudo_nopasswd", "account", "info", "root 권한이 있어야 확인할 수 있습니다.")
        return judge_sudoers({k: v for k, v in texts.items() if v is not None}, ssh_state["password"])
    step("sudo_nopasswd", sudoers)

    # 방화벽·포트
    fw = {"on": None}

    def firewall():
        ufw = run(["ufw", "status"]) if is_root else None
        nft = run(["nft", "list", "ruleset"]) if is_root else None
        ipt = run(["iptables", "-S"]) if is_root else None
        res, on = judge_firewall(is_root, ufw[1] if ufw else None, service_active("firewalld"),
                                 nft[1] if nft else None, ipt[1] if ipt else None, family)
        fw["on"] = on
        return res
    step("firewall", firewall)

    listeners = []

    def ports():
        r = run(["ss", "-H", "-tulpn"])
        if not r or r[0] != 0:
            r = run(["ss", "-tulpn"])
        if not r or r[0] != 0:
            r = run(["netstat", "-tulpn"])
            if not r or r[0] != 0:
                return finding("srv_ports", "network", "info", "ss·netstat 명령이 없어 열린 포트를 확인하지 못했습니다.")
        listeners.extend(parse_ss(r[1]))
        return judge_ports(listeners, bool(fw["on"]))
    step("ports", ports)

    def bruteforce():
        log = None
        for p in ("/var/log/auth.log", "/var/log/secure"):
            log = read_tail(p)
            if log is not None:
                break
        failures = count_ssh_failures(log) if log is not None else None
        return judge_bruteforce(service_active("fail2ban"), service_active("sshguard"), ssh_state["password"], failures)
    step("bruteforce", bruteforce)

    # 파일 권한
    def sysperm():
        stats = {}
        for p in ("/etc/shadow", "/etc/gshadow", "/etc/passwd", "/etc/group", "/etc/sudoers", "/etc/ssh/sshd_config"):
            try:
                st = os.stat(p)
                stats[p] = (st.st_mode, st.st_uid)
            except OSError:
                pass
        try:
            for e in os.scandir("/etc"):
                if e.is_file(follow_symlinks=False):
                    st = e.stat(follow_symlinks=False)
                    if st.st_mode & 0o002:
                        stats[e.path] = (st.st_mode, st.st_uid)
        except OSError:
            pass
        return judge_system_perms(stats)
    step("perm_system", sysperm)

    def cronperm():
        paths = ["/etc/crontab"] + glob.glob("/etc/cron.d/*")
        for d in ("hourly", "daily", "weekly", "monthly"):
            paths += glob.glob("/etc/cron.{}/*".format(d))
        paths += glob.glob("/var/spool/cron/crontabs/*") + glob.glob("/var/spool/cron/root")
        stats = {}
        for p in paths:
            try:
                st = os.lstat(p)
                if stat.S_ISREG(st.st_mode):
                    stats[p] = (st.st_mode, st.st_uid)
            except OSError:
                pass
        return judge_cron_perms(stats)
    step("perm_cron", cronperm)

    # 웹 폴더
    def web():
        roots = [r for pat in WEB_ROOT_GLOBS for r in glob.glob(pat) if os.path.isdir(r)]
        files, gits, writable, trunc = walk_web_roots(roots)
        return judge_web(roots, files, gits, writable, trunc)
    step("web", web)

    def cms():
        roots = [r for pat in WEB_ROOT_GLOBS for r in glob.glob(pat) if os.path.isdir(r)]
        return judge_cms(roots, find_cms(roots), time.time())
    step("cms", cms)

    # 침해 흔적
    def intrusion_web():
        roots = [r for pat in WEB_ROOT_GLOBS for r in glob.glob(pat) if os.path.isdir(r)]
        return judge_intrusion_web(roots, scan_web_tree(roots, time.time() - 7 * 86400))
    step("webshell", intrusion_web)

    def ssh_keys():
        entries, seen = [], set()
        for u in users:
            if u["uid"] != 0 and (u["uid"] < 1000 or re.search(r"(nologin|false)$", u["shell"])):
                continue
            path = os.path.join(u["home"] or "/nonexistent", ".ssh", "authorized_keys")
            for p in (path, path + "2"):
                real = os.path.realpath(p)
                if real in seen:
                    continue
                try:
                    st = os.stat(p)
                except OSError:
                    continue
                seen.add(real)
                keys = parse_authorized_keys(read_text(p, 512 * 1024))
                entries.append((u["name"], p, st.st_mtime, bool(st.st_mode & 0o002), keys))
        return judge_ssh_keys(entries, time.time(), is_root)
    step("ssh_keys", ssh_keys)

    def cron_suspicious():
        entries = []
        tabs = ["/etc/crontab"] + glob.glob("/etc/cron.d/*") + glob.glob("/var/spool/cron/crontabs/*") + glob.glob("/var/spool/cron/*")
        scripts = [p for d in ("hourly", "daily", "weekly", "monthly") for p in glob.glob("/etc/cron.{}/*".format(d))]
        for p in tabs + scripts:
            if os.path.isfile(p):
                entries.append((p, read_text(p, 256 * 1024), p in tabs))
        return judge_cron_suspicious(entries)
    step("cron_suspicious", cron_suspicious)

    # 서비스
    def php():
        versions = []
        r = run(["php", "-r", "echo PHP_VERSION;"])
        if r and r[0] == 0 and re.match(r"^\d+\.\d+", r[1].strip()):
            versions.append(".".join(r[1].strip().split(".")[:2]))
        sapi_ini = {}
        for d in glob.glob("/etc/php/*/*"):  # Debian/Ubuntu: /etc/php/8.3/fpm
            parts = d.rstrip("/").split("/")
            ver, sapi = parts[-2], parts[-1]
            if not re.match(r"^\d+\.\d+$", ver) or sapi not in ("fpm", "apache2", "cli", "cgi"):
                continue
            versions.append(ver)
            ini = parse_ini(read_text(os.path.join(d, "php.ini")))
            for extra in sorted(glob.glob(os.path.join(d, "conf.d", "*.ini"))):
                ini.update(parse_ini(read_text(extra)))
            sapi_ini["{} {}".format(sapi, ver)] = ini
        if os.path.exists("/etc/php.ini"):  # RHEL 계열
            ini = parse_ini(read_text("/etc/php.ini"))
            for extra in sorted(glob.glob("/etc/php.d/*.ini")):
                ini.update(parse_ini(read_text(extra)))
            sapi_ini["php.ini"] = ini
        return judge_php(versions, sapi_ini, today)
    step("php", php)

    def advisories():
        out, none = [], []
        web_roots = [r for pat in WEB_ROOT_GLOBS for r in glob.glob(pat) if os.path.isdir(r)]
        wp_bases = None
        done = set()
        for rule in RULES:
            if time_left() <= 5:
                break
            key = (rule["id"], rule["type"])
            if rule["type"] not in ("package", "wp_core", "wp_plugin", "cms_file") or key in done:
                continue
            done.add(key)
            res = None
            if rule["type"] == "package":
                installs = probe_package(rule, family)
                res = judge_package(rule, installs, pending_security(family, upd["raw"], rule))
            elif rule["type"] in ("wp_core", "wp_plugin"):
                if wp_bases is None:
                    wp_bases = find_installs(web_roots, "wp-includes/version.php")
                if rule["type"] == "wp_core":
                    found = [(b, read_wp_core(b)) for b in wp_bases]
                else:
                    found = [(b, read_wp_plugin(b, rule["plugin"])) for b in wp_bases] if re.match(r"^[a-z0-9-]{1,80}$", rule.get("plugin", "")) else []
                res = judge_app(rule, [(b, v) for b, v in found if v])
            elif rule["type"] == "cms_file":
                rel = rule.get("path", "")
                if rel and not rel.startswith("/") and ".." not in rel:
                    found = []
                    for b in find_installs(web_roots, rel):
                        m = re.search(rule["pattern"], read_text(os.path.join(b, rel), 65536) or "")
                        if m:
                            found.append((b, m.group(1)))
                    res = judge_app(rule, found)
            if res is None:
                if rule["title"] not in none and not any(f["id"] == rule["id"] for f in out):
                    none.append(rule["title"])
            else:
                out = [f for f in out if f["id"] != rule["id"] or LEVELS.index(f["level"]) < LEVELS.index(res["level"])]
                if not any(f["id"] == rule["id"] for f in out):
                    out.append(res)
                    none = [t for t in none if t != rule["title"]]
        if none:
            out.append(finding("srv_advisories", "vuln", "pass",
                               "보안 브리핑의 알려진 취약점 {}건은 이 서버에 해당 프로그램이 없습니다: {}.".format(len(none), ", ".join(none[:6]))))
        age = judge_rules_age(RULES_DATE, today)
        if age:
            out.append(age)
        if not RULES:
            out.append(finding("srv_advisories", "vuln", "info", "이 스크립트에는 알려진 취약점 규칙이 없습니다."))
        return out
    step("advisories", advisories)

    def restart():
        entries = []
        try:
            pids = [d for d in os.listdir("/proc") if d.isdigit()]
        except OSError:
            pids = []
        for pid in pids[:3000]:
            if time_left() <= 3:
                break
            comm = (read_text("/proc/{}/comm".format(pid), 256) or "").strip()
            try:
                exe = os.readlink("/proc/{}/exe".format(pid))
            except OSError:
                exe = None
            maps = read_text("/proc/{}/maps".format(pid), 512 * 1024)
            if comm and (exe or maps):
                entries.append((int(pid), comm, exe, maps))
        PROCS[:] = [(pid, comm, exe) for pid, comm, exe, _ in entries]
        stale = find_stale(entries)
        units = {c: unit_of(read_text("/proc/{}/cgroup".format(lst[0][0]), 4096)) for c, lst in stale.items()}
        return judge_restart(stale, is_root, units)
    PROCS = []
    step("restart", restart)
    step("suspicious_proc", lambda: judge_suspicious_procs(PROCS, is_root) if PROCS else None)

    def scope_for(port):
        scopes = [scope_of(l["host"], l["iface"]) for l in listeners if l["port"] == port and l["proto"] == "tcp"]
        if not scopes:
            return None
        return "any" if "any" in scopes else ("private" if "private" in scopes else "local")

    def mysql():
        files = [p for p in (["/etc/mysql/my.cnf", "/etc/my.cnf"] + sorted(glob.glob("/etc/mysql/*/*.cnf"))
                             + sorted(glob.glob("/etc/my.cnf.d/*.cnf"))) if os.path.isfile(p)]
        present = files or which("mysqld") or which("mariadbd") or scope_for(3306)
        if not present:
            return None
        bind, skip = parse_mycnf([(p, read_text(p)) for p in files])
        return judge_mysql(bind, skip, scope_for(3306))
    step("mysql", mysql)

    def redis():
        conf = next((p for p in ("/etc/redis/redis.conf", "/etc/redis.conf", "/etc/redis/default.conf") if os.path.isfile(p)), None)
        if not conf and not scope_for(6379):
            return None
        text = read_text(conf) if conf else None
        if conf and text is None:
            return finding("srv_redis", "service", "info", "Redis 설정 파일을 읽으려면 root 권한이 필요합니다.")
        return judge_redis(parse_redis(text), scope_for(6379))
    step("redis", redis)

    def docker():
        if not which("docker") and not os.path.exists("/var/run/docker.sock"):
            return None
        try:
            mode = os.stat("/var/run/docker.sock").st_mode
        except OSError:
            mode = None
        try:
            members = grp.getgrnam("docker").gr_mem
        except KeyError:
            members = []
        r = run(["docker", "ps", "--format", "{{.Names}}|{{.Ports}}"])
        ok = bool(r and r[0] == 0)
        return judge_docker(mode, parse_docker_ps(r[1]) if ok else [], members, ok)
    step("docker", docker)

    # 기타
    def disk():
        usages, seen = [], set()
        for m in ("/", "/var", "/home"):
            try:
                st = os.statvfs(m)
            except OSError:
                continue
            key = (st.f_blocks, st.f_bfree)
            if key in seen or not st.f_blocks:
                continue
            seen.add(key)
            used = st.f_blocks - st.f_bfree
            usages.append((m, int(round(100.0 * used / max(1, used + st.f_bavail)))))
        return judge_disk(usages)
    step("disk", disk)

    def timesync():
        r = run(["timedatectl", "show", "-p", "NTPSynchronized", "--value"])
        if r and r[1].strip() in ("yes", "no"):
            return judge_time(r[1].strip() == "yes")
        r = run(["chronyc", "tracking"])
        if r and r[0] == 0:
            return judge_time("Normal" in r[1])
        return judge_time(None)
    step("time", timesync)

    meta = {
        "tool": "mundansok-server", "version": VERSION, "rules_date": RULES_DATE, "rules": len({r["id"] for r in RULES}),
        "generated": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "host": socket.gethostname(), "os": osr.get("PRETTY_NAME", platform.platform()),
        "kernel": platform.release(), "root": is_root, "family": family,
        "seconds": round(time.monotonic() - START, 1), "skipped": skipped,
    }
    return F, meta


# ---------------------------------------------------------------- 출력

COLORS = {"danger": "\033[1;31m", "warn": "\033[1;33m", "info": "\033[36m", "pass": "\033[32m"}
RESET, BOLD, DIM = "\033[0m", "\033[1m", "\033[2m"


def counts(F):
    c = {lv: 0 for lv in LEVELS}
    for f in F:
        c[f["level"]] += 1
    return c


def report_text(F, meta, color=True):
    def c(code, s):
        return code + s + RESET if color else s
    out = []
    out.append(c(BOLD, "문단속 서버 점검 v{}".format(meta["version"])) +
               "  (알려진 취약점 규칙 {}건, {} 기준)".format(meta.get("rules", 0), meta.get("rules_date") or "없음"))
    out.append("서버: {} · {} · 커널 {}".format(meta["host"], meta["os"], meta["kernel"]))
    out.append("시각: {} · 소요 {}초 · {}".format(meta["generated"], meta["seconds"],
                                              "root로 실행" if meta["root"] else c(COLORS["warn"], "root 아님 — 일부 항목 건너뜀 (sudo로 실행하세요)")))
    cn = counts(F)
    out.append("결과: " + "  ".join(c(COLORS[lv], "{} {}".format(LEVEL_KO[lv], cn[lv])) for lv in LEVELS))
    out.append("")
    for cid, cname in CATEGORIES:
        items = sorted([f for f in F if f["cat"] == cid], key=lambda f: LEVELS.index(f["level"]))
        if not items:
            continue
        out.append(c(BOLD, "■ " + cname))
        for f in items:
            out.append("  " + c(COLORS[f["level"]], "[{}]".format(LEVEL_KO[f["level"]])) + " " + c(BOLD, f["title"]))
            out.append("        " + f["detail"])
            if f["level"] in ("danger", "warn"):
                for line in f["fix"]:
                    out.append("        " + c(DIM, "조치: ") + line)
                out.append("        " + c(DIM, "자세히: " + more_url(f)))
        out.append("")
    if meta["skipped"]:
        out.append("시간 제한으로 건너뛴 항목: " + ", ".join(meta["skipped"]))
    out.append(c(BOLD, "이 점검이 보지 못하는 것"))
    for l in LIMITS:
        out.append("  - " + l)
    out.append("'양호'는 해당 항목에서 문제를 찾지 못했다는 뜻이며, 서버가 안전하다는 보증은 아닙니다.")
    out.append("이 스크립트는 아무것도 바꾸거나 전송하지 않았습니다.")
    return "\n".join(out)


def report_html(F, meta):
    e = html.escape
    cn = counts(F)
    rows = []
    for cid, cname in CATEGORIES:
        items = sorted([f for f in F if f["cat"] == cid], key=lambda f: LEVELS.index(f["level"]))
        if not items:
            continue
        rows.append("<h2>{}</h2>".format(e(cname)))
        for f in items:
            fix = ""
            if f["level"] in ("danger", "warn") and f["fix"]:
                fix = "<pre>{}</pre>".format(e("\n".join(f["fix"])))
            link = '<a href="{0}">자세히</a>'.format(e(more_url(f))) if f["level"] != "pass" else ""
            rows.append('<div class="f"><span class="b {0}">{1}</span><b>{2}</b><p>{3} {4}</p>{5}</div>'.format(
                f["level"], LEVEL_KO[f["level"]], e(f["title"]), e(f["detail"]), link, fix))
    limits = "".join("<li>{}</li>".format(e(l)) for l in LIMITS)
    chips = "".join('<span class="b {0}">{1} {2}</span> '.format(lv, LEVEL_KO[lv], cn[lv]) for lv in LEVELS)
    return """<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>문단속 서버 점검 — {host}</title><style>
body{{font:15px/1.6 system-ui,"Malgun Gothic","Apple SD Gothic Neo",sans-serif;max-width:860px;margin:24px auto;padding:0 16px;color:#16202c}}
h1{{font-size:24px}}h2{{font-size:17px;margin-top:28px;border-bottom:1px solid #dde3ea;padding-bottom:4px}}
.f{{padding:10px 0;border-bottom:1px solid #eef1f4}}.f p{{margin:4px 0 0;color:#3d4a5a}}
.b{{display:inline-block;font-size:12px;font-weight:700;padding:2px 8px;border-radius:6px;margin-right:8px}}
.danger{{background:#fdeeee;color:#c62b2b}}.warn{{background:#fff4e2;color:#a85d00}}.info{{background:#eef1f4;color:#4a5867}}.pass{{background:#e9f6ee;color:#1b7a43}}
pre{{background:#101823;color:#e6edf5;padding:10px 12px;border-radius:8px;overflow-x:auto;font-size:13px}}.m{{color:#6b7684;font-size:13px}}
</style></head><body><h1>문단속 서버 점검</h1>
<p class="m">{host} · {os} · 커널 {kernel}<br>{gen} · {mode} · v{ver} · 취약점 규칙 {rd} 기준</p><p>{chips}</p>{rows}
<h2>이 점검이 보지 못하는 것</h2><ul>{limits}</ul>
<p class="m">'양호'는 해당 항목에서 문제를 찾지 못했다는 뜻이며, 서버가 안전하다는 보증은 아닙니다. 이 보고서에는 서버 정보(계정 이름, 경로, 포트)가 들어 있으니 공유에 주의하세요.</p>
</body></html>""".format(host=e(meta["host"]), os=e(meta["os"]), kernel=e(meta["kernel"]), gen=e(meta["generated"]),
                         mode="root로 실행" if meta["root"] else "root 아님 — 일부 항목 건너뜀", ver=e(meta["version"]), rd=e(meta.get("rules_date") or "없음"),
                         chips=chips, rows="".join(rows), limits=limits)


def write_private(path, text):
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        f.write(text)


def main(argv=None):
    ap = argparse.ArgumentParser(description="문단속 서버 점검 — 읽기 전용, 아무것도 바꾸거나 전송하지 않습니다.")
    ap.add_argument("--json", action="store_true", help="결과를 JSON으로 출력")
    ap.add_argument("--html", metavar="파일", help="HTML 보고서를 이 파일로 저장 (권한 600)")
    ap.add_argument("--no-color", action="store_true", help="색 없이 출력")
    ap.add_argument("--version", action="version", version="mundansok-server " + VERSION)
    args = ap.parse_args(argv)
    if sys.platform != "linux":
        print("리눅스 서버에서만 실행할 수 있습니다.", file=sys.stderr)
        return 3
    F, meta = collect()
    cn = counts(F)
    if args.json:
        print(json.dumps({"meta": meta, "counts": cn, "findings": F, "limits": LIMITS}, ensure_ascii=False, indent=2))
    else:
        print(report_text(F, meta, color=not args.no_color and sys.stdout.isatty()))
    if args.html:
        write_private(args.html, report_html(F, meta))
        print("\nHTML 보고서: {} (서버 정보가 들어 있으니 공유에 주의하세요)".format(args.html), file=sys.stderr)
    return 2 if cn["danger"] else (1 if cn["warn"] else 0)


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