enodia-sentinal/enodia_sentinel/events/monitor.py
Luna 0eb5077551 Add event-driven eBPF execve layer with a Snort-style rule engine
Closes polling's blind spot (processes that exit between sweeps) with a real
eBPF probe and a declarative, data-driven detection engine — inspired by Snort
(rule language, signature IDs) and OSSEC (host-IDS framing).

New events/ subpackage:
- bcc_source.py : eBPF C tracing execve (filename, argv[1..2], ppid, uid,
                  parent comm) over a perf buffer, loaded via bcc; lazy import
                  + available()/try-except so it fails closed to poll-only when
                  bcc/root/BTF are absent — a broken probe never downs the daemon
- exec_event.py : the ExecEvent type
- rules.py      : ExecRule (sid/msg/severity/classtype + path/exec/parent/argv
                  conditions) and ExecRuleEngine; 4 shipped rules (fileless exec
                  100001, reverse-shell argv 100002, web/DB→shell RCE 100003,
                  curl|sh 100004); operators add more via exec_rules_file TOML
- monitor.py    : runs the source on a thread, routes events through the engine

Integration:
- daemon starts the monitor, shares a lock-guarded cooldown with the sweep
  loop, and feeds event alerts into the same snapshot pipeline
- Alert gains Snort-style sid + classtype; retrofitted onto all 7 poll
  detectors; snapshots and JSON now carry them
- config: ebpf_exec_monitor (default on, degrades), exec_rules_file
- systemd: opt-in ebpf.conf drop-in (relaxes MemoryDenyWriteExecute + widens
  caps for bcc's JIT) so the base unit stays hardened for poll-only
- sentinel-redteam: ebpf_exec drill (short-lived /tmp exec + /dev/tcp argv the
  poller can't see); footer now uses the Python CLI

Tests: +14 cases for the rule engine (each default rule match/non-match, rule
validation, parent-exclude). 39/39 pass. Graceful non-root degradation verified.

NOTE: the eBPF C follows bcc's execsnoop pattern but could not be run here
(BPF needs root); it wants a root smoke-test on a real host.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 07:16:53 -07:00

55 lines
1.8 KiB
Python

# SPDX-License-Identifier: GPL-3.0-or-later
"""Runs the eBPF exec source on a thread and routes events through the engine."""
from __future__ import annotations
import threading
from collections.abc import Callable
from ..alert import Alert
from ..config import Config
from . import bcc_source
from .exec_event import ExecEvent
from .rules import ExecRuleEngine
class ExecMonitor:
"""Owns the event source + rule engine; emits Alerts via ``on_alert``.
``start()`` is best-effort: it returns a (started, reason) pair and never
raises, so the daemon can log the reason and carry on with polling.
"""
def __init__(self, cfg: Config, on_alert: Callable[[Alert], None]) -> None:
self.cfg = cfg
self._on_alert = on_alert
self.engine = ExecRuleEngine.load(cfg.exec_rules_file)
self._source = bcc_source.BccExecSource(self._on_event)
self._thread: threading.Thread | None = None
self._stop = threading.Event()
def start(self) -> tuple[bool, str]:
ok, reason = bcc_source.available()
if not ok:
return False, reason
try:
self._source.start()
except Exception as exc: # compilation/attach/permission failure
return False, f"probe load failed: {exc!r}"
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
return True, "ok"
def _run(self) -> None:
while not self._stop.is_set():
try:
self._source.poll(timeout_ms=200)
except Exception:
break
def _on_event(self, ev: ExecEvent) -> None:
for alert in self.engine.match(ev):
self._on_alert(alert)
def stop(self) -> None:
self._stop.set()
self._source.stop()