diff --git a/README.md b/README.md index 72b866d..8a39c13 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,242 @@ -# Threat Engine Agent (Triton Edition) +# threat-engine-agent -A self-healing synchronization agent designed to ensure the local `nftables` kernel state perfectly matches the CrowdSec Local API (LAPI) desired state. +A reconciliation and self-healing agent for CrowdSec + `nftables` environments. +`threat-engine-agent` continuously compares CrowdSec Local API (LAPI) decision truth to the actual `nftables` kernel enforcement state on a node. When drift is detected, it can apply a targeted heal, verify convergence, and record structured telemetry for operators. +This is intended for operators running CrowdSec with `nftables` who want stronger guarantees than β€œthe bouncer is probably in sync.” -## 🎯 Purpose -The standard `crowdsec-firewall-bouncer` can occasionally experience "ghost" desynchronization where the LAPI removes a ban, but the kernel retains it (or vice-versa). This agent acts as a high-integrity supervisor to: -1. **Audit:** Compare LAPI "Truth" vs. `nftables` "Reality" every cycle. -2. **Heal:** Restart `crowdsec-firewall-bouncer` on desync to force a fresh LAPI pull. -3. **Verify:** Re-check state after healing and record success/failure telemetry. +--- -## πŸ› οΈ Technical Architecture +## Why this exists -### The Auditor (`auditor.py`) -- **Schema-tolerant parsing:** Supports both flat decision JSON and nested alert-style JSON from `cscli`. -- **State reconciliation:** Compares LAPI decision IP set against kernel IP set and computes drift as `missing` and `extra`. -- **Drift fingerprinting:** Generates a deterministic fingerprint for flap suppression and heal history. -- **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`. +In practice, `crowdsec-firewall-bouncer` can occasionally drift from the state CrowdSec intends to enforce. -### The Orchestrator (`main.py`) -- Runs the reconcile loop (default `600s` interval). -- Applies bounded random check jitter (default `10%`) to avoid synchronized polling across nodes. -- Validates effective runtime config at boot and fails fast on invalid critical settings. -- Triggers heal when any drift is detected. -- Applies flap suppression using drift fingerprint, not raw kernel count. -- Performs post-heal verification after a short delay (default `5s`). +Examples include: -### The Reporter (`reporter.py`) -- Writes local health state JSON atomically. -- Persists structured heal history, including pre/post fingerprints and heal result. -- Exposes lightweight node metrics in state (`uptime_seconds`, `checks_total`, `heals_total`, `heal_failures_total`). -- Tracks drift activity counters (`drift_events_total`, `drift_heal_attempts_total`) for suppression/load visibility. -- Exposes rolling 24h counters (`drift_events_24h`, `drift_heal_attempts_24h`, `heals_24h`, `heal_failures_24h`). -- Default state path: `/root/threat-engine-agent/threat-agent-state.json`. +- a decision exists in LAPI but is missing from kernel enforcement +- an IP remains in `nftables` after the decision has expired upstream +- long-duration bans remain present, but their kernel metadata appears stale or near expiry +- the bouncer process is running, but actual enforcement no longer matches CrowdSec’s desired state + +`threat-engine-agent` acts as a supervisory reconciliation loop: + +1. **Audit** the node’s live enforcement state against LAPI truth +2. **Classify** drift as membership mismatch or metadata drift +3. **Heal** using a targeted remediation path +4. **Verify** that post-heal state converged +5. **Record** the result for operators and dashboards + +This turns firewall enforcement from a best-effort assumption into something measurable and self-correcting. + +--- + +## What it does + +At a high level, the agent: + +- queries CrowdSec decisions via `cscli` +- normalizes decision data across supported JSON shapes +- inspects `nftables` state directly from kernel tables +- compares desired vs observed enforcement across IPv4 and IPv6 +- detects: + - **membership drift**: missing or extra enforced IPs + - **metadata drift**: bans present in kernel state, but with suspicious remaining TTL / expiry metadata +- computes a deterministic drift fingerprint +- suppresses repeated no-op heals for identical recent drift +- performs a heal when allowed +- re-checks state after healing +- writes structured local state and heal history for external reporting + +--- + +## Example reconciliation flow + +A real metadata drift event looks like this: -## πŸ“‚ Project Structure ```text -threat-engine-agent/ -β”œβ”€β”€ 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) -β”œβ”€β”€ systemd/ # Deployment configurations -β”‚ └── threat-agent.service -└── logs/ # Runtime logs +2026-04-04 20:05:13,383 - root - INFO - LAPI Local Parser: Found 295 active bans. +2026-04-04 20:05:13,390 - root - WARNING - Metadata Drift detected (count=3). +2026-04-04 20:05:13,390 - root - WARNING - Desync detected (kernel=295, missing=0, extra=0, metadata=3). +2026-04-04 20:05:13,390 - root - WARNING - Healing approved. +2026-04-04 20:05:13,445 - root - INFO - Heal: Flushed CrowdSec nft sets to clear stale metadata. +2026-04-04 20:05:13,689 - root - INFO - Heal: Bouncer restarted successfully. +2026-04-04 20:05:13,689 - root - INFO - Post-heal verification in 5s (pre_fingerprint=ecfd0f22f0c86788). +2026-04-04 20:05:18,797 - root - INFO - LAPI Local Parser: Found 295 active bans. +2026-04-04 20:05:18,804 - root - WARNING - Post-heal verification result result=success pre=ecfd0f22f0c86788 post= missing=0 extra=0 metadata=0 +2026-04-04 20:14:37,296 - root - INFO - LAPI Local Parser: Found 295 active bans. +2026-04-04 20:14:37,303 - root - INFO - Audit Success: 295 IPs in sync. ``` -## πŸš€ Installation & Deployment +In this case: -1. Environment Setup: +- LAPI still reported 295 valid bans +- kernel membership matched +- three bans showed stale metadata / TTL behavior +- the agent chose the metadata-drift remediation path +- CrowdSec-managed sets were flushed +- the bouncer was restarted +- post-heal verification confirmed full convergence -```bash -mkdir -p /root/threat-engine-agent/logs +That is the core design goal of this agent: **don’t just restart blindly β€” detect, classify, remediate, and verify**. + +--- + +## Privileges / safety + +This agent is designed for system-level enforcement reconciliation and therefore **requires elevated privileges** in normal operation. + +It needs sufficient access to: + +- run `cscli decisions list -a -o json` +- inspect `nftables` tables via `nft -j list table ...` +- flush managed CrowdSec sets when performing metadata-drift healing +- restart `crowdsec-firewall-bouncer` via `systemctl` + +### What it changes + +Depending on drift type, the agent may: + +- read CrowdSec decision state +- read `nftables` kernel state +- flush **managed CrowdSec sets only** +- restart `crowdsec-firewall-bouncer` +- write local health state / history files + +### What it does not change + +By design, the agent does **not**: + +- manage unrelated firewall policy +- rewrite arbitrary `nftables` rulesets +- invent its own ban decisions +- replace CrowdSec or the firewall bouncer +- act as a general-purpose firewall orchestration framework + +It is a narrow reconciliation and healing supervisor for CrowdSec enforcement drift. + +--- + +## Core components + +### `auditor.py` + +Responsible for desired-vs-observed reconciliation. + +Key behaviors: + +- schema-tolerant parsing of `cscli` JSON output +- support for flat decision objects and nested alert-like payloads +- normalization of CrowdSec decision metadata +- scanning of both IPv4 and IPv6 enforcement targets +- membership mismatch detection (`missing` / `extra`) +- TTL / metadata drift detection for long-duration bans +- drift fingerprint generation for suppression and history correlation + +### `healing.py` + +Responsible for heal gating and post-heal validation. + +Key behaviors: + +- prevents repeated heals for the same recent drift fingerprint +- executes remediation through the auditor +- waits a configurable delay before re-checking +- records whether the heal actually converged +- distinguishes restart failure, verification failure, and success + +### `doctor.py` + +Preflight self-test / environment validation. + +Checks include: + +- runtime config sanity +- `cscli` JSON parseability +- configured `nftables` table accessibility +- writable state paths +- `systemctl` restart capability for `crowdsec-firewall-bouncer` + +### `reporter.py` + +Persists lightweight node state and heal history for dashboards and operators. + +Exposes metrics such as: + +- `uptime_seconds` +- `checks_total` +- `heals_total` +- `heal_failures_total` +- `drift_events_total` +- rolling 24h counters for drift and healing activity + +### `main.py` + +Orchestrates the full reconcile loop. + +Features include: + +- configurable check interval +- bounded random jitter to avoid synchronized polling +- fail-fast config validation at startup +- heal triggering on detected drift +- post-heal verification + +--- + +## Drift model + +The agent currently reasons about two main drift categories: + +### 1. Membership mismatch + +The set of IPs CrowdSec wants enforced does not match what kernel state currently holds. + +Examples: + +- LAPI decision exists, kernel entry missing +- kernel entry exists, but CrowdSec no longer considers it active + +### 2. Metadata drift + +An IP is present in both places, but expiry / TTL behavior suggests stale or invalid kernel metadata. + +This is especially important for longer-duration bans, where stale metadata can create β€œlooks present, behaves wrong” enforcement drift. + +To reduce noise, short-duration TTL variance is intentionally tolerated. The goal is to catch meaningful desynchronization, not harmless decay. + +--- + +## Project structure + +```text + threat-engine-agent/ + β”œβ”€β”€ agent.py # Compatibility entrypoint / CLI wrapper + β”œβ”€β”€ main.py # Main loop and orchestration + β”œβ”€β”€ config.py # Runtime settings + logging setup + β”œβ”€β”€ auditor.py # LAPI vs nft reconciliation and drift fingerprinting + β”œβ”€β”€ healing.py # Heal gating + post-heal verification + β”œβ”€β”€ doctor.py # Preflight diagnostics + β”œβ”€β”€ reporter.py # Local state + heal history writer + β”œβ”€β”€ config.yaml # Runtime defaults (overridable) + β”œβ”€β”€ systemd/ + β”‚ └── threat-agent.service + └── tests/ +``` + +--- + +## Installation + +### 1. Prepare directories + +```bash +sudo mkdir -p /root/threat-engine-agent/logs cd /root/threat-engine-agent cp .env.example .env ``` -2. Systemd Integration: +### 2. Install service ```bash sudo cp systemd/threat-agent.service /etc/systemd/system/ @@ -68,12 +244,30 @@ sudo systemctl daemon-reload sudo systemctl enable --now threat-agent ``` -### Configuration Precedence -1. Environment variables (from systemd environment and/or `.env`) +### 3. Watch logs + +```bash +tail -f /root/threat-engine-agent/logs/threat-agent.log +``` + +### 4. Run preflight checks + +```bash +python3 agent.py --doctor +``` + +--- + +## Configuration + +Configuration precedence: + +1. environment variables 2. `config.yaml` -3. Built-in defaults in code +3. built-in defaults + +Supported environment overrides: -Supported env overrides: - `SERVER_NAME` - `CHECK_INTERVAL` - `CHECK_JITTER_PCT` @@ -83,29 +277,92 @@ Supported env overrides: - `STATE_FILE` - `THREAT_AGENT_CONFIG` -`config.yaml` also controls enforcement scan/flush scope: -- `enforcement.targets` (preferred): list of `{family, table}` mappings -- legacy fallback: `enforcement.table`, `enforcement.table6`, and `enforcement.families` -- `enforcement.sets`: optional allowlist of set names to manage (when omitted, `*-cscli` sets are managed) +### Enforcement scope -3. Monitoring: +`config.yaml` supports: -```bash -# Watch the agent in real time -tail -f /root/threat-engine-agent/logs/threat-agent.log -``` +- `enforcement.targets`: list of `{family, table}` mappings +- `enforcement.sets`: optional allowlist of set names to manage -4. Preflight Self-Test: +If no explicit set allowlist is given, the agent defaults to managing CrowdSec-style `*-cscli` sets where applicable. This keeps healing scope intentionally narrow. -```bash -# Run startup diagnostics without entering the main loop -python3 agent.py --doctor -``` +--- -## πŸ” Troubleshooting +## Operational notes -If you see a "Heal Loop" in the logs: -1. **Check decision source**: Run `/usr/bin/cscli decisions list -a -o json` and confirm output shape/contents are valid. -2. **Check kernel state**: Run `nft -j list table ip crowdsec` and `nft -j list table ip6 crowdsec6`. -3. **Check drift telemetry**: Review `missing`, `extra`, `drift_fingerprint`, `heal_result`, and `post_drift_fingerprint` in logs/history. -4. **Check service health**: `systemctl status threat-agent crowdsec-firewall-bouncer`. +- This agent is best suited for hosts where CrowdSec enforcement correctness matters enough to justify active reconciliation. +- It is intentionally conservative about repeated heals and uses drift fingerprints to suppress flap loops. +- Post-heal verification is part of the design, not an optional extra: a restart is not treated as success unless state actually converges. +- `doctor.py` should be run before first deployment or after major environment changes. + +--- + +## Troubleshooting + +If the agent appears stuck in repeated drift or heal behavior: + +1. Inspect CrowdSec decision output: + + /usr/bin/cscli decisions list -a -o json + +2. Inspect current kernel enforcement state: + + nft -j list table ip crowdsec + nft -j list table ip6 crowdsec6 + +3. Review local agent logs and history: + - drift fingerprint + - missing / extra counts + - metadata drift count + - heal result + - post-heal fingerprint + +4. Check service status: + + systemctl status threat-agent crowdsec-firewall-bouncer + +5. Run diagnostics: + + python3 agent.py --doctor + +--- + +## Why not just trust the bouncer? + +In many environments, trusting the bouncer is fine. + +This agent exists for operators who want stronger guarantees around enforcement correctness, especially in multi-node or long-running environments where silent drift is costly or hard to notice. + +It does not replace CrowdSec’s decisioning model. It supervises the last-mile enforcement path and verifies that local kernel state still reflects upstream intent. + +If the bouncer is healthy and in sync, the agent becomes a lightweight audit loop. +If drift appears, it provides a structured, verifiable path back to convergence. + +--- + +## Scope and philosophy + +`threat-engine-agent` is intentionally narrow. + +It does not try to become a full security control plane. It solves one problem well: + +**keeping CrowdSec enforcement aligned with actual kernel reality, and proving when it is.** + +That means: + +- deterministic reconciliation over guesswork +- targeted healing over blind restart loops +- verification over assumption +- operational evidence over β€œit should be fine” + +--- + +## Status + +This project is designed for real production use, but the interface and documentation may continue to evolve as the agent is generalized beyond its original environment. + +--- + +## License + +MIT License