diff --git a/README.md b/README.md index 6066cd3..f438f3c 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ The standard `crowdsec-firewall-bouncer` can occasionally experience "ghost" des - **Metadata drift check:** Flags long-duration decisions that are near expiry in kernel state. - **Kernel scan scope:** Scans `ip crowdsec` and `ip6 crowdsec6` tables via `nft -j`. -### The Orchestrator (`agent.py`) +### The Orchestrator (`main.py`) - Runs the reconcile loop (default `600s` interval). - Triggers heal when any drift is detected. - Applies flap suppression using drift fingerprint, not raw kernel count. @@ -33,7 +33,10 @@ The standard `crowdsec-firewall-bouncer` can occasionally experience "ghost" des ## 📂 Project Structure ```text threat-engine-agent/ -├── agent.py # Main loop and heal orchestration +├── agent.py # Compatibility entrypoint used by systemd +├── main.py # Main loop and orchestration +├── config.py # Runtime settings + logging setup +├── healing.py # Heal gating + post-heal verification ├── auditor.py # LAPI vs nft reconciliation and drift fingerprinting ├── reporter.py # Local state and heal history writer ├── config.yaml # Runtime defaults (overridable by env) diff --git a/agent.py b/agent.py index 0135e96..f9e8721 100644 --- a/agent.py +++ b/agent.py @@ -1,334 +1,8 @@ -# threat-engine-agent/agent.py +from healing import execute_heal_and_verify, should_heal +from main import main -import time -import logging -from auditor import FirewallAuditor -from reporter import LocalStateReporter -from dotenv import load_dotenv -import os -from datetime import datetime, timedelta +__all__ = ["main", "should_heal", "execute_heal_and_verify"] -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_HEAL_VERIFY_DELAY = 5 -DEFAULT_HEAL_MIN_INTERVAL = 900 - - -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 - - 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 - else: - config[key] = _parse_scalar(value) - current_section = None - continue - - if current_section is None: - continue - - stripped = line.strip() - if stripped.startswith("- "): - continue - if ":" not in stripped: - continue - key, value = stripped.split(":", 1) - config[current_section][key.strip()] = _parse_scalar(value) - - 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 _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, - ) - -################ -#### Helpers ### -################ - -def should_heal(history_file, drift_fingerprint, min_interval=900): - """ - Prevents heal flapping by suppressing repeated no-op heals. - """ - try: - if not os.path.exists(history_file): - return True - - with open(history_file) as f: - lines = [l.strip() for l in f.readlines() if "HEAL:" in l] - - if not lines: - return True - - last = lines[-1] - ts_str, msg = last.split(" - ", 1) - last_time = datetime.fromisoformat(ts_str) - last_fingerprint = "" - marker = "drift_fingerprint=" - if marker in msg: - last_fingerprint = msg.split(marker, 1)[1].split()[0].strip() - - if not drift_fingerprint: - return True - - # If healed recently AND nothing changed, suppress - if datetime.now() - last_time < timedelta(seconds=min_interval): - if last_fingerprint and last_fingerprint == drift_fingerprint: - logging.warning( - "Heal suppressed (recent identical drift fingerprint)." - ) - return False - - return True - - except Exception as e: - logging.error(f"Heal gate failed open: {e}") - return True - - -def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay): - """ - Executes heal + post-heal verification and persists reporter state. - """ - heal_ok = auditor.heal() - heal_result = "restart_failed" - post_drift = { - "reason": "not_verified", - "missing_count": 0, - "extra_count": 0, - "metadata_drift_count": 0, - "fingerprint": "", - } - - if heal_ok: - logging.info( - f"Post-heal verification in {heal_verify_delay}s " - f"(pre_fingerprint={drift.get('fingerprint', '')})." - ) - time.sleep(heal_verify_delay) - post_is_synced, post_count, post_drift = auditor.reconcile() - heal_result = "success" if post_is_synced else "failed" - verify_error = None if post_is_synced else "Post-heal verification failed" - reporter.update_status(post_is_synced, post_count, last_error=verify_error) - - logging.warning( - "Post-heal verification result " - f"result={heal_result} pre={drift.get('fingerprint', '')} " - f"post={post_drift.get('fingerprint', '')} " - f"missing={post_drift.get('missing_count', 0)} " - f"extra={post_drift.get('extra_count', 0)} " - f"metadata={post_drift.get('metadata_drift_count', 0)}" - ) - else: - reporter.update_status(False, count, last_error="Bouncer restart failed") - logging.error( - f"Heal restart failed; skipping verification " - f"(pre_fingerprint={drift.get('fingerprint', '')})." - ) - - return heal_result, post_drift - - -################ -##### Main ##### -################ - -def main(): - """ - The Orchestrator: Links Audit findings to the State Reporter. - """ - load_dotenv() - config_path = os.getenv("THREAT_AGENT_CONFIG", "config.yaml") - config = _load_config(config_path) - - node_name = os.getenv( - "SERVER_NAME", - _cfg_get(config, "agent", "node_name", default="Unknown Node"), - ) - 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, - ) - 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, - ) - - _setup_logging(log_path) - auditor = FirewallAuditor() - reporter = LocalStateReporter(state_file=state_file, node_name=node_name) - - print(f"[*] Agent started. Check interval: {check_interval}s") - logging.info( - f"Threat Engine Agent initialized on {node_name}. " - f"config_path={config_path} log_path={log_path} state_file={state_file}" - ) - - while True: - try: - is_synced, count, drift = auditor.reconcile() - reporter.update_status(is_synced, count) - - if is_synced: - status_msg = f"Audit Success: {count} IPs in sync." - else: - status_msg = ( - f"DESYNC: kernel={count}, missing={drift['missing_count']}, " - f"extra={drift['extra_count']}, metadata={drift['metadata_drift_count']}. " - "Healing..." - ) - print(f"[+] {status_msg}") # This will show up in your terminal! - - if not is_synced: - logging.warning( - "Desync detected " - f"(kernel={count}, missing={drift['missing_count']}, " - f"extra={drift['extra_count']}, metadata={drift['metadata_drift_count']})." - ) - - history_file = reporter.state_file.replace(".json", ".history") - - if should_heal( - history_file, - drift.get("fingerprint", ""), - min_interval=heal_min_interval, - ): - logging.warning("Healing approved.") - heal_result, post_drift = execute_heal_and_verify( - auditor, - reporter, - count, - drift, - heal_verify_delay, - ) - - reporter.log_heal_event( - count, - drift.get("missing_count", 0), - drift.get("extra_count", 0), - drift.get("metadata_drift_count", 0), - drift.get("fingerprint", ""), - drift.get("reason", "unknown"), - heal_result, - post_drift.get("fingerprint", ""), - ) - else: - logging.warning("Healing skipped to prevent flapping.") - else: - logging.info(f"Audit Success: {count} IPs in sync.") - - print(f"[*] Sleeping for {check_interval} seconds...") - time.sleep(check_interval) - - except KeyboardInterrupt: - logging.info("Agent shutting down manually.") - break - except Exception as e: - logging.error(f"Main loop error: {e}") - # Ensure the reporter notes the error state - try: - reporter.update_status(False, 0, last_error=str(e)) - except Exception as reporter_error: - logging.error(f"Reporter update failed during exception handling: {reporter_error}") - time.sleep(60) if __name__ == "__main__": main() diff --git a/auditor.py b/auditor.py index e671ddc..c090619 100644 --- a/auditor.py +++ b/auditor.py @@ -4,7 +4,11 @@ import subprocess import json import logging import hashlib -from dotenv import load_dotenv +try: + from dotenv import load_dotenv +except ImportError: + def load_dotenv(): + return None class FirewallAuditor: def __init__(self): diff --git a/config.py b/config.py new file mode 100644 index 0000000..823ea9c --- /dev/null +++ b/config.py @@ -0,0 +1,175 @@ +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_HEAL_VERIFY_DELAY = 5 +DEFAULT_HEAL_MIN_INTERVAL = 900 +DEFAULT_CONFIG_PATH = "config.yaml" +DEFAULT_NODE_NAME = "Unknown Node" + + +@dataclass(frozen=True) +class RuntimeSettings: + node_name: str + log_path: str + state_file: str + check_interval: int + heal_verify_delay: int + heal_min_interval: int + config_path: 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 + + 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 + else: + config[key] = _parse_scalar(value) + current_section = None + continue + + if current_section is None: + continue + + stripped = line.strip() + if stripped.startswith("- "): + continue + if ":" not in stripped: + continue + key, value = stripped.split(":", 1) + config[current_section][key.strip()] = _parse_scalar(value) + + 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 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, + ) + 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, + ) + + return RuntimeSettings( + node_name=node_name, + log_path=log_path, + state_file=state_file, + check_interval=check_interval, + heal_verify_delay=heal_verify_delay, + heal_min_interval=heal_min_interval, + config_path=config_path, + ) diff --git a/healing.py b/healing.py new file mode 100644 index 0000000..caa9e1b --- /dev/null +++ b/healing.py @@ -0,0 +1,87 @@ +import logging +import os +import time +from datetime import datetime, timedelta + + +def should_heal(history_file, drift_fingerprint, min_interval=900): + """ + Prevents heal flapping by suppressing repeated no-op heals. + """ + try: + if not os.path.exists(history_file): + return True + + with open(history_file) as f: + lines = [l.strip() for l in f.readlines() if "HEAL:" in l] + + if not lines: + return True + + last = lines[-1] + ts_str, msg = last.split(" - ", 1) + last_time = datetime.fromisoformat(ts_str) + last_fingerprint = "" + marker = "drift_fingerprint=" + if marker in msg: + last_fingerprint = msg.split(marker, 1)[1].split()[0].strip() + + if not drift_fingerprint: + return True + + # If healed recently AND nothing changed, suppress + if datetime.now() - last_time < timedelta(seconds=min_interval): + if last_fingerprint and last_fingerprint == drift_fingerprint: + logging.warning( + "Heal suppressed (recent identical drift fingerprint)." + ) + return False + + return True + + except Exception as e: + logging.error(f"Heal gate failed open: {e}") + return True + + +def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay): + """ + Executes heal + post-heal verification and persists reporter state. + """ + heal_ok = auditor.heal() + heal_result = "restart_failed" + post_drift = { + "reason": "not_verified", + "missing_count": 0, + "extra_count": 0, + "metadata_drift_count": 0, + "fingerprint": "", + } + + if heal_ok: + logging.info( + f"Post-heal verification in {heal_verify_delay}s " + f"(pre_fingerprint={drift.get('fingerprint', '')})." + ) + time.sleep(heal_verify_delay) + post_is_synced, post_count, post_drift = auditor.reconcile() + heal_result = "success" if post_is_synced else "failed" + verify_error = None if post_is_synced else "Post-heal verification failed" + reporter.update_status(post_is_synced, post_count, last_error=verify_error) + + logging.warning( + "Post-heal verification result " + f"result={heal_result} pre={drift.get('fingerprint', '')} " + f"post={post_drift.get('fingerprint', '')} " + f"missing={post_drift.get('missing_count', 0)} " + f"extra={post_drift.get('extra_count', 0)} " + f"metadata={post_drift.get('metadata_drift_count', 0)}" + ) + else: + reporter.update_status(False, count, last_error="Bouncer restart failed") + logging.error( + f"Heal restart failed; skipping verification " + f"(pre_fingerprint={drift.get('fingerprint', '')})." + ) + + return heal_result, post_drift diff --git a/main.py b/main.py new file mode 100644 index 0000000..1f213d0 --- /dev/null +++ b/main.py @@ -0,0 +1,110 @@ +import logging +import time + +try: + from dotenv import load_dotenv +except ImportError: + def load_dotenv(): + return None + +from auditor import FirewallAuditor +from config import load_runtime_settings, setup_logging +from healing import execute_heal_and_verify, should_heal +from reporter import LocalStateReporter + + +def main(): + """ + The Orchestrator: Links Audit findings to the State Reporter. + """ + load_dotenv() + settings = load_runtime_settings() + + setup_logging(settings.log_path) + auditor = FirewallAuditor() + reporter = LocalStateReporter( + state_file=settings.state_file, + node_name=settings.node_name, + ) + + print(f"[*] Agent started. Check interval: {settings.check_interval}s") + logging.info( + f"Threat Engine Agent initialized on {settings.node_name}. " + f"config_path={settings.config_path} " + f"log_path={settings.log_path} state_file={settings.state_file}" + ) + + while True: + try: + is_synced, count, drift = auditor.reconcile() + reporter.update_status(is_synced, count) + + if is_synced: + status_msg = f"Audit Success: {count} IPs in sync." + else: + status_msg = ( + f"DESYNC: kernel={count}, missing={drift['missing_count']}, " + f"extra={drift['extra_count']}, metadata={drift['metadata_drift_count']}. " + "Healing..." + ) + print(f"[+] {status_msg}") # This will show up in your terminal! + + if not is_synced: + logging.warning( + "Desync detected " + f"(kernel={count}, missing={drift['missing_count']}, " + f"extra={drift['extra_count']}, metadata={drift['metadata_drift_count']})." + ) + + history_file = reporter.state_file.replace(".json", ".history") + + if should_heal( + history_file, + drift.get("fingerprint", ""), + min_interval=settings.heal_min_interval, + ): + logging.warning("Healing approved.") + heal_result, post_drift = execute_heal_and_verify( + auditor, + reporter, + count, + drift, + settings.heal_verify_delay, + ) + + reporter.log_heal_event( + count, + drift.get("missing_count", 0), + drift.get("extra_count", 0), + drift.get("metadata_drift_count", 0), + drift.get("fingerprint", ""), + drift.get("reason", "unknown"), + heal_result, + post_drift.get("fingerprint", ""), + ) + else: + logging.warning("Healing skipped to prevent flapping.") + else: + logging.info(f"Audit Success: {count} IPs in sync.") + + print(f"[*] Sleeping for {settings.check_interval} seconds...") + time.sleep(settings.check_interval) + + except KeyboardInterrupt: + logging.info("Agent shutting down manually.") + break + except Exception as e: + logging.error(f"Main loop error: {e}") + # Ensure the reporter notes the error state + try: + reporter.update_status(False, 0, last_error=str(e)) + except Exception as reporter_error: + logging.error( + "Reporter update failed during exception handling: " + f"{reporter_error}" + ) + time.sleep(60) + + +if __name__ == "__main__": + main() diff --git a/tests/test_agent.py b/tests/test_agent.py index ac6497a..6c8db2a 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -3,7 +3,7 @@ import unittest from datetime import datetime from unittest.mock import patch -from agent import should_heal, execute_heal_and_verify +from healing import should_heal, execute_heal_and_verify class FakeReporter: @@ -49,7 +49,7 @@ class HealGateTests(unittest.TestCase): class PostHealVerificationTests(unittest.TestCase): - @patch("agent.time.sleep", return_value=None) + @patch("healing.time.sleep", return_value=None) def test_execute_heal_and_verify_success(self, _sleep): reporter = FakeReporter() post_drift = { @@ -73,7 +73,7 @@ class PostHealVerificationTests(unittest.TestCase): self.assertEqual(post_drift, returned_post_drift) self.assertEqual([(True, 12, None)], reporter.update_calls) - @patch("agent.time.sleep", return_value=None) + @patch("healing.time.sleep", return_value=None) def test_execute_heal_and_verify_restart_failed(self, _sleep): reporter = FakeReporter() auditor = FakeAuditor(heal_ok=False, reconcile_result=(True, 0, {}))