Forráskód Böngészése

fix(security): secure default bind and PVE TLS verification (#1608)

Default the plain listener to loopback when TLS and on-box HTTPS are disabled, and allow NETPULSE_BIND to override it. PVE now validates TLS against system roots by default, supports a CA PEM or SHA-256 fingerprint pin, and keeps an explicit insecure escape hatch. Expose the new PVE fields in settings and document the changes.

Closes #1607
Nacho 1 hónapja
szülő
commit
9573ae507e

+ 6 - 0
app/public/locales/en/translation.json

@@ -1883,6 +1883,12 @@
       "notConfigured": "Not configured",
       "edit": "Edit Proxmox configuration",
       "url": "Cluster URL",
+      "caPem": "CA certificate (PEM)",
+      "caPemPlaceholder": "-----BEGIN CERTIFICATE-----",
+      "fingerprint": "SHA-256 fingerprint",
+      "fingerprintPlaceholder": "AA:BB:CC:...",
+      "insecure": "Skip TLS verification (unsafe)",
+      "insecureHint": "Use only with a trusted self-signed Proxmox. A CA or fingerprint is safer.",
       "tokenId": "Token ID (user@realm!name)",
       "secret": "Token secret",
       "secretKeep": "Current secret (leave empty to keep it)",

+ 6 - 0
app/public/locales/es/translation.json

@@ -1883,6 +1883,12 @@
       "notConfigured": "Sin configurar",
       "edit": "Editar configuración de Proxmox",
       "url": "URL del cluster",
+      "caPem": "Certificado de la CA (PEM)",
+      "caPemPlaceholder": "-----BEGIN CERTIFICATE-----",
+      "fingerprint": "Huella SHA-256",
+      "fingerprintPlaceholder": "AA:BB:CC:...",
+      "insecure": "Omitir la verificación TLS (inseguro)",
+      "insecureHint": "Úsalo solo con un Proxmox autofirmado de confianza. Una CA o una huella es más seguro.",
       "tokenId": "Token ID (usuario@realm!nombre)",
       "secret": "Secret del token",
       "secretKeep": "Secret actual (déjalo vacío para conservarlo)",

+ 41 - 1
app/src/pages/Settings.tsx

@@ -1961,6 +1961,9 @@ interface PveInstanceCfg {
   url: string
   tokenId: string
   secret?: string
+  caPem?: string
+  fingerprintSha256?: string
+  insecure?: boolean
 }
 
 function ProxmoxManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => void }) {
@@ -2015,6 +2018,9 @@ function ProxmoxManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
         name: editing.name.trim(),
         url: editing.url.trim(),
         tokenId: editing.tokenId.trim(),
+        caPem: editing.caPem?.trim() ?? '',
+        fingerprintSha256: editing.fingerprintSha256?.trim() ?? '',
+        insecure: editing.insecure === true,
       }
       if (editing.secret) body.secret = editing.secret
       const res = await fetch('/api/config/proxmox', {
@@ -2049,6 +2055,9 @@ function ProxmoxManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     try {
       const body: Record<string, unknown> = {
         id: inst.id.trim(), url: inst.url.trim(), tokenId: inst.tokenId.trim(),
+        caPem: inst.caPem?.trim() ?? '',
+        fingerprintSha256: inst.fingerprintSha256?.trim() ?? '',
+        insecure: inst.insecure === true,
       }
       if (inst.secret) body.secret = inst.secret
       const res = await fetch('/api/config/proxmox/test', {
@@ -2091,7 +2100,10 @@ function ProxmoxManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     }
   }
 
-  const empty = { id: '', name: '', url: '', tokenId: '', secret: '' }
+  const empty = {
+    id: '', name: '', url: '', tokenId: '', secret: '',
+    caPem: '', fingerprintSha256: '', insecure: false,
+  }
 
   // Detectar (#967): POST /api/config/proxmox/detect barre la /24 de los
   // hosts de la flota en dos fases (TCP :8006 masivo + confirmación TLS en
@@ -2199,6 +2211,34 @@ function ProxmoxManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
               aria-label={t('settings.proxmox.url')}
               className="w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
             />
+            <textarea
+              value={editing.caPem ?? ''}
+              onChange={(e) => setEditing({ ...editing, caPem: e.target.value })}
+              placeholder={t('settings.proxmox.caPemPlaceholder')}
+              aria-label={t('settings.proxmox.caPem')}
+              rows={3}
+              className="w-full resize-y rounded-lg border border-border bg-elevated px-3 py-2 font-mono text-xs text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+            />
+            <input
+              type="text"
+              value={editing.fingerprintSha256 ?? ''}
+              onChange={(e) => setEditing({ ...editing, fingerprintSha256: e.target.value })}
+              placeholder={t('settings.proxmox.fingerprintPlaceholder')}
+              aria-label={t('settings.proxmox.fingerprint')}
+              className="w-full rounded-lg border border-border bg-elevated px-3 py-2 font-mono text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+            />
+            <label className="flex items-start gap-2 text-caption text-text-secondary">
+              <input
+                type="checkbox"
+                checked={editing.insecure === true}
+                onChange={(e) => setEditing({ ...editing, insecure: e.target.checked })}
+                className="mt-0.5 h-4 w-4"
+              />
+              <span>{t('settings.proxmox.insecure')}</span>
+            </label>
+            {editing.insecure === true && (
+              <p className="text-caption leading-relaxed text-warn">{t('settings.proxmox.insecureHint')}</p>
+            )}
             <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
               <input
                 type="text"

+ 5 - 0
docs/manual.en.md

@@ -36,6 +36,10 @@ NetPulse is multi-user with password authentication. The installer prints an ini
 
 There is also a **demo mode** that opens without a password or backend: it shows a sample network with dozens of devices so you can explore the UI. In demo there is no real data and the write features are disabled.
 
+### Transport security
+
+When neither TLS nor on-box HTTPS is enabled, the server binds to `127.0.0.1` by default. A fresh installation therefore does not accept logins from the LAN. Set `NETPULSE_BIND=0.0.0.0` only when you deliberately want to expose it, and enable TLS (`NETPULSE_TLS_ENABLED=1`) for any remote access. With TLS or on-box HTTPS enabled the bind stays open unless `NETPULSE_BIND` says otherwise.
+
 ---
 
 ## Overview
@@ -553,6 +557,7 @@ This is the largest screen. Main sections:
 - **Topology overrides** and **Trusted devices** (admin only).
 - **Agent adoption**: pairing token and server fingerprint.
 - **AdGuard Home**: configuration of the read-only connection to the router's AdGuard panel.
+- **Proxmox VE**: read-only cluster inventory. Besides the URL and token, you can paste a CA certificate, pin a SHA-256 fingerprint or enable an explicit insecure mode for a trusted self-signed host.
 - **My profile**: name, language, password and sign out.
 - **API Tokens**: bearer tokens for integrations. A `read` token only allows `GET`, `HEAD` and `OPTIONS`, a `write` token can also mutate non-admin resources, and only an `admin` token reaches administration routes and the database download.
 - **About**: version, links, push/PWA, Telegram and system data.

+ 5 - 0
docs/manual.es.md

@@ -36,6 +36,10 @@ NetPulse es multiusuario con autenticación por contraseña. El instalador impri
 
 Existe además un **modo demo** que se puede abrir sin contraseña ni backend: muestra una red de ejemplo con decenas de dispositivos para explorar la interfaz. En demo no hay datos reales y las funciones de escritura quedan deshabilitadas.
 
+### Seguridad del transporte
+
+Cuando no hay TLS ni HTTPS on-box, el servidor escucha en `127.0.0.1` por defecto. Una instalación nueva no acepta inicios de sesión desde la LAN. Usa `NETPULSE_BIND=0.0.0.0` solo si quieres exponerlo a propósito, y activa TLS (`NETPULSE_TLS_ENABLED=1`) para cualquier acceso remoto. Con TLS u HTTPS on-box el bind queda abierto salvo que `NETPULSE_BIND` indique otra cosa.
+
 ---
 
 ## Resumen
@@ -553,6 +557,7 @@ Es la pantalla más grande. Secciones principales:
 - **Overrides de topología** y **Dispositivos de confianza** (solo admin).
 - **Adopción de agentes**: token de emparejamiento y huella del servidor.
 - **AdGuard Home**: configuración de la conexión de solo lectura al panel AdGuard del router.
+- **Proxmox VE**: inventario de solo lectura del cluster. Además de la URL y el token, puedes pegar un certificado de la CA, fijar una huella SHA-256 o activar un modo inseguro explícito para un host autofirmado de confianza.
 - **Mi perfil**: nombre, idioma, contraseña y salir.
 - **API Tokens**: tokens bearer para integraciones. Un token `read` solo permite `GET`, `HEAD` y `OPTIONS`, un token `write` puede además mutar recursos que no son de administración, y solo un token `admin` alcanza las rutas de administración y la descarga de la base de datos.
 - **Acerca de**: versión, enlaces, push/PWA, Telegram y datos del sistema.

+ 11 - 2
server-go/cmd/netpulse/main.go

@@ -118,6 +118,15 @@ func withSSEWriteTimeout(next http.Handler, long time.Duration) http.Handler {
 
 // newHTTPServer construye un http.Server con los timeouts comunes (issue #210).
 // Compartido entre el listener HTTP de PORT y el listener HTTPS adicional (#696).
+// listenAddr joins the configured bind address and port. An empty bind keeps
+// the historical all-interfaces listener.
+func listenAddr(bind string, port int) string {
+	if bind == "" {
+		return fmt.Sprintf(":%d", port)
+	}
+	return net.JoinHostPort(bind, strconv.Itoa(port))
+}
+
 func newHTTPServer(addr string, h http.Handler) *http.Server {
 	return &http.Server{
 		Addr:              addr,
@@ -812,12 +821,12 @@ func run() error {
 	}
 	defer tlsMgr.Close()
 	// FORK: on the plain port, what the HTTP mode allows (a no-op in full).
-	srv := newHTTPServer(fmt.Sprintf(":%d", cfg.Port), withSSEWriteTimeout(tlsMgr.PlainHandler(handler), sseWriteTimeout))
+	srv := newHTTPServer(listenAddr(cfg.BindAddr, cfg.Port), withSSEWriteTimeout(tlsMgr.PlainHandler(handler), sseWriteTimeout))
 
 	// Listener HTTPS adicional (#696): mismo handler y timeouts que el HTTP.
 	var tlsSrv *http.Server
 	if extraTLSConf != nil {
-		tlsSrv = newHTTPServer(fmt.Sprintf(":%d", cfg.TLSPort), withSSEWriteTimeout(handler, sseWriteTimeout))
+		tlsSrv = newHTTPServer(listenAddr(cfg.BindAddr, cfg.TLSPort), withSSEWriteTimeout(handler, sseWriteTimeout))
 		tlsSrv.TLSConfig = extraTLSConf
 	}
 

+ 18 - 0
server-go/internal/config/config.go

@@ -6,6 +6,7 @@ package config
 import (
 	"encoding/json"
 	"fmt"
+	"net"
 	"net/url"
 	"os"
 	"path/filepath"
@@ -43,6 +44,7 @@ type Webhook struct {
 // Config es la config normalizada (equivalente al objeto de loadConfig).
 type Config struct {
 	Port            int
+	BindAddr        string // listener HTTP; loopback por defecto sin TLS
 	NodeEnv         string
 	StaticDir       string // resuelta (absoluta)
 	DataDir         string // resuelta (absoluta)
@@ -559,6 +561,21 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		}
 	}
 
+	// NETPULSE_BIND: dirección del listener HTTP. Sin TLS ni on-box el default
+	// es loopback; con TLS u on-box se mantiene el comportamiento histórico
+	// (todas las interfaces). Un valor explícito manda.
+	bindAddr := "127.0.0.1"
+	if tlsEnabled || onbox {
+		bindAddr = ""
+	}
+	if v := strings.TrimSpace(env["NETPULSE_BIND"]); v != "" {
+		if v == "localhost" || net.ParseIP(v) != nil {
+			bindAddr = v
+		} else {
+			errs.issues = append(errs.issues, issue{"NETPULSE_BIND", "Expected an IP address or localhost"})
+		}
+	}
+
 	// NETPULSE_TLS_CERT / NETPULSE_TLS_KEY: paths del cert del usuario. Ambos
 	// o ninguno (fail-fast si solo viene uno).
 	tlsCert := strings.TrimSpace(env["NETPULSE_TLS_CERT"])
@@ -645,6 +662,7 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 
 	return &Config{
 		Port:                       port,
+		BindAddr:                   bindAddr,
 		NodeEnv:                    nodeEnv,
 		StaticDir:                  resolve(staticDir),
 		DataDir:                    resolve(dataDir),

+ 37 - 0
server-go/internal/config/config_test.go

@@ -310,3 +310,40 @@ func TestLoadAutoReinstallConAgentURL(t *testing.T) {
 		t.Fatalf("AUTO_REINSTALL sin ninguna URL debe fallar señalando el par: %v", err)
 	}
 }
+
+func TestLoadBindAddrLoopbackByDefault(t *testing.T) {
+	cfg, err := Load(map[string]string{"AUTH_PASS": "segura-y-larga"}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if cfg.BindAddr != "127.0.0.1" {
+		t.Fatalf("BindAddr = %q, esperaba loopback sin TLS", cfg.BindAddr)
+	}
+}
+
+func TestLoadBindAddrOverride(t *testing.T) {
+	cfg, err := Load(map[string]string{"AUTH_PASS": "segura-y-larga", "NETPULSE_BIND": "0.0.0.0"}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if cfg.BindAddr != "0.0.0.0" {
+		t.Fatalf("BindAddr = %q, esperaba 0.0.0.0", cfg.BindAddr)
+	}
+}
+
+func TestLoadBindAddrTLSKeepsAllInterfaces(t *testing.T) {
+	cfg, err := Load(map[string]string{"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_ENABLED": "1"}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if cfg.BindAddr != "" {
+		t.Fatalf("BindAddr = %q, esperaba vacío con TLS", cfg.BindAddr)
+	}
+}
+
+func TestLoadBindAddrInvalido(t *testing.T) {
+	_, err := Load(map[string]string{"AUTH_PASS": "segura-y-larga", "NETPULSE_BIND": "not-an-ip"}, t.TempDir())
+	if err == nil || !strings.Contains(err.Error(), "NETPULSE_BIND") {
+		t.Fatalf("NETPULSE_BIND inválido debe fallar señalando la variable: %v", err)
+	}
+}

+ 42 - 9
server-go/internal/httpapi/config.go

@@ -604,10 +604,11 @@ func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Reques
 func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
 	instances := pve.LoadInstances(s.db.DB)
 	// Vista sanitizada: el secret JAMAS sale del server (#764).
-	view := make([]map[string]string, 0, len(instances))
+	view := make([]map[string]any, 0, len(instances))
 	for _, in := range instances {
-		view = append(view, map[string]string{
+		view = append(view, map[string]any{
 			"id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
+			"caPem": in.CAPEM, "fingerprintSha256": in.FingerprintSHA256, "insecure": in.Insecure,
 		})
 	}
 	out := map[string]any{
@@ -631,11 +632,14 @@ type proxmoxInput struct {
 }
 
 type proxmoxInstanceInput struct {
-	ID      string `json:"id"`
-	Name    string `json:"name"`
-	URL     string `json:"url"`
-	TokenID string `json:"tokenId"`
-	Secret  string `json:"secret"` // vacío en edición = conservar el actual
+	ID                string  `json:"id"`
+	Name              string  `json:"name"`
+	URL               string  `json:"url"`
+	TokenID           string  `json:"tokenId"`
+	Secret            string  `json:"secret"` // vacío en edición = conservar el actual
+	CAPEM             *string `json:"caPem"`
+	FingerprintSHA256 *string `json:"fingerprintSha256"`
+	Insecure          *bool   `json:"insecure"`
 }
 
 // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
@@ -677,7 +681,8 @@ func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request)
 		}
 	}
 	if current != nil {
-		if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" {
+		if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" &&
+			in.CAPEM == nil && in.FingerprintSHA256 == nil && in.Insecure == nil {
 			writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
 			return
 		}
@@ -690,6 +695,15 @@ func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request)
 		if in.Secret != "" {
 			current.Secret = in.Secret
 		}
+		if in.CAPEM != nil {
+			current.CAPEM = strings.TrimSpace(*in.CAPEM)
+		}
+		if in.FingerprintSHA256 != nil {
+			current.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
+		}
+		if in.Insecure != nil {
+			current.Insecure = *in.Insecure
+		}
 		if n := strings.TrimSpace(in.Name); n != "" {
 			current.Name = n
 		}
@@ -709,7 +723,17 @@ func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request)
 	if name == "" {
 		name = id
 	}
-	inst := pve.Instance{ID: id, Name: name, Config: pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}}
+	cfg := pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}
+	if in.CAPEM != nil {
+		cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
+	}
+	if in.FingerprintSHA256 != nil {
+		cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
+	}
+	if in.Insecure != nil {
+		cfg.Insecure = *in.Insecure
+	}
+	inst := pve.Instance{ID: id, Name: name, Config: cfg}
 	if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
 		writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
 		return
@@ -764,6 +788,15 @@ func (s *server) handleTestProxmoxConfig(w http.ResponseWriter, r *http.Request)
 	if in.Secret != "" {
 		cfg.Secret = in.Secret
 	}
+	if in.CAPEM != nil {
+		cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
+	}
+	if in.FingerprintSHA256 != nil {
+		cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
+	}
+	if in.Insecure != nil {
+		cfg.Insecure = *in.Insecure
+	}
 	if !cfg.Enabled() {
 		writeError(w, http.StatusBadRequest, "invalid_input", "faltan url, tokenId o secret")
 		return

+ 37 - 0
server-go/internal/httpapi/config_test.go

@@ -647,6 +647,43 @@ func TestProxmoxConfig(t *testing.T) {
 	}
 }
 
+func TestProxmoxTLSConfig(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	res := doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
+		`{"id":"casa","name":"Casa","url":"https://192.168.1.100:8006","tokenId":"root@pam!netpulse","secret":"uuid-1234","caPem":"PEM-CA","fingerprintSha256":"AABB","insecure":true}`)
+	if res.StatusCode != 204 {
+		body := readJSON(t, res)
+		t.Fatalf("PUT proxmox tls: %d %v", res.StatusCode, body)
+	}
+
+	res = doReq(t, "GET", srv.URL+"/api/config/proxmox", cookie, "")
+	body := readJSON(t, res)
+	instances, _ := body["instances"].([]any)
+	if len(instances) != 1 {
+		t.Fatalf("instances: %v", instances)
+	}
+	inst, _ := instances[0].(map[string]any)
+	if inst["caPem"] != "PEM-CA" || inst["fingerprintSha256"] != "AABB" || inst["insecure"] != true {
+		t.Fatalf("GET proxmox tls: %v", inst)
+	}
+
+	res = doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
+		`{"id":"casa","caPem":"","fingerprintSha256":"","insecure":false}`)
+	if res.StatusCode != 204 {
+		body := readJSON(t, res)
+		t.Fatalf("PUT proxmox tls clear: %d %v", res.StatusCode, body)
+	}
+	res = doReq(t, "GET", srv.URL+"/api/config/proxmox", cookie, "")
+	body = readJSON(t, res)
+	instances, _ = body["instances"].([]any)
+	inst, _ = instances[0].(map[string]any)
+	if inst["caPem"] != "" || inst["fingerprintSha256"] != "" || inst["insecure"] != false {
+		t.Fatalf("GET proxmox tls clear: %v", inst)
+	}
+}
+
 // The Proxmox test endpoint: a failure is a result the form can show, not an
 // HTTP error, and it needs a session like the rest of the config API.
 func TestProxmoxTestEndpoint(t *testing.T) {

+ 70 - 9
server-go/internal/pve/pve.go

@@ -11,14 +11,19 @@
 //
 //	Authorization: PVEAPIToken=USER@REALM!TOKENID=UUID
 //
-// TLS: el certificado del cluster es self-signed (pve-api-daemon genera uno
-// propio); el cliente acepta cualquier cert (configurable en el futuro con
-// CA fija). Solo lectura: GET únicamente.
+// TLS: el certificado del cluster suele ser self-signed. Por defecto se valida
+// contra las raíces del sistema; se puede fijar una CA (caPem) o el SHA-256 del
+// certificado hoja (fingerprintSha256). "insecure" desactiva la validación de
+// forma explícita. Solo lectura: GET únicamente.
 package pve
 
 import (
 	"context"
+	"crypto/sha256"
+	"crypto/subtle"
 	"crypto/tls"
+	"crypto/x509"
+	"encoding/hex"
 	"encoding/json"
 	"fmt"
 	"io"
@@ -37,6 +42,12 @@ type Config struct {
 	// Secret: la parte UUID del token (se muestra una sola vez al crearlo).
 	// NUNCA viaja en respuestas de la API (la config se expone sanitizada).
 	Secret string `json:"secret,omitempty"`
+	// CAPEM: CA en PEM para validar el certificado del cluster.
+	CAPEM string `json:"caPem,omitempty"`
+	// FingerprintSHA256: SHA-256 en hex del certificado hoja.
+	FingerprintSHA256 string `json:"fingerprintSha256,omitempty"`
+	// Insecure: desactiva la validación TLS. Solo para transiciones controladas.
+	Insecure bool `json:"insecure,omitempty"`
 }
 
 // Enabled: true si hay config completa.
@@ -50,27 +61,77 @@ const httpTimeout = 5 * time.Second
 type Client struct {
 	cfg Config
 	hc  *http.Client
+	err error
 }
 
-// NewClient crea el cliente (sin red: solo guarda config). TLS: los clusters
-// PVE usan un certificado self-signed (pve-api-daemon genera uno propio al
-// instalar); el cliente acepta cualquier cert (InsecureSkipVerify) porque la
-// autenticación real es el token API, no el cert. Una CA fija configurable se
-// podría añadir en el futuro si hiciera falta.
+// NewClient crea el cliente (sin red: solo guarda config). Por defecto valida
+// el certificado contra las raíces del sistema. CAPEM añade una CA,
+// FingerprintSHA256 fija el certificado hoja e Insecure desactiva la validación.
 func NewClient(cfg Config) *Client {
 	transport := http.DefaultTransport.(*http.Transport).Clone()
-	transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #561
+	tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12}
+	var clientErr error
+	switch {
+	case cfg.Insecure:
+		tlsCfg.InsecureSkipVerify = true
+	case cfg.FingerprintSHA256 != "":
+		want, err := normalizeFingerprint(cfg.FingerprintSHA256)
+		if err != nil {
+			clientErr = err
+			break
+		}
+		tlsCfg.InsecureSkipVerify = true
+		tlsCfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
+			return verifyFingerprint(rawCerts, want)
+		}
+	case cfg.CAPEM != "":
+		pool := x509.NewCertPool()
+		if !pool.AppendCertsFromPEM([]byte(cfg.CAPEM)) {
+			clientErr = fmt.Errorf("PVE: invalid caPem")
+			break
+		}
+		tlsCfg.RootCAs = pool
+	}
+	transport.TLSClientConfig = tlsCfg
 	return &Client{
 		cfg: cfg,
 		hc:  &http.Client{Timeout: httpTimeout, Transport: transport},
+		err: clientErr,
 	}
 }
 
+func normalizeFingerprint(v string) (string, error) {
+	s := strings.ToLower(strings.TrimSpace(v))
+	s = strings.NewReplacer(":", "", " ", "", "-", "").Replace(s)
+	if len(s) != 64 {
+		return "", fmt.Errorf("PVE: fingerprintSha256 must be 64 hex characters")
+	}
+	if _, err := hex.DecodeString(s); err != nil {
+		return "", fmt.Errorf("PVE: invalid fingerprintSha256: %w", err)
+	}
+	return s, nil
+}
+
+func verifyFingerprint(rawCerts [][]byte, want string) error {
+	if len(rawCerts) == 0 {
+		return fmt.Errorf("PVE: no peer certificate")
+	}
+	sum := sha256.Sum256(rawCerts[0])
+	got := hex.EncodeToString(sum[:])
+	if subtle.ConstantTimeCompare([]byte(got), []byte(want)) != 1 {
+		return fmt.Errorf("PVE: certificate fingerprint mismatch")
+	}
+	return nil
+}
+
 func (c *Client) authHeader() string {
 	return "PVEAPIToken=" + c.cfg.TokenID + "=" + c.cfg.Secret
 }
 
 func (c *Client) get(ctx context.Context, path string, dst any) error {
+	if c.err != nil {
+		return c.err
+	}
 	req, err := http.NewRequestWithContext(ctx, "GET", c.cfg.URL+path, nil)
 	if err != nil {
 		return err

+ 40 - 0
server-go/internal/pve/pve_test.go

@@ -2,6 +2,9 @@ package pve
 
 import (
 	"context"
+	"crypto/sha256"
+	"encoding/hex"
+	"encoding/pem"
 	"net/http"
 	"net/http/httptest"
 	"reflect"
@@ -285,3 +288,40 @@ func TestNodeIPWithoutAnyAddress(t *testing.T) {
 		t.Fatalf("ip=%q err=%v", ip, err)
 	}
 }
+
+func TestClientTLSVerification(t *testing.T) {
+	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "application/json")
+		w.Write([]byte(`{"data":[]}`))
+	}))
+	defer srv.Close()
+
+	cert := srv.Certificate()
+	caPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
+	sum := sha256.Sum256(cert.Raw)
+	fingerprint := hex.EncodeToString(sum[:])
+
+	base := Config{URL: srv.URL, TokenID: "root@pam!netpulse", Secret: "uuid-secret"}
+	tests := []struct {
+		name    string
+		mutate  func(*Config)
+		wantErr bool
+	}{
+		{name: "default rejects self-signed", wantErr: true},
+		{name: "configured CA", mutate: func(c *Config) { c.CAPEM = string(caPEM) }},
+		{name: "pinned fingerprint", mutate: func(c *Config) { c.FingerprintSHA256 = fingerprint }},
+		{name: "wrong fingerprint", mutate: func(c *Config) { c.FingerprintSHA256 = strings.Repeat("0", 64) }, wantErr: true},
+		{name: "explicit insecure", mutate: func(c *Config) { c.Insecure = true }},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			cfg := base
+			if tt.mutate != nil {
+				tt.mutate(&cfg)
+			}
+			if _, err := NewClient(cfg).ClusterResources(context.Background()); (err != nil) != tt.wantErr {
+				t.Fatalf("error: got %v wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}