# threat-engine-agent/auditor.py import subprocess import json import logging from dotenv import load_dotenv import os import requests class FirewallAuditor: def __init__(self): """Ensures the NFT kernel state matches the LAPI's desired state.""" load_dotenv() self.table = "crowdsec" self.set_name = "0.0.0.0/0-cscli" self.API_KEY = os.getenv("BOUNCER_KEY") self.TRITON = "triton.beane.me" def get_remote_lapi_truth(self): url = f"https://{self.TRITON}:8081/v1/decisions" headers = {"X-Api-Key": self.API_KEY} try: r = requests.get( url, headers=headers, verify=True, timeout=(3.05, 10), # Connect timeout of 3s, Read timeout of 10s allow_redirects=False ) data = r.json() or [] if not isinstance(data, list): logging.error(f"Unexpected LAPI response type: {type(data)}") return set() truth_map = { d["value"]: d.get("duration") for d in data if isinstance(d, dict) and d.get("value") and d.get("origin") != "CAPI" } return truth_map except requests.exceptions.ConnectTimeout: logging.error("Connection to Triton timed out. Check if port 8081 is open on Triton's firewall.") return {} except Exception as e: logging.error(f"LAPI Sync Error: {e}") return {} def get_kernel_state(self): """Scans BOTH IPv4 and IPv6 sets in the crowdsec tables.""" all_ips = {} # Changed from set() to {} targets = [ {"family": "ip", "table": "crowdsec"}, {"family": "ip6", "table": "crowdsec6"} ] for target in targets: try: cmd = ["/usr/sbin/nft", "-j", "list", "table", target["family"], target["table"]] res = subprocess.run(cmd, capture_output=True, text=True, check=True) data = json.loads(res.stdout) for item in data.get('nftables', []): nft_set = item.get('set') if nft_set: elements = nft_set.get('elem', []) for e in elements: if isinstance(e, dict): inner = e.get('elem', e) if isinstance(inner, dict): val = inner.get('val') # NFT provides 'expires' in milliseconds expires_ms = inner.get('expires', 0) if val: all_ips[val] = expires_ms else: # Fallback if it's just a raw string IP all_ips[e] = 0 except subprocess.CalledProcessError: logging.debug(f"Table {target['table']} not found, skipped.") except Exception as e: logging.error(f"Kernel Table scan failed for {target['table']}: {e}") return all_ips def parse_duration(self, duration_str): """Converts CrowdSec strings like '14d', '24h', '4h' to seconds.""" try: units = {"d": 86400, "h": 3600, "m": 60, "s": 1} unit = duration_str[-1] value = int(duration_str[:-1]) return value * units.get(unit, 1) except: return 0 def heal(self): """Directly restarts the bouncer service.""" try: subprocess.run(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True) logging.info("Heal: Bouncer restarted successfully.") except subprocess.CalledProcessError as e: logging.error(f"Heal Failed: Could not restart bouncer: {e}") def reconcile(self): truth_map = self.get_remote_lapi_truth() reality_map = self.get_kernel_state() truth_set = set(truth_map.keys()) reality_set = set(reality_map.keys()) if truth_set != reality_set: logging.warning("Desync: IP Membership mismatch.") return False, len(reality_set) for ip, duration_str in truth_map.items(): siem_seconds = self.parse_duration(duration_str) kernel_seconds = reality_map.get(ip, 0) / 1000 # Convert ms to s if siem_seconds > 86400: # If SIEM target is > 24h if kernel_seconds < 18000: # And kernel has < 5h left logging.warning(f"Metadata Drift: {ip} needs {duration_str}, but kernel only has {int(kernel_seconds/3600)}h left.") return False, len(reality_map) return True, len(reality_map)