Fix metadata-drift healing by flushing CrowdSec nft sets before restart
Add drift-aware heal path in FirewallAuditor to remediate metadata drift by discovering and flushing *-cscli sets in crowdsec/crowdsec6 tables, then restarting the bouncer. Update execute_heal_and_verify to pass drift context to heal_with_drift when supported, keeping backward compatibility via heal(). Add unit tests covering metadata-drift flush+restart behavior, non-metadata restart-only behavior, and drift context propagation.
This commit is contained in:
1 parent
28267a0cf4
commit
0f7f03f005
4 files changed
+121
-1
No files matched your search
+42
-1
@@ -175,14 +175,55 @@ class FirewallAuditor:
|
|||||||
return kernel_seconds + allowed_shortfall < expected_seconds
|
return kernel_seconds + allowed_shortfall < expected_seconds
|
||||||
|
|
||||||
def heal(self):
|
def heal(self):
|
||||||
"""Directly restarts the bouncer service."""
|
"""Executes heal actions based on drift type, then restarts the bouncer."""
|
||||||
|
return self.heal_with_drift({})
|
||||||
|
|
||||||
|
def heal_with_drift(self, drift):
|
||||||
|
"""Performs targeted pre-heal remediation for metadata drift."""
|
||||||
try:
|
try:
|
||||||
|
if drift.get("reason") == "metadata_drift":
|
||||||
|
self._flush_crowdsec_sets()
|
||||||
|
logging.info("Heal: Flushed CrowdSec nft sets to clear stale metadata.")
|
||||||
subprocess.run(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True)
|
subprocess.run(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True)
|
||||||
logging.info("Heal: Bouncer restarted successfully.")
|
logging.info("Heal: Bouncer restarted successfully.")
|
||||||
return True
|
return True
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
logging.error(f"Heal Failed: Could not restart bouncer: {e}")
|
logging.error(f"Heal Failed: Could not restart bouncer: {e}")
|
||||||
return False
|
return False
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Heal Failed: Unexpected error: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _flush_crowdsec_sets(self):
|
||||||
|
for family, table in (("ip", "crowdsec"), ("ip6", "crowdsec6")):
|
||||||
|
try:
|
||||||
|
res = subprocess.run(
|
||||||
|
["/usr/sbin/nft", "-j", "list", "table", family, table],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
except subprocess.CalledProcessError:
|
||||||
|
logging.debug(f"Heal: Table not present, skip flush ({family} {table}).")
|
||||||
|
continue
|
||||||
|
|
||||||
|
data = json.loads(res.stdout or "{}")
|
||||||
|
set_names = []
|
||||||
|
for item in data.get("nftables", []):
|
||||||
|
nft_set = item.get("set")
|
||||||
|
if not isinstance(nft_set, dict):
|
||||||
|
continue
|
||||||
|
set_name = nft_set.get("name")
|
||||||
|
if isinstance(set_name, str) and set_name.endswith("-cscli"):
|
||||||
|
set_names.append(set_name)
|
||||||
|
|
||||||
|
for set_name in set_names:
|
||||||
|
subprocess.run(
|
||||||
|
["/usr/sbin/nft", "flush", "set", family, table, set_name],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
|
||||||
def reconcile(self):
|
def reconcile(self):
|
||||||
truth_map = self.get_remote_lapi_truth()
|
truth_map = self.get_remote_lapi_truth()
|
||||||
|
|||||||
@@ -48,6 +48,9 @@ def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay):
|
|||||||
"""
|
"""
|
||||||
Executes heal + post-heal verification and persists reporter state.
|
Executes heal + post-heal verification and persists reporter state.
|
||||||
"""
|
"""
|
||||||
|
if hasattr(auditor, "heal_with_drift"):
|
||||||
|
heal_ok = auditor.heal_with_drift(drift or {})
|
||||||
|
else:
|
||||||
heal_ok = auditor.heal()
|
heal_ok = auditor.heal()
|
||||||
heal_result = "restart_failed"
|
heal_result = "restart_failed"
|
||||||
post_drift = {
|
post_drift = {
|
||||||
|
|||||||
@@ -18,10 +18,15 @@ class FakeAuditor:
|
|||||||
def __init__(self, heal_ok=True, reconcile_result=None):
|
def __init__(self, heal_ok=True, reconcile_result=None):
|
||||||
self.heal_ok = heal_ok
|
self.heal_ok = heal_ok
|
||||||
self.reconcile_result = reconcile_result
|
self.reconcile_result = reconcile_result
|
||||||
|
self.last_heal_drift = None
|
||||||
|
|
||||||
def heal(self):
|
def heal(self):
|
||||||
return self.heal_ok
|
return self.heal_ok
|
||||||
|
|
||||||
|
def heal_with_drift(self, drift):
|
||||||
|
self.last_heal_drift = drift
|
||||||
|
return self.heal_ok
|
||||||
|
|
||||||
def reconcile(self):
|
def reconcile(self):
|
||||||
return self.reconcile_result
|
return self.reconcile_result
|
||||||
|
|
||||||
@@ -72,6 +77,7 @@ class PostHealVerificationTests(unittest.TestCase):
|
|||||||
self.assertEqual("success", heal_result)
|
self.assertEqual("success", heal_result)
|
||||||
self.assertEqual(post_drift, returned_post_drift)
|
self.assertEqual(post_drift, returned_post_drift)
|
||||||
self.assertEqual([(True, 12, None)], reporter.update_calls)
|
self.assertEqual([(True, 12, None)], reporter.update_calls)
|
||||||
|
self.assertEqual({"fingerprint": "pre123"}, auditor.last_heal_drift)
|
||||||
|
|
||||||
@patch("healing.time.sleep", return_value=None)
|
@patch("healing.time.sleep", return_value=None)
|
||||||
def test_execute_heal_and_verify_restart_failed(self, _sleep):
|
def test_execute_heal_and_verify_restart_failed(self, _sleep):
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import unittest
|
import unittest
|
||||||
import datetime
|
import datetime
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
from unittest.mock import patch, call
|
||||||
|
|
||||||
from auditor import FirewallAuditor
|
from auditor import FirewallAuditor
|
||||||
|
|
||||||
@@ -69,6 +72,73 @@ 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"))
|
||||||
|
|
||||||
|
@patch("auditor.subprocess.run")
|
||||||
|
def test_heal_with_metadata_drift_flushes_sets_before_restart(self, run_mock):
|
||||||
|
auditor = FirewallAuditor()
|
||||||
|
|
||||||
|
run_mock.side_effect = [
|
||||||
|
subprocess.CompletedProcess(
|
||||||
|
args=[],
|
||||||
|
returncode=0,
|
||||||
|
stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli"}}]}),
|
||||||
|
),
|
||||||
|
None, # flush ip set
|
||||||
|
subprocess.CompletedProcess(
|
||||||
|
args=[],
|
||||||
|
returncode=0,
|
||||||
|
stdout=json.dumps({"nftables": [{"set": {"name": "::/0-cscli"}}]}),
|
||||||
|
),
|
||||||
|
None, # flush ip6 set
|
||||||
|
None, # systemctl restart
|
||||||
|
]
|
||||||
|
|
||||||
|
ok = auditor.heal_with_drift({"reason": "metadata_drift"})
|
||||||
|
|
||||||
|
self.assertTrue(ok)
|
||||||
|
self.assertEqual(
|
||||||
|
[
|
||||||
|
call(
|
||||||
|
["/usr/sbin/nft", "-j", "list", "table", "ip", "crowdsec"],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
),
|
||||||
|
call(
|
||||||
|
["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "0.0.0.0/0-cscli"],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
),
|
||||||
|
call(
|
||||||
|
["/usr/sbin/nft", "-j", "list", "table", "ip6", "crowdsec6"],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
),
|
||||||
|
call(
|
||||||
|
["/usr/sbin/nft", "flush", "set", "ip6", "crowdsec6", "::/0-cscli"],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
),
|
||||||
|
call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True),
|
||||||
|
],
|
||||||
|
run_mock.call_args_list,
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch("auditor.subprocess.run")
|
||||||
|
def test_heal_without_metadata_drift_only_restarts_bouncer(self, run_mock):
|
||||||
|
auditor = FirewallAuditor()
|
||||||
|
run_mock.return_value = None
|
||||||
|
|
||||||
|
ok = auditor.heal_with_drift({"reason": "membership_mismatch"})
|
||||||
|
|
||||||
|
self.assertTrue(ok)
|
||||||
|
self.assertEqual(
|
||||||
|
[call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True)],
|
||||||
|
run_mock.call_args_list,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Reference in new issue
Block a user