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 json
import logging import logging
import hashlib import hashlib
import datetime
try: try:
from dotenv import load_dotenv from dotenv import load_dotenv
except ImportError: except ImportError:
@@ -28,7 +29,14 @@ class FirewallAuditor:
for decision in self._extract_decisions(data): for decision in self._extract_decisions(data):
val = decision.get("value") val = decision.get("value")
if val and decision.get("origin") != "CAPI": 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.") logging.info(f"LAPI Local Parser: Found {len(truth_map)} active bans.")
return truth_map return truth_map
@@ -36,6 +44,27 @@ class FirewallAuditor:
logging.error(f"Failed to get LAPI truth: {e}") logging.error(f"Failed to get LAPI truth: {e}")
return {} 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): def _extract_decisions(self, payload):
""" """
Supports both: Supports both:
@@ -111,15 +140,40 @@ class FirewallAuditor:
return all_ips return all_ips
def parse_duration(self, duration_str): 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: try:
if not duration_str:
return 0
units = {"d": 86400, "h": 3600, "m": 60, "s": 1} units = {"d": 86400, "h": 3600, "m": 60, "s": 1}
unit = duration_str[-1] total = 0
value = int(duration_str[:-1]) number = ""
return value * units.get(unit, 1) for ch in str(duration_str).strip().lower():
except: 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 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): def heal(self):
"""Directly restarts the bouncer service.""" """Directly restarts the bouncer service."""
try: try:
@@ -154,14 +208,14 @@ class FirewallAuditor:
return False, len(reality_set), drift return False, len(reality_set), drift
metadata_drift = [] metadata_drift = []
now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
for ip, duration_str in truth_map.items(): for ip, decision_meta in truth_map.items():
siem_seconds = self.parse_duration(duration_str) siem_seconds = self._expected_remaining_seconds(decision_meta, now_epoch)
kernel_seconds = reality_map.get(ip, 0) / 1000 # Convert ms to s kernel_seconds = reality_map.get(ip, 0) / 1000 # Convert ms to s
if siem_seconds > 86400: # If SIEM target is > 24h if self._has_ttl_drift(siem_seconds, kernel_seconds):
if kernel_seconds < 18000: # And kernel has < 5h left metadata_drift.append(ip)
metadata_drift.append(ip)
if metadata_drift: if metadata_drift:
drift = { drift = {
+36
View File
@@ -1,4 +1,5 @@
import unittest import unittest
import datetime
from auditor import FirewallAuditor from auditor import FirewallAuditor
@@ -33,6 +34,41 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
self.assertIn(("3.3.3.3", "12h", "manual"), decision_keys) self.assertIn(("3.3.3.3", "12h", "manual"), decision_keys)
self.assertEqual(3, len(decision_keys)) self.assertEqual(3, len(decision_keys))
def test_reconcile_detects_metadata_drift_for_extended_duration(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"1.1.1.1": {"duration": "24h", "until_epoch": None}
}
auditor.get_kernel_state = lambda: {"1.1.1.1": 3 * 3600 * 1000}
is_synced, count, drift = auditor.reconcile()
self.assertFalse(is_synced)
self.assertEqual(1, count)
self.assertEqual("metadata_drift", drift["reason"])
self.assertEqual(1, drift["metadata_drift_count"])
def test_reconcile_uses_until_for_expected_remaining(self):
now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"2.2.2.2": {
"duration": "4h",
"until_epoch": now_epoch + (24 * 3600),
}
}
auditor.get_kernel_state = lambda: {"2.2.2.2": 2 * 3600 * 1000}
is_synced, _, drift = auditor.reconcile()
self.assertFalse(is_synced)
self.assertEqual("metadata_drift", drift["reason"])
def test_parse_duration_supports_compound_values(self):
auditor = FirewallAuditor()
self.assertEqual(5400, auditor.parse_duration("1h30m"))
self.assertEqual(1209600, auditor.parse_duration("14d"))
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()