Merge branch 'agent-node'

This commit is contained in:
patrick committed 2026-01-26 03:10:21 +00:00
commit 5990dddf5a
8 files changed
+111 -45

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
BOUNCER_KEY=example
SERVER_NAME=Name
+2 -2
View File
@@ -1,5 +1,5 @@
logs/*.log
logs/*.log*
__pycache__/
.venv/
.env
*.json
*.history
+1
View File
@@ -41,6 +41,7 @@ threat-engine-agent/
```chmod +x main.py
mkdir logs
```
2. Systemd Integration:
```sudo cp systemd/threat-agent.service /etc/systemd/system/
+65 -5
View File
@@ -4,36 +4,96 @@ import time
import logging
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,
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'
)
################
#### 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.
"""
load_dotenv()
auditor = FirewallAuditor()
reporter = LocalStateReporter()
node_name = os.getenv("SERVER_NAME", "Unknown Node")
CHECK_INTERVAL = 600
logging.info("Threat Engine Agent initialized on Triton.")
print(f"[*] Agent started. Check interval: {CHECK_INTERVAL}s")
logging.info(f"Threat Engine Agent initialized on {node_name}.")
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...")
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) # Record the event in history
reporter.log_heal_event(count)
else:
logging.warning("Healing skipped to prevent flapping.")
else:
logging.info(f"Audit Success: {count} IPs in sync.")
print(f"[*] Sleeping for {CHECK_INTERVAL} seconds...")
time.sleep(CHECK_INTERVAL)
except KeyboardInterrupt:
+33 -30
View File
@@ -3,10 +3,14 @@
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"
@@ -29,28 +33,23 @@ class FirewallAuditor:
continue
val = d.get('value')
if val:
if val and ':' not in val:
ips.add(val)
logging.info(f"LAPI Parser: found {len(ips)} active bans (IPv4+IPv6).")
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
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 = set()
targets = [
{"family": "ip", "table": "crowdsec"},
{"family": "ip6", "table": "crowdsec6"}
]
for target in targets:
"""Scans ALL sets in the crowdsec table to find every blocked IP."""
try:
cmd = ["/usr/sbin/nft", "-j", "list", "table", target["family"], target["table"]]
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)
ips = set()
for item in data.get('nftables', []):
nft_set = item.get('set')
if nft_set:
@@ -61,16 +60,14 @@ class FirewallAuditor:
if isinstance(inner, dict):
val = inner.get('val')
if val:
all_ips.add(val)
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}")
ips.add(e)
return ips
return all_ips
except Exception as e:
logging.error(f"Kernel Table Scan Failed: {e}")
return set()
def heal(self):
"""Directly restarts the bouncer service."""
@@ -81,17 +78,23 @@ class FirewallAuditor:
logging.error(f"Heal Failed: Could not restart bouncer: {e}")
def reconcile(self):
truth = self.get_lapi_state()
reality = self.get_kernel_state()
truth_map = self.get_remote_lapi_truth()
reality_map = self.get_kernel_state()
if truth is None or reality is None:
return False, 0
truth_set = set(truth_map.keys())
reality_set = set(reality_map.keys())
missing_from_kernel = truth - reality
extra_in_kernel = reality - truth
if truth_set != reality_set:
logging.warning("Desync: IP Membership mismatch.")
return False, len(reality_set)
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)
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
return True, 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_map)
+2 -2
View File
@@ -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
View File
@@ -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-engine-agent/threat-agent-state.json"):
def __init__(self, state_file="/home/patrick/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,
+4 -4
View File
@@ -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