Browse Source

feat(devices): fall back to reverse DNS for unnamed static hosts

Hosts with a static address never take a DHCP lease, so servers, switches
and access points on fixed IPs show up as bare MACs even when the local DNS
knows their names. When no lease, reservation, alias, override or mDNS name
applies, use the device's forward-confirmed PTR record.

Lookups are asynchronous and cached (1 h, 15 min for misses), so the poll
never waits on DNS. Only private, CGNAT and link-local addresses are looked
up, and PTRs that embed the address (wildcard zones, ip-a-b-c-d) are
skipped. NETPULSE_RDNS=0 turns it off; tests and demo mode never resolve.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
mick 1 tháng trước cách đây
mục cha
commit
b8e2e9128d

+ 4 - 0
server-go/.env.example

@@ -31,6 +31,10 @@ ADGUARD_PASS=
 # interfaz o una lista separada por comas, p. ej. "wg0" o "wg0,wg1") actúa
 # como filtro y solo sondea esas interfaces.
 WG_INTERFACE=auto
+# Reverse DNS fallback for device names: a device nothing else named (no DHCP
+# hostname, reservation, alias or mDNS) takes its forward-confirmed PTR name.
+# Private and link-local addresses only. 0 = off.
+# NETPULSE_RDNS=1
 
 # --- Auto-rearme de agentes (Fase 6.1+) ---
 # 1 = el supervisor rearma automáticamente los agentes cuyo último push

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

@@ -364,6 +364,8 @@ type Live struct {
 	unknownGrace    map[string]int
 	unknownAlerted  map[string]bool
 	unknownGraceNum int // ticks antes de declarar desconocido (default 3, #234)
+	// rdns: reverse DNS fallback for devices nothing else named (rdns.go).
+	rdns *rdnsCache
 	// impostorActive (#1358): BSSID impostor → alertID emitida. Solo en
 	// memoria a propósito: si el server reinicia y el impostor sigue
 	// visible, la alerta se re-emite (seguridad prima sobre re-aviso).
@@ -593,6 +595,11 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 	// #1441: peers marcados como urgentes (persistidos en kv).
 	l.loadWGUrgent()
 	l.SetRouters(initial)
+	// Only a real, non-demo server resolves names: NewLive(nil, ...) in tests
+	// and the demo dataset stay off the network.
+	if cfg != nil && !cfg.DemoMode {
+		l.rdns = newRDNSCache()
+	}
 	return l
 }
 
@@ -3405,6 +3412,12 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 				}
 			}
 		}
+		// Static-IP hosts never take a lease: fall back to their PTR record.
+		if d.Name == mac && d.IP != "" {
+			if host := l.rdns.Name(d.IP); host != "" {
+				d.Name = host
+			}
+		}
 		if randomMACs[mac] {
 			d.RandomMAC = true
 		}

+ 172 - 0
server-go/internal/adapters/rdns.go

