feat: add TTL-aware drift detection and stabilize healing
This commit is contained in:
1 parent
c23f2b7a47
commit
14c5ac758e
3 files changed
+103
-28
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
logs/*.log
|
logs/*.log*
|
||||||
__pycache__/
|
__pycache__/
|
||||||
.venv/
|
.venv/
|
||||||
.env
|
.env
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from auditor import FirewallAuditor
|
|||||||
from reporter import LocalStateReporter
|
from reporter import LocalStateReporter
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import os
|
import os
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
@@ -13,6 +14,48 @@ logging.basicConfig(
|
|||||||
filename='/root/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.
|
||||||
@@ -37,9 +80,16 @@ def main():
|
|||||||
print(f"[+] {status_msg}") # This will show up in your terminal!
|
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).")
|
||||||
auditor.heal()
|
|
||||||
reporter.log_heal_event(count) # Record the event in history
|
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:
|
else:
|
||||||
logging.info(f"Audit Success: {count} IPs in sync.")
|
logging.info(f"Audit Success: {count} IPs in sync.")
|
||||||
|
|
||||||
|
|||||||
+49
-24
@@ -17,7 +17,7 @@ class FirewallAuditor:
|
|||||||
self.TRITON = "triton.beane.me"
|
self.TRITON = "triton.beane.me"
|
||||||
|
|
||||||
def get_remote_lapi_truth(self):
|
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}
|
headers = {"X-Api-Key": self.API_KEY}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -29,23 +29,32 @@ class FirewallAuditor:
|
|||||||
allow_redirects=False
|
allow_redirects=False
|
||||||
)
|
)
|
||||||
|
|
||||||
data = r.json() or {}
|
data = r.json() or []
|
||||||
|
|
||||||
new_decisions = data.get('new') or []
|
if not isinstance(data, list):
|
||||||
unique_ips = {d['value'] for d in new_decisions if d.get('origin') != 'CAPI'}
|
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:
|
except requests.exceptions.ConnectTimeout:
|
||||||
logging.error("Connection to Triton timed out. Check if port 8081 is open on Triton's firewall.")
|
logging.error("Connection to Triton timed out. Check if port 8081 is open on Triton's firewall.")
|
||||||
return set()
|
return {}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"LAPI Sync Error: {e}")
|
logging.error(f"LAPI Sync Error: {e}")
|
||||||
return set()
|
return {}
|
||||||
|
|
||||||
def get_kernel_state(self):
|
def get_kernel_state(self):
|
||||||
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
|
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
|
||||||
all_ips = set()
|
all_ips = {} # Changed from set() to {}
|
||||||
targets = [
|
targets = [
|
||||||
{"family": "ip", "table": "crowdsec"},
|
{"family": "ip", "table": "crowdsec"},
|
||||||
{"family": "ip6", "table": "crowdsec6"}
|
{"family": "ip6", "table": "crowdsec6"}
|
||||||
@@ -65,18 +74,30 @@ class FirewallAuditor:
|
|||||||
inner = e.get('elem', e)
|
inner = e.get('elem', e)
|
||||||
if isinstance(inner, dict):
|
if isinstance(inner, dict):
|
||||||
val = inner.get('val')
|
val = inner.get('val')
|
||||||
|
# NFT provides 'expires' in milliseconds
|
||||||
|
expires_ms = inner.get('expires', 0)
|
||||||
if val:
|
if val:
|
||||||
all_ips.add(val)
|
all_ips[val] = expires_ms
|
||||||
else:
|
else:
|
||||||
all_ips.add(e)
|
# Fallback if it's just a raw string IP
|
||||||
|
all_ips[e] = 0
|
||||||
except subprocess.CalledProcessError:
|
except subprocess.CalledProcessError:
|
||||||
# This happens if a node doesn't have IPv6 enabled/initialized
|
logging.debug(f"Table {target['table']} not found, skipped.")
|
||||||
logging.debug(f"Table {target['table']} not found, skipping.")
|
|
||||||
except Exception as e:
|
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
|
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):
|
def heal(self):
|
||||||
"""Directly restarts the bouncer service."""
|
"""Directly restarts the bouncer service."""
|
||||||
try:
|
try:
|
||||||
@@ -86,19 +107,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_remote_lapi_truth()
|
truth_map = self.get_remote_lapi_truth()
|
||||||
reality = self.get_kernel_state()
|
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:
|
if truth_set != reality_set:
|
||||||
return False, 0
|
logging.warning("Desync: IP Membership mismatch.")
|
||||||
|
return False, len(reality_set)
|
||||||
|
|
||||||
missing_from_kernel = truth - reality
|
for ip, duration_str in truth_map.items():
|
||||||
extra_in_kernel = reality - truth
|
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:
|
if siem_seconds > 86400: # If SIEM target is > 24h
|
||||||
logging.warning(f"Desync Details: Missing from Kernel: {list(missing_from_kernel)[:5]}... Extra in Kernel: {list(extra_in_kernel)[:5]}...")
|
if kernel_seconds < 18000: # And kernel has < 5h left
|
||||||
return False, len(reality)
|
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)
|
||||||
Reference in new issue
Block a user