Skip to content

Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.

Add cmdline + parent attribution for interpreter-aware rules

MoneyLisa4ad39eb39ce6
diff --git a/backend/api/main.py b/backend/api/main.py
index 9a49e53..f19d27d 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -1023,6 +1023,7 @@ def _process_batch(packets: list[Packet]) -> None:
node_id=remote_ip,
details={"name": pkt.sni, "ip": remote_ip,
"process": pkt.process_name, "pid": pkt.pid,
+ "cmdline": pkt.cmdline, "parent": pkt.parent_name,
**hit}), notify=True)
# ── LAN accounting / Comptabilisation LAN ───────────────────────────
@@ -1285,7 +1286,8 @@ def _process_batch(packets: list[Packet]) -> None:
node_id=remote_ip,
details={"ip": remote_ip, "port": pkt.remote_port,
"entropy": round(ent, 2),
- "process": pkt.process_name, "pid": pkt.pid},
+ "process": pkt.process_name, "pid": pkt.pid,
+ "cmdline": pkt.cmdline, "parent": pkt.parent_name},
)
_flag_alert(a, nodes)
ad = a.to_dict()
@@ -1315,7 +1317,8 @@ def _process_batch(packets: list[Packet]) -> None:
node_id=remote_ip,
details={"ip": remote_ip, "port": pkt.remote_port,
"reason": reason,
- "process": pkt.process_name, "pid": pkt.pid}),
+ "process": pkt.process_name, "pid": pkt.pid,
+ "cmdline": pkt.cmdline, "parent": pkt.parent_name}),
notify=True)
# EN: ICMP tunnel heuristic — echo requests/replies SHOULD carry ~0
diff --git a/backend/capture/procinfo.py b/backend/capture/procinfo.py
new file mode 100644
index 0000000..3b15b26
--- /dev/null
+++ b/backend/capture/procinfo.py
@@ -0,0 +1,111 @@
+"""
+EN: Process enrichment — cmdline + parent attribution for connections.
+ Attribution gives us a pid; users writing rules need more than the
+ 16-char kernel `comm` to distinguish "node" running an MCP server
+ from "node" running their editor. This module resolves, once per
+ pid per TTL window:
+ cmdline — full command line (psutil .cmdline(), joined)
+ ppid — parent pid
+ parent_name — parent process name (comm), so a rule can key
+ on the *launcher* of an interpreter process.
+ Everything is lazy + TTL-cached: the hot path never touches procfs
+ twice per pid per window, and dead/foreign pids fail closed.
+FR: Enrichissement processus — cmdline + attribution parente pour les
+ connexions. L'attribution donne un pid ; pour écrire des règles il
+ faut plus que le `comm` noyau de 16 caractères pour distinguer
+ « node » lançant un serveur MCP de « node » lançant l'éditeur.
+ Ce module résout, une fois par pid par fenêtre TTL :
+ cmdline — ligne de commande complète (psutil .cmdline())
+ ppid — pid parent
+ parent_name — nom du processus parent (comm), pour qu'une
+ règle puisse viser le *lanceur* d'un interpréteur.
+ Tout est paresseux + cache TTL : le chemin chaud ne touche jamais
+ procfs deux fois par pid par fenêtre, et les pid morts/étrangers
+ échouent silencieusement.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Optional
+
+import psutil
+
+_ENRICH_TTL = 45.0 # seconds — process metadata rarely changes
+
+
+class ProcEnricher:
+ """EN: TTL-cached pid → (cmdline, ppid, parent_name) resolver.
+ FR: Résolveur pid → (cmdline, ppid, parent_name) à cache TTL."""
+
+ def __init__(self, ttl: float = _ENRICH_TTL):
+ self.ttl = ttl
+ self._cache: dict[int, tuple[float, Optional[str], Optional[int], Optional[str]]] = {}
+ self._lock = threading.Lock()
+
+ def _resolve(self, pid: int) -> tuple[Optional[str], Optional[int], Optional[str]]:
+ cmdline = ppid = parent_name = None
+ try:
+ proc = psutil.Process(pid)
+ try:
+ cmdline = " ".join(proc.cmdline()) or None
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
+ pass
+ try:
+ ppid = proc.ppid()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ pass
+ if ppid:
+ try:
+ parent_name = psutil.Process(ppid).name()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ pass
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ pass
+ return cmdline, ppid, parent_name
+
+ def enrich(self, pid: Optional[int]) -> tuple[Optional[str], Optional[int], Optional[str]]:
+ """EN: (cmdline, ppid, parent_name) for pid, cached for `ttl`.
+ FR: (cmdline, ppid, parent_name) du pid, mis en cache `ttl`."""
+ if not pid:
+ return None, None, None
+ now = time.monotonic()
+ with self._lock:
+ hit = self._cache.get(pid)
+ if hit and now - hit[0] < self.ttl:
+ return hit[1], hit[2], hit[3]
+ # EN: Bound the cache — pids churn, keep only live window.
+ # FR: Borner le cache — les pid tournent, garder la fenêtre.
+ if len(self._cache) > 4096:
+ self._cache = {p: v for p, v in self._cache.items()
+ if now - v[0] < self.ttl}
+ resolved = self._resolve(pid)
+ with self._lock:
+ self._cache[pid] = (now, *resolved)
+ return resolved
+
+ def parent_chain(self, pid: Optional[int], depth: int = 8) -> list[tuple[int, str]]:
+ """EN: Walk up the parent chain → [(ppid, name), ...], root-first
+ order is NOT guaranteed — listed nearest-parent first. Used
+ by agent-audit views, not the packet hot path.
+ FR: Remonte la chaîne des parents → [(ppid, nom), ...], du parent
+ le plus proche vers la racine. Pour les vues d'audit agent,
+ pas le chemin chaud."""
+ chain: list[tuple[int, str]] = []
+ seen: set[int] = set()
+ cur = pid
+ for _ in range(depth):
+ if not cur or cur in seen:
+ break
+ seen.add(cur)
+ try:
+ proc = psutil.Process(cur)
+ ppid = proc.ppid()
+ if not ppid or ppid in seen:
+ break
+ chain.append((ppid, psutil.Process(ppid).name()))
+ cur = ppid
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ break
+ return chain
diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.py
index f1d3d67..6378f42 100644
--- a/backend/capture/sniffer.py
+++ b/backend/capture/sniffer.py
@@ -37,6 +37,7 @@ from datetime import datetime, timezone
from typing import Callable, Optional
import psutil
+from .procinfo import ProcEnricher
from capture.pcap import PcapError, PcapSession, is_available, list_devices
from capture.parser import parse_frame
@@ -93,6 +94,13 @@ class Packet:
direction: str # "out" | "in"
pid: Optional[int] = None
process_name: Optional[str] = None
+ # EN: Enriched attribution — full cmdline + parent identity, so rules
+ # can distinguish "node mcp-server" from bare "node".
+ # FR: Attribution enrichie — cmdline complet + identité parente, pour
+ # distinguer « node mcp-server » de « node » nu dans les règles.
+ cmdline: Optional[str] = None
+ ppid: Optional[int] = None
+ parent_name: Optional[str] = None
tcp_flags: int = 0
sni: Optional[str] = None
dns: list = field(default_factory=list)
@@ -217,6 +225,7 @@ class PacketSniffer:
self.local_ips = get_local_ips()
self._session: Optional[PcapSession] = None
self._conn_table = ConnectionTable()
+ self._procinfo = ProcEnricher()
# EN: Optional kernel-level attribution probe (eBPF) — consulted when
# the socket table misses. Set via set_attribution_probe().
# FR: Sonde d'attribution noyau optionnelle (eBPF) — consultée quand
@@ -408,6 +417,10 @@ class PacketSniffer:
pid, process_name = self._attribution_probe.lookup(
dst, parsed.dst_port)
+ cmdline = ppid = parent_name = None
+ if pid:
+ cmdline, ppid, parent_name = self._procinfo.enrich(pid)
+
self.callback(Packet(
src_ip=src,
dst_ip=dst,
@@ -420,6 +433,9 @@ class PacketSniffer:
direction=direction,
pid=pid,
process_name=process_name,
+ cmdline=cmdline,
+ ppid=ppid,
+ parent_name=parent_name,
tcp_flags=parsed.tcp_flags,
sni=parsed.sni,
dns=parsed.dns,
diff --git a/backend/detection/customrules.py b/backend/detection/customrules.py
index 2f203c2..4249ff1 100644
--- a/backend/detection/customrules.py
+++ b/backend/detection/customrules.py
@@ -11,8 +11,9 @@ EN: User-defined alert rules — a deliberately SMALL matcher, not a
firewall rule on the matched remote host (deduped per rule+target).
Supported fields : remote_ip, host (SNI or DNS answer name),
- process_name, remote_port, protocol, direction,
- size, asn, country (from the local geo DB).
+ process_name, cmdline (full command line),
+ parent_name (launcher process name), remote_port,
+ protocol, direction, size, asn, country.
Supported ops : eq, ne, contains, regex, gt, lt, cidr.
Actions : alert (default) | block (firewall rule on the
matched remote_ip — the per-flow kill-switch).
@@ -43,8 +44,8 @@ import time
import uuid
from typing import Optional
-_FIELDS = ("remote_ip", "host", "process_name", "remote_port",
- "protocol", "direction", "size", "asn", "country")
+_FIELDS = ("remote_ip", "host", "process_name", "cmdline", "parent_name",
+ "remote_port", "protocol", "direction", "size", "asn", "country")
_OPS = ("eq", "ne", "contains", "regex", "gt", "lt", "cidr")
_SEVERITIES = ("info", "warning", "critical")
# EN: "alert" (default) emits CUSTOM_RULE only; "block" additionally
@@ -271,7 +272,7 @@ class CustomRules:
first_field not in ("remote_ip", "host",
"process_name", "asn", "country"):
raise ValueError("block action needs a blockable field "
- "(remote_ip/host/process_name/asn/country)")
+ "(remote_ip/host/process_name/cmdline/parent_name/asn/country)")
def add(self, name: str, field: str, op: str, value: str,
severity: str = "warning", action: str = "alert",
@@ -330,6 +331,10 @@ class CustomRules:
return names
if field == "process_name":
return pkt.process_name or ""
+ if field == "cmdline":
+ return getattr(pkt, "cmdline", None) or ""
+ if field == "parent_name":
+ return getattr(pkt, "parent_name", None) or ""
if field == "remote_port":
return pkt.remote_port
if field == "protocol":