crowdsec-firewall-bouncer's nftables mode strips the prefix from Range decisions and bans only the network address, so a /24 decision blocked a single IP. With ranges.enabled, every audit now syncs range decisions into a dedicated `inet crowdsec-ranges` table (interval+timeout sets with input/forward drop chains) in one atomic `nft -f` transaction, then reads it back to confirm each range is enforced. - element timeouts track each decision's remaining lifetime; stale elements are removed and extended decisions refreshed - ranges nested in another active range are covered, not inserted - ranges broader than min_prefix_v4/v6 (default /16, /32) are refused - ranges still missing after the sync stay in unenforceable_ranges, so the node reports DEGRADED rather than HEALTHY - the bouncer-set scan normalizes nft prefix elements to addr/len instead of failing the table scan on them - doctor checks the range table; the audit log line says when a synced node is degraded Disabled by default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
382 lines
12 KiB
Python
382 lines
12 KiB
Python
import logging
|
|
import os
|
|
from dataclasses import dataclass
|
|
|
|
DEFAULT_LOG_PATH = "/root/threat-engine-agent/logs/threat-agent.log"
|
|
DEFAULT_STATE_FILE = "/root/threat-engine-agent/threat-agent-state.json"
|
|
DEFAULT_CHECK_INTERVAL = 600
|
|
DEFAULT_CHECK_JITTER_PCT = 0.10
|
|
DEFAULT_HEAL_VERIFY_DELAY = 5
|
|
DEFAULT_HEAL_MIN_INTERVAL = 900
|
|
DEFAULT_MEMBERSHIP_RECHECK_DELAY = 30
|
|
DEFAULT_CONFIG_PATH = "config.yaml"
|
|
DEFAULT_NODE_NAME = "Unknown Node"
|
|
DEFAULT_ENFORCEMENT_TARGETS = (("ip", "crowdsec"), ("ip6", "crowdsec6"))
|
|
DEFAULT_RANGES_TABLE = "crowdsec-ranges"
|
|
DEFAULT_RANGES_MIN_PREFIX_V4 = 16
|
|
DEFAULT_RANGES_MIN_PREFIX_V6 = 32
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RuntimeSettings:
|
|
node_name: str
|
|
log_path: str
|
|
state_file: str
|
|
check_interval: int
|
|
check_jitter_pct: float
|
|
heal_verify_delay: int
|
|
heal_min_interval: int
|
|
enforcement_targets: tuple[tuple[str, str], ...]
|
|
enforcement_sets: tuple[str, ...]
|
|
config_path: str
|
|
membership_recheck_delay: int = DEFAULT_MEMBERSHIP_RECHECK_DELAY
|
|
ranges_enabled: bool = False
|
|
ranges_table: str = DEFAULT_RANGES_TABLE
|
|
ranges_min_prefix_v4: int = DEFAULT_RANGES_MIN_PREFIX_V4
|
|
ranges_min_prefix_v6: int = DEFAULT_RANGES_MIN_PREFIX_V6
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ValidationIssue:
|
|
level: str # ERROR | WARN
|
|
message: str
|
|
|
|
|
|
def _parse_scalar(value):
|
|
value = value.strip()
|
|
if value.startswith(("'", '"')) and value.endswith(("'", '"')) and len(value) >= 2:
|
|
return value[1:-1]
|
|
if value.lower() == "true":
|
|
return True
|
|
if value.lower() == "false":
|
|
return False
|
|
try:
|
|
return int(value)
|
|
except ValueError:
|
|
return value
|
|
|
|
|
|
def _load_config_minimal(config_path):
|
|
"""
|
|
Minimal parser for simple two-level YAML mappings.
|
|
Supports the current config.yaml structure without external deps.
|
|
"""
|
|
config = {}
|
|
current_section = None
|
|
current_list_key = None
|
|
|
|
with open(config_path, "r") as f:
|
|
for raw_line in f:
|
|
line = raw_line.split("#", 1)[0].rstrip()
|
|
if not line.strip():
|
|
continue
|
|
|
|
if not line.startswith(" "):
|
|
if ":" not in line:
|
|
continue
|
|
key, value = line.split(":", 1)
|
|
key = key.strip()
|
|
value = value.strip()
|
|
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:
|
|
continue
|
|
|
|
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)
|
|
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
|
|
|
|
|
|
def load_config(config_path):
|
|
"""
|
|
Loads YAML config when available. Falls back to empty config.
|
|
"""
|
|
try:
|
|
import yaml # Local import so runtime still works without PyYAML
|
|
except ImportError:
|
|
try:
|
|
return _load_config_minimal(config_path)
|
|
except FileNotFoundError:
|
|
return {}
|
|
except Exception as e:
|
|
logging.warning(f"Failed to read config file '{config_path}': {e}")
|
|
return {}
|
|
|
|
try:
|
|
with open(config_path, "r") as f:
|
|
return yaml.safe_load(f) or {}
|
|
except FileNotFoundError:
|
|
return {}
|
|
except Exception as e:
|
|
logging.warning(f"Failed to read config file '{config_path}': {e}")
|
|
return {}
|
|
|
|
|
|
def cfg_get(config, *keys, default=None):
|
|
cur = config
|
|
for key in keys:
|
|
if not isinstance(cur, dict):
|
|
return default
|
|
cur = cur.get(key)
|
|
return default if cur is None else cur
|
|
|
|
|
|
def as_int(value, default):
|
|
try:
|
|
return int(value)
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
|
|
def as_float(value, default):
|
|
try:
|
|
return float(value)
|
|
except (TypeError, ValueError):
|
|
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(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
filename=log_path,
|
|
force=True,
|
|
)
|
|
|
|
|
|
def load_runtime_settings():
|
|
config_path = os.getenv("THREAT_AGENT_CONFIG", DEFAULT_CONFIG_PATH)
|
|
config = load_config(config_path)
|
|
|
|
node_name = os.getenv(
|
|
"SERVER_NAME",
|
|
cfg_get(config, "agent", "node_name", default=DEFAULT_NODE_NAME),
|
|
)
|
|
log_path = os.getenv(
|
|
"LOG_PATH",
|
|
cfg_get(config, "agent", "log_path", default=DEFAULT_LOG_PATH),
|
|
)
|
|
state_file = os.getenv(
|
|
"STATE_FILE",
|
|
cfg_get(config, "agent", "state_file", default=DEFAULT_STATE_FILE),
|
|
)
|
|
check_interval = as_int(
|
|
os.getenv("CHECK_INTERVAL", cfg_get(config, "agent", "check_interval")),
|
|
DEFAULT_CHECK_INTERVAL,
|
|
)
|
|
check_jitter_pct = as_float(
|
|
os.getenv("CHECK_JITTER_PCT", cfg_get(config, "agent", "check_jitter_pct")),
|
|
DEFAULT_CHECK_JITTER_PCT,
|
|
)
|
|
check_jitter_pct = min(max(check_jitter_pct, 0.0), 0.90)
|
|
heal_verify_delay = as_int(
|
|
os.getenv(
|
|
"HEAL_VERIFY_DELAY",
|
|
cfg_get(config, "agent", "heal_verify_delay"),
|
|
),
|
|
DEFAULT_HEAL_VERIFY_DELAY,
|
|
)
|
|
heal_min_interval = as_int(
|
|
os.getenv(
|
|
"HEAL_MIN_INTERVAL",
|
|
cfg_get(config, "agent", "heal_min_interval"),
|
|
),
|
|
DEFAULT_HEAL_MIN_INTERVAL,
|
|
)
|
|
membership_recheck_delay = as_int(
|
|
os.getenv(
|
|
"MEMBERSHIP_RECHECK_DELAY",
|
|
cfg_get(config, "agent", "membership_recheck_delay"),
|
|
),
|
|
DEFAULT_MEMBERSHIP_RECHECK_DELAY,
|
|
)
|
|
enforcement_targets = _resolve_enforcement_targets(config)
|
|
enforcement_sets = _resolve_enforcement_sets(config)
|
|
ranges_enabled = cfg_get(config, "ranges", "enabled", default=False) is True
|
|
ranges_table = (
|
|
str(cfg_get(config, "ranges", "table", default=DEFAULT_RANGES_TABLE)).strip()
|
|
)
|
|
ranges_min_prefix_v4 = as_int(
|
|
cfg_get(config, "ranges", "min_prefix_v4"), DEFAULT_RANGES_MIN_PREFIX_V4
|
|
)
|
|
ranges_min_prefix_v6 = as_int(
|
|
cfg_get(config, "ranges", "min_prefix_v6"), DEFAULT_RANGES_MIN_PREFIX_V6
|
|
)
|
|
|
|
return RuntimeSettings(
|
|
node_name=node_name,
|
|
log_path=log_path,
|
|
state_file=state_file,
|
|
check_interval=check_interval,
|
|
check_jitter_pct=check_jitter_pct,
|
|
heal_verify_delay=heal_verify_delay,
|
|
heal_min_interval=heal_min_interval,
|
|
enforcement_targets=enforcement_targets,
|
|
enforcement_sets=enforcement_sets,
|
|
config_path=config_path,
|
|
membership_recheck_delay=membership_recheck_delay,
|
|
ranges_enabled=ranges_enabled,
|
|
ranges_table=ranges_table,
|
|
ranges_min_prefix_v4=ranges_min_prefix_v4,
|
|
ranges_min_prefix_v6=ranges_min_prefix_v6,
|
|
)
|
|
|
|
|
|
def validate_runtime_settings(settings):
|
|
issues = []
|
|
|
|
if settings.check_interval < 1:
|
|
issues.append(
|
|
ValidationIssue(
|
|
"ERROR",
|
|
f"check_interval must be >= 1 (got {settings.check_interval})",
|
|
)
|
|
)
|
|
if settings.heal_verify_delay < 0:
|
|
issues.append(
|
|
ValidationIssue(
|
|
"ERROR",
|
|
f"heal_verify_delay must be >= 0 (got {settings.heal_verify_delay})",
|
|
)
|
|
)
|
|
if settings.heal_min_interval < 0:
|
|
issues.append(
|
|
ValidationIssue(
|
|
"ERROR",
|
|
f"heal_min_interval must be >= 0 (got {settings.heal_min_interval})",
|
|
)
|
|
)
|
|
if settings.membership_recheck_delay < 0:
|
|
issues.append(
|
|
ValidationIssue(
|
|
"ERROR",
|
|
"membership_recheck_delay must be >= 0 "
|
|
f"(got {settings.membership_recheck_delay})",
|
|
)
|
|
)
|
|
if not settings.enforcement_targets:
|
|
issues.append(
|
|
ValidationIssue("ERROR", "At least one enforcement target is required.")
|
|
)
|
|
|
|
for target in settings.enforcement_targets:
|
|
if (
|
|
not isinstance(target, tuple)
|
|
or len(target) != 2
|
|
or not all(isinstance(part, str) and part.strip() for part in target)
|
|
):
|
|
issues.append(
|
|
ValidationIssue(
|
|
"ERROR",
|
|
f"Malformed enforcement target: {target!r}",
|
|
)
|
|
)
|
|
|
|
if settings.ranges_enabled:
|
|
if not settings.ranges_table:
|
|
issues.append(ValidationIssue("ERROR", "ranges.table must not be empty."))
|
|
if not 1 <= settings.ranges_min_prefix_v4 <= 32:
|
|
issues.append(
|
|
ValidationIssue(
|
|
"ERROR",
|
|
"ranges.min_prefix_v4 must be within [1, 32] "
|
|
f"(got {settings.ranges_min_prefix_v4})",
|
|
)
|
|
)
|
|
if not 1 <= settings.ranges_min_prefix_v6 <= 128:
|
|
issues.append(
|
|
ValidationIssue(
|
|
"ERROR",
|
|
"ranges.min_prefix_v6 must be within [1, 128] "
|
|
f"(got {settings.ranges_min_prefix_v6})",
|
|
)
|
|
)
|
|
|
|
if settings.check_jitter_pct < 0.0 or settings.check_jitter_pct > 0.90:
|
|
issues.append(
|
|
ValidationIssue(
|
|
"WARN",
|
|
f"check_jitter_pct should be between 0.0 and 0.90 (got {settings.check_jitter_pct})",
|
|
)
|
|
)
|
|
if not os.path.isabs(settings.state_file):
|
|
issues.append(
|
|
ValidationIssue(
|
|
"WARN",
|
|
f"state_file is not absolute: {settings.state_file}",
|
|
)
|
|
)
|
|
|
|
return issues
|