#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LOI Zabbix Linux Monitoring Agent
Pure Python 3 - Zero external dependencies required (No pip, No psutil needed)
"""

import sys
import os
import re
import glob
import time
import json
import socket
import shutil
import platform
import argparse
import struct
import subprocess
import hashlib
import calendar
import hmac
import threading
import urllib.request
import urllib.parse

CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "agent_config.json")
DEFAULT_PORT = 65000

# 수집기 인증 토큰 (collector\agent_token.json 과 동일해야 함)
AGENT_TOKEN = "30a6a25d0940d771db6e899735fd495f8a3b5d298ee4aedf76c7de6597e0c050"

# 종료/재부팅 명령 (감시 대상): shutdown, reboot, halt, poweroff, init 0/6, systemctl reboot/poweroff
SHUTDOWN_COMMS = ("shutdown", "reboot", "halt", "poweroff", "init", "systemctl")

# ---- WAF (Linux, access-log based detection) ----
WAF_DIR = "/etc/loi-waf"
WAF_RULES_PATH = os.path.join(WAF_DIR, "waf_rules.json")
WAF_MODE_PATH = os.path.join(WAF_DIR, "waf_mode.txt")
WAF_EXC_PATH = os.path.join(WAF_DIR, "waf_exceptions.json")
WAF_SITES_PATH = os.path.join(WAF_DIR, "waf_sites.json")
WAF_RATE_PATH = os.path.join(WAF_DIR, "waf_ratelimits.json")
WAF_REP_PATH = os.path.join(WAF_DIR, "reputation.txt")
WAF_BOT_PATH = os.path.join(WAF_DIR, "bot_allow.txt")
WAF_API_PATH = os.path.join(WAF_DIR, "api_guard.json")
WAF_LOG_DIR = "/var/log/loi-waf"
WAF_LOG_PATH = os.path.join(WAF_LOG_DIR, "waf_module.log")
WAF_STATE_DIR = "/var/lib/loi-waf"
WAF_STATE_PATH = os.path.join(WAF_STATE_DIR, "offsets.json")
WAF_AUDIT_PATH = "/var/log/httpd/loi_waf_audit.log"
WAF_AUDIT_PATH_ALT = "/var/log/apache2/loi_waf_audit.log"
WAF_GEO_PATH = os.path.join(WAF_DIR, "geo_deny.txt")
WAF_GEO_ALLOW_PATH = os.path.join(WAF_DIR, "geo_allow.txt")
WAF_GEN_PATH = "/opt/loi-waf/loi_waf_gen.py"
WAF_AUDIT_STATE_PATH = os.path.join(WAF_STATE_DIR, "audit_offsets.json")
WAF_BLOCK_FLAG = os.path.join(WAF_DIR, "loi_waf_block")

class LinuxAgent:
    def __init__(self, server_ip=None, agent_name=None):
        self.server_ip = server_ip
        self.agent_name = agent_name
        self.report_ip = ""
        self.port = DEFAULT_PORT
        self._av_proc_cache = set()
        self._av_proc_cache_ts = 0

        # State for CPU calculation
        self.prev_cpu_total = 0
        self.prev_cpu_idle = 0

        # State for Network calculation
        self.prev_net_in = 0
        self.prev_net_out = 0
        self.prev_net_time = time.time()

        # State for Disk I/O + last measured agent->server latency
        self.prev_disk_ticks = None
        self.prev_disk_time = 0.0
        self.last_latency_ms = 0

        # Root login tracking (wtmp)
        self._seen_logins = set()
        self._last_login_poll = 0
        self._pending_login_fails = []
        # Report logins from this far back (widened from 1h so Rocky/minimal
        # hosts, whose agents may restart, still surface 접속 이력).
        self._login_window_secs = 7 * 24 * 3600

        # Warning/error events (journald, syslog fallback) for the detail card.
        self._last_event_poll = 0
        self._seen_events = set()

        # File-watch state (paths pushed by collector ACK)
        self.file_watch_paths = []
        self.file_snapshot = None
        self._watch_cycle = 0

        # Web visitor tracking (nginx/apache access logs, 5-minute window)
        self._weblog_offsets = {}
        self._web_ip_seen = {}

        # WAF (access-log based detection; no blocking on Linux phase 1)
        self.waf_enabled = False
        self.waf_mode = "detect"
        self.waf_mode_requested = "detect"
        self.waf_version = ""
        self.waf_rules = []
        self.waf_rule_count = 0
        self.waf_exceptions = []
        self._waf_rule_mtime = 0
        self._waf_exc_mtime = 0
        self._waf_bot_allow = []
        self._waf_bot_mtime = 0
        self._waf_offsets = self._load_waf_offsets()
        self._audit_offsets = self._load_audit_offsets()
        self._waf_last_alert = {}
        self._waf_modsec_ver = ""
        self._waf_modsec_ver_ts = 0.0
        self._pending_job_results = []
        self._job_result_lock = threading.Lock()
        self._job_exec_lock = threading.Lock()
        self._job_seen = set()

        # File traffic per URL (nginx $body_bytes_sent / apache %b), hourly buckets
        # so totals and peaks survive the 7-day retention without exploding rows.
        self.file_traffic_enabled = False
        self._ft_hours = {}
        self._pending_file_traffic = []

        # Shutdown/reboot command watcher (/proc scan)
        self._seen_shutdown_pids = set()
        self._last_shutdown_push = 0.0
        self._agent_version_cache = None
        self._last_update_attempt = 0.0

        # 송신 급증 감지: 최근 1시간(5초 표본 720개) 중앙값 대비 5배 + 하한 25Mbps 가
        # 30초 지속되면 그 순간의 연결 상대(원격지/프로세스)를 스냅샷으로 남긴다.
        # 서버가 폭증 원인을 스스로 기록하므로, 나중에 "어디로 보냈나"를 확인할 수 있다.
        self._net_out_hist = []
        self._net_spike_hits = 0
        self._last_net_capture = 0.0
        self._pending_net_spikes = []

        # AV detection shells out to systemctl/pidof, which is slow.
        # Cache it - AV state does not change every report cycle.
        self._av_cache = None
        self._av_cache_ts = 0.0
        self._av_cache_ttl = 300.0

        self.ensure_config()
        self.init_baselines()

    def ensure_config(self):
        # 1. Load from file if exists (keep every key so we never drop settings)
        self._config = {}
        if os.path.isfile(CONFIG_FILE):
            try:
                with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                    cfg = json.load(f)
                if isinstance(cfg, dict):
                    self._config = cfg
                    if not self.server_ip and "server_ip" in cfg:
                        self.server_ip = cfg["server_ip"]
                    if not self.agent_name and "agent_name" in cfg:
                        self.agent_name = cfg["agent_name"]
                    if not self.report_ip and "report_ip" in cfg:
                        self.report_ip = cfg["report_ip"]
            except Exception as e:
                print(f"[WARN] Config load error: {e}")

        # 2. Defaults if still empty
        if not self.server_ip:
            default_ip = "monitrack.loict.co.kr"
            if sys.stdin.isatty():
                val = input(f"1. 모니터링 서버 IP 주소 [기본값: {default_ip}]: ").strip()
                self.server_ip = val if val else default_ip
            else:
                self.server_ip = default_ip

        if not self.agent_name:
            default_name = socket.gethostname()
            if sys.stdin.isatty():
                val = input(f"2. 에이전트 이름 (호스트명) [기본값: {default_name}]: ").strip()
                self.agent_name = val if val else default_name
            else:
                self.agent_name = default_name

        # 3. Save config (merge - keeps keys we do not manage, e.g. report_ip)
        self._save_config()

    def _save_config(self):
        """Write agent_config.json, preserving any keys we do not manage."""
        try:
            cfg = getattr(self, "_config", None)
            if not isinstance(cfg, dict):
                cfg = {}
                if os.path.isfile(CONFIG_FILE):
                    try:
                        with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                            cfg = json.load(f) or {}
                    except Exception:
                        cfg = {}
            cfg["server_ip"] = self.server_ip
            cfg["agent_name"] = self.agent_name
            self._config = cfg
            with open(CONFIG_FILE, "w", encoding="utf-8") as f:
                json.dump(cfg, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"[WARN] Config save error: {e}")

    def init_baselines(self):
        # CPU
        total, idle = self.read_cpu_times()
        self.prev_cpu_total = total
        self.prev_cpu_idle = idle

        # Network
        net_in, net_out = self.read_network_bytes()
        self.prev_net_in = net_in
        self.prev_net_out = net_out
        self.prev_net_time = time.time()

        # Disk I/O baseline
        self.prev_disk_ticks = self.read_disk_io_totals()
        self.prev_disk_time = time.time()

    def read_cpu_times(self):
        try:
            with open("/proc/stat", "r") as f:
                for line in f:
                    if line.startswith("cpu "):
                        parts = [float(x) for x in line.strip().split()[1:]]
                        idle = parts[3] + (parts[4] if len(parts) > 4 else 0)
                        total = sum(parts)
                        return total, idle
        except Exception:
            pass
        return 0, 0

    def get_cpu_percent(self):
        total, idle = self.read_cpu_times()
        diff_total = total - self.prev_cpu_total
        diff_idle = idle - self.prev_cpu_idle
        self.prev_cpu_total = total
        self.prev_cpu_idle = idle

        if diff_total <= 0:
            return 0.0
        cpu = (diff_total - diff_idle) / diff_total * 100.0
        return round(max(0.0, min(100.0, cpu)), 1)

    def get_memory_info(self):
        total_kb = 0
        avail_kb = 0
        try:
            with open("/proc/meminfo", "r") as f:
                for line in f:
                    if line.startswith("MemTotal:"):
                        total_kb = int(line.split()[1])
                    elif line.startswith("MemAvailable:"):
                        avail_kb = int(line.split()[1])
            if avail_kb == 0:
                # Fallback for old kernels
                free_kb = 0
                buffers_kb = 0
                cached_kb = 0
                with open("/proc/meminfo", "r") as f:
                    for line in f:
                        if line.startswith("MemFree:"): free_kb = int(line.split()[1])
                        elif line.startswith("Buffers:"): buffers_kb = int(line.split()[1])
                        elif line.startswith("Cached:"): cached_kb = int(line.split()[1])
                avail_kb = free_kb + buffers_kb + cached_kb
        except Exception:
            pass

        total_mb = round(total_kb / 1024.0, 1)
        used_mb = round((total_kb - avail_kb) / 1024.0, 1)
        pct = round((used_mb / total_mb * 100.0), 1) if total_mb > 0 else 0.0
        return total_mb, used_mb, pct

    def get_disk_info(self):
        mounts = set()
        disks = []
        try:
            with open("/proc/mounts", "r") as f:
                for line in f:
                    parts = line.split()
                    dev = parts[0]
                    mp = parts[1]
                    fstype = parts[2]
                    # Filter physical filesystems
                    if dev.startswith("/dev/") and fstype not in ["squashfs", "iso9660"]:
                        mounts.add(mp)
        except Exception:
            mounts.add("/")

        if not mounts:
            mounts.add("/")

        for mp in sorted(mounts):
            try:
                st = os.statvfs(mp)
                total = st.f_blocks * st.f_frsize
                free = st.f_bavail * st.f_frsize
                used = total - free
                if total > 0:
                    total_gb = round(total / (1024**3), 1)
                    used_gb = round(used / (1024**3), 1)
                    free_gb = round(free / (1024**3), 1)
                    pct = round(used / total * 100.0, 1)
                    disks.append({
                        "drive": mp,
                        "total_gb": total_gb,
                        "used_gb": used_gb,
                        "free_gb": free_gb,
                        "percent": pct
                    })
            except Exception:
                pass
        return disks

    def read_network_bytes(self):
        total_in = 0
        total_out = 0
        try:
            with open("/proc/net/dev", "r") as f:
                lines = f.readlines()[2:]
                for line in lines:
                    parts = line.replace(":", " ").split()
                    if len(parts) >= 10:
                        iface = parts[0]
                        if iface != "lo" and not iface.startswith("docker") and not iface.startswith("veth"):
                            rx = int(parts[1])
                            tx = int(parts[9])
                            total_in += rx
                            total_out += tx
        except Exception:
            pass
        return total_in, total_out

    def get_network_rates(self):
        cur_in, cur_out = self.read_network_bytes()
        now = time.time()
        elapsed = now - self.prev_net_time
        if elapsed < 0.5:
            elapsed = 1.0

        in_bps = int(max(0, (cur_in - self.prev_net_in) / elapsed))
        out_bps = int(max(0, (cur_out - self.prev_net_out) / elapsed))

        self.prev_net_in = cur_in
        self.prev_net_out = cur_out
        self.prev_net_time = now
        return in_bps, out_bps

    def get_local_ip(self):
        if self.report_ip:
            return self.report_ip
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect((self.server_ip, self.port))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except Exception:
            return "127.0.0.1"

    def get_machine_id(self):
        for path in ("/etc/machine-id", "/var/lib/dbus/machine-id"):
            try:
                with open(path, "r") as f:
                    mid = f.read().strip().split()[0]
                    if mid:
                        return mid
            except Exception:
                pass
        return ""

    def get_os_info(self):
        try:
            if os.path.isfile("/etc/os-release"):
                with open("/etc/os-release") as f:
                    for line in f:
                        if line.startswith("PRETTY_NAME="):
                            return line.split("=")[1].strip().strip('"')
            return f"Linux {platform.release()}"
        except Exception:
            return "Linux"

    def get_antivirus_info(self):
        """Detect common Linux AV products. State: ON(active) / OFF / 설치됨(unchecked)."""
        candidates = [
            ("ClamAV", ["clamscan", "clamdscan", "freshclam"],
             ["/etc/clamav", "/etc/clamav/clamd.conf"],
             ["clamav-daemon", "clamd", "clamav-freshclam"],
             ["/clamav", "/clamd", "freshclam"]),
            ("Sophos", ["savscan", "savdstatus"],
             ["/opt/sophos-av", "/opt/sophos-av/bin/savdstatus"],
             ["sav-protect", "sophos-av"],
             ["/opt/sophos", "/sophos-av"]),
            ("ESET", ["esets_scan", "esets_eia"],
             ["/opt/eset/esets/sbin/esets_daemon",
              "/opt/eset/efs/sbin/startd",
              "/opt/eset/efs/lib/scand",
              "/opt/eset/efs/lib/netisd",
              "/opt/eset/RemoteAdministrator/Agent/ERAAgent"],
             ["esets_daemon", "esets", "esets-efs", "eset-efs",
              "esets-daemon", "eraagent"],
             ["/opt/eset/"]),
            ("Kaspersky", ["kesl-control"],
             ["/opt/kaspersky/kesl/bin/kesl-control"],
             ["kesl-supervisor", "kesl"],
             ["/opt/kaspersky", "kesl-control", "kesl-supervisor"]),
            ("Comodo", ["cmdscan"],
             ["/opt/COMODO/ccav"],
             ["cmdagent"],
             ["/comodo", "cmdagent"]),
            ("Bitdefender", ["bdsecd", "bdsec", "bdservice-agent", "bdsystemd"],
             ["/opt/bitdefender-security-tools", "/etc/BitDefender",
              "/opt/BitDefender", "/var/opt/BitDefender"],
             ["bdsec", "bdsec-daemon", "bdsec-epagng", "bdsec-update",
              "bdservice-agent", "bdsystemd", "bdsecd"],
             ["/bitdefender", "bitdefender", "bdsec", "bdsystemd"]),
        ]
        products = []
        error = None
        try:
            running = self._running_av_markers()
            for name, binaries, paths, services, procmarks in candidates:
                running_hit = any(m in running for m in procmarks)
                found = any(shutil.which(b) for b in binaries) or \
                        any(os.path.exists(p) for p in paths) or \
                        self._any_service_loaded(services) or \
                        running_hit
                if not found:
                    continue
                active = self._any_service_active(services)
                if running_hit or active is True:
                    state = "ON"
                elif active is False:
                    state = "OFF"
                else:
                    state = "설치됨"
                products.append({"name": name, "state": state})
        except Exception as e:
            error = str(e)
        result = {"installed": len(products) > 0, "products": products}
        if error:
            result["error"] = error
        return result

    _UNIT_DIRS = ("/run/systemd/system", "/etc/systemd/system", "/lib/systemd/system",
                  "/usr/lib/systemd/system", "/etc/systemd/system/multi-user.target.wants")
    _CGROUP_DIRS = ("/sys/fs/cgroup/systemd.slice", "/sys/fs/cgroup/systemd")

    _PROC_MARKERS = ("/opt/eset/", "/bitdefender", "bitdefender", "bdsec", "bdsystemd",
                     "/opt/kaspersky", "kesl-control", "kesl-supervisor",
                     "/opt/sophos", "sophos-av", "sav-protect",
                     "/clamav", "/clamd", "freshclam", "/comodo", "cmdagent")

    def _running_av_markers(self):
        """Lowercase cmdline fragments of AV daemons currently running.

        ESET on Linux ships under /opt/eset/efs with a systemd unit whose name
        varies by packaging, so the unit file alone is not a reliable signal.
        Reading /proc once is cheap and version independent.
        """
        now = time.time()
        if self._av_proc_cache_ts and (now - self._av_proc_cache_ts) < 60:
            return self._av_proc_cache

        hits = set()
        try:
            for pid in os.listdir("/proc"):
                if not pid.isdigit():
                    continue
                try:
                    with open("/proc/" + pid + "/cmdline", "rb") as fh:
                        raw = fh.read().decode("utf-8", "replace")
                except Exception:
                    continue
                if not raw:
                    continue
                low = raw.replace("\x00", " ").lower()
                for m in self._PROC_MARKERS:
                    if m in low:
                        hits.add(m)
        except Exception:
            pass

        self._av_proc_cache = hits
        self._av_proc_cache_ts = now
        return hits

    def get_antivirus_info_cached(self):
        """Cached wrapper around get_antivirus_info (default 5 minute TTL).

        A product that was detected before does not disappear between two
        probes, so an empty result is ignored when we already had one.
        Otherwise the dashboard badge flickers on a transient probe failure.
        """
        now = time.time()
        if self._av_cache is None or (now - self._av_cache_ts) > self._av_cache_ttl:
            try:
                fresh = self.get_antivirus_info()
            except Exception as e:
                fresh = {"installed": False, "products": [], "error": str(e)}
            prev_products = (self._av_cache or {}).get("products") or []
            if fresh.get("products") or not prev_products:
                self._av_cache = fresh
            else:
                print("[WARN] AV probe returned empty, keeping previous result")
            self._av_cache_ts = now
        return self._av_cache

    def _any_service_loaded(self, services):
        """True when the systemd unit exists at all, even if stopped.

        Some AV agents install no binary on PATH and live in a private
        directory, so the unit file is the only reliable signal. The unit
        file check is filesystem-based because `systemctl show` behaves
        inconsistently across systemd versions.
        """
        for svc in services:
            for d in self._UNIT_DIRS:
                if os.path.exists(os.path.join(d, svc + ".service")):
                    return True
        if shutil.which("systemctl") is not None:
            for svc in services:
                try:
                    r = subprocess.run(["systemctl", "is-enabled", svc],
                                       stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=5)
                    out = r.stdout.strip()
                    if out and out not in ("disabled", "not-found", "indirect"):
                        return True
                except Exception:
                    pass
        return False

    def _any_service_active(self, services):
        """True/False/None - True when a unit is running.

        Reads the systemd cgroup tree instead of spawning systemctl/pidof.
        Forks cost ~100-500ms each on D-Bus and were showing up as CPU
        spikes, and their timeouts made the state flap.
        """
        for svc in services:
            for d in self._CGROUP_DIRS:
                try:
                    if svc + ".service" in os.listdir(d):
                        return True
                except Exception:
                    pass
        # cgroup tree not readable - fall back to systemctl, but only once per unit.
        if shutil.which("systemctl") is not None:
            for svc in services:
                try:
                    r = subprocess.run(["systemctl", "is-active", svc],
                                       stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=3)
                    if r.stdout.strip() in ("active", "activating", "reloading"):
                        return True
                except Exception:
                    pass
            return False
        if shutil.which("pidof") is None:
            return None
        for svc in services:
            try:
                r = subprocess.run(["pidof", svc], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=3)
                if r.returncode == 0 and r.stdout.strip():
                    return True
            except Exception:
                pass
        return False

    def read_disk_io_totals(self):
        """Sum read/write ticks + completed I/Os over whole disks (/sys/block)."""
        r_ms = 0
        w_ms = 0
        ios = 0
        try:
            devs = os.listdir("/sys/block")
        except Exception:
            return r_ms, w_ms, ios
        for dev in devs:
            if dev.startswith(("loop", "ram", "fd", "sr", "dm-")):
                continue
            try:
                with open("/sys/block/" + dev + "/stat") as f:
                    fields = f.read().split()
                # 0:reads_completed 3:ms_reading 4:writes_completed 7:ms_writing
                r_ms += int(fields[3])
                w_ms += int(fields[7])
                ios += int(fields[0]) + int(fields[4])
            except Exception:
                pass
        return r_ms, w_ms, ios

    def get_disk_io_stats(self):
        cur = self.read_disk_io_totals()
        now = time.time()
        if self.prev_disk_ticks is None:
            self.prev_disk_ticks = cur
            self.prev_disk_time = now
            return 0.0, 0.0
        elapsed_ms = max(1.0, (now - self.prev_disk_time) * 1000.0)
        dr = max(0, cur[0] - self.prev_disk_ticks[0])
        dw = max(0, cur[1] - self.prev_disk_ticks[1])
        d_ios = max(0, cur[2] - self.prev_disk_ticks[2])
        util = round(min(100.0, (dr + dw) / elapsed_ms * 100.0), 1)
        await_ms = round((dr + dw) / d_ios, 1) if d_ios > 0 else 0.0
        self.prev_disk_ticks = cur
        self.prev_disk_time = now
        return util, await_ms

    _MONTHS = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04",
               "May": "05", "Jun": "06", "Jul": "07", "Aug": "08",
               "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"}

    def _fmt_last_time(self, s):
        try:
            p = s.split()  # [Mon, Sep, 01, 10:00:00, 2025]
            return "%s-%s-%s %s" % (p[4], self._MONTHS[p[1]], p[2].zfill(2), p[3])
        except Exception:
            return s

    def get_admin_logins(self):
        """Root access: direct logins (wtmp) + su/sudo escalation (auth log)."""
        logins = []
        try:
            if time.time() - self._last_login_poll < 30:
                return logins, []
            self._last_login_poll = time.time()
            all_logins = self._all_last_logins()
            root_direct = [e for e in all_logins if e["user"] == "root"]
            admin_logins = root_direct + self._root_auth_logins()
            return admin_logins[:20], all_logins[:50]
        except Exception:
            pass
        return [], []

    def _root_last_logins(self):
        return [e for e in self._all_last_logins() if e["user"] == "root"][:20]

    # /var/log/wtmp record layout (glibc utmp, 384 bytes). These offsets are the
    # same on 32- and 64-bit Linux, so login history does not depend on the
    # external `last` tool (which can be unavailable or blocked for a systemd
    # service via a minimal PATH or SELinux - seen on Rocky 8).
    _WTMP_REC = 384
    _UT_USER_PROCESS = 7

    def _wtmp_logins(self):
        """Direct /var/log/wtmp parse -> [(user, tty, host, epoch), ...] (oldest first)."""
        rows = []
        for path in ("/var/log/wtmp", "/var/run/utmp"):
            try:
                if not os.path.isfile(path):
                    continue
                with open(path, "rb") as f:
                    data = f.read()
            except Exception as e:
                print("[WARN] wtmp read failed (%s): %s" % (path, e))
                continue
            rec = self._WTMP_REC
            if len(data) < rec:
                continue
            for off in range(0, len(data) - rec + 1, rec):
                try:
                    if struct.unpack_from("<h", data, off)[0] != self._UT_USER_PROCESS:
                        continue
                    user = data[off + 44:off + 76].split(b"\x00", 1)[0].decode("utf-8", "ignore").strip()
                    if not user:
                        continue
                    line = data[off + 8:off + 40].split(b"\x00", 1)[0].decode("utf-8", "ignore").strip() or "-"
                    host = data[off + 76:off + 332].split(b"\x00", 1)[0].decode("utf-8", "ignore").strip() or "-"
                    sec = struct.unpack_from("<i", data, off + 340)[0]
                except Exception:
                    continue
                if sec <= 0:
                    continue
                rows.append((user, line, host, sec))
            if rows:
                break
        return rows

    def _last_cmd_logins(self):
        """Fallback: parse `last -F -w` output -> [(user, tty, host, epoch), ...]."""
        rows = []
        try:
            r = subprocess.run(["last", "-F", "-w"],
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=10)
            if r.returncode != 0:
                print("[WARN] `last` exited %s: %s" % (r.returncode, (r.stderr or "").strip()[:200]))
                return rows
            for line in r.stdout.splitlines():
                parts = line.split()
                if len(parts) < 7:
                    continue
                username = parts[0]
                if username in ("reboot", "shutdown", "wtmp", ""):
                    continue
                # user pts/0 203.0.113.5 Mon Sep 01 10:00:00 2025 ...
                # user tty1 Mon Sep 01 10:00:00 2025 ... / user :0 ... (no host)
                if parts[1].startswith("tty") or parts[1].startswith(":"):
                    tty, host, tstart = parts[1], "-", 2
                else:
                    if len(parts) < 8:
                        continue
                    tty, host, tstart = parts[1], parts[2], 3
                login_raw = " ".join(parts[tstart:tstart + 5])
                if len(login_raw.split()) < 5:
                    continue
                try:
                    epoch = int(time.mktime(time.strptime(self._fmt_last_time(login_raw), "%Y-%m-%d %H:%M:%S")))
                except Exception:
                    epoch = 0
                rows.append((username, tty, host, epoch))
        except Exception as e:
            print("[WARN] `last` fallback failed: %s" % e)
        return rows

    def _all_last_logins(self):
        """Recent interactive logons for ALL users. wtmp is parsed directly first
        (no external tool needed); `last` output is used only as a fallback."""
        logins = []
        try:
            now = time.time()
            rows = self._wtmp_logins()
            if not rows:
                rows = self._last_cmd_logins()
            for (username, tty, host, epoch) in reversed(rows):  # newest first
                tty = tty or "-"
                host = host or "-"
                key = (username, tty, host, epoch)
                if key in self._seen_logins:
                    continue
                self._seen_logins.add(key)
                if not epoch:
                    # Unknown login time -> report once, no age filtering.
                    logins.append({"user": username, "logon_type": tty, "ip": host,
                                   "time": time.strftime("%Y-%m-%d %H:%M:%S")})
                elif now - epoch <= self._login_window_secs:
                    logins.append({"user": username, "logon_type": tty, "ip": host,
                                   "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(epoch))})
                if len(logins) >= 50:
                    break
            while len(self._seen_logins) > 2000:
                self._seen_logins.pop()
            return logins
        except Exception as e:
            print("[WARN] login history failed: %s" % e)
        return logins

    def _fmt_syslog_time(self, line):
        # "Sep 19 10:00:01 host ..." (no year) -> "YYYY-MM-DD HH:MM:SS"
        try:
            p = line.split()
            year = time.strftime("%Y")
            timestr = "%s-%s-%s %s" % (year, self._MONTHS[p[0]], p[1].zfill(2), p[2])
            if time.mktime(time.strptime(timestr, "%Y-%m-%d %H:%M:%S")) > time.time() + 86400:
                timestr = "%d-%s-%s %s" % (int(year) - 1, self._MONTHS[p[0]], p[1].zfill(2), p[2])
            return timestr
        except Exception:
            return time.strftime("%Y-%m-%d %H:%M:%S")

    def _parse_auth_line(self, line):
        # su to root: "su[123]: pam_unix(su:session): session opened for user root by admin(uid=1000)"
        m = re.search(r"pam_unix\(su:session\): session opened for user root by (\S+)", line)
        if m:
            by = m.group(1).split("(")[0]
            return {"user": "root", "logon_type": "su(" + by + ")",
                    "ip": "-", "time": self._fmt_syslog_time(line)}
        # sudo to root shell: "sudo: admin : TTY=pts/0 ; ... COMMAND=/bin/bash"
        m = re.search(r"sudo:\s+(\S+)\s*:.*COMMAND=(/bin/(?:ba)?sh|/usr/bin/su|/bin/su)\b", line)
        if m:
            return {"user": "root", "logon_type": "sudo(" + m.group(1) + ")",
                    "ip": "-", "time": self._fmt_syslog_time(line)}
        return None

    def _root_auth_logins(self):
        """su/sudo escalation from auth log. Offset-tracked: first sight starts at EOF."""
        logins = []
        if not hasattr(self, "_auth_offsets"):
            self._auth_offsets = {}
        for path in ("/var/log/auth.log", "/var/log/secure"):
            if not os.path.isfile(path):
                continue
            try:
                st = os.stat(path)
                key = (st.st_dev, st.st_ino)
                prev = self._auth_offsets.get(path)
                if prev is None or prev.get("key") != key:
                    # First sight or rotated: start at end to avoid history flood.
                    self._auth_offsets[path] = {"key": key, "pos": st.st_size}
                    continue
                pos = prev.get("pos", 0)
                if st.st_size < pos:
                    pos = 0
                if st.st_size == pos:
                    continue
                with open(path, "r", errors="ignore") as f:
                    f.seek(pos)
                    lines = f.readlines()
                    pos = f.tell()
                self._auth_offsets[path] = {"key": key, "pos": pos}
                fails = {}
                for line in lines[-500:]:
                    entry = self._parse_auth_line(line)
                    if entry:
                        logins.append(entry)
                    if len(logins) >= 20:
                        break
                    # SSH brute force: "Failed password for root/admin from 1.2.3.4"
                    m = re.search(r"Failed \S+ for (invalid user )?(\S+) from (\S+)", line)
                    if m:
                        user = m.group(2)
                        ip = m.group(3)
                        k = (user, ip)
                        fails[k] = fails.get(k, 0) + 1
                for (user, ip), cnt in fails.items():
                    if cnt >= 5 and len(self._pending_login_fails) < 20:
                        self._pending_login_fails.append(
                            {"user": user, "ip": ip, "count": cnt, "source": "SSH"})
            except Exception:
                pass
        return logins

    def check_file_changes(self):
        """Poll watched folders every 6th cycle (~30s). First run only seeds baseline."""
        changes = []
        try:
            self._watch_cycle += 1
            if self._watch_cycle % 6 != 0 and self.file_snapshot is not None:
                return changes
            snap = {}
            for root_path in self.file_watch_paths:
                if not root_path or not os.path.isdir(root_path):
                    continue
                for dirpath, dirnames, filenames in os.walk(root_path, followlinks=False):
                    for fn in filenames:
                        fp = os.path.join(dirpath, fn)
                        try:
                            st = os.stat(fp)
                            snap[fp] = (st.st_mtime, st.st_size)
                        except Exception:
                            pass
                        if len(snap) >= 20000:
                            break
                    if len(snap) >= 20000:
                        break
            if self.file_snapshot is None:
                self.file_snapshot = snap
                return changes
            now_str = time.strftime("%Y-%m-%d %H:%M:%S")
            for fp, meta in snap.items():
                if fp not in self.file_snapshot:
                    changes.append({"path": fp, "change": "생성", "time": now_str})
                elif meta != self.file_snapshot[fp]:
                    changes.append({"path": fp, "change": "수정", "time": now_str})
                if len(changes) >= 50:
                    break
            for fp in self.file_snapshot:
                if fp not in snap:
                    changes.append({"path": fp, "change": "삭제", "time": now_str})
                if len(changes) >= 50:
                    break
            self.file_snapshot = snap
        except Exception:
            pass
        return changes[:50]

    # journald syslog priorities: 3=err 4=warning (0-2 are more severe than err).
    _PRIO_CRITICAL = ("0", "1", "2", "3")

    def _events_from_journal(self, since):
        """Warning/error entries from journald. Returns [] when unavailable."""
        if shutil.which("journalctl") is None:
            return []
        try:
            proc = subprocess.run(
                ["journalctl", "-p", "warning", "--since", since, "--no-pager", "-n", "200", "-o", "json"],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=8)
            if proc.returncode != 0 or not proc.stdout:
                return []
        except Exception:
            return []

        out = []
        for line in proc.stdout.splitlines():
            if '"MESSAGE"' not in line:
                continue
            m_prio = re.search(r'"PRIORITY":"(\d+)"', line)
            m_ts = re.search(r'"__REALTIME_TIMESTAMP":"(\d+)"', line)
            m_msg = re.search(r'"MESSAGE":"((?:[^"\\]|\\.)*)"', line)
            if not m_msg:
                continue
            prio = m_prio.group(1) if m_prio else "3"
            ts = int(m_ts.group(1)) / 1000000.0 if m_ts else time.time()

            ident = ""
            for field in ("SYSLOG_IDENTIFIER", "_SYSTEMD_UNIT", "_COMM"):
                mi = re.search(r'"%s":"((?:[^"\\]|\\.)*)"' % field, line)
                if mi and mi.group(1):
                    ident = mi.group(1)
                    break

            try:
                message = json.loads('"' + m_msg.group(1) + '"')
            except Exception:
                message = m_msg.group(1)
            message = " ".join(str(message).split())
            if not message:
                continue

            out.append({
                "log": "journal",
                "source": (ident or "system")[:200],
                "event_id": int(prio) if prio.isdigit() else 3,
                "level": "위험" if prio in self._PRIO_CRITICAL else "경고",
                "message": message[:500],
                "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)),
                "_ts": ts
            })
        return out

    _SYSLOG_RE = re.compile(
        r"^(\w{3}\s+\d+\s+\d+:\d+:\d+)\s+(\S+)\s+([\w\-\.\/]+)(?:\[(\d+)\])?:\s*(.*)$")

    def _events_from_syslog(self, since):
        """Fallback for hosts without journald: tail the classic syslog files."""
        out = []
        year = time.localtime().tm_year
        for path in ("/var/log/syslog", "/var/log/messages"):
            if not os.path.isfile(path):
                continue
            try:
                with open(path, "r", errors="ignore") as f:
                    lines = f.readlines()[-400:]
            except Exception:
                continue
            for line in lines:
                line = line.rstrip("\n")
                m = self._SYSLOG_RE.match(line)
                if not m:
                    continue
                stamp, host, prog, pid, msg = m.groups()
                try:
                    lt = time.strptime(stamp, "%b %d %H:%M:%S")
                except Exception:
                    continue
                # Classic syslog stamps carry no year; strptime defaults to 1900,
                # which would push every entry behind the cutoff. Use the current one.
                ts = time.mktime((year, lt[1], lt[2], lt[3], lt[4], lt[5], 0, 0, -1))
                if ts < since:
                    continue
                low = msg.lower()
                if prog in ("kernel",):
                    # Kernel only reaches warning level for real faults.
                    if not re.search(r"error|fail|panic|oom|segfault|call trace", low):
                        continue
                level = "위험" if re.search(r"error|fail|panic|critical|crit|fatal|segfault", low) else "경고"
                out.append({
                    "log": "syslog",
                    "source": prog[:200],
                    "event_id": int(pid) if pid else 0,
                    "level": level,
                    "message": " ".join(msg.split())[:500],
                    "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)),
                    "_ts": ts
                })
            break
        return out

    def get_event_logs(self):
        """Recent warning/error entries, deduped across overlapping poll windows."""
        events = []
        try:
            now = time.time()
            if self._last_event_poll and (now - self._last_event_poll) < 30:
                return events
            # Overlap the window so nothing slips through between polls; dedup below absorbs the repeats.
            since_ts = now - 45
            self._last_event_poll = now

            collected = self._events_from_journal("-45s")
            if not collected:
                collected = self._events_from_syslog(since_ts)

            for e in collected:
                key = (round(e["_ts"]), e["source"], e["message"][:120])
                if key in self._seen_events:
                    continue
                self._seen_events.add(key)
                e.pop("_ts", None)
                events.append(e)
                if len(events) >= 20:
                    break
            while len(self._seen_events) > 1000:
                self._seen_events.pop()
        except Exception:
            pass
        return events

    WEB_LOG_GLOBS = ("/var/log/nginx/*access*.log",
                       "/var/log/apache2/*access*.log",
                       "/var/log/httpd/*access*log*")

    def get_web_visitors(self):
        """Unique visitor IPs in the trailing 5 minutes (access logs)."""
        hits = 0
        try:
            cutoff = time.time() - 300
            for pattern in self.WEB_LOG_GLOBS:
                for path in glob.glob(pattern):
                    hits += self._scan_web_log(path, cutoff)
            for ip in [k for k, v in self._web_ip_seen.items() if v < cutoff]:
                del self._web_ip_seen[ip]
            return len(self._web_ip_seen), hits
        except Exception:
            return 0, 0

    def _parse_web_line(self, line):
        """Return (unix_ts, url, response_bytes) or None.

        Handles nginx and apache combined/common formats, which both put the
        served byte count right after the status code: nginx $body_bytes_sent,
        apache %b ("-" when zero).
        """
        p2 = line.find("[")
        p3 = line.find("]")
        if p2 < 0 or p3 < 0:
            return None
        try:
            ts = time.mktime(time.strptime(line[p2 + 1:p3].rsplit(" ", 1)[0], "%d/%b/%Y:%H:%M:%S"))
        except Exception:
            return None

        # Request: "GET /path?query HTTP/1.1" - url is the token after the method.
        q1 = line.find('"')
        q2 = line.find('"', q1 + 1) if q1 >= 0 else -1
        if q1 < 0 or q2 < 0:
            return None
        req = line[q1 + 1:q2].split(" ")
        if len(req) < 2:
            return None
        url = req[1]

        tail = line[q2 + 1:].split()
        if len(tail) < 2:
            return None
        sent = 0
        try:
            sent = int(tail[1])
        except ValueError:
            # Apache writes "-" for a zero-length response.
            sent = 0
        if sent < 0:
            sent = 0
        return ts, url.split("?")[0], sent

    def add_file_traffic(self, ts, url, sent):
        """Attribute served bytes to a URL, bucketed by hour with a 5-minute peak."""
        if not self.file_traffic_enabled or sent <= 0 or not url:
            return
        if len(url) > 300:
            url = url[:300]
        local = time.localtime(ts)
        hour = time.strftime("%Y-%m-%d %H:00:00", local)
        win = "%04d-%02d-%02d %02d:%02d:00" % (
            local.tm_year, local.tm_mon, local.tm_mday,
            local.tm_hour, (local.tm_min // 5) * 5)

        bucket = self._ft_hours.setdefault(hour, {})
        agg = bucket.get(url)
        if agg is None:
            agg = {"bytes": 0, "hits": 0, "window_bytes": 0,
                   "window_start": None, "peak_bps": 0,
                   "sent_bytes": 0, "sent_hits": 0}
            bucket[url] = agg
        if agg["window_start"] != win:
            if agg["window_start"] is not None and agg["window_bytes"] > 0:
                bps = agg["window_bytes"] * 8 // 300
                if bps > agg["peak_bps"]:
                    agg["peak_bps"] = bps
            agg["window_start"] = win
            agg["window_bytes"] = 0
        agg["window_bytes"] += sent
        agg["bytes"] += sent
        agg["hits"] += 1

    def flush_file_traffic(self):
        """Queue the bytes accrued since the last report.

        The collector accumulates on (host, hour, url), so only the delta is sent.
        That keeps the dashboard live within a few seconds instead of waiting for
        the hour to roll over, while the hourly bucket still bounds row growth.
        """
        if not self.file_traffic_enabled:
            self._ft_hours = {}
            return
        now_hour = time.strftime("%Y-%m-%d %H:00:00", time.localtime())

        for hour in list(self._ft_hours.keys()):
            bucket = self._ft_hours[hour]
            for agg in bucket.values():
                if agg["window_bytes"] > 0:
                    bps = agg["window_bytes"] * 8 // 300
                    if bps > agg["peak_bps"]:
                        agg["peak_bps"] = bps

            # Biggest movers first so the 120-item queue spends its budget well.
            for url, agg in sorted(bucket.items(), key=lambda kv: kv[1]["bytes"], reverse=True)[:40]:
                d_bytes = agg["bytes"] - agg["sent_bytes"]
                d_hits = agg["hits"] - agg["sent_hits"]
                if d_bytes <= 0 and d_hits <= 0:
                    continue
                agg["sent_bytes"] = agg["bytes"]
                agg["sent_hits"] = agg["hits"]
                self._pending_file_traffic.append({
                    "hour": hour,
                    "url": url,
                    "bytes": d_bytes,
                    "hits": d_hits,
                    "peak_bps": agg["peak_bps"]
                })

            # Once the hour is over the collector holds the full total; drop it here.
            if hour < now_hour:
                del self._ft_hours[hour]

        while len(self._pending_file_traffic) > 120:
            self._pending_file_traffic.pop(0)

    def _scan_web_log(self, path, cutoff):
        hits = 0
        try:
            st = os.stat(path)
            key = (st.st_dev, st.st_ino)
            prev = self._weblog_offsets.get(path)
            if prev is None or prev.get("key") != key:
                # First sight or rotated: start at end (ramps up within minutes).
                self._weblog_offsets[path] = {"key": key, "pos": st.st_size}
                return 0
            pos = prev.get("pos", 0)
            if st.st_size < pos:
                pos = 0
            if st.st_size == pos:
                return 0
            with open(path, "r", errors="ignore") as f:
                f.seek(pos)
                lines = f.readlines()
                self._weblog_offsets[path] = {"key": key, "pos": f.tell()}
            # 203.0.113.5 - - [19/Sep/2026:16:30:00 +0900] "GET / ..." (local tz assumed)
            for line in lines[-5000:]:
                parsed = self._parse_web_line(line)
                if parsed is None:
                    continue
                ts, url, sent = parsed
                # Book bytes before the visitor cutoff so a cold start still counts them.
                if sent > 0 and url:
                    self.add_file_traffic(ts, url, sent)
                if ts < cutoff:
                    continue
                hits += 1
                ip = line.split(" ")[0]
                if ip != "-":
                    self._web_ip_seen[ip] = ts
        except Exception:
            pass
        return hits

    def _file_md5(self, path):
        try:
            h = hashlib.md5()
            with open(path, "rb") as f:
                for chunk in iter(lambda: f.read(65536), b""):
                    h.update(chunk)
            return h.hexdigest()
        except Exception:
            return ""

    # ---- 에이전트 버전 (파일 작성시각 + MD5). 웹이 배포본과 비교해 구버전을 판별한다.
    def get_agent_version(self):
        if self._agent_version_cache:
            return self._agent_version_cache
        try:
            path = os.path.abspath(__file__)
            st = os.stat(path)
            self._agent_version_cache = "%s|%s" % (
                time.strftime("%Y-%m-%d %H:%M", time.localtime(st.st_mtime)), self._file_md5(path))
        except Exception:
            self._agent_version_cache = "unknown"
        return self._agent_version_cache

    # ---- 자동 업데이트: 서버 ACK 의 agent_update 지시에 따라 새 .py 를 받아 스스로 교체한다.
    def try_self_update(self, url, expected_md5):
        if not url or not expected_md5:
            return
        if time.time() - self._last_update_attempt < 600:
            return  # 실패 후 10분 쿨다운
        self._last_update_attempt = time.time()
        try:
            install = os.path.abspath(__file__)
            cur = self._file_md5(install)
            if cur and cur.lower() == expected_md5.lower():
                return  # 이미 최신
            print("[INFO] Auto-update starting: %s" % url)
            new_path = install + ".new"
            req = urllib.request.Request(url, headers={"User-Agent": "LoiAgentUpdater/1.0"})
            with urllib.request.urlopen(req, timeout=30) as resp, open(new_path, "wb") as f:
                f.write(resp.read())
            got = self._file_md5(new_path)
            if not got or got.lower() != expected_md5.lower():
                print("[WARN] Auto-update aborted: hash mismatch got=%s" % got)
                try:
                    os.remove(new_path)
                except Exception:
                    pass
                return
            # 분리 실행되는 스크립트가 서비스를 재시작하며 교체한다. 실패 시 .bak 으로 롤백.
            script = "/tmp/loi_agent_update.sh"
            sh = """#!/bin/bash
