diff --git a/auditor.py b/auditor.py index 699b54d..2dfca8a 100644 --- a/auditor.py +++ b/auditor.py @@ -230,16 +230,17 @@ class FirewallAuditor: continue data = json.loads(res.stdout or "{}") - set_names = [] + set_targets = [] for item in data.get("nftables", []): nft_set = item.get("set") if not isinstance(nft_set, dict): continue set_name = nft_set.get("name") + set_handle = nft_set.get("handle") if isinstance(set_name, str) and set_name.endswith("-cscli"): - set_names.append(set_name) + set_targets.append((set_name, set_handle)) - for set_name in set_names: + for set_name, set_handle in set_targets: try: subprocess.run( ["/usr/sbin/nft", "flush", "set", family, table, set_name], @@ -249,6 +250,32 @@ class FirewallAuditor: ) except subprocess.CalledProcessError as e: stderr = (e.stderr or "").strip() + syntax_error = "syntax error" in stderr.lower() + if syntax_error and isinstance(set_handle, int): + try: + subprocess.run( + [ + "/usr/sbin/nft", + "flush", + "set", + family, + table, + "handle", + str(set_handle), + ], + check=True, + capture_output=True, + text=True, + ) + continue + except subprocess.CalledProcessError as handle_err: + handle_stderr = (handle_err.stderr or "").strip() + logging.warning( + "Heal: Failed to flush set " + f"({family} {table} {set_name}, handle={set_handle}): " + f"{handle_stderr or handle_err}" + ) + continue logging.warning( "Heal: Failed to flush set " f"({family} {table} {set_name}): {stderr or e}" diff --git a/tests/test_auditor.py b/tests/test_auditor.py index beadc01..db96f60 100644 --- a/tests/test_auditor.py +++ b/tests/test_auditor.py @@ -107,13 +107,13 @@ class AuditorDecisionExtractionTests(unittest.TestCase): subprocess.CompletedProcess( args=[], returncode=0, - stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli"}}]}), + stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli", "handle": 7}}]}), ), None, # flush ip set subprocess.CompletedProcess( args=[], returncode=0, - stdout=json.dumps({"nftables": [{"set": {"name": "::/0-cscli"}}]}), + stdout=json.dumps({"nftables": [{"set": {"name": "::/0-cscli", "handle": 8}}]}), ), None, # flush ip6 set subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # inet crowdsec absent @@ -180,7 +180,7 @@ class AuditorDecisionExtractionTests(unittest.TestCase): subprocess.CompletedProcess( args=[], returncode=0, - stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli"}}]}), + stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli", "handle": 9}}]}), ), subprocess.CalledProcessError( 1, @@ -200,6 +200,39 @@ class AuditorDecisionExtractionTests(unittest.TestCase): run_mock.call_args_list[-1], ) + @patch("auditor.subprocess.run") + def test_heal_metadata_drift_falls_back_to_handle_on_name_syntax_error(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", "handle": 21}}]}), + ), + subprocess.CalledProcessError( + 1, + ["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "0.0.0.0/0-cscli"], + stderr="Error: syntax error, unexpected /", + ), + None, # fallback flush by handle succeeds + subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # ip6 crowdsec6 absent + subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # inet crowdsec absent + None, # restart + ] + + ok = auditor.heal_with_drift({"reason": "metadata_drift"}) + + self.assertTrue(ok) + self.assertIn( + call( + ["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "handle", "21"], + check=True, + capture_output=True, + text=True, + ), + run_mock.call_args_list, + ) + if __name__ == "__main__": unittest.main()