fix(auditor): heal on decision-duration drift, not just IP membership/count

This commit is contained in:
patrick committed 2026-02-23 22:20:16 -05:00
1 parent 480eea8095
commit 28267a0cf4
2 files changed
+101 -11

No files matched your search

+65 -11
View File
@@ -4,6 +4,7 @@ import subprocess
import json
import logging
import hashlib
import datetime
try:
from dotenv import load_dotenv
except ImportError:
@@ -28,7 +29,14 @@ class FirewallAuditor:
for decision in self._extract_decisions(data):
val = decision.get("value")
if val and decision.get("origin") != "CAPI":
truth_map[val] = decision.get("duration")
parsed = self._normalize_truth_decision(decision)
existing = truth_map.get(val)
if existing is None:
truth_map[val] = parsed
else:
# Keep the decision with the furthest expected expiry.
if self._decision_rank(parsed) > self._decision_rank(existing):
truth_map[val] = parsed
logging.info(f"LAPI Local Parser: Found {len(truth_map)} active bans.")
return truth_map
@@ -36,6 +44,27 @@ class FirewallAuditor:
logging.error(f"Failed to get LAPI truth: {e}")
return {}
def _normalize_truth_decision(self, decision):
return {
"duration": decision.get("duration"),
"until_epoch": self._parse_until_epoch(decision.get("until")),
}
def _decision_rank(self, decision_meta):
if decision_meta.get("until_epoch"):
return decision_meta["until_epoch"]
return self.parse_duration(decision_meta.get("duration"))
def _parse_until_epoch(self, until_str):
if not until_str:
return None
try:
normalized = str(until_str).replace("Z", "+00:00")
dt = datetime.datetime.fromisoformat(normalized)
return dt.timestamp()
except Exception:
return None
def _extract_decisions(self, payload):
"""
Supports both:
@@ -111,15 +140,40 @@ class FirewallAuditor:
return all_ips
def parse_duration(self, duration_str):
"""Converts CrowdSec strings like '14d', '24h', '4h' to seconds."""
"""Converts CrowdSec strings like '14d', '24h', '4h', '1h30m' to seconds."""
try:
if not duration_str:
return 0
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:
total = 0
number = ""
for ch in str(duration_str).strip().lower():
if ch.isdigit():
number += ch
continue
if ch in units and number:
total += int(number) * units[ch]
number = ""
else:
return 0
return total
except Exception:
return 0
def _expected_remaining_seconds(self, decision_meta, now_epoch):
until_epoch = decision_meta.get("until_epoch")
if until_epoch:
return max(0, int(until_epoch - now_epoch))
return self.parse_duration(decision_meta.get("duration"))
def _has_ttl_drift(self, expected_seconds, kernel_seconds):
if expected_seconds <= 21600:
return False
allowed_shortfall = max(7200, int(expected_seconds * 0.40))
return kernel_seconds + allowed_shortfall < expected_seconds
def heal(self):
"""Directly restarts the bouncer service."""
try:
@@ -154,14 +208,14 @@ class FirewallAuditor:
return False, len(reality_set), drift
metadata_drift = []
now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
for ip, duration_str in truth_map.items():
siem_seconds = self.parse_duration(duration_str)
for ip, decision_meta in truth_map.items():
siem_seconds = self._expected_remaining_seconds(decision_meta, now_epoch)
kernel_seconds = reality_map.get(ip, 0) / 1000 # Convert ms to s
if siem_seconds > 86400: # If SIEM target is > 24h
if kernel_seconds < 18000: # And kernel has < 5h left
metadata_drift.append(ip)
if self._has_ttl_drift(siem_seconds, kernel_seconds):
metadata_drift.append(ip)
if metadata_drift:
drift = {