@@ -0,0 +1,172 @@
+package adapters
+
+import (
+	"context"
+	"net"
+	"net/netip"
+	"os"
+	"strings"
+	"sync"
+	"time"
+)
+
+// rdns.go — reverse DNS fallback for device names.
+//
+// Hosts with a static address never take a DHCP lease, so a network made of
+// fixed-IP servers, switches and access points shows most of them as bare
+// MACs even when the local DNS already knows every name. When nothing else
+// named a device (lease, reservation, alias, override, mDNS) its PTR record
+// is the last source tried.
+//
+// buildDevices runs on every poll and must never wait on DNS, so lookups are
+// asynchronous: Name answers from the cache and queues a background lookup
+// on a miss; the name shows up on the next poll. Only private and link-local
+// addresses are looked up, so the server does not send PTR queries for
+// public addresses to an upstream resolver. NETPULSE_RDNS=0 turns it off.
+
+const (
+	rdnsTTL         = time.Hour
+	rdnsNegativeTTL = 15 * time.Minute
+	rdnsTimeout     = 3 * time.Second
+	rdnsConcurrency = 4
+)
+
+type rdnsResolver interface {
+	LookupAddr(ctx context.Context, addr string) ([]string, error)
+	LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
+}
+
+type rdnsEntry struct {
+	name    string
+	expires time.Time
+}
+
+type rdnsCache struct {
+	enabled  bool
+	resolver rdnsResolver
+	now      func() time.Time
+
+	mu       sync.Mutex
+	entries  map[string]rdnsEntry
+	inflight map[string]bool
+	sem      chan struct{}
+	wg       sync.WaitGroup
+}
+
+func newRDNSCache() *rdnsCache {
+	c := &rdnsCache{
+		enabled:  true,
+		resolver: net.DefaultResolver,
+		now:      time.Now,
+		entries:  map[string]rdnsEntry{},
+		inflight: map[string]bool{},
+		sem:      make(chan struct{}, rdnsConcurrency),
+	}
+	if v, ok := os.LookupEnv("NETPULSE_RDNS"); ok {
+		switch strings.ToLower(strings.TrimSpace(v)) {
+		case "0", "false", "off", "no":
+			c.enabled = false
+		}
+	}
+	return c
+}
+
+// Name returns the cached PTR name for ip, or "" when there is none yet. A
+// missing or expired entry queues one background lookup.
+func (c *rdnsCache) Name(ip string) string {
+	if c == nil || !c.enabled {
+		return ""
+	}
+	addr, err := netip.ParseAddr(ip)
+	if err != nil || !rdnsEligible(addr) {
+		return ""
+	}
+	key := addr.String()
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	e, ok := c.entries[key]
+	if ok && c.now().Before(e.expires) {
+		return e.name
+	}
+	if !c.inflight[key] {
+		c.inflight[key] = true
+		c.wg.Add(1)
+		go c.resolve(addr)
+	}
+	// A stale name is still better than a MAC while the refresh runs.
+	return e.name
+}
+
+func (c *rdnsCache) resolve(addr netip.Addr) {
+	defer c.wg.Done()
+	c.sem <- struct{}{}
+	defer func() { <-c.sem }()
+	name := c.lookup(addr)
+	ttl := rdnsTTL
+	if name == "" {
+		ttl = rdnsNegativeTTL
+	}
+	key := addr.String()
+	c.mu.Lock()
+	c.entries[key] = rdnsEntry{name: name, expires: c.now().Add(ttl)}
+	delete(c.inflight, key)
+	c.mu.Unlock()
+}
+
+// lookup returns the short name of the first PTR target that resolves back
+// to addr (forward-confirmed), skipping names generated from the address.
+func (c *rdnsCache) lookup(addr netip.Addr) string {
+	ctx, cancel := context.WithTimeout(context.Background(), rdnsTimeout)
+	defer cancel()
+	names, err := c.resolver.LookupAddr(ctx, addr.String())
+	if err != nil {
+		return ""
+	}
+	for _, n := range names {
+		fqdn := strings.TrimSuffix(n, ".")
+		if fqdn == "" || rdnsEmbedsAddr(fqdn, addr) {
+			continue
+		}
+		ips, err := c.resolver.LookupNetIP(ctx, "ip", fqdn)
+		if err != nil {
+			continue
+		}
+		for _, ip := range ips {
+			if ip.Unmap() == addr {
+				return rdnsShortName(fqdn)
+			}
+		}
+	}
+	return ""
+}
+
+// rdnsEligible keeps lookups on the local resolver's own zones: private,
+// shared CGNAT and link-local space only.
+func rdnsEligible(addr netip.Addr) bool {
+	addr = addr.Unmap()
+	if addr.IsPrivate() || addr.IsLinkLocalUnicast() {
+		return true
+	}
+	return rdnsCGNAT.Contains(addr)
+}
+
+var rdnsCGNAT = netip.MustParsePrefix("100.64.0.0/10")
+
+// rdnsEmbedsAddr rejects synthesized PTRs such as "192-168-8-217.example.net"
+// or "ip-10-0-0-5.ec2.internal": they name the address, not the device, and
+// some public wildcard zones answer for private ranges.
+func rdnsEmbedsAddr(fqdn string, addr netip.Addr) bool {
+	host := strings.ToLower(fqdn)
+	s := addr.String()
+	return strings.Contains(host, strings.NewReplacer(".", "-", ":", "-").Replace(s)) ||
+		strings.Contains(host, s)
+}
+
+// rdnsShortName drops the domain, matching the bare hostnames DHCP leases
+// report ("switch-garage.home.arpa" -> "switch-garage").
+func rdnsShortName(fqdn string) string {
+	if i := strings.IndexByte(fqdn, '.'); i > 0 {
+		return fqdn[:i]
+	}
+	return fqdn
+}

+ 59 - 0
server-go/internal/adapters/rdns_builddevices_test.go

