import json import os import tempfile import subprocess from dataclasses import dataclass @dataclass(frozen=True) class CheckResult: name: str status: str # PASS | WARN | FAIL detail: str def _run_cmd(cmd, timeout=20): return subprocess.run( cmd, check=True, capture_output=True, text=True, timeout=timeout, ) def check_runtime_settings(settings): if settings.check_interval < 1: return CheckResult( "runtime_settings", "FAIL", f"check_interval must be >= 1 (got {settings.check_interval})", ) if settings.check_jitter_pct < 0 or settings.check_jitter_pct > 0.90: return CheckResult( "runtime_settings", "FAIL", f"check_jitter_pct must be within [0.0, 0.90] (got {settings.check_jitter_pct})", ) if not settings.enforcement_targets: return CheckResult("runtime_settings", "FAIL", "No enforcement targets configured.") return CheckResult( "runtime_settings", "PASS", ( f"check_interval={settings.check_interval}s " f"check_jitter_pct={settings.check_jitter_pct:.2f} " f"targets={len(settings.enforcement_targets)}" ), ) def check_cscli_json(): try: res = _run_cmd(["/usr/bin/cscli", "decisions", "list", "-a", "-o", "json"]) payload = json.loads(res.stdout or "[]") if isinstance(payload, list): return CheckResult("cscli_json", "PASS", f"Parsed {len(payload)} top-level entries.") if isinstance(payload, dict): return CheckResult("cscli_json", "PASS", "Parsed JSON object payload.") return CheckResult("cscli_json", "FAIL", "Unexpected JSON type from cscli.") except subprocess.CalledProcessError as e: stderr = (e.stderr or "").strip() return CheckResult("cscli_json", "FAIL", f"Command failed: {stderr or e}") except json.JSONDecodeError as e: return CheckResult("cscli_json", "FAIL", f"Invalid JSON output: {e}") except Exception as e: return CheckResult("cscli_json", "FAIL", f"Unexpected error: {e}") def check_nft_tables(settings): failures = [] summaries = [] for family, table in settings.enforcement_targets: try: res = _run_cmd(["/usr/sbin/nft", "-j", "list", "table", family, table]) data = json.loads(res.stdout or "{}") set_count = sum( 1 for item in data.get("nftables", []) if isinstance(item.get("set"), dict) ) summaries.append(f"{family} {table} ({set_count} sets)") except Exception as e: failures.append(f"{family} {table}: {e}") if failures: return CheckResult("nft_tables", "FAIL", "; ".join(failures)) return CheckResult("nft_tables", "PASS", ", ".join(summaries)) def check_range_table(settings): if not settings.ranges_enabled: return CheckResult("range_table", "PASS", "Range enforcement disabled.") try: res = _run_cmd(["/usr/sbin/nft", "-j", "list", "table", "inet", settings.ranges_table]) data = json.loads(res.stdout or "{}") set_names = { item["set"].get("name") for item in data.get("nftables", []) if isinstance(item.get("set"), dict) } missing = {"ranges-v4", "ranges-v6"} - set_names if missing: return CheckResult( "range_table", "FAIL", f"inet {settings.ranges_table} lacks sets: {', '.join(sorted(missing))}", ) return CheckResult("range_table", "PASS", f"inet {settings.ranges_table} present.") except subprocess.CalledProcessError: return CheckResult( "range_table", "WARN", f"inet {settings.ranges_table} not found; the agent creates it on its first audit.", ) except Exception as e: return CheckResult("range_table", "FAIL", f"Unexpected error: {e}") def check_state_paths(settings): state_dir = os.path.dirname(os.path.abspath(settings.state_file)) history_file = os.path.splitext(settings.state_file)[0] + ".history" history_dir = os.path.dirname(os.path.abspath(history_file)) try: os.makedirs(state_dir, exist_ok=True) os.makedirs(history_dir, exist_ok=True) with tempfile.NamedTemporaryFile(dir=state_dir, prefix="doctor-", delete=True): pass return CheckResult("state_paths", "PASS", f"Writable: {state_dir}") except Exception as e: return CheckResult("state_paths", "FAIL", f"Path check failed: {e}") def check_systemctl_restart_capability(): if os.geteuid() != 0: return CheckResult( "systemctl_restart_capability", "WARN", "Not running as root; bouncer restart may fail.", ) try: res = _run_cmd( [ "systemctl", "show", "crowdsec-firewall-bouncer", "--property=LoadState", "--property=CanStart", "--value", ] ) lines = [line.strip() for line in (res.stdout or "").splitlines() if line.strip()] load_state = lines[0] if len(lines) >= 1 else "" can_start = lines[1] if len(lines) >= 2 else "" if load_state == "not-found": return CheckResult( "systemctl_restart_capability", "FAIL", "crowdsec-firewall-bouncer unit not found.", ) if can_start.lower() == "no": return CheckResult( "systemctl_restart_capability", "FAIL", "systemd reports CanStart=no for crowdsec-firewall-bouncer.", ) return CheckResult( "systemctl_restart_capability", "PASS", f"LoadState={load_state or 'unknown'} CanStart={can_start or 'unknown'}", ) except Exception as e: return CheckResult( "systemctl_restart_capability", "WARN", f"Could not verify via systemctl: {e}", ) def run_doctor(settings, output=print): checks = [ check_runtime_settings(settings), check_cscli_json(), check_nft_tables(settings), check_range_table(settings), check_state_paths(settings), check_systemctl_restart_capability(), ] output("Threat Engine Agent doctor results:") for item in checks: output(f"[{item.status}] {item.name}: {item.detail}") failed = [item for item in checks if item.status == "FAIL"] warned = [item for item in checks if item.status == "WARN"] output(f"Summary: {len(failed)} failed, {len(warned)} warnings, {len(checks)} total.") return len(failed) == 0