Re-architect Sentinel as a zero-dependency Python package

Port the bash prototype to a structured, testable Python codebase while
preserving the same control loop and the seven detection signatures. The bash
implementation stays in src/ as the regression oracle.

Highlights:
- enodia_sentinel/ package (stdlib only — no runtime deps):
  - detectors/ : one pure function per signature, detect(state, cfg)->Alerts
  - system.py  : SystemState — one cached /proc + ss snapshot per sweep,
                 fully injectable so detectors are unit-testable
  - daemon.py  : sweep loop, in-process cooldown dedup, threaded snapshot
                 capture, and a SUID filesystem scan moved OFF the loop
                 thread onto a slow background cadence
  - snapshot.py: forensic text + JSON sidecar with per-signature IR guidance
  - config.py  : dataclass config via TOML + env overrides
  - netutil.py : public-IP / CIDR logic via stdlib ipaddress
- tests/ : 25 stdlib-unittest cases (no root, no /proc, no ss needed)
- TOML config, launcher wrapper, Makefile (pip-free install), hardened
  systemd unit (env-resolved ExecStart), updated PKGBUILD, rewritten README

Performance: per-sweep cost ~200 ms (shared cached state); the multi-second
SUID walk no longer blocks detection. scandir-based walk replaces os.walk.

Verified on Arch: all 7 detectors fire on red-team drills (reverse_shell,
ld_preload, deleted_exe, new_listener, new_suid confirmed live end-to-end),
no false positives on a clean sweep, 25/25 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Luna 2026-05-31 01:50:50 -07:00
parent 45f8acb24a
commit 28d67a1360
28 changed files with 1783 additions and 133 deletions

View file

@ -0,0 +1,62 @@
"""Detector registry.
Each detector is a ``Detector`` with a ``name`` and a ``detect(state, cfg)``
callable yielding ``Alert``s. They are pure functions of the injected
``SystemState`` + ``Config``, which is what makes them unit-testable without
root or a live system.
"""
from __future__ import annotations
from collections.abc import Callable, Iterable, Iterator
from dataclasses import dataclass
from ..alert import Alert
from ..config import Config
from ..system import SystemState
from . import (
deleted_exe,
egress,
ld_preload,
new_listener,
new_suid,
persistence,
reverse_shell,
)
DetectFn = Callable[[SystemState, Config], Iterable[Alert]]
@dataclass(frozen=True)
class Detector:
name: str
detect: DetectFn
needs_baseline: bool = False # gated until after the grace window
expensive: bool = False # gated to the slow scan cadence
# Order here is the order signatures appear in a snapshot.
REGISTRY: tuple[Detector, ...] = (
Detector("reverse_shell", reverse_shell.detect),
Detector("ld_preload", ld_preload.detect),
Detector("deleted_exe", deleted_exe.detect),
Detector("egress", egress.detect),
Detector("new_listener", new_listener.detect, needs_baseline=True),
Detector("persistence", persistence.detect, needs_baseline=True),
Detector("new_suid", new_suid.detect, needs_baseline=True, expensive=True),
)
def run_all(
state: SystemState,
cfg: Config,
*,
include: Iterable[str] | None = None,
) -> Iterator[Alert]:
"""Run the enabled detectors whose names are in ``include`` (or all)."""
wanted = set(include) if include is not None else None
for det in REGISTRY:
if not cfg.enabled(det.name):
continue
if wanted is not None and det.name not in wanted:
continue
yield from det.detect(state, cfg)

View file

