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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Expose infrastructure credentials following redirects to another origin
pulse-triage[bot]5abea1941909
diff --git a/pkg/pbs/client_redirect_test.go b/pkg/pbs/client_redirect_test.gonew file mode 100644index 0000000000..aec8a5b9c3--- /dev/null+++ b/pkg/pbs/client_redirect_test.go@@ -0,0 +1,112 @@+package pbs++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// Exercise the actual client constructors and both password encodings, not+// just a synthetic Authorization header on a general-purpose HTTP client.+func TestInfrastructureCredentialRedirectCannotLeaveOrigin(t *testing.T) {+ for _, trust := range []string{"explicit-opt-out", "pin"} {+ for _, auth := range []string{"token", "ticket-and-csrf", "password-json", "password-form"} {+ t.Run(trust+"/"+auth, func(t *testing.T) {+ var sourceRequests, destinationRequests atomic.Int32+ sink := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ destinationRequests.Add(1)+ io.Copy(io.Discard, r.Body)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"data":{"ticket":"synthetic-ticket","CSRFPreventionToken":"synthetic-csrf"}}`))+ }))+ defer sink.Close()+ source := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ sourceRequests.Add(1)+ if auth == "password-form" && r.Header.Get("Content-Type") == "application/json" {+ http.Error(w, "form required", http.StatusUnsupportedMediaType)+ return+ }+ http.Redirect(w, r, sink.URL+"/redirected", http.StatusTemporaryRedirect)+ }))+ defer source.Close()+ cfg := ClientConfig{Host: source.URL, TokenName: "synthetic@pbs!pulse", TokenValue: "synthetic-token"}+ if trust == "pin" {+ cfg.VerifySSL = true+ digest := sha256.Sum256(source.Certificate().Raw)+ cfg.Fingerprint = hex.EncodeToString(digest[:])+ }+ var err error+ if strings.HasPrefix(auth, "password-") {+ cfg.TokenName, cfg.TokenValue = "", ""+ cfg.User, cfg.Password = "synthetic@pbs", "synthetic-password"+ _, err = NewClient(cfg)+ } else {+ var client *Client+ client, err = NewClient(cfg)+ if err != nil {+ t.Fatal(err)+ }+ defer client.httpClient.CloseIdleConnections()+ if auth == "ticket-and-csrf" {+ client.auth.tokenName, client.auth.tokenValue = "", ""+ client.auth.ticket, client.auth.csrfToken = "synthetic-ticket", "synthetic-csrf"+ client.auth.expiresAt = time.Now().Add(time.Hour)+ }+ var response *http.Response+ response, err = client.request(context.Background(), "POST", "/synthetic-action", url.Values{"action": {"synthetic-action"}})+ if response != nil {+ response.Body.Close()+ }+ }+ wantSource := int32(1)+ if auth == "password-form" {+ wantSource = 2+ }+ if err == nil || !strings.Contains(err.Error(), "same origin") || destinationRequests.Load() != 0 || sourceRequests.Load() != wantSource {+ t.Fatalf("credential redirect: source=%d want=%d destination=%d err=%v",+ sourceRequests.Load(), wantSource, destinationRequests.Load(), err)+ }+ })+ }+ }+}++func TestInfrastructureTokenSameOriginProxyRedirect(t *testing.T) {+ var requests atomic.Int32+ source := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ if r.Header.Get("Authorization") == "" {+ t.Error("same-origin request lost token authentication")+ }+ if r.URL.Path == "/api2/json/version" {+ http.Redirect(w, r, "/proxy/api2/json/version", http.StatusTemporaryRedirect)+ return+ }+ if r.URL.Path != "/proxy/api2/json/version" {+ t.Errorf("unexpected proxy path: %s", r.URL.Path)+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"data":{}}`))+ }))+ defer source.Close()+ client, err := NewClient(ClientConfig{Host: source.URL, TokenName: "synthetic@pbs!pulse", TokenValue: "synthetic-token"})+ if err != nil {+ t.Fatal(err)+ }+ defer client.httpClient.CloseIdleConnections()+ response, err := client.get(context.Background(), "/version")+ if response != nil {+ response.Body.Close()+ }+ if err != nil || requests.Load() != 2 {+ t.Fatalf("same-origin proxy path stopped: requests=%d err=%v", requests.Load(), err)+ }+}diff --git a/pkg/proxmox/client_redirect_test.go b/pkg/proxmox/client_redirect_test.gonew file mode 100644index 0000000000..6a32597b9e--- /dev/null+++ b/pkg/proxmox/client_redirect_test.go@@ -0,0 +1,112 @@+package proxmox++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// Exercise the actual client constructors and both password encodings, not+// just a synthetic Authorization header on a general-purpose HTTP client.+func TestInfrastructureCredentialRedirectCannotLeaveOrigin(t *testing.T) {+ for _, trust := range []string{"explicit-opt-out", "pin"} {+ for _, auth := range []string{"token", "ticket-and-csrf", "password-json", "password-form"} {+ t.Run(trust+"/"+auth, func(t *testing.T) {+ var sourceRequests, destinationRequests atomic.Int32+ sink := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ destinationRequests.Add(1)+ io.Copy(io.Discard, r.Body)+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"data":{"ticket":"synthetic-ticket","CSRFPreventionToken":"synthetic-csrf"}}`))+ }))+ defer sink.Close()+ source := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ sourceRequests.Add(1)+ if auth == "password-form" && r.Header.Get("Content-Type") == "application/json" {+ http.Error(w, "form required", http.StatusUnsupportedMediaType)+ return+ }+ http.Redirect(w, r, sink.URL+"/redirected", http.StatusTemporaryRedirect)+ }))+ defer source.Close()+ cfg := ClientConfig{Host: source.URL, TokenName: "synthetic@pam!pulse", TokenValue: "synthetic-token"}+ if trust == "pin" {+ cfg.VerifySSL = true+ digest := sha256.Sum256(source.Certificate().Raw)+ cfg.Fingerprint = hex.EncodeToString(digest[:])+ }+ var err error+ if strings.HasPrefix(auth, "password-") {+ cfg.TokenName, cfg.TokenValue = "", ""+ cfg.User, cfg.Password = "synthetic@pam", "synthetic-password"+ _, err = NewClient(cfg)+ } else {+ var client *Client+ client, err = NewClient(cfg)+ if err != nil {+ t.Fatal(err)+ }+ defer client.httpClient.CloseIdleConnections()+ if auth == "ticket-and-csrf" {+ client.auth.tokenName, client.auth.tokenValue = "", ""+ client.auth.ticket, client.auth.csrfToken = "synthetic-ticket", "synthetic-csrf"+ client.auth.expiresAt = time.Now().Add(time.Hour)+ }+ var response *http.Response+ response, err = client.request(context.Background(), "POST", "/synthetic-action", url.Values{"action": {"synthetic-action"}})+ if response != nil {+ response.Body.Close()+ }+ }+ wantSource := int32(1)+ if auth == "password-form" {+ wantSource = 2+ }+ if err == nil || !strings.Contains(err.Error(), "same origin") || destinationRequests.Load() != 0 || sourceRequests.Load() != wantSource {+ t.Fatalf("credential redirect: source=%d want=%d destination=%d err=%v",+ sourceRequests.Load(), wantSource, destinationRequests.Load(), err)+ }+ })+ }+ }+}++func TestInfrastructureTokenSameOriginProxyRedirect(t *testing.T) {+ var requests atomic.Int32+ source := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests.Add(1)+ if r.Header.Get("Authorization") == "" {+ t.Error("same-origin request lost token authentication")+ }+ if r.URL.Path == "/api2/json/version" {+ http.Redirect(w, r, "/proxy/api2/json/version", http.StatusTemporaryRedirect)+ return+ }+ if r.URL.Path != "/proxy/api2/json/version" {+ t.Errorf("unexpected proxy path: %s", r.URL.Path)+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"data":{}}`))+ }))+ defer source.Close()+ client, err := NewClient(ClientConfig{Host: source.URL, TokenName: "synthetic@pam!pulse", TokenValue: "synthetic-token"})+ if err != nil {+ t.Fatal(err)+ }+ defer client.httpClient.CloseIdleConnections()+ response, err := client.get(context.Background(), "/version")+ if response != nil {+ response.Body.Close()+ }+ if err != nil || requests.Load() != 2 {+ t.Fatalf("same-origin proxy path stopped: requests=%d err=%v", requests.Load(), err)+ }+}diff --git a/pkg/tlsutil/client_redirect_test.go b/pkg/tlsutil/client_redirect_test.gonew file mode 100644index 0000000000..85ff6744d5--- /dev/null+++ b/pkg/tlsutil/client_redirect_test.go@@ -0,0 +1,153 @@+package tlsutil++import (+ "crypto/sha256"+ "crypto/x509"+ "encoding/hex"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+)++type infrastructureRedirectTransport func(*http.Request) (*http.Response, error)++func (f infrastructureRedirectTransport) RoundTrip(r *http.Request) (*http.Response, error) {+ return f(r)+}++// A recording transport proves refusal before a second request, independently+// of DNS, destination reachability or whether Go would strip selected headers.+func TestInfrastructureRedirectOriginPolicy(t *testing.T) {+ for _, status := range []int{301, 302, 303, 307, 308} {+ for _, destination := range []struct {+ name, location string+ allowed bool+ }{+ {"relative", "/proxy/version?view=full", true},+ {"same-origin", "https://pve.example.test/proxy/version", true},+ {"default-port-and-case", "https://PVE.example.test:443/proxy/version", true},+ {"downgrade", "http://pve.example.test/proxy/version", false},+ {"other-port", "https://pve.example.test:8006/proxy/version", false},+ {"subdomain", "https://peer.pve.example.test/proxy/version", false},+ {"other-host", "https://pbs.example.test/proxy/version", false},+ {"userinfo", "https://synthetic:[email protected]/proxy/version", false},+ } {+ t.Run(fmt.Sprintf("%d/%s", status, destination.name), func(t *testing.T) {+ client := CreateHTTPClient(true, "")+ calls := 0+ client.Transport = infrastructureRedirectTransport(func(r *http.Request) (*http.Response, error) {+ calls+++ response := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("{}")), Request: r}+ if calls == 1 {+ response.StatusCode = status+ response.Header.Set("Location", destination.location)+ }+ return response, nil+ })+ req, err := http.NewRequest("POST", "https://pve.example.test/api2/json/version", strings.NewReader("synthetic-body"))+ if err != nil {+ t.Fatal(err)+ }+ req.Header.Set("Authorization", "Bearer synthetic-token")+ req.Header.Set("Cookie", "PVEAuthCookie=synthetic-ticket")+ req.Header.Set("CSRFPreventionToken", "synthetic-csrf")+ response, err := client.Do(req)+ if response != nil {+ response.Body.Close()+ }+ if destination.allowed {+ if err != nil || calls != 2 {+ t.Fatalf("same-origin path redirect: requests=%d err=%v", calls, err)+ }+ } else if err == nil || calls != 1 {+ t.Fatalf("untrusted redirect reached transport: requests=%d err=%v", calls, err)+ }+ })+ }+ }+}++func TestInfrastructureRedirectChainAndLimit(t *testing.T) {+ for _, escape := range []bool{false, true} {+ t.Run(fmt.Sprintf("escape=%t", escape), func(t *testing.T) {+ client := CreateHTTPClient(false, "")+ calls := 0+ client.Transport = infrastructureRedirectTransport(func(r *http.Request) (*http.Response, error) {+ calls+++ location := fmt.Sprintf("/proxy/step-%d", calls)+ if escape && calls == 2 {+ location = "http://pve.example.test/stolen"+ }+ return &http.Response{StatusCode: 307, Header: http.Header{"Location": {location}}, Body: io.NopCloser(strings.NewReader("")), Request: r}, nil+ })+ response, err := client.Get("https://pve.example.test/api2/json/version")+ if response != nil {+ response.Body.Close()+ }+ wantCalls := 10+ if escape {+ wantCalls = 2+ }+ if err == nil || calls != wantCalls {+ t.Fatalf("chain refusal: requests=%d want=%d err=%v", calls, wantCalls, err)+ }+ })+ }+}++func TestInfrastructureRedirectRefusesConnectedOriginChanges(t *testing.T) {+ for _, mode := range []string{"ca", "pin", "explicit-opt-out"} {+ for _, destination := range []string{"plaintext", "other-tls-port"} {+ t.Run(mode+"/"+destination, func(t *testing.T) {+ var destinationRequests atomic.Int32+ sinkHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ destinationRequests.Add(1)+ io.Copy(io.Discard, r.Body)+ w.Write([]byte("{}"))+ })+ sink := httptest.NewUnstartedServer(sinkHandler)+ if destination == "plaintext" {+ sink.Start()+ } else {+ sink.StartTLS()+ }+ defer sink.Close()+ source := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, sink.URL+"/redirected", http.StatusTemporaryRedirect)+ }))+ defer source.Close()+ // httptest's TLS fixture certificate is shared by both servers:+ // pin/CA rejection must not accidentally stand in for origin policy.+ client := CreateHTTPClient(mode != "explicit-opt-out", "")+ transport := client.Transport.(*http.Transport)+ if mode == "pin" {+ digest := sha256.Sum256(source.Certificate().Raw)+ transport.TLSClientConfig = FingerprintVerifier(hex.EncodeToString(digest[:]))+ } else if mode == "ca" {+ roots := x509.NewCertPool()+ roots.AddCert(source.Certificate())+ transport.TLSClientConfig.RootCAs = roots+ }+ defer client.CloseIdleConnections()+ req, err := http.NewRequest("POST", source.URL+"/api2/json/access/ticket", strings.NewReader("synthetic-password"))+ if err != nil {+ t.Fatal(err)+ }+ req.Header.Set("Authorization", "Bearer synthetic-token")+ req.Header.Set("Cookie", "PVEAuthCookie=synthetic-ticket")+ req.Header.Set("CSRFPreventionToken", "synthetic-csrf")+ response, err := client.Do(req)+ if response != nil {+ response.Body.Close()+ }+ if err == nil || !strings.Contains(err.Error(), "same origin") || destinationRequests.Load() != 0 {+ t.Fatalf("changed origin reached actual destination: requests=%d err=%v", destinationRequests.Load(), err)+ }+ })+ }+ }+}