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.

Fleet maturity 1.6.2 — enrollment, feed refresh, agent CI

MoneyLisa2497c1d549dd
diff --git a/.github/workflows/ci-agent.yml b/.github/workflows/ci-agent.yml
new file mode 100644
index 0000000..286b3e7
--- /dev/null
+++ b/.github/workflows/ci-agent.yml
@@ -0,0 +1,51 @@
+# Snitch agent — Rust CI / CI Rust de l'agent
+# EN: Compile + unit-test the zero-dependency agent on all three desktop
+# targets on every push touching agent/. The binary MUST stay
+# dependency-free — if a crate is ever added, Cargo.lock appears and
+# this file should pin it.
+# FR: Compile + teste l'agent zéro-dépendance sur les trois cibles
+# desktop à chaque push touchant agent/. Le binaire DOIT rester sans
+# dépendance — si une crate est ajoutée, Cargo.lock apparaît et ce
+# fichier devra l'épingler.
+
+name: agent-ci
+
+on:
+ push:
+ paths: ["agent/**", ".github/workflows/ci-agent.yml"]
+ pull_request:
+ paths: ["agent/**"]
+
+jobs:
+ build:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: ubuntu-latest
+ target: x86_64-unknown-linux-gnu
+ artifact: snitch-agent-linux-x86_64
+ - os: macos-latest
+ target: x86_64-apple-darwin
+ artifact: snitch-agent-macos-x86_64
+ - os: windows-latest
+ target: x86_64-pc-windows-msvc
+ artifact: snitch-agent-windows-x86_64.exe
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: ${{ matrix.target }}
+ - name: Unit tests / tests unitaires
+ working-directory: agent
+ run: cargo test
+ - name: Release build / build release
+ working-directory: agent
+ run: cargo build --release --target ${{ matrix.target }}
+ - name: Upload binary / envoi du binaire
+ uses: actions/upload-artifact@v4
+ with:
+ name: ${{ matrix.artifact }}
+ path: agent/target/${{ matrix.target }}/release/snitch-agent*
+ if-no-files-found: ignore
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 260d880..674249d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,55 @@ All notable changes to Snitch. / Toutes les modifications notables de Snitch.
The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
+## [1.6.2] — 2026-10-22 — fleet maturity / maturité de flotte
+
+### Added / Ajouté
+
+- EN: **Per-agent enrollment** — `POST /ingest/enroll` mints one-shot
+ `sagt_…` credentials (only the hash is stored), `GET /ingest/agents`
+ lists them, `POST /ingest/revoke` kills one by name. `/ingest/events`
+ accepts `X-Snitch-Agent: sagt_…` where the enrolled name is
+ authoritative (a stolen token can't spoof another agent) or the master
+ `X-Snitch-Token` for local deployments.
+ FR: **Enrôlement par agent** — `POST /ingest/enroll` mint des crédences
+ `sagt_…` one-shot (seul le hash est stocké), `GET /ingest/agents` les
+ liste, `POST /ingest/revoke` les révoque par nom. `/ingest/events`
+ accepte `X-Snitch-Agent: sagt_…` (le nom enrôlé fait foi — un jeton
+ volé ne peut pas usurper un autre agent) ou le jeton maître.
+- EN: **Agent process attribution (Linux)** — the Rust agent now maps
+ socket inodes to `pid`/`process` via a `/proc/*/fd` walk, lazily
+ (only when new sockets appear). Still zero-dependency; Windows/macOS
+ builds compile and report `pid: 0` until their OS paths land.
+ FR: **Attribution de processus (Linux)** — l'agent Rust mappe les
+ inodes de socket vers `pid`/`process` via `/proc/*/fd`, à la demande.
+ Toujours zéro-dépendance ; les builds Windows/macOS compilent et
+ reportent `pid: 0` tant que leurs chemins OS ne sont pas livrés.
+- EN: **Scheduled threat feeds** — the `ti_feeds` setting (declarative
+ via `snitch.toml` or `POST /settings`) refreshes each feed on its own
+ `hours` clock through a background asyncio worker; imports run
+ through the same dedupe/caps path as `/firewall/blocklist` and the
+ firewall reloads hot. `ti_feeds_state` persists last-fetch times.
+ FR: **Flux TI planifiés** — le réglage `ti_feeds` (déclaratif via
+ `snitch.toml` ou `POST /settings`) rafraîchit chaque flux selon son
+ horloge `hours` via un worker asyncio ; imports par le même chemin
+ dédupe/caps que `/firewall/blocklist`, pare-feu rechargé à chaud.
+- EN: **Agent CI** — `.github/workflows/ci-agent.yml` compiles and
+ unit-tests `snitch-agent` on Linux, macOS and Windows targets on every
+ `agent/**` push; 6 unit tests cover hex decoding, table parsing,
+ attribution and JSON escaping.
+ FR: **CI agent** — `.github/workflows/ci-agent.yml` compile et teste
+ `snitch-agent` sur cibles Linux/macOS/Windows à chaque push
+ `agent/**` ; 6 tests unitaires.
+
+### Fixed / Corrigé
+
+- EN: the agent previously sent `Authorization: Bearer`, which the
+ ingest endpoint never read — it now sends `X-Snitch-Agent` (enrolled
+ `sagt_…`) or `X-Snitch-Token` (master) matching the actual auth path.
+ FR: l'agent envoyait `Authorization: Bearer`, jamais lu par l'endpoint
+ — il envoie désormais `X-Snitch-Agent` (`sagt_…` enrôlé) ou
+ `X-Snitch-Token` (maître) selon le vrai chemin d'auth.
+
## [1.6.1] — 2026-10-22 — enterprise follow-through / suite entreprise
### Added / Ajouté
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
index 9ed9235..778ddb9 100644
--- a/agent/Cargo.toml
+++ b/agent/Cargo.toml
@@ -5,7 +5,7 @@
# /proc en fs brut, le POST ingest en TcpStream manuel.
[package]
name = "snitch-agent"
-version = "1.6.1"
+version = "1.6.2"
edition = "2021"
license = "AGPL-3.0-only"
description = "Lightweight socket-observation agent for the Snitch collector"
diff --git a/agent/README.md b/agent/README.md
index 8124a8c..fa0e552 100644
--- a/agent/README.md
+++ b/agent/README.md
@@ -10,10 +10,14 @@ Scope, honestly:
- it observes **sockets**, it does not sniff packets — no payloads, no
SNI/DNS; the collector's own capture keeps those duties;
-- process attribution (`/proc/*/fd` walk) is a marked TODO in
- `src/main.rs`, not half-implemented;
-- transport is plain HTTP + bearer — same trust-domain model as
- `gossip_peers`; tunnel over WireGuard/TLS on hostile links.
+- process attribution works on Linux: socket inodes are mapped to
+ `pid`/`process` via a `/proc/*/fd` walk (`socket:[inode]` →
+ `/proc/<pid>/comm`), built only when the socket diff is non-empty.
+ 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.
**FR :** Un daemon Rust sans dépendance qui surveille la table de
sockets de l'hôte (`/proc/net/*`, Linux) et pousse les nouveaux flux
@@ -22,33 +26,52 @@ sortants vers `POST /ingest/events` du collecteur — contrat
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 en TODO explicite dans `src/main.rs`, transport
-HTTP + bearer (même modèle de confiance que `gossip_peers`).
+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.
-## Build & run / Compiler & lancer
+## Enroll & run / Enrôler & lancer
```bash
+# EN: mint a per-agent token on the collector (master token required)
+# FR: mint un jeton par agent sur le collecteur (jeton maître requis)
+curl -X POST http://collector:8000/ingest/enroll \
+ -H "X-Snitch-Token: <master token>" \
+ -H "Content-Type: application/json" \
+ -d '{"name": "agent-01"}' # → {"token": "sagt_…"} (shown once)
+
cargo build --release
SNITCH_SERVER="collector:8000" \
-SNITCH_TOKEN="<collector api token>" \
+SNITCH_TOKEN="sagt_…" \
SNITCH_HOST="agent-01" \
./target/release/snitch-agent
```
+`SNITCH_TOKEN` accepts either an enrolled `sagt_…` credential (sent as
+`X-Snitch-Agent`, the enrolled name is authoritative — the agent cannot
+spoof another) or the collector master token (sent as `X-Snitch-Token`).
+Revoke with `POST /ingest/revoke {"name": "agent-01"}`.
+
## systemd / service
`deploy/systemd/snitch-agent.service` runs it unprivileged — the agent
-only needs to read `/proc/net`, no capabilities at all.
+only needs to read `/proc/net` + `/proc/*/fd`, no capabilities at all.
+
+## CI
+
+`.github/workflows/ci-agent.yml` compiles and unit-tests on
+`x86_64-unknown-linux-gnu`, `x86_64-apple-darwin` and
+`x86_64-pc-windows-msvc` on every `agent/**` push.
## Wire format / format fil
```json
-POST /ingest/events Authorization: Bearer <token>
+POST /ingest/events X-Snitch-Agent: sagt_…
{"agent":"snitch-agent/1","host":"agent-01","events":[
{"ts":1718000000,"src_ip":"10.0.0.5","dst_ip":"93.184.216.34",
"src_port":51822,"dst_port":443,"proto":"tcp","direction":"out",
- "bytes":0,"process":"","pid":0,"sni":""}]}
+ "bytes":0,"process":"curl","pid":1337,"sni":""}]}
```
-`bytes`, `process`, `pid` are `0`/empty until the TODOs land — the
-collector still applies the full custom-rules surface to every event.
+`process`/`pid` are filled on Linux, `0`/empty elsewhere. The collector
+still applies the full custom-rules surface to every event.
diff --git a/agent/src/main.rs b/agent/src/main.rs
index 9a0fc94..a142773 100644
--- a/agent/src/main.rs
+++ b/agent/src/main.rs
@@ -42,6 +42,7 @@ struct Sock {
local: String, // "ip:port"
remote: String, // "ip:port" — empty when LISTEN/unconnected
state: u8,
+ inode: u64, // EN: socket inode → pid attribution key / FR: inode → clé d'attribution
}
fn hex_ip(h: &str, v6: bool) -> String {
@@ -74,13 +75,14 @@ fn hex_ip(h: &str, v6: bool) -> String {
a.to_string()
}
-fn parse_table(path: &str, proto: &str, v6: bool, out: &mut HashSet<Sock>) {
- // EN: One line: sl local rem st … — rem "00000000:0000" = unconnected.
- // FR: Une ligne : sl local rem st … — rem « 00000000:0000 » = non connecté.
- let Ok(text) = fs::read_to_string(path) else { return };
+fn parse_lines(text: &str, proto: &str, v6: bool, out: &mut HashSet<Sock>) {
+ // EN: One line: sl local rem st tx rx tr when retrnsmt uid timeout inode
+ // — rem "00000000:0000" = unconnected; f[9] = socket inode.
+ // FR: Une ligne : sl local rem st … — rem « 00000000:0000 » = non
+ // connecté ; f[9] = inode du socket.
for line in text.lines().skip(1) {
let f: Vec<&str> = line.split_whitespace().collect();
- if f.len() < 4 {
+ if f.len() < 10 {
continue;
}
let (lip, lport) = f[1].split_once(':').unwrap_or(("", "0"));
@@ -93,7 +95,14 @@ fn parse_table(path: &str, proto: &str, v6: bool, out: &mut HashSet<Sock>) {
let local = format!("{}:{}", hex_ip(lip, v6),
u16::from_str_radix(lport, 16).unwrap_or(0));
let remote = format!("{}:{}", hex_ip(rip, v6), port);
- out.insert(Sock { proto: proto.into(), local, remote, state });
+ out.insert(Sock { proto: proto.into(), local, remote, state,
+ inode: f[9].parse().unwrap_or(0) });
+ }
+}
+
+fn parse_table(path: &str, proto: &str, v6: bool, out: &mut HashSet<Sock>) {
+ if let Ok(text) = fs::read_to_string(path) {
+ parse_lines(&text, proto, v6, out);
}
}
@@ -124,15 +133,23 @@ 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. Bearer auth on every request.
- // FR: POST HTTP/1.1 minimal, pas de TLS — voir le doc module pour le
- // domaine de confiance. Bearer sur chaque requête.
+ // 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 ».
+ let auth = if token.starts_with("sagt_") {
+ format!("X-Snitch-Agent: {token}")
+ } else {
+ format!("X-Snitch-Token: {token}")
+ };
let body = format!(
"{{\"agent\":\"{}\",\"host\":\"{}\",\"events\":[{}]}}",
json_escape(AGENT_ID), json_escape(host), events.join(","));
let req = format!(
"POST /ingest/events HTTP/1.1\r\nHost: {server}\r\n\
- Authorization: Bearer {token}\r\nContent-Type: application/json\r\n\
+ {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)
@@ -149,7 +166,41 @@ fn post_batch(server: &str, token: &str, host: &str,
}
}
-fn sock_to_event(s: &Sock) -> Option<String> {
+/// EN: socket inode → (pid, process name), built by walking
+/// /proc/<pid>/fd symlink targets "socket:[inode]" — the same
+/// technique netstat/ss use, pure std, Linux-only. Built lazily:
+/// only when a diff produced new sockets to attribute.
+/// FR: inode de socket → (pid, nom du processus), construit en lisant
+/// les liens /proc/<pid>/fd « socket:[inode] » — même technique que
+/// netstat/ss, std pur, Linux seulement. Construit à la demande.
+fn inode_pid_map() -> std::collections::HashMap<u64, (u32, String)> {
+ let mut m = std::collections::HashMap::new();
+ let Ok(procs) = fs::read_dir("/proc") else { return m };
+ for entry in procs.flatten() {
+ let name = entry.file_name();
+ let Ok(pid) = name.to_string_lossy().parse::<u32>() else { continue };
+ let Ok(fds) = fs::read_dir(entry.path().join("fd")) else { continue };
+ let comm = || -> String {
+ fs::read_to_string(format!("/proc/{pid}/comm"))
+ .unwrap_or_default().trim().to_string()
+ };
+ for fd in fds.flatten() {
+ let Ok(target) = fs::read_link(fd.path()) else { continue };
+ let t = target.to_string_lossy();
+ if let Some(inner) = t.strip_prefix("socket:[")
+ .and_then(|s| s.strip_suffix(']')) {
+ if let Ok(ino) = inner.parse::<u64>() {
+ m.entry(ino).or_insert_with(|| (pid, comm()));
+ }
+ }
+ }
+ }
+ m
+}
+
+fn sock_to_event(s: &Sock,
+ pids: &std::collections::HashMap<u64, (u32, String)>)
+ -> Option<String> {
// EN: only flow-like rows — a REMOTE endpoint with a real port.
// Direction is "out": the agent reports what the box reaches,
// which is the threat surface Snitch models.
@@ -161,13 +212,17 @@ fn sock_to_event(s: &Sock) -> Option<String> {
if rip.is_empty() || rip == "0.0.0.0" || rip == "::" || rport == "0" {
return None;
}
+ let (pid, pname) = pids.get(&s.inode)
+ .map(|(p, n)| (*p, n.clone()))
+ .unwrap_or((0, String::new()));
let ts = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
Some(format!(
"{{\"ts\":{ts},\"src_ip\":\"{}\",\"dst_ip\":\"{}\",\
\"src_port\":{},\"dst_port\":{},\"proto\":\"{}\",\
- \"direction\":\"out\",\"bytes\":0}}",
+ \"direction\":\"out\",\"bytes\":0,\"process\":\"{}\",\"pid\":{}}}",
json_escape(lip), json_escape(rip),
- lport, rport, json_escape(&s.proto)))
+ lport, rport, json_escape(&s.proto),
+ json_escape(&pname), pid))
}
fn main() {
@@ -182,18 +237,23 @@ fn main() {
let interval: u64 = env::var("SNITCH_INTERVAL_SECS")
.ok().and_then(|v| v.parse().ok()).unwrap_or(5).max(1);
- // TODO(pid-attr): walk /proc/<pid>/fd symlinks to map socket inodes
- // → process name/pid, then fill the `process`/`pid` event fields.
- // Kept out on purpose until it is exact, not approximate.
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");
loop {
let now = socket_table();
- for s in now.difference(&seen) {
- if let Some(ev) = sock_to_event(s) {
- pending.push(ev);
+ // EN: build the inode→pid map ONLY when the diff is non-empty —
+ // the /proc fd walk is O(all fds) and pointless otherwise.
+ // FR: ne construire la map inode→pid QUE si le diff n'est pas
+ // vide — le parcours /proc/fd coûte O(tous les fds).
+ let new: Vec<&Sock> = now.difference(&seen).collect();
+ if !new.is_empty() {
+ let pids = inode_pid_map();
+ for s in new {
+ if let Some(ev) = sock_to_event(s, &pids) {
+ pending.push(ev);
+ }
}
}
// EN: forget departed sockets so reconnecting flaps re-report —
@@ -218,3 +278,62 @@ fn main() {
std::thread::sleep(Duration::from_secs(interval));
}
}
+
+// ── unit tests / tests unitaires ────────────────────────────────────────────
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hex_ip_v4_is_little_endian() {
+ // EN: 0100007F stored LE → 127.0.0.1 / FR: LE → 127.0.0.1
+ assert_eq!(hex_ip("0100007F", false), "127.0.0.1");
+ assert_eq!(hex_ip("0A010203", false), "3.2.1.10");
+ }
+
+ #[test]
+ fn hex_ip_v6_groups_swapped() {
+ // EN: ::1 is "00000000000000000000000001000000" in /proc — the last
+ // u32 group holds 1 in LE. / FR: ::1 vaut « …01000000 » en
+ // /proc — le dernier groupe u32 porte 1 en LE.
+ assert_eq!(hex_ip("00000000000000000000000001000000", true), "::1");
+ assert_eq!(hex_ip("bad", true), "");
+ }
+
+ #[test]
+ fn parse_lines_extracts_flows_and_inodes() {
+ let table = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n\
+ 0: 0100007F:C000 0A010203:01BB 01 00000000:00000000 00:00000000 00000000 1000 0 12345\n\
+ 1: 0100007F:0035 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 99999\n";
+ let mut s = HashSet::new();
+ parse_lines(table, "tcp", false, &mut s);
+ assert_eq!(s.len(), 1); // EN: LISTEN row dropped / FR: ligne LISTEN ignorée
+ let sock = s.iter().next().unwrap();
+ assert_eq!(sock.inode, 12345);
+ assert_eq!(sock.remote, "3.2.1.10:443"); // EN: LE decode / FR: décodage LE
+ assert_eq!(sock.local, "127.0.0.1:49152");
+ }
+
+ #[test]
+ fn event_includes_process_attribution() {
+ let mut pids = std::collections::HashMap::new();
+ pids.insert(42u64, (1337u32, "evil".to_string()));
+ let s = Sock { proto: "tcp".into(), local: "10.0.0.5:5".into(),
+ remote: "8.8.8.8:53".into(), state: 1, inode: 42 };
+ let ev = sock_to_event(&s, &pids).unwrap();
+ assert!(ev.contains("\"process\":\"evil\"") && ev.contains("\"pid\":1337"));
+ assert!(ev.contains("\"dst_ip\":\"8.8.8.8\""));
+ }
+
+ #[test]
+ fn event_skips_unconnected() {
+ let s = Sock { proto: "udp".into(), local: "0.0.0.0:53".into(),
+ remote: "0.0.0.0:0".into(), state: 7, inode: 1 };
+ assert!(sock_to_event(&s, &Default::default()).is_none());
+ }
+
+ #[test]
+ fn json_escapes_quotes_and_control() {
+ assert_eq!(json_escape("a\"b\\c\nd"), "a\\\"b\\\\c\\u000ad");
+ }
+}
diff --git a/backend/api/main.py b/backend/api/main.py
index 0b084bc..4912609 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -58,12 +58,14 @@ FR: Cœur du backend. Détenir l'état du graphe en mémoire (nœuds / arêtes /
"""
import asyncio
+import hashlib
import math
import ipaddress
import json
import logging
import os
import queue
+import secrets
import socket
import subprocess
import sys
@@ -74,7 +76,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
-from fastapi import Depends, FastAPI, HTTPException, WebSocket, WebSocketDisconnect
+from fastapi import Depends, FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse
from fastapi.staticfiles import StaticFiles
@@ -1504,6 +1506,87 @@ async def _gossip_loop() -> None:
logger.warning("ioc peer sync failed: %s", exc)
+_FEED_TICK_S = 300 # EN: check feeds every 5 min / FR: vérif toutes les 5 min
+
+
+async def _feed_loop() -> None:
+ """EN: Scheduled threat-feed refresh — opt-in per feed. Setting
+ `ti_feeds` is a list of {url|path, kind: "ip"|"domain",
+ action: "block"|"sinkhole", hours: N}; each entry is fetched when
+ its own `hours` interval elapsed (`ti_feeds_state` persists last
+ fetch), parsed through the SAME importer as /firewall/blocklist
+ (dedupe + caps), and the firewall reloads hot — no restart.
+ Remote urls are the documented opt-in fetch path; `path:` feeds
+ stay fully offline. Bounded: ≤64 feeds.
+ FR: Rafraîchissement planifié des flux TI — opt-in par flux. Le
+ réglage `ti_feeds` = liste de {url|path, kind, action, hours} ;
+ chaque entrée est fetchée quand son intervalle a expiré
+ (`ti_feeds_state` persiste le dernier fetch), parsée par le MÊME
+ importeur que /firewall/blocklist, et le pare-feu recharge à
+ chaud. Les url distantes suivent le chemin opt-in documenté ;
+ `path:` reste hors-ligne. Borné à 64 flux."""
+ while not _shutdown:
+ await asyncio.sleep(_FEED_TICK_S)
+ if _shutdown:
+ break
+ try:
+ feeds = db.get_setting("ti_feeds", []) or []
+ if not isinstance(feeds, list) or not feeds:
+ continue
+ state: dict = db.get_setting("ti_feeds_state", {}) or {}
+ loop = asyncio.get_running_loop()
+ changed = False
+ now = time.time()
+ for feed in feeds[:64]:
+ if not isinstance(feed, dict):
+ continue
+ url = str(feed.get("url") or "").strip()
+ path = str(feed.get("path") or "").strip()
+ kind = feed.get("kind") if feed.get("kind") in \
+ ("ip", "domain") else "domain"
+ action = feed.get("action") if feed.get("action") in \
+ ("block", "sinkhole") else "block"
+ try:
+ hours = max(1, min(int(feed.get("hours", 24)), 24 * 30))
+ except (TypeError, ValueError):
+ hours = 24
+ key = url or path
+ if not key:
+ continue
+ if now - float(state.get(key, 0)) < hours * 3600:
+ continue
+ try:
+ if url:
+ text = await loop.run_in_executor(
+ None, blocklist.fetch_url, url)
+ else:
+ p = Path(path).expanduser()
+ if not p.is_file() or \
+ p.stat().st_size > 4 * 1024 * 1024:
+ raise ValueError("feed file missing/too large")
+ text = await loop.run_in_executor(
+ None, p.read_text)
+ added, skipped, parsed, truncated = \
+ await loop.run_in_executor(
+ None, _import_blocklist_text, text,
+ kind, action, 5000)
+ state[key] = now
+ changed = True
+ logger.info("ti feed %s: +%d rules (%d parsed%s)",
+ key, added, parsed,
+ ", truncated" if truncated else "")
+ except Exception as e: # noqa: BLE001
+ logger.warning("ti feed %s failed: %s", key, e)
+ if changed:
+ rules, _lk = fw.serialized()
+ db.set_setting("firewall_rules", rules)
+ db.set_setting("ti_feeds_state", state)
+ await broadcast({"type": "firewall", "rules": rules,
+ "lockdown": _lk})
+ except Exception as exc: # noqa: BLE001
+ logger.warning("feed refresh failed: %s", exc)
+
+
async def _miner_corroborate() -> None:
"""EN: Sample CPU for pool-port suspects off the event loop; each
corroborated case becomes a MINING_SUSPECT alert.
@@ -1952,6 +2035,7 @@ async def _startup() -> None:
_start_capture()
asyncio.get_running_loop().create_task(_drain_loop())
asyncio.get_running_loop().create_task(_gossip_loop())
+ asyncio.get_running_loop().create_task(_feed_loop())
threading.Thread(target=_flush_loop, daemon=True).start()
threading.Thread(target=_cleanup_loop, daemon=True).start()
@@ -2867,32 +2951,41 @@ async def firewall_blocklist(body: BlocklistBody) -> dict:
# IPs for feed-style lists (private/reserved never imported).
# FR: `kind` choisit l'extracteur — domaines pour les listes façon
# hosts, IP pour les flux (privées/réservées jamais importées).
- parse = blocklist.parse_ips if body.kind == "ip" \
- else blocklist.parse_domains
- entries = parse(text)
- cap = blocklist.clamp_max(body.max_entries)
- truncated = len(entries) > cap
- entries = entries[:cap]
-
- def _apply() -> tuple[int, int]:
- added = skipped = 0
- for d in entries:
- if fw._find_rule(body.kind, d, body.action):
- skipped += 1
- continue
- fw.add_rule(body.kind, d, body.action)
- added += 1
- return added, skipped
-
- added, skipped = await loop.run_in_executor(None, _apply)
+ added, skipped, parsed, truncated = await loop.run_in_executor(
+ None, _import_blocklist_text, text, body.kind, body.action,
+ body.max_entries)
rules, lockdown = fw.serialized()
db.set_setting("firewall_rules", rules)
await broadcast({"type": "firewall", "rules": rules, "lockdown": lockdown})
return {"ok": True, "remote_fetch": remote, "kind": body.kind,
- "parsed": len(entries),
+ "parsed": parsed,
"added": added, "skipped": skipped, "truncated": truncated}
+def _import_blocklist_text(text: str, kind: str, action: str,
+ max_entries: int) -> tuple[int, int, int, bool]:
+ """EN: Shared blocklist import — parse (kind), cap, dedupe against
+ existing rules, apply to the firewall orchestrator. Blocking helper:
+ callers run it in an executor. Returns (added, skipped, parsed,
+ truncated). / FR: Import blocklist partagé — parse (kind), borne,
+ déduplique contre les règles existantes, applique à l'orchestrateur.
+ Bloquant : à lancer en executor. Renvoie (added, skipped, parsed,
+ truncated)."""
+ parse = blocklist.parse_ips if kind == "ip" else blocklist.parse_domains
+ entries = parse(text)
+ cap = blocklist.clamp_max(max_entries)
+ truncated = len(entries) > cap
+ entries = entries[:cap]
+ added = skipped = 0
+ for d in entries:
+ if fw._find_rule(kind, d, action):
+ skipped += 1
+ continue
+ fw.add_rule(kind, d, action)
+ added += 1
+ return added, skipped, len(entries), truncated
+
+
# ── Custom alert rules / Règles d'alerte utilisateur ─────────────────────────
@app.get("/alerts/rules", dependencies=_AUTH)
@@ -3261,6 +3354,86 @@ _MAX_AGENT_EVENTS = 1000 # EN: per request / FR: par requête
_MAX_AGENT_FIELD = 253 # EN: chars per string field / FR: caractères
+def _agent_store() -> dict:
+ """EN: token-sha256 → {"name": agent_id, "created": ts}. Only the
+ HASH is persisted — a leaked settings dump can't replay tokens.
+ FR: sha256(jeton) → {"name": agent_id, "created": ts}. Seul le HASH
+ est persisté — un dump de settings fuité ne peut pas rejouer les jetons."""
+ return db.get_setting("agent_tokens", {}) or {}
+
+
+def _agent_lookup(token: str) -> Optional[str]:
+ if not token:
+ return None
+ h = hashlib.sha256(token.encode()).hexdigest()
+ ent = _agent_store().get(h)
+ return ent.get("name") if ent else None
+
+
+async def agent_or_master(request: Request) -> str:
+ """EN: Ingest auth — the master token always works (single-box or
+ admin pushes); `X-Snitch-Agent: <enrolled-token>` resolves to the
+ enrolled agent's name, which is then authoritative for event tagging
+ (the body's `host` field stays a hint only). 401 otherwise.
+ FR: Auth ingest — le jeton maître marche toujours ; `X-Snitch-Agent`
+ résout le nom de l'agent enrôlé, qui fait foi pour le tagging
+ (le `host` du corps reste un indice). 401 sinon."""
+ from api.security import _extract_token, API_TOKEN
+ master = _extract_token(request)
+ if master and secrets.compare_digest(master, API_TOKEN):
+ return ""
+ agent_tok = request.headers.get("x-snitch-agent", "")
+ name = _agent_lookup(agent_tok)
+ if name:
+ return name
+ raise HTTPException(401, "enrolled agent token or master token required")
+
+
[email protected]("/ingest/enroll", dependencies=_AUTH)
+async def ingest_enroll(body: dict) -> dict:
+ """EN: Enroll a remote agent — mint a per-agent bearer token
+ (`sagt_…`, returned ONCE, stored hashed). The agent then sends it
+ as `X-Snitch-Agent` on /ingest/events; revocation = deleting the
+ hash. Enrolling requires the MASTER token.
+ FR: Enrôler un agent — mint un jeton bearer dédié (`sagt_…`, rendu
+ UNE fois, stocké hashé). L'agent l'envoie en `X-Snitch-Agent`
+ sur /ingest/events ; révocation = suppression du hash. L'enrôlement
+ exige le jeton MAÎTRE."""
+ name = str((body or {}).get("name", "")).strip()[:80]
+ if not name:
+ raise HTTPException(400, "agent name required")
+ store = _agent_store()
+ if any(e.get("name") == name for e in store.values()):
+ raise HTTPException(409, "agent name already enrolled")
+ if len(store) >= 4096:
+ raise HTTPException(400, "agent limit reached")
+ token = "sagt_" + secrets.token_hex(24)
+ store[hashlib.sha256(token.encode()).hexdigest()] = {
+ "name": name, "created": time.time()}
+ db.set_setting("agent_tokens", store)
+ return {"ok": True, "agent": name, "token": token}
+
+
[email protected]("/ingest/agents", dependencies=_AUTH)
+async def ingest_agents() -> dict:
+ """EN: Enrolled agent names (tokens never leave the store).
+ FR: Noms des agents enrôlés (les jetons ne quittent jamais le store)."""
+ return {"agents": sorted(e.get("name", "?")
+ for e in _agent_store().values())}
+
+
[email protected]("/ingest/revoke", dependencies=_AUTH)
+async def ingest_revoke(body: dict) -> dict:
+ """EN: Revoke an enrolled agent by name — the token dies with its hash.
+ FR: Révoquer un agent par nom — le jeton meurt avec son hash."""
+ name = str((body or {}).get("name", "")).strip()
+ store = _agent_store()
+ store = {h: e for h, e in store.items() if e.get("name") != name}
+ db.set_setting("agent_tokens", store)
+ return {"ok": True, "agents": sorted(e.get("name", "?")
+ for e in store.values())}
+
+
class AgentBatchBody(BaseModel):
"""EN: POST /ingest/events envelope — the documented contract a
lightweight agent (Rust daemon, scripted /proc reader, forwarder)
@@ -3280,8 +3453,9 @@ class AgentBatchBody(BaseModel):
events: list = []
[email protected]("/ingest/events", dependencies=_AUTH)
-async def ingest_events(body: AgentBatchBody) -> dict:
[email protected]("/ingest/events")
+async def ingest_events(body: AgentBatchBody,
+ agent_name: str = Depends(agent_or_master)) -> dict:
"""EN: Ingest normalized flow events from remote agents.
Contract `snitch-agent/1` — each event: {src_ip, dst_ip,
@@ -3293,14 +3467,18 @@ async def ingest_events(body: AgentBatchBody) -> dict:
bytes accumulate into host/process history under
`agent:<host>:<ip>`/`agent:<host>:<process>`. Unknown fields are
ignored; nothing here trusts the agent beyond the bearer token.
+
+ Auth: master `X-Snitch-Token` (host name taken from the body) or
+ an enrolled `X-Snitch-Agent` token (enrolled name is
+ authoritative — a compromised agent can't spoof another).
FR: Ingérer des événements de flux normalisés d'agents distants.
- Contrat `snitch-agent/1`. Événements validés et bornés puis
- injectés dans la MÊME machinerie de détection que les paquets
- locaux : règles custom → CUSTOM_RULE (préfixé par l'hôte agent)
- et historique sous `agent:<hôte>:…`. Champs inconnus ignorés.
+ Auth : `X-Snitch-Token` maître (nom du corps) ou `X-Snitch-Agent`
+ enrôlé (le nom enrôlé fait foi — un agent compromis ne peut pas
+ usurper un autre).
"""
events = body.events[:_MAX_AGENT_EVENTS]
- host = str(body.host or "agent")[:_MAX_AGENT_FIELD] or "agent"
+ host = (agent_name or
+ str(body.host or "agent")[:_MAX_AGENT_FIELD] or "agent")
accepted = alerts = 0
minute = db._utcnow_minute()
@@ -3358,6 +3536,7 @@ async def ingest_events(body: AgentBatchBody) -> dict:
asyncio.get_running_loop().create_task(_notify(ad))
alerts += 1
return {"ok": True, "agent": body.agent or "unknown",
+ "host": host,
"received": len(body.events), "accepted": accepted,
"alerts": alerts,
"truncated": len(body.events) > _MAX_AGENT_EVENTS}
diff --git a/backend/tests/test_enterprise.py b/backend/tests/test_enterprise.py
index f664a38..eec48c1 100644
--- a/backend/tests/test_enterprise.py
+++ b/backend/tests/test_enterprise.py
@@ -300,3 +300,61 @@ def test_ingest_events_bounded_and_validated():
body = r.json()
assert body["accepted"] == 1 # EN: only the valid one / FR: seul le valide
assert body["received"] == 3
+
+
+def test_ingest_enroll_and_agent_token():
+ # EN: Master enrolls an agent → returns a one-shot sagt_ token; the
+ # agent then ingests with X-Snitch-Agent and its enrolled name is
+ # authoritative. Revoking removes the token hash → 401 again.
+ # FR: Le maître enrôle un agent → jeton sagt_ one-shot ; l'agent ingère
+ # ensuite avec X-Snitch-Agent et son nom enrôlé fait foi. La
+ # révocation supprime le hash → 401.
+ import pytest
+ pytest.importorskip("httpx")
+ from fastapi.testclient import TestClient
+ from api.main import app
+ from api.security import API_TOKEN
+ c = TestClient(app)
+ auth = {"X-Snitch-Token": API_TOKEN}
+
+ # EN: enroll requires the master token / FR: enrôlement = jeton maître
+ assert c.post("/ingest/enroll", json={"name": "edge-1"}).status_code in (401, 403)
+ r = c.post("/ingest/enroll", headers=auth, json={"name": "edge-1"})
+ assert r.status_code == 200
+ tok = r.json()["token"]
+ assert tok.startswith("sagt_")
+
+ # EN: duplicate name rejected / FR: nom dupliqué rejeté
+ assert c.post("/ingest/enroll", headers=auth,
+ json={"name": "edge-1"}).status_code == 409
+
+ # EN: agent token ingests, master-free / FR: le jeton agent ingère sans maître
+ r = c.post("/ingest/events", headers={"X-Snitch-Agent": tok},
+ json={"agent": "snitch-agent/1", "host": "spoofed",
+ "events": [{"dst_ip": "8.8.8.8", "dst_port": 443,
+ "proto": "tcp"}]})
+ # EN: enrolled name is authoritative, not the body's claimed host
+ # FR: le nom enrôlé fait foi, pas le host déclaré dans le corps
+ assert r.status_code == 200 and r.json()["host"] == "edge-1"
+
+ # EN: list + revoke / FR: liste + révocation
+ assert "edge-1" in c.get("/ingest/agents", headers=auth).json()["agents"]
+ c.post("/ingest/revoke", headers=auth, json={"name": "edge-1"})
+ r = c.post("/ingest/events", headers={"X-Snitch-Agent": tok},
+ json={"events": []})
+ assert r.status_code in (401, 403)
+
+
+def test_feeds_setting_bounded():
+ # EN: ti_feeds is a plain setting — the loop only reads it; verify a
+ # path-feed import works end-to-end through the shared importer.
+ # FR: ti_feeds est un réglage simple — la boucle ne fait que le lire ;
+ # on vérifie l'import de flux `path:` de bout en bout via
+ # l'importeur partagé.
+ import pytest
+ pytest.importorskip("httpx")
+ from api.main import _import_blocklist_text
+ added, skipped, parsed, truncated = _import_blocklist_text(
+ "8.8.8.8\n# comment\n1.1.1.1\n10.0.0.1\n", "ip", "block", 5000)
+ assert parsed == 2 # EN: private IP filtered / FR: IP privée filtrée
+ assert added >= 0 and not truncated
diff --git a/backend/tests/test_v15_features.py b/backend/tests/test_v15_features.py
index dc99113..428c8d3 100644
--- a/backend/tests/test_v15_features.py
+++ b/backend/tests/test_v15_features.py
@@ -311,7 +311,13 @@ def test_flow_ml_inert_then_scores():
sous le minimum d'entraînement, puis émet pour un flux extrême."""
from detection.mlflow import FlowAnomaly, _TRAIN_MIN
m = FlowAnomaly()
- t = time.time()
+ # EN: 2024-01-01 12:00 UTC — the learned "hour" feature is 12/23 ≈ 0.52,
+ # matching the hard-coded normal vector below. A live clock made the
+ # test pass only when run near noon UTC — flaky-by-clock, fixed.
+ # FR: 01/01/2024 12:00 UTC — la feature « heure » apprise vaut 12/23
+ # ≈ 0,52, comme le vecteur « normal » ci-dessous. L'horloge réelle
+ # ne faisait passer le test que vers midi UTC — flaky, corrigé.
+ t = 1_704_110_400
# EN: Learn a realistic baseline — a small stable set of destinations
# (intervals + fanout stay meaningful), boring web ports/sizes.
# FR: Baseline réaliste — petit ensemble stable de destinations
diff --git a/backend/version.py b/backend/version.py
index 70d36ba..91d1632 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.1"
+__version__ = "1.6.2"
diff --git a/deploy/helm/snitch/Chart.yaml b/deploy/helm/snitch/Chart.yaml
index b635fa2..78b6e7a 100644
--- a/deploy/helm/snitch/Chart.yaml
+++ b/deploy/helm/snitch/Chart.yaml
@@ -6,7 +6,7 @@ description: |
(/remote/fleet over gossip_peers) or a per-node agent.
type: application
version: 0.1.0
-appVersion: "1.6.1"
+appVersion: "1.6.2"
home: https://github.com/aixisstudio/Snitch
keywords:
- security
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index 7a18c8b..528fc35 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -142,10 +142,34 @@ Sigma→YARA-L path is covered transitively.
`agent/` ships a zero-dependency Rust daemon (~1 MB single binary) that
watches the host socket table (`/proc/net/*`, Linux) and pushes newly
observed outbound flows to `POST /ingest/events`. It observes sockets —
-no payloads/SNI (that's the local capture's job); process attribution is
-a marked TODO. Transport: HTTP + bearer token, same trust-domain model
-as `gossip_peers`. A `snitch-agent.service` unit lives in
-`deploy/systemd/`.
+no payloads/SNI (that's the local capture's job); `pid`/`process`
+attribution works on Linux via the `/proc/*/fd` inode walk and reports
+`0` elsewhere until the Windows/macOS backends land. Transport: HTTP,
+same trust-domain model as `gossip_peers`. A `snitch-agent.service`
+unit lives in `deploy/systemd/`; CI compiles and tests the binary on
+Linux, macOS and Windows on every `agent/**` push.
+
+### Per-agent enrollment
+
+Each deployed agent should carry its OWN credential — a stolen token
+can only impersonate that one agent, and revocation is per-name:
+
+```bash
+# EN: mint on the collector (master token), returned once
+curl -X POST http://collector:8000/ingest/enroll \
+ -H "X-Snitch-Token: <master>" -d '{"name": "edge-01"}'
+# → {"token": "sagt_…"} — put it in the agent's SNITCH_TOKEN
+
+curl -X POST http://collector:8000/ingest/revoke \
+ -H "X-Snitch-Token: <master>" -d '{"name": "edge-01"}'
+
+curl http://collector:8000/ingest/agents -H "X-Snitch-Token: <master>"
+```
+
+The ingest endpoint accepts `X-Snitch-Agent: sagt_…` (enrolled name is
+authoritative — the body's `host` field can't override it) or the
+master `X-Snitch-Token` for local/small deployments. Only token hashes
+are stored, so a leaked settings dump can't replay credentials.
## 10. Threat-intel feeds (free)
@@ -163,6 +187,26 @@ audited opt-in fetch (`remote_fetch: true` in the response). Cap at
Opt-in API providers (AbuseIPDB / OTX / VirusTotal) stay available via
`ti_provider` + `ti_api_key` — nothing calls out until you set a key.
+### Scheduled refresh (`ti_feeds`)
+
+A background worker re-imports feeds on their own clock — no restart,
+hot firewall reload. Configure it declaratively:
+
+```toml
+ti_feeds = [
+ { url = "https://lists.blocklist.de/lists/all.txt",
+ kind = "ip", action = "block", hours = 24 },
+ { path = "/etc/snitch/corp-domains.txt",
+ kind = "domain", action = "sinkhole", hours = 6 },
+]
+```
+
+Each entry runs through the same importer as `POST
+/firewall/blocklist` — dedupe against existing rules, `path:` stays
+fully offline, `url:` is the same audited opt-in. Last-fetch state
+persists across restarts (`ti_feeds_state`); ≤64 feeds, ≤5000 rules
+per refresh — giant feeds belong in a resolver, not here.
+
## 11. Headless / daemon mode
The GUI is optional: the backend is the whole product. Run it bare
diff --git a/electron/package.json b/electron/package.json
index 1d342aa..eca295d 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch",
- "version": "1.6.1",
+ "version": "1.6.2",
"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 5ac6a0f..d6241ff 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch-frontend",
- "version": "1.6.1",
+ "version": "1.6.2",
"private": true,
"license": "AGPL-3.0-or-later",
"description": "Snitch UI \u2014 React + D3.js / Interface React + D3.js",
diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml
index a385db9..579baa4 100644
--- a/packaging/nfpm.yaml
+++ b/packaging/nfpm.yaml
@@ -10,7 +10,7 @@
name: snitch
arch: amd64
platform: linux
-version: "1.6.1"
+version: "1.6.2"
release: 1
section: net
priority: optional
diff --git a/packaging/snitch.toml.example b/packaging/snitch.toml.example
index e75856b..746e4ef 100644
--- a/packaging/snitch.toml.example
+++ b/packaging/snitch.toml.example
@@ -23,3 +23,16 @@ upload_threshold_mb = 500
# EN: Monitored ports (empty = all). / FR: Ports surveillés (vide = tous).
# ports = [80, 443]
+
+# EN: Scheduled threat feeds — refreshed every `hours` per feed, hot-reloaded
+# into the firewall. Remote urls are an explicit opt-in; path: feeds are
+# fully offline. kind: "ip"|"domain", action: "block"|"sinkhole".
+# FR: Flux TI planifiés — rafraîchis toutes les `hours`, rechargés à chaud
+# dans le pare-feu. Les url distantes = opt-in explicite ; `path:` reste
+# hors-ligne. kind : « ip »|« domain », action : « block »|« sinkhole ».
+# ti_feeds = [
+# { url = "https://lists.blocklist.de/lists/all.txt", kind = "ip",
+# action = "block", hours = 24 },
+# { path = "/etc/snitch/corp-domains.txt", kind = "domain",
+# action = "sinkhole", hours = 6 },
+# ]