sleep 1
INSTALL="{install}"
NEW="{new}"
BAK="${{INSTALL}}.bak"
cp -f "$INSTALL" "$BAK" 2>/dev/null || true
cp -f "$NEW" "$INSTALL"
chmod +x "$INSTALL"
systemctl restart loi-agent || true
sleep 3
if ! systemctl is-active --quiet loi-agent; then
  cp -f "$BAK" "$INSTALL" 2>/dev/null || true
  systemctl restart loi-agent || true
fi
rm -f "$NEW" "$0"
""".format(install=install, new=new_path)
            with open(script, "w") as f:
                f.write(sh)
            os.chmod(script, 0o755)
            subprocess.Popen(["/bin/bash", script], start_new_session=True,
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            print("[INFO] Auto-update script launched. Service will restart with the new build.")
        except Exception as e:
            print("[WARN] Auto-update failed: %s" % e)

    # ---- 종료/재부팅 명령 감시 ----
    def _match_shutdown(self, comm, args):
        # shutdown/reboot/halt/poweroff 는 실행 자체가 곧 종료 시도
        if comm in ("shutdown", "reboot", "halt", "poweroff"):
            return comm
        # init/systemctl 은 첫 번째 비옵션 인자(런레벨/서브명령)만 본다 (오탐 방지)
        first = None
        for a in args:
            if a.startswith("-"):
                continue
            first = a
            break
        if comm == "init" and first in ("0", "6"):
            return "init " + first
        if comm == "systemctl" and first in ("reboot", "poweroff"):
            return "systemctl " + first
        return None

    def _scan_shutdown(self):
        hits = []
        try:
            pids = [p for p in os.listdir("/proc") if p.isdigit()]
        except Exception:
            return hits
        for pid in pids:
            if pid in self._seen_shutdown_pids:
                continue
            try:
                with open("/proc/%s/comm" % pid, "r") as f:
                    comm = f.read().strip()
            except Exception:
                continue
            if comm not in SHUTDOWN_COMMS:
                continue
            try:
                with open("/proc/%s/cmdline" % pid, "rb") as f:
                    raw = f.read().decode("utf-8", "replace")
                argv = [a for a in raw.split("\x00") if a]
            except Exception:
                argv = []
            cmd = self._match_shutdown(comm, argv[1:])
            if cmd:
                self._seen_shutdown_pids.add(pid)
                hits.append((cmd, pid, " ".join(argv) if argv else comm))
        if len(self._seen_shutdown_pids) > 500:
            self._seen_shutdown_pids.clear()
        return hits

    def send_shutdown_push(self, cmd, pid, cmdline):
        # 짧은 시간 내 중복 푸시 방지 (shutdown 이 내부에서 reboot 을 다시 호출하는 등)
        if time.time() - self._last_shutdown_push < 5:
            return
        self._last_shutdown_push = time.time()
        now = time.strftime("%Y-%m-%d %H:%M:%S")
        try:
            user = ""
            try:
                user = os.environ.get("USER", "") or ""
            except Exception:
                pass
            msg = "명령: %s (pid %s)" % (cmd, pid)
            if cmdline:
                msg += " / " + cmdline[:180]
            payload = {
                "host_name": self.agent_name,
                "ip": self.get_local_ip(),
                "machine_id": self.get_machine_id(),
                "token": AGENT_TOKEN,
                "event_type": "shutdown_push",
                "id": 0,
                "source": "Linux/" + cmd,
                "time": now,
                "message": msg,
            }
            data = json.dumps(payload) + "\n"
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(5.0)
                s.connect((self.server_ip, self.port))
                s.sendall(data.encode("utf-8"))
                try:
                    s.recv(4096)
                except Exception:
                    pass
            print("[%s] [INFO] Shutdown push sent: %s" % (time.strftime("%H:%M:%S"), cmd))
        except Exception as e:
            print("[%s] [WARN] Shutdown push failed: %s" % (time.strftime("%H:%M:%S"), e))

    def _shutdown_watch_loop(self):
        while True:
            try:
                for cmd, pid, cmdline in self._scan_shutdown():
                    self.send_shutdown_push(cmd, pid, cmdline)
            except Exception:
                pass
            time.sleep(0.5)

    # journald 감시: /proc 스캔이 놓치기 쉬운 짧은 명령(reboot, systemctl reboot 등)과
    # sudo 로그(COMMAND=.../reboot) 및 systemd 종료 메시지를 잡는다.
    JOURNAL_PATTERNS = (
        "reached target shutdown", "reached target reboot", "reached target power-off",
        "system is rebooting", "system is powering off", "system is going down",
        "the system will reboot now", "the system will power off now",
        "systemd-shutdown", "shutting down.",
    )

    def _journal_watch_loop(self):
        cmd_re = re.compile(r"COMMAND=(?:/usr)?/s?bin/(reboot|shutdown|halt|poweroff|init)\b")
        while True:
            try:
                proc = subprocess.Popen(["journalctl", "-f", "-n", "0", "-o", "cat"],
                                        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
                                        universal_newlines=True, bufsize=1)
                for line in proc.stdout:
                    s = line.strip()
                    if not s:
                        continue
                    m = cmd_re.search(s)
                    if m:
                        self.send_shutdown_push("sudo " + m.group(1), 0, s[:180])
                        continue
                    low = s.lower()
                    for pat in self.JOURNAL_PATTERNS:
                        if pat in low:
                            self.send_shutdown_push("systemd", 0, s[:180])
                            break
            except Exception:
                pass
            time.sleep(5)

    # ---- systemd ExecStop 기반 종료 감지 ----
    # systemd 는 종료 시 서비스를 이른 단계에 중지시킨다. 그래서 실행 중 감시만으로는
    # 종료 직전에 푸시를 못 보낼 수 있다. ExecStop 으로 서비스가 멈추는 순간(네트워크가
    # 아직 살아있을 때) 직접 푸시를 보낸다. 수동 재시작/정지 때는 오탐을 내지 않는다.
    def notify_shutdown_once(self):
        state = ""
        try:
            r = subprocess.run(["systemctl", "is-system-running"],
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=5)
            state = (r.stdout or "").strip()
        except Exception:
            pass
        print("[INFO] ExecStop notify: system state = '%s'" % state)
        if state == "stopping":
            self.send_shutdown_push("systemd", 0, "시스템 종료/재부팅 진행 (ExecStop)")

    def ensure_shutdown_notifier_dropin(self):
        # systemd 드롭인을 (없으면) 설치해 종료 시 ExecStop 이 푸시를 보내게 한다.
        try:
            if os.geteuid() != 0:
                return
            me = os.path.abspath(__file__)
            d = "/etc/systemd/system/loi-agent.service.d"
            f = os.path.join(d, "notify-shutdown.conf")
            content = ("[Service]\n"
                       "ExecStop=/usr/bin/env python3 %s -notify-shutdown\n" % me)
            old = ""
            try:
                with open(f) as fh:
                    old = fh.read()
            except Exception:
                old = ""
            if old.strip() != content.strip():
                os.makedirs(d, exist_ok=True)
                with open(f, "w") as fh:
                    fh.write(content)
                subprocess.call(["systemctl", "daemon-reload"])
                print("[INFO] Shutdown notifier drop-in installed: %s" % f)
        except Exception as e:
            print("[WARN] Shutdown notifier drop-in failed: %s" % e)

    def _hex_ip(self, h, v6=False):
        """ /proc/net/* 의 16진 주소 → 사람이 읽는 IP """
        try:
            if v6:
                raw = b"".join(struct.pack("<I", int(h[i:i+8], 16)) for i in range(0, 32, 8))
                return socket.inet_ntop(socket.AF_INET6, raw)
            return socket.inet_ntoa(struct.pack("<I", int(h, 16)))
        except Exception:
            return h

    def _socket_pid_map(self):
        """ socket inode → pid (root 권한이면 동작) """
        m = {}
        try:
            for pid in os.listdir("/proc"):
                if not pid.isdigit():
                    continue
                d = "/proc/%s/fd" % pid
                try:
                    for fd in os.listdir(d):
                        try:
                            link = os.readlink(os.path.join(d, fd))
                        except Exception:
                            continue
                        if link.startswith("socket:["):
                            m[link[8:-1]] = pid
                except Exception:
                    continue
        except Exception:
            pass
        return m

    def collect_ports(self, limit=300):
        """ 수신 대기 TCP + UDP 포트와 그 점유 프로세스 """
        out = []
        try:
            sock_pid = self._socket_pid_map()
            for path, proto, v6 in (("/proc/net/tcp", "TCP", False), ("/proc/net/tcp6", "TCP", True),
                                    ("/proc/net/udp", "UDP", False), ("/proc/net/udp6", "UDP", True)):
                try:
                    with open(path, "r") as f:
                        lines = f.readlines()[1:]
                except Exception:
                    continue
                for ln in lines:
                    p = ln.split()
                    if len(p) < 10:
                        continue
                    la, st, inode = p[1], p[3], p[9]
                    if proto == "TCP" and st != "0A":
                        continue                      # LISTEN 만
                    try:
                        ip_h, port_h = la.rsplit(":", 1)
                        lport = int(port_h, 16)
                    except Exception:
                        continue
                    if lport <= 0:
                        continue
                    try:
                        pid = int(sock_pid.get(inode, 0))
                    except Exception:
                        pid = 0
                    name = ""
                    if pid > 0:
                        try:
                            with open("/proc/%d/comm" % pid, "r") as cf:
                                name = cf.read().strip()
                        except Exception:
                            name = ""
                    out.append({
                        "proto": proto,
                        "local_addr": self._hex_ip(ip_h, v6),
                        "local_port": lport,
                        "state": "LISTEN" if proto == "TCP" else "UDP",
                        "pid": pid,
                        "proc": name,
                    })
                    if len(out) >= limit:
                        return out
        except Exception:
            pass
        return out

    _proc_cpu_last = {}
    _proc_cpu_last_at = 0.0

    # ---- 송신 급증 감지 + 원격지 스냅샷 ----
    def _is_local_ip(self, ip):
        return (not ip) or ip.startswith("127.") or ip.startswith("0.") \
            or ip in ("::1", "::") or ip.startswith("fe80:")

    def collect_outbound_peers(self, limit=12):
        """ ESTABLISHED TCP 연결의 원격지 + 점유 프로세스 (ss -tnp 와 같은 정보) """
        out = []
        try:
            sock_pid = self._socket_pid_map()
            agg = {}
            for path, proto, v6 in (("/proc/net/tcp", "TCP", False), ("/proc/net/tcp6", "TCP", True)):
                try:
                    with open(path, "r") as f:
                        lines = f.readlines()[1:]
                except Exception:
                    continue
                for ln in lines:
                    p = ln.split()
                    if len(p) < 10:
                        continue
                    if p[3] != "01":          # 01 = ESTABLISHED
                        continue
                    try:
                        ra, rp = p[2].rsplit(":", 1)
                        rip = self._hex_ip(ra, v6)
                        rport = int(rp, 16)
                    except Exception:
                        continue
                    if rport <= 0 or self._is_local_ip(rip):
                        continue
                    pid = 0
                    try:
                        pid = int(sock_pid.get(p[9], 0))
                    except Exception:
                        pid = 0
                    name = ""
                    if pid > 0:
                        try:
                            with open("/proc/%d/comm" % pid, "r") as cf:
                                name = cf.read().strip()
                        except Exception:
                            name = ""
                    key = (rip, rport, name, proto)
                    agg[key] = agg.get(key, 0) + 1
            peers = [{"proto": k[3], "ip": k[0], "port": k[1], "proc": k[2],
                      "state": "ESTABLISHED", "conns": n} for k, n in agg.items()]
            peers.sort(key=lambda x: x["conns"], reverse=True)
            out = peers[:limit]
        except Exception:
            pass
        return out

    def maybe_capture_net_spike(self, out_bps):
        """ 송신이 평소(최근 1시간 중앙값)의 5배 + 25Mbps 를 30초 넘게 유지하면 1회 캡처 """
        try:
            mbps = out_bps / 1000000.0
            self._net_out_hist.append(mbps)
            if len(self._net_out_hist) > 720:
                del self._net_out_hist[0:len(self._net_out_hist) - 720]
            base = 0.0
            if len(self._net_out_hist) >= 60:
                s = sorted(self._net_out_hist)
                base = s[len(s) // 2]
            threshold = max(25.0, base * 5.0)
            if mbps >= threshold:
                self._net_spike_hits += 1
            else:
                self._net_spike_hits = 0
            if self._net_spike_hits < 6:            # 5초 × 6 = 30초 지속
                return
            if time.time() - self._last_net_capture < 600:   # 10분에 1회
                return
            self._last_net_capture = time.time()
            peers = self.collect_outbound_peers(12)
            self._pending_net_spikes.append({
                "ts": int(time.time()),
                "out_mbps": round(mbps, 1),
                "avg_mbps": round(base, 1),
                "peers": peers,
            })
            if len(self._pending_net_spikes) > 5:
                del self._pending_net_spikes[0:len(self._pending_net_spikes) - 5]
            print("[INFO] Net spike captured: %.1f Mbps (baseline %.1f), %d peer(s)"
                  % (mbps, base, len(peers)))
        except Exception as e:
            print("[WARN] net spike capture failed: %s" % e)

    def collect_top_processes(self, top=10):
        """ CPU/메모리 상위 프로세스 (CPU 는 이전 표본과의 델타) """
        out = []
        try:
            now = time.time()
            elapsed = now - (self._proc_cpu_last_at or 0.0)
            cores = os.cpu_count() or 1
            try:
                pagesz = os.sysconf("SC_PAGE_SIZE")
            except Exception:
                pagesz = 4096
            rows, cur = [], {}
            for pid in os.listdir("/proc"):
                if not pid.isdigit():
                    continue
                try:
                    with open("/proc/%s/stat" % pid, "r") as f:
                        s = f.read()
                    rp = s.rfind(")")
                    comm = s[s.find("(") + 1:rp]
                    fld = s[rp + 2:].split()
                    ticks = int(fld[11]) + int(fld[12])
                    with open("/proc/%s/statm" % pid, "r") as f2:
                        rss = int(f2.read().split()[1]) * pagesz
                except Exception:
                    continue
                cur[pid] = ticks
                cpu = 0.0
                if elapsed > 1 and pid in self._proc_cpu_last:
                    d = ticks - self._proc_cpu_last[pid]
                    if d >= 0:
                        cpu = round(d / (elapsed * 100.0 * cores) * 100.0, 1)
                rows.append({"pid": int(pid), "name": comm[:64], "cpu": cpu,
                             "mem_mb": round(rss / 1048576.0, 1)})
            self._proc_cpu_last = cur
            self._proc_cpu_last_at = now
            rows.sort(key=lambda r: r["cpu"], reverse=True)
            seen = set()
            for r in rows[:top]:
                seen.add(r["pid"]); out.append(r)
            rows.sort(key=lambda r: r["mem_mb"], reverse=True)
            for r in rows:
                if len(out) >= top * 2:
                    break
                if r["pid"] not in seen:
                    seen.add(r["pid"]); out.append(r)
        except Exception:
            pass
        return out

    _dir_scan_last = 0.0
    _dir_scan_cache = []

    def collect_dir_usage(self, roots=("/var", "/home", "/opt", "/srv", "/tmp"),
                          top=20, budget=300000):
        """ 주요 루트의 1단계 하위 폴더 용량 상위 (1시간 캐시, 검사 파일 수 상한) """
        try:
            now = time.time()
            if (now - (self._dir_scan_last or 0.0)) < 3600 and self._dir_scan_cache:
                return self._dir_scan_cache
            self._dir_scan_last = now
            out = []
            for root in roots:
                try:
                    children = [os.path.join(root, d) for d in os.listdir(root)]
                except Exception:
                    continue
                for path in children:
                    try:
                        if os.path.islink(path) or not os.path.isdir(path):
                            continue
                    except Exception:
                        continue
                    size, files = 0, 0
                    for dp, dns, fns in os.walk(path, followlinks=False):
                        for fn in fns:
                            try:
                                size += os.path.getsize(os.path.join(dp, fn))
                            except Exception:
                                pass
                            files += 1
                            budget -= 1
                            if budget <= 0:
                                break
                        if budget <= 0:
                            break
                    if size > 0:
                        out.append({"path": path[:200], "bytes": size, "files": files})
                    if budget <= 0:
                        break
                if budget <= 0:
                    break
            out.sort(key=lambda r: r["bytes"], reverse=True)
            out = out[:top]
            self._dir_scan_cache = out
            return out
        except Exception:
            return self._dir_scan_cache

    # ---------------- WAF (Linux, access-log detection) ----------------
    def _ensure_waf_dirs(self):
        for d in (WAF_DIR, WAF_LOG_DIR, WAF_STATE_DIR):
            try:
                os.makedirs(d, exist_ok=True)
            except Exception:
                pass

    def _load_waf_offsets(self):
        try:
            with open(WAF_STATE_PATH, "r", encoding="utf-8") as f:
                d = json.load(f)
            return d if isinstance(d, dict) else {}
        except Exception:
            return {}

    def _save_waf_offsets(self):
        try:
            self._ensure_waf_dirs()
            tmp = WAF_STATE_PATH + ".tmp"
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump(self._waf_offsets, f)
            os.replace(tmp, WAF_STATE_PATH)
        except Exception:
            pass

    def apply_waf_ack(self, w):
        try:
            self._ensure_waf_dirs()
            mode = str(w.get("mode", "detect")).strip().lower()
            self.waf_mode_requested = "block" if mode == "block" else "detect"
            # ModSecurity 차단 플래그가 있으면 실제 차단 모드로 보고한다.
            self.waf_mode = "block" if os.path.exists(WAF_BLOCK_FLAG) else "detect"
            ver = str(w.get("version", "") or "")
            if ver:
                self.waf_version = ver
            try:
                with open(WAF_MODE_PATH, "w", encoding="utf-8") as f:
                    f.write(self.waf_mode + "\n")
            except Exception:
                pass
            exc = w.get("exceptions")
            if isinstance(exc, list):
                try:
                    with open(WAF_EXC_PATH, "w", encoding="utf-8") as f:
                        json.dump(exc, f, ensure_ascii=False)
                    self._waf_exc_mtime = 0
                except Exception:
                    pass
            rl = w.get("ratelimits")
            if isinstance(rl, list):
                try:
                    with open(WAF_RATE_PATH, "w", encoding="utf-8") as f:
                        json.dump({"rules": rl}, f, ensure_ascii=False)
                except Exception:
                    pass
            rep = w.get("reputation")
            if isinstance(rep, list):
                try:
                    with open(WAF_REP_PATH, "w", encoding="utf-8") as f:
                        for x in rep:
                            s = str(x or "").strip()
                            if s:
                                f.write(s + "\n")
                except Exception:
                    pass
            bot = w.get("bot_allow")
            if isinstance(bot, list):
                try:
                    with open(WAF_BOT_PATH, "w", encoding="utf-8") as f:
                        for x in bot:
                            if isinstance(x, dict):
                                p = str(x.get("p", "") or "").strip()
                                try:
                                    v = int(x.get("v", 0) or 0)
                                except Exception:
                                    v = 0
                                # rDNS 검증이 필요한 항목은 Linux(ModSecurity)에서 검증할 수 없으므로
                                # UA 만으로 자동 허용하지 않는다(스푸핑 방지).
                                if v:
                                    continue
                            else:
                                p = str(x or "").strip()
                            if p:
                                f.write(p + "\n")
                except Exception:
                    pass
            ag = w.get("api_guard")
            if isinstance(ag, list):
                try:
                    with open(WAF_API_PATH, "w", encoding="utf-8") as f:
                        json.dump({"guards": ag}, f, ensure_ascii=False)
                except Exception:
                    pass
            url = str(w.get("url", "") or "")
            md5 = str(w.get("md5", "") or "").lower()
            if url and md5 and self._file_md5(WAF_RULES_PATH) != md5:
                try:
                    req = urllib.request.Request(url, headers={"User-Agent": "LoiAgentWafLinux/1.0"})
                    with urllib.request.urlopen(req, timeout=15) as resp:
                        data = resp.read(4 * 1024 * 1024)
                    if data:
                        tmp = WAF_RULES_PATH + ".tmp"
                        with open(tmp, "wb") as f:
                            f.write(data)
                        os.replace(tmp, WAF_RULES_PATH)
                        self._waf_rule_mtime = 0
                except Exception as e:
                    print("[WARN] WAF rules download failed: %s" % e)
            gurl = str(w.get("geo_url", "") or "")
            gmd5 = str(w.get("geo_md5", "") or "").lower()
            if gurl and gmd5:
                try:
                    if self._file_md5(WAF_GEO_PATH) != gmd5:
                        req = urllib.request.Request(gurl, headers={"User-Agent": "LoiAgentWafGeo/1.0"})
                        with urllib.request.urlopen(req, timeout=30) as resp:
                            data = resp.read(8 * 1024 * 1024)
                        tmp = WAF_GEO_PATH + ".tmp"
                        with open(tmp, "wb") as f:
                            f.write(data)
                        os.replace(tmp, WAF_GEO_PATH)
                        print("[INFO] WAF geo CIDR updated (%d bytes)" % len(data))
                except Exception as e:
                    print("[WARN] WAF geo download failed: %s" % e)
            gaurl = str(w.get("geo_allow_url", "") or "")
            gamd5 = str(w.get("geo_allow_md5", "") or "").lower()
            if gaurl and gamd5:
                try:
                    if self._file_md5(WAF_GEO_ALLOW_PATH) != gamd5:
                        reqa = urllib.request.Request(gaurl, headers={"User-Agent": "LoiAgentWafGeoAllow/1.0"})
                        with urllib.request.urlopen(reqa, timeout=30) as respa:
                            dataa = respa.read(8 * 1024 * 1024)
                        tmpa = WAF_GEO_ALLOW_PATH + ".tmp"
                        with open(tmpa, "wb") as f:
                            f.write(dataa)
                        os.replace(tmpa, WAF_GEO_ALLOW_PATH)
                        print("[INFO] WAF geo allow updated (%d bytes)" % len(dataa))
                except Exception as e:
                    print("[WARN] WAF geo allow download failed: %s" % e)
            gurl2 = str(w.get("gen_url", "") or "")
            gmd52 = str(w.get("gen_md5", "") or "").lower()
            if gurl2 and gmd52 and os.path.isdir("/opt/loi-waf"):
                try:
                    if self._file_md5(WAF_GEN_PATH) != gmd52:
                        req2 = urllib.request.Request(gurl2, headers={"User-Agent": "LoiAgentWafGen/1.0"})
                        with urllib.request.urlopen(req2, timeout=30) as resp2:
                            data2 = resp2.read(4 * 1024 * 1024)
                        tmp2 = WAF_GEN_PATH + ".tmp"
                        with open(tmp2, "wb") as f:
                            f.write(data2)
                        os.chmod(tmp2, 0o755)
                        os.replace(tmp2, WAF_GEN_PATH)
                        print("[INFO] loi_waf_gen.py updated (%d bytes)" % len(data2))
                except Exception as e:
                    print("[WARN] WAF gen update failed: %s" % e)
            self.waf_enabled = True
            self._load_waf_rules(force=True)
            print("[INFO] WAF(log): mode=%s rules=%d ver=%s" % (
                self.waf_mode, self.waf_rule_count, self.waf_version))
        except Exception as e:
            print("[WARN] WAF ACK apply failed: %s" % e)

    def _load_waf_rules(self, force=False):
        try:
            self._ensure_waf_dirs()
            st = os.stat(WAF_RULES_PATH)
            if not force and st.st_mtime == self._waf_rule_mtime and self.waf_rules:
                self._load_waf_exceptions()
                return
            with open(WAF_RULES_PATH, "r", encoding="utf-8") as f:
                doc = json.load(f)
            rules = []
            for r in (doc.get("rules") or []):
                if not isinstance(r, dict):
                    continue
                try:
                    rx = re.compile(str(r.get("re", "")), re.IGNORECASE)
                except Exception:
                    continue
                rules.append({
                    "id": str(r.get("id", "")),
                    "cat": str(r.get("cat", "")),
                    "sev": str(r.get("sev", "")),
                    "action": str(r.get("action", "detect")),
                    "scope": str(r.get("scope", "uri,query")).lower(),
                    "re": rx,
                })
            self.waf_rules = rules
            self.waf_rule_count = len(rules)
            ver = str(doc.get("version", "") or "")
            if ver:
                self.waf_version = ver
            self._waf_rule_mtime = st.st_mtime
            self._load_waf_exceptions()
        except Exception:
            pass

    def _load_waf_exceptions(self):
        try:
            st = os.stat(WAF_EXC_PATH)
            if st.st_mtime == self._waf_exc_mtime and self.waf_exceptions:
                return
            with open(WAF_EXC_PATH, "r", encoding="utf-8") as f:
                arr = json.load(f)
            self.waf_exceptions = arr if isinstance(arr, list) else []
            self._waf_exc_mtime = st.st_mtime
        except Exception:
            self.waf_exceptions = []

    def _waf_excepted(self, ip, path, url, rule_id, cat):
        try:
            now = time.time()
            for e in self.waf_exceptions:
                if not isinstance(e, dict):
                    continue
                if e.get("enabled") is False or str(e.get("enabled", "true")).lower() in ("false", "0"):
                    continue
                exp = str(e.get("expires", "") or "").strip()
                if exp:
                    try:
                        if len(exp) > 10:
                            t = time.mktime(time.strptime(exp[:19], "%Y-%m-%d %H:%M:%S"))
                        else:
                            t = time.mktime(time.strptime(exp[:10], "%Y-%m-%d")) + 86399
                        if now >= t:
                            continue
                    except Exception:
                        pass
                erule = str(e.get("rule", "") or "").strip()
                if erule and erule.lower() != (rule_id or "").lower():
                    continue
                esite = str(e.get("site", "") or "").strip()
                if esite and esite.lower() != (self.agent_name or "").lower():
                    continue
                et = str(e.get("type", "url") or "url").strip().lower()
                pat = str(e.get("pattern", "") or "").strip()
                if not pat:
                    continue
                if et == "ip" and (ip or "").lower() == pat.lower():
                    return True
                if et == "url" and pat.lower() in (url or "").lower():
                    return True
                if et == "path":
                    p = "/" + pat.strip("/").lower()
                    cur = (path or "").lower()
                    if cur == p or cur.startswith(p + "/"):
                        return True
                if et == "rule" and (rule_id or "").lower() == pat.lower():
                    return True
                if et in ("category", "cat") and (cat or "").lower() == pat.lower():
                    return True
        except Exception:
            pass
        return False

    def _waf_write_log(self, ip, rule, url, ua, act="detect"):
        try:
            self._ensure_waf_dirs()
            line = "[%s] %s site=%s ip=%s rule=%s cat=%s url=%s ua=%s body=N\n" % (
                time.strftime("%Y-%m-%d %H:%M:%S"),
                (act or "detect").upper(),
                (self.agent_name or "linux").replace(" ", "_"),
                ip, rule.get("id", ""), rule.get("cat", ""),
                (url or "")[:300], (ua or "")[:120])
            with open(WAF_LOG_PATH, "a", encoding="utf-8") as f:
                f.write(line)
        except Exception:
            pass

    def _waf_check_line(self, line, now):
        try:
            m = re.match(r'^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) [^"]*" (\d{3}) (\S+)(?: "([^"]*)" "([^"]*)")?', line)
            if not m:
                return None
            ip = m.group(1)
            tstr = m.group(2)
            url = m.group(4)
            referer = m.group(7) or ""
            ua = m.group(8) or ""
            status = m.group(5) or ""
            if not ip or ip == "-":
                return None
            try:
                ts = time.mktime(time.strptime(tstr.split()[0], "%d/%b/%Y:%H:%M:%S"))
            except Exception:
                ts = now
            if now - ts > 600:
                return None
            path = url.split("?", 1)[0]
            query = url.split("?", 1)[1] if "?" in url else ""
            hay = path + ("?" + query if query else "")
            dec = urllib.parse.unquote(hay)
            dec2 = urllib.parse.unquote(dec)
            for r in self.waf_rules:
                try:
                    sc = r.get("scope", "")
                    hit = False
                    if "uri" in sc or "query" in sc:
                        hit = bool(r["re"].search(hay) or r["re"].search(dec) or r["re"].search(dec2))
                    if not hit and "ua" in sc and ua:
                        hit = bool(r["re"].search(ua))
                    if not hit and ("header" in sc or "cookie" in sc):
                        hit = bool(r["re"].search(ua)) or bool(r["re"].search(referer))
                    if not hit:
                        continue
                    if self._waf_excepted(ip, path, url, r.get("id", ""), r.get("cat", "")):
                        continue
                    _rid = str(r.get("id", ""))
                    _cat = str(r.get("cat", ""))
                    if (_rid in ("1009", "1012") or _cat in ("Scanner/Bot", "Suspicious UA")) and self._waf_bot_allowed(ua):
                        continue
                    key = "%s|%s|%s" % (ip, r.get("id", ""), path)
                    last = self._waf_last_alert.get(key, 0)
                    if now - last < 60:
                        continue
                    self._waf_last_alert[key] = now
                    if len(self._waf_last_alert) > 2000:
                        self._waf_last_alert.clear()
                    act = "block" if (self.waf_mode == "block" and status == "403") else "detect"
                    self._waf_write_log(ip, r, url, ua, act)
                    return {
                        "ip": ip,
                        "url": (url or "")[:300],
                        "pattern": "%s(%s)" % (r.get("cat", ""), r.get("id", "")),
                        "action": act,
                        "src": "agent",
                    }
                except Exception:
                    continue
        except Exception:
            pass
        return None

    def _waf_bot_allowed(self, ua):
        """bot_allow.txt(허용 UA)에 매칭되면 1009/1012(봇/스캐너) 룰을 건너뛴다."""
        if not ua:
            return False
        try:
            st = os.stat(WAF_BOT_PATH)
            if st.st_mtime != self._waf_bot_mtime:
                self._waf_bot_mtime = st.st_mtime
                with open(WAF_BOT_PATH, "r", encoding="utf-8", errors="ignore") as f:
                    self._waf_bot_allow = [ln.strip().lower() for ln in f
                                           if ln.strip() and not ln.strip().startswith("#")]
        except Exception:
            pass
        low = ua.lower()
        for p in self._waf_bot_allow:
            if p and p in low:
                return True
        return False

    # ---------------- WAF audit log (ModSecurity block events) ----------------
    def _load_audit_offsets(self):
        try:
            with open(WAF_AUDIT_STATE_PATH, "r", encoding="utf-8") as f:
                d = json.load(f)
            return d if isinstance(d, dict) else {}
        except Exception:
            return {}

    def _save_audit_offsets(self):
        try:
            self._ensure_waf_dirs()
            tmp = WAF_AUDIT_STATE_PATH + ".tmp"
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump(self._audit_offsets, f)
            os.replace(tmp, WAF_AUDIT_STATE_PATH)
        except Exception:
            pass

    def _waf_emit_block(self, ip, uri, rule, msg, alerts, now, ua="", denied=True):
        path = (uri or "/").split("?", 1)[0]
        # 속도 제한(ModSecurity rate rule)은 콘솔에서 공통 룰 3001로 표시한다.
        act = "block"
        if msg and "Rate Limit" in msg:
            rule = "3001"
            if "Delay" in msg:
                act = "detect"
        if msg and "IP Reputation" in msg:
            rule = "3002"
            act = "block"
        # API 보호(3201~3204): detect 모드에서는 pass+auditlog 로 기록된다.
        if (msg or "").strip().startswith("LOI API"):
            act = "block" if denied else "detect"
        key = "%s|%s|%s" % (ip, rule, path)
        last = self._waf_last_alert.get(key, 0)
        if now - last < 60:
            return
        self._waf_last_alert[key] = now
        if len(self._waf_last_alert) > 2000:
            self._waf_last_alert.clear()
        cat = (msg or "").strip()
        if cat.upper().startswith("LOI "):
            cat = cat[4:].strip()
        if not cat:
            cat = "ModSecurity"
        if msg and "Rate Limit" in msg:
            cat = "Rate Limit"
        if msg and "IP Reputation" in msg:
            cat = "IP Reputation"
        if (msg or "").strip().startswith("LOI API"):
            cat = "API Guard"
        self._waf_write_log(ip, {"id": rule, "cat": cat}, uri, "modsec", act)
        alerts.append({
            "ip": ip,
            "url": (uri or "")[:300],
            "pattern": "%s(%s)" % (cat, rule),
            "action": act,
            "src": "module",
            "ua": (ua or "")[:120],
        })

    def scan_waf_audit(self):
        """Read ModSecurity serial audit log and report intercepted requests."""
        if not self.waf_enabled:
            return []
        alerts = []
        now = time.time()
        for path in (WAF_AUDIT_PATH, WAF_AUDIT_PATH_ALT):
            try:
                self._scan_waf_audit_file(path, alerts, now)
            except Exception:
                pass
            if len(alerts) >= 20:
                break
        return alerts

    def _scan_waf_audit_file(self, path, alerts, now):
        try:
            st = os.stat(path)
        except Exception:
            return
        ent = self._audit_offsets.get(path)
        if not isinstance(ent, dict):
            self._audit_offsets[path] = {"ino": st.st_ino, "off": st.st_size}
            self._save_audit_offsets()
            return
        if ent.get("ino") != st.st_ino or st.st_size < int(ent.get("off", 0) or 0):
            ent = {"ino": st.st_ino, "off": 0}
            self._audit_offsets[path] = ent
        off = int(ent.get("off", 0) or 0)
        if st.st_size <= off:
            return
        with open(path, "rb") as f:
            f.seek(off)
            chunk = f.read(min(st.st_size - off, 4 * 1024 * 1024))
        last_nl = chunk.rfind(b"\n")
        if last_nl < 0:
            return
        data = chunk[:last_nl + 1]
        self._audit_offsets[path]["off"] = off + len(data)
        self._save_audit_offsets()
        cur = None
        for raw in data.split(b"\n"):
            line = raw.decode("utf-8", "replace").rstrip("\r")
            if not line:
                continue
            _sm = re.match(r'^--+[0-9A-Za-z]+-+([A-Z])--$', line)
            if _sm and _sm.group(1) == "A":
                cur = {"ip": "", "uri": "", "rule": "", "msg": "", "deny": False, "ua": "", "api": False}
                continue
            if cur is None:
                continue
            if _sm and _sm.group(1) == "Z":
                _amsg = cur.get("msg") or ""
                _api = bool(cur.get("api")) or str(cur.get("rule", "")) in ("3201", "3202", "3203", "3204")
                if (cur.get("deny") or ("Rate Limit Delay" in _amsg) or _api) and cur["ip"] and cur["uri"] and cur["rule"]:
                    self._waf_emit_block(cur["ip"], cur["uri"], cur["rule"],
                                         cur["msg"], alerts, now, cur.get("ua", ""),
                                         denied=bool(cur.get("deny")))
                cur = None
                if len(alerts) >= 20:
                    break
                continue
            if not cur.get("ua"):
                m = re.match(r'^\s*User-Agent:\s*(.+)$', line, re.I)
                if m:
                    cur["ua"] = m.group(1).strip()[:120]
                    continue
            if not cur["ip"]:
                m = re.match(r'^\[[^\]]+\]\s+\S+\s+(\S+)\s+', line)
                if m and re.match(r'^[0-9A-Fa-f:.]+$', m.group(1)):
                    cur["ip"] = m.group(1)
                    continue
            if line.startswith("Action:") and "Intercepted" in line:
                cur["deny"] = True
                continue
            if '[uri "' in line:
                m = re.search(r'\[uri "([^"]*)"', line)
                if m:
                    cur["uri"] = m.group(1)
                    continue
            if not cur["uri"]:
                m = re.match(r'^(GET|POST|HEAD|PUT|DELETE|OPTIONS|PATCH) (\S+) HTTP/', line)
                if m:
                    cur["uri"] = m.group(2)
                    continue
            if not cur["rule"] and '[id "' in line:
                m = re.search(r'\[id "(\d+)"', line)
                if m and m.group(1) != "0":
                    cur["rule"] = m.group(1)
            if '[msg "' in line:
                m = re.search(r'\[msg "([^"]*)"', line)
                if m:
                    cur["msg"] = m.group(1)
                    if m.group(1).strip().startswith("LOI API"):
                        cur["api"] = True

    def scan_waf_logs(self):
        if not self.waf_enabled:
            return []
        self._load_waf_rules()
        self._ensure_waf_dirs()
        alerts = []
        now = time.time()
        changed = False
        try:
            for pattern in self.WEB_LOG_GLOBS:
                for path in glob.glob(pattern):
                    try:
                        st = os.stat(path)
                        ent = self._waf_offsets.get(path)
                        if not isinstance(ent, dict):
                            self._waf_offsets[path] = {"ino": st.st_ino, "off": st.st_size}
                            changed = True
                            continue
                        if ent.get("ino") != st.st_ino or st.st_size < int(ent.get("off", 0) or 0):
                            ent = {"ino": st.st_ino, "off": 0}
                            self._waf_offsets[path] = ent
                            changed = True
                        off = int(ent.get("off", 0) or 0)
                        if st.st_size <= off:
                            continue
                        read_n = min(st.st_size - off, 2 * 1024 * 1024)
                        with open(path, "rb") as f:
                            f.seek(off)
                            chunk = f.read(read_n)
                        last_nl = chunk.rfind(b"\n")
                        if last_nl < 0:
                            continue
                        data = chunk[:last_nl + 1]
                        self._waf_offsets[path]["off"] = off + len(data)
                        changed = True
                        for raw in data.split(b"\n"):
                            if not raw:
                                continue
                            a = self._waf_check_line(raw.decode("utf-8", "replace"), now)
                            if a:
                                alerts.append(a)
                            if len(alerts) >= 20:
                                break
                    except Exception:
                        continue
                    if len(alerts) >= 20:
                        break
                if len(alerts) >= 20:
                    break
        except Exception:
            pass
        if changed:
            self._save_waf_offsets()
        return alerts

    def get_waf_modsec_version(self):
        """Installed ModSecurity package version (cached)."""
        try:
            now = time.time()
            ttl = 300 if self._waf_modsec_ver not in ("", "none") else 30
            if self._waf_modsec_ver_ts and now - self._waf_modsec_ver_ts < ttl:
                return self._waf_modsec_ver
            ver = "none"
            try:
                if shutil.which("rpm") is not None:
                    r = subprocess.run(["rpm", "-q", "--qf", "%{VERSION}-%{RELEASE}", "mod_security"],
                                       stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
                                       universal_newlines=True, timeout=5)
                    if r.returncode == 0 and (r.stdout or "").strip():
                        ver = r.stdout.strip()
            except Exception:
                pass
            if ver == "none":
                try:
                    if shutil.which("dpkg-query") is not None:
                        r = subprocess.run(["dpkg-query", "-W", "-f=${Version}", "libapache2-mod-security2"],
                                           stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
                                           universal_newlines=True, timeout=5)
                        if r.returncode == 0 and (r.stdout or "").strip():
                            ver = r.stdout.strip()
                except Exception:
                    pass
            ver = ver.strip() or "none"
            if len(ver) > 20:
                ver = ver[:20]
            self._waf_modsec_ver = ver
            self._waf_modsec_ver_ts = now
            return ver
        except Exception:
            return "none"

    # ---------------- WAF Job (Linux: installer 실행) ----------------
    WAF_JOB_ARGS = {
        "preflight": "--status",
        "install_detect": "--detect",
        "switch_detect": "--detect",
        "install_block": "--block",
        "switch_block": "--block",
        "uninstall": "--uninstall",
    }

    def _queue_job_result(self, jid, action, site, status, output="", error=""):
        try:
            with self._job_result_lock:
                self._pending_job_results.append({
                    "id": jid,
                    "action": action,
                    "site": site,
                    "status": status,
                    "output": (output or "")[:4000],
                    "error": (error or "")[:1000],
                })
        except Exception:
            pass

    def _verify_waf_job_sig(self, j):
        try:
            jid = str(j.get("id", "")).strip()
            action = str(j.get("action", "")).strip()
            site = str(j.get("site", "")).strip()
            mode = str(j.get("mode", "detect")).strip().lower()
            if mode != "block":
                mode = "detect"
            run_all = str(j.get("run_all", "")).strip().lower() in ("true", "1")
            module_sha = str(j.get("module_sha256", "")).strip().lower()
            script_sha = str(j.get("script_sha256", "")).strip().lower()
            plan_hash = str(j.get("plan_hash", "")).strip().lower()
            expires = str(j.get("expires", "")).strip()
            sig = str(j.get("sig", "")).strip().lower()
            if not jid or not action or not sig:
                return False
            try:
                exp = calendar.timegm(time.strptime(expires, "%Y-%m-%dT%H:%M:%SZ"))
            except Exception:
                return False
            if time.time() > exp + 60:
                return False
            data = "|".join([jid, action, site, mode, "true" if run_all else "false",
                             module_sha, script_sha, plan_hash, expires])
            calc = hmac.new(AGENT_TOKEN.encode("utf-8"), data.encode("utf-8"), hashlib.sha256).hexdigest()
            return hmac.compare_digest(calc, sig)
        except Exception:
            return False

    def start_waf_job(self, j):
        try:
            jid = int(str(j.get("id", "0")).strip() or 0)
        except Exception:
            return
        if jid <= 0 or jid in self._job_seen:
            return
        self._job_seen.add(jid)
        if len(self._job_seen) > 500:
            self._job_seen.clear()
        threading.Thread(target=self._run_waf_job, args=(dict(j),), daemon=True).start()

    def _run_waf_job(self, j):
        jid = 0
        action = str(j.get("action", "")).strip()
        site = str(j.get("site", "")).strip()
        tmp = ""
        try:
            jid = int(str(j.get("id", "0")).strip() or 0)
        except Exception:
            return
        with self._job_exec_lock:
            try:
                if not self._verify_waf_job_sig(j):
                    self._queue_job_result(jid, action, site, "fail", error="invalid signature or expired")
                    return
                arg = self.WAF_JOB_ARGS.get(action)
                if not arg:
                    self._queue_job_result(jid, action, site, "fail", error="unsupported action on linux: " + action)
                    return
                url = str(j.get("script_url", "") or "").strip()
                sha = str(j.get("script_sha256", "") or "").strip().lower()
                if not url or not sha:
                    self._queue_job_result(jid, action, site, "fail", error="script url/sha missing")
                    return
                req = urllib.request.Request(url, headers={"User-Agent": "LoiAgentWafJob/1.0"})
                with urllib.request.urlopen(req, timeout=60) as resp:
                    data = resp.read(4 * 1024 * 1024)
                got = hashlib.sha256(data).hexdigest()
                if got.lower() != sha:
                    self._queue_job_result(jid, action, site, "fail", error="script sha256 mismatch")
                    return
                tmp = "/tmp/loi_waf_job_%d.sh" % jid
                with open(tmp, "wb") as f:
                    f.write(data)
                os.chmod(tmp, 0o700)
                cmd = ["/bin/bash", tmp, arg]
                if os.geteuid() != 0:
                    cmd = ["sudo", "-n"] + cmd
                r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                   universal_newlines=True, timeout=900)
                out = (r.stdout or "").strip()
                ok = (r.returncode == 0)
                self._queue_job_result(jid, action, site, "ok" if ok else "fail",
                                       output=out, error="" if ok else ("rc=%d" % r.returncode))
            except Exception as e:
                self._queue_job_result(jid, action, site, "fail", error=str(e)[:300])
            finally:
                if tmp:
                    try:
                        os.remove(tmp)
                    except Exception:
                        pass

    def collect_payload(self):
        cpu_pct = self.get_cpu_percent()
        total_mb, used_mb, mem_pct = self.get_memory_info()
        disks = self.get_disk_info()
        in_bps, out_bps = self.get_network_rates()
        self.maybe_capture_net_spike(out_bps)
        disk_io_pct, disk_await_ms = self.get_disk_io_stats()
        admin_logins, user_logins = self.get_admin_logins()
        file_changes = self.check_file_changes()
        event_logs = self.get_event_logs()
        web_unique, web_hits = self.get_web_visitors()
        waf_attacks = []
        if self.waf_enabled:
            waf_attacks = self.scan_waf_audit() + self.scan_waf_logs()
        login_fails = list(self._pending_login_fails)
        self._pending_login_fails = []
        self.flush_file_traffic()
        ft_batch = list(self._pending_file_traffic) if self.file_traffic_enabled else []

        payload = {
            "host_name": self.agent_name,
            "ip": self.get_local_ip(),
            "machine_id": self.get_machine_id(),
            "token": AGENT_TOKEN,
            "os": self.get_os_info(),
            "agent_version": self.get_agent_version(),
            "cpu_percent": cpu_pct,
            "cpu_cores": os.cpu_count() or 0,
            "antivirus": self.get_antivirus_info_cached(),
            "disk_io_percent": disk_io_pct,
            "disk_await_ms": disk_await_ms,
            "admin_logins": admin_logins,
            "user_logins": user_logins,
            "login_failures": login_fails,
            "file_changes": file_changes,
            "event_logs": event_logs,
            "web_visitors": {
                "unique_ips": web_unique,
                "hits": web_hits,
                "connections": 0
            },
            "memory_percent": mem_pct,
            "memory_used_mb": used_mb,
            "memory_total_mb": total_mb,
            "disks": disks,
            "ports": self.collect_ports(),
            "top_proc": self.collect_top_processes(10),
            "dir_usage": self.collect_dir_usage(),
            "network": {
                "in_bps": in_bps,
                "out_bps": out_bps,
                "latency_ms": self.last_latency_ms
            }
        }
        if ft_batch:
            payload["file_traffic"] = ft_batch
        if waf_attacks:
            payload["web_attacks"] = waf_attacks
        try:
            with self._job_result_lock:
                if self._pending_job_results:
                    payload["job_results"] = list(self._pending_job_results)
                    self._pending_job_results = []
        except Exception:
            pass
        try:
            if self._pending_net_spikes:
                payload["net_spikes"] = list(self._pending_net_spikes)
        except Exception:
            pass
        if self.waf_enabled:
            payload["waf_version"] = self.waf_version
            payload["waf_mode"] = self.waf_mode
            payload["waf_rules"] = self.waf_rule_count
            payload["waf_module"] = "1"
            payload["waf_module_ver"] = self.get_waf_modsec_version()
            payload["waf_module_status"] = "ok" if payload["waf_module_ver"] not in ("", "none") else "none"
        return payload

    def send_goodbye(self):
        data = json.dumps({"goodbye": True, "machine_id": self.get_machine_id(), "token": AGENT_TOKEN}) + "\n"
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(5.0)
            s.connect((self.server_ip, self.port))
            s.sendall(data.encode("utf-8"))

    def send_metrics(self, payload):
        data = json.dumps(payload) + "\n"
        start = time.time()
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(5.0)
            s.connect((self.server_ip, self.port))
            self.last_latency_ms = int((time.time() - start) * 1000)
            s.sendall(data.encode("utf-8"))
            raw = b""
            while True:
                try:
                    chunk = s.recv(4096)
                except socket.timeout:
                    break
                if not chunk:
                    break
                raw += chunk
                if b"\n" in chunk or len(raw) > 65536:
                    break
            response = raw.decode("utf-8-sig").strip()
            try:
                ack = json.loads(response)
                # 이름의 기준은 사이트(DB HostName). 서버가 내려주면 그대로 저장·사용한다.
                if isinstance(ack, dict) and ack.get("agent_name"):
                    new_name = str(ack["agent_name"]).strip()
                    if new_name and new_name != self.agent_name:
                        self.agent_name = new_name
                        self._save_config()
                        print("[INFO] Agent name set by server: %s" % new_name)
                if isinstance(ack, dict) and "watch_paths" in ack:
                    self.file_watch_paths = [p for p in ack["watch_paths"] if p]
                if isinstance(ack, dict) and "file_traffic" in ack:
                    want = ack["file_traffic"] is True
                    if want != self.file_traffic_enabled:
                        self.file_traffic_enabled = want
                        self._ft_hours = {}
                        print("[INFO] File traffic accounting: %s" % ("ON" if want else "OFF"))
                if isinstance(ack, dict) and ack.get("uninstall") is True:
                    print("[INFO] Uninstall requested by server. Removing agent...")
                    try:
                        self.send_goodbye()
                    except Exception:
                        pass
                    try:
                        base = os.path.dirname(os.path.abspath(__file__))
                        if base.startswith("/opt/loi_agent"):
                            shutil.rmtree("/opt/loi_agent", ignore_errors=True)
                    except Exception:
                        pass
                    try:
                        os.system("systemctl disable --now loi-agent")
                    except Exception:
                        pass
                    sys.exit(0)
                if isinstance(ack, dict) and ack.get("agent_update") is True:
                    self.try_self_update(ack.get("agent_url", ""), ack.get("agent_md5", ""))
                if isinstance(ack, dict) and "waf_target" in ack:
                    if str(ack.get("waf_target")) != "1":
                        self.waf_enabled = False
                if isinstance(ack, dict) and isinstance(ack.get("waf"), dict):
                    self.apply_waf_ack(ack["waf"])
                if isinstance(ack, dict) and isinstance(ack.get("jobs"), list):
                    for _j in ack["jobs"]:
                        if isinstance(_j, dict):
                            self.start_waf_job(_j)
            except SystemExit:
                raise
            except Exception:
                pass
            return response

    def run(self):
        print("=" * 54)
        print("  LOI Zabbix Linux Monitoring Agent")
        print("=" * 54)
        print(f"[INFO] Agent Name   : {self.agent_name}")
        print(f"[INFO] Monitoring IP: {self.server_ip}")
        print(f"[INFO] Target Port  : TCP {self.port}")
        try:
            av = self.get_antivirus_info()
            if av.get("products"):
                for p in av["products"]:
                    print(f"[INFO] AV detected  : {p.get('name')} ({p.get('state')})")
            else:
                print("[INFO] AV detected  : none")
        except Exception as e:
            print(f"[WARN] AV probe failed: {e}")
        print("[INFO] Starting metric collection every 5 seconds... (Press Ctrl+C to stop)")

        # 종료/재부팅 명령 감시 스레드 (shutdown, reboot, halt, poweroff, init 0/6, systemctl reboot/poweroff)
        try:
            threading.Thread(target=self._shutdown_watch_loop, daemon=True).start()
            print("[INFO] Shutdown watcher started: shutdown, reboot, halt, poweroff, init 0/6, systemctl reboot/poweroff")
        except Exception as e:
            print("[WARN] Shutdown watcher failed: %s" % e)
        # journald 감시 스레드 (짧은 명령/ sudo / systemd 종료 메시지 보조 감지)
        try:
            threading.Thread(target=self._journal_watch_loop, daemon=True).start()
            print("[INFO] Journal watcher started (journalctl -f)")
        except Exception as e:
            print("[WARN] Journal watcher failed: %s" % e)
        # 종료 시 ExecStop 으로 확실히 푸시하도록 systemd 드롭인 설치
        self.ensure_shutdown_notifier_dropin()

        while True:
            try:
                time.sleep(5)
                payload = self.collect_payload()
                ack = self.send_metrics(payload)
                # Ack received means the hour buckets landed; drop them so they are not resent.
                sent_ft = payload.get("file_traffic") or []
                if sent_ft:
                    del self._pending_file_traffic[:len(sent_ft)]
                sent_ns = payload.get("net_spikes") or []
                if sent_ns:
                    del self._pending_net_spikes[:len(sent_ns)]
                now_str = time.strftime("%H:%M:%S")
                cpu = payload['cpu_percent']
                mem = payload['memory_percent']
                in_kb = payload['network']['in_bps'] / 1024.0
                out_kb = payload['network']['out_bps'] / 1024.0
                print(f"[{now_str}] Sent: CPU {cpu}%, RAM {mem}%, NetIn {in_kb:.1f}KB/s, NetOut {out_kb:.1f}KB/s | Server: {ack}")
            except KeyboardInterrupt:
                print("\n[INFO] Stopping Linux Agent...")
                break
            except Exception as e:
                now_str = time.strftime("%H:%M:%S")
                print(f"[{now_str}] [ERROR] TCP Send Failed: {e}")

def main():
    parser = argparse.ArgumentParser(description="LOI Zabbix Linux Monitoring Agent")
    parser.add_argument("-server", "-s", dest="server", help="Monitoring Server IP Address")
    parser.add_argument("-name", "-n", dest="name", help="Agent Host Name")
    parser.add_argument("-notify-shutdown", "--notify-shutdown", dest="notify_shutdown",
                        action="store_true", help="Send a shutdown push and exit (systemd ExecStop)")
    args = parser.parse_args()

    agent = LinuxAgent(server_ip=args.server, agent_name=args.name)
    if args.notify_shutdown:
        agent.notify_shutdown_once()
        return
    agent.run()

if __name__ == "__main__":
    main()
