137 lines
4.3 KiB
Python
137 lines
4.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, 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
|
|
|
|
|
|
################
|
|
##### 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, 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", "")):
|
|
logging.warning("Healing approved.")
|
|
auditor.heal()
|
|
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"),
|
|
)
|
|
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()
|