discover.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // Package discover — descubrimiento de routers candidatos en la LAN
  2. // (paridad src/discover.js, SPEC §7.7):
  3. // 1. Subred /24 derivada del gateway por defecto (`ip route`).
  4. // 2. Barrido TCP del puerto 22 en los 254 hosts (concurrencia 100; NO ping).
  5. // 3. Firma OpenWrt: POST http://<ip>/ubus (cualquier JSON-RPC, incluso
  6. // "access denied", delata uhttpd+ubus; GL.iNet redirige a su UI → firma
  7. // gl-ui por https).
  8. // 4. Probe SSH con la clave propia → {authorized, model}.
  9. //
  10. // Caché de 60 s (force=1 la ignora).
  11. package discover
  12. import (
  13. "bytes"
  14. "context"
  15. "crypto/tls"
  16. "database/sql"
  17. "io"
  18. "log"
  19. "net"
  20. "net/http"
  21. "os/exec"
  22. "regexp"
  23. "sort"
  24. "strings"
  25. "sync"
  26. "time"
  27. "github.com/gnacho/netpulse/server-go/internal/adapters"
  28. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  29. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  30. )
  31. const (
  32. cacheMS = 60_000
  33. tcpTimeout = 800 * time.Millisecond
  34. httpTimeout = 1500 * time.Millisecond
  35. sshTimeout = 4 * time.Second
  36. scanWorkers = 100
  37. probeWorkers = 16
  38. )
  39. // hostKey normaliza una referencia de unidad: minúsculas, sin puerto y sin el
  40. // punto final de un FQDN. El barrido trabaja con IPs y el alta permite escribir
  41. // nombres, así que sin normalizar la misma unidad tiene dos claves distintas.
  42. func hostKey(h string) string {
  43. h = strings.TrimSpace(strings.ToLower(h))
  44. if h == "" {
  45. return ""
  46. }
  47. if host, _, err := net.SplitHostPort(h); err == nil {
  48. h = host
  49. }
  50. return strings.TrimSuffix(h, ".")
  51. }
  52. // configuredIndex: claves bajo las que una unidad ya dada de alta puede
  53. // aparecer en el barrido (#1895). Además de la cadena literal se resuelven los
  54. // nombres a IP, porque un AP configurado como "ap.lan" aparece en el barrido
  55. // como 192.168.1.2. lookup es inyectable para tests; nil usa net.Resolver.
  56. func configuredIndex(ctx context.Context, routers []adapters.RouterConfig, lookup func(context.Context, string) ([]string, error)) map[string]bool {
  57. if lookup == nil {
  58. res := &net.Resolver{}
  59. lookup = res.LookupHost
  60. }
  61. out := map[string]bool{}
  62. for _, r := range routers {
  63. key := hostKey(r.Host)
  64. if key == "" {
  65. continue
  66. }
  67. out[key] = true
  68. if net.ParseIP(key) != nil {
  69. continue
  70. }
  71. // Resolver es best-effort y acotado: un nombre que ya no resuelve no
  72. // debe frenar el barrido ni marcar nada como configurado.
  73. rctx, cancel := context.WithTimeout(ctx, 2*time.Second)
  74. addrs, err := lookup(rctx, key)
  75. cancel()
  76. if err != nil {
  77. continue
  78. }
  79. for _, a := range addrs {
  80. out[hostKey(a)] = true
  81. }
  82. }
  83. return out
  84. }
  85. // Result es un candidato a router.
  86. type Result struct {
  87. Host string `json:"host"`
  88. Hostname string `json:"hostname,omitempty"`
  89. IsGateway bool `json:"isGateway"`
  90. Authorized bool `json:"authorized"`
  91. Model *string `json:"model"`
  92. Configured bool `json:"configured"`
  93. }
  94. // Response es la respuesta de /api/config/discover.
  95. type Response struct {
  96. At int64 `json:"at,omitempty"` // la respuesta no_gateway de Node NO incluye `at`
  97. Subnet *string `json:"subnet"`
  98. Results []Result `json:"results"`
  99. Cached bool `json:"cached"`
  100. Error string `json:"error,omitempty"`
  101. }
  102. var (
  103. cacheMu sync.Mutex
  104. cache Response
  105. )
  106. // tcpOpen: true si el puerto TCP responde antes del timeout.
  107. // Respeta ctx: DialContext aborta el intento en cuanto ctx se cancela.
  108. func tcpOpen(ctx context.Context, host string, port int, timeout time.Duration) bool {
  109. d := net.Dialer{Timeout: timeout}
  110. conn, err := d.DialContext(ctx, "tcp", net.JoinHostPort(host, itoa(port)))
  111. if err != nil {
  112. return false
  113. }
  114. _ = conn.Close()
  115. return true
  116. }
  117. func itoa(n int) string {
  118. var buf [4]byte
  119. i := len(buf)
  120. for n > 0 {
  121. i--
  122. buf[i] = byte('0' + n%10)
  123. n /= 10
  124. }
  125. return string(buf[i:])
  126. }
  127. // pool ejecuta fn sobre items con concurrencia limitada.
  128. // Los workers comprueban ctx.Err() antes de tomar cada item: si el contexto
  129. // se cancela (p.ej. el cliente cerró la request HTTP), dejan de aceptar trabajo
  130. // y pool devuelve lo recolectado hasta ese momento.
  131. func pool[T any](ctx context.Context, items []T, size int, fn func(T) *T) []*T {
  132. out := make([]*T, len(items))
  133. var idx int64
  134. var mu sync.Mutex
  135. var wg sync.WaitGroup
  136. workers := size
  137. if len(items) < workers {
  138. workers = len(items)
  139. }
  140. for w := 0; w < workers; w++ {
  141. wg.Add(1)
  142. go func() {
  143. defer wg.Done()
  144. for {
  145. if ctx.Err() != nil {
  146. return
  147. }
  148. mu.Lock()
  149. if idx >= int64(len(items)) {
  150. mu.Unlock()
  151. return
  152. }
  153. i := idx
  154. idx++
  155. mu.Unlock()
  156. out[i] = fn(items[i])
  157. }
  158. }()
  159. }
  160. wg.Wait()
  161. res := make([]*T, 0, len(out))
  162. for _, r := range out {
  163. if r != nil {
  164. res = append(res, r)
  165. }
  166. }
  167. return res
  168. }
  169. func httpClient() *http.Client {
  170. return &http.Client{
  171. Timeout: httpTimeout,
  172. Transport: &http.Transport{
  173. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // firma, no confianza
  174. DisableKeepAlives: true,
  175. MaxConnsPerHost: 1,
  176. TLSHandshakeTimeout: httpTimeout,
  177. },
  178. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  179. return http.ErrUseLastResponse // necesitamos el status crudo (301/302)
  180. },
  181. }
  182. }
  183. type probeResp struct {
  184. status int
  185. body string
  186. }
  187. var ubusProbeBody = `{"jsonrpc":"2.0","id":1,"method":"call","params":["00000000000000000000000000000000","session","login",{"username":"netpulse-probe","password":""}]}`
  188. // postUbus: POST /ubus crudo (http u https) — {status, body} o nil.
  189. func postUbus(ctx context.Context, host string, useHTTPS bool) *probeResp {
  190. scheme := "http"
  191. port := "80"
  192. if useHTTPS {
  193. scheme = "https"
  194. port = "443"
  195. }
  196. req, err := http.NewRequestWithContext(ctx, "POST", scheme+"://"+host+":"+port+"/ubus", bytes.NewReader([]byte(ubusProbeBody)))
  197. if err != nil {
  198. return nil
  199. }
  200. req.Header.Set("Content-Type", "application/json")
  201. res, err := httpClient().Do(req)
  202. if err != nil {
  203. return nil
  204. }
  205. defer res.Body.Close()
  206. body, _ := io.ReadAll(io.LimitReader(res.Body, 8192))
  207. return &probeResp{status: res.StatusCode, body: string(body)}
  208. }
  209. // getRoot: GET / (http/https) — {status, body} o nil.
  210. func getRoot(ctx context.Context, host string, useHTTPS bool) *probeResp {
  211. scheme := "http"
  212. port := "80"
  213. if useHTTPS {
  214. scheme = "https"
  215. port = "443"
  216. }
  217. req, err := http.NewRequestWithContext(ctx, "GET", scheme+"://"+host+":"+port+"/", nil)
  218. if err != nil {
  219. return nil
  220. }
  221. res, err := httpClient().Do(req)
  222. if err != nil {
  223. return nil
  224. }
  225. defer res.Body.Close()
  226. body, _ := io.ReadAll(io.LimitReader(res.Body, 16384))
  227. return &probeResp{status: res.StatusCode, body: string(body)}
  228. }
  229. var glUIRe = regexp.MustCompile(`(?i)gl-ui|GL\.iNet|glinet`)
  230. // probeUbus: true si el host huele a OpenWrt/GL.iNet.
  231. func probeUbus(ctx context.Context, host string) bool {
  232. isUbus := func(r *probeResp) bool {
  233. return r != nil && (strings.Contains(r.body, "jsonrpc") || strings.Contains(r.body, "ubus_rpc_session"))
  234. }
  235. httpRes := postUbus(ctx, host, false)
  236. if isUbus(httpRes) {
  237. return true
  238. }
  239. if httpRes != nil && (httpRes.status == 301 || httpRes.status == 302 || httpRes.status == 307 || httpRes.status == 308) {
  240. if isUbus(postUbus(ctx, host, true)) {
  241. return true
  242. }
  243. if root := getRoot(ctx, host, true); root != nil && glUIRe.MatchString(root.body) {
  244. return true
  245. }
  246. }
  247. return false
  248. }
  249. // probeSsh prueba SSH con la clave propia; devuelve (authorized, model).
  250. // exec.CommandContext mata el proceso ssh si ctx se cancela (además del
  251. // timeout propio de sshTimeout), así la cancelación de la request HTTP
  252. // libera el worker sin esperar al timeout de 4 s.
  253. func probeSsh(ctx context.Context, host, keyPath string) (bool, *string) {
  254. args := append(sshkey.BaseArgs(keyPath),
  255. "-o", "ConnectTimeout=2",
  256. "-o", "ControlMaster=no",
  257. "root@"+host,
  258. "ubus call system board | jsonfilter -e @.model",
  259. )
  260. cmd := exec.CommandContext(ctx, "ssh", args...)
  261. type result struct {
  262. out []byte
  263. err error
  264. }
  265. ch := make(chan result, 1)
  266. go func() {
  267. out, err := cmd.Output()
  268. ch <- result{out, err}
  269. }()
  270. select {
  271. case <-ctx.Done():
  272. _ = cmd.Process.Kill()
  273. return false, nil
  274. case <-time.After(sshTimeout):
  275. _ = cmd.Process.Kill()
  276. return false, nil
  277. case res := <-ch:
  278. if res.err != nil {
  279. return false, nil
  280. }
  281. model := strings.TrimSpace(string(res.out))
  282. if model == "" {
  283. return true, nil
  284. }
  285. return true, &model
  286. }
  287. }
  288. // reverseHostname intenta obtener el FQDN de una IP y validarlo con DNS
  289. // directo. Devuelve el hostname (sin punto final) o cadena vacía.
  290. func reverseHostname(ip string) string {
  291. names, err := net.LookupAddr(ip)
  292. if err != nil || len(names) == 0 {
  293. return ""
  294. }
  295. for _, n := range names {
  296. // Solo devolver nombres que resuelven de vuelta a la IP (evita
  297. // fallback genéricos de PTR mal configurados).
  298. ips, lerr := net.LookupIP(n)
  299. if lerr != nil {
  300. continue
  301. }
  302. for _, resolved := range ips {
  303. if resolved.String() == ip {
  304. return strings.TrimSuffix(n, ".")
  305. }
  306. }
  307. }
  308. return ""
  309. }
  310. // selfIPs: IPs propias del servidor (para excluirlas del barrido).
  311. func selfIPs() map[string]bool {
  312. out, err := exec.Command("sh", "-c", `ip -o -4 addr show | grep -oP "inet \K[0-9.]+"`).Output()
  313. ips := map[string]bool{}
  314. if err != nil {
  315. return ips
  316. }
  317. for _, l := range strings.Split(string(out), "\n") {
  318. if l = strings.TrimSpace(l); l != "" {
  319. ips[l] = true
  320. }
  321. }
  322. return ips
  323. }
  324. // Routers escanea la LAN y devuelve candidatos (paridad discoverRouters).
  325. // db se usa solo para marcar los ya configurados.
  326. //
  327. // ctx permite cancelar el barrido en vuelo: cuando el cliente cierra la
  328. // request HTTP, los workers dejan de tomar items y las probes en curso
  329. // (TCP/HTTP/SSH) abortan vía DialContext / NewRequestWithContext /
  330. // CommandContext. Si ctx se cancela, Routers devuelve una Response con
  331. // Error="cancelled" SIN pisar la caché (no se quiere guardar un barrido
  332. // parcial). El siguiente llamador podrá reintentar o usar la caché previa.
  333. func Routers(ctx context.Context, db *sql.DB, keyPath string, force bool) Response {
  334. cacheMu.Lock()
  335. defer cacheMu.Unlock()
  336. now := time.Now().UnixMilli()
  337. if !force && now-cache.At < cacheMS {
  338. c := cache
  339. c.Cached = true
  340. return c
  341. }
  342. gwIP := routerstore.DetectGatewayIP()
  343. if gwIP == "" {
  344. return Response{Subnet: nil, Results: []Result{}, Cached: false, Error: "no_gateway"}
  345. }
  346. parts := strings.Split(gwIP, ".")
  347. prefix := strings.Join(parts[:3], ".")
  348. subnet := prefix + ".0/24"
  349. own := selfIPs()
  350. hosts := make([]string, 0, 254)
  351. for i := 1; i <= 254; i++ {
  352. h := prefix + "." + itoa(i)
  353. if !own[h] {
  354. hosts = append(hosts, h)
  355. }
  356. }
  357. alive := pool(ctx, hosts, scanWorkers, func(h string) *string {
  358. if tcpOpen(ctx, h, 22, tcpTimeout) {
  359. return &h
  360. }
  361. return nil
  362. })
  363. if ctx.Err() != nil {
  364. return Response{Subnet: &subnet, Results: []Result{}, Cached: false, Error: "cancelled"}
  365. }
  366. // #1893: el barrido abre y cierra TCP/22 en todo el /24 sin autenticar, que
  367. // en dropbear aparece como "Exit before auth". Una sola línea por barrido
  368. // basta para atribuir ese tráfico (y descartar que sea un sondeo de flota).
  369. log.Printf("[netpulse:discover] sweep %s: %d of %d hosts with port 22 open", subnet, len(alive), len(hosts))
  370. // #1895: "ya añadido" no puede ser una comparación de cadenas en crudo. El
  371. // alta admite un nombre DNS o una IP con puerto y el barrido solo ve IPs,
  372. // así que un AP configurado como "ap.lan" se ofrecía como nuevo mientras
  373. // el gateway, configurado por IP, sí se marcaba.
  374. configured := configuredIndex(ctx, routerstore.ListRouters(db), nil)
  375. type candidate struct{ h string }
  376. cands := make([]candidate, 0, len(alive))
  377. for _, h := range alive {
  378. cands = append(cands, candidate{*h})
  379. }
  380. found := pool(ctx, cands, probeWorkers, func(c candidate) *candidate {
  381. if !probeUbus(ctx, c.h) {
  382. return nil
  383. }
  384. return &c
  385. })
  386. if ctx.Err() != nil {
  387. return Response{Subnet: &subnet, Results: []Result{}, Cached: false, Error: "cancelled"}
  388. }
  389. results := make([]Result, 0, len(found))
  390. for _, c := range found {
  391. if ctx.Err() != nil {
  392. return Response{Subnet: &subnet, Results: []Result{}, Cached: false, Error: "cancelled"}
  393. }
  394. authorized, model := probeSsh(ctx, c.h, keyPath)
  395. // #1893: deja rastro del probe openssh (una conexión TCP/22 por host), que
  396. // de otro modo no aparece en el log del servidor.
  397. log.Printf("[netpulse:ssh] %s: probe openssh autorizado=%v", c.h, authorized)
  398. if authorized {
  399. // Issue #651: pinar TODAS las host keys del router en known_hosts.
  400. // El probe openssh (accept-new) solo registra la clave negociada
  401. // (ed25519); el pool Go negocia otra (ecdsa/rsa), así que un host
  402. // con varias host keys daba falso "host key changed" al probar a
  403. // sondearlo. Bombear todas las keys evita el falso positivo sin
  404. // debilitar la protección anti-MITM (#603): no se acepta una
  405. // identidad con todas las claves cambiadas.
  406. if err := sshkey.PinHostKeys(c.h, keyPath); err != nil {
  407. log.Printf("[netpulse:discover] pin host keys %s: %v", c.h, err)
  408. }
  409. }
  410. hostname := ""
  411. if authorized {
  412. hostname = reverseHostname(c.h)
  413. }
  414. results = append(results, Result{
  415. Host: c.h,
  416. Hostname: hostname,
  417. IsGateway: c.h == gwIP,
  418. Authorized: authorized,
  419. Model: model,
  420. Configured: configured[hostKey(c.h)] || (hostname != "" && configured[hostKey(hostname)]),
  421. })
  422. }
  423. sort.Slice(results, func(i, j int) bool {
  424. if results[i].IsGateway != results[j].IsGateway {
  425. return results[i].IsGateway
  426. }
  427. return results[i].Host < results[j].Host
  428. })
  429. cache = Response{At: now, Subnet: &subnet, Results: results, Cached: false}
  430. return cache
  431. }