Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix: Per-node TLS fingerprints for cluster peers (TOFU)

rcourtmane0dc6695fcc2
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.go
index b15b81522f..c33eaa5cbc 100644
--- a/internal/api/config_handlers.go
+++ b/internal/api/config_handlers.go
@@ -35,6 +35,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/pkg/pbs"
"github.com/rcourtman/pulse-go-rewrite/pkg/pmg"
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/tlsutil"
"github.com/rs/zerolog/log"
)
@@ -541,8 +542,9 @@ func ensureHostHasPort(host, port string) string {
}
// validateNodeAPI tests if a cluster node has a working Proxmox API
-// This helps filter out qdevice VMs and other non-Proxmox participants
-func validateNodeAPI(clusterNode proxmox.ClusterStatus, baseConfig proxmox.ClientConfig) bool {
+// This helps filter out qdevice VMs and other non-Proxmox participants.
+// Returns (isValid, fingerprint) - fingerprint is captured for TOFU (Trust On First Use).
+func validateNodeAPI(clusterNode proxmox.ClusterStatus, baseConfig proxmox.ClientConfig) (bool, string) {
// Determine the host to test - prefer IP if available, otherwise use node name
testHost := clusterNode.IP
if testHost == "" {
@@ -551,7 +553,7 @@ func validateNodeAPI(clusterNode proxmox.ClusterStatus, baseConfig proxmox.Clien
// Skip empty hostnames (shouldn't happen but be safe)
if testHost == "" {
- return false
+ return false, ""
}
scheme, defaultPort := deriveSchemeAndPort(baseConfig.Host)
@@ -572,6 +574,24 @@ func validateNodeAPI(clusterNode proxmox.ClusterStatus, baseConfig proxmox.Clien
Str("test_host", testConfig.Host).
Msg("Validating Proxmox API for cluster node")
+ // Capture the fingerprint for TOFU (Trust On First Use)
+ var capturedFingerprint string
+ if testHost != "" {
+ fp, err := tlsutil.FetchFingerprint(testConfig.Host)
+ if err != nil {
+ log.Debug().
+ Str("node", clusterNode.Name).
+ Err(err).
+ Msg("Could not fetch TLS fingerprint for cluster node")
+ } else {
+ capturedFingerprint = fp
+ log.Debug().
+ Str("node", clusterNode.Name).
+ Str("fingerprint", fp[:16]+"...").
+ Msg("Captured TLS fingerprint for cluster node")
+ }
+ }
+
// Try to create a client and make a simple API call
testClient, err := proxmox.NewClient(testConfig)
if err != nil {
@@ -595,7 +615,7 @@ func validateNodeAPI(clusterNode proxmox.ClusterStatus, baseConfig proxmox.Clien
Str("node", clusterNode.Name).
Err(err).
Msg("Failed to create test client for cluster node")
- return false
+ return false, ""
}
}
@@ -615,21 +635,21 @@ func validateNodeAPI(clusterNode proxmox.ClusterStatus, baseConfig proxmox.Clien
Str("node", clusterNode.Name).
Err(err).
Msg("Cluster node API responded but denied access; accepting for discovery")
- return true
+ return true, capturedFingerprint
}
log.Debug().
Str("node", clusterNode.Name).
Err(err).
Msg("Node failed Proxmox API validation - likely not a Proxmox node")
- return false
+ return false, ""
}
log.Debug().
Str("node", clusterNode.Name).
Msg("Node passed Proxmox API validation")
- return true
+ return true, capturedFingerprint
}
// findExistingGuestURL looks up the GuestURL for a node from existing endpoints
@@ -718,7 +738,9 @@ func detectPVECluster(clientConfig proxmox.ClientConfig, nodeName string, existi
for _, clusterNode := range clusterNodes {
// Validate that this node actually has a working Proxmox API
// This filters out qdevice VMs and other non-Proxmox participants
- if !validateNodeAPI(clusterNode, clientConfig) {
+ // Also captures the node's TLS fingerprint for TOFU
+ isValid, nodeFingerprint := validateNodeAPI(clusterNode, clientConfig)
+ if !isValid {
log.Debug().
Str("node", clusterNode.Name).
Str("ip", clusterNode.IP).
@@ -730,11 +752,12 @@ func detectPVECluster(clientConfig proxmox.ClientConfig, nodeName string, existi
// Build the host URL with proper port
// Store hostname in Host field (for TLS validation), IP separately
endpoint := config.ClusterEndpoint{
- NodeID: clusterNode.ID,
- NodeName: clusterNode.Name,
- GuestURL: findExistingGuestURL(clusterNode.Name, existingEndpoints),
- Online: clusterNode.Online == 1,
- LastSeen: time.Now(),
+ NodeID: clusterNode.ID,
+ NodeName: clusterNode.Name,
+ GuestURL: findExistingGuestURL(clusterNode.Name, existingEndpoints),
+ Fingerprint: nodeFingerprint, // Store captured fingerprint for per-node TLS verification
+ Online: clusterNode.Online == 1,
+ LastSeen: time.Now(),
}
// Populate Host field with hostname (if available) for TLS certificate validation
diff --git a/internal/config/config.go b/internal/config/config.go
index 79f82aeb40..94fb252b88 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -449,6 +449,7 @@ type ClusterEndpoint struct {
Host string // Full URL (e.g., https://node1.lan:8006)
GuestURL string // Optional guest-accessible URL (for navigation)
IP string // IP address
+ Fingerprint string // TLS certificate fingerprint (SHA256, auto-captured via TOFU)
Online bool // Current online status from Proxmox
LastSeen time.Time // Last successful connection
PulseReachable *bool // Pulse's view: can Pulse reach this endpoint? nil = not yet checked
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index efcc98660c..3e2c4930ae 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -3211,6 +3211,7 @@ func New(cfg *config.Config) (*Monitor, error) {
// If not, use the main host for all connections (Proxmox will route cluster API calls)
hasValidEndpoints := false
endpoints := make([]string, 0, len(pve.ClusterEndpoints))
+ endpointFingerprints := make(map[string]string)
for _, ep := range pve.ClusterEndpoints {
hasFingerprint := pve.Fingerprint != ""
@@ -3235,6 +3236,10 @@ func New(cfg *config.Config) (*Monitor, error) {
}
endpoints = append(endpoints, effectiveURL)
+ // Store per-endpoint fingerprint for TOFU (Trust On First Use)
+ if ep.Fingerprint != "" {
+ endpointFingerprints[effectiveURL] = ep.Fingerprint
+ }
}
// If endpoints are just node names (not FQDNs or IPs), use main host only
@@ -3254,6 +3259,7 @@ func New(cfg *config.Config) (*Monitor, error) {
log.Info().
Str("cluster", pve.ClusterName).
Strs("endpoints", endpoints).
+ Int("fingerprints", len(endpointFingerprints)).
Msg("Creating cluster-aware client")
clientConfig := config.CreateProxmoxConfig(&pve)
@@ -3262,6 +3268,7 @@ func New(cfg *config.Config) (*Monitor, error) {
pve.Name,
clientConfig,
endpoints,
+ endpointFingerprints,
)
m.pveClients[pve.Name] = clusterClient
log.Info().
@@ -3971,6 +3978,7 @@ func (m *Monitor) retryFailedConnections(ctx context.Context) {
// Create cluster client
hasValidEndpoints := false
endpoints := make([]string, 0, len(pve.ClusterEndpoints))
+ endpointFingerprints := make(map[string]string)
for _, ep := range pve.ClusterEndpoints {
host := ep.IP
@@ -3987,6 +3995,10 @@ func (m *Monitor) retryFailedConnections(ctx context.Context) {
host = fmt.Sprintf("https://%s:8006", host)
}
endpoints = append(endpoints, host)
+ // Store per-endpoint fingerprint for TOFU
+ if ep.Fingerprint != "" {
+ endpointFingerprints[host] = ep.Fingerprint
+ }
}
if !hasValidEndpoints || len(endpoints) == 0 {
@@ -3998,7 +4010,7 @@ func (m *Monitor) retryFailedConnections(ctx context.Context) {
clientConfig := config.CreateProxmoxConfig(&pve)
clientConfig.Timeout = m.config.ConnectionTimeout
- clusterClient := proxmox.NewClusterClient(pve.Name, clientConfig, endpoints)
+ clusterClient := proxmox.NewClusterClient(pve.Name, clientConfig, endpoints, endpointFingerprints)
m.mu.Lock()
m.pveClients[pve.Name] = clusterClient
diff --git a/pkg/proxmox/cluster_client.go b/pkg/proxmox/cluster_client.go
index 955c5216c0..c6a40e0421 100644
--- a/pkg/proxmox/cluster_client.go
+++ b/pkg/proxmox/cluster_client.go
@@ -15,15 +15,16 @@ import (
// ClusterClient wraps multiple Proxmox clients for cluster-aware operations
type ClusterClient struct {
- mu sync.RWMutex
- name string
- clients map[string]*Client // Key is node name
- endpoints []string // All available endpoints
- nodeHealth map[string]bool // Track node health
- lastHealthCheck map[string]time.Time // Track last health check time
- lastError map[string]string // Track last error per endpoint
- config ClientConfig // Base config (auth info)
- rateLimitUntil map[string]time.Time // Cooldown window for rate-limited endpoints
+ mu sync.RWMutex
+ name string
+ clients map[string]*Client // Key is node name
+ endpoints []string // All available endpoints
+ endpointFingerprints map[string]string // Per-endpoint TLS fingerprints (TOFU)
+ nodeHealth map[string]bool // Track node health
+ lastHealthCheck map[string]time.Time // Track last health check time
+ lastError map[string]string // Track last error per endpoint
+ config ClientConfig // Base config (auth info)
+ rateLimitUntil map[string]time.Time // Cooldown window for rate-limited endpoints
}
const (
@@ -125,17 +126,23 @@ func sanitizeEndpointError(errMsg string) string {
return errMsg
}
-// NewClusterClient creates a new cluster-aware client
-func NewClusterClient(name string, config ClientConfig, endpoints []string) *ClusterClient {
+// NewClusterClient creates a new cluster-aware client.
+// endpointFingerprints is an optional map of endpoint URL -> TLS fingerprint for per-node certificate verification.
+// This enables TOFU (Trust On First Use) for clusters with unique self-signed certs per node.
+func NewClusterClient(name string, config ClientConfig, endpoints []string, endpointFingerprints map[string]string) *ClusterClient {
+ if endpointFingerprints == nil {
+ endpointFingerprints = make(map[string]string)
+ }
cc := &ClusterClient{
- name: name,
- clients: make(map[string]*Client),
- endpoints: endpoints,
- nodeHealth: make(map[string]bool),
- lastHealthCheck: make(map[string]time.Time),
- lastError: make(map[string]string),
- config: config,
- rateLimitUntil: make(map[string]time.Time),
+ name: name,
+ clients: make(map[string]*Client),
+ endpoints: endpoints,
+ endpointFingerprints: endpointFingerprints,
+ nodeHealth: make(map[string]bool),
+ lastHealthCheck: make(map[string]time.Time),
+ lastError: make(map[string]string),
+ config: config,
+ rateLimitUntil: make(map[string]time.Time),
}
// Initialize all endpoints as unknown (will be tested on first use)
@@ -152,6 +159,15 @@ func NewClusterClient(name string, config ClientConfig, endpoints []string) *Clu
return cc
}
+// getEndpointFingerprint returns the TLS fingerprint to use for a specific endpoint.
+// It prefers the per-endpoint fingerprint (TOFU) over the base config fingerprint.
+func (cc *ClusterClient) getEndpointFingerprint(endpoint string) string {
+ if fp, ok := cc.endpointFingerprints[endpoint]; ok && fp != "" {
+ return fp
+ }
+ return cc.config.Fingerprint
+}
+
// initialHealthCheck performs a quick parallel health check on all endpoints
func (cc *ClusterClient) initialHealthCheck() {
// Skip initial health check if there's only one endpoint
@@ -176,6 +192,7 @@ func (cc *ClusterClient) initialHealthCheck() {
// Try a quick connection test with slightly longer timeout for initial check
cfg := cc.config
cfg.Host = ep
+ cfg.Fingerprint = cc.getEndpointFingerprint(ep)
cfg.Timeout = 5 * time.Second
testClient, err := NewClient(cfg)
@@ -207,6 +224,7 @@ func (cc *ClusterClient) initialHealthCheck() {
// Node is healthy - create a proper client with full timeout for actual use
fullCfg := cc.config
fullCfg.Host = ep
+ fullCfg.Fingerprint = cc.getEndpointFingerprint(ep)
fullClient, clientErr := NewClient(fullCfg)
if clientErr != nil {
cc.nodeHealth[ep] = false
@@ -381,6 +399,7 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)
// Create new client with shorter timeout for initial test
cfg := cc.config
cfg.Host = selectedEndpoint
+ cfg.Fingerprint = cc.getEndpointFingerprint(selectedEndpoint)
// First try with a short timeout to quickly detect offline nodes
testCfg := cfg
@@ -549,6 +568,7 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {
// typically takes ~3 seconds on local networks
cfg := cc.config
cfg.Host = ep
+ cfg.Fingerprint = cc.getEndpointFingerprint(ep)
cfg.Timeout = 5 * time.Second
testClient, err := NewClient(cfg)
diff --git a/pkg/proxmox/cluster_client_test.go b/pkg/proxmox/cluster_client_test.go
index 04345f98da..5daf67ae43 100644
--- a/pkg/proxmox/cluster_client_test.go
+++ b/pkg/proxmox/cluster_client_test.go
@@ -41,7 +41,7 @@ func TestClusterClientHandlesRateLimitWithoutMarkingUnhealthy(t *testing.T) {
Timeout: 2 * time.Second,
}
- cc := NewClusterClient("test-cluster", cfg, []string{server.URL})
+ cc := NewClusterClient("test-cluster", cfg, []string{server.URL}, nil)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
@@ -89,7 +89,7 @@ func TestClusterClientIgnoresGuestAgentTimeoutForHealth(t *testing.T) {
Timeout: 2 * time.Second,
}
- cc := NewClusterClient("test-cluster", cfg, []string{server.URL})
+ cc := NewClusterClient("test-cluster", cfg, []string{server.URL}, nil)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
@@ -385,7 +385,7 @@ func TestClusterClient_GetNodes_PermanentFailure(t *testing.T) {
Timeout: 2 * time.Second,
}
- cc := NewClusterClient("test-cluster", cfg, []string{server.URL})
+ cc := NewClusterClient("test-cluster", cfg, []string{server.URL}, nil)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
diff --git a/pkg/tlsutil/fingerprint.go b/pkg/tlsutil/fingerprint.go
index 096d81032b..01f7792aec 100644
--- a/pkg/tlsutil/fingerprint.go
+++ b/pkg/tlsutil/fingerprint.go
@@ -1,16 +1,69 @@
package tlsutil
import (
+ "context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"fmt"
+ "net"
"net/http"
+ "net/url"
"strings"
"time"
)
+// FetchFingerprint connects to a host and returns the SHA256 fingerprint of its TLS certificate.
+// This is used for TOFU (Trust On First Use) when discovering cluster peers.
+// The host should be in the format "hostname:port" or "https://hostname:port".
+func FetchFingerprint(host string) (string, error) {
+ // Normalize the host to just host:port format
+ targetHost := host
+ if strings.HasPrefix(host, "https://") || strings.HasPrefix(host, "http://") {
+ parsed, err := url.Parse(host)
+ if err != nil {
+ return "", fmt.Errorf("failed to parse host URL: %w", err)
+ }
+ targetHost = parsed.Host
+ }
+
+ // Ensure port is present (default to 8006 for Proxmox)
+ if _, _, err := net.SplitHostPort(targetHost); err != nil {
+ targetHost = targetHost + ":8006"
+ }
+
+ // Create a TLS connection with InsecureSkipVerify to fetch the cert
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ dialer := &net.Dialer{Timeout: 5 * time.Second}
+ conn, err := tls.DialWithDialer(dialer, "tcp", targetHost, &tls.Config{
+ InsecureSkipVerify: true,
+ })
+ if err != nil {
+ return "", fmt.Errorf("failed to connect to %s: %w", targetHost, err)
+ }
+ defer conn.Close()
+
+ // Check context wasn't cancelled
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ default:
+ }
+
+ // Get the peer certificates
+ certs := conn.ConnectionState().PeerCertificates
+ if len(certs) == 0 {
+ return "", fmt.Errorf("no certificates presented by %s", targetHost)
+ }
+
+ // Calculate SHA256 fingerprint of the leaf certificate
+ fingerprint := sha256.Sum256(certs[0].Raw)
+ return hex.EncodeToString(fingerprint[:]), nil
+}
+
// FingerprintVerifier creates a custom TLS config that verifies server certificate fingerprint
func FingerprintVerifier(fingerprint string) *tls.Config {
// Normalize fingerprint (remove colons, convert to lowercase)