Просмотр исходного кода

feat(discovery): mDNS fingerprinting and randomized MAC detection (#338) (#351)

Agent: new Discovery probe section running umdns browse on OpenWrt.
Detects locally-administered (randomized) MACs from wireless clients.
Payload gains DiscoveryData with services (hostname -> service types),
hostByIp (IP -> mDNS hostname), and randomMacs list.

Server: buildDevices enriches each device with mDNS services (via IP
lookup) and randomMac flag. When hostname/DHCP classification yields
'desconocido', guessFromMdns refines the type using well-known service
types (AirPlay -> altavoz, Google Cast -> altavoz, IPP -> iot, etc).

Device struct gains mdnsServices []string and randomMac bool fields.
Tests: IsRandomizedMAC (8 cases + edge cases), ParseMdnsBrowse (empty,
real umdns output with services + IP mapping).

This helps identify: Apple TVs (airplay/raop), Google speakers (cast),
printers (ipp), HomeKit devices (hap), NAS/file servers (smb/nfs), and
reduces phantom 'new device' alerts from iOS/Android MAC randomization.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
bbcd4f8a04

+ 28 - 0
agent/probe/local.go

@@ -96,6 +96,8 @@ func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
 	pl.Data.FDB = p.probeFDB(ctx)
 	pl.Data.Dawn = p.probeDawn(ctx)
 	pl.Data.LuCI = p.probeLuCI(ctx)
+	// Discovery (#338): mDNS services + randomized MAC detection.
+	pl.Data.Discovery = p.probeDiscovery(ctx, pl.Data.Wireless)
 	// NetIf (#305): contadores por iface desde el MISMO /proc/net/dev que
 	// leyó probeSystem (sin segundo cat). Los rates los computa el server
 	// con el delta entre payloads.
@@ -394,3 +396,29 @@ func (p *Prober) probeDawn(ctx context.Context) *DawnData {
 	}
 	return &DawnData{SSIDs: ssids}
 }
+
+// probeDiscovery (#338): mDNS service discovery + randomized MAC detection.
+// Runs umdns browse; enriches with randomized MACs from wireless clients.
+func (p *Prober) probeDiscovery(ctx context.Context, wireless *WirelessData) *DiscoveryData {
+	out, err := p.run.Run(ctx, CmdMdnsBrowse, 5*time.Second)
+	var dd *DiscoveryData
+	if err == nil && strings.TrimSpace(out) != "" && strings.TrimSpace(out) != "{}" {
+		dd = ParseMdnsBrowse([]byte(out))
+	}
+	if dd == nil {
+		dd = &DiscoveryData{}
+	}
+
+	// Detect randomized MACs from wireless clients.
+	if wireless != nil {
+		for mac := range wireless.Clients {
+			if IsRandomizedMAC(mac) {
+				dd.RandomMACs = append(dd.RandomMACs, mac)
+			}
+		}
+	}
+	if len(dd.Services) == 0 && len(dd.HostByIP) == 0 && len(dd.RandomMACs) == 0 {
+		return nil
+	}
+	return dd
+}

+ 17 - 0
agent/probe/payload.go

@@ -40,6 +40,8 @@ type PayloadData struct {
 	// Vlans: VLANs del bridge (issue #315, bridge vlan show). nil = sonda
 	// fallida o router sin bridge vlan filtering.
 	Vlans []VlanPort `json:"vlans,omitempty"`
+	// Discovery: mDNS services and randomized MAC detection (#338).
+	Discovery *DiscoveryData `json:"discovery,omitempty"`
 }
 
 // SystemData: salud del equipo + tráfico + latencias.
@@ -110,3 +112,18 @@ type DawnClient struct {
 	HT     bool   `json:"ht"`
 	VHT    bool   `json:"vht"`
 }
+
+// DiscoveryData: mDNS service discovery + randomized MAC detection (#338).
+// Source: umdns browse on OpenWrt; falls back to parsing /tmp/umdns/ if
+// available. Best-effort: nil section if umdns is not installed.
+type DiscoveryData struct {
+	// Services: hostname -> list of mDNS service types advertised.
+	// e.g. {"Apple-TV._airplay._tcp.local": ["_airplay._tcp", "_raop._tcp"]}
+	Services map[string][]string `json:"services,omitempty"`
+	// HostByIP: IP -> hostname from mDNS PTR records. Helps resolve devices
+	// that have no DHCP hostname.
+	HostByIP map[string]string `json:"hostByIp,omitempty"`
+	// RandomMACs: MACs detected as locally-administered (bit 1 of byte 0 set).
+	// These are typically iOS/Android private WiFi addresses that rotate.
+	RandomMACs []string `json:"randomMacs,omitempty"`
+}

