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.

identify: full IEEE OUI table, gateway detection, passive mDNS naming

MoneyLisaeb9e8ad79b47
diff --git a/backend/api/main.py b/backend/api/main.py
index 1623319..fefb0a6 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -81,7 +81,7 @@ from capture.media_monitor import MediaMonitor, MediaState
from classifier.traffic import classify
from resolver.dns_geo import (enrich_ip, is_private, learn_dns_answers,
learn_sni, lookup_domain)
-from scanner.arp_scanner import ARPScanner, Device
+from scanner.arp_scanner import ARPScanner, Device, default_gateway as _default_gateway
from detection.anomaly import AnomalyDetector
import storage.db as db
@@ -218,12 +218,15 @@ def _ensure_lan_device(ip: str) -> dict:
key = f"lan:{ip}"
dev = lan_devices.get(key)
if dev is None:
+ is_gw = ip == _gateway()
dev = {
"id": key, "ip": ip, "mac": None,
"label": ip, "hostname": None, "vendor": "",
- "category": "lan_device", "device_type": "unknown",
+ "category": "lan_device",
+ "device_type": "router" if is_gw else "unknown",
+ "is_gateway": is_gw, "private_mac": False,
"online": True, "bytes": 0, "packets": 0,
- "color": "#64748b", "alerted": False,
+ "color": "#f97316" if is_gw else "#64748b", "alerted": False,
}
lan_devices[key] = dev
edges[f"lan-edge-{ip}"] = {
@@ -234,6 +237,43 @@ def _ensure_lan_device(ip: str) -> dict:
return dev
+# EN: Default-gateway cache — `route`/`/proc` is re-read at most once per
+# minute so stub creation stays cheap.
+# FR: Cache de la passerelle par défaut — `route`/`/proc` relu au maximum
+# une fois par minute pour que la création de stub reste légère.
+_gateway_cache: dict = {"ip": None, "ts": 0.0}
+
+
+def _gateway() -> Optional[str]:
+ """EN: Cached default_gateway() (5 min TTL).
+ FR: default_gateway() mis en cache (TTL 5 min)."""
+ now = time.time()
+ if now - _gateway_cache["ts"] > 300:
+ _gateway_cache["ip"] = _default_gateway()
+ _gateway_cache["ts"] = now
+ return _gateway_cache["ip"]
+
+
+def _learn_lan_hostname(ip: str, name: str,
+ touched_devices: dict) -> None:
+ """
+ EN: An mDNS "*.local" announcement named this LAN device — store the
+ hostname on the entry (stub or real) so the UI shows "iPhone-de-Lisa"
+ instead of a bare IP. Never overwrites an existing name.
+ FR: Une annonce mDNS « *.local » a nommé cet appareil LAN — stocker le
+ nom d'hôte sur l'entrée (stub ou réelle) pour que l'UI affiche
+ « iPhone-de-Lisa » au lieu d'une IP nue. N'écrase jamais un nom
+ existant.
+ """
+ dev = _ensure_lan_device(ip)
+ if dev.get("hostname"):
+ return
+ dev["hostname"] = name
+ if dev.get("label") == dev.get("ip"):
+ dev["label"] = name
+ touched_devices[dev["id"]] = dev
+
+
# ── Packet handling / Traitement des paquets ─────────────────────────────────
def on_packet(pkt: Packet) -> None:
@@ -331,16 +371,25 @@ def _process_batch(packets: list[Packet]) -> None:
continue
remote_ip = pkt.dst_ip if pkt.direction == "out" else pkt.src_ip
+
+ # EN: DNS/mDNS learning runs BEFORE the noise filter — mDNS answers
+ # are destined to multicast 224.0.0.251, which must never become
+ # a node but still carries "*.local" device names we want.
+ # FR: L'apprentissage DNS/mDNS tourne AVANT le filtre anti-bruit —
+ # les réponses mDNS visent le multicast 224.0.0.251, qui ne doit
+ # jamais devenir un nœud mais porte les noms « *.local » utiles.
+ if pkt.dns:
+ dns53 = [a for a in pkt.dns if not a[0].lower().endswith(".local")]
+ if dns53:
+ learn_dns_answers(dns53)
+ for name, ip, _ttl in pkt.dns:
+ if name.lower().endswith(".local") and is_private(ip):
+ _learn_lan_hostname(ip, name[:-len(".local")],
+ touched_devices)
+
if remote_ip in _whitelisted_ips or _is_noise_ip(remote_ip):
continue
- # EN: Feed the observed-domain map first — DNS answers map many IPs,
- # SNI names the destination of this very packet.
- # FR: Alimenter d'abord la table des domaines observés — les réponses
- # DNS mappent beaucoup d'IP, le SNI nomme la destination de ce
- # paquet même.
- if pkt.dns:
- learn_dns_answers(pkt.dns)
if pkt.sni:
learn_sni(remote_ip, pkt.sni)
@@ -521,6 +570,13 @@ async def _handle_device(device: Device, is_new: bool) -> None:
node["bytes"] = prev.get("bytes", 0)
node["packets"] = prev.get("packets", 0)
node["alerted"] = prev.get("alerted", False)
+ # EN: Keep names learned from mDNS — reverse-DNS often returns None
+ # where a passive mDNS announcement already gave a real hostname.
+ # FR: Garder les noms appris via mDNS — le DNS inverse renvoie souvent
+ # None là où une annonce mDNS passive a déjà donné un vrai nom.
+ if not device.hostname and prev.get("hostname"):
+ node["hostname"] = prev["hostname"]
+ node["label"] = prev["hostname"]
else:
node["alerted"] = False
lan_devices[node["id"]] = node
diff --git a/backend/backend.spec b/backend/backend.spec
index 1aad11d..2245eb3 100644
--- a/backend/backend.spec
+++ b/backend/backend.spec
@@ -33,7 +33,8 @@ a = Analysis(
# app finds them — _list_dir() resolves via sys._MEIPASS.
# FR: Embarquer classifier/lists/ (listes trackers + CDN) pour que l'app
# figée les trouve — _list_dir() résout via sys._MEIPASS.
- datas=[('classifier/lists', 'classifier/lists')],
+ datas=[('classifier/lists', 'classifier/lists'),
+ ('scanner/oui_table.txt.gz', 'scanner')],
hiddenimports=(
# ── uvicorn internals / éléments internes d'uvicorn ─────────────
collect_submodules('uvicorn')
diff --git a/backend/capture/parser.py b/backend/capture/parser.py
index d3b7b20..ff952a3 100644
--- a/backend/capture/parser.py
+++ b/backend/capture/parser.py
@@ -266,7 +266,16 @@ def _parse_transport(payload: bytes, proto: int, src: str, dst: str,
return None
sport, dport = struct.unpack("!HH", payload[:4])
udp_payload = payload[8:]
- dns = parse_dns(udp_payload) if (sport == 53 or dport == 53) else []
+ if sport == 53 or dport == 53:
+ dns = parse_dns(udp_payload)
+ elif sport == 5353 or dport == 5353:
+ # EN: mDNS — devices announce "<name>.local → <ip>" here; that's
+ # how we learn hostnames without ever sending a query.
+ # FR: mDNS — les appareils annoncent « <nom>.local → <ip> » ici ;
+ # c'est ainsi qu'on apprend les noms sans jamais émettre.
+ dns = parse_mdns(udp_payload)
+ else:
+ dns = []
return ParsedPacket(src, dst, "UDP", wire_len, sport, dport, 0, dns, None)
if proto in (IPPROTO_ICMP, IPPROTO_ICMPV6):
@@ -354,6 +363,56 @@ def parse_dns(payload: bytes) -> list[tuple[str, str, int]]:
return []
+def parse_mdns(payload: bytes) -> list[tuple[str, str, int]]:
+ """
+ EN: Parse an mDNS message (UDP/5353). Same wire format as DNS, but device
+ A/AAAA records often live in the ADDITIONAL section — so we walk all
+ three record sections, not just answers, and we don't require the QR
+ bit (mDNS announcements and responses both carry records). Only
+ "*.local" names are returned, as (hostname, ip, ttl) — hostname with
+ the .local suffix stripped.
+ FR: Analyser un message mDNS (UDP/5353). Même format fil que DNS, mais les
+ enregistrements A/AAAA des appareils vivent souvent dans la section
+ ADDITIONNELLE — on parcourt donc les trois sections, pas seulement
+ les réponses, et le bit QR n'est pas exigé (annonces et réponses
+ portent des enregistrements). Seuls les noms « *.local » sont
+ renvoyés, en (nom d'hôte, ip, ttl) — suffixe .local retiré.
+ """
+ try:
+ if len(payload) < 12:
+ return []
+ _, _flags, qdcount, ancount, nscount, arcount = struct.unpack("!HHHHHH", payload[:12])
+
+ off = 12
+ for _ in range(qdcount):
+ _, off = _dns_name(payload, off)
+ off += 4
+
+ answers = []
+ for _ in range(ancount + nscount + arcount):
+ name, off = _dns_name(payload, off)
+ if off + 10 > len(payload):
+ break
+ rtype, _, ttl, rdlen = struct.unpack("!HHIH", payload[off:off + 10])
+ rdata_off = off + 10
+ if rdata_off + rdlen > len(payload):
+ break
+ rdata = payload[rdata_off:rdata_off + rdlen]
+ # EN: Keep the ".local" suffix — main.py uses it to tell mDNS
+ # device names apart from regular DNS answers.
+ # FR: Garder le suffixe « .local » — main.py s'en sert pour
+ # distinguer les noms d'appareils mDNS des réponses DNS normales.
+ if name.lower().endswith(".local"):
+ if rtype == 1 and rdlen == 4: # EN: A / FR: A
+ answers.append((name, socket.inet_ntop(socket.AF_INET, rdata), ttl))
+ elif rtype == 28 and rdlen == 16: # EN: AAAA / FR: AAAA
+ answers.append((name, socket.inet_ntop(socket.AF_INET6, rdata), ttl))
+ off = rdata_off + rdlen
+ return answers
+ except (IndexError, struct.error, ValueError):
+ return []
+
+
# ── TLS SNI / SNI TLS ────────────────────────────────────────────────────────
def parse_tls_sni(payload: bytes) -> Optional[str]:
diff --git a/backend/scanner/arp_scanner.py b/backend/scanner/arp_scanner.py
index 192efc3..7e8f5a3 100644
--- a/backend/scanner/arp_scanner.py
+++ b/backend/scanner/arp_scanner.py
@@ -42,7 +42,7 @@ from typing import Callable, Optional
import psutil
-from scanner.oui import lookup, DEVICE_TYPE_COLORS
+from scanner.oui import lookup, is_local_mac, DEVICE_TYPE_COLORS
logger = logging.getLogger("snitch.scanner")
@@ -63,6 +63,10 @@ class Device:
vendor: str = ""
device_type: str = "unknown" # phone / pc / router / iot / tv / unknown
hostname: Optional[str] = None
+ is_gateway: bool = False # EN: this device IS the internet box
+ # FR: cet appareil EST la box internet
+ private_mac: bool = False # EN: randomized/locally-administered MAC
+ # FR: MAC aléatoire/administrée localement
online: bool = True
first_seen: float = field(default_factory=time.time)
last_seen: float = field(default_factory=time.time)
@@ -81,6 +85,8 @@ class Device:
"vendor": self.vendor,
"category": "lan_device",
"device_type": self.device_type,
+ "is_gateway": self.is_gateway,
+ "private_mac": self.private_mac,
"online": self.online,
"bytes": self.bytes,
"packets": self.packets,
@@ -164,6 +170,48 @@ def _resolve_hostname(ip: str) -> Optional[str]:
return None
+def default_gateway() -> Optional[str]:
+ """
+ EN: The IPv4 default gateway — i.e. the user's internet box/router.
+ Per-OS readers: /proc/net/route on Linux, `route -n get default` on
+ macOS, `route print -4` on Windows. None when undetectable.
+ Used to flag the matching LAN device as a router even when its OUI
+ is missing from both tables.
+ FR: La passerelle IPv4 par défaut — c'est-à-dire la box/routeur de
+ l'utilisateur. Lecteurs par OS : /proc/net/route sous Linux,
+ `route -n get default` sous macOS, `route print -4` sous Windows.
+ None si indétectable. Sert à marquer l'appareil LAN correspondant
+ comme routeur même si son OUI est absent des deux tables.
+ """
+ try:
+ if sys.platform.startswith("linux"):
+ # EN: /proc/net/route — gateway is column 3, little-endian hex,
+ # on lines whose destination is 00000000.
+ # FR: /proc/net/route — la passerelle est en colonne 3, hex
+ # little-endian, sur les lignes dont la destination est 00000000.
+ for line in Path("/proc/net/route").read_text().splitlines()[1:]:
+ parts = line.split()
+ if len(parts) > 2 and parts[1] == "00000000":
+ raw = parts[2]
+ return socket.inet_ntoa(bytes.fromhex(raw)[::-1])
+ elif sys.platform == "darwin":
+ proc = subprocess.run(["route", "-n", "get", "default"],
+ capture_output=True, text=True, timeout=5)
+ m = re.search(r"gateway:\s*(\S+)", proc.stdout)
+ if m:
+ return m.group(1)
+ elif sys.platform.startswith("win"):
+ proc = subprocess.run(["route", "print", "-4", "0.0.0.0"],
+ capture_output=True, text=True, timeout=10)
+ for line in proc.stdout.splitlines():
+ cols = line.split()
+ if len(cols) >= 3 and cols[0] == "0.0.0.0" and IPV4_RE.fullmatch(cols[2]):
+ return cols[2]
+ except (OSError, subprocess.TimeoutExpired, ValueError) as exc:
+ logger.debug("default gateway detection failed: %s", exc)
+ return None
+
+
class ARPScanner:
"""
EN: Background scanner — re-reads the neighbour table every `interval`
@@ -192,6 +240,11 @@ class ARPScanner:
local_ips = _get_local_ips()
while self._running:
seen_ips: set[str] = set()
+ # EN: Re-resolve the gateway each round — DHCP/roaming can change
+ # it, and the flag must follow the real box.
+ # FR: Re-résoudre la passerelle à chaque tour — DHCP/itinérance
+ # peuvent la changer, et le drapeau doit suivre la vraie box.
+ gateway = default_gateway()
for ip, mac in _read_arp_table():
if ip in local_ips:
@@ -207,18 +260,37 @@ class ARPScanner:
is_new = ip not in self._known
if is_new:
vendor, device_type = lookup(mac)
+ is_gateway = ip == gateway
+ if is_gateway:
+ # EN: The gateway IS the router — better than any OUI
+ # guess, and it works for unknown vendors too.
+ # FR: La passerelle EST le routeur — plus fiable que
+ # tout OUI, et marche pour les fabricants inconnus.
+ device_type = "router"
hostname = _resolve_hostname(ip)
self._known[ip] = Device(
ip=ip, mac=mac, vendor=vendor, device_type=device_type,
hostname=hostname, online=True,
+ is_gateway=is_gateway,
+ private_mac=is_local_mac(mac),
color=DEVICE_TYPE_COLORS.get(device_type, "#64748b"),
)
else:
- self._known[ip].last_seen = time.time()
- if not self._known[ip].online:
- self._known[ip].online = True
+ dev = self._known[ip]
+ dev.last_seen = time.time()
+ if not dev.online:
+ dev.online = True
is_new = True # EN: treat reappearance as a change event
# FR: traiter la réapparition comme un événement
+ # EN: Late gateway promotion — the route may only resolve
+ # after the device was first seen.
+ # FR: Promotion tardive en passerelle — la route peut ne se
+ # résoudre qu'après la première vue de l'appareil.
+ if ip == gateway and not dev.is_gateway:
+ dev.is_gateway = True
+ dev.device_type = "router"
+ dev.color = DEVICE_TYPE_COLORS["router"]
+ is_new = True
self.callback(self._known[ip], is_new)
# EN: Mark disappeared devices as offline.
diff --git a/backend/scanner/oui.py b/backend/scanner/oui.py
index 245d846..9c0442a 100644
--- a/backend/scanner/oui.py
+++ b/backend/scanner/oui.py
@@ -2,18 +2,45 @@
Snitch — OUI lookup table.
EN: Maps the first 6 hex chars of a MAC address (the Organizationally Unique
- Identifier) to a (vendor, device_type) pair. This is a partial,
- hand-picked table covering the most common home-network devices — extend
- it freely.
+ Identifier) to a (vendor, device_type) pair.
+
+ Two layers:
+ 1. OUI_TABLE — hand-picked prefixes that also carry a device_type guess
+ (home routers, phones, TVs, IoT). These always win.
+ 2. oui_table.txt.gz — the full IEEE MA-L registry (~40k vendors,
+ ~390 KB compressed), loaded lazily from package data. Gives a vendor
+ name for almost every real MAC; device_type stays "unknown" since
+ the registry doesn't tell you what the device IS.
+
+ Locally-administered MACs (bit 1 of the first octet set) are private/
+ randomized addresses — iOS/Android default to them. is_local_mac()
+ detects them so the UI can explain why no vendor shows.
FR: Associe les 6 premiers caractères hex d'une adresse MAC (l'Organizationally
- Unique Identifier) à un couple (fabricant, type d'appareil). Table
- partielle et choisie couvrant les appareils domestiques les plus courants —
- à enrichir librement.
+ Unique Identifier) à un couple (fabricant, type d'appareil).
+
+ Deux couches :
+ 1. OUI_TABLE — préfixes choisis qui portent aussi une estimation de type
+ d'appareil (routeurs, téléphones, TV, IoT). Toujours prioritaires.
+ 2. oui_table.txt.gz — le registre IEEE MA-L complet (~40 000 fabricants,
+ ~390 Ko compressé), chargé paresseusement depuis les données du
+ package. Donne un nom de fabricant pour presque toute MAC réelle ;
+ le type reste « unknown » car le registre ne dit pas ce qu'est
+ l'appareil.
+
+ Les MAC locales (bit 1 du premier octet levé) sont des adresses privées/
+ aléatoires — iOS/Android les utilisent par défaut. is_local_mac() les
+ détecte pour que l'UI explique l'absence de fabricant.
"""
-# EN: Partial OUI table — key = first 6 hex chars of MAC (uppercase, no colons).
-# FR: Table OUI partielle — clé = 6 premiers caractères hex de la MAC (majuscules, sans « : »).
+import gzip
+import sys
+from pathlib import Path
+
+# EN: Curated OUI table — key = first 6 hex chars of MAC (uppercase, no colons).
+# Value = (vendor, device_type). Takes precedence over the IEEE registry.
+# FR: Table OUI choisie — clé = 6 premiers caractères hex de la MAC (majuscules,
+# sans « : »). Valeur = (fabricant, type). Prioritaire sur le registre IEEE.
OUI_TABLE: dict[str, tuple[str, str]] = {
# Apple
"A4C138": ("Apple", "phone"), "F0DCE2": ("Apple", "phone"),
@@ -39,8 +66,16 @@ OUI_TABLE: dict[str, tuple[str, str]] = {
"E45F01": ("Raspberry Pi", "iot"),
# Intel — EN: usually PC/laptop / FR: généralement PC/portable
"8086F2": ("Intel", "pc"), "A4C3F0": ("Intel", "pc"),
+ "58A023": ("Intel", "pc"),
# Realtek — EN: PC NICs / FR: cartes réseau de PC
"00E04C": ("Realtek", "pc"),
+ # French ISP boxes — EN: gate the gateway check anyway, these are belts
+ # FR: Box d'opérateurs français — la détection de passerelle reste active,
+ # ce ne sont que des indices supplémentaires
+ "70FC8F": ("Freebox", "router"), "001D19": ("Freebox", "router"),
+ "F4CAE5": ("Freebox", "router"), "14A9E3": ("Orange", "router"),
+ "A09169": ("Orange", "router"), "449F51": ("Bouygues", "router"),
+ "EC43E6": ("SFR", "router"), "2485B5": ("SFR", "router"),
# Google — Chromecast, Home, etc.
"54600A": ("Google", "iot"), "F88FCA": ("Google", "iot"),
"A47733": ("Google", "iot"),
@@ -68,12 +103,71 @@ DEVICE_TYPE_COLORS: dict[str, str] = {
}
+# EN: Full IEEE registry, loaded lazily on first lookup miss: prefix → vendor.
+# The .gz sits in package data (works in dev AND under sys._MEIPASS).
+# FR: Registre IEEE complet, chargé paresseusement au premier échec de lookup :
+# préfixe → fabricant. Le .gz est embarqué dans les données du package
+# (fonctionne en dev ET sous sys._MEIPASS).
+_IEEE_TABLE: dict[str, str] | None = None
+
+
+def _ieee_table() -> dict[str, str]:
+ """
+ EN: One-shot loader for oui_table.txt.gz — lines "HHHHHH|Vendor Name".
+ Empty dict on any failure; lookup then falls back to "unknown".
+ FR: Chargeur unique de oui_table.txt.gz — lignes « HHHHHH|Nom fabricant ».
+ Dictionnaire vide sur erreur ; le lookup retombe alors sur « unknown ».
+ """
+ global _IEEE_TABLE
+ if _IEEE_TABLE is not None:
+ return _IEEE_TABLE
+ base = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
+ candidates = [
+ base / "scanner" / "oui_table.txt.gz" if getattr(sys, "_MEIPASS", None)
+ else base / "oui_table.txt.gz",
+ base / "oui_table.txt.gz",
+ ]
+ table: dict[str, str] = {}
+ for path in candidates:
+ try:
+ if path.exists():
+ with gzip.open(path, "rt", encoding="utf-8", errors="replace") as fh:
+ for line in fh:
+ prefix, _, vendor = line.strip().partition("|")
+ if prefix and vendor:
+ table[prefix] = vendor
+ break
+ except OSError:
+ continue
+ _IEEE_TABLE = table
+ return table
+
+
+def is_local_mac(mac: str) -> bool:
+ """
+ EN: True for locally-administered addresses (U/L bit = bit 1 of the first
+ octet). iOS, Android and modern Windows randomize MACs this way on
+ Wi-Fi — no OUI will ever match, and the UI should say so.
+ FR: Vrai pour les adresses administrées localement (bit U/L = bit 1 du
+ premier octet). iOS, Android et Windows récents randomisent ainsi les
+ MAC en Wi-Fi — aucun OUI ne correspondra, l'UI doit le dire.
+ """
+ try:
+ first = int(mac.replace(":", "").replace("-", "")[:2], 16)
+ return bool(first & 0x02)
+ except ValueError:
+ return False
+
+
def lookup(mac: str) -> tuple[str, str]:
"""
- EN: Return (vendor, device_type) for a MAC address string. Unknown OUIs
- return ("Unknown", "unknown").
- FR: Renvoyer (fabricant, type d'appareil) pour une adresse MAC. Les OUI
- inconnus renvoient ("Unknown", "unknown").
+ EN: Return (vendor, device_type) for a MAC address string.
+ Resolution order: curated table → IEEE registry → ("", "unknown").
+ FR: Renvoyer (fabricant, type d'appareil) pour une adresse MAC.
+ Ordre : table choisie → registre IEEE → ("", "unknown").
"""
key = mac.upper().replace(":", "").replace("-", "")[:6]
- return OUI_TABLE.get(key, ("", "unknown"))
+ if key in OUI_TABLE:
+ return OUI_TABLE[key]
+ vendor = _ieee_table().get(key, "")
+ return (vendor, "unknown") if vendor else ("", "unknown")
diff --git a/backend/scanner/oui_table.txt.gz b/backend/scanner/oui_table.txt.gz
new file mode 100644
index 0000000..829d205
Binary files /dev/null and b/backend/scanner/oui_table.txt.gz differ
diff --git a/backend/tests/test_oui.py b/backend/tests/test_oui.py
index 7484a55..8d1ead2 100644
--- a/backend/tests/test_oui.py
+++ b/backend/tests/test_oui.py
@@ -32,3 +32,22 @@ def test_unknown_prefix():
# FR: vide — l'UI retombe sur l'IP et
# affiche un badge « non identifié »
assert dev_type == "unknown"
+
+
+def test_local_mac_detection():
+ """EN: Randomized/locally-administered MACs are detected (U/L bit).
+ FR: Les MAC aléatoires/administrées localement sont détectées (bit U/L)."""
+ from scanner.oui import is_local_mac
+ assert is_local_mac("BE:18:9D:A0:C1:3F") # EN: iOS private MAC
+ assert is_local_mac("ea:d5:0e:80:3b:cf") # FR: MAC privée Android
+ assert not is_local_mac("70:FC:8F:57:31:FB") # EN: real OUI (Freebox)
+ assert not is_local_mac("58:A0:23:E9:E3:B4") # EN: real OUI (Intel)
+
+
+def test_ieee_registry_fallback():
+ """EN: Curated table wins; IEEE registry covers the long tail; unknown
+ prefixes still return ("", "unknown").
+ FR: La table choisie gagne ; le registre IEEE couvre le reste ; les
+ préfixes inconnus renvoient toujours ("", "unknown")."""
+ vendor, _ = lookup("70:FC:8F:57:31:FB") # EN: in curated table → router
+ assert vendor == "Freebox"
diff --git a/backend/tests/test_parser.py b/backend/tests/test_parser.py
index 81ee525..988c006 100644
--- a/backend/tests/test_parser.py
+++ b/backend/tests/test_parser.py
@@ -16,7 +16,7 @@ import struct
from capture.parser import (
DLT_EN10MB, DLT_LINUX_SLL, DLT_LINUX_SLL2, DLT_NULL, DLT_RAW,
- parse_frame, parse_dns, parse_tls_sni,
+ parse_frame, parse_dns, parse_mdns, parse_tls_sni,
)
ETH = DLT_EN10MB
@@ -223,3 +223,70 @@ def test_dns_malformed():
def test_sni_garbage():
assert parse_tls_sni(b"\x16\x03\x01") is None
assert parse_tls_sni(b"GET / HTTP/1.1\r\n\r\n") is None
+
+
+# ── mDNS / mDNS ──────────────────────────────────────────────────────────────
+
+def mdns_frame(hostname: str, ip: bytes, section: str = "answer") -> bytes:
+ """
+ EN: Minimal mDNS message carrying "<hostname>.local → <ip>" — the A
+ record can sit in the ANSWER or ADDITIONAL section (real devices put
+ it in additional, e.g. under a PTR service answer).
+ FR: Message mDNS minimal portant « <hostname>.local → <ip> » — le record
+ A peut siéger dans la section ANSWER ou ADDITIONNELLE (les vrais
+ appareils le mettent en additional, ex. sous une réponse PTR).
+ """
+ def name_to_wire(n: str) -> bytes:
+ out = b""
+ for label in n.split("."):
+ out += bytes([len(label)]) + label.encode()
+ return out + b"\x00"
+
+ a_rec = name_to_wire(f"{hostname}.local") + struct.pack("!HHIH", 1, 1, 120, 4) + ip
+ an, ar = (1, 0) if section == "answer" else (0, 1)
+ # EN: when the A lives in ADDITIONAL, the answer section holds a dummy
+ # PTR record (name "ptr.local" → target "ptr.local") to stay realistic.
+ # FR: quand le A vit en ADDITIONNELLE, la section réponses tient un
+ # enregistrement PTR factice (« ptr.local » → « ptr.local ») pour
+ # rester réaliste.
+ answers = b"" if ar else a_rec
+ if ar:
+ ptr_name = name_to_wire("ptr.local")
+ answers = ptr_name + struct.pack("!HHIH", 12, 1, 120, len(ptr_name)) + ptr_name
+ an = 1
+ hdr = struct.pack("!HHHHHH", 0, 0x8400, 0, an, 0, ar)
+ return hdr + answers + (a_rec if ar else b"")
+
+
+def test_mdns_answer_section():
+ """EN: A record in ANSWER. / FR: Enregistrement A en ANSWER."""
+ res = parse_mdns(mdns_frame("iPhone-de-Lisa", b"\xc0\xa8\x01\xc6", "answer"))
+ assert res == [("iPhone-de-Lisa.local", "192.168.1.198", 120)]
+
+
+def test_mdns_additional_section():
+ """EN: A record in ADDITIONAL under a PTR answer — the common real case.
+ FR: Enregistrement A en ADDITIONNELLE sous une réponse PTR — le cas réel
+ le plus courant."""
+ res = parse_mdns(mdns_frame("MacBook-Pro", b"\xc0\xa8\x01\x2a", "additional"))
+ assert res == [("MacBook-Pro.local", "192.168.1.42", 120)]
+
+
+def test_mdns_udp_5353_flows_through_parser():
+ """EN: A real UDP/5353 frame exposes dns tuples; port 53 still works and
+ other ports stay empty.
+ FR: Une vraie trame UDP/5353 expose des tuples dns ; le port 53 marche
+ toujours et les autres ports restent vides."""
+ mdns = mdns_frame("Nest-Mini", b"\xc0\xa8\x01\x63")
+ ip = ipv4(b"\xc0\xa8\x01\x63", b"\xe0\x00\x00\xfb", 17, udp(5353, 5353, mdns))
+ p = parse_frame(ETH, eth(ip))
+ assert p is not None and p.dns == [("Nest-Mini.local", "192.168.1.99", 120)]
+
+ plain = ipv4(b"\x0a\x00\x00\x01", b"\x5d\xb8\xd8\x22", 17, udp(5354, 8080, mdns))
+ p2 = parse_frame(ETH, eth(plain))
+ assert p2 is not None and p2.dns == []
+
+
+def test_mdns_malformed():
+ assert parse_mdns(b"\x00") == []
+ assert parse_mdns(b"\x00" * 12) == []
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 71c568b..9076982 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -204,7 +204,11 @@ function DeviceRow({ device }) {
)}
</div>
<div style={{ fontSize: 9, color: '#64748b', fontFamily: 'monospace' }}>
- {device.ip} · {device.mac}
+ {/* EN: Type first — "Routeur · 192.168.1.254" tells a neophyte more
+ than a bare MAC address does.
+ FR: Le type d'abord — « Routeur · 192.168.1.254 » dit plus à un
+ néophyte qu'une MAC nue. */}
+ {enumName(t, 'devtype_', device.device_type)} · {device.ip}
</div>
</div>
<div style={{ fontSize: 9, color: device.online === false ? '#ef4444' : '#22c55e', flexShrink: 0 }}>
@@ -289,6 +293,20 @@ function NodeDetail({ node, onWhitelist }) {
</div>
)}
+ {/* EN: Randomized-MAC note — iOS/Android hide their real MAC, so "no
+ vendor" is expected, not suspicious.
+ FR: Note MAC randomisée — iOS/Android masquent leur vraie MAC, donc
+ « pas de fabricant » est attendu, pas suspect. */}
+ {node.private_mac && (
+ <div style={{
+ marginTop: 8, padding: '6px 8px', fontSize: 9, lineHeight: 1.5,
+ color: '#64748b', background: '#1e293b', borderRadius: 6,
+ borderLeft: '2px solid #a855f7',
+ }}>
+ {t('hint_private_mac')}
+ </div>
+ )}
+
{processes.length > 0 && (
<>
<div style={{ fontSize: 9, color: '#475569', textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 8, marginBottom: 4 }}>
diff --git a/frontend/src/i18n.jsx b/frontend/src/i18n.jsx
index 1e69644..3cf885f 100644
--- a/frontend/src/i18n.jsx
+++ b/frontend/src/i18n.jsx
@@ -90,6 +90,7 @@ const en = {
devtype_unknown: 'Unknown type',
hint_unidentified: "Not identified yet — its name appears when it announces itself (DNS/mDNS) or its MAC vendor is known. If you don't recognize it, check your router's client list.",
hint_unresolved: 'Not yet named — the domain appears when a DNS answer or TLS handshake reveals it.',
+ hint_private_mac: 'Private (randomized) MAC address — iOS/Android/Windows hide the real one, so the vendor can\'t be identified. This is normal privacy behavior.',
ext_empty: "No external connections yet — anything your machine talks to will appear here.",
// Alert panel / Panneau d'alertes
@@ -315,6 +316,7 @@ const fr = {
devtype_unknown: 'Type inconnu',
hint_unidentified: "Pas encore identifié — son nom apparaîtra s'il s'annonce (DNS/mDNS) ou si son fabricant est connu. Si vous ne le reconnaissez pas, vérifiez la liste des clients de votre box/routeur.",
hint_unresolved: "Pas encore nommé — le domaine apparaîtra quand une réponse DNS ou un handshake TLS le révélera.",
+ hint_private_mac: "Adresse MAC privée (aléatoire) — iOS/Android/Windows masquent la vraie, le fabricant ne peut pas être identifié. C'est un comportement de confidentialité normal.",
ext_empty: "Aucune connexion externe pour l'instant — tout hôte contacté par votre machine apparaîtra ici.",
// Panneau d'alertes / Alert panel
diff --git a/pyproject.toml b/pyproject.toml
index 07230c9..38e6801 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -52,3 +52,6 @@ py-modules = ["cli", "paths", "logging_config", "run_backend"]
# EN: Domain lists ship inside the wheel too (tracker + CDN suffix lists).
# FR: Les listes de domaines sont aussi embarquées dans la wheel.
"classifier" = ["lists/*.txt"]
+# EN: Full IEEE OUI registry (gzipped) — offline MAC→vendor lookup.
+# FR: Registre IEEE OUI complet (gzippé) — lookup MAC→fabricant hors ligne.
+"scanner" = ["oui_table.txt.gz"]