@ -0,0 +1,39 @@
"""deleted_exe — a process running from a deleted or memfd-backed binary.
Fileless malware unlinks its dropper (or runs straight from ``memfd``) so there
is nothing on disk to scan. The kernel still labels the ``/proc/<pid>/exe``
symlink ``(deleted)`` or ``memfd:``. Normal-path deleted exes (a daemon still
running after a package upgrade) are ignored only attacker-controlled/fileless
locations alert.
"""
from __future__ import annotations
from collections.abc import Iterator
from ..alert import Alert, Severity
from ..config import Config
from ..system import SystemState
_SUSPICIOUS_PREFIXES = ("/tmp/", "/dev/shm/", "/var/tmp/", "/run/")
def _is_fileless(exe: str) -> bool:
if "memfd:" in exe:
return True
if "(deleted)" not in exe:
return False
return exe.startswith(_SUSPICIOUS_PREFIXES)
def detect(state: SystemState, cfg: Config) -> Iterator[Alert]:
for proc in state.processes:
exe = proc.exe
if not exe or not _is_fileless(exe):
continue
yield Alert(
severity=Severity.CRITICAL,
signature="deleted_exe",
key=f"del:{proc.pid}",
detail=f"pid={proc.pid} comm={proc.comm} exe=[{exe}]",
pids=(proc.pid,),
)

View file

@ -0,0 +1,35 @@
"""egress — an interpreter holding an outbound connection to a public IP.
C2 beacons and exfil phone home. A scripting interpreter (bash/python/perl/nc)
with an established connection to a globally-routable address that isn't in
the operator's trust list — is worth a look.
"""
from __future__ import annotations
from collections.abc import Iterator
from ..alert import Alert, Severity
from ..config import Config
from ..netutil import ip_in_cidrs, is_public_ip, split_host_port
from ..system import SystemState
def detect(state: SystemState, cfg: Config) -> Iterator[Alert]:
for s in state.established_sockets():
if s.comm not in cfg.interpreters:
continue
host, port = split_host_port(s.peer)
if not is_public_ip(host):
continue
if ip_in_cidrs(host, cfg.egress_allow_cidrs):
continue
yield Alert(
severity=Severity.HIGH,
signature="egress",
key=f"egr:{s.pid}:{host}",
detail=(
f"pid={s.pid} comm={s.comm} -> {host}:{port} "
"(interpreter to public IP)"
),
pids=(s.pid,) if s.pid else (),
)

View file

@ -0,0 +1,46 @@
"""ld_preload — userland rootkit / library-injection indicators.
Two signatures:
* ``/etc/ld.so.preload`` non-empty: injects into *every* dynamically-linked
process the classic system-wide rootkit hook.
* a process whose ``LD_PRELOAD`` points into a writable/temp dir per-process
function hooking (hiding files/procs, stealing credentials).
"""
from __future__ import annotations
from collections.abc import Iterator
from pathlib import Path
from ..alert import Alert, Severity
from ..config import Config
from ..system import SystemState
_SUSPICIOUS_PREFIXES = ("/tmp/", "/dev/shm/", "/var/tmp/", "/run/user/", "./")
def detect(state: SystemState, cfg: Config) -> Iterator[Alert]:
preload = Path("/etc/ld.so.preload")
try:
contents = preload.read_text().strip() if preload.is_file() else ""
except OSError:
contents = ""
if contents:
yield Alert(
severity=Severity.CRITICAL,
signature="ld_preload",
key="ldp:global",
detail=f"/etc/ld.so.preload is non-empty: [{contents.replace(chr(10), ' ')}]",
)
for proc in state.processes:
pre = proc.environ.get("LD_PRELOAD", "")
if not pre:
continue
if pre.startswith(_SUSPICIOUS_PREFIXES):
yield Alert(
severity=Severity.CRITICAL,
signature="ld_preload",
key=f"ldp:{proc.pid}",
detail=f"pid={proc.pid} comm={proc.comm} LD_PRELOAD=[{pre}]",
pids=(proc.pid,),
)

View file

@ -0,0 +1,33 @@
"""new_listener — a listening socket absent from the startup baseline.
Bind shells and backdoors have to listen somewhere. We diff the current set of
``port/comm`` listeners against the baseline captured at start; anything new
(and not explicitly allow-listed) alerts.
"""
from __future__ import annotations
from collections.abc import Iterator
from ..alert import Alert, Severity
from ..config import Config
from ..system import SystemState
def detect(state: SystemState, cfg: Config) -> Iterator[Alert]:
if state.listener_baseline is None:
return
for s in state.listening_sockets():
port = s.local.rpartition(":")[2]
comm = s.comm or "?"
key = f"{port}/{comm}"
if key in state.listener_baseline:
continue
if port in cfg.listener_allow_ports:
continue
yield Alert(
severity=Severity.HIGH,
signature="new_listener",
key=f"lis:{key}",
detail=f"new listening socket {s.local} by comm={comm}",
pids=(s.pid,) if s.pid else (),
)

