pve.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. // Package pve — cliente read-only de la API de Proxmox VE (issue #561).
  2. //
  3. // Objetivo: obtener el inventario del cluster (VMs/CTs → nodo/host) como
  4. // ground truth para sellar la infraestructura en NetPulse (hypervisor + ct
  5. // con attachTo). La relación CT→host NO es deducible del tráfico L2 (un
  6. // puerto del router mezcla dispositivos); vive en el cluster.
  7. //
  8. // Auth: API token de Proxmox (PVEAPIToken) con privilegios de solo lectura
  9. // (Sys.Audit para cluster/resources; VM.Audit para leer la config de cada
  10. // VM/CT y extraer sus MACs). El token se envía en el header Authorization:
  11. //
  12. // Authorization: PVEAPIToken=USER@REALM!TOKENID=UUID
  13. //
  14. // TLS: el certificado del cluster suele ser self-signed. Por defecto se valida
  15. // contra las raíces del sistema; se puede fijar una CA (caPem) o el SHA-256 del
  16. // certificado hoja (fingerprintSha256). "insecure" desactiva la validación de
  17. // forma explícita. Solo lectura: GET únicamente.
  18. package pve
  19. import (
  20. "context"
  21. "crypto/sha256"
  22. "crypto/subtle"
  23. "crypto/tls"
  24. "crypto/x509"
  25. "encoding/hex"
  26. "encoding/json"
  27. "fmt"
  28. "io"
  29. "net/http"
  30. "net/url"
  31. "sort"
  32. "strconv"
  33. "strings"
  34. "time"
  35. "github.com/gnacho/netpulse/agent/macaddr"
  36. )
  37. // Config: datos de conexión al cluster (persistidos en kv por el server).
  38. type Config struct {
  39. // URL base, p. ej. "https://192.168.1.100:8006" (sin barra final).
  40. URL string `json:"url"`
  41. // TokenID: "USER@REALM!TOKENID" (p. ej. "root@pam!netpulse").
  42. TokenID string `json:"tokenId"`
  43. // Secret: la parte UUID del token (se muestra una sola vez al crearlo).
  44. // NUNCA viaja en respuestas de la API (la config se expone sanitizada).
  45. Secret string `json:"secret,omitempty"`
  46. // CAPEM: CA en PEM para validar el certificado del cluster.
  47. CAPEM string `json:"caPem,omitempty"`
  48. // FingerprintSHA256: SHA-256 en hex del certificado hoja.
  49. FingerprintSHA256 string `json:"fingerprintSha256,omitempty"`
  50. // Insecure: desactiva la validación TLS. Solo para transiciones controladas.
  51. Insecure bool `json:"insecure,omitempty"`
  52. }
  53. // Enabled: true si hay config completa.
  54. func (c Config) Enabled() bool {
  55. return c.URL != "" && c.TokenID != "" && c.Secret != ""
  56. }
  57. const httpTimeout = 5 * time.Second
  58. // Client consulta la API PVE de un cluster.
  59. type Client struct {
  60. cfg Config
  61. hc *http.Client
  62. err error
  63. }
  64. // NewClient crea el cliente (sin red: solo guarda config). Por defecto valida
  65. // el certificado contra las raíces del sistema. CAPEM añade una CA,
  66. // FingerprintSHA256 fija el certificado hoja e Insecure desactiva la validación.
  67. func NewClient(cfg Config) *Client {
  68. transport := http.DefaultTransport.(*http.Transport).Clone()
  69. tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12}
  70. var clientErr error
  71. switch {
  72. case cfg.Insecure:
  73. tlsCfg.InsecureSkipVerify = true
  74. case cfg.FingerprintSHA256 != "":
  75. want, err := normalizeFingerprint(cfg.FingerprintSHA256)
  76. if err != nil {
  77. clientErr = err
  78. break
  79. }
  80. tlsCfg.InsecureSkipVerify = true
  81. tlsCfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
  82. return verifyFingerprint(rawCerts, want)
  83. }
  84. case cfg.CAPEM != "":
  85. pool := x509.NewCertPool()
  86. if !pool.AppendCertsFromPEM([]byte(cfg.CAPEM)) {
  87. clientErr = fmt.Errorf("PVE: invalid caPem")
  88. break
  89. }
  90. tlsCfg.RootCAs = pool
  91. }
  92. transport.TLSClientConfig = tlsCfg
  93. return &Client{
  94. cfg: cfg,
  95. hc: &http.Client{Timeout: httpTimeout, Transport: transport},
  96. err: clientErr,
  97. }
  98. }
  99. func normalizeFingerprint(v string) (string, error) {
  100. s := strings.ToLower(strings.TrimSpace(v))
  101. s = strings.NewReplacer(":", "", " ", "", "-", "").Replace(s)
  102. if len(s) != 64 {
  103. return "", fmt.Errorf("PVE: fingerprintSha256 must be 64 hex characters")
  104. }
  105. if _, err := hex.DecodeString(s); err != nil {
  106. return "", fmt.Errorf("PVE: invalid fingerprintSha256: %w", err)
  107. }
  108. return s, nil
  109. }
  110. func verifyFingerprint(rawCerts [][]byte, want string) error {
  111. if len(rawCerts) == 0 {
  112. return fmt.Errorf("PVE: no peer certificate")
  113. }
  114. sum := sha256.Sum256(rawCerts[0])
  115. got := hex.EncodeToString(sum[:])
  116. if subtle.ConstantTimeCompare([]byte(got), []byte(want)) != 1 {
  117. return fmt.Errorf("PVE: certificate fingerprint mismatch")
  118. }
  119. return nil
  120. }
  121. func (c *Client) authHeader() string {
  122. return "PVEAPIToken=" + c.cfg.TokenID + "=" + c.cfg.Secret
  123. }
  124. func (c *Client) get(ctx context.Context, path string, dst any) error {
  125. if c.err != nil {
  126. return c.err
  127. }
  128. req, err := http.NewRequestWithContext(ctx, "GET", c.cfg.URL+path, nil)
  129. if err != nil {
  130. return err
  131. }
  132. req.Header.Set("Authorization", c.authHeader())
  133. req.Header.Set("Accept", "application/json")
  134. res, err := c.hc.Do(req)
  135. if err != nil {
  136. return fmt.Errorf("PVE %s: %w", path, err)
  137. }
  138. defer res.Body.Close()
  139. if res.StatusCode != 200 {
  140. body, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
  141. return fmt.Errorf("PVE %s → HTTP %d: %s", path, res.StatusCode, strings.TrimSpace(string(body)))
  142. }
  143. // La API PVE envuelve todo en {"data": ...}.
  144. var wrapper struct {
  145. Data json.RawMessage `json:"data"`
  146. }
  147. if err := json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(&wrapper); err != nil {
  148. return err
  149. }
  150. return json.Unmarshal(wrapper.Data, dst)
  151. }
  152. // Resource: un elemento de cluster/resources (VM, CT, storage, node…).
  153. // Verificado contra pve-docs: los campos que NetPulse necesita para el
  154. // sellado de infra son vmid/name/type/node/status.
  155. type Resource struct {
  156. ID string `json:"id"` // "qemu/100" | "lxc/200" | "node/citadel-01"…
  157. VMID int `json:"vmid"` // 0 para nodos/storage
  158. Name string `json:"name"` // hostname del CT/VM, o nombre del nodo
  159. Type string `json:"type"` // "lxc" | "qemu" | "node" | "storage" | …
  160. Node string `json:"node"` // nodo que lo ejecuta ("" para storage)
  161. Status string `json:"status"` // "running" | "stopped" | …
  162. }
  163. // ClusterResources: GET /api2/json/cluster/resources → VMs/CTs de TODO el
  164. // cluster con su nodo (host). Una sola llamada.
  165. func (c *Client) ClusterResources(ctx context.Context) ([]Resource, error) {
  166. var out []Resource
  167. if err := c.get(ctx, "/api2/json/cluster/resources", &out); err != nil {
  168. return nil, err
  169. }
  170. return out, nil
  171. }
  172. // VMConfig: GET /nodes/{node}/lxc|qemu/{vmid}/config. Devuelve el objeto de
  173. // config crudo; NetPulse usa netN → MAC de cada interfaz.
  174. func (c *Client) VMConfig(ctx context.Context, node, typ string, vmid int) (map[string]any, error) {
  175. path := fmt.Sprintf("/api2/json/nodes/%s/%s/%d/config", url.PathEscape(node), typ, vmid)
  176. var out map[string]any
  177. if err := c.get(ctx, path, &out); err != nil {
  178. return nil, err
  179. }
  180. return out, nil
  181. }
  182. // NodeIP: GET /nodes/{node}/network → IP IPv4 del bridge vmbr0 (o el primer
  183. // iface con address IPv4). Identifica al host físico del nodo en la LAN.
  184. func (c *Client) NodeIP(ctx context.Context, node string) (string, error) {
  185. path := fmt.Sprintf("/api2/json/nodes/%s/network", url.PathEscape(node))
  186. var out []struct {
  187. Iface string `json:"iface"`
  188. Type string `json:"type"`
  189. Address string `json:"address"`
  190. }
  191. if err := c.get(ctx, path, &out); err != nil {
  192. return "", err
  193. }
  194. // Preferencia: vmbr0 (bridge principal); si no, cualquier iface con IPv4.
  195. var fallback string
  196. for _, i := range out {
  197. if !strings.Contains(i.Address, ".") {
  198. continue
  199. }
  200. if i.Iface == "vmbr0" {
  201. return i.Address, nil
  202. }
  203. if fallback == "" {
  204. fallback = i.Address
  205. }
  206. }
  207. return fallback, nil
  208. }
  209. // NIC is one NIC declared in a guest config: the MAC it uses, the VLAN tag it
  210. // carries and the bridge it hangs from. Proxmox writes tag=<vid> when the
  211. // guest is not on the native VLAN, and that is the only place the tag exists:
  212. // the guest sits behind the host bridge, so the router never sees it (#1757).
  213. type NIC struct {
  214. MAC string
  215. Tag int
  216. Bridge string
  217. }
  218. // NICsOfConfig returns the NICs of a VM/CT config, in net<N> order so the
  219. // result is stable between polls. Proxmox exposes each NIC as "net0": "…":
  220. //
  221. // LXC: net0: bridge=vmbr0,hwaddr=BC:24:11:XX:XX:XX,ip=dhcp,name=eth0,type=veth
  222. // QEMU: net0: virtio=BC:24:11:XX:XX:XX,bridge=vmbr0 (MAC tras el modelo)
  223. //
  224. // MACs are normalised to upper case with ':'.
  225. func NICsOfConfig(cfg map[string]any) []NIC {
  226. keys := make([]string, 0, len(cfg))
  227. for k := range cfg {
  228. if strings.HasPrefix(k, "net") {
  229. keys = append(keys, k)
  230. }
  231. }
  232. sort.Strings(keys)
  233. var out []NIC
  234. for _, k := range keys {
  235. s, ok := cfg[k].(string)
  236. if !ok {
  237. continue
  238. }
  239. var nic NIC
  240. for _, field := range strings.Split(s, ",") {
  241. switch {
  242. case strings.HasPrefix(field, "hwaddr="):
  243. nic.MAC = normMAC(field[len("hwaddr="):])
  244. case strings.HasPrefix(field, "bridge="):
  245. nic.Bridge = field[len("bridge="):]
  246. case strings.HasPrefix(field, "tag="):
  247. if n, err := strconv.Atoi(field[len("tag="):]); err == nil && n > 0 && n < 4095 {
  248. nic.Tag = n
  249. }
  250. default:
  251. // QEMU: el primer campo es <modelo>=<MAC> (virtio=XX, e1000=XX…)
  252. if eq := strings.Index(field, "="); eq > 0 {
  253. if looksLikeMAC(field[eq+1:]) {
  254. nic.MAC = normMAC(field[eq+1:])
  255. }
  256. }
  257. }
  258. }
  259. if nic.MAC != "" {
  260. out = append(out, nic)
  261. }
  262. }
  263. return out
  264. }
  265. // MACsOfConfig extrae las MACs de una config de VM/CT (ver NICsOfConfig).
  266. func MACsOfConfig(cfg map[string]any) []string {
  267. nics := NICsOfConfig(cfg)
  268. if len(nics) == 0 {
  269. return nil
  270. }
  271. out := make([]string, 0, len(nics))
  272. for _, n := range nics {
  273. out = append(out, n.MAC)
  274. }
  275. return out
  276. }
  277. // looksLikeMAC comprueba si el valor de un campo key=value de netN es una MAC
  278. // con separadores (17 caracteres) para distinguirlo de otras opciones de NIC.
  279. func looksLikeMAC(s string) bool {
  280. return macaddr.NormalizeSeparated(s) != ""
  281. }
  282. func normMAC(s string) string {
  283. return macaddr.Normalize(s)
  284. }
  285. // TestResult is what a connection test can tell the user about an endpoint.
  286. type TestResult struct {
  287. // Version: the PVE release string ("8.4.21").
  288. Version string `json:"version"`
  289. Nodes int `json:"nodes"`
  290. VMs int `json:"vms"`
  291. CTs int `json:"cts"`
  292. // Limited: the token authenticates but Proxmox is filtering the listings
  293. // because the token has no audit rights. This is the failure the test
  294. // exists for: PVE does not reject a list a token may not see, it returns
  295. // it empty with HTTP 200, so an under-privileged token looks exactly
  296. // like a cluster with no guests and the integration goes quiet.
  297. Limited bool `json:"limited"`
  298. }
  299. // Test checks an endpoint the way a user needs it checked: can we reach it,
  300. // does the token authenticate, and can it actually see anything.
  301. func (c *Client) Test(ctx context.Context) (*TestResult, error) {
  302. if !c.cfg.Enabled() {
  303. return nil, fmt.Errorf("missing url, tokenId or secret")
  304. }
  305. var version struct {
  306. Version string `json:"version"`
  307. Release string `json:"release"`
  308. }
  309. // /version needs no privileges: it separates "unreachable or bad token"
  310. // from "authenticated but blind", which are different problems.
  311. if err := c.get(ctx, "/api2/json/version", &version); err != nil {
  312. return nil, err
  313. }
  314. out := &TestResult{Version: version.Version}
  315. if out.Version == "" {
  316. out.Version = version.Release
  317. }
  318. resources, err := c.ClusterResources(ctx)
  319. if err != nil {
  320. return nil, err
  321. }
  322. var firstNode string
  323. for _, r := range resources {
  324. switch r.Type {
  325. case "node":
  326. out.Nodes++
  327. if firstNode == "" {
  328. firstNode = r.Node
  329. }
  330. case "qemu":
  331. out.VMs++
  332. case "lxc":
  333. out.CTs++
  334. }
  335. }
  336. // Nothing to seal: is the cluster empty, or is the token blind? Ask for
  337. // something that needs Sys.Audit and read the answer. A 403 proves the
  338. // token lacks the rights, and the user gets told which ones.
  339. if out.VMs == 0 && out.CTs == 0 && firstNode != "" {
  340. var status map[string]any
  341. if err := c.get(ctx, "/api2/json/nodes/"+url.PathEscape(firstNode)+"/status", &status); err != nil &&
  342. strings.Contains(err.Error(), "HTTP 403") {
  343. out.Limited = true
  344. }
  345. }
  346. return out, nil
  347. }
  348. // ClusterNode is one entry of /cluster/status: the address corosync knows a
  349. // node by, which is the node's real address on the network.
  350. type ClusterNode struct {
  351. Type string `json:"type"` // "node" | "cluster"
  352. Name string `json:"name"`
  353. IP string `json:"ip"`
  354. }
  355. // ClusterStatus: GET /api2/json/cluster/status → node name and IP.
  356. //
  357. // This is where a node's address actually lives. /nodes/{node}/network only
  358. // reports what /etc/network/interfaces declares, so a host whose management
  359. // address is configured outside it -- DHCP on the NIC, systemd-networkd, a
  360. // setup with no bridge in that file -- lists its interfaces with no address
  361. // at all and offers nothing to match the host device by.
  362. //
  363. // Needs Sys.Audit on "/"; a token without it gets a 403 and the caller
  364. // falls back to the interface listing.
  365. func (c *Client) ClusterStatus(ctx context.Context) ([]ClusterNode, error) {
  366. var out []ClusterNode
  367. if err := c.get(ctx, "/api2/json/cluster/status", &out); err != nil {
  368. return nil, err
  369. }
  370. return out, nil
  371. }
  372. // HostOfURL: the host part of the configured endpoint, with no port. For a
  373. // single-node instance that is the node's address, and it is the last
  374. // resort when the API will not say what its own address is.
  375. func (c *Client) HostOfURL() string {
  376. u, err := url.Parse(c.cfg.URL)
  377. if err != nil {
  378. return ""
  379. }
  380. return u.Hostname()
  381. }