From 28267a0cf440323c643638379e8900ec5e71d8a4 Mon Sep 17 00:00:00 2001 From: patrickbeane Date: Mon, 23 Feb 2026 22:20:16 -0500 Subject: [PATCH] fix(auditor): heal on decision-duration drift, not just IP membership/count --- auditor.py | 76 ++++++++++++++++++++++++++++++++++++------- tests/test_auditor.py | 36 ++++++++++++++++++++ 2 files changed, 101 insertions(+), 11 deletions(-) diff --git a/auditor.py b/auditor.py index c090619..87c02f0 100644 --- a/auditor.py +++ b/auditor.py @@ -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 = { diff --git a/tests/test_auditor.py b/tests/test_auditor.py index 52488b1..1f0676e 100644 --- a/tests/test_auditor.py +++ b/tests/test_auditor.py @@ -1,4 +1,5 @@ import unittest +import datetime from auditor import FirewallAuditor @@ -33,6 +34,41 @@ class AuditorDecisionExtractionTests(unittest.TestCase): self.assertIn(("3.3.3.3", "12h", "manual"), 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__": unittest.main()