#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================================================
GEPI SECURITY SENTINEL — AGENTE DEFENSIVO PARA SERVIDORES LINUX / VPS (v3.0)
MenuGepi / Trinity OS — Arquitectura Zero-Recompile Cloud-AI
=============================================================================
Compatible con Ubuntu, Debian, CentOS, AlmaLinux, Rocky, Fedora, Oracle Linux.
Cero dependencias externas (solo biblioteca estándar Python 3).

Capacidades Defensivas:
  0. Descarga de política diaria IA desde Firebase (con fallback Modo Trinchera).
  1. Auditoría de versiones críticas (PHP EOL, Nginx/Apache, estado de Firewall).
  2. Puertos en escucha (ss/netstat) y detección de bases de datos expuestas (0.0.0.0).
  3. Procesos reales (/proc) y detección de binarios en /tmp, /dev/shm o (deleted).
  4. Persistencia Linux (cron, /etc/cron.d, systemd, conteo de SSH authorized_keys).
  5. Análisis de binarios sospechosos: SHA-256, Entropía de Shannon y cadenas.
  6. Envío de metadatos mínimos (LFPDPPP) al Webhook IA de Firebase y veredicto Gemini.
=============================================================================
"""

import os
import re
import sys
import json
import math
import glob
import socket
import hashlib
import platform
import argparse
import subprocess
import urllib.request
from datetime import datetime

DEFAULT_CLOUD_WEBHOOK = "https://us-central1-menugepi.cloudfunctions.net/escanerPolicyWebhook"
RULES_CACHE_FILE = "rules-cache-linux.json"
CONSENT_FILE = "gepi-consent.json"
PRIVACY_NOTICE_VERSION = "2026.1"

DEFAULT_POLICY_LINUX = {
    "version": "3.0.0-linux-local",
    "fuente": "modo-trinchera-offline",
    "entropy_threshold": 7.2,
    "suspicious_paths": ["/tmp/", "/dev/shm/", "/var/tmp/", "/run/shm/"],
    "suspicious_strings": [
        "base64 -d", "curl | sh", "wget -qo-", "nc -e", "/dev/tcp/",
        "xmrig", "stratum+tcp", "chmod +x /tmp", "ignore previous instructions"
    ],
    "blacklist_hashes": [],
    "blacklist_ips": [],
    "indicaciones_ia": [
        "Modo Trinchera Linux: verificar PHP vigente (>=8.2), puertos BD cerrados y /tmp limpio."
    ]
}


def run_cmd(cmd, timeout=3.0):
    try:
        res = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
        return (res.stdout or "").strip()
    except Exception:
        return ""


def verificar_consentimiento(aceptado_cli=False):
    path = os.path.abspath(CONSENT_FILE)
    if os.path.exists(path):
        try:
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)
            if data.get("aceptado") is True and data.get("version") == PRIVACY_NOTICE_VERSION:
                return True
        except Exception:
            pass

    if aceptado_cli:
        try:
            with open(path, "w", encoding="utf-8") as f:
                json.dump({"aceptado": True, "version": PRIVACY_NOTICE_VERSION, "fecha": datetime.now().isoformat()}, f, indent=2)
        except Exception:
            pass
        return True

    print("=" * 70)
    print("AVISO DE PRIVACIDAD — GEPI SECURITY SENTINEL LINUX/VPS (v3.0)")
    print("Solo envía metadatos técnicos (versiones, puertos, hashes SHA-256 y entropía).")
    print("NUNCA sube archivos de clientes, bases de datos ni claves privadas.")
    print("=" * 70)
    resp = input("Escribe 'SI' para autorizar (o usa --accept-privacy / --offline): ").strip().lower()
    if resp in ("si", "sí", "s", "y", "yes"):
        try:
            with open(path, "w", encoding="utf-8") as f:
                json.dump({"aceptado": True, "version": PRIVACY_NOTICE_VERSION, "fecha": datetime.now().isoformat()}, f, indent=2)
        except Exception:
            pass
        return True
    return False


def cargar_politica_dinamica(cloud_url, offline=False):
    politica = dict(DEFAULT_POLICY_LINUX)
    cache_path = os.path.abspath(RULES_CACHE_FILE)

    if not offline and cloud_url:
        try:
            req = urllib.request.Request(
                cloud_url,
                headers={"Accept": "application/json", "User-Agent": "GepiSentinel-Linux/3.0"},
                method="GET"
            )
            with urllib.request.urlopen(req, timeout=6.0) as resp:
                if resp.status == 200:
                    data = json.loads(resp.read().decode("utf-8", errors="replace"))
                    remota = data.get("politica") if isinstance(data, dict) else None
                    if isinstance(remota, dict):
                        politica.update(remota)
                        try:
                            with open(cache_path, "w", encoding="utf-8") as f:
                                json.dump(politica, f, indent=2, ensure_ascii=False)
                        except Exception:
                            pass
                        print(f"  [+] Política IA sincronizada desde Firebase ({politica.get('fuente')})")
                        return politica
        except Exception as e:
            print(f"  [!] Firebase no alcanzable ({e}). Activando Modo Trinchera Offline...")

    if os.path.exists(cache_path):
        try:
            with open(cache_path, "r", encoding="utf-8") as f:
                cached = json.load(f)
            if isinstance(cached, dict):
                politica.update(cached)
                politica["fuente"] = f"cache-local ({cached.get('actualizado', 'previa')})"
                print("  [+] Usando caché local de política.")
                return politica
        except Exception:
            pass

    print("  [i] Operando con reglas deterministas base (Modo Trinchera).")
    return politica


def auditar_servicios_y_firewall():
    info = {
        "php_version": None,
        "php_eol_riesgo": False,
        "web_server": [],
        "firewall_activo": False,
        "firewall_detalle": "No detectado"
    }

    php_out = run_cmd("php -v 2>/dev/null | head -n 1")
    if php_out:
        m = re.search(r"PHP\s+(\d+\.\d+\.\d+)", php_out)
        if m:
            ver = m.group(1)
            info["php_version"] = ver
            parts = [int(x) for x in ver.split(".")[:2]]
            if parts[0] < 8 or (parts[0] == 8 and parts[1] < 2):
                info["php_eol_riesgo"] = True

    if run_cmd("which nginx 2>/dev/null"):
        info["web_server"].append("nginx")
    if run_cmd("which apache2 2>/dev/null") or run_cmd("which httpd 2>/dev/null"):
        info["web_server"].append("apache")

    ufw = run_cmd("ufw status 2>/dev/null | head -n 1")
    if "active" in ufw.lower() and "inactive" not in ufw.lower():
        info["firewall_activo"] = True
        info["firewall_detalle"] = "ufw activo"
    else:
        fwd = run_cmd("firewall-cmd --state 2>/dev/null")
        if "running" in fwd.lower():
            info["firewall_activo"] = True
            info["firewall_detalle"] = "firewalld activo"
        else:
            nft = run_cmd("nft list ruleset 2>/dev/null | head -n 5")
            if nft:
                info["firewall_activo"] = True
                info["firewall_detalle"] = "nftables con reglas"

    return info


def auditar_puertos_linux():
    puertos = []
    bd_expuestas = []
    out = run_cmd("ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null")
    db_ports = {3306: "MySQL/MariaDB", 5432: "PostgreSQL", 6379: "Redis", 27017: "MongoDB"}

    for line in out.splitlines()[1:]:
        parts = line.split()
        if len(parts) < 5:
            continue
        local_addr = parts[4] if parts[0].startswith(("tcp", "udp")) else parts[3]
        if ":" not in local_addr:
            continue
        host_part, port_str = local_addr.rsplit(":", 1)
        if not port_str.isdigit():
            continue
        port = int(port_str)
        puertos.append({"direccion": local_addr, "puerto": port})
        if port in db_ports and host_part in ("0.0.0.0", "*", "[::]", "::"):
            bd_expuestas.append({"puerto": port, "servicio": db_ports[port], "direccion": local_addr})

    return puertos[:40], bd_expuestas


def calcular_entropia(data_bytes):
    if not data_bytes:
        return 0.0
    freq = [0] * 256
    for b in data_bytes:
        freq[b] += 1
    n = len(data_bytes)
    return round(-sum((c / n) * math.log2(c / n) for c in freq if c), 2)


def analizar_archivo(ruta, politica):
    info = {
        "ruta": ruta,
        "nombre": os.path.basename(ruta),
        "sha256": None,
        "entropia": 0.0,
        "coincidencias_strings": [],
        "hash_bloqueado": False,
        "alerta": False
    }
    if not os.path.isfile(ruta):
        return info
    try:
        h = hashlib.sha256()
        with open(ruta, "rb") as f:
            sample = f.read(524288)
            chunk = sample
            while chunk:
                h.update(chunk)
                chunk = f.read(524288)
        info["sha256"] = h.hexdigest()
        info["entropia"] = calcular_entropia(sample)

        bl = {str(x).lower() for x in politica.get("blacklist_hashes", [])}
        if info["sha256"].lower() in bl:
            info["hash_bloqueado"] = True

        sample_l = sample.decode("latin-1", errors="ignore").lower()
        for pat in politica.get("suspicious_strings", []):
            p = str(pat).strip().lower()
            if p and p in sample_l:
                info["coincidencias_strings"].append(p)

        if info["hash_bloqueado"] or info["entropia"] >= float(politica.get("entropy_threshold", 7.2)) or info["coincidencias_strings"]:
            info["alerta"] = True
    except Exception:
        pass
    return info


def auditar_procesos_y_archivos_linux(politica):
    rutas_vigiladas = [str(r).lower() for r in politica.get("suspicious_paths", DEFAULT_POLICY_LINUX["suspicious_paths"])]
    procesos_temp = []
    binarios_sospechosos = []
    revisados = set()
    total_procs = 0

    for pid_dir in glob.glob("/proc/[0-9]*"):
        total_procs += 1
        pid = os.path.basename(pid_dir)
        try:
            exe = os.readlink(os.path.join(pid_dir, "exe"))
        except Exception:
            continue
        exe_l = exe.lower()
        es_deleted = "(deleted)" in exe_l
        en_ruta_volatil = any(rv in exe_l for rv in rutas_vigiladas)

        if es_deleted or en_ruta_volatil:
            procesos_temp.append({"pid": int(pid), "nombre": os.path.basename(exe), "ruta": exe, "deleted": es_deleted})
            if not es_deleted and exe_l not in revisados and os.path.isfile(exe):
                revisados.add(exe_l)
                res = analizar_archivo(exe, politica)
                res["pid"] = int(pid)
                binarios_sospechosos.append(res)

    return total_procs, procesos_temp, {"total_revisados": len(revisados), "sospechosos": binarios_sospechosos}


def auditar_persistencia_linux():
    run_keys = []
    for cron_file in ["/etc/crontab"] + glob.glob("/etc/cron.d/*"):
        try:
            with open(cron_file, "r", encoding="utf-8", errors="ignore") as f:
                for line in f:
                    s = line.strip()
                    if s and not s.startswith("#") and ("curl" in s or "wget" in s or "/tmp/" in s or "base64" in s):
                        run_keys.append({"ubicacion": cron_file, "nombre": "cron_sospechoso", "valor": s[:180]})
        except Exception:
            pass
    return run_keys


def consultar_webhook_ia(reporte, cloud_url, offline=False, agent_key=None):
    if not offline and cloud_url:
        try:
            headers = {"Content-Type": "application/json; charset=utf-8", "User-Agent": "GepiSentinel-Linux/3.0"}
            key = agent_key or os.getenv("GEPI_AGENT_KEY", "").strip()
            if key:
                headers["X-Gepi-Agent-Key"] = key
            req = urllib.request.Request(
                cloud_url,
                data=json.dumps(reporte).encode("utf-8"),
                headers=headers,
                method="POST"
            )
            with urllib.request.urlopen(req, timeout=25.0) as resp:
                if resp.status == 200:
                    data = json.loads(resp.read().decode("utf-8", errors="replace"))
                    if isinstance(data.get("veredicto"), dict):
                        return data["veredicto"]
        except Exception as e:
            print(f"  [!] Webhook IA no disponible ({e}). Evaluando en Modo Trinchera Offline.")

    score = 100
    if reporte["servicios_linux"].get("php_eol_riesgo"):
        score -= 20
    if not reporte["servicios_linux"].get("firewall_activo"):
        score -= 15
    if reporte["bd_expuestas"]:
        score -= 30
    if reporte["persistencia"]["procesos_temp"]:
        score -= 25
    score = max(0, score)
    risk = "CRITICAL" if score < 50 else "HIGH" if score < 75 else "MEDIUM" if score < 90 else "NONE"
    return {
        "is_malicious": score < 75,
        "risk_level": risk,
        "score": score,
        "motor": "trinchera-linux-offline",
        "resumen_ejecutivo": f"Evaluación Linux offline completada. Riesgo: {risk} ({score}/100).",
        "hallazgos": []
    }


def main():
    parser = argparse.ArgumentParser(description="GEPI Security Sentinel — Agente Linux / VPS v3.0")
    parser.add_argument("--output", "-o", default="gepi-report-linux.json", help="Archivo de salida JSON")
    parser.add_argument("--offline", action="store_true", help="Modo Trinchera Offline")
    parser.add_argument("--accept-privacy", action="store_true", help="Aceptar Aviso de Privacidad (para cron/systemd)")
    parser.add_argument("--agent-key", default=None, help="Token X-Gepi-Agent-Key (o GEPI_AGENT_KEY)")
    parser.add_argument("--cloud-url", default=DEFAULT_CLOUD_WEBHOOK, help="URL del Webhook Firebase IA")
    args = parser.parse_args()

    if not args.offline and not verificar_consentimiento(aceptado_cli=args.accept_privacy):
        print("[!] Cancelado: se requiere aceptar el Aviso de Privacidad (o usar --offline).")
        return 1

    print("\n🛡️  GEPI SECURITY SENTINEL — LINUX / VPS AGENT v3.0")
    print("=" * 65)
    politica = cargar_politica_dinamica(args.cloud_url, offline=args.offline)
    servicios = auditar_servicios_y_firewall()
    puertos, bd_expuestas = auditar_puertos_linux()
    total_procs, procesos_temp, analisis_archivos = auditar_procesos_y_archivos_linux(politica)
    run_keys = auditar_persistencia_linux()

    print(f"  [i] Host: {socket.gethostname()} | Kernel: {platform.release()}")
    print(f"  [i] PHP: {servicios['php_version'] or 'No instalado'} | EOL Riesgo: {servicios['php_eol_riesgo']}")
    print(f"  [i] Firewall: {servicios['firewall_detalle']} | Puertos: {len(puertos)} | BD Expuestas: {len(bd_expuestas)}")
    print(f"  [i] Procesos auditados: {total_procs} | En rutas volátiles/deleted: {len(procesos_temp)}")

    reporte = {
        "consentimiento_privacidad": True,
        "plataforma": "linux",
        "version_agente": "3.0.0-linux",
        "timestamp": datetime.now().isoformat(),
        "equipo": socket.gethostname(),
        "os": f"{platform.system()} {platform.release()} ({platform.machine()})",
        "servicios_linux": servicios,
        "bd_expuestas": bd_expuestas,
        "puertos_escuchando": puertos,
        "persistencia": {
            "procesos_temp": procesos_temp,
            "run_keys": run_keys
        },
        "analisis_archivos": analisis_archivos
    }

    reporte["veredicto_ia"] = consultar_webhook_ia(
        reporte, args.cloud_url, offline=args.offline, agent_key=args.agent_key
    )

    with open(args.output, "w", encoding="utf-8") as f:
        json.dump(reporte, f, indent=2, ensure_ascii=False)

    v = reporte["veredicto_ia"]
    print(f"\n  [+] Veredicto ({v.get('motor')}): {v.get('risk_level')} | Score: {v.get('score')}/100")
    print(f"      {v.get('resumen_ejecutivo', '')}")
    print(f"  [OK] Reporte guardado en: {os.path.abspath(args.output)}")
    return 0


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