Files
threat-engine-agent/auditor.py
T

105 lines
3.8 KiB
Python

# 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/stream?startup=true"
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 {}
new_decisions = data.get('new') or []
unique_ips = {d['value'] for d in new_decisions if d.get('origin') != 'CAPI'}
return unique_ips
except requests.exceptions.ConnectTimeout:
logging.error("Connection to Triton timed out. Check if port 8081 is open on Triton's firewall.")
return set()
except Exception as e:
logging.error(f"LAPI Sync Error: {e}")
return set()
def get_kernel_state(self):
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
all_ips = set()
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')
if val:
all_ips.add(val)
else:
all_ips.add(e)
except subprocess.CalledProcessError:
# This happens if a node doesn't have IPv6 enabled/initialized
logging.debug(f"Table {target['table']} not found, skipping.")
except Exception as e:
logging.error(f"Kernel Table Scan Failed for {target['table']}: {e}")
return all_ips
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 = self.get_remote_lapi_truth()
reality = self.get_kernel_state()
logging.info(f"Received {len(truth)} IPs from CrowdSec, and {len(reality)} IPs from the firewall (nft)")
if truth is None or reality is None:
return False, 0
missing_from_kernel = truth - reality
extra_in_kernel = reality - truth
if missing_from_kernel or extra_in_kernel:
logging.warning(f"Desync Details: Missing from Kernel: {list(missing_from_kernel)[:5]}... Extra in Kernel: {list(extra_in_kernel)[:5]}...")
return False, len(reality)
return True, len(reality)