92 lines
3.1 KiB
Python
92 lines
3.1 KiB
Python
"""Alert -> decision. Rule metadata leaf_action drives intent, policy gates it."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from typing import Any
|
|
|
|
log = logging.getLogger("leaf.policy")
|
|
|
|
|
|
@dataclass
|
|
class Decision:
|
|
ip: str
|
|
kind: str # dest | src
|
|
sid: int
|
|
reason: str
|
|
sig: str = ""
|
|
hits: int = 1
|
|
|
|
|
|
class Policy:
|
|
def __init__(self, cfg, state):
|
|
self.cfg = cfg
|
|
self.state = state
|
|
|
|
@staticmethod
|
|
def metadata_actions(event: dict) -> list[str]:
|
|
md = event.get("alert", {}).get("metadata", {}) or {}
|
|
vals = md.get("leaf_action", []) or []
|
|
if isinstance(vals, str):
|
|
vals = [vals]
|
|
return [str(v).strip().lower() for v in vals]
|
|
|
|
def evaluate(self, event: dict, now: float | None = None) -> Decision | None:
|
|
"""Return Decision to block, or None. `event` = eve alert record."""
|
|
now = now or time.time()
|
|
if event.get("event_type") != "alert":
|
|
return None
|
|
alert = event.get("alert", {})
|
|
sid = int(alert.get("signature_id", -1))
|
|
sig = str(alert.get("signature", ""))
|
|
actions = self.metadata_actions(event)
|
|
if not actions:
|
|
return None
|
|
|
|
sids_only = [int(s) for s in self.cfg.get("policy.sids_only", [])]
|
|
sids_deny = [int(s) for s in self.cfg.get("policy.sids_deny", [])]
|
|
if sids_only and sid not in sids_only:
|
|
return None
|
|
if sid in sids_deny:
|
|
return None
|
|
|
|
mode = self.cfg.get("policy.mode", "threshold")
|
|
src_ip = str(event.get("src_ip", ""))
|
|
dest_ip = str(event.get("dest_ip", ""))
|
|
|
|
candidates: list[tuple[str, str]] = []
|
|
if "block" in actions:
|
|
candidates.append((dest_ip, "dest"))
|
|
if "block_src" in actions and self.cfg.get("policy.block_src", False):
|
|
candidates.append((src_ip, "src"))
|
|
|
|
for ip, kind in candidates:
|
|
dec = self._gate(ip, kind, sid, sig, now, mode)
|
|
if dec:
|
|
return dec
|
|
return None
|
|
|
|
def _gate(self, ip: str, kind: str, sid: int, sig: str,
|
|
now: float, mode: str) -> Decision | None:
|
|
if not ip:
|
|
return None
|
|
import ipaddress
|
|
try:
|
|
if ipaddress.ip_address(ip).version != 4:
|
|
return None
|
|
except ValueError:
|
|
return None
|
|
if self.cfg.is_allowed_ip(ip):
|
|
log.debug("allowlisted, not blocking: %s (sid=%s)", ip, sid)
|
|
return None
|
|
self.state.record_hit(sid, ip, now)
|
|
min_hits = int(self.cfg.get("policy.min_hits", 1))
|
|
window = float(self.cfg.get("policy.window_seconds", 300))
|
|
hits = self.state.hit_count(sid, ip, window, now)
|
|
if mode == "immediate" or hits >= min_hits:
|
|
return Decision(ip=ip, kind=kind, sid=sid, sig=sig, hits=hits,
|
|
reason=f"{mode}:{hits} hit(s) sid={sid} in {window:.0f}s")
|
|
log.info("hit %d/%d for %s (sid=%s) — not yet blocking", hits, min_hits, ip, sid)
|
|
return None
|