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.

Hardening pass: batched alert writes, IP refresh, SHA-pinned CI

MoneyLisab926d4645aba
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2add9d8..66eb3e8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -31,8 +31,8 @@ jobs:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-python@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
with:
python-version: '3.11'
- name: Install dependencies
@@ -46,8 +46,8 @@ jobs:
frontend:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-node@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '20'
- name: Install + test + build
@@ -69,11 +69,11 @@ jobs:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-python@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
with:
python-version: '3.11'
- - uses: actions/setup-node@v7
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '20'
- name: Build frontend
@@ -103,7 +103,7 @@ jobs:
cd dist/backend
tar czf snitch-backend-${{ matrix.os }}.tar.gz snitch-backend
sha256sum snitch-backend-${{ matrix.os }}.tar.gz > snitch-backend-${{ matrix.os }}.sha256
- - uses: actions/upload-artifact@v7
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: snitch-backend-${{ matrix.os }}
path: dist/backend/*.tar.gz*
@@ -165,7 +165,7 @@ jobs:
# les dossiers unpacked et les blockmaps gonflent les artefacts à
# ~900 Mo et cassent le téléchargement de la release.
- name: Upload app installers
- uses: actions/upload-artifact@v7
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
if: always()
with:
name: snitch-app-${{ matrix.os }}
@@ -216,16 +216,16 @@ jobs:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v7
- - uses: docker/setup-buildx-action@v3
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Login to GHCR
- uses: docker/login-action@v3
+ uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build + push image
- uses: docker/build-push-action@v6
+ uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: .
push: true
@@ -248,7 +248,7 @@ jobs:
permissions:
contents: write
steps:
- - uses: actions/download-artifact@v7
+ - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
with:
path: artifacts
pattern: snitch-*
diff --git a/Dockerfile b/Dockerfile
index bcc40c9..ecb773f 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -33,6 +33,12 @@ COPY backend/ ./backend/
# FR: Application React compilée — servie en fichiers statiques par FastAPI.
COPY --from=frontend-builder /build/dist ./frontend_dist/
+# EN: No USER directive — the container intentionally runs as root because
+# libpcap needs CAP_NET_RAW/CAP_NET_ADMIN to capture. Compose grants only
+# those two caps; do NOT add a USER here or capture silently stops.
+# FR: Pas de directive USER — le conteneur tourne volontairement en root car
+# libpcap exige CAP_NET_RAW/CAP_NET_ADMIN pour capturer. Compose n'accorde
+# que ces deux capacités ; ne PAS ajouter de USER, la capture s'arrêterait.
EXPOSE 8000
WORKDIR /app/backend
CMD ["python", "run_backend.py"]
diff --git a/PRIVACY.md b/PRIVACY.md
index be9c7ad..16f45ae 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -12,7 +12,8 @@ update checks, no phone-home of any kind.
- captures packets on your local interfaces (passive observation),
- reads your system ARP/neighbour table (no active scanning),
- resolves reverse DNS via your OS resolver — standard PTR lookups that
- already happen implicitly with any network activity,
+ already happen implicitly with any network activity (set
+ `SNITCH_DISABLE_PTR=1` to disable them entirely),
- serves a web UI on `127.0.0.1` for your own browser.
**Geolocation is offline-only.** If you place a DB-IP Lite or MaxMind
@@ -48,7 +49,8 @@ vérification de mise à jour, aucun appel sortant.
- capturer les paquets sur vos interfaces locales (observation passive),
- lire la table ARP/voisinage système (pas de scan actif),
- résoudre le DNS inverse via le résolveur de votre OS — des requêtes PTR
- standard qui ont déjà lieu implicitement avec toute activité réseau,
+ standard qui ont déjà lieu implicitement avec toute activité réseau
+ (`SNITCH_DISABLE_PTR=1` pour les désactiver complètement),
- servir une UI web sur `127.0.0.1` pour votre propre navigateur.
**La géolocalisation est 100 % hors ligne.** Si vous placez un fichier
diff --git a/backend/api/main.py b/backend/api/main.py
index 2df00b7..0e0df91 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -1273,12 +1273,28 @@ async def set_ip_whitelist(body: WhitelistBody) -> dict:
await broadcast({"type": "nodes_removed", "ids": removed_ids})
return {"whitelisted_ips": sorted(_whitelisted_ips)}
+# EN: Upper bound for `minutes` query params — a week. Prevents absurd
+# values (minutes=1e9) from scanning the whole history table; the
+# retention cleanup makes anything older empty anyway.
+# FR: Borne haute pour le paramètre `minutes` — une semaine. Empêche des
+# valeurs absurdes (minutes=1e9) de scanner toute la table d'historique ;
+# le nettoyage par rétention vide de toute façon tout ce qui est plus vieux.
+MAX_HISTORY_MINUTES = 7 * 24 * 60
+
+
+def _clamp_minutes(minutes: int) -> int:
+ """EN: Clamp a client-supplied lookback window to [1, one week].
+ FR: Borner une fenêtre d'historique fournie par le client à [1, 1 semaine]."""
+ return max(1, min(int(minutes), MAX_HISTORY_MINUTES))
+
+
@app.get("/timeline", dependencies=_AUTH)
async def get_timeline(minutes: int = 60) -> dict:
"""EN: Per-minute aggregates for the timeline chart.
FR: Agrégats par minute pour le graphique timeline."""
loop = asyncio.get_running_loop()
- data = await loop.run_in_executor(None, db.get_timeline, minutes)
+ data = await loop.run_in_executor(
+ None, db.get_timeline, _clamp_minutes(minutes))
return {"timeline": data}
@@ -1358,7 +1374,7 @@ async def get_host_history(ip: str, minutes: int = 60) -> dict:
"""EN: Per-host byte/packet history. / FR: Historique par hôte."""
loop = asyncio.get_running_loop()
return {"history": await loop.run_in_executor(
- None, db.get_history, "host", ip, minutes)}
+ None, db.get_history, "host", ip, _clamp_minutes(minutes))}
@app.get("/history/process/{name}", dependencies=_AUTH)
@@ -1366,7 +1382,7 @@ async def get_process_history(name: str, minutes: int = 60) -> dict:
"""EN: Per-process byte/packet history. / FR: Historique par processus."""
loop = asyncio.get_running_loop()
return {"history": await loop.run_in_executor(
- None, db.get_history, "process", name, minutes)}
+ None, db.get_history, "process", name, _clamp_minutes(minutes))}
@app.get("/history/top_processes", dependencies=_AUTH)
@@ -1375,7 +1391,7 @@ async def get_top_processes(minutes: int = 60) -> dict:
FR: Plus gros émetteurs par processus — la source de la vue Apps."""
loop = asyncio.get_running_loop()
return {"processes": await loop.run_in_executor(
- None, db.get_top_processes, minutes)}
+ None, db.get_top_processes, _clamp_minutes(minutes))}
# ── Diagnostics / Diagnostic ────────────────────────────────────────────────
@@ -1461,6 +1477,13 @@ def _download_dbip() -> dict:
geo_dir = data_dir() / "geo"
geo_dir.mkdir(parents=True, exist_ok=True)
+ # EN: Sanity ceilings — DB-IP Lite is ~40 MB gzip / ~130 MB plain. A
+ # broken or hostile upstream must not exhaust disk or memory.
+ # FR: Plafonds de bon sens — DB-IP Lite fait ~40 Mo gzip / ~130 Mo en
+ # clair. Un amont cassé ou hostile ne doit pas épuiser disque ou RAM.
+ MAX_GZIP_BYTES = 128 * 1024 * 1024
+ MAX_PLAIN_BYTES = 512 * 1024 * 1024
+
downloaded = []
errors = []
for remote, local in files.items():
@@ -1468,8 +1491,23 @@ def _download_dbip() -> dict:
try:
req = urllib.request.Request(url, headers={"User-Agent": "Snitch/1.1"})
with urllib.request.urlopen(req, timeout=60) as resp:
- data = gzip.decompress(resp.read())
- (geo_dir / local).write_bytes(data)
+ # EN: Read at most cap+1 so an oversize body is detected, not
+ # silently truncated into a corrupt database.
+ # FR: Lire au plus borne+1 pour détecter un corps trop gros
+ # plutôt que de tronquer silencieusement en base corrompue.
+ raw = resp.read(MAX_GZIP_BYTES + 1)
+ if len(raw) > MAX_GZIP_BYTES:
+ raise ValueError("download exceeds size limit")
+ data = gzip.decompress(raw)
+ if len(data) > MAX_PLAIN_BYTES:
+ raise ValueError("decompressed database exceeds size limit")
+ # EN: Atomic install — a crashed write must not leave a partial
+ # .mmdb that maxminddb then chokes on.
+ # FR: Installation atomique — une écriture interrompue ne doit pas
+ # laisser un .mmdb partiel sur lequel maxminddb échouerait.
+ tmp = geo_dir / f"{local}.tmp"
+ tmp.write_bytes(data)
+ os.replace(tmp, geo_dir / local)
downloaded.append(local)
except Exception as exc:
errors.append(f"{local}: {exc}")
diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.py
index deaf7fe..909a066 100644
--- a/backend/capture/sniffer.py
+++ b/backend/capture/sniffer.py
@@ -370,12 +370,23 @@ class PacketSniffer:
bpf_filter=self._bpf_filter)
logger.info("capture on %s (linktype=%d, filter=%r)",
self.iface, self._session.linktype, self._bpf_filter)
+ # EN: Refresh the local-IP set periodically — a VPN toggle or a
+ # DHCP renewal changes our addresses, and a frozen set would
+ # silently classify all new traffic as "not_for_us".
+ # FR: Rafraîchir périodiquement les IP locales — une bascule VPN
+ # ou un renouvellement DHCP change nos adresses, et un
+ # ensemble figé classerait tout le nouveau trafic en
+ # « not_for_us ».
+ last_ip_refresh = time.monotonic()
while self._running:
try:
pkt = self._session.next_packet()
except PcapError as exc:
logger.error("capture error: %s", exc)
break
+ if time.monotonic() - last_ip_refresh > 30:
+ self.local_ips = get_local_ips()
+ last_ip_refresh = time.monotonic()
if pkt is not None:
self._handle_frame(*pkt)
except PcapError as exc:
diff --git a/backend/resolver/dns_geo.py b/backend/resolver/dns_geo.py
index 6bd8975..57b65e4 100644
--- a/backend/resolver/dns_geo.py
+++ b/backend/resolver/dns_geo.py
@@ -51,6 +51,7 @@ import asyncio
import gzip
import ipaddress
import logging
+import os
import socket
import sys
import threading
@@ -166,14 +167,30 @@ def lookup_domain(ip: str) -> Optional[str]:
# ── Reverse DNS / DNS inverse ────────────────────────────────────────────────
+# EN: SNITCH_DISABLE_PTR=1 turns reverse-DNS lookups off entirely. PTR
+# queries go to YOUR configured resolver — they reveal nothing the
+# resolver does not already see from your forward lookups, but they are
+# still outbound traffic, so the strictest setups can opt out.
+# FR: SNITCH_DISABLE_PTR=1 désactive totalement le DNS inverse. Les requêtes
+# PTR partent vers VOTRE résolveur configuré — elles ne révèlent rien que
+# le résolveur ne voie déjà via vos requêtes directes, mais restent du
+# trafic sortant, donc les configurations les plus strictes peuvent
+# s'en passer.
+_DISABLE_PTR = os.environ.get("SNITCH_DISABLE_PTR") == "1"
+
+
@lru_cache(maxsize=2048)
def resolve_hostname(ip: str) -> Optional[str]:
"""
- EN: Reverse DNS — None on NXDOMAIN/timeout. lru_cache caches negatives
- too: PTR absence is stable, so that's the desired behavior.
- FR: DNS inverse — None sur NXDOMAIN/timeout. lru_cache met aussi en cache
- les échecs : l'absence de PTR est stable, c'est le comportement voulu.
+ EN: Reverse DNS — None on NXDOMAIN/timeout, and always None when
+ SNITCH_DISABLE_PTR=1. lru_cache caches negatives too: PTR absence is
+ stable, so that's the desired behavior.
+ FR: DNS inverse — None sur NXDOMAIN/timeout, et toujours None avec
+ SNITCH_DISABLE_PTR=1. lru_cache met aussi en cache les échecs :
+ l'absence de PTR est stable, c'est le comportement voulu.
"""
+ if _DISABLE_PTR:
+ return None
try:
return socket.gethostbyaddr(ip)[0]
except Exception:
diff --git a/backend/storage/db.py b/backend/storage/db.py
index 9ea4aff..0197825 100644
--- a/backend/storage/db.py
+++ b/backend/storage/db.py
@@ -51,6 +51,7 @@ _conn_lock = threading.Lock()
# FR: Accumulateur d'écriture en mémoire — (minute, catégorie) -> [paquets, octets].
_pending: dict[tuple, list] = defaultdict(lambda: [0, 0])
_pending_hist: dict[tuple, list] = defaultdict(lambda: [0, 0])
+_pending_alerts: list[tuple] = []
_pending_lock = threading.Lock()
@@ -319,12 +320,14 @@ def flush() -> None:
Appelé par le thread de flush toutes les ~10 s.
"""
with _pending_lock:
- if not _pending and not _pending_hist:
+ if not _pending and not _pending_hist and not _pending_alerts:
return
batch = dict(_pending)
_pending.clear()
hist_batch = dict(_pending_hist)
_pending_hist.clear()
+ alert_rows = list(_pending_alerts)
+ _pending_alerts.clear()
rows = [(m, c, v[0], v[1]) for (m, c), v in batch.items()]
hist_rows = [(m, d, k, v[0], v[1]) for (m, d, k), v in hist_batch.items()]
@@ -345,6 +348,12 @@ def flush() -> None:
packets = packets + excluded.packets,
bytes = bytes + excluded.bytes
""", hist_rows)
+ if alert_rows:
+ conn.executemany("""
+ INSERT OR IGNORE INTO alerts_log
+ (id, ts, type, severity, message, node_id, details)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ """, alert_rows)
conn.commit()
except sqlite3.Error as exc:
logger.error("flush failed: %s", exc)
@@ -352,25 +361,25 @@ def flush() -> None:
def log_alert(alert: dict) -> None:
"""
- EN: Persist one alert. INSERT OR IGNORE makes retries idempotent on the
- UUID primary key.
- FR: Persister une alerte. INSERT OR IGNORE rend les réessais idempotents
- grâce à la clé primaire UUID.
+ EN: Buffer one alert for the next flush() — previously this did an
+ INSERT + COMMIT per alert on the event loop, so an alert storm
+ (port scan) stalled the packet pipeline on disk fsyncs. Batched with
+ the 10 s accumulator flush instead. INSERT OR IGNORE keeps retries
+ idempotent on the UUID primary key.
+ FR: Mettre une alerte en tampon jusqu'au prochain flush() — auparavant
+ chaque alerte faisait un INSERT + COMMIT sur la boucle
+ événementielle, donc une tempête d'alertes (scan de ports) bloquait
+ le pipeline de paquets sur des fsync disque. Désormais groupées avec
+ le flush d'accumulateur de 10 s. INSERT OR IGNORE rend les réessais
+ idempotents grâce à la clé primaire UUID.
"""
- try:
- with _conn_lock:
- conn = get_conn()
- conn.execute("""
- INSERT OR IGNORE INTO alerts_log (id, ts, type, severity, message, node_id, details)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- """, (
- alert["id"], alert["timestamp"], alert["type"],
- alert["severity"], alert["message"],
- alert.get("node_id"), json.dumps(alert.get("details", {})),
- ))
- conn.commit()
- except sqlite3.Error as exc:
- logger.error("log_alert failed: %s", exc)
+ row = (
+ alert["id"], alert["timestamp"], alert["type"],
+ alert["severity"], alert["message"],
+ alert.get("node_id"), json.dumps(alert.get("details", {})),
+ )
+ with _pending_lock:
+ _pending_alerts.append(row)
# ── Read helpers / Aides de lecture ──────────────────────────────────────────
diff --git a/backend/tests/test_db.py b/backend/tests/test_db.py
index 224028a..1a588d6 100644
--- a/backend/tests/test_db.py
+++ b/backend/tests/test_db.py
@@ -42,8 +42,12 @@ def test_log_alert_persists():
}
db.log_alert(alert)
# EN: Second insert of the same id must be a no-op (INSERT OR IGNORE).
+ # Alerts are buffered and written by flush(), like the accumulators.
# FR: Une seconde insertion du même id doit être un no-op (INSERT OR IGNORE).
+ # Les alertes sont mises en tampon et écrites par flush(), comme les
+ # accumulateurs.
db.log_alert(alert)
+ db.flush()
with db._conn_lock:
rows = db.get_conn().execute(
@@ -87,6 +91,7 @@ def test_get_alerts_reads_persisted():
"details": {"ports": 25},
}
db.log_alert(alert)
+ db.flush()
rows = db.get_alerts(100)
hit = [r for r in rows if r["id"] == alert["id"]]
assert hit and hit[0]["type"] == "PORT_SCAN" and hit[0]["details"]["ports"] == 25
diff --git a/electron/main.js b/electron/main.js
index 62fcdfb..1916f92 100644
--- a/electron/main.js
+++ b/electron/main.js
@@ -430,8 +430,10 @@ function launchBackendElevated() {
// précédent a laissé le dossier de données en root — sous POSIX les
// variables d'environnement ci-dessous portent le jeton de toute façon,
// donc une écriture ratée ne doit pas interrompre le démarrage.
+ let tokenFileWritten = false
try {
fs.writeFileSync(path.join(dataDir, 'api_token.txt'), API_TOKEN, { mode: 0o600 })
+ tokenFileWritten = true
} catch { /* EN: token still reaches the backend via env / FR: le jeton arrive quand même via l'env */ }
if (isWindows) {
@@ -443,17 +445,17 @@ function launchBackendElevated() {
], { windowsHide: true, stdio: 'ignore' })
} else if (process.platform === 'darwin') {
// EN: Escape for the AppleScript double-quoted string, then the shell.
- // SNITCH_TOKEN travels in the command env — osascript runs it through
- // `sh -c`, so assignment prefixes survive elevation. (Token exposure in
- // `ps` is acceptable: it is a per-launch random secret on a loopback
- // API, gone with the process.)
+ // The token normally travels via the api_token.txt file written above
+ // so it never appears in `ps`; the SNITCH_TOKEN env prefix is only a
+ // fallback for when that write failed (root-owned data dir).
// FR: Échapper pour la chaîne AppleScript entre guillemets, puis le shell.
- // SNITCH_TOKEN voyage dans l'env de la commande — osascript l'exécute
- // via `sh -c`, donc les préfixes d'affectation survivent à l'élévation.
- // (Exposition du jeton dans `ps` acceptable : secret aléatoire par
- // lancement sur une API loopback, mort avec le processus.)
+ // Le jeton voyage normalement via le fichier api_token.txt écrit
+ // ci-dessus et n'apparaît donc jamais dans `ps` ; le préfixe
+ // SNITCH_TOKEN n'est qu'un repli quand cette écriture a échoué
+ // (dossier de données possédé par root).
const esc = s => s.replace(/(["\\$`])/g, '\\$1')
- const shellCmd = `SNITCH_DATA_DIR="${dataDir}" SNITCH_TOKEN="${API_TOKEN}" "${backendExe}" --port ${backendPort}`
+ const tokenPrefix = tokenFileWritten ? '' : `SNITCH_TOKEN="${API_TOKEN}" `
+ const shellCmd = `SNITCH_DATA_DIR="${dataDir}" ${tokenPrefix}"${backendExe}" --port ${backendPort}`
backendProc = spawn('osascript', [
'-e', `do shell script "${esc(shellCmd)}" with administrator privileges`,
], { stdio: 'ignore' })
@@ -467,8 +469,15 @@ function launchBackendElevated() {
const pkexecBin = ['/usr/bin/pkexec', '/bin/pkexec', '/usr/local/bin/pkexec']
.find(p => fs.existsSync(p))
if (!pkexecBin) { spawnBackendPlain(); return }
+ // EN: Same rule as macOS — prefer the token file over an env assignment
+ // visible in /proc/<pid>/cmdline; env only when the write failed.
+ // FR: Même règle que macOS — préférer le fichier de jeton à une
+ // affectation d'env visible dans /proc/<pid>/cmdline ; l'env sert
+ // seulement si l'écriture a échoué.
+ const envArgs = [`SNITCH_DATA_DIR=${dataDir}`]
+ if (!tokenFileWritten) envArgs.push(`SNITCH_TOKEN=${API_TOKEN}`)
backendProc = spawn(pkexecBin, [
- 'env', `SNITCH_DATA_DIR=${dataDir}`, `SNITCH_TOKEN=${API_TOKEN}`,
+ 'env', ...envArgs,
backendExe, '--port', String(backendPort),
], { stdio: 'ignore' })
}
diff --git a/frontend/src/api.js b/frontend/src/api.js
index d172106..895e6ef 100644
--- a/frontend/src/api.js
+++ b/frontend/src/api.js
@@ -84,6 +84,13 @@ export function getToken() {
const fromUrl = new URLSearchParams(window.location.search).get('token')
if (fromUrl) {
sessionStorage.setItem('snitch_token', fromUrl)
+ // EN: Strip the token from the address bar so it cannot linger in
+ // browser history — the stored copy keeps auth working.
+ // FR: Retirer le jeton de la barre d'adresse pour qu'il ne reste pas
+ // dans l'historique du navigateur — la copie stockée suffit.
+ const clean = new URL(window.location.href)
+ clean.searchParams.delete('token')
+ window.history.replaceState(null, '', clean)
return fromUrl
}
const stored = sessionStorage.getItem('snitch_token')