discover.go 11 KB

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