@@ -0,0 +1,59 @@
+package adapters
+
+import (
+	"testing"
+	"time"
+)
+
+// TestBuildDevicesNamesFromReverseDNS: a static-IP host seen only in ARP
+// takes its PTR name once the background lookup lands; a device with a
+// DHCP hostname keeps it and is never looked up.
+func TestBuildDevicesNamesFromReverseDNS(t *testing.T) {
+	f := &fakeRDNS{
+		ptr: map[string][]string{
+			"172.16.16.4":  {"switch-garage.home.arpa."},
+			"172.16.16.70": {"should-not-win.home.arpa."},
+		},
+		forward: map[string][]string{
+			"switch-garage.home.arpa":  {"172.16.16.4"},
+			"should-not-win.home.arpa": {"172.16.16.70"},
+		},
+	}
+	l := NewLive(nil, nil, nil, nil)
+	l.rdns = newTestRDNS(f, time.Now)
+	polled := map[string]*routerPolled{
+		"gw": {
+			cfg: RouterConfig{ID: "gw", Name: "Gateway", Host: "172.16.16.1", IsGateway: true},
+			arp: map[string]string{
+				"5C:E2:8C:00:00:04": "172.16.16.4",
+			},
+			leases: []DhcpLease{
+				{MAC: "AA:BB:CC:00:00:70", IP: "172.16.16.70", Hostname: "laptop"},
+			},
+		},
+	}
+	byMAC := func(devs []Device) map[string]Device {
+		m := map[string]Device{}
+		for _, d := range devs {
+			m[d.MAC] = d
+		}
+		return m
+	}
+
+	first := byMAC(l.buildDevices(polled, ""))
+	if got := first["5C:E2:8C:00:00:04"].Name; got != "5C:E2:8C:00:00:04" {
+		t.Fatalf("first poll must not wait on DNS: got %q", got)
+	}
+	l.rdns.wg.Wait()
+
+	devs := byMAC(l.buildDevices(polled, ""))
+	if got := devs["5C:E2:8C:00:00:04"].Name; got != "switch-garage" {
+		t.Fatalf("static host: got %q, want switch-garage", got)
+	}
+	if got := devs["AA:BB:CC:00:00:70"].Name; got != "laptop" {
+		t.Fatalf("leased host: got %q, want laptop", got)
+	}
+	if n := f.count("172.16.16.70"); n != 0 {
+		t.Fatalf("named device was looked up %d times", n)
+	}
+}

+ 181 - 0
server-go/internal/adapters/rdns_test.go

