proxmox_detect.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. // proxmox_detect.go - POST /api/config/proxmox/detect (#967): descubrimiento
  2. // de hosts Proxmox VE en la /24 de los hosts configurados en `routers`.
  3. //
  4. // DOS FASES, y el orden importa: pveproxy LIMITA las conexiones simultaneas
  5. // por IP de origen, así que un barrido TLS paralelo mata TODAS las conexiones
  6. // (context deadline exceeded incluso contra hosts sanos). Por eso:
  7. // - Fase 1: TCP connect masivo al :8006 (64 workers, 400ms) para filtrar
  8. // los que aceptan el puerto (RST instantaneo o timeout ARP de 400ms).
  9. // - Fase 2: confirmacion TLS GET /api2/json/version EN SERIE (5s), valida
  10. // si el header Server es "pve-api-daemon" o el body contiene "pve".
  11. package httpapi
  12. import (
  13. "context"
  14. "crypto/tls"
  15. "fmt"
  16. "io"
  17. "net"
  18. "net/http"
  19. "sort"
  20. "strings"
  21. "sync"
  22. "time"
  23. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  24. )
  25. // proxmoxDetectResponse es la forma JSON del detect: la lista de hosts
  26. // confirmados como PVE (puede estar vacia).
  27. type proxmoxDetectResponse struct {
  28. Found bool `json:"found"`
  29. Hosts []string `json:"hosts"`
  30. }
  31. // Constantes del barrido (#967): los valores vienen de la validacion en vivo
  32. // (fase 1 ~1,6s por /24; fase 2 una conexion cada vez, siempre).
  33. const (
  34. pveDetectPort = 8006
  35. pveDetectTCPWorkers = 64
  36. pveDetectTCPTimeout = 400 * time.Millisecond
  37. pveDetectTLSTimeout = 5 * time.Second
  38. pveDetectOverallCap = 3 * time.Minute
  39. pveDetectTLSMaxBytes = 8192
  40. )
  41. // Sondas inyectables en tests.
  42. var (
  43. pveTCPProbe = tcpAcceptsPVE
  44. pveTLSConfirm = confirmPVEHost
  45. )
  46. // tcpAcceptsPVE: el host acepta TCP en el puerto (fase 1, barata y paralela).
  47. func tcpAcceptsPVE(host string, port int, timeout time.Duration) bool {
  48. d := net.Dialer{Timeout: timeout}
  49. conn, err := d.Dial("tcp", net.JoinHostPort(host, fmt.Sprintf("%d", port)))
  50. if err != nil {
  51. return false
  52. }
  53. _ = conn.Close()
  54. return true
  55. }
  56. // confirmPVEHost: GET TLS /api2/json/version (fase 2, EN SERIE). Valido si
  57. // el header Server es "pve-api-daemon" o el body contiene "pve". El cert es
  58. // autofirmado en cualquier PVE real (mismo criterio que pve.NewClient).
  59. func confirmPVEHost(host string, port int, timeout time.Duration) bool {
  60. tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} // #561
  61. client := &http.Client{Transport: tr, Timeout: timeout}
  62. res, err := client.Get(fmt.Sprintf("https://%s/api2/json/version", net.JoinHostPort(host, fmt.Sprintf("%d", port))))
  63. if err != nil {
  64. return false
  65. }
  66. defer res.Body.Close()
  67. if strings.Contains(res.Header.Get("Server"), "pve-api-daemon") {
  68. return true
  69. }
  70. body, err := io.ReadAll(io.LimitReader(res.Body, pveDetectTLSMaxBytes))
  71. if err != nil {
  72. return false
  73. }
  74. return strings.Contains(string(body), "pve")
  75. }
  76. // scanSubnetPVE: fase 1 - TCP connect masivo a toda la /24 en el puerto PVE.
  77. func scanSubnetPVE(subnet string) []string {
  78. jobs := make(chan string)
  79. var mu sync.Mutex
  80. found := []string{}
  81. var wg sync.WaitGroup
  82. for w := 0; w < pveDetectTCPWorkers; w++ {
  83. wg.Add(1)
  84. go func() {
  85. defer wg.Done()
  86. for ip := range jobs {
  87. if pveTCPProbe(ip, pveDetectPort, pveDetectTCPTimeout) {
  88. mu.Lock()
  89. found = append(found, ip)
  90. mu.Unlock()
  91. }
  92. }
  93. }()
  94. }
  95. for i := 1; i <= 254; i++ {
  96. jobs <- fmt.Sprintf("%s.%d", subnet, i)
  97. }
  98. close(jobs)
  99. wg.Wait()
  100. sort.Strings(found)
  101. return found
  102. }
  103. // handleDetectProxmox: escanea la /24 de cada host configurado en `routers`
  104. // y devuelve los hosts confirmados como Proxmox VE.
  105. func (s *server) handleDetectProxmox(w http.ResponseWriter, r *http.Request) {
  106. ctx, cancel := context.WithTimeout(r.Context(), pveDetectOverallCap)
  107. defer cancel()
  108. subnets := map[string]bool{}
  109. for _, rt := range routerstore.ListRouters(s.db.DB) {
  110. ip := net.ParseIP(strings.TrimSpace(rt.Host))
  111. if ip == nil || ip.To4() == nil {
  112. continue
  113. }
  114. v4 := ip.To4()
  115. subnets[fmt.Sprintf("%d.%d.%d", v4[0], v4[1], v4[2])] = true
  116. }
  117. confirmed := []string{}
  118. for subnet := range subnets {
  119. if ctx.Err() != nil {
  120. break
  121. }
  122. for _, ip := range scanSubnetPVE(subnet) {
  123. if ctx.Err() != nil {
  124. break
  125. }
  126. // Fase 2 EN SERIE: pveproxy muere con TLS paralelo (ver cabecera).
  127. if pveTLSConfirm(ip, pveDetectPort, pveDetectTLSTimeout) {
  128. confirmed = append(confirmed, ip)
  129. }
  130. }
  131. }
  132. sort.Strings(confirmed)
  133. writeJSON(w, http.StatusOK, proxmoxDetectResponse{Found: len(confirmed) > 0, Hosts: confirmed})
  134. }