View file

@ -0,0 +1,35 @@
"""new_suid — a SUID/SGID binary that wasn't in the baseline.
A new setuid binary is a privilege-escalation persistence trick; one in a
world-writable dir (``/tmp``, ``/home`` ) is almost never legitimate, so it is
escalated to CRITICAL. The filesystem walk is expensive, so the daemon only
populates ``state.suid_binaries`` on its slow scan cadence when it's absent
this detector is a no-op.
"""
from __future__ import annotations
from collections.abc import Iterator
from ..alert import Alert, Severity
from ..config import Config
from ..system import SystemState
def detect(state: SystemState, cfg: Config) -> Iterator[Alert]:
if state.suid_binaries is None or state.suid_baseline is None:
return
for path in state.suid_binaries:
if path in state.suid_baseline:
continue
hot = any(
path.startswith(d.rstrip("/") + "/") for d in cfg.suid_hot_dirs
)
yield Alert(
severity=Severity.CRITICAL if hot else Severity.HIGH,
signature="new_suid",
key=f"suid:{path}",
detail=(
("SUID/SGID binary in writable dir: " if hot
else "new SUID/SGID binary: ") + path
),
)

View file

@ -0,0 +1,42 @@
"""persistence — modification of a watched persistence-relevant file.
Persistence has to land somewhere that survives a reboot: cron, systemd units,
``authorized_keys``, shell rc files. We watch a configurable set and alert on
anything modified since the previous scan (``state.persist_since``).
"""
from __future__ import annotations
import os
from collections.abc import Iterator
from ..alert import Alert, Severity
from ..config import Config
from ..system import SystemState
def _iter_files(roots) -> Iterator[str]:
for root in roots:
if os.path.isdir(root):
for dirpath, _dirs, files in os.walk(root, onerror=lambda e: None):
for f in files:
yield os.path.join(dirpath, f)
elif os.path.lexists(root):
yield root
def detect(state: SystemState, cfg: Config) -> Iterator[Alert]:
since = state.persist_since
if since is None:
return
for path in _iter_files(cfg.watch_persistence):
try:
mtime = os.lstat(path).st_mtime
except OSError:
continue
if mtime > since:
yield Alert(
severity=Severity.HIGH,
signature="persistence",
key=f"persist:{path}",
detail=f"persistence file modified: {path}",
)

View file

@ -0,0 +1,37 @@
"""reverse_shell — an interpreter with a network socket on its stdio.
A real reverse shell dups a TCP/UDP socket onto fd 0/1/2 (``nc -e /bin/bash``,
``bash -i >& /dev/tcp/...``). Interactive shells get a pty, and daemons get
unix sockets/pipes neither is a network socket, so requiring the stdio socket
to appear in the network socket table is what keeps false positives near zero.
"""
from __future__ import annotations
from collections.abc import Iterator
from ..alert import Alert, Severity
from ..config import Config
from ..system import SystemState
def detect(state: SystemState, cfg: Config) -> Iterator[Alert]:
peer_by_inode = state.net_peer_by_inode
for proc in state.processes:
if proc.comm not in cfg.interpreters:
continue
inode = proc.stdio_socket_inode()
if inode is None:
continue
peer = peer_by_inode.get(inode)
if not peer: # unix socket / pipe — benign
continue
yield Alert(
severity=Severity.CRITICAL,
signature="reverse_shell",
key=f"rsh:{proc.pid}",
detail=(
f"pid={proc.pid} comm={proc.comm} stdio=net-socket "
f"peer=[{peer}] cmd=[{proc.cmdline[:90]}]"
),
pids=(proc.pid,),
)