+ 108 - 0
agent/probe/probe.go

@@ -77,6 +77,11 @@ const (
 	// Da proto ("pppoe"), IP, gateway (ptpaddress/nexthop) y DNS (issue #276).
 	CmdWanStatus = "ubus call network.interface.wan status 2>/dev/null || true"
 	CmdBridgeVlan = "bridge vlan show 2>/dev/null || true"
+
+	// CmdMdnsBrowse (#338): mDNS service discovery via umdns (OpenWrt's
+	// lightweight mDNS daemon). Returns JSON with hostname -> services.
+	// Falls back to empty if umdns is not installed.
+	CmdMdnsBrowse = "ubus call umdns browse 2>/dev/null || echo '{}'"
 	CmdEthtoolSFP = "ethtool -m %s 2>/dev/null || true"
 )
 
@@ -985,3 +990,106 @@ func max0(v float64) float64 {
 	}
 	return v
 }
+
+// ParseMdnsBrowse (#338): parsea la salida de `ubus call umdns browse`.
+// Formato típico (JSON):
+//
+//	{ "hostname._service._tcp.local": { "port": 1234, "txt": [...] }, ... }
+//
+// Extrae: hostname (de la clave, antes del primer punto) y tipos de servicio
+// (el segmento _service._tcp). También recoge IPs si aparecen en registros A.
+func ParseMdnsBrowse(raw []byte) *DiscoveryData {
+	if len(raw) == 0 {
+		return nil
+	}
+	// umdns browse devuelve un objeto JSON con claves "fqdn" y valores que
+	// contienen "port", "txt", "ipv4", etc. Parseamos como map genérico.
+	var browse map[string]json.RawMessage
+	if json.Unmarshal(raw, &browse) != nil {
+		return nil
+	}
+	if len(browse) == 0 {
+		return nil
+	}
+
+	dd := &DiscoveryData{
+		Services: map[string][]string{},
+		HostByIP: map[string]string{},
+	}
+	for fqdn, val := range browse {
+		// Extraer hostname: primera parte antes del "."
+		hostname := fqdn
+		if idx := strings.Index(fqdn, "."); idx > 0 {
+			hostname = fqdn[:idx]
+		}
+		// Extraer tipo de servicio: segundo segmento "_svc._tcp" o "_svc._udp"
+		parts := strings.SplitN(fqdn, ".", 3)
+		if len(parts) >= 2 && strings.HasPrefix(parts[1], "_") {
+			svcType := parts[1]
+			if len(parts) >= 3 {
+				svcType = parts[1] + "." + strings.SplitN(parts[2], ".", 2)[0]
+			}
+			dd.Services[hostname] = appendUnique(dd.Services[hostname], svcType)
+		}
+		// Extraer IP si disponible
+		var entry struct {
+			IPv4 string `json:"ipv4"`
+		}
+		if json.Unmarshal(val, &entry) == nil && entry.IPv4 != "" {
+			dd.HostByIP[entry.IPv4] = hostname
+		}
+	}
+	if len(dd.Services) == 0 && len(dd.HostByIP) == 0 {
+		return nil
+	}
+	return dd
+}
+
+func appendUnique(slice []string, s string) []string {
+	for _, x := range slice {
+		if x == s {
+			return slice
+		}
+	}
+	return append(slice, s)
+}
+
+// IsRandomizedMAC returns true if the MAC address has the locally-administered
+// bit set (bit 1 of byte 0). Apple, Google, and Samsung use this for WiFi
+// privacy features — the device appears as a new MAC periodically.
+func IsRandomizedMAC(mac string) bool {
+	if len(mac) < 2 {
+		return false
+	}
+	// Byte 0: first two hex chars
+	b, err := parseHexByte(mac[0], mac[1])
+	if err != nil {
+		return false
+	}
+	return b&0x02 != 0
+}
+
+func parseHexByte(hi, lo byte) (byte, error) {
+	h, err := hexNibble(hi)
+	if err != nil {
+		return 0, err
+	}
+	l, err := hexNibble(lo)
+	if err != nil {
+		return 0, err
+	}
+	return h<<4 | l, nil
+}
+
+func hexNibble(c byte) (byte, error) {
+	switch {
+	case c >= '0' && c <= '9':
+		return c - '0', nil
+	case c >= 'a' && c <= 'f':
+		return c - 'a' + 10, nil
+	case c >= 'A' && c <= 'F':
+		return c - 'A' + 10, nil
+	default:
+		return 0, fmt.Errorf("invalid hex nibble: %c", c)
+	}
+}

