fix: metadata drift false positives - corrected by normalizing nft TTL and skipping unverifiable expiry

This commit is contained in:
patrick committed 2026-02-25 15:02:24 -05:00
1 parent 0f7f03f005
commit aae920fb73
2 files changed
+64 -6

No files matched your search

+37 -6
View File
@@ -105,7 +105,7 @@ class FirewallAuditor:
def get_kernel_state(self): def get_kernel_state(self):
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables.""" """Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
all_ips = {} # Changed from set() to {} all_ips = {}
targets = [ targets = [
{"family": "ip", "table": "crowdsec"}, {"family": "ip", "table": "crowdsec"},
{"family": "ip6", "table": "crowdsec6"} {"family": "ip6", "table": "crowdsec6"}
@@ -125,13 +125,16 @@ class FirewallAuditor:
inner = e.get('elem', e) inner = e.get('elem', e)
if isinstance(inner, dict): if isinstance(inner, dict):
val = inner.get('val') val = inner.get('val')
# NFT provides 'expires' in milliseconds expires_raw = inner.get('expires')
expires_ms = inner.get('expires', 0)
if val: 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: else:
# Fallback if it's just a raw string IP # Fallback if it's just a raw string IP
all_ips[e] = 0 all_ips[e] = None
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
logging.debug(f"Table {target['table']} not found, skipped.") logging.debug(f"Table {target['table']} not found, skipped.")
except Exception as e: except Exception as e:
@@ -174,6 +177,25 @@ class FirewallAuditor:
allowed_shortfall = max(7200, int(expected_seconds * 0.40)) allowed_shortfall = max(7200, int(expected_seconds * 0.40))
return kernel_seconds + allowed_shortfall < expected_seconds 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): def heal(self):
"""Executes heal actions based on drift type, then restarts the bouncer.""" """Executes heal actions based on drift type, then restarts the bouncer."""
return self.heal_with_drift({}) return self.heal_with_drift({})
@@ -253,7 +275,16 @@ class FirewallAuditor:
for ip, decision_meta in truth_map.items(): for ip, decision_meta in truth_map.items():
siem_seconds = self._expected_remaining_seconds(decision_meta, now_epoch) 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): if self._has_ttl_drift(siem_seconds, kernel_seconds):
metadata_drift.append(ip) metadata_drift.append(ip)
+27
View File
@@ -72,6 +72,33 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
self.assertEqual(5400, auditor.parse_duration("1h30m")) self.assertEqual(5400, auditor.parse_duration("1h30m"))
self.assertEqual(1209600, auditor.parse_duration("14d")) 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") @patch("auditor.subprocess.run")
def test_heal_with_metadata_drift_flushes_sets_before_restart(self, run_mock): def test_heal_with_metadata_drift_flushes_sets_before_restart(self, run_mock):
auditor = FirewallAuditor() auditor = FirewallAuditor()