Files
threat-engine-agent/main.py
T
patrickandClaude Opus 5.5 7156cfd4fe
CI / Unit tests (push) Successful in 9s
CI / Unit tests (pull_request) Successful in 6s
feat(ranges): enforce LAPI range decisions in an agent-owned nft table
crowdsec-firewall-bouncer's nftables mode strips the prefix from Range
decisions and bans only the network address, so a /24 decision blocked
a single IP. With ranges.enabled, every audit now syncs range decisions
into a dedicated `inet crowdsec-ranges` table (interval+timeout sets with
input/forward drop chains) in one atomic `nft -f` transaction, then reads
it back to confirm each range is enforced.

- element timeouts track each decision's remaining lifetime; stale
  elements are removed and extended decisions refreshed
- ranges nested in another active range are covered, not inserted
- ranges broader than min_prefix_v4/v6 (default /16, /32) are refused
- ranges still missing after the sync stay in unenforceable_ranges, so
  the node reports DEGRADED rather than HEALTHY
- the bouncer-set scan normalizes nft prefix elements to addr/len
  instead of failing the table scan on them
- doctor checks the range table; the audit log line says when a synced
  node is degraded

Disabled by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:54:26 -04:00

208 lines
7.8 KiB
Python

import logging
import random
import signal
import threading
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, validate_runtime_settings
from healing import execute_heal_and_verify, recheck_membership_mismatch, should_heal
from ranges import RangeEnforcer
from reporter import LocalStateReporter
def compute_sleep_interval(base_interval, jitter_pct):
base = max(1.0, float(base_interval))
jitter = min(max(float(jitter_pct), 0.0), 0.90)
if jitter == 0:
return base
factor = 1.0 + random.uniform(-jitter, jitter)
return max(1.0, base * factor)
def main():
"""
The Orchestrator: Links Audit findings to the State Reporter.
"""
load_dotenv()
settings = load_runtime_settings()
setup_logging(settings.log_path)
issues = validate_runtime_settings(settings)
for issue in issues:
if issue.level == "ERROR":
logging.error(f"Config validation: {issue.message}")
else:
logging.warning(f"Config validation: {issue.message}")
if any(issue.level == "ERROR" for issue in issues):
raise RuntimeError("Configuration validation failed; refusing to start.")
targets_desc = ", ".join(
f"{family}:{table}" for family, table in settings.enforcement_targets
)
sets_mode = "explicit" if settings.enforcement_sets else "auto(*-cscli)"
sets_desc = ", ".join(settings.enforcement_sets) if settings.enforcement_sets else "(none)"
logging.info(
"Effective config: "
f"node={settings.node_name} "
f"check_interval={settings.check_interval}s "
f"check_jitter_pct={settings.check_jitter_pct:.2f} "
f"heal_verify_delay={settings.heal_verify_delay}s "
f"heal_min_interval={settings.heal_min_interval}s "
f"membership_recheck_delay={settings.membership_recheck_delay}s "
f"state_file={settings.state_file} "
f"targets=[{targets_desc}] "
f"sets_mode={sets_mode} sets=[{sets_desc}] "
f"ranges_enabled={settings.ranges_enabled} ranges_table={settings.ranges_table} "
f"ranges_min_prefix=v4:/{settings.ranges_min_prefix_v4},"
f"v6:/{settings.ranges_min_prefix_v6}"
)
range_enforcer = None
if settings.ranges_enabled:
range_enforcer = RangeEnforcer(
table=settings.ranges_table,
min_prefix_v4=settings.ranges_min_prefix_v4,
min_prefix_v6=settings.ranges_min_prefix_v6,
)
auditor = FirewallAuditor(
targets=settings.enforcement_targets,
managed_sets=settings.enforcement_sets,
range_enforcer=range_enforcer,
)
auditor.log_enforcement_startup_state()
reporter = LocalStateReporter(
state_file=settings.state_file,
node_name=settings.node_name,
)
stop_event = threading.Event()
def _handle_stop_signal(signum, _frame):
sig_name = signal.Signals(signum).name
logging.info(f"Stop signal received: {sig_name}. Shutting down.")
stop_event.set()
signal.signal(signal.SIGTERM, _handle_stop_signal)
signal.signal(signal.SIGINT, _handle_stop_signal)
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} "
f"check_jitter_pct={settings.check_jitter_pct:.2f}"
)
while not stop_event.is_set():
try:
is_synced, count, drift = recheck_membership_mismatch(
auditor,
auditor.reconcile(),
settings.membership_recheck_delay,
wait=stop_event.wait,
)
if stop_event.is_set():
break
# Decide on the heal before recording the check, so a drift the gate
# suppresses is counted as such rather than silently lacking a heal.
heal_approved = is_synced or should_heal(
reporter.get_history_file(),
drift.get("fingerprint", ""),
min_interval=settings.heal_min_interval,
)
reporter.update_status(
is_synced,
count,
missing_count=drift.get("missing_count", 0),
extra_count=drift.get("extra_count", 0),
metadata_drift_count=drift.get("metadata_drift_count", 0),
last_drift_fingerprint=drift.get("fingerprint", ""),
checks_increment=1,
drift_events_increment=0 if is_synced else 1,
heal_suppressed=not heal_approved,
unenforceable_range_count=len(drift.get("unenforceable_ranges", [])),
)
unenforced_ranges = len(drift.get("unenforceable_ranges", []))
if is_synced and unenforced_ranges:
status_msg = (
f"Audit Success (degraded): {count} IPs in sync, "
f"{unenforced_ranges} range decision(s) not enforced."
)
elif 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']})."
)
if heal_approved:
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(status_msg)
sleep_seconds = compute_sleep_interval(
settings.check_interval,
settings.check_jitter_pct,
)
print(f"[*] Sleeping for {sleep_seconds:.1f} seconds...")
stop_event.wait(sleep_seconds)
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}"
)
if stop_event.wait(60):
break
logging.info("Agent shutdown complete.")
if __name__ == "__main__":
main()