242 lines
7.2 KiB
Python
242 lines
7.2 KiB
Python
import logging
|
|
import os
|
|
from dataclasses import dataclass
|
|
|
|
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
|
|
DEFAULT_CONFIG_PATH = "config.yaml"
|
|
DEFAULT_NODE_NAME = "Unknown Node"
|
|
DEFAULT_ENFORCEMENT_TARGETS = (("ip", "crowdsec"), ("ip6", "crowdsec6"))
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RuntimeSettings:
|
|
node_name: str
|
|
log_path: str
|
|
state_file: str
|
|
check_interval: int
|
|
heal_verify_delay: int
|
|
heal_min_interval: int
|
|
enforcement_targets: tuple[tuple[str, str], ...]
|
|
enforcement_sets: tuple[str, ...]
|
|
config_path: str
|
|
|
|
|
|
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
|
|
current_list_key = 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
|
|
current_list_key = None
|
|
else:
|
|
config[key] = _parse_scalar(value)
|
|
current_section = None
|
|
current_list_key = None
|
|
continue
|
|
|
|
if current_section is None:
|
|
continue
|
|
|
|
stripped = line.strip()
|
|
if stripped.startswith("- "):
|
|
if current_list_key:
|
|
config[current_section].setdefault(current_list_key, []).append(
|
|
_parse_scalar(stripped[2:].strip())
|
|
)
|
|
continue
|
|
if ":" not in stripped:
|
|
continue
|
|
key, value = stripped.split(":", 1)
|
|
key = key.strip()
|
|
value = value.strip()
|
|
if value == "":
|
|
config[current_section][key] = []
|
|
current_list_key = key
|
|
else:
|
|
config[current_section][key] = _parse_scalar(value)
|
|
current_list_key = None
|
|
|
|
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 _as_string_list(value):
|
|
if isinstance(value, list):
|
|
return [str(item).strip() for item in value if str(item).strip()]
|
|
if isinstance(value, str):
|
|
return [item.strip() for item in value.split(",") if item.strip()]
|
|
return []
|
|
|
|
|
|
def _resolve_enforcement_targets(config):
|
|
targets_cfg = cfg_get(config, "enforcement", "targets")
|
|
targets = []
|
|
if isinstance(targets_cfg, list):
|
|
for item in targets_cfg:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
family = str(item.get("family", "")).strip()
|
|
table = str(item.get("table", "")).strip()
|
|
if family and table:
|
|
targets.append((family, table))
|
|
if targets:
|
|
return tuple(targets)
|
|
|
|
table_v4 = str(cfg_get(config, "enforcement", "table", default="crowdsec")).strip() or "crowdsec"
|
|
table_v6 = str(cfg_get(config, "enforcement", "table6", default="crowdsec6")).strip() or "crowdsec6"
|
|
families = _as_string_list(cfg_get(config, "enforcement", "families"))
|
|
|
|
if not families:
|
|
return (("ip", table_v4), ("ip6", table_v6))
|
|
|
|
resolved = []
|
|
for family in families:
|
|
if family == "ip":
|
|
resolved.append((family, table_v4))
|
|
elif family == "ip6":
|
|
resolved.append((family, table_v6))
|
|
elif family == "inet":
|
|
resolved.append((family, table_v4))
|
|
|
|
return tuple(resolved) if resolved else DEFAULT_ENFORCEMENT_TARGETS
|
|
|
|
|
|
def _resolve_enforcement_sets(config):
|
|
return tuple(_as_string_list(cfg_get(config, "enforcement", "sets")))
|
|
|
|
|
|
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,
|
|
)
|
|
|
|
|
|
def load_runtime_settings():
|
|
config_path = os.getenv("THREAT_AGENT_CONFIG", DEFAULT_CONFIG_PATH)
|
|
config = load_config(config_path)
|
|
|
|
node_name = os.getenv(
|
|
"SERVER_NAME",
|
|
cfg_get(config, "agent", "node_name", default=DEFAULT_NODE_NAME),
|
|
)
|
|
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,
|
|
)
|
|
enforcement_targets = _resolve_enforcement_targets(config)
|
|
enforcement_sets = _resolve_enforcement_sets(config)
|
|
|
|
return RuntimeSettings(
|
|
node_name=node_name,
|
|
log_path=log_path,
|
|
state_file=state_file,
|
|
check_interval=check_interval,
|
|
heal_verify_delay=heal_verify_delay,
|
|
heal_min_interval=heal_min_interval,
|
|
enforcement_targets=enforcement_targets,
|
|
enforcement_sets=enforcement_sets,
|
|
config_path=config_path,
|
|
)
|