Files

113 lines
3.3 KiB
Python

# 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
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='/root/threat-engine-agent/logs/threat-agent.log'
)
################
#### Helpers ###
################
def should_heal(history_file, current_count, 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_count = int(msg.split("desync of")[1].split("IPs")[0])
# If healed recently AND nothing changed, suppress
if datetime.now() - last_time < timedelta(seconds=min_interval):
if last_count == current_count:
logging.warning(
f"Heal suppressed (recent identical heal: {last_count} IPs)"
)
return False
return True
except Exception as e:
logging.error(f"Heal gate failed open: {e}")
return True
################
##### Main #####
################
def main():
"""
The Orchestrator: Links Audit findings to the State Reporter.
"""
load_dotenv()
auditor = FirewallAuditor()
reporter = LocalStateReporter()
node_name = os.getenv("SERVER_NAME", "Unknown Node")
CHECK_INTERVAL = 600
print(f"[*] Agent started. Check interval: {CHECK_INTERVAL}s")
logging.info(f"Threat Engine Agent initialized on {node_name}.")
while True:
try:
is_synced, count = auditor.reconcile()
reporter.update_status(is_synced, count)
status_msg = f"Audit Success: {count} IPs in sync." if is_synced else f"DESYNC: {count} in kernel. Healing..."
print(f"[+] {status_msg}") # This will show up in your terminal!
if not is_synced:
logging.warning(f"Desync detected ({count} IPs in kernel).")
history_file = reporter.state_file.replace(".json", ".history")
if should_heal(history_file, count):
logging.warning("Healing approved.")
auditor.heal()
reporter.log_heal_event(count)
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:
pass
time.sleep(60)
if __name__ == "__main__":
main()