diff --git a/auditor.py b/auditor.py index 4d4f0c9..eabbb42 100644 --- a/auditor.py +++ b/auditor.py @@ -105,7 +105,7 @@ class FirewallAuditor: def get_kernel_state(self): """Scans BOTH IPv4 and IPv6 sets in the crowdsec tables.""" - all_ips = {} # Changed from set() to {} + all_ips = {} targets = [ {"family": "ip", "table": "crowdsec"}, {"family": "ip6", "table": "crowdsec6"} @@ -125,13 +125,16 @@ 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) + expires_raw = inner.get('expires') if val: - all_ips[val] = expires_ms + if isinstance(expires_raw, (int, float)): + all_ips[val] = float(expires_raw) + else: + # Expiry not reported for this element; TTL drift is unverifiable. + all_ips[val] = None else: # Fallback if it's just a raw string IP - all_ips[e] = 0 + all_ips[e] = None except subprocess.CalledProcessError: logging.debug(f"Table {target['table']} not found, skipped.") except Exception as e: @@ -174,6 +177,25 @@ class FirewallAuditor: allowed_shortfall = max(7200, int(expected_seconds * 0.40)) return kernel_seconds + allowed_shortfall < expected_seconds + def _normalize_kernel_remaining_seconds(self, kernel_raw, expected_seconds): + """ + nft 'expires' can appear in either seconds or milliseconds depending on stack/version. + Pick the representation closest to expected TTL from CrowdSec. + """ + try: + if kernel_raw is None: + return None + raw = float(kernel_raw) + if raw <= 0: + return None + + candidates = [raw, raw / 1000.0] + if expected_seconds <= 0: + return max(candidates) + return min(candidates, key=lambda value: abs(value - expected_seconds)) + except Exception: + return None + def heal(self): """Executes heal actions based on drift type, then restarts the bouncer.""" return self.heal_with_drift({}) @@ -253,7 +275,16 @@ class FirewallAuditor: 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 <= 0: + continue + + kernel_raw = reality_map.get(ip) + kernel_seconds = self._normalize_kernel_remaining_seconds( + kernel_raw, + siem_seconds, + ) + if kernel_seconds is None: + continue if self._has_ttl_drift(siem_seconds, kernel_seconds): metadata_drift.append(ip) diff --git a/tests/test_auditor.py b/tests/test_auditor.py index 33fdc92..3e153c1 100644 --- a/tests/test_auditor.py +++ b/tests/test_auditor.py @@ -72,6 +72,33 @@ class AuditorDecisionExtractionTests(unittest.TestCase): self.assertEqual(5400, auditor.parse_duration("1h30m")) self.assertEqual(1209600, auditor.parse_duration("14d")) + def test_reconcile_skips_metadata_check_when_kernel_expiry_unavailable(self): + auditor = FirewallAuditor() + auditor.get_remote_lapi_truth = lambda: { + "4.4.4.4": {"duration": "14d", "until_epoch": None} + } + auditor.get_kernel_state = lambda: {"4.4.4.4": None} + + is_synced, count, drift = auditor.reconcile() + + self.assertTrue(is_synced) + self.assertEqual(1, count) + self.assertEqual("in_sync", drift["reason"]) + + def test_reconcile_supports_kernel_ttl_reported_in_seconds(self): + auditor = FirewallAuditor() + auditor.get_remote_lapi_truth = lambda: { + "5.5.5.5": {"duration": "14d", "until_epoch": None} + } + # Some nft stacks report expires directly in seconds. + auditor.get_kernel_state = lambda: {"5.5.5.5": 13 * 24 * 3600} + + is_synced, count, drift = auditor.reconcile() + + self.assertTrue(is_synced) + self.assertEqual(1, count) + self.assertEqual("in_sync", drift["reason"]) + @patch("auditor.subprocess.run") def test_heal_with_metadata_drift_flushes_sets_before_restart(self, run_mock): auditor = FirewallAuditor()