@@ -0,0 +1,181 @@
+package adapters
+
+import (
+	"context"
+	"errors"
+	"net/netip"
+	"sync"
+	"testing"
+	"time"
+)
+
+type fakeRDNS struct {
+	mu      sync.Mutex
+	ptr     map[string][]string
+	forward map[string][]string
+	calls   map[string]int
+}
+
+func (f *fakeRDNS) LookupAddr(_ context.Context, addr string) ([]string, error) {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	if f.calls == nil {
+		f.calls = map[string]int{}
+	}
+	f.calls[addr]++
+	if names, ok := f.ptr[addr]; ok {
+		return names, nil
+	}
+	return nil, errors.New("no such host")
+}
+
+func (f *fakeRDNS) LookupNetIP(_ context.Context, _, host string) ([]netip.Addr, error) {
+	ips, ok := f.forward[host]
+	if !ok {
+		return nil, errors.New("no such host")
+	}
+	out := []netip.Addr{}
+	for _, s := range ips {
+		out = append(out, netip.MustParseAddr(s))
+	}
+	return out, nil
+}
+
+func (f *fakeRDNS) count(addr string) int {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	return f.calls[addr]
+}
+
+func newTestRDNS(f *fakeRDNS, now func() time.Time) *rdnsCache {
+	c := newRDNSCache()
+	c.enabled = true
+	c.resolver = f
+	c.now = now
+	return c
+}
+
+// resolved asks once (queues the lookup), waits for it, and asks again.
+func resolved(c *rdnsCache, ip string) string {
+	if n := c.Name(ip); n != "" {
+		return n
+	}
+	c.wg.Wait()
+	return c.Name(ip)
+}
+
+func TestRDNSName(t *testing.T) {
+	f := &fakeRDNS{
+		ptr: map[string][]string{
+			"172.16.16.4":   {"switch-garage.home.arpa."},
+			"172.16.17.202": {"pihole.home.arpa."},
+			"192.168.8.217": {"192-168-8-217.0a1b2c3d4e5f.stremio.rocks."},
+			"10.0.0.5":      {"ip-10-0-0-5.ec2.internal."},
+			"172.16.16.30":  {"stale.home.arpa."},
+			"172.16.16.31":  {"printer-ptr-only."},
+			"172.16.16.40":  {"192-168-8-217.example.net.", "nas.home.arpa."},
+			"fd00::10":      {"nas6.home.arpa."},
+			"203.0.113.1":   {"gateway.isp.example."},
+		},
+		forward: map[string][]string{
+			"switch-garage.home.arpa":                  {"172.16.16.4"},
+			"pihole.home.arpa":                         {"172.16.17.202"},
+			"192-168-8-217.0a1b2c3d4e5f.stremio.rocks": {"192.168.8.217"},
+			"ip-10-0-0-5.ec2.internal":                 {"10.0.0.5"},
+			"stale.home.arpa":                          {"172.16.16.99"},
+			"nas.home.arpa":                            {"172.16.16.40"},
+			"nas6.home.arpa":                           {"fd00::10"},
+			"gateway.isp.example":                      {"203.0.113.1"},
+		},
+	}
+	c := newTestRDNS(f, time.Now)
+	cases := []struct {
+		ip, want, why string
+	}{
+		{"172.16.16.4", "switch-garage", "static switch, forward-confirmed"},
+		{"172.16.17.202", "pihole", "static container"},
+		{"192.168.8.217", "", "wildcard PTR that embeds the address"},
+		{"10.0.0.5", "", "cloud-style ip-a-b-c-d name"},
+		{"172.16.16.30", "", "PTR that does not resolve back"},
+		{"172.16.16.31", "", "PTR target with no forward record"},
+		{"172.16.16.40", "nas", "skips the synthesized name, takes the real one"},
+		{"fd00::10", "nas6", "IPv6 ULA"},
+		{"203.0.113.1", "", "public address is never looked up"},
+		{"172.16.16.50", "", "no PTR at all"},
+		{"not-an-ip", "", "garbage input"},
+	}
+	for _, tc := range cases {
+		if got := resolved(c, tc.ip); got != tc.want {
+			t.Errorf("%s (%s): got %q, want %q", tc.ip, tc.why, got, tc.want)
+		}
+	}
+	if n := f.count("203.0.113.1"); n != 0 {
+		t.Errorf("public address was looked up %d times", n)
+	}
+}
+
+func TestRDNSCachesAndExpires(t *testing.T) {
+	f := &fakeRDNS{
+		ptr:     map[string][]string{"172.16.16.4": {"switch-garage.home.arpa."}},
+		forward: map[string][]string{"switch-garage.home.arpa": {"172.16.16.4"}},
+	}
+	now := time.Unix(1_800_000_000, 0)
+	c := newTestRDNS(f, func() time.Time { return now })
+
+	if got := c.Name("172.16.16.4"); got != "" {
+		t.Fatalf("first call must not block on DNS, got %q", got)
+	}
+	c.wg.Wait()
+	for i := 0; i < 5; i++ {
+		if got := c.Name("172.16.16.4"); got != "switch-garage" {
+			t.Fatalf("cached name: got %q", got)
+		}
+	}
+	if n := f.count("172.16.16.4"); n != 1 {
+		t.Fatalf("lookups within TTL: got %d, want 1", n)
+	}
+
+	// After the TTL the stale name keeps showing while one refresh runs.
+	now = now.Add(rdnsTTL + time.Second)
+	if got := c.Name("172.16.16.4"); got != "switch-garage" {
+		t.Fatalf("stale name during refresh: got %q", got)
+	}
+	c.wg.Wait()
+	if n := f.count("172.16.16.4"); n != 2 {
+		t.Fatalf("lookups after TTL: got %d, want 2", n)
+	}
+}
+
+func TestRDNSNegativeCache(t *testing.T) {
+	f := &fakeRDNS{}
+	now := time.Unix(1_800_000_000, 0)
+	c := newTestRDNS(f, func() time.Time { return now })
+	resolved(c, "172.16.16.50")
+	resolved(c, "172.16.16.50")
+	if n := f.count("172.16.16.50"); n != 1 {
+		t.Fatalf("misses within negative TTL: got %d lookups, want 1", n)
+	}
+	now = now.Add(rdnsNegativeTTL + time.Second)
+	resolved(c, "172.16.16.50")
+	if n := f.count("172.16.16.50"); n != 2 {
+		t.Fatalf("after negative TTL: got %d lookups, want 2", n)
+	}
+}
+
+func TestRDNSDisabled(t *testing.T) {
+	t.Setenv("NETPULSE_RDNS", "0")
+	c := newRDNSCache()
+	f := &fakeRDNS{ptr: map[string][]string{"172.16.16.4": {"switch-garage.home.arpa."}}}
+	c.resolver = f
+	if got := c.Name("172.16.16.4"); got != "" {
+		t.Fatalf("disabled cache returned %q", got)
+	}
+	c.wg.Wait()
+	if n := f.count("172.16.16.4"); n != 0 {
+		t.Fatalf("disabled cache looked up %d times", n)
+	}
+	var nilCache *rdnsCache
+	if got := nilCache.Name("172.16.16.4"); got != "" {
+		t.Fatalf("nil cache returned %q", got)
+	}
+}