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
+49
-24
@@ -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)
|
||||
Reference in new issue
Block a user