# threat-engine-agent/agent.py import time import logging from auditor import FirewallAuditor from reporter import LocalStateReporter from dotenv import load_dotenv import os from datetime import datetime, timedelta 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()