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.

Harden audit findings: TLS transport, input validation, bounds

MoneyLisaf931f00a6255
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f136a57..3bd2306 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,10 +6,55 @@ All notable changes to Snitch. / Toutes les modifications notables de Snitch.
The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
-## [Unreleased] — docs & pipeline sync / synchro docs & pipeline
+## [Unreleased] — security & efficiency hardening / durcissement sécurité & efficacité
+
+### Security / Sécurité
+
+- EN: **Agent↔collector TLS** — `snitch-agent` gains opt-in rustls
+ transport (`SNITCH_TLS=1`, WebPKI roots, `SNITCH_CA` for private CAs);
+ the collector terminates TLS when `SNITCH_TLS_CERT`/`SNITCH_TLS_KEY`
+ are set. The `sagt_…` token and flow metadata no longer travel in
+ cleartext on hostile links.
+ FR: **TLS agent↔collecteur** — `snitch-agent` gagne un transport rustls
+ opt-in (`SNITCH_TLS=1`, racines WebPKI, `SNITCH_CA` pour CA privée) ;
+ le collecteur termine TLS avec `SNITCH_TLS_CERT`/`SNITCH_TLS_KEY`. Le
+ jeton `sagt_…` et les métadonnées ne transitent plus en clair.
+- EN: **hosts-file injection closed** — `domain` firewall rules are now
+ validated against a strict RFC-1034 hostname regex before any
+ sinkhole write, and `port` rules must be an integer 1–65535 (both
+ reached argv/hosts verbatim before).
+ FR: **Injection hosts colmatée** — les règles `domain` sont validées
+ par regex RFC-1034 stricte avant toute écriture sinkhole, et les
+ règles `port` exigent un entier 1–65535.
+- EN: **`?token=` restricted to the WebSocket** — REST endpoints only
+ accept the `X-Snitch-Token` header, so the credential can no longer
+ leak into browser history or access logs via API URLs.
+ FR: **`?token=` réservé au WebSocket** — les endpoints REST
+ n'acceptent que l'en-tête `X-Snitch-Token`.
+- EN: **Per-IP brute-force ban** — 20 failed auth attempts in 5 min →
+ HTTP 429 / WS close for 60 s (loopback included).
+ FR: **Bannissement anti-force brute par IP** — 20 échecs en 5 min →
+ HTTP 429 / fermeture WS pendant 60 s (loopback inclus).
+- EN: `SNITCH_PRINT_TOKEN=0` suppresses the one-time stdout token
+ print for hardened deployments (api_token.txt stays readable, 0600).
+ FR: `SNITCH_PRINT_TOKEN=0` supprime l'affichage stdout du jeton.
+- EN: IP whitelist entries are validated (real addresses only, ≤512);
+ port/process filter lists bounded to 512 entries.
+ FR: Les entrées whitelist sont validées (vraies adresses, ≤512) ;
+ filtres de ports/processus bornés à 512.
### Changed / Modifié
+- EN: **Non-blocking WebSocket broadcast** — each client send has a 5 s
+ timeout and runs concurrently, so one stalled UI can no longer delay
+ the packet feed for every other client.
+ FR: **Diffusion WebSocket non bloquante** — chaque envoi client a un
+ timeout de 5 s et tourne en parallèle.
+- EN: `lan_devices` is now bounded (1024 entries, quietest-eviction) —
+ private-prefix enumeration can't grow the map forever.
+ FR: `lan_devices` est désormais bornée (1024 entrées, éviction de la
+ plus discrète).
+
- EN: **All project surfaces synced to v1.6.3** — README (Rust agent,
enrollment, `ti_feeds`, `.rpm`, `snitchd` formula), ROADMAP (v1.5.x/
v1.6.x shipped rows, fleet scale-out items), wiki (API catalog → 76
diff --git a/CITATION.cff b/CITATION.cff
index 9b09381..e78df52 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -18,5 +18,5 @@ keywords:
- privacy
- siem
- cybersecurity
-version: "1.6.3"
+version: "1.6.4"
date-released: "2026-10-22"
diff --git a/SECURITY.md b/SECURITY.md
index 395b4c0..55be260 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -17,9 +17,12 @@ N'ouvrez pas d'issue publique pour les problèmes de sécurité.
**EN:** The API exposes your full traffic graph — it is protected by design:
- **Token auth** on every REST endpoint and the WebSocket
- (`X-Snitch-Token` or `?token=`). Generated per launch under Electron,
- persisted 0600 otherwise.
+ (`X-Snitch-Token` header; `?token=` is honoured on the WebSocket
+ handshake only — it never authenticates REST). Generated per launch
+ under Electron, persisted 0600 otherwise.
- **Loopback bind** (`127.0.0.1`) in all modes by default.
+- **Brute-force guard** — after 20 failed auth attempts in 5 min the
+ source IP is rejected (HTTP 429 / WS close) for 60 s, loopback included.
- **Origin allowlist** on the WebSocket handshake (loopback hosts + `null`)
to block cross-site WebSocket hijacking.
- **Restricted CORS** — loopback origins only, no credentials.
@@ -27,14 +30,21 @@ N'ouvrez pas d'issue publique pour les problèmes de sécurité.
tokens for fleet agents; only the hash is stored and each is revocable
(`/ingest/revoke`). Agent tokens may submit events as themselves only —
no read access, no impersonation.
+- **Optional TLS** — the collector terminates TLS when `SNITCH_TLS_CERT` +
+ `SNITCH_TLS_KEY` are set; `snitch-agent` speaks TLS with `SNITCH_TLS=1`
+ (rustls, WebPKI roots, `SNITCH_CA` for private CAs). Plain HTTP stays
+ the default for loopback/mesh-VPN deployments.
**FR :** L'API expose tout votre graphe de trafic — elle est protégée par
conception :
- **Authentification par jeton** sur chaque endpoint REST et le WebSocket
- (`X-Snitch-Token` ou `?token=`). Généré à chaque lancement sous Electron,
+ (en-tête `X-Snitch-Token` ; `?token=` n'est honoré qu'au handshake
+ WebSocket — jamais pour REST). Généré à chaque lancement sous Electron,
persisté en 0600 sinon.
- **Bind loopback** (`127.0.0.1`) par défaut dans tous les modes.
+- **Garde anti-force brute** — après 20 échecs d'auth en 5 min l'IP
+ source est rejetée (HTTP 429 / fermeture WS) pendant 60 s, loopback inclus.
- **Liste blanche d'Origin** sur le handshake WebSocket (hôtes loopback +
`null`) pour bloquer le détournement de WebSocket cross-site.
- **CORS restreint** — origines loopback uniquement, sans identifiants.
@@ -42,6 +52,10 @@ conception :
`sagt_…` pour les agents de flotte ; seul le hash est stocké et chacun
est révocable (`/ingest/revoke`). Un jeton agent ne peut qu'envoyer des
événements en son nom — pas de lecture, pas d'usurpation.
+- **TLS optionnel** — le collecteur termine TLS quand `SNITCH_TLS_CERT` +
+ `SNITCH_TLS_KEY` sont posés ; `snitch-agent` parle TLS avec
+ `SNITCH_TLS=1` (rustls, racines WebPKI, `SNITCH_CA` pour CA privée).
+ HTTP clair reste le défaut sur loopback/VPN mesh.
## Privileges / Privilèges
diff --git a/agent/.gitignore b/agent/.gitignore
new file mode 100644
index 0000000..2f7896d
--- /dev/null
+++ b/agent/.gitignore
@@ -0,0 +1 @@
+target/
diff --git a/agent/Cargo.lock b/agent/Cargo.lock
new file mode 100644
index 0000000..1b011aa
--- /dev/null
+++ b/agent/Cargo.lock
@@ -0,0 +1,233 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "cc"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom",
+ "libc",
+ "untrusted",
+ "windows-sys",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
+dependencies = [
+ "log",
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-pemfile"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "snitch-agent"
+version = "1.6.4"
+dependencies = [
+ "rustls",
+ "rustls-pemfile",
+ "webpki-roots",
+]
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "zeroize"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
index 2ef2168..54d817d 100644
--- a/agent/Cargo.toml
+++ b/agent/Cargo.toml
@@ -1,11 +1,13 @@
-# Snitch agent — zero-dependency mini-daemon / mini-daemon sans dépendances.
-# EN: `cargo build --release` produces ONE static-ish binary. No crates:
-# /proc parsing is plain fs, the ingest POST is a raw TcpStream.
-# FR: `cargo build --release` produit UN seul binaire. Zéro crate :
-# /proc en fs brut, le POST ingest en TcpStream manuel.
+# Snitch agent — lightweight mini-daemon / mini-daemon léger.
+# EN: `cargo build --release` produces ONE static-ish binary. Deps are kept
+# to the TLS stack only (rustls is pure-Rust, no OpenSSL link): /proc
+# parsing is plain fs, the ingest POST is a hand-built HTTP/1.1 request.
+# FR: `cargo build --release` produit UN seul binaire. Les deps se limitent à
+# la pile TLS (rustls est pur Rust, sans lien OpenSSL) : /proc en fs brut,
+# POST ingest en requête HTTP/1.1 manuelle.
[package]
name = "snitch-agent"
-version = "1.6.3"
+version = "1.6.4"
edition = "2021"
license = "AGPL-3.0-only"
description = "Lightweight socket-observation agent for the Snitch collector"
@@ -14,6 +16,15 @@ description = "Lightweight socket-observation agent for the Snitch collector"
name = "snitch-agent"
path = "src/main.rs"
+[dependencies]
+# EN: TLS is opt-in at runtime (SNITCH_TLS=1) — collectors bound to
+# loopback or fronted by a mesh VPN can skip it entirely.
+# FR: Le TLS est opt-in à l'exécution (SNITCH_TLS=1) — les collecteurs sur
+# loopback ou derrière un VPN mesh peuvent s'en passer.
+rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
+webpki-roots = "1"
+rustls-pemfile = "2"
+
[profile.release]
opt-level = "z" # EN: smallest binary / FR: binaire minimal
lto = true
diff --git a/agent/README.md b/agent/README.md
index fa0e552..53421fd 100644
--- a/agent/README.md
+++ b/agent/README.md
@@ -1,10 +1,11 @@
# snitch-agent — lightweight remote sensor / capteur distant léger
-**EN:** A zero-dependency Rust daemon that watches the host's socket
+**EN:** A minimal-dependency Rust daemon that watches the host's socket
table (`/proc/net/*`, Linux) and pushes newly-observed outbound flows to
a Snitch collector's `POST /ingest/events` — contract `snitch-agent/1`.
-One `cargo build --release` produces a single ~1 MB binary with no
-runtime deps, so it deploys via a plain file copy or `nfpm`.
+One `cargo build --release` produces a single binary whose only crates
+are the pure-Rust TLS stack (rustls) — no OpenSSL, no runtime deps —
+so it deploys via a plain file copy or `nfpm`.
Scope, honestly:
@@ -16,19 +17,22 @@ Scope, honestly:
Windows/macOS builds compile but report `pid: 0` until their
`GetExtendedTcpTable`/`libproc` paths land — they are NOT silently
wrong, just un-attributed;
-- transport is plain HTTP — same trust-domain model as `gossip_peers`;
- tunnel over WireGuard/TLS on hostile links.
+- transport is plain HTTP by default for loopback/mesh-VPN collectors,
+ **with opt-in TLS** (`SNITCH_TLS=1`, `SNITCH_CA=/path/ca.pem` for a
+ private CA) backed by rustls + webpki roots — no system TLS needed.
-**FR :** Un daemon Rust sans dépendance qui surveille la table de
+**FR :** Un daemon Rust à dépendances minimales qui surveille la table de
sockets de l'hôte (`/proc/net/*`, Linux) et pousse les nouveaux flux
sortants vers `POST /ingest/events` du collecteur — contrat
-`snitch-agent/1`. Un seul `cargo build --release` → binaire ~1 Mo sans
-dépendance runtime, déployable par simple copie ou `nfpm`.
+`snitch-agent/1`. Un seul `cargo build --release` → binaire dont les
+seules crates sont la pile TLS pur-Rust (rustls) — pas d'OpenSSL, pas
+de dépendance runtime — déployable par simple copie ou `nfpm`.
Périmètre honnête : SOCKETS seulement (pas de payloads/SNI/DNS),
attribution de processus fonctionnelle sous Linux via `/proc/*/fd`
(reporte `pid: 0` sous Windows/macOS tant que leurs chemins
-`GetExtendedTcpTable`/`libproc` ne sont pas livrés), transport HTTP.
+`GetExtendedTcpTable`/`libproc` ne sont pas livrés), transport HTTP par
+défaut **avec TLS opt-in** (`SNITCH_TLS=1`, `SNITCH_CA` pour CA privée).
## Enroll & run / Enrôler & lancer
@@ -52,6 +56,30 @@ SNITCH_HOST="agent-01" \
spoof another) or the collector master token (sent as `X-Snitch-Token`).
Revoke with `POST /ingest/revoke {"name": "agent-01"}`.
+## TLS / chiffrement
+
+```bash
+# EN: agent side — pure-Rust TLS (rustls + WebPKI roots); SNITCH_CA adds
+# a private-CA bundle for collectors on self-signed/internal certs.
+# FR: côté agent — TLS pur-Rust (rustls + racines WebPKI) ; SNITCH_CA ajoute
+# un bundle CA privé pour les collecteurs en cert auto-signé/interne.
+SNITCH_SERVER="collector:8443" SNITCH_TLS=1 \
+SNITCH_CA="/etc/snitch/ca.pem" SNITCH_TOKEN="sagt_…" \
+./target/release/snitch-agent
+
+# EN: collector side — uvicorn terminates TLS when both env vars are set.
+# FR: côté collecteur — uvicorn termine TLS quand les deux variables sont posées.
+SNITCH_TLS_CERT="/etc/snitch/cert.pem" \
+SNITCH_TLS_KEY="/etc/snitch/key.pem" \
+python run_backend.py
+```
+
+Without `SNITCH_TLS` the agent speaks plain HTTP — fine over loopback,
+localhost or a WireGuard/Tailscale mesh, NOT over a hostile link.
+
+Sans `SNITCH_TLS` l'agent parle HTTP clair — acceptable sur loopback ou
+un mesh WireGuard/Tailscale, PAS sur un lien hostile.
+
## systemd / service
`deploy/systemd/snitch-agent.service` runs it unprivileged — the agent
diff --git a/agent/src/main.rs b/agent/src/main.rs
index a142773..fb53730 100644
--- a/agent/src/main.rs
+++ b/agent/src/main.rs
@@ -6,17 +6,19 @@
//! new outbound/established endpoints only — to the collector's
//! `POST /ingest/events` endpoint, contract `snitch-agent/1`.
//!
-//! Deliberately zero-dependency and honest about scope:
+//! Deliberately minimal-dependency and honest about scope:
//! * it observes SOCKETS, it does not sniff packets — no payloads,
//! no SNI, no DNS answers (the collector's own pcap path keeps
//! those duties on the host it runs on);
-//! * pid↔process attribution needs /proc/*/fd walking — marked
-//! TODO below rather than half-done;
-//! * HTTP only for the same reason gossip allows http: LAN/trust
-//! domain; run behind a WireGuard/TLS tunnel on hostile links.
+//! * pid↔process attribution walks /proc/*/fd (Linux; other OSes
+//! report pid 0 honestly);
+//! * transport is plain HTTP by default — set SNITCH_TLS=1 for
+//! rustls TLS (system-free pure-Rust stack). On hostile links
+//! either enable it or run behind WireGuard/Tailscale.
//!
//! Config: SNITCH_SERVER="collector:8000" SNITCH_TOKEN="<bearer>"
//! SNITCH_HOST="agent-name" SNITCH_INTERVAL_SECS=5
+//! SNITCH_TLS=1 SNITCH_CA="/path/ca.pem"
//!
//! FR: Surveille la table de sockets de l'hôte (/proc/net/*) et pousse
//! le DIFF — nouvelles extrémités sortantes/établies — vers le
@@ -28,14 +30,95 @@
use std::collections::HashSet;
use std::env;
use std::fs;
-use std::io::{Read, Write};
+use std::io::{BufReader, Read, Write};
use std::net::TcpStream;
use std::process;
+use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const AGENT_ID: &str = "snitch-agent/1";
const MAX_EVENTS_PER_POST: usize = 1000; // EN: matches backend cap / FR: cap backend
+/// EN: Transport abstraction — plain TCP or a rustls TLS session over it.
+/// Both implement Read+Write so post_batch stays transport-agnostic.
+/// FR: Abstraction de transport — TCP brut ou session TLS rustls par-dessus.
+/// Les deux implémentent Read+Write pour que post_batch reste agnostique.
+enum Transport {
+ Plain(TcpStream),
+ Tls(rustls::StreamOwned<rustls::ClientConnection, TcpStream>),
+}
+
+impl Read for Transport {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+ match self {
+ Transport::Plain(s) => s.read(buf),
+ Transport::Tls(s) => s.read(buf),
+ }
+ }
+}
+
+impl Write for Transport {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ match self {
+ Transport::Plain(s) => s.write(buf),
+ Transport::Tls(s) => s.write(buf),
+ }
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ match self {
+ Transport::Plain(s) => s.flush(),
+ Transport::Tls(s) => s.flush(),
+ }
+ }
+}
+
+/// EN: Build the root store — the system-free webpki bundle by default,
+/// plus an optional extra CA PEM (SNITCH_CA) for internal collectors
+/// terminating TLS with a private/self-signed certificate.
+/// FR: Construire le magasin de racines — le bundle webpki autonome par
+/// défaut, plus une CA PEM optionnelle (SNITCH_CA) pour les collecteurs
+/// internes terminant TLS avec un certificat privé/auto-signé.
+fn root_store(ca_path: Option<&str>) -> Result<rustls::RootCertStore, String> {
+ let mut roots = rustls::RootCertStore::empty();
+ roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
+ if let Some(path) = ca_path {
+ let f = fs::File::open(path).map_err(|e| format!("open CA {path}: {e}"))?;
+ let certs = rustls_pemfile::certs(&mut BufReader::new(f))
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|e| format!("parse CA {path}: {e}"))?;
+ if certs.is_empty() {
+ return Err(format!("no PEM certificates in {path}"));
+ }
+ let (added, _) = roots.add_parsable_certificates(certs);
+ if added == 0 {
+ return Err(format!("CA file {path} added 0 usable roots"));
+ }
+ }
+ Ok(roots)
+}
+
+fn connect(server: &str, use_tls: bool, ca_path: Option<&str>)
+ -> Result<Transport, String> {
+ let stream = TcpStream::connect(server)
+ .map_err(|e| format!("connect {server}: {e}"))?;
+ stream.set_read_timeout(Some(Duration::from_secs(10))).ok();
+ stream.set_write_timeout(Some(Duration::from_secs(10))).ok();
+ if !use_tls {
+ return Ok(Transport::Plain(stream));
+ }
+ // EN: SNI / verification name = the host part of "host:port".
+ // FR: Nom SNI / de vérification = la partie hôte de « host:port ».
+ let host = server.rsplit_once(':').map(|(h, _)| h).unwrap_or(server);
+ let name = rustls::pki_types::ServerName::try_from(host.to_string())
+ .map_err(|e| format!("bad server name {host}: {e}"))?;
+ let config = rustls::ClientConfig::builder()
+ .with_root_certificates(root_store(ca_path)?)
+ .with_no_client_auth();
+ let conn = rustls::ClientConnection::new(Arc::new(config), name)
+ .map_err(|e| format!("tls init: {e}"))?;
+ Ok(Transport::Tls(rustls::StreamOwned::new(conn, stream)))
+}
+
#[derive(Clone, PartialEq, Eq, Hash)]
struct Sock {
proto: String, // "tcp" | "udp"
@@ -131,14 +214,14 @@ fn json_escape(s: &str) -> String {
}
fn post_batch(server: &str, token: &str, host: &str,
- events: &[String]) -> Result<(), String> {
- // EN: Minimal HTTP/1.1 POST, no TLS stack — see module doc for the
- // trust-domain reasoning. `sagt_…` tokens are per-agent enrolled
- // credentials → `X-Snitch-Agent`; anything else is the master
- // API token → `X-Snitch-Token`.
- // FR: POST HTTP/1.1 minimal, pas de TLS — voir le doc module. Les
- // jetons « sagt_… » sont des crédences d'agent enrôlé →
- // « X-Snitch-Agent » ; le reste = jeton maître → « X-Snitch-Token ».
+ events: &[String], use_tls: bool, ca_path: Option<&str>)
+ -> Result<(), String> {
+ // EN: Minimal HTTP/1.1 POST over plain TCP or rustls TLS. `sagt_…`
+ // tokens are per-agent enrolled credentials → `X-Snitch-Agent`;
+ // anything else is the master API token → `X-Snitch-Token`.
+ // FR: POST HTTP/1.1 minimal sur TCP brut ou TLS rustls. Les jetons
+ // « sagt_… » sont des crédences d'agent enrôlé → « X-Snitch-Agent » ;
+ // le reste = jeton maître → « X-Snitch-Token ».
let auth = if token.starts_with("sagt_") {
format!("X-Snitch-Agent: {token}")
} else {
@@ -152,13 +235,20 @@ fn post_batch(server: &str, token: &str, host: &str,
{auth}\r\nContent-Type: application/json\r\n\
Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len());
- let mut stream = TcpStream::connect(server)
- .map_err(|e| format!("connect {server}: {e}"))?;
- stream.set_read_timeout(Some(Duration::from_secs(10))).ok();
- stream.set_write_timeout(Some(Duration::from_secs(10))).ok();
+ let mut stream = connect(server, use_tls, ca_path)?;
stream.write_all(req.as_bytes()).map_err(|e| e.to_string())?;
- let mut resp = String::new();
- stream.read_to_string(&mut resp).map_err(|e| e.to_string())?;
+ // EN: read the whole response; a TLS peer that drops without
+ // close_notify must not discard an otherwise complete answer —
+ // only propagate the error when nothing arrived at all.
+ // FR: lire toute la réponse ; un pair TLS qui coupe sans close_notify
+ // ne doit pas faire perdre une réponse complète — ne propager
+ // l'erreur que si rien n'est arrivé.
+ let mut raw = Vec::new();
+ let read_res = stream.read_to_end(&mut raw);
+ if raw.is_empty() {
+ read_res.map_err(|e| e.to_string())?;
+ }
+ let resp = String::from_utf8_lossy(&raw);
match resp.split(' ').nth(1) {
Some(code) if code.starts_with('2') => Ok(()),
_ => Err(format!("ingest rejected: {}",
@@ -236,10 +326,18 @@ fn main() {
.unwrap_or_else(|_| env::var("HOSTNAME").unwrap_or_else(|_| "agent".into()));
let interval: u64 = env::var("SNITCH_INTERVAL_SECS")
.ok().and_then(|v| v.parse().ok()).unwrap_or(5).max(1);
+ // EN: TLS opt-in — anything but empty/"0" enables it. SNITCH_CA points
+ // at an extra PEM bundle for collectors on a private CA.
+ // FR: TLS opt-in — tout sauf vide/« 0 » l'active. SNITCH_CA pointe vers
+ // un bundle PEM additionnel pour les collecteurs en CA privée.
+ let use_tls = !matches!(env::var("SNITCH_TLS").as_deref(),
+ Err(_) | Ok("") | Ok("0"));
+ let ca_path = env::var("SNITCH_CA").ok().filter(|s| !s.is_empty());
let mut seen: HashSet<Sock> = HashSet::new();
let mut pending: Vec<String> = Vec::new();
- eprintln!("snitch-agent {AGENT_ID} → {server} as '{host}' every {interval}s");
+ eprintln!("snitch-agent {AGENT_ID} → {server} as '{host}' every {interval}s{}",
+ if use_tls { " (TLS)" } else { "" });
loop {
let now = socket_table();
@@ -264,7 +362,8 @@ fn main() {
if !pending.is_empty() {
let chunk: Vec<String> = pending
.drain(..pending.len().min(MAX_EVENTS_PER_POST)).collect();
- match post_batch(&server, &token, &host, &chunk) {
+ match post_batch(&server, &token, &host, &chunk,
+ use_tls, ca_path.as_deref()) {
Ok(()) => {}
Err(e) => {
eprintln!("snitch-agent: {e}");
diff --git a/backend/api/main.py b/backend/api/main.py
index 128bcdf..10768ec 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -251,6 +251,7 @@ _drop_stats = {
# FR: Plafonds stricts pour qu'une instance longue durée ne fuie pas de mémoire.
MAX_GRAPH_NODES = 800
MAX_ENRICHMENT_CACHE = 4096
+MAX_LAN_DEVICES = 1024 # EN: private-peer enumeration can't grow the map / FR: borne la map de pairs privés
DRAIN_INTERVAL_S = 0.25 # EN: ~4 Hz batch broadcasts / FR: ~4 lots par seconde
DRAIN_MAX_PACKETS = 2_000 # EN: per tick / FR: par tick
@@ -467,18 +468,25 @@ async def broadcast(message: dict) -> None:
if not connected_clients:
return
payload = json.dumps(message)
- dead = []
- for ws in connected_clients:
+
+ async def _send(ws: WebSocket) -> Optional[WebSocket]:
try:
- await ws.send_text(payload)
+ # EN: Per-client timeout — one stalled client must not hold the
+ # whole broadcast hostage (slow reader, flaky LAN UI).
+ # FR: Timeout par client — un client bloqué ne doit pas prendre
+ # en otage toute la diffusion (lecteur lent, UI LAN instable).
+ await asyncio.wait_for(ws.send_text(payload), timeout=5)
+ return None
except Exception:
- dead.append(ws)
+ return ws
+
+ dead = await asyncio.gather(*(_send(ws) for ws in list(connected_clients)))
for ws in dead:
# EN: the WS handler may have already dropped it — remove() must not
# raise on an absent element or the whole packet batch is lost.
# FR: le handler WS a pu le retirer avant — remove() ne doit pas
# lever sur un élément absent sinon tout le batch est perdu.
- if ws in connected_clients:
+ if ws is not None and ws in connected_clients:
connected_clients.remove(ws)
@@ -569,6 +577,16 @@ def _ensure_lan_device(ip: str) -> dict:
dev["vendor"] = stored["vendor"]
if stored.get("device_type") and dev["device_type"] == "unknown":
dev["device_type"] = stored["device_type"]
+ # EN: Bound the map — a host enumerating a large private prefix
+ # (VPN scan) must not grow lan_devices forever. Evict the
+ # quietest device when full.
+ # FR: Borner la map — un hôte énumérant un gros préfixe privé
+ # (scan VPN) ne doit pas faire grossir lan_devices sans fin.
+ # Évincer l'appareil le plus discret quand c'est plein.
+ if len(lan_devices) >= MAX_LAN_DEVICES:
+ victim = min(lan_devices, key=lambda k: lan_devices[k].get("bytes", 0))
+ edges.pop(f"lan-edge-{lan_devices[victim].get('ip', '')}", None)
+ lan_devices.pop(victim, None)
lan_devices[key] = dev
edges[f"lan-edge-{ip}"] = {
"id": f"lan-edge-{ip}", "source": "local", "target": key,
@@ -1709,6 +1727,14 @@ async def _handle_device(device: Device, is_new: bool) -> None:
hostname=node.get("hostname"),
private_mac=device.private_mac)
+ # EN: Same bound as _ensure_lan_device — the map must stay finite even
+ # when the ARP scanner runs on a huge broadcast domain.
+ # FR: Même borne que _ensure_lan_device — la map doit rester finie même
+ # quand le scanner ARP tourne sur un immense domaine broadcast.
+ if node["id"] not in lan_devices and len(lan_devices) >= MAX_LAN_DEVICES:
+ victim = min(lan_devices, key=lambda k: lan_devices[k].get("bytes", 0))
+ edges.pop(f"lan-edge-{lan_devices[victim].get('ip', '')}", None)
+ lan_devices.pop(victim, None)
lan_devices[node["id"]] = node
edge_id = f"lan-edge-{device.ip}"
@@ -2356,7 +2382,9 @@ async def set_port_filter(body: PortFilterBody) -> dict:
trafic correspondant. Persisté — le filtre survit aux redémarrages.
"""
global _port_filter
- _port_filter = [p for p in body.ports if 1 <= p <= 65535]
+ # EN: Bounded too — an absurd list would only waste memory and log noise.
+ # FR: Bornée aussi — une liste absurde ne ferait que gaspiller mémoire et logs.
+ _port_filter = [p for p in body.ports[:512] if 1 <= p <= 65535]
db.set_setting("ports", _port_filter)
# EN: Clear graph + detector state — keep only the "local" node.
@@ -2400,7 +2428,7 @@ async def set_process_filter(body: ProcessFilterBody) -> dict:
"""EN: Hide traffic from named processes (persisted).
FR: Masquer le trafic de processus nommés (persisté)."""
global _excluded_processes
- _excluded_processes = {str(p) for p in body.excluded}
+ _excluded_processes = {str(p)[:256] for p in body.excluded[:512]}
db.set_setting("excluded_processes", sorted(_excluded_processes))
await broadcast({
@@ -2424,7 +2452,18 @@ async def set_ip_whitelist(body: WhitelistBody) -> dict:
whitelist fonctionne ensuite correctement.
"""
global _whitelisted_ips
- _whitelisted_ips = {str(ip) for ip in body.ips}
+ # EN: Validate every entry — whitelist strings feed askmode's exempt_ips
+ # which reach iptables argv (validated there too, but failing here
+ # gives the user an immediate 400 instead of a deferred error).
+ # FR: Valider chaque entrée — la whitelist alimente exempt_ips d'askmode
+ # qui arrive en argv iptables (validé là aussi, mais échouer ici
+ # donne un 400 immédiat au lieu d'une erreur différée).
+ import ipaddress
+ try:
+ _whitelisted_ips = {str(ipaddress.ip_address(str(ip).strip()))
+ for ip in body.ips[:512]}
+ except ValueError:
+ raise HTTPException(400, "whitelist entries must be valid IP addresses") from None
db.set_setting("whitelisted_ips", sorted(_whitelisted_ips))
removed_ids = [ip for ip in _whitelisted_ips
diff --git a/backend/api/security.py b/backend/api/security.py
index 1f2d7f2..39cfe61 100644
--- a/backend/api/security.py
+++ b/backend/api/security.py
@@ -5,8 +5,10 @@ EN: Three complementary protections:
1. Bearer-style token. Generated at startup (or taken from the
SNITCH_TOKEN env var, which is how the Electron wrapper injects
it), persisted to <data>/api_token.txt (0600) and printed once to
- stdout so Docker/dev users can pass ?token=… in the browser.
- Every REST endpoint and the WebSocket require it.
+ stdout so Docker/dev users can pass ?token=… in the browser
+ (disable that print with SNITCH_PRINT_TOKEN=0). REST endpoints
+ require the X-Snitch-Token header; ?token= is honoured on the
+ WebSocket handshake only.
2. CORS allowlist — no more `*`. Only the Vite dev server, the
backend's own origin and `null` (file:// pages under Electron).
3. Origin check on the WebSocket handshake — blocks Cross-Site
@@ -16,8 +18,10 @@ FR: Trois protections complémentaires :
1. Jeton d'authentification. Généré au démarrage (ou pris de la variable
SNITCH_TOKEN, ce que fait le conteneur Electron), persisté dans
<data>/api_token.txt (0600) et affiché une fois sur stdout pour que
- les utilisateurs Docker/dev passent ?token=… dans le navigateur.
- Chaque endpoint REST et le WebSocket l'exigent.
+ les utilisateurs Docker/dev passent ?token=… dans le navigateur
+ (désactivable via SNITCH_PRINT_TOKEN=0). Les endpoints REST exigent
+ l'en-tête X-Snitch-Token ; ?token= n'est honoré qu'au handshake
+ WebSocket.
2. Liste blanche CORS — plus de `*`. Seulement le serveur de dev Vite,
l'origine du backend lui-même et `null` (pages file:// sous Electron).
3. Vérification d'Origin sur le handshake WebSocket — bloque le
@@ -27,6 +31,8 @@ FR: Trois protections complémentaires :
import logging
import os
import secrets
+import threading
+import time
from fastapi import HTTPException, Request, WebSocket, status
@@ -132,8 +138,14 @@ def _load_or_create_token() -> str:
logger.warning("Could not persist API token to %s: %s", token_file, exc)
# EN: Printed once so Docker/browser users can complete the ?token= URL.
- # FR: Affiché une fois pour que les utilisateurs Docker/navigateur complètent l'URL ?token=.
- print(f"[snitch] API token: {token}", flush=True)
+ # Hardened deployments can suppress it with SNITCH_PRINT_TOKEN=0 —
+ # the token remains readable from api_token.txt (0600).
+ # FR: Affiché une fois pour que les utilisateurs Docker/navigateur
+ # complètent l'URL ?token=. Les déploiements durcis peuvent le
+ # supprimer via SNITCH_PRINT_TOKEN=0 — le jeton reste lisible dans
+ # api_token.txt (0600).
+ if os.environ.get("SNITCH_PRINT_TOKEN", "1") != "0":
+ print(f"[snitch] API token: {token}", flush=True)
return token
@@ -148,28 +160,100 @@ def get_token() -> str:
return API_TOKEN
+# ── Brute-force guard / Garde anti-force brute ───────────────────────────────
+# EN: The 48-hex token is not realistically brute-forceable, but when the
+# API is bound to a LAN address (opt-in SNITCH_BIND) failed attempts
+# are cheap to spray. Track failures per client IP: after
+# _AUTH_MAX_FAILS within _AUTH_WINDOW_S the source is rejected with
+# 429/4401 for _AUTH_BAN_S. Loopback keeps the same rules — a rogue
+# local process should not get unlimited guesses either.
+# FR: Le jeton hex de 48 caractères n'est pas réalistement brute-forçable,
+# mais quand l'API écoute sur une adresse LAN (SNITCH_BIND opt-in) les
+# tentatives ratées ne coûtent rien. Suivre les échecs par IP cliente :
+# après _AUTH_MAX_FAILS dans _AUTH_WINDOW_S la source est rejetée en
+# 429/4401 pendant _AUTH_BAN_S. Loopback suit les mêmes règles — un
+# processus local malveillant ne doit pas avoir d'essais illimités non plus.
+_AUTH_MAX_FAILS = 20
+_AUTH_WINDOW_S = 300.0
+_AUTH_BAN_S = 60.0
+_AUTH_FAILS_CAP = 512 # EN: bound the tracker dict / FR: borne du suivi
+_fail_lock = threading.Lock()
+_fail_track: dict[str, list[float]] = {}
+_banned_until: dict[str, float] = {}
+
+
+def _client_ip(request: Request | WebSocket) -> str:
+ """EN: Client source for the ban tracker. / FR: Source cliente pour le suivi."""
+ return request.client.host if request.client else "unknown"
+
+
+def _check_banned(ip: str) -> bool:
+ """EN: True while `ip` is inside its ban window.
+ FR: True tant qu'`ip` est dans sa fenêtre de bannissement."""
+ with _fail_lock:
+ until = _banned_until.get(ip, 0.0)
+ if until > time.time():
+ return True
+ _banned_until.pop(ip, None)
+ return False
+
+
+def _record_failure(ip: str) -> None:
+ """EN: Count a failed auth; ban at the threshold. Prunes stale entries
+ so a long-running instance can't grow the tracker unboundedly.
+ FR: Compter un échec d'auth ; bannir au seuil. Épure les entrées
+ périmées pour ne pas laisser le suivi grossir indéfiniment."""
+ now = time.time()
+ with _fail_lock:
+ fails = _fail_track.setdefault(ip, [])
+ fails.append(now)
+ fresh = [t for t in fails if now - t < _AUTH_WINDOW_S]
+ if len(fresh) >= _AUTH_MAX_FAILS:
+ _banned_until[ip] = now + _AUTH_BAN_S
+ _fail_track.pop(ip, None)
+ logger.warning("auth failures: %s banned for %ds", ip,
+ int(_AUTH_BAN_S))
+ return
+ _fail_track[ip] = fresh
+ # EN: Bound the dict — evict the oldest-seen sources beyond the cap.
+ # FR: Borner le dict — évincer les sources les plus anciennes au-delà du plafond.
+ if len(_fail_track) > _AUTH_FAILS_CAP:
+ for k in sorted(_fail_track,
+ key=lambda k: _fail_track[k][0])[:64]:
+ _fail_track.pop(k, None)
+
+
def _extract_token(request: Request) -> str | None:
"""
- EN: Accept `X-Snitch-Token` header (preferred) or `?token=` query param
- (needed by the WebSocket, which can't set headers in the browser API).
- FR: Accepter l'en-tête `X-Snitch-Token` (préféré) ou le paramètre `?token=`
- (nécessaire pour le WebSocket, qui ne peut pas poser d'en-têtes dans
- l'API navigateur).
+ EN: `X-Snitch-Token` header ONLY. The `?token=` query param is honoured
+ on the WebSocket handshake (browser API can't set headers) but not
+ on REST — URLs end up in browser history and access logs.
+ FR: En-tête `X-Snitch-Token` UNIQUEMENT. Le paramètre `?token=` est
+ honoré au handshake WebSocket (l'API navigateur ne peut pas poser
+ d'en-têtes) mais pas sur REST — les URLs finissent dans l'historique
+ navigateur et les access logs.
"""
- return request.headers.get("x-snitch-token") or request.query_params.get("token")
+ return request.headers.get("x-snitch-token")
def require_token(request: Request) -> None:
"""
EN: FastAPI dependency — 401 unless a valid token is presented.
Applies to ALL endpoints: even GET /graph leaks sensitive traffic data.
+ Repeated failures earn the source a 429 ban.
FR: Dépendance FastAPI — 401 sans jeton valide.
S'applique à TOUS les endpoints : même GET /graph divulgue des données
- de trafic sensibles.
+ de trafic sensibles. Les échecs répétés valent un bannissement 429.
"""
+ ip = _client_ip(request)
+ if _check_banned(ip):
+ raise HTTPException(status.HTTP_429_TOO_MANY_REQUESTS,
+ detail="too many failed auth attempts")
token = _extract_token(request)
if not token or not secrets.compare_digest(token, API_TOKEN):
- raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API token")
+ _record_failure(ip)
+ raise HTTPException(status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid or missing API token")
async def ws_authorized(websocket: WebSocket) -> bool:
@@ -180,11 +264,16 @@ async def ws_authorized(websocket: WebSocket) -> bool:
?token=. Ferme avec 4401/4403 et renvoie False en cas d'échec pour
que l'appelant abandonne.
"""
+ ip = _client_ip(websocket)
+ if _check_banned(ip):
+ await websocket.close(code=4401)
+ return False
if not origin_allowed(websocket.headers.get("origin")):
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
return False
token = websocket.query_params.get("token") or websocket.headers.get("x-snitch-token")
if not token or not secrets.compare_digest(token, API_TOKEN):
+ _record_failure(ip)
await websocket.close(code=4401)
return False
return True
diff --git a/backend/cli.py b/backend/cli.py
index c3e378b..273bce5 100644
--- a/backend/cli.py
+++ b/backend/cli.py
@@ -96,7 +96,11 @@ def main() -> int:
# FR: Ouvrir après un court délai pour qu'uvicorn écoute d'abord.
threading.Timer(1.0, lambda: webbrowser.open(url)).start()
- uvicorn.run(app, host=args.bind, port=port, log_level="warning")
+ # EN: Same optional TLS as run_backend — SNITCH_TLS_CERT/SNITCH_TLS_KEY.
+ # FR: Même TLS optionnel que run_backend — SNITCH_TLS_CERT/SNITCH_TLS_KEY.
+ uvicorn.run(app, host=args.bind, port=port, log_level="warning",
+ ssl_certfile=os.environ.get("SNITCH_TLS_CERT") or None,
+ ssl_keyfile=os.environ.get("SNITCH_TLS_KEY") or None)
return 0
diff --git a/backend/detection/firewall.py b/backend/detection/firewall.py
index 6a1ed8f..ed2cdbe 100644
--- a/backend/detection/firewall.py
+++ b/backend/detection/firewall.py
@@ -51,6 +51,7 @@ from __future__ import annotations
import ipaddress
import os
import platform
+import re
import shutil
import socket
import subprocess
@@ -60,6 +61,15 @@ import uuid
from pathlib import Path
from typing import Optional
+# EN: RFC-1034/1123 hostname — labels of ≤63 alnum/dash chars joined by
+# dots, total ≤253. Anchored so no whitespace/newline can slip through.
+# FR: Nom d'hôte RFC-1034/1123 — labels de ≤63 caractères alnum/tiret joints
+# par des points, total ≤253. Ancré : aucun espace/newline ne passe.
+_DOMAIN_RE = re.compile(
+ r"(?=.{1,253}\Z)"
+ r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
+ r"(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\Z")
+
# EN: Cooldown between two BLOCKED_ATTEMPT alerts for the same rule.
# FR: Cooldown entre deux alertes BLOCKED_ATTEMPT pour une même règle.
_BLOCKED_COOLDOWN = 120
@@ -165,6 +175,30 @@ class FirewallManager:
raise ValueError(f"unknown rule action: {action}")
if action != "block" and kind in ("process", "port"):
raise ValueError(f"{action} is not meaningful for kind {kind}")
+ if kind == "domain":
+ # EN: Strict hostname validation — the sinkhole path writes this
+ # value verbatim into the hosts file, so newlines/whitespace
+ # or shell chars must be impossible.
+ # FR: Validation stricte du nom d'hôte — le chemin sinkhole
+ # écrit cette valeur verbatim dans le fichier hosts, donc
+ # retours à la ligne/espaces/caractères shell impossibles.
+ value = value.lower().rstrip(".")
+ if not _DOMAIN_RE.match(value):
+ raise ValueError(f"invalid domain name: {value[:80]}")
+ if kind == "port":
+ # EN: Ports reach iptables/netsh argv — coerce to a real port
+ # number so the rule fails here, not silently downstream.
+ # FR: Les ports arrivent en argv iptables/netsh — forcer un
+ # vrai numéro pour échouer ici, pas silencieusement plus bas.
+ try:
+ port_no = int(value)
+ except ValueError:
+ raise ValueError(f"invalid port: {value[:80]}") from None
+ if not 1 <= port_no <= 65535:
+ raise ValueError(f"port out of range: {port_no}")
+ value = str(port_no)
+ if len(value) > 253:
+ raise ValueError("rule value too long")
rule = {
"id": uuid.uuid4().hex[:10],
"kind": kind,
diff --git a/backend/run_backend.py b/backend/run_backend.py
index 5d0ef8e..14a47eb 100644
--- a/backend/run_backend.py
+++ b/backend/run_backend.py
@@ -107,10 +107,21 @@ if __name__ == '__main__':
# est honoré en dernière priorité — env et argv gagnent toujours.
import storage.db as _db
_lan_bind = _db.get_setting("lan_bind", "") or ""
+ # EN: Optional TLS termination — set SNITCH_TLS_CERT + SNITCH_TLS_KEY to
+ # PEM paths (e.g. for remote collectors receiving snitch-agent posts
+ # over SNITCH_TLS=1). Off by default: loopback serving needs no TLS.
+ # FR: Terminaison TLS optionnelle — poser SNITCH_TLS_CERT +
+ # SNITCH_TLS_KEY vers des PEM (ex. collecteur distant recevant des
+ # posts snitch-agent en SNITCH_TLS=1). Off par défaut : loopback n'en
+ # a pas besoin.
+ _tls_cert = os.environ.get('SNITCH_TLS_CERT') or None
+ _tls_key = os.environ.get('SNITCH_TLS_KEY') or None
uvicorn.run(
app,
host=(os.environ.get('SNITCH_BIND') or argv_bind
or _lan_bind or '127.0.0.1'),
port=int(os.environ.get('SNITCH_PORT') or argv_port or '8000'),
log_level='warning',
+ ssl_certfile=_tls_cert,
+ ssl_keyfile=_tls_key,
)
diff --git a/backend/tests/test_security.py b/backend/tests/test_security.py
index 1958476..710eeee 100644
--- a/backend/tests/test_security.py
+++ b/backend/tests/test_security.py
@@ -1,12 +1,13 @@
"""
Snitch — API security tests.
-EN: Verifies the token gate (401 without / wrong token, 200 with header or
- ?token=) and the Origin allowlist used by both CORS and the WebSocket
- handshake.
+EN: Verifies the token gate (401 without / wrong token, 200 with header;
+ ?token= is WebSocket-only and now 401 on REST), the per-IP brute-force
+ ban, and the Origin allowlist used by CORS and the WebSocket handshake.
FR: Vérifie la barrière à jeton (401 sans jeton / mauvais jeton, 200 avec
- en-tête ou ?token=) et la liste blanche d'Origin utilisée par CORS et le
- handshake WebSocket.
+ en-tête ; ?token= réservé au WebSocket et désormais 401 sur REST), le
+ bannissement anti-force brute par IP et la liste blanche d'Origin
+ utilisée par CORS et le handshake WebSocket.
"""
import pytest
@@ -40,9 +41,13 @@ def test_valid_header_token_passes():
assert r.status_code == 200
-def test_valid_query_token_passes():
+def test_query_token_rejected_on_rest():
+ """EN: ?token= is honoured on /ws only — on REST it must 401 so the
+ credential cannot linger in URLs, history or access logs.
+ FR: ?token= n'est honoré que sur /ws — sur REST il doit renvoyer 401
+ pour que la crédence ne persiste pas dans URLs, historique ou logs."""
r = client.get(f"/protected?token={API_TOKEN}")
- assert r.status_code == 200
+ assert r.status_code == 401
@pytest.mark.parametrize("origin", [
@@ -72,3 +77,41 @@ def test_absent_origin_allowed():
"""EN: No Origin header = non-browser client (curl, Electron main) — allowed.
FR: Pas d'en-tête Origin = client non-navigateur (curl, main Electron) — autorisé."""
assert origin_allowed(None)
+
+
+def test_bruteforce_triggers_ban():
+ """EN: After _AUTH_MAX_FAILS bad tokens the source gets 429 instead of
+ another 401 — and the ban window then rejects even valid tokens.
+ FR: Après _AUTH_MAX_FAILS mauvais jetons la source obtient 429 au lieu
+ d'un 401 — et la fenêtre de bannissement rejette même les bons jetons."""
+ import api.security as sec
+ ip = "10.66.0.1"
+ with sec._fail_lock:
+ sec._fail_track.clear()
+ sec._banned_until.clear()
+ for _ in range(sec._AUTH_MAX_FAILS):
+ sec._record_failure(ip)
+ assert sec._check_banned(ip)
+ # EN: A banned source stays banned until the window expires.
+ # FR: Une source bannie le reste jusqu'à l'expiration de la fenêtre.
+ assert sec._check_banned(ip)
+ # EN: Simulate expiry — the ban lifts cleanly.
+ # FR: Simuler l'expiration — le bannissement se lève proprement.
+ with sec._fail_lock:
+ sec._banned_until[ip] = 0.0
+ assert not sec._check_banned(ip)
+
+
+def test_fail_tracker_stays_bounded():
+ """EN: Spraying failures from many distinct sources must not grow the
+ tracker dict past _AUTH_FAILS_CAP.
+ FR: Arroser des échecs depuis de nombreuses sources distinctes ne doit
+ pas faire grossir le suivi au-delà de _AUTH_FAILS_CAP."""
+ import api.security as sec
+ with sec._fail_lock:
+ sec._fail_track.clear()
+ sec._banned_until.clear()
+ for i in range(sec._AUTH_FAILS_CAP + 200):
+ sec._record_failure(f"192.0.2.{i % 250}")
+ with sec._fail_lock:
+ assert len(sec._fail_track) <= sec._AUTH_FAILS_CAP
diff --git a/backend/tests/test_security_features.py b/backend/tests/test_security_features.py
index ed1b843..a2a6427 100644
--- a/backend/tests/test_security_features.py
+++ b/backend/tests/test_security_features.py
@@ -346,6 +346,42 @@ def test_rule_action_defaults_to_block(tmp_path, monkeypatch):
raise AssertionError("expected ValueError for bogus action")
+def test_domain_rule_rejects_injection(tmp_path, monkeypatch):
+ """EN: Domain values must be real hostnames — a newline or whitespace
+ would otherwise be written verbatim into the hosts file by the
+ sinkhole path (host-mapping injection).
+ FR: Les valeurs domaine doivent être de vrais noms d'hôte — un newline
+ ou espace serait sinon écrit verbatim dans le fichier hosts par le
+ chemin sinkhole (injection de mappings)."""
+ fw = _fw(tmp_path, monkeypatch)
+ for bad in ("evil.com\n0.0.0.0 bank.example", "evil.com extra",
+ "-bad.com", "ex_ample.com", "", "a" * 254 + ".com"):
+ try:
+ fw.add_rule("domain", bad)
+ except ValueError:
+ continue
+ raise AssertionError(f"domain accepted: {bad!r}")
+ assert fw.add_rule("domain", "good-example.com")["value"] == \
+ "good-example.com"
+
+
+def test_port_rule_validates_range(tmp_path, monkeypatch):
+ """EN: Port values must coerce to 1-65535 — the string reaches iptables
+ /netsh argv, so reject junk at creation.
+ FR: Les valeurs port doivent donner 1-65535 — la chaîne arrive en argv
+ iptables/netsh, donc rejeter le bruit à la création."""
+ fw = _fw(tmp_path, monkeypatch)
+ for bad in ("0", "70000", "abc", "80 -j ACCEPT", "8.8.8.8"):
+ try:
+ fw.add_rule("port", bad)
+ except ValueError:
+ continue
+ raise AssertionError(f"port accepted: {bad!r}")
+ # EN: Normalized — leading zeros collapse to the canonical int form.
+ # FR: Normalisé — les zéros initiaux se replient sur la forme int.
+ assert fw.add_rule("port", "080")["value"] == "80"
+
+
# ── Integrity watch / Veille d'intégrité ────────────────────────────────────
diff --git a/backend/version.py b/backend/version.py
index a3a5ce9..91606fd 100644
--- a/backend/version.py
+++ b/backend/version.py
@@ -5,4 +5,4 @@ FR: Source unique de la version du backend (affichée dans /diagnostics).
À garder alignée avec electron/package.json et frontend/package.json.
"""
-__version__ = "1.6.3"
+__version__ = "1.6.4"
diff --git a/electron/package.json b/electron/package.json
index 55e3039..79406bc 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch",
- "version": "1.6.3",
+ "version": "1.6.4",
"description": "Snitch \u2014 real-time network traffic visualizer / visualiseur de trafic r\u00e9seau en temps r\u00e9el",
"main": "main.js",
"license": "AGPL-3.0-or-later",
diff --git a/frontend/package.json b/frontend/package.json
index 9300227..c4ec573 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch-frontend",
- "version": "1.6.3",
+ "version": "1.6.4",
"private": true,
"license": "AGPL-3.0-or-later",
"description": "Snitch UI \u2014 React + D3.js / Interface React + D3.js",