// Package discover — descubrimiento de routers candidatos en la LAN // (paridad src/discover.js, SPEC §7.7): // 1. Subred /24 derivada del gateway por defecto (`ip route`). // 2. Barrido TCP del puerto 22 en los 254 hosts (concurrencia 100; NO ping). // 3. Firma OpenWrt: POST http:///ubus (cualquier JSON-RPC, incluso // "access denied", delata uhttpd+ubus; GL.iNet redirige a su UI → firma // gl-ui por https). // 4. Probe SSH con la clave propia → {authorized, model}. // // Caché de 60 s (force=1 la ignora). package discover import ( "bytes" "context" "crypto/tls" "database/sql" "io" "log" "net" "net/http" "os/exec" "regexp" "sort" "strings" "sync" "time" "github.com/gnacho/netpulse/server-go/internal/adapters" "github.com/gnacho/netpulse/server-go/internal/routerstore" "github.com/gnacho/netpulse/server-go/internal/sshkey" ) const ( cacheMS = 60_000 tcpTimeout = 800 * time.Millisecond httpTimeout = 1500 * time.Millisecond sshTimeout = 4 * time.Second scanWorkers = 100 probeWorkers = 16 ) // hostKey normaliza una referencia de unidad: minúsculas, sin puerto y sin el // punto final de un FQDN. El barrido trabaja con IPs y el alta permite escribir // nombres, así que sin normalizar la misma unidad tiene dos claves distintas. func hostKey(h string) string { h = strings.TrimSpace(strings.ToLower(h)) if h == "" { return "" } if host, _, err := net.SplitHostPort(h); err == nil { h = host } return strings.TrimSuffix(h, ".") } // configuredIndex: claves bajo las que una unidad ya dada de alta puede // aparecer en el barrido (#1895). Además de la cadena literal se resuelven los // nombres a IP, porque un AP configurado como "ap.lan" aparece en el barrido // como 192.168.1.2. lookup es inyectable para tests; nil usa net.Resolver. func configuredIndex(ctx context.Context, routers []adapters.RouterConfig, lookup func(context.Context, string) ([]string, error)) map[string]bool { if lookup == nil { res := &net.Resolver{} lookup = res.LookupHost } out := map[string]bool{} for _, r := range routers { key := hostKey(r.Host) if key == "" { continue } out[key] = true if net.ParseIP(key) != nil { continue } // Resolver es best-effort y acotado: un nombre que ya no resuelve no // debe frenar el barrido ni marcar nada como configurado. rctx, cancel := context.WithTimeout(ctx, 2*time.Second) addrs, err := lookup(rctx, key) cancel() if err != nil { continue } for _, a := range addrs { out[hostKey(a)] = true } } return out } // Result es un candidato a router. type Result struct { Host string `json:"host"` Hostname string `json:"hostname,omitempty"` IsGateway bool `json:"isGateway"` Authorized bool `json:"authorized"` Model *string `json:"model"` Configured bool `json:"configured"` } // Response es la respuesta de /api/config/discover. type Response struct { At int64 `json:"at,omitempty"` // la respuesta no_gateway de Node NO incluye `at` Subnet *string `json:"subnet"` Results []Result `json:"results"` Cached bool `json:"cached"` Error string `json:"error,omitempty"` } var ( cacheMu sync.Mutex cache Response ) // tcpOpen: true si el puerto TCP responde antes del timeout. // Respeta ctx: DialContext aborta el intento en cuanto ctx se cancela. func tcpOpen(ctx context.Context, host string, port int, timeout time.Duration) bool { d := net.Dialer{Timeout: timeout} conn, err := d.DialContext(ctx, "tcp", net.JoinHostPort(host, itoa(port))) if err != nil { return false } _ = conn.Close() return true } func itoa(n int) string { var buf [4]byte i := len(buf) for n > 0 { i-- buf[i] = byte('0' + n%10) n /= 10 } return string(buf[i:]) } // pool ejecuta fn sobre items con concurrencia limitada. // Los workers comprueban ctx.Err() antes de tomar cada item: si el contexto // se cancela (p.ej. el cliente cerró la request HTTP), dejan de aceptar trabajo // y pool devuelve lo recolectado hasta ese momento. func pool[T any](ctx context.Context, items []T, size int, fn func(T) *T) []*T { out := make([]*T, len(items)) var idx int64 var mu sync.Mutex var wg sync.WaitGroup workers := size if len(items) < workers { workers = len(items) } for w := 0; w < workers; w++ { wg.Add(1) go func() { defer wg.Done() for { if ctx.Err() != nil { return } mu.Lock() if idx >= int64(len(items)) { mu.Unlock() return } i := idx idx++ mu.Unlock() out[i] = fn(items[i]) } }() } wg.Wait() res := make([]*T, 0, len(out)) for _, r := range out { if r != nil { res = append(res, r) } } return res } func httpClient() *http.Client { return &http.Client{ Timeout: httpTimeout, Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // firma, no confianza DisableKeepAlives: true, MaxConnsPerHost: 1, TLSHandshakeTimeout: httpTimeout, }, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse // necesitamos el status crudo (301/302) }, } } type probeResp struct { status int body string } var ubusProbeBody = `{"jsonrpc":"2.0","id":1,"method":"call","params":["00000000000000000000000000000000","session","login",{"username":"netpulse-probe","password":""}]}` // postUbus: POST /ubus crudo (http u https) — {status, body} o nil. func postUbus(ctx context.Context, host string, useHTTPS bool) *probeResp { scheme := "http" port := "80" if useHTTPS { scheme = "https" port = "443" } req, err := http.NewRequestWithContext(ctx, "POST", scheme+"://"+host+":"+port+"/ubus", bytes.NewReader([]byte(ubusProbeBody))) if err != nil { return nil } req.Header.Set("Content-Type", "application/json") res, err := httpClient().Do(req) if err != nil { return nil } defer res.Body.Close() body, _ := io.ReadAll(io.LimitReader(res.Body, 8192)) return &probeResp{status: res.StatusCode, body: string(body)} } // getRoot: GET / (http/https) — {status, body} o nil. func getRoot(ctx context.Context, host string, useHTTPS bool) *probeResp { scheme := "http" port := "80" if useHTTPS { scheme = "https" port = "443" } req, err := http.NewRequestWithContext(ctx, "GET", scheme+"://"+host+":"+port+"/", nil) if err != nil { return nil } res, err := httpClient().Do(req) if err != nil { return nil } defer res.Body.Close() body, _ := io.ReadAll(io.LimitReader(res.Body, 16384)) return &probeResp{status: res.StatusCode, body: string(body)} } var glUIRe = regexp.MustCompile(`(?i)gl-ui|GL\.iNet|glinet`) // probeUbus: true si el host huele a OpenWrt/GL.iNet. func probeUbus(ctx context.Context, host string) bool { isUbus := func(r *probeResp) bool { return r != nil && (strings.Contains(r.body, "jsonrpc") || strings.Contains(r.body, "ubus_rpc_session")) } httpRes := postUbus(ctx, host, false) if isUbus(httpRes) { return true } if httpRes != nil && (httpRes.status == 301 || httpRes.status == 302 || httpRes.status == 307 || httpRes.status == 308) { if isUbus(postUbus(ctx, host, true)) { return true } if root := getRoot(ctx, host, true); root != nil && glUIRe.MatchString(root.body) { return true } } return false } // probeSsh prueba SSH con la clave propia; devuelve (authorized, model). // exec.CommandContext mata el proceso ssh si ctx se cancela (además del // timeout propio de sshTimeout), así la cancelación de la request HTTP // libera el worker sin esperar al timeout de 4 s. func probeSsh(ctx context.Context, host, keyPath string) (bool, *string) { args := append(sshkey.BaseArgs(keyPath), "-o", "ConnectTimeout=2", "-o", "ControlMaster=no", "root@"+host, // #2122: jsonfilter sale distinto de cero cuando el path no existe // (los x86/64 no traen `model` en el board), y eso se leía como "clave // no autorizada" aunque la sesión hubiera autenticado. Lo que decide // es ssh: si conectó y ejecutó, la clave vale. Sin modelo, el // candidato se queda con su IP o su hostname. "ubus call system board | jsonfilter -e @.model || true", ) cmd := exec.CommandContext(ctx, "ssh", args...) type result struct { out []byte err error } ch := make(chan result, 1) go func() { out, err := cmd.Output() ch <- result{out, err} }() select { case <-ctx.Done(): _ = cmd.Process.Kill() return false, nil case <-time.After(sshTimeout): _ = cmd.Process.Kill() return false, nil case res := <-ch: if res.err != nil { return false, nil } model := strings.TrimSpace(string(res.out)) if model == "" { return true, nil } return true, &model } } // reverseHostname intenta obtener el FQDN de una IP y validarlo con DNS // directo. Devuelve el hostname (sin punto final) o cadena vacía. func reverseHostname(ip string) string { names, err := net.LookupAddr(ip) if err != nil || len(names) == 0 { return "" } for _, n := range names { // Solo devolver nombres que resuelven de vuelta a la IP (evita // fallback genéricos de PTR mal configurados). ips, lerr := net.LookupIP(n) if lerr != nil { continue } for _, resolved := range ips { if resolved.String() == ip { return strings.TrimSuffix(n, ".") } } } return "" } // selfIPs: IPs propias del servidor (para excluirlas del barrido). func selfIPs() map[string]bool { out, err := exec.Command("sh", "-c", `ip -o -4 addr show | grep -oP "inet \K[0-9.]+"`).Output() ips := map[string]bool{} if err != nil { return ips } for _, l := range strings.Split(string(out), "\n") { if l = strings.TrimSpace(l); l != "" { ips[l] = true } } return ips } // Routers escanea la LAN y devuelve candidatos (paridad discoverRouters). // db se usa solo para marcar los ya configurados. // // ctx permite cancelar el barrido en vuelo: cuando el cliente cierra la // request HTTP, los workers dejan de tomar items y las probes en curso // (TCP/HTTP/SSH) abortan vía DialContext / NewRequestWithContext / // CommandContext. Si ctx se cancela, Routers devuelve una Response con // Error="cancelled" SIN pisar la caché (no se quiere guardar un barrido // parcial). El siguiente llamador podrá reintentar o usar la caché previa. func Routers(ctx context.Context, db *sql.DB, keyPath string, force bool) Response { cacheMu.Lock() defer cacheMu.Unlock() now := time.Now().UnixMilli() if !force && now-cache.At < cacheMS { c := cache c.Cached = true return c } gwIP := routerstore.DetectGatewayIP() if gwIP == "" { return Response{Subnet: nil, Results: []Result{}, Cached: false, Error: "no_gateway"} } parts := strings.Split(gwIP, ".") prefix := strings.Join(parts[:3], ".") subnet := prefix + ".0/24" own := selfIPs() hosts := make([]string, 0, 254) for i := 1; i <= 254; i++ { h := prefix + "." + itoa(i) if !own[h] { hosts = append(hosts, h) } } alive := pool(ctx, hosts, scanWorkers, func(h string) *string { if tcpOpen(ctx, h, 22, tcpTimeout) { return &h } return nil }) if ctx.Err() != nil { return Response{Subnet: &subnet, Results: []Result{}, Cached: false, Error: "cancelled"} } // #1893: el barrido abre y cierra TCP/22 en todo el /24 sin autenticar, que // en dropbear aparece como "Exit before auth". Una sola línea por barrido // basta para atribuir ese tráfico (y descartar que sea un sondeo de flota). log.Printf("[netpulse:discover] sweep %s: %d of %d hosts with port 22 open", subnet, len(alive), len(hosts)) // #1895: "ya añadido" no puede ser una comparación de cadenas en crudo. El // alta admite un nombre DNS o una IP con puerto y el barrido solo ve IPs, // así que un AP configurado como "ap.lan" se ofrecía como nuevo mientras // el gateway, configurado por IP, sí se marcaba. configured := configuredIndex(ctx, routerstore.ListRouters(db), nil) type candidate struct{ h string } cands := make([]candidate, 0, len(alive)) for _, h := range alive { cands = append(cands, candidate{*h}) } found := pool(ctx, cands, probeWorkers, func(c candidate) *candidate { if !probeUbus(ctx, c.h) { return nil } return &c }) if ctx.Err() != nil { return Response{Subnet: &subnet, Results: []Result{}, Cached: false, Error: "cancelled"} } results := make([]Result, 0, len(found)) for _, c := range found { if ctx.Err() != nil { return Response{Subnet: &subnet, Results: []Result{}, Cached: false, Error: "cancelled"} } authorized, model := probeSsh(ctx, c.h, keyPath) // #1893: deja rastro del probe openssh (una conexión TCP/22 por host), que // de otro modo no aparece en el log del servidor. log.Printf("[netpulse:ssh] %s: probe openssh autorizado=%v", c.h, authorized) if authorized { // Issue #651: pinar TODAS las host keys del router en known_hosts. // El probe openssh (accept-new) solo registra la clave negociada // (ed25519); el pool Go negocia otra (ecdsa/rsa), así que un host // con varias host keys daba falso "host key changed" al probar a // sondearlo. Bombear todas las keys evita el falso positivo sin // debilitar la protección anti-MITM (#603): no se acepta una // identidad con todas las claves cambiadas. if err := sshkey.PinHostKeys(c.h, keyPath); err != nil { log.Printf("[netpulse:discover] pin host keys %s: %v", c.h, err) } } hostname := "" if authorized { hostname = reverseHostname(c.h) } results = append(results, Result{ Host: c.h, Hostname: hostname, IsGateway: c.h == gwIP, Authorized: authorized, Model: model, Configured: configured[hostKey(c.h)] || (hostname != "" && configured[hostKey(hostname)]), }) } sort.Slice(results, func(i, j int) bool { if results[i].IsGateway != results[j].IsGateway { return results[i].IsGateway } return results[i].Host < results[j].Host }) cache = Response{At: now, Subnet: &subnet, Results: results, Cached: false} return cache }