feat: implement self-healing auditor with remote LAPI sync

This commit is contained in:
patrick committed 2026-01-23 10:58:35 -05:00
1 parent 848a29543d
commit 672e821738
6 files changed
+56 -12

No files matched your search

+2
View File
@@ -1,4 +1,6 @@
logs/*.log logs/*.log
__pycache__/ __pycache__/
.venv/ .venv/
.env
*.json *.json
*.history
+7 -3
View File
@@ -8,7 +8,7 @@ from reporter import LocalStateReporter
logging.basicConfig( logging.basicConfig(
level=logging.INFO, level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='/home/patrick/threat-engine-agent/logs/threat-agent.log' filename='/root/threat-engine-agent/logs/threat-agent.log'
) )
def main(): def main():
@@ -19,14 +19,17 @@ def main():
reporter = LocalStateReporter() reporter = LocalStateReporter()
CHECK_INTERVAL = 600 CHECK_INTERVAL = 600
logging.info("Threat Engine Agent initialized on Triton.") print(f"[*] Agent started. Check interval: {CHECK_INTERVAL}s")
logging.info("Threat Engine Agent initialized on Zephyrus.")
while True: while True:
try: try:
is_synced, count = auditor.reconcile() is_synced, count = auditor.reconcile()
reporter.update_status(is_synced, count) reporter.update_status(is_synced, count)
status_msg = f"Audit Success: {count} IPs in sync." if is_synced else f"DESYNC: {count} in kernel. Healing..."
print(f"[+] {status_msg}") # This will show up in your terminal!
if not is_synced: if not is_synced:
logging.warning(f"Desync detected ({count} IPs in kernel). Healing...") logging.warning(f"Desync detected ({count} IPs in kernel). Healing...")
auditor.heal() auditor.heal()
@@ -34,6 +37,7 @@ def main():
else: else:
logging.info(f"Audit Success: {count} IPs in sync.") logging.info(f"Audit Success: {count} IPs in sync.")
print(f"[*] Sleeping for {CHECK_INTERVAL} seconds...")
time.sleep(CHECK_INTERVAL) time.sleep(CHECK_INTERVAL)
except KeyboardInterrupt: except KeyboardInterrupt:
+39 -1
View File
@@ -3,12 +3,18 @@
import subprocess import subprocess
import json import json
import logging import logging
from dotenv import load_dotenv
import os
import requests
class FirewallAuditor: class FirewallAuditor:
def __init__(self): def __init__(self):
"""Ensures the NFT kernel state matches the LAPI's desired state.""" """Ensures the NFT kernel state matches the LAPI's desired state."""
load_dotenv()
self.table = "crowdsec" self.table = "crowdsec"
self.set_name = "0.0.0.0/0-cscli" self.set_name = "0.0.0.0/0-cscli"
self.API_KEY = os.getenv("BOUNCER_KEY")
self.TRITON = "triton.beane.me"
def get_lapi_state(self): def get_lapi_state(self):
"""Precision parser: Only harvests IPs from active remediation decisions.""" """Precision parser: Only harvests IPs from active remediation decisions."""
@@ -38,6 +44,36 @@ class FirewallAuditor:
logging.error(f"LAPI Query Failed: {e}") logging.error(f"LAPI Query Failed: {e}")
return None return None
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:
# We add a shorter timeout and explicitly disable redirects
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 {}
total_items_received = len(new_decisions)
new_decisions = data.get('new') or []
unique_ips = {d['value'] for d in new_decisions if d.get('origin') != 'CAPI' and ':' not in d['value']}
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): def get_kernel_state(self):
"""Scans ALL sets in the crowdsec table to find every blocked IP.""" """Scans ALL sets in the crowdsec table to find every blocked IP."""
try: try:
@@ -74,9 +110,11 @@ class FirewallAuditor:
logging.error(f"Heal Failed: Could not restart bouncer: {e}") logging.error(f"Heal Failed: Could not restart bouncer: {e}")
def reconcile(self): def reconcile(self):
truth = self.get_lapi_state() truth = self.get_remote_lapi_truth()
reality = self.get_kernel_state() 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: if truth is None or reality is None:
return False, 0 return False, 0
+2 -2
View File
@@ -1,7 +1,7 @@
agent: agent:
node_name: "triton" node_name: "zephyrus"
check_interval: 600 # 10 minutes check_interval: 600 # 10 minutes
log_path: "/home/patrick/threat-engine-agent/logs/threat-agent.log" log_path: "/root/threat-engine-agent/logs/threat-agent.log"
enforcement: enforcement:
table: "crowdsec" table: "crowdsec"
+2 -2
View File
@@ -10,7 +10,7 @@ class LocalStateReporter:
Manages the health manifest on Triton. Manages the health manifest on Triton.
Acts as the 'Black Box' recorder for Argus to query. Acts as the 'Black Box' recorder for Argus to query.
""" """
def __init__(self, state_file="/home/patrick/threat-agent-state.json"): def __init__(self, state_file="/root/threat-engine-agent/threat-agent-state.json"):
self.state_file = state_file self.state_file = state_file
# Ensure the directory is writable # Ensure the directory is writable
os.makedirs(os.path.dirname(os.path.abspath(self.state_file)), exist_ok=True) os.makedirs(os.path.dirname(os.path.abspath(self.state_file)), exist_ok=True)
@@ -20,7 +20,7 @@ class LocalStateReporter:
Writes the current health snapshot to a JSON file. Writes the current health snapshot to a JSON file.
""" """
status_data = { status_data = {
"node": "triton", "node": "zephyrus",
"last_check": datetime.now().isoformat(), "last_check": datetime.now().isoformat(),
"status": "HEALTHY" if is_synced else "DESYNC_DETECTED", "status": "HEALTHY" if is_synced else "DESYNC_DETECTED",
"is_synced": is_synced, "is_synced": is_synced,
+4 -4
View File
@@ -7,13 +7,13 @@ Type=simple
User=root User=root
Group=root Group=root
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Environment="HOME=/home/patrick" Environment="HOME=/root"
WorkingDirectory=/home/patrick/threat-engine-agent WorkingDirectory=/root/threat-engine-agent
ExecStart=/usr/bin/python3 agent.py ExecStart=/usr/bin/python3 agent.py
Restart=always Restart=always
RestartSec=10 RestartSec=10
StandardOutput=append:/home/patrick/threat-engine-agent/logs/threat-agent.log StandardOutput=append:/root/threat-engine-agent/logs/threat-agent.log
StandardError=append:/home/patrick/threat-engine-agent/logs/threat-agent.log StandardError=append:/root/threat-engine-agent/logs/threat-agent.log
[Install] [Install]
WantedBy=multi-user.target WantedBy=multi-user.target