| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458 |
- // 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://<ip>/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,
- "ubus call system board | jsonfilter -e @.model",
- )
- 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
- }
|