feat: implement self-healing auditor with remote LAPI sync
This commit is contained in:
1 parent
848a29543d
commit
672e821738
6 files changed
+56
-12
No files matched your search
@@ -1,4 +1,6 @@
|
||||
logs/*.log
|
||||
__pycache__/
|
||||
.venv/
|
||||
.env
|
||||
*.json
|
||||
*.history
|
||||
@@ -8,7 +8,7 @@ from reporter import LocalStateReporter
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
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():
|
||||
@@ -19,14 +19,17 @@ def main():
|
||||
reporter = LocalStateReporter()
|
||||
|
||||
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:
|
||||
try:
|
||||
is_synced, count = auditor.reconcile()
|
||||
|
||||
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:
|
||||
logging.warning(f"Desync detected ({count} IPs in kernel). Healing...")
|
||||
auditor.heal()
|
||||
@@ -34,6 +37,7 @@ def main():
|
||||
else:
|
||||
logging.info(f"Audit Success: {count} IPs in sync.")
|
||||
|
||||
print(f"[*] Sleeping for {CHECK_INTERVAL} seconds...")
|
||||
time.sleep(CHECK_INTERVAL)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
+39
-1
@@ -3,12 +3,18 @@
|
||||
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_lapi_state(self):
|
||||
"""Precision parser: Only harvests IPs from active remediation decisions."""
|
||||
@@ -38,6 +44,36 @@ class FirewallAuditor:
|
||||
logging.error(f"LAPI Query Failed: {e}")
|
||||
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):
|
||||
"""Scans ALL sets in the crowdsec table to find every blocked IP."""
|
||||
try:
|
||||
@@ -74,9 +110,11 @@ class FirewallAuditor:
|
||||
logging.error(f"Heal Failed: Could not restart bouncer: {e}")
|
||||
|
||||
def reconcile(self):
|
||||
truth = self.get_lapi_state()
|
||||
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
|
||||
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
agent:
|
||||
node_name: "triton"
|
||||
node_name: "zephyrus"
|
||||
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:
|
||||
table: "crowdsec"
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ class LocalStateReporter:
|
||||
Manages the health manifest on Triton.
|
||||
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
|
||||
# Ensure the directory is writable
|
||||
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.
|
||||
"""
|
||||
status_data = {
|
||||
"node": "triton",
|
||||
"node": "zephyrus",
|
||||
"last_check": datetime.now().isoformat(),
|
||||
"status": "HEALTHY" if is_synced else "DESYNC_DETECTED",
|
||||
"is_synced": is_synced,
|
||||
|
||||
@@ -7,13 +7,13 @@ Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
Environment="HOME=/home/patrick"
|
||||
WorkingDirectory=/home/patrick/threat-engine-agent
|
||||
Environment="HOME=/root"
|
||||
WorkingDirectory=/root/threat-engine-agent
|
||||
ExecStart=/usr/bin/python3 agent.py
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
StandardOutput=append:/home/patrick/threat-engine-agent/logs/threat-agent.log
|
||||
StandardError=append:/home/patrick/threat-engine-agent/logs/threat-agent.log
|
||||
StandardOutput=append:/root/threat-engine-agent/logs/threat-agent.log
|
||||
StandardError=append:/root/threat-engine-agent/logs/threat-agent.log
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Reference in new issue
Block a user