From 672e821738f5aa00bba1b7d5f43daef95f2d75cf Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 23 Jan 2026 10:58:35 -0500 Subject: [PATCH 1/8] feat: implement self-healing auditor with remote LAPI sync --- .gitignore | 2 ++ agent.py | 10 ++++++--- auditor.py | 40 +++++++++++++++++++++++++++++++++++- config.yaml | 4 ++-- reporter.py | 4 ++-- systemd/threat-agent.service | 8 ++++---- 6 files changed, 56 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index e2ec125..5a79364 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ logs/*.log __pycache__/ .venv/ +.env *.json +*.history diff --git a/agent.py b/agent.py index 891dabb..2930e71 100644 --- a/agent.py +++ b/agent.py @@ -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: diff --git a/auditor.py b/auditor.py index 077d0bf..d487696 100644 --- a/auditor.py +++ b/auditor.py @@ -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 diff --git a/config.yaml b/config.yaml index d8045ce..c0718dc 100644 --- a/config.yaml +++ b/config.yaml @@ -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" diff --git a/reporter.py b/reporter.py index 2dd18f4..4f5cd86 100644 --- a/reporter.py +++ b/reporter.py @@ -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, diff --git a/systemd/threat-agent.service b/systemd/threat-agent.service index fece94d..eab39fe 100644 --- a/systemd/threat-agent.service +++ b/systemd/threat-agent.service @@ -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 From 4446b5c3d81af138b1cacdc4f380b06516e578d6 Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 23 Jan 2026 11:01:53 -0500 Subject: [PATCH 2/8] docs: README cleanup --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5e12402..536fb12 100644 --- a/README.md +++ b/README.md @@ -40,14 +40,17 @@ threat-engine-agent/ ```chmod +x main.py mkdir logs ``` + 2. Systemd Integration: ```sudo cp systemd/threat-agent.service /etc/systemd/system/ sudo systemctl daemon-reload -sudo systemctl enable --now threat-agent``` +sudo systemctl enable --now threat-agent +``` 3. Monitoring: ```# Watch the auditor work in real-time -tail -f logs/threat-agent.log``` +tail -f logs/threat-agent.log +``` ## 🔍 Troubleshooting From b48dabed8504986a97bbfb49a1c09596d0fc213e Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 23 Jan 2026 11:20:07 -0500 Subject: [PATCH 3/8] fix: remove errant line, not used --- auditor.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/auditor.py b/auditor.py index d487696..dc48e52 100644 --- a/auditor.py +++ b/auditor.py @@ -60,9 +60,7 @@ class FirewallAuditor: 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 From 4e3ac06c1cf965fec46769dc6a45b54c2cb4c92c Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 23 Jan 2026 11:25:54 -0500 Subject: [PATCH 4/8] feat: add .env.example template for deployment --- .env.example | 1 + 1 file changed, 1 insertion(+) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..2147eda --- /dev/null +++ b/.env.example @@ -0,0 +1 @@ +BOUNCER_KEY=example From f7e7b8f100de8a7c57b056776e480edb21f4259e Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 23 Jan 2026 11:36:21 -0500 Subject: [PATCH 5/8] feat: add node name to .env --- agent.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/agent.py b/agent.py index 2930e71..3b8ea5a 100644 --- a/agent.py +++ b/agent.py @@ -4,6 +4,8 @@ import time import logging from auditor import FirewallAuditor from reporter import LocalStateReporter +from dotenv import load_dotenv +import os logging.basicConfig( level=logging.INFO, @@ -15,12 +17,16 @@ def main(): """ The Orchestrator: Links Audit findings to the State Reporter. """ + load_dotenv() + auditor = FirewallAuditor() reporter = LocalStateReporter() + node_name = os.getenv("SERVER_NAME", "Unknown Node") + CHECK_INTERVAL = 600 print(f"[*] Agent started. Check interval: {CHECK_INTERVAL}s") - logging.info("Threat Engine Agent initialized on Zephyrus.") + logging.info(f"Threat Engine Agent initialized on {node_name}.") while True: try: From 884860ab17a4bf9e14933dae0840f84714dbeeba Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 23 Jan 2026 11:42:44 -0500 Subject: [PATCH 6/8] update: add SERVER_NAME to .env.example --- .env.example | 1 + 1 file changed, 1 insertion(+) diff --git a/.env.example b/.env.example index 2147eda..7eb43c4 100644 --- a/.env.example +++ b/.env.example @@ -1 +1,2 @@ BOUNCER_KEY=example +SERVER_NAME=Name From c23f2b7a472b0a43c6fb35fa960023fca5bf3405 Mon Sep 17 00:00:00 2001 From: patrick Date: Fri, 23 Jan 2026 13:28:35 -0500 Subject: [PATCH 7/8] fix: dual-stack ipv6 audit and cleanup unused lapi function --- auditor.py | 84 ++++++++++++++++++++---------------------------------- 1 file changed, 31 insertions(+), 53 deletions(-) diff --git a/auditor.py b/auditor.py index dc48e52..5b3e9e5 100644 --- a/auditor.py +++ b/auditor.py @@ -16,40 +16,11 @@ class FirewallAuditor: 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.""" - try: - res = subprocess.run(["/usr/bin/cscli", "decisions", "list", "-a", "-o", "json"], - capture_output=True, text=True, check=True) - data = json.loads(res.stdout) or [] - - ips = set() - for item in data: - if item.get('remediation') is True: - for d in item.get('decisions', []): - duration = d.get('duration', '') - if d.get('type') != 'ban': - continue - - if duration.startswith('-'): - continue - - val = d.get('value') - if val and ':' not in val: - ips.add(val) - - logging.info(f"LAPI Parser (IPv4-Only) found {len(ips)} active bans.") - return ips - except Exception as e: - 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, @@ -61,7 +32,7 @@ class FirewallAuditor: data = r.json() or {} 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']} + unique_ips = {d['value'] for d in new_decisions if d.get('origin') != 'CAPI'} return unique_ips @@ -73,31 +44,38 @@ class FirewallAuditor: return set() def get_kernel_state(self): - """Scans ALL sets in the crowdsec table to find every blocked IP.""" - try: - cmd = ["/usr/sbin/nft", "-j", "list", "table", "ip", "crowdsec"] - res = subprocess.run(cmd, capture_output=True, text=True, check=True) - data = json.loads(res.stdout) + """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) - ips = set() - 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: - ips.add(val) - else: - ips.add(e) - return ips + 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}") - except Exception as e: - logging.error(f"Kernel Table Scan Failed: {e}") - return set() + return all_ips def heal(self): """Directly restarts the bouncer service.""" From 14c5ac758eb648553de16d9a481a3204e5361af3 Mon Sep 17 00:00:00 2001 From: patrick Date: Sun, 25 Jan 2026 21:32:02 -0500 Subject: [PATCH 8/8] feat: add TTL-aware drift detection and stabilize healing --- .gitignore | 2 +- agent.py | 56 ++++++++++++++++++++++++++++++++++++++--- auditor.py | 73 ++++++++++++++++++++++++++++++++++++------------------ 3 files changed, 103 insertions(+), 28 deletions(-) diff --git a/.gitignore b/.gitignore index 5a79364..cad96ca 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -logs/*.log +logs/*.log* __pycache__/ .venv/ .env diff --git a/agent.py b/agent.py index 3b8ea5a..1b696ac 100644 --- a/agent.py +++ b/agent.py @@ -6,6 +6,7 @@ from auditor import FirewallAuditor from reporter import LocalStateReporter from dotenv import load_dotenv import os +from datetime import datetime, timedelta logging.basicConfig( level=logging.INFO, @@ -13,6 +14,48 @@ logging.basicConfig( filename='/root/threat-engine-agent/logs/threat-agent.log' ) +################ +#### Helpers ### +################ + +def should_heal(history_file, current_count, min_interval=900): + """ + Prevents heal flapping by suppressing repeated no-op heals. + """ + try: + if not os.path.exists(history_file): + return True + + with open(history_file) as f: + lines = [l.strip() for l in f.readlines() if "HEAL:" in l] + + if not lines: + return True + + last = lines[-1] + ts_str, msg = last.split(" - ", 1) + last_time = datetime.fromisoformat(ts_str) + last_count = int(msg.split("desync of")[1].split("IPs")[0]) + + # If healed recently AND nothing changed, suppress + if datetime.now() - last_time < timedelta(seconds=min_interval): + if last_count == current_count: + logging.warning( + f"Heal suppressed (recent identical heal: {last_count} IPs)" + ) + return False + + return True + + except Exception as e: + logging.error(f"Heal gate failed open: {e}") + return True + + +################ +##### Main ##### +################ + def main(): """ The Orchestrator: Links Audit findings to the State Reporter. @@ -37,9 +80,16 @@ def main(): 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() - reporter.log_heal_event(count) # Record the event in history + logging.warning(f"Desync detected ({count} IPs in kernel).") + + history_file = reporter.state_file.replace(".json", ".history") + + if should_heal(history_file, count): + logging.warning("Healing approved.") + auditor.heal() + reporter.log_heal_event(count) + else: + logging.warning("Healing skipped to prevent flapping.") else: logging.info(f"Audit Success: {count} IPs in sync.") diff --git a/auditor.py b/auditor.py index 5b3e9e5..2c2b645 100644 --- a/auditor.py +++ b/auditor.py @@ -17,7 +17,7 @@ class FirewallAuditor: self.TRITON = "triton.beane.me" def get_remote_lapi_truth(self): - url = f"https://{self.TRITON}:8081/v1/decisions/stream?startup=true" + url = f"https://{self.TRITON}:8081/v1/decisions" headers = {"X-Api-Key": self.API_KEY} try: @@ -29,23 +29,32 @@ class FirewallAuditor: allow_redirects=False ) - data = r.json() or {} + data = r.json() or [] - new_decisions = data.get('new') or [] - unique_ips = {d['value'] for d in new_decisions if d.get('origin') != 'CAPI'} + if not isinstance(data, list): + logging.error(f"Unexpected LAPI response type: {type(data)}") + return set() - return unique_ips + 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 set() + return {} except Exception as e: logging.error(f"LAPI Sync Error: {e}") - return set() + return {} def get_kernel_state(self): """Scans BOTH IPv4 and IPv6 sets in the crowdsec tables.""" - all_ips = set() + all_ips = {} # Changed from set() to {} targets = [ {"family": "ip", "table": "crowdsec"}, {"family": "ip6", "table": "crowdsec6"} @@ -65,18 +74,30 @@ class FirewallAuditor: 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.add(val) + all_ips[val] = expires_ms else: - all_ips.add(e) + # Fallback if it's just a raw string IP + all_ips[e] = 0 except subprocess.CalledProcessError: - # This happens if a node doesn't have IPv6 enabled/initialized - logging.debug(f"Table {target['table']} not found, skipping.") + logging.debug(f"Table {target['table']} not found, skipped.") except Exception as e: - logging.error(f"Kernel Table Scan Failed for {target['table']}: {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: @@ -86,19 +107,23 @@ class FirewallAuditor: logging.error(f"Heal Failed: Could not restart bouncer: {e}") def reconcile(self): - truth = self.get_remote_lapi_truth() - reality = self.get_kernel_state() + truth_map = self.get_remote_lapi_truth() + reality_map = self.get_kernel_state() - logging.info(f"Received {len(truth)} IPs from CrowdSec, and {len(reality)} IPs from the firewall (nft)") + truth_set = set(truth_map.keys()) + reality_set = set(reality_map.keys()) - if truth is None or reality is None: - return False, 0 + if truth_set != reality_set: + logging.warning("Desync: IP Membership mismatch.") + return False, len(reality_set) - missing_from_kernel = truth - reality - extra_in_kernel = reality - truth + 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 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) + 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) + return True, len(reality_map)