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
+122
-2
No files matched your search
+42
-1
@@ -175,14 +175,55 @@ class FirewallAuditor:
|
||||
return kernel_seconds + allowed_shortfall < expected_seconds
|
||||
|
||||
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:
|
||||
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)
|
||||
logging.info("Heal: Bouncer restarted successfully.")
|
||||
return True
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.error(f"Heal Failed: Could not restart bouncer: {e}")
|
||||
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):
|
||||
truth_map = self.get_remote_lapi_truth()
|
||||
|
||||
Reference in new issue
Block a user