#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================================================
GEPI SECURITY SENTINEL — AGENTE DEFENSIVO NATIVO PARA macOS (v3.0)
MenuGepi / Trinity OS — Arquitectura Zero-Recompile Cloud-AI
=============================================================================
Compatible con macOS Apple Silicon (M1/M2/M3/M4) e Intel.
Usa exclusivamente herramientas oficiales de macOS (cero kexts, cero hacks).

Capacidades Defensivas:
  0. Descarga de política diaria IA desde Firebase (fallback Modo Trinchera).
  1. Postura Apple: Gatekeeper (spctl), SIP (csrutil), FileVault y Firewall ALF.
  2. Persistencia macOS: auditoría de plist en LaunchAgents y LaunchDaemons.
  3. Puertos TCP en escucha (lsof) y procesos activos en rutas volátiles (/tmp, /Users/Shared).
  4. Análisis de binarios sospechosos: SHA-256, Entropía de Shannon y cadenas.
  5. Envío de metadatos mínimos (LFPDPPP) al Webhook IA de Firebase y veredicto Gemini.
=============================================================================
"""

import os
import sys
import json
import math
import glob
import socket
import hashlib
import plistlib
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-macos.json"
CONSENT_FILE = "gepi-consent.json"
PRIVACY_NOTICE_VERSION = "2026.1"

DEFAULT_POLICY_MACOS = {
    "version": "3.0.0-macos-local",
    "fuente": "modo-trinchera-offline",
    "entropy_threshold": 7.2,
    "suspicious_paths": ["/tmp/", "/private/tmp/", "/users/shared/", "/var/tmp/"],
    "suspicious_strings": [
        "osascript -e", "curl -fsSL", "base64 -D", "chmod +x /tmp",
        "security find-generic-password", "launchctl load", "ignore previous instructions"
    ],
    "blacklist_hashes": [],
    "blacklist_ips": [],
    "indicaciones_ia": [
        "Modo Trinchera macOS: verificar Gatekeeper, SIP, Firewall y LaunchAgents no firmados."
    ]
}


def run_cmd(cmd, timeout=3.5):
    try:
        res = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
        return ((res.stdout or "") + "\n" + (res.stderr 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 macOS (v3.0)")
    print("Solo envía metadatos técnicos (Gatekeeper, SIP, LaunchAgents, hashes SHA-256).")
    print("NUNCA accede a Keychain, fotos, documentos personales ni contraseñas.")
    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_MACOS)
    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-macOS/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')})"
                return politica
        except Exception:
            pass

    return politica


def auditar_postura_macos():
    gatekeeper = run_cmd("spctl --status")
    sip = run_cmd("csrutil status")
    filevault = run_cmd("fdesetup status")
    fw = run_cmd("/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate")

    return {
        "gatekeeper_activo": "assessments enabled" in gatekeeper.lower(),
        "sip_activo": "enabled" in sip.lower(),
        "filevault_activo": "filevault is on" in filevault.lower(),
        "firewall_activo": "enabled" in fw.lower(),
        "detalle": {
            "gatekeeper": gatekeeper[:100],
            "sip": sip[:100],
            "firewall": fw[:100]
        }
    }


def auditar_launch_agents():
    dirs = [
        os.path.expanduser("~/Library/LaunchAgents"),
        "/Library/LaunchAgents",
        "/Library/LaunchDaemons"
    ]
    run_keys = []
    for d in dirs:
        for plist_path in glob.glob(os.path.join(d, "*.plist")):
            try:
                with open(plist_path, "rb") as f:
                    data = plistlib.load(f)
                label = str(data.get("Label") or os.path.basename(plist_path))
                if label.startswith("com.apple."):
                    continue
                prog_args = data.get("ProgramArguments") or ([data.get("Program")] if data.get("Program") else [])
                cmd_str = " ".join(str(x) for x in prog_args if x)
                run_keys.append({
                    "ubicacion": d,
                    "nombre": label,
                    "valor": cmd_str[:220]
                })
            except Exception:
                continue
    return run_keys[:30]


def auditar_puertos_macos():
    puertos = []
    out = run_cmd("lsof -iTCP -sTCP:LISTEN -P -n 2>/dev/null")
    for line in out.splitlines()[1:]:
        parts = line.split()
        if len(parts) < 9:
            continue
        name_field = parts[8]
        if ":" in name_field:
            port_str = name_field.rsplit(":", 1)[-1]
            if port_str.isdigit():
                puertos.append({"proceso": parts[0], "pid": parts[1], "puerto": int(port_str), "direccion": name_field})
    return puertos[:35]


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_macos(politica):
    rutas_vigiladas = [str(r).lower() for r in politica.get("suspicious_paths", DEFAULT_POLICY_MACOS["suspicious_paths"])]
    out = run_cmd("ps -Ao pid,args")
    procesos_temp = []
    binarios_sospechosos = []
    revisados = set()
    lines = out.splitlines()[1:]

    for line in lines:
        parts = line.strip().split(None, 1)
        if len(parts) < 2 or not parts[0].isdigit():
            continue
        pid = int(parts[0])
        cmdline = parts[1]
        cmd_l = cmdline.lower()
        exe_path = cmdline.split()[0]

        es_sospechoso = any(rv in cmd_l for rv in rutas_vigiladas) or ("osascript" in cmd_l and "curl" in cmd_l)
        if es_sospechoso:
            procesos_temp.append({"pid": pid, "nombre": os.path.basename(exe_path), "ruta": cmdline[:220]})
            if exe_path.lower() not in revisados and os.path.isfile(exe_path):
                revisados.add(exe_path.lower())
                res = analizar_archivo(exe_path, politica)
                res["pid"] = pid
                binarios_sospechosos.append(res)

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


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-macOS/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.")

    p = reporte["postura_macos"]
    score = 100
    if not p.get("gatekeeper_activo"):
        score -= 20
    if not p.get("sip_activo"):
        score -= 25
    if not p.get("firewall_activo"):
        score -= 10
    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-macos-offline",
        "resumen_ejecutivo": f"Evaluación macOS offline completada. Riesgo: {risk} ({score}/100).",
        "hallazgos": []
    }


def main():
    parser = argparse.ArgumentParser(description="GEPI Security Sentinel — Agente macOS v3.0")
    parser.add_argument("--output", "-o", default="gepi-report-macos.json", help="Archivo JSON de salida")
    parser.add_argument("--offline", action="store_true", help="Modo Trinchera Offline")
    parser.add_argument("--accept-privacy", action="store_true", help="Aceptar Aviso de Privacidad")
    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 — macOS AGENT v3.0")
    print("=" * 65)
    politica = cargar_politica_dinamica(args.cloud_url, offline=args.offline)
    postura = auditar_postura_macos()
    run_keys = auditar_launch_agents()
    puertos = auditar_puertos_macos()
    total_procs, procesos_temp, analisis_archivos = auditar_procesos_macos(politica)

    print(f"  [i] Mac: {socket.gethostname()} | Arch: {platform.machine()} | macOS {platform.mac_ver()[0]}")
    print(f"  [i] Gatekeeper: {postura['gatekeeper_activo']} | SIP: {postura['sip_activo']} | Firewall: {postura['firewall_activo']}")
    print(f"  [i] LaunchAgents de terceros: {len(run_keys)} | Puertos: {len(puertos)} | Procesos sospechosos: {len(procesos_temp)}")

    reporte = {
        "consentimiento_privacidad": True,
        "plataforma": "macos",
        "version_agente": "3.0.0-macos",
        "timestamp": datetime.now().isoformat(),
        "equipo": socket.gethostname(),
        "os": f"macOS {platform.mac_ver()[0]} ({platform.machine()})",
        "postura_macos": postura,
        "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())
