feat(config): wire runtime settings from env/config with sane defaults
This commit is contained in:
1 parent
6dac06c117
commit
461512f20a
6 files changed
+195
-20
No files matched your search
@@ -1,2 +1,8 @@
|
||||
BOUNCER_KEY=example
|
||||
SERVER_NAME=Name
|
||||
CHECK_INTERVAL=600
|
||||
HEAL_VERIFY_DELAY=5
|
||||
HEAL_MIN_INTERVAL=900
|
||||
LOG_PATH=/root/threat-engine-agent/logs/threat-agent.log
|
||||
STATE_FILE=/root/threat-engine-agent/threat-agent-state.json
|
||||
THREAT_AGENT_CONFIG=config.yaml
|
||||
@@ -36,7 +36,7 @@ threat-engine-agent/
|
||||
├── agent.py # Main loop and heal orchestration
|
||||
├── auditor.py # LAPI vs nft reconciliation and drift fingerprinting
|
||||
├── reporter.py # Local state and heal history writer
|
||||
├── config.yaml # Static config (currently not wired into runtime)
|
||||
├── config.yaml # Runtime defaults (overridable by env)
|
||||
├── systemd/ # Deployment configurations
|
||||
│ └── threat-agent.service
|
||||
└── logs/ # Runtime logs
|
||||
@@ -49,6 +49,7 @@ threat-engine-agent/
|
||||
```bash
|
||||
mkdir -p /root/threat-engine-agent/logs
|
||||
cd /root/threat-engine-agent
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
2. Systemd Integration:
|
||||
@@ -59,6 +60,20 @@ sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now threat-agent
|
||||
```
|
||||
|
||||
### Configuration Precedence
|
||||
1. Environment variables (from systemd environment and/or `.env`)
|
||||
2. `config.yaml`
|
||||
3. Built-in defaults in code
|
||||
|
||||
Supported env overrides:
|
||||
- `SERVER_NAME`
|
||||
- `CHECK_INTERVAL`
|
||||
- `HEAL_VERIFY_DELAY`
|
||||
- `HEAL_MIN_INTERVAL`
|
||||
- `LOG_PATH`
|
||||
- `STATE_FILE`
|
||||
- `THREAT_AGENT_CONFIG`
|
||||
|
||||
3. Monitoring:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -8,11 +8,118 @@ 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'
|
||||
)
|
||||
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 ###
|
||||
@@ -67,16 +174,50 @@ 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()
|
||||
reporter = LocalStateReporter(state_file=state_file, node_name=node_name)
|
||||
|
||||
node_name = os.getenv("SERVER_NAME", "Unknown Node")
|
||||
|
||||
CHECK_INTERVAL = 600
|
||||
HEAL_VERIFY_DELAY = 5
|
||||
print(f"[*] Agent started. Check interval: {CHECK_INTERVAL}s")
|
||||
logging.info(f"Threat Engine Agent initialized on {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:
|
||||
@@ -102,7 +243,11 @@ def main():
|
||||
|
||||
history_file = reporter.state_file.replace(".json", ".history")
|
||||
|
||||
if should_heal(history_file, drift.get("fingerprint", "")):
|
||||
if should_heal(
|
||||
history_file,
|
||||
drift.get("fingerprint", ""),
|
||||
min_interval=heal_min_interval,
|
||||
):
|
||||
logging.warning("Healing approved.")
|
||||
heal_ok = auditor.heal()
|
||||
heal_result = "restart_failed"
|
||||
@@ -116,10 +261,10 @@ def main():
|
||||
|
||||
if heal_ok:
|
||||
logging.info(
|
||||
f"Post-heal verification in {HEAL_VERIFY_DELAY}s "
|
||||
f"Post-heal verification in {heal_verify_delay}s "
|
||||
f"(pre_fingerprint={drift.get('fingerprint', '')})."
|
||||
)
|
||||
time.sleep(HEAL_VERIFY_DELAY)
|
||||
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"
|
||||
@@ -155,8 +300,8 @@ def main():
|
||||
else:
|
||||
logging.info(f"Audit Success: {count} IPs in sync.")
|
||||
|
||||
print(f"[*] Sleeping for {CHECK_INTERVAL} seconds...")
|
||||
time.sleep(CHECK_INTERVAL)
|
||||
print(f"[*] Sleeping for {check_interval} seconds...")
|
||||
time.sleep(check_interval)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.info("Agent shutting down manually.")
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
agent:
|
||||
node_name: "zephyrus"
|
||||
check_interval: 600 # 10 minutes
|
||||
heal_verify_delay: 5
|
||||
heal_min_interval: 900
|
||||
log_path: "/root/threat-engine-agent/logs/threat-agent.log"
|
||||
state_file: "/root/threat-engine-agent/threat-agent-state.json"
|
||||
|
||||
enforcement:
|
||||
table: "crowdsec"
|
||||
|
||||
+7
-2
@@ -10,8 +10,13 @@ class LocalStateReporter:
|
||||
Manages the health manifest on Triton.
|
||||
Acts as the 'Black Box' recorder for Argus to query.
|
||||
"""
|
||||
def __init__(self, state_file="/root/threat-engine-agent/threat-agent-state.json"):
|
||||
def __init__(
|
||||
self,
|
||||
state_file="/root/threat-engine-agent/threat-agent-state.json",
|
||||
node_name="unknown",
|
||||
):
|
||||
self.state_file = state_file
|
||||
self.node_name = node_name
|
||||
# Ensure the directory is writable
|
||||
os.makedirs(os.path.dirname(os.path.abspath(self.state_file)), exist_ok=True)
|
||||
|
||||
@@ -20,7 +25,7 @@ class LocalStateReporter:
|
||||
Writes the current health snapshot to a JSON file.
|
||||
"""
|
||||
status_data = {
|
||||
"node_name": "triton",
|
||||
"node_name": self.node_name,
|
||||
"last_check": datetime.now().isoformat(),
|
||||
"status": "HEALTHY" if is_synced else "DESYNC_DETECTED",
|
||||
"is_synced": is_synced,
|
||||
|
||||
@@ -8,6 +8,7 @@ User=root
|
||||
Group=root
|
||||
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
Environment="HOME=/root"
|
||||
EnvironmentFile=-/root/threat-engine-agent/.env
|
||||
WorkingDirectory=/root/threat-engine-agent
|
||||
ExecStart=/usr/bin/python3 agent.py
|
||||
Restart=always
|
||||
|
||||
Reference in new issue
Block a user