Merge branch 'agent-node'
This commit is contained in:
commit
5990dddf5a
8 files changed
+111
-45
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
BOUNCER_KEY=example
|
||||||
|
SERVER_NAME=Name
|
||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
logs/*.log
|
logs/*.log*
|
||||||
__pycache__/
|
__pycache__/
|
||||||
.venv/
|
.venv/
|
||||||
|
.env
|
||||||
*.json
|
*.json
|
||||||
*.history
|
|
||||||
@@ -41,6 +41,7 @@ threat-engine-agent/
|
|||||||
```chmod +x main.py
|
```chmod +x main.py
|
||||||
mkdir logs
|
mkdir logs
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Systemd Integration:
|
2. Systemd Integration:
|
||||||
|
|
||||||
```sudo cp systemd/threat-agent.service /etc/systemd/system/
|
```sudo cp systemd/threat-agent.service /etc/systemd/system/
|
||||||
|
|||||||
@@ -4,36 +4,96 @@ import time
|
|||||||
import logging
|
import logging
|
||||||
from auditor import FirewallAuditor
|
from auditor import FirewallAuditor
|
||||||
from reporter import LocalStateReporter
|
from reporter import LocalStateReporter
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
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'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
################
|
||||||
|
#### 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():
|
def main():
|
||||||
"""
|
"""
|
||||||
The Orchestrator: Links Audit findings to the State Reporter.
|
The Orchestrator: Links Audit findings to the State Reporter.
|
||||||
"""
|
"""
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
auditor = FirewallAuditor()
|
auditor = FirewallAuditor()
|
||||||
reporter = LocalStateReporter()
|
reporter = LocalStateReporter()
|
||||||
|
|
||||||
|
node_name = os.getenv("SERVER_NAME", "Unknown Node")
|
||||||
|
|
||||||
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(f"Threat Engine Agent initialized on {node_name}.")
|
||||||
|
|
||||||
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).")
|
||||||
|
|
||||||
|
history_file = reporter.state_file.replace(".json", ".history")
|
||||||
|
|
||||||
|
if should_heal(history_file, count):
|
||||||
|
logging.warning("Healing approved.")
|
||||||
auditor.heal()
|
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:
|
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:
|
||||||
|
|||||||
+33
-30
@@ -3,10 +3,14 @@
|
|||||||
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"
|
||||||
|
|
||||||
@@ -29,28 +33,23 @@ class FirewallAuditor:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
val = d.get('value')
|
val = d.get('value')
|
||||||
if val:
|
if val and ':' not in val:
|
||||||
ips.add(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
|
return ips
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"LAPI Query Failed: {e}")
|
logging.error(f"LAPI Sync Error: {e}")
|
||||||
return None
|
return {}
|
||||||
|
|
||||||
def get_kernel_state(self):
|
def get_kernel_state(self):
|
||||||
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
|
"""Scans ALL sets in the crowdsec table to find every blocked IP."""
|
||||||
all_ips = set()
|
|
||||||
targets = [
|
|
||||||
{"family": "ip", "table": "crowdsec"},
|
|
||||||
{"family": "ip6", "table": "crowdsec6"}
|
|
||||||
]
|
|
||||||
for target in targets:
|
|
||||||
try:
|
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)
|
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
||||||
data = json.loads(res.stdout)
|
data = json.loads(res.stdout)
|
||||||
|
|
||||||
|
ips = set()
|
||||||
for item in data.get('nftables', []):
|
for item in data.get('nftables', []):
|
||||||
nft_set = item.get('set')
|
nft_set = item.get('set')
|
||||||
if nft_set:
|
if nft_set:
|
||||||
@@ -61,16 +60,14 @@ class FirewallAuditor:
|
|||||||
if isinstance(inner, dict):
|
if isinstance(inner, dict):
|
||||||
val = inner.get('val')
|
val = inner.get('val')
|
||||||
if val:
|
if val:
|
||||||
all_ips.add(val)
|
ips.add(val)
|
||||||
else:
|
else:
|
||||||
all_ips.add(e)
|
ips.add(e)
|
||||||
except subprocess.CalledProcessError:
|
return ips
|
||||||
# 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
|
except Exception as e:
|
||||||
|
logging.error(f"Kernel Table Scan Failed: {e}")
|
||||||
|
return set()
|
||||||
|
|
||||||
def heal(self):
|
def heal(self):
|
||||||
"""Directly restarts the bouncer service."""
|
"""Directly restarts the bouncer service."""
|
||||||
@@ -81,17 +78,23 @@ 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_map = self.get_remote_lapi_truth()
|
||||||
reality = self.get_kernel_state()
|
reality_map = self.get_kernel_state()
|
||||||
|
|
||||||
if truth is None or reality is None:
|
truth_set = set(truth_map.keys())
|
||||||
return False, 0
|
reality_set = set(reality_map.keys())
|
||||||
|
|
||||||
missing_from_kernel = truth - reality
|
if truth_set != reality_set:
|
||||||
extra_in_kernel = reality - truth
|
logging.warning("Desync: IP Membership mismatch.")
|
||||||
|
return False, len(reality_set)
|
||||||
|
|
||||||
if missing_from_kernel or extra_in_kernel:
|
for ip, duration_str in truth_map.items():
|
||||||
logging.warning(f"Desync Details: Missing from Kernel: {list(missing_from_kernel)[:5]}... Extra in Kernel: {list(extra_in_kernel)[:5]}...")
|
siem_seconds = self.parse_duration(duration_str)
|
||||||
return False, len(reality)
|
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
@@ -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
@@ -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-engine-agent/threat-agent-state.json"):
|
def __init__(self, state_file="/home/patrick/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,
|
||||||
|
|||||||
@@ -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
|
||||||
Reference in new issue
Block a user