feat(config): enforce runtime nft targets and managed sets from config.yaml
This commit is contained in:
1 parent
3c6c4e384b
commit
bffe28485d
7 files changed
+182
-24
No files matched your search
@@ -77,6 +77,11 @@ Supported env overrides:
|
||||
- `STATE_FILE`
|
||||
- `THREAT_AGENT_CONFIG`
|
||||
|
||||
`config.yaml` also controls enforcement scan/flush scope:
|
||||
- `enforcement.targets` (preferred): list of `{family, table}` mappings
|
||||
- legacy fallback: `enforcement.table`, `enforcement.table6`, and `enforcement.families`
|
||||
- `enforcement.sets`: optional allowlist of set names to manage (when omitted, `*-cscli` sets are managed)
|
||||
|
||||
3. Monitoring:
|
||||
|
||||
```bash
|
||||
|
||||
+17
-13
@@ -12,11 +12,11 @@ except ImportError:
|
||||
return None
|
||||
|
||||
class FirewallAuditor:
|
||||
def __init__(self):
|
||||
def __init__(self, targets=None, managed_sets=None):
|
||||
"""Ensures the NFT kernel state matches the LAPI's desired state."""
|
||||
load_dotenv()
|
||||
self.table = "crowdsec"
|
||||
self.set_name = "0.0.0.0/0-cscli"
|
||||
self.targets = list(targets or (("ip", "crowdsec"), ("ip6", "crowdsec6")))
|
||||
self.managed_sets = {str(name) for name in (managed_sets or ()) if str(name)}
|
||||
|
||||
def get_remote_lapi_truth(self):
|
||||
"""Queries CrowdSec decisions and normalizes across schema variants."""
|
||||
@@ -106,19 +106,18 @@ class FirewallAuditor:
|
||||
def get_kernel_state(self):
|
||||
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
|
||||
all_ips = {}
|
||||
targets = [
|
||||
{"family": "ip", "table": "crowdsec"},
|
||||
{"family": "ip6", "table": "crowdsec6"}
|
||||
]
|
||||
for target in targets:
|
||||
for family, table in self.targets:
|
||||
try:
|
||||
cmd = ["/usr/sbin/nft", "-j", "list", "table", target["family"], target["table"]]
|
||||
cmd = ["/usr/sbin/nft", "-j", "list", "table", family, table]
|
||||
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
||||
data = json.loads(res.stdout)
|
||||
|
||||
for item in data.get('nftables', []):
|
||||
nft_set = item.get('set')
|
||||
if nft_set:
|
||||
set_name = nft_set.get("name")
|
||||
if self.managed_sets and set_name not in self.managed_sets:
|
||||
continue
|
||||
elements = nft_set.get('elem', [])
|
||||
for e in elements:
|
||||
if isinstance(e, dict):
|
||||
@@ -136,9 +135,9 @@ class FirewallAuditor:
|
||||
# Fallback if it's just a raw string IP
|
||||
all_ips[e] = None
|
||||
except subprocess.CalledProcessError:
|
||||
logging.debug(f"Table {target['table']} not found, skipped.")
|
||||
logging.debug(f"Table {table} not found, skipped.")
|
||||
except Exception as e:
|
||||
logging.error(f"Kernel Table scan failed for {target['table']}: {e}")
|
||||
logging.error(f"Kernel Table scan failed for {table}: {e}")
|
||||
|
||||
return all_ips
|
||||
|
||||
@@ -217,7 +216,7 @@ class FirewallAuditor:
|
||||
return False
|
||||
|
||||
def _flush_crowdsec_sets(self):
|
||||
for family, table in (("ip", "crowdsec"), ("ip6", "crowdsec6"), ("inet", "crowdsec")):
|
||||
for family, table in dict.fromkeys(self.targets):
|
||||
try:
|
||||
res = subprocess.run(
|
||||
["/usr/sbin/nft", "-j", "list", "table", family, table],
|
||||
@@ -237,7 +236,12 @@ class FirewallAuditor:
|
||||
continue
|
||||
set_name = nft_set.get("name")
|
||||
set_handle = nft_set.get("handle")
|
||||
if isinstance(set_name, str) and set_name.endswith("-cscli"):
|
||||
if not isinstance(set_name, str):
|
||||
continue
|
||||
if self.managed_sets:
|
||||
if set_name in self.managed_sets:
|
||||
set_targets.append((set_name, set_handle))
|
||||
elif set_name.endswith("-cscli"):
|
||||
set_targets.append((set_name, set_handle))
|
||||
|
||||
for set_name, set_handle in set_targets:
|
||||
|
||||
@@ -9,6 +9,7 @@ DEFAULT_HEAL_VERIFY_DELAY = 5
|
||||
DEFAULT_HEAL_MIN_INTERVAL = 900
|
||||
DEFAULT_CONFIG_PATH = "config.yaml"
|
||||
DEFAULT_NODE_NAME = "Unknown Node"
|
||||
DEFAULT_ENFORCEMENT_TARGETS = (("ip", "crowdsec"), ("ip6", "crowdsec6"))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -19,6 +20,8 @@ class RuntimeSettings:
|
||||
check_interval: int
|
||||
heal_verify_delay: int
|
||||
heal_min_interval: int
|
||||
enforcement_targets: tuple[tuple[str, str], ...]
|
||||
enforcement_sets: tuple[str, ...]
|
||||
config_path: str
|
||||
|
||||
|
||||
@@ -43,6 +46,7 @@ def _load_config_minimal(config_path):
|
||||
"""
|
||||
config = {}
|
||||
current_section = None
|
||||
current_list_key = None
|
||||
|
||||
with open(config_path, "r") as f:
|
||||
for raw_line in f:
|
||||
@@ -59,9 +63,11 @@ def _load_config_minimal(config_path):
|
||||
if value == "":
|
||||
config[key] = {}
|
||||
current_section = key
|
||||
current_list_key = None
|
||||
else:
|
||||
config[key] = _parse_scalar(value)
|
||||
current_section = None
|
||||
current_list_key = None
|
||||
continue
|
||||
|
||||
if current_section is None:
|
||||
@@ -69,11 +75,22 @@ def _load_config_minimal(config_path):
|
||||
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("- "):
|
||||
if current_list_key:
|
||||
config[current_section].setdefault(current_list_key, []).append(
|
||||
_parse_scalar(stripped[2:].strip())
|
||||
)
|
||||
continue
|
||||
if ":" not in stripped:
|
||||
continue
|
||||
key, value = stripped.split(":", 1)
|
||||
config[current_section][key.strip()] = _parse_scalar(value)
|
||||
key = key.strip()
|
||||
value = value.strip()
|
||||
if value == "":
|
||||
config[current_section][key] = []
|
||||
current_list_key = key
|
||||
else:
|
||||
config[current_section][key] = _parse_scalar(value)
|
||||
current_list_key = None
|
||||
|
||||
return config
|
||||
|
||||
@@ -119,6 +136,51 @@ def as_int(value, default):
|
||||
return default
|
||||
|
||||
|
||||
def _as_string_list(value):
|
||||
if isinstance(value, list):
|
||||
return [str(item).strip() for item in value if str(item).strip()]
|
||||
if isinstance(value, str):
|
||||
return [item.strip() for item in value.split(",") if item.strip()]
|
||||
return []
|
||||
|
||||
|
||||
def _resolve_enforcement_targets(config):
|
||||
targets_cfg = cfg_get(config, "enforcement", "targets")
|
||||
targets = []
|
||||
if isinstance(targets_cfg, list):
|
||||
for item in targets_cfg:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
family = str(item.get("family", "")).strip()
|
||||
table = str(item.get("table", "")).strip()
|
||||
if family and table:
|
||||
targets.append((family, table))
|
||||
if targets:
|
||||
return tuple(targets)
|
||||
|
||||
table_v4 = str(cfg_get(config, "enforcement", "table", default="crowdsec")).strip() or "crowdsec"
|
||||
table_v6 = str(cfg_get(config, "enforcement", "table6", default="crowdsec6")).strip() or "crowdsec6"
|
||||
families = _as_string_list(cfg_get(config, "enforcement", "families"))
|
||||
|
||||
if not families:
|
||||
return (("ip", table_v4), ("ip6", table_v6))
|
||||
|
||||
resolved = []
|
||||
for family in families:
|
||||
if family == "ip":
|
||||
resolved.append((family, table_v4))
|
||||
elif family == "ip6":
|
||||
resolved.append((family, table_v6))
|
||||
elif family == "inet":
|
||||
resolved.append((family, table_v4))
|
||||
|
||||
return tuple(resolved) if resolved else DEFAULT_ENFORCEMENT_TARGETS
|
||||
|
||||
|
||||
def _resolve_enforcement_sets(config):
|
||||
return tuple(_as_string_list(cfg_get(config, "enforcement", "sets")))
|
||||
|
||||
|
||||
def setup_logging(log_path):
|
||||
os.makedirs(os.path.dirname(os.path.abspath(log_path)), exist_ok=True)
|
||||
logging.basicConfig(
|
||||
@@ -163,6 +225,8 @@ def load_runtime_settings():
|
||||
),
|
||||
DEFAULT_HEAL_MIN_INTERVAL,
|
||||
)
|
||||
enforcement_targets = _resolve_enforcement_targets(config)
|
||||
enforcement_sets = _resolve_enforcement_sets(config)
|
||||
|
||||
return RuntimeSettings(
|
||||
node_name=node_name,
|
||||
@@ -171,5 +235,7 @@ def load_runtime_settings():
|
||||
check_interval=check_interval,
|
||||
heal_verify_delay=heal_verify_delay,
|
||||
heal_min_interval=heal_min_interval,
|
||||
enforcement_targets=enforcement_targets,
|
||||
enforcement_sets=enforcement_sets,
|
||||
config_path=config_path,
|
||||
)
|
||||
@@ -8,6 +8,7 @@ agent:
|
||||
|
||||
enforcement:
|
||||
table: "crowdsec"
|
||||
table6: "crowdsec6"
|
||||
sets:
|
||||
- "0.0.0.0/0-cscli"
|
||||
- "crowdsec-blacklists"
|
||||
@@ -22,7 +22,10 @@ def main():
|
||||
settings = load_runtime_settings()
|
||||
|
||||
setup_logging(settings.log_path)
|
||||
auditor = FirewallAuditor()
|
||||
auditor = FirewallAuditor(
|
||||
targets=settings.enforcement_targets,
|
||||
managed_sets=settings.enforcement_sets,
|
||||
)
|
||||
reporter = LocalStateReporter(
|
||||
state_file=settings.state_file,
|
||||
node_name=settings.node_name,
|
||||
|
||||
+33
-9
@@ -116,7 +116,6 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
|
||||
stdout=json.dumps({"nftables": [{"set": {"name": "::/0-cscli", "handle": 8}}]}),
|
||||
),
|
||||
None, # flush ip6 set
|
||||
subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # inet crowdsec absent
|
||||
None, # systemctl restart
|
||||
]
|
||||
|
||||
@@ -149,12 +148,6 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
|
||||
capture_output=True,
|
||||
text=True,
|
||||
),
|
||||
call(
|
||||
["/usr/sbin/nft", "-j", "list", "table", "inet", "crowdsec"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
),
|
||||
call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True),
|
||||
],
|
||||
run_mock.call_args_list,
|
||||
@@ -188,7 +181,6 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
|
||||
stderr="No such file or directory",
|
||||
),
|
||||
subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # ip6 crowdsec6 absent
|
||||
subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # inet crowdsec absent
|
||||
None, # restart still executes
|
||||
]
|
||||
|
||||
@@ -216,7 +208,6 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
|
||||
),
|
||||
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
|
||||
]
|
||||
|
||||
@@ -233,6 +224,39 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
|
||||
run_mock.call_args_list,
|
||||
)
|
||||
|
||||
@patch("auditor.subprocess.run")
|
||||
def test_get_kernel_state_filters_to_configured_managed_sets(self, run_mock):
|
||||
auditor = FirewallAuditor(
|
||||
targets=[("ip", "crowdsec")],
|
||||
managed_sets=["0.0.0.0/0-cscli"],
|
||||
)
|
||||
run_mock.return_value = subprocess.CompletedProcess(
|
||||
args=[],
|
||||
returncode=0,
|
||||
stdout=json.dumps(
|
||||
{
|
||||
"nftables": [
|
||||
{
|
||||
"set": {
|
||||
"name": "0.0.0.0/0-cscli",
|
||||
"elem": [{"elem": {"val": "1.1.1.1", "expires": 1000}}],
|
||||
}
|
||||
},
|
||||
{
|
||||
"set": {
|
||||
"name": "crowdsec-blacklists",
|
||||
"elem": [{"elem": {"val": "9.9.9.9", "expires": 2000}}],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
kernel_state = auditor.get_kernel_state()
|
||||
|
||||
self.assertEqual({"1.1.1.1": 1000.0}, kernel_state)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,55 @@
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from config import load_runtime_settings
|
||||
|
||||
|
||||
class RuntimeSettingsEnforcementTests(unittest.TestCase):
|
||||
@patch("config.load_config")
|
||||
def test_enforcement_uses_explicit_targets_when_present(self, load_config_mock):
|
||||
load_config_mock.return_value = {
|
||||
"agent": {"node_name": "n1"},
|
||||
"enforcement": {
|
||||
"targets": [
|
||||
{"family": "ip", "table": "custom_v4"},
|
||||
{"family": "inet", "table": "custom_inet"},
|
||||
],
|
||||
"sets": ["0.0.0.0/0-cscli", "crowdsec-blacklists"],
|
||||
},
|
||||
}
|
||||
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
settings = load_runtime_settings()
|
||||
|
||||
self.assertEqual(
|
||||
(("ip", "custom_v4"), ("inet", "custom_inet")),
|
||||
settings.enforcement_targets,
|
||||
)
|
||||
self.assertEqual(
|
||||
("0.0.0.0/0-cscli", "crowdsec-blacklists"),
|
||||
settings.enforcement_sets,
|
||||
)
|
||||
|
||||
@patch("config.load_config")
|
||||
def test_enforcement_falls_back_to_table_fields(self, load_config_mock):
|
||||
load_config_mock.return_value = {
|
||||
"enforcement": {
|
||||
"table": "crowdsec_main",
|
||||
"table6": "crowdsec6_main",
|
||||
"families": ["ip", "ip6"],
|
||||
}
|
||||
}
|
||||
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
settings = load_runtime_settings()
|
||||
|
||||
self.assertEqual(
|
||||
(("ip", "crowdsec_main"), ("ip6", "crowdsec6_main")),
|
||||
settings.enforcement_targets,
|
||||
)
|
||||
self.assertEqual((), settings.enforcement_sets)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user