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.

observability: zero silent drops — count & surface every discard path

MoneyLisaaf6628bcc0cc
diff --git a/backend/api/main.py b/backend/api/main.py
index fcd351b..68ea993 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -85,6 +85,7 @@ from classifier.traffic import classify
from resolver.dns_geo import (enrich_ip, is_private, learn_dns_answers,
learn_sni, lookup_domain)
from scanner.arp_scanner import ARPScanner, Device, default_gateway as _default_gateway
+from scanner.arp_scanner import READ_STATS as _arp_stats
from detection.anomaly import AnomalyDetector
import storage.db as db
@@ -120,6 +121,25 @@ _shutdown = False
# le trafic frais.
_pkt_queue: queue.Queue = queue.Queue(maxsize=20_000)
+# EN: Drop accounting — every skipped/dropped packet is counted with its
+# reason and exposed via /diagnostics. Security rule: nothing is ignored
+# silently — a blind spot is a finding.
+# FR: Comptabilité des rejets — chaque paquet écarté/jeté est compté avec sa
+# raison et exposé via /diagnostics. Règle de sécurité : rien n'est
+# ignoré silencieusement — un angle mort est un problème.
+_drop_stats = {
+ "queue_oldest_dropped": 0, # EN: full queue → stale packet evicted
+ # FR: file pleine → paquet périmé évincé
+ "queue_put_failed": 0, # EN: queue still full after eviction
+ # FR: file encore pleine après éviction
+ "excluded_process": 0, # EN: user-excluded process (settings)
+ # FR: processus exclu par l'utilisateur
+ "whitelisted_ip": 0, # EN: trusted IP (e.g. the box)
+ # FR: IP de confiance (ex. la box)
+ "noise_filtered": 0, # EN: multicast/broadcast/etc. noise
+ # FR: bruit multicast/broadcast/etc.
+}
+
# EN: Hard caps so a long-running instance can't leak memory.
# FR: Plafonds stricts pour qu'une instance longue durée ne fuie pas de mémoire.
MAX_GRAPH_NODES = 800
@@ -385,9 +405,19 @@ def on_packet(pkt: Packet) -> None:
except queue.Full:
try:
_pkt_queue.get_nowait() # EN: drop oldest / FR: jeter le plus ancien
+ _drop_stats["queue_oldest_dropped"] += 1
_pkt_queue.put_nowait(pkt)
+ # EN: Saturated queue = lost traffic — surface it at the 1st drop
+ # and each power of 10 so bursts don't flood the log.
+ # FR: File saturée = trafic perdu — signaler au 1er rejet puis à
+ # chaque puissance de 10 pour que les rafales ne noient pas
+ # le journal.
+ n = _drop_stats["queue_oldest_dropped"]
+ if n == 1 or n % 1000 == 0:
+ logger.warning("packet queue saturated — %d stale packets "
+ "dropped so far", n)
except (queue.Empty, queue.Full):
- pass
+ _drop_stats["queue_put_failed"] += 1
def _request_enrichment(ip: str) -> None:
@@ -464,6 +494,7 @@ def _process_batch(packets: list[Packet]) -> None:
for pkt in packets:
if pkt.process_name and pkt.process_name in _excluded_processes:
+ _drop_stats["excluded_process"] += 1
continue
remote_ip = pkt.dst_ip if pkt.direction == "out" else pkt.src_ip
@@ -504,7 +535,11 @@ def _process_batch(packets: list[Packet]) -> None:
if pkt.dhcp:
_learn_dhcp_name(*pkt.dhcp, touched_devices)
- if remote_ip in _whitelisted_ips or _is_noise_ip(remote_ip):
+ if remote_ip in _whitelisted_ips:
+ _drop_stats["whitelisted_ip"] += 1
+ continue
+ if _is_noise_ip(remote_ip):
+ _drop_stats["noise_filtered"] += 1
continue
if pkt.sni:
@@ -1245,6 +1280,16 @@ async def get_diagnostics() -> dict:
"counts": {"nodes": len(nodes), "edges": len(edges),
"lan_devices": len(lan_devices),
"alerts_memory": len(detector.history)},
+ # EN: Drop accounting — every ignored/skipped packet, frame and ARP
+ # row, with its reason. Security: no silent blind spots.
+ # FR: Comptabilité des rejets — chaque paquet, trame et ligne ARP
+ # ignorée/écartée, avec sa raison. Sécurité : aucun angle mort
+ # silencieux.
+ "dropped": {
+ **dict(_drop_stats),
+ "capture": dict(_sniffer.stats) if _sniffer else {},
+ "arp_read": dict(_arp_stats),
+ },
"db_bytes": db_file.stat().st_size if db_file.exists() else 0,
"log_tail": log_tail,
}
diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.py
index 84c26ab..81614f3 100644
--- a/backend/capture/sniffer.py
+++ b/backend/capture/sniffer.py
@@ -188,6 +188,15 @@ class PacketSniffer:
self._conn_table = ConnectionTable()
self._running = False
self._thread: Optional[threading.Thread] = None
+ # EN: Drop accounting — every discarded frame is counted with its
+ # reason and surfaced in /diagnostics. Security rule: no silent
+ # skips — an unparsed frame could be the one that mattered.
+ # FR: Comptabilité des rejets — chaque trame écartée est comptée avec
+ # sa raison et exposée dans /diagnostics. Règle de sécurité :
+ # zéro rejet silencieux — une trame non lue pourrait être celle
+ # qui comptait.
+ self.stats = {"frames": 0, "delivered": 0, "parse_failed": 0,
+ "not_for_us": 0}
@staticmethod
def _default_iface() -> Optional[str]:
@@ -223,12 +232,24 @@ class PacketSniffer:
paquets qui ne concernent pas cet hôte.
"""
assert self._session is not None
+ self.stats["frames"] += 1
parsed = parse_frame(self._session.linktype, buf)
if parsed is None:
+ self.stats["parse_failed"] += 1
+ # EN: Warn at the 1st failure then each power of 10 — the count
+ # matters (format drift, corruption), not each individual line.
+ # FR: Avertir à la 1re erreur puis à chaque puissance de 10 — c'est
+ # le compte qui importe (dérive de format, corruption), pas
+ # chaque ligne isolée.
+ n = self.stats["parse_failed"]
+ if n == 1 or n % 1000 == 0:
+ logger.warning("unparseable frame #%d (%d bytes, linktype=%d)",
+ n, len(buf), self._session.linktype)
return
src, dst = parsed.src_ip, parsed.dst_ip
if src not in self.local_ips and dst not in self.local_ips:
+ self.stats["not_for_us"] += 1
return
direction = "out" if src in self.local_ips else "in"
@@ -260,6 +281,7 @@ class PacketSniffer:
dns=parsed.dns,
dhcp=parsed.dhcp,
))
+ self.stats["delivered"] += 1
def start(self) -> None:
"""EN: Launch the capture thread. / FR: Lancer le thread de capture."""
diff --git a/backend/scanner/arp_scanner.py b/backend/scanner/arp_scanner.py
index 7e8f5a3..89d57ff 100644
--- a/backend/scanner/arp_scanner.py
+++ b/backend/scanner/arp_scanner.py
@@ -46,9 +46,21 @@ from scanner.oui import lookup, is_local_mac, DEVICE_TYPE_COLORS
logger = logging.getLogger("snitch.scanner")
-# EN: MAC address matcher — handles both : and - separators.
-# FR: Reconnaisseur d'adresse MAC — gère les séparateurs : et -.
-MAC_RE = re.compile(r"([0-9a-fA-F]{2}[:\-]){5}[0-9a-fA-F]{2}")
+# EN: MAC address matcher — handles : and - separators AND macOS's
+# non-zero-padded octets ("be:18:9d:a0:c1:3" — that trailing "3" is real:
+# without {1,2} the entry is silently skipped).
+# FR: Reconnaisseur d'adresse MAC — gère les séparateurs : et - ET les octets
+# non complétés de macOS (« be:18:9d:a0:c1:3 » — ce « 3 » final est réel :
+# sans {1,2} l'entrée est silencieusement ignorée).
+MAC_RE = re.compile(r"([0-9a-fA-F]{1,2}[:\-]){5}[0-9a-fA-F]{1,2}")
+
+
+def _norm_mac(mac: str) -> str:
+ """EN: Canonical "AA:BB:CC:DD:EE:FF" — zero-pads single-digit octets
+ (macOS `arp -a` prints "…:c1:3" instead of "…:C1:03").
+ FR: « AA:BB:CC:DD:EE:FF » canonique — complète à zéro les octets à un
+ chiffre (`arp -a` de macOS affiche « …:c1:3 » au lieu de « …:C1:03 »)."""
+ return ":".join(p.zfill(2).upper() for p in mac.replace("-", ":").split(":"))
IPV4_RE = re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b")
@@ -114,6 +126,8 @@ def _read_arp_table() -> list[tuple[str, str]]:
Lecteur par plateforme ; renvoie [] en cas d'échec — le scanner reste
vivant et réessaie à l'intervalle suivant.
"""
+ READ_STATS.update({"lines": 0, "parsed": 0, "incomplete": 0,
+ "ip_no_mac": 0})
if sys.platform.startswith("linux"):
return _read_arp_linux()
return _read_arp_cmd()
@@ -122,6 +136,8 @@ def _read_arp_table() -> list[tuple[str, str]]:
def _read_arp_linux() -> list[tuple[str, str]]:
"""EN: Parse /proc/net/arp — flag 0x0 or 00:00:... means incomplete.
FR: Analyser /proc/net/arp — flag 0x0 ou MAC 00:00:… signifie incomplet."""
+ READ_STATS.update({"lines": 0, "parsed": 0, "incomplete": 0,
+ "ip_no_mac": 0})
out = []
try:
lines = Path("/proc/net/arp").read_text().splitlines()[1:]
@@ -129,16 +145,39 @@ def _read_arp_linux() -> list[tuple[str, str]]:
logger.debug("/proc/net/arp unreadable: %s", exc)
return out
for line in lines:
+ READ_STATS["lines"] += 1
parts = line.split()
if len(parts) < 6:
+ READ_STATS["ip_no_mac"] += 1
+ logger.warning("/proc/net/arp line unreadable — row SKIPPED: %r",
+ line.strip())
continue
ip, _hwtype, flags, mac = parts[0], parts[1], parts[2], parts[3]
if int(flags, 16) == 0 or mac == "00:00:00:00:00:00":
+ READ_STATS["incomplete"] += 1
continue
- out.append((ip, mac.upper()))
+ if not MAC_RE.fullmatch(mac):
+ READ_STATS["ip_no_mac"] += 1
+ logger.warning("/proc/net/arp MAC unreadable — device SKIPPED: %r",
+ mac)
+ continue
+ out.append((ip, _norm_mac(mac)))
+ READ_STATS["parsed"] += 1
return out
+# EN: Parse accounting for the last table read — reset on each call. A line
+# that carries an IP but no MAC match is a FORMAT DRIFT signal (this is
+# how macOS's unpadded octets once hid whole devices) — never silent.
+# FR: Comptabilité de la dernière lecture — remise à zéro à chaque appel.
+# Une ligne avec une IP mais sans MAC reconnue signale une DÉRIVE DE
+# FORMAT (c'est ainsi que les octets non complétés de macOS ont déjà
+# caché des appareils entiers) — jamais silencieux.
+READ_STATS: dict[str, int] = {"lines": 0, "parsed": 0, "incomplete": 0,
+ "ip_no_mac": 0}
+_warned_lines: set[str] = set()
+
+
def _read_arp_cmd() -> list[tuple[str, str]]:
"""EN: Parse `arp -a` on Windows ("-"-separated MACs) and macOS
(parenthesized IPs). / FR: Analyser `arp -a` sous Windows (MAC séparées par
@@ -151,14 +190,27 @@ def _read_arp_cmd() -> list[tuple[str, str]]:
logger.debug("arp -a failed: %s", exc)
return []
+ READ_STATS.update({"lines": 0, "parsed": 0, "incomplete": 0,
+ "ip_no_mac": 0})
pairs = []
for line in out_text.splitlines():
+ if not line.strip():
+ continue
+ READ_STATS["lines"] += 1
if "incomplete" in line.lower():
+ READ_STATS["incomplete"] += 1
continue
ip_m = IPV4_RE.search(line)
mac_m = MAC_RE.search(line)
if ip_m and mac_m:
- pairs.append((ip_m.group(0), mac_m.group(0).replace("-", ":").upper()))
+ pairs.append((ip_m.group(0), _norm_mac(mac_m.group(0))))
+ READ_STATS["parsed"] += 1
+ elif ip_m:
+ READ_STATS["ip_no_mac"] += 1
+ if line not in _warned_lines:
+ _warned_lines.add(line)
+ logger.warning("arp line has an IP but no readable MAC — "
+ "device SKIPPED: %r", line.strip())
return pairs
diff --git a/backend/tests/test_arp_scanner.py b/backend/tests/test_arp_scanner.py
new file mode 100644
index 0000000..c8495c7
--- /dev/null
+++ b/backend/tests/test_arp_scanner.py
@@ -0,0 +1,36 @@
+"""
+Snitch — ARP scanner parsing tests.
+
+EN: macOS `arp -a` drops leading zeros in MAC octets ("be:18:9d:a0:c1:3") —
+ a strict two-digit regex silently skips whole devices (this actually
+ hid the user's phone). Regression coverage for _norm_mac / MAC_RE.
+
+FR: `arp -a` de macOS supprime les zéros de tête dans les octets MAC
+ (« be:18:9d:a0:c1:3 ») — une regex stricte à deux chiffres ignorait
+ silencieusement des appareils entiers (ça a réellement caché le
+ téléphone de l'utilisateur). Couverture de régression pour
+ _norm_mac / MAC_RE.
+"""
+
+from scanner.arp_scanner import MAC_RE, _norm_mac
+
+
+def test_norm_mac_macos_unpadded():
+ """EN: Single-digit octets get zero-padded. / FR: Octets à un chiffre complétés à zéro."""
+ assert _norm_mac("be:18:9d:a0:c1:3") == "BE:18:9D:A0:C1:03"
+ assert _norm_mac("ea:d5:e:80:3b:cf") == "EA:D5:0E:80:3B:CF"
+
+
+def test_norm_mac_canonical_and_windows():
+ assert _norm_mac("70:FC:8F:57:31:FB") == "70:FC:8F:57:31:FB"
+ assert _norm_mac("00-e0-4c-12-34-56") == "00:E0:4C:12:34:56" # EN: '-' separator / FR: séparateur « - »
+
+
+def test_mac_re_matches_unpadded_line():
+ line = "? (192.168.1.25) at be:18:9d:a0:c1:3 on en1 ifscope [ethernet]"
+ assert MAC_RE.search(line)
+
+
+def test_mac_re_rejects_incomplete():
+ line = "? (192.168.1.9) at incomplete on en1 ifscope [ethernet]"
+ assert not MAC_RE.search(line)