+ 62 - 0
agent/probe/probe_test.go

@@ -566,3 +566,65 @@ func TestParseEthtoolSFP(t *testing.T) {
 		t.Fatalf("sin DOM debía dar nil: %+v", got)
 	}
 }
+
+// TestIsRandomizedMAC (#338): detects locally-administered MACs.
+func TestIsRandomizedMAC(t *testing.T) {
+	cases := map[string]bool{
+		"AA:BB:CC:DD:EE:FF": true,  // 0xAA = 10101010, bit 1 set
+		"02:11:22:33:44:55": true,  // 0x02 = 00000010, bit 1 set
+		"F6:A1:B2:C3:D4:E5": true,  // 0xF6 = 11110110, bit 1 set
+		"00:11:22:33:44:55": false, // 0x00 = 00000000, bit 1 clear
+		"DC:A6:32:XX:YY:ZZ": false, // 0xDC = 11011100, bit 1 clear (Raspberry Pi)
+		"B8:27:EB:11:22:33": false, // 0xB8 = 10111000, bit 1 clear
+		"B2:AA:BB:CC:DD:EE": true,  // 0xB2 = 10110010, bit 1 set (Apple private)
+	}
+	for mac, want := range cases {
+		got := IsRandomizedMAC(mac)
+		if got != want {
+			t.Errorf("IsRandomizedMAC(%q) = %v, want %v", mac, got, want)
+		}
+	}
+	// Edge cases
+	if IsRandomizedMAC("") {
+		t.Error("empty should be false")
+	}
+	if IsRandomizedMAC("X") {
+		t.Error("single char should be false")
+	}
+}
+
+// TestParseMdnsBrowse (#338): parses umdns browse output.
+func TestParseMdnsBrowse(t *testing.T) {
+	// Empty input
+	if got := ParseMdnsBrowse(nil); got != nil {
+		t.Fatalf("nil should return nil, got %+v", got)
+	}
+	if got := ParseMdnsBrowse([]byte("{}")); got != nil {
+		t.Fatalf("empty object should return nil, got %+v", got)
+	}
+
+	// Real umdns browse output (simplified)
+	raw := `{
+		"Apple-TV._airplay._tcp.local": {"port": 7000, "ipv4": "192.168.1.50"},
+		"Apple-TV._raop._tcp.local": {"port": 7000, "ipv4": "192.168.1.50"},
+		"Printer._ipp._tcp.local": {"port": 631, "ipv4": "192.168.1.60"}
+	}`
+	dd := ParseMdnsBrowse([]byte(raw))
+	if dd == nil {
+		t.Fatal("should parse valid browse output")
+	}
+	// Check services
+	if svcs, ok := dd.Services["Apple-TV"]; !ok || len(svcs) != 2 {
+		t.Errorf("Apple-TV services: %v", dd.Services)
+	}
+	if svcs, ok := dd.Services["Printer"]; !ok || len(svcs) != 1 {
+		t.Errorf("Printer services: %v", dd.Services)
+	}
+	// Check IP mapping
+	if host, ok := dd.HostByIP["192.168.1.50"]; !ok || host != "Apple-TV" {
+		t.Errorf("HostByIP[192.168.1.50] = %q", host)
+	}
+	if host, ok := dd.HostByIP["192.168.1.60"]; !ok || host != "Printer" {
+		t.Errorf("HostByIP[192.168.1.60] = %q", host)
+	}
+}

+ 4 - 0
server-go/internal/adapters/agent.go

@@ -540,6 +540,10 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	if p.Data.LuCI != nil {
 		out.luci = p.Data.LuCI
 	}
+	// Discovery (#338): mDNS services + randomized MACs. Best-effort.
+	if p.Data.Discovery != nil {
+		out.discovery = p.Data.Discovery
+	}
 
 	if cached == nil {
 		cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},

+ 28 - 0
server-go/internal/adapters/classify.go

@@ -86,3 +86,31 @@ func GuessDeviceType(hostname, manufacturer, dhcpVendorClass, dhcpClientID, lldp
 	}
 	return "desconocido"
 }
+
+// guessFromMdns (#338): classify a device from its mDNS service types when
+// hostname/DHCP/LLDP classification yielded "desconocido". The mapping is
+// intentionally conservative: only well-known service types that strongly
+// indicate a device category.
+func guessFromMdns(services []string) string {
+	for _, svc := range services {
+		s := strings.ToLower(svc)
+		switch {
+		case strings.Contains(s, "_airplay") || strings.Contains(s, "_raop"):
+			return "altavoz"
+		case strings.Contains(s, "_googlecast") || strings.Contains(s, "_googlezone"):
+			return "altavoz"
+		case strings.Contains(s, "_appletv") || strings.Contains(s, "_mediaremote"):
+			return "tv"
+		case strings.Contains(s, "_ipp") || strings.Contains(s, "_printer") || strings.Contains(s, "_pdl-datastream"):
+			return "iot" // printer
+		case strings.Contains(s, "_hap") || strings.Contains(s, "_homekit"):
+			return "iot"
+		case strings.Contains(s, "_smb") || strings.Contains(s, "_afpovertcp") || strings.Contains(s, "_nfs"):
+			return "servidor"
+		case strings.Contains(s, "_ssh") || strings.Contains(s, "_http") || strings.Contains(s, "_https"):
+			// Too generic — many devices expose SSH/HTTP. Don't classify.
+			continue
+		}
+	}
+	return "desconocido"
+}

+ 42 - 0
server-go/internal/adapters/live.go

@@ -128,6 +128,9 @@ type routerPolled struct {
 	// vlans: VLANs del bridge (issue #315, bridge vlan show). nil = sin
 	// datos (router sin bridge vlan filtering o sonda fallida).
 	vlans []VlanPort
+	// discovery: mDNS services + randomized MACs (#338). nil = sin datos
+	// (umdns no instalado o sonda fallida).
+	discovery *probe.DiscoveryData
 }
 
 // extrasSnapshot es la caché anti-parpadeo por router.
@@ -1590,6 +1593,25 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			}
 		}
 	}
+	// Discovery (#338): aggregate mDNS host-by-IP and random MAC sets from
+	// all polled routers. Used to enrich devices below.
+	mdnsHostByIP := map[string]string{}
+	randomMACs := map[string]bool{}
+	mdnsSvcByHost := map[string][]string{}
+	for _, p := range polled {
+		if p.discovery == nil {
+			continue
+		}
+		for ip, host := range p.discovery.HostByIP {
+			mdnsHostByIP[ip] = host
+		}
+		for _, mac := range p.discovery.RandomMACs {
+			randomMACs[mac] = true
+		}
+		for host, svcs := range p.discovery.Services {
+			mdnsSvcByHost[host] = svcs
+		}
+	}
 	type knownInfo struct {
 		routerID string
 		band     string
@@ -1807,6 +1829,26 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 		// Tipo estimado con reglas deterministas (hostname, huella DHCP y
 		// capacidades LLDP). Con nombre-MAC (sin hostname) queda "desconocido".
 		d.Type = GuessDeviceType(d.Name, d.Manufacturer, vendorClass, clientID, lldpCapsByMac[mac])
+		// mDNS enrichment (#338): resolve hostname from IP → lookup services.
+		if d.IP != "" {
+			if host, ok := mdnsHostByIP[d.IP]; ok {
+				if svcs, ok := mdnsSvcByHost[host]; ok {
+					d.MdnsServices = svcs
+				}
+				// If the device has no name (just MAC), use the mDNS hostname.
+				if d.Name == mac {
+					d.Name = host
+				}
+			}
+		}
+		if randomMACs[mac] {
+			d.RandomMAC = true
+		}
+		// mDNS-based type refinement (#338): if the hostname/DHCP classification
+		// yielded "desconocido" but mDNS services are available, try to classify.
+		if d.Type == "desconocido" && len(d.MdnsServices) > 0 {
+			d.Type = guessFromMdns(d.MdnsServices)
+		}
 		if isSeen {
 			d.RouterID = s.routerID
 			d.Band = s.band

+ 7 - 0
server-go/internal/adapters/types.go

@@ -224,6 +224,13 @@ type Device struct {
 	// "ct" (CT/VM anidado bajo hipervisor), "managed-switch" (switch con gestión
 	// identificado por LLDP — hoy switch-netgear).
 	Infra string `json:"infra,omitempty"` // "hypervisor"|"ct"|"managed-switch"
+	// --- mDNS/SSDP fingerprinting (#338) ---
+	// MdnsServices: mDNS service types advertised by this device (from umdns).
+	// e.g. ["_airplay._tcp", "_raop._tcp"] for an Apple TV.
+	MdnsServices []string `json:"mdnsServices,omitempty"`
+	// RandomMAC: true if the MAC has the locally-administered bit set
+	// (typical of iOS/Android WiFi privacy features).
+	RandomMAC bool `json:"randomMac,omitempty"`
 	// --- extras demo (omitempty = ausentes en live) ---
 	Hostname     string `json:"hostname,omitempty"`
 	DHCPLease    string `json:"dhcpLease,omitempty"`