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.

Accept SAML LogoutResponses only for the logout they answer

rcourtman2eec0549a3b5
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 6f04936296..0ed3d19b90 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -8936,6 +8936,17 @@ install, update, removal and report identity are unchanged.
logout still takes `POST`. No agent registration, enrolment, install, update or
removal path changed.
+### SAML SLO responses bound to the logout that requested them
+
+`internal/api/saml_service.go` and `internal/api/saml_handlers.go` changed only
+so `/api/saml/{id}/slo` accepts an IdP LogoutResponse when its signed
+`InResponseTo` names an unexpired LogoutRequest that `/api/saml/{id}/logout`
+issued, once, in a browser carrying no session or the session that logout
+ended. Other responses are refused, the SLO handler writes no session or
+cookie for any response (the logout request already cleared both), and
+`/api/saml/{id}/logout` refuses a request that carries no session. No agent
+registration, enrolment, install, update or removal path changed.
+
### Demo write guard ignores websocket upgrade headers
`internal/api/demo_middleware.go` changed only so a `POST`, `PUT`, `PATCH` or
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 361bbedaa8..e95ea4078a 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -5170,6 +5170,46 @@ Single-resource report generation at `GET /api/admin/reports/generate` still
runs the configured AI narrator, a paid provider call recorded in the cost
ledger; that is a known open exception, not part of this contract.
+The SAML SLO callback at `/api/saml/{id}/slo` accepts a LogoutResponse only as
+the answer to a logout this SP started. crewjam/saml verifies the response's
+signature, `Destination`, `Issuer` and `Status` and rejects one issued more
+than 90 seconds ago, but never checks its `InResponseTo`, and the IdP signs its
+answer to every user's logout, so a valid signature alone let one user replay
+the answer to their own logout through a cross-site `GET` and clear another
+user's session. `SAMLService.MakeLogoutRequest` in
+`internal/api/saml_service.go` therefore records each LogoutRequest ID, on the
+provider's own service, against the session-store hash of the session
+`handleSAMLLogout` is ending. A record is honored for ten minutes unless the
+1,024-record cap evicts it first, oldest first. `SAMLService.ValidateLogoutResponse`
+reads `InResponseTo` from the same payload crewjam verified, taking only the
+root element's attribute written without a prefix, the one the signature
+covers (a namespace declaration such as `xmlns:InResponseTo` is ignored,
+because exclusive canonicalization can leave an unused one out of the signed
+form), and
+spends the matching record. The response is accepted only when that record
+exists and is unexpired, and the browser carries either no session cookie (the
+normal case, because `handleSAMLLogout` clears the cookie before redirecting to
+the IdP) or the session that request ended. Unsolicited, expired, evicted,
+replayed and other-session responses are refused with `403` and a failed
+`saml_slo_callback` audit event, and the handler leaves sessions and cookies
+alone. A misdelivered response still spends its record, so each LogoutRequest
+is answered at most once. The handler writes no session state or cookie for an
+accepted response either: `handleSAMLLogout` already invalidated the session
+and expired its cookies, and a cross-site HTTP-POST delivery withholds the
+`SameSite=Lax` cookie, so a deletion cookie written there could log out a
+browser whose session the request never presented. For the same reason
+`handleSAMLLogout` answers `401` to a request that carries no session cookie,
+API-token-only callers included, instead of falling back to a cookie-clearing
+logout: the SAML routes are public and skip CSRF, so that fallback was a
+cross-site forced logout of a kind a deployment with authentication configured
+refuses on `/api/logout` as unauthenticated. The records live in memory,
+so a restart or provider re-initialization during the IdP round trip leaves the
+returning response unmatched and refused; the local session was already
+cleared when logout began. `TestSAMLSLOAuditsLogoutResponseNotBoundToSession`
+in `internal/api/audit_handlers_test.go` replays one user's signed response
+into another user's browser and proves the victim's session survives and the
+refusal is audited.
+
Alert delivery diagnosis is a read-only monitoring API contract.
`GET /api/alerts/delivery-diagnosis?alertIdentifier=<id>` returns the alert
manager's current delivery-policy projection for one active alert, including
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index d5112ce305..3d353be523 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -6876,6 +6876,16 @@ so `/api/discovery/settings` (`PUT` or `POST`) and `/api/saml/{id}/logout`
of changing the discovery staleness threshold or clearing a session. No
storage, retention, backup, migration or recovery path is added or moved.
+### SAML SLO responses bound to the logout that requested them
+
+`internal/api/saml_service.go` keeps each outstanding SAML LogoutRequest ID in
+memory on the provider's service, bound to the session-store hash of the
+session being logged out, and honors it for ten minutes (at most 1,024
+records; expired ones are dropped on the next logout). `internal/api/saml_handlers.go`
+refuses a LogoutResponse that does not answer one of them. The records are not
+persisted, and the SLO handler no longer writes session state. No storage,
+retention, backup, migration or recovery path is added or moved.
+
### Demo write guard ignores websocket upgrade headers
`internal/api/demo_middleware.go` no longer exempts every request carrying
diff --git a/internal/api/audit_handlers_test.go b/internal/api/audit_handlers_test.go
index 117f882d03..57e40f74cc 100644
--- a/internal/api/audit_handlers_test.go
+++ b/internal/api/audit_handlers_test.go
@@ -1081,3 +1081,53 @@ func TestParseAuditLimitCapsOversizedRequests(t *testing.T) {
})
}
}
+
+// A signed SAML LogoutResponse answering one user's logout, replayed into
+// another user's browser through a cross-site GET to /slo, is refused like the
+// other SLO refusals: the victim keeps their session and one failed
+// saml_slo_callback audit event names the binding failure. The genuine
+// completion of a logout still audits success.
+func TestSAMLSLOAuditsLogoutResponseNotBoundToSession(t *testing.T) {
+ previousManager := GetTenantAuditManager()
+ SetTenantAuditManager(nil)
+ t.Cleanup(func() {
+ SetTenantAuditManager(previousManager)
+ })
+ logger := &testAuditLoggerNoVerify{}
+ setAuditLogger(t, logger)
+
+ router, idp := newSAMLSLOTestRouter(t)
+ attackerRequestID := startSAMLTestLogout(t, router, newSAMLTestSession(t, "attacker"))
+ victim := newSAMLTestSession(t, "victim")
+
+ sloCallbackEvents := func() []audit.Event {
+ var events []audit.Event
+ for _, event := range logger.events {
+ if event.EventType == "saml_slo_callback" {
+ events = append(events, event)
+ }
+ }
+ return events
+ }
+
+ rec := deliverSAMLTestLogoutResponse(router, idp.redirectQuery(t, attackerRequestID), victim)
+ assertSAMLSLORefused(t, rec, "another session's response")
+ if !ValidateSession(victim) {
+ t.Fatal("another user's LogoutResponse cleared the victim's session")
+ }
+ refusals := sloCallbackEvents()
+ if len(refusals) != 1 || refusals[0].Success ||
+ refusals[0].Details != "LogoutResponse does not answer an outstanding logout request for this session" {
+ t.Fatalf("expected one failed saml_slo_callback binding refusal, got %+v", refusals)
+ }
+
+ logger.events = nil
+ victimRequestID := startSAMLTestLogout(t, router, victim)
+ if rec := deliverSAMLTestLogoutResponse(router, idp.redirectQuery(t, victimRequestID), ""); rec.Code != http.StatusFound {
+ t.Fatalf("genuine completion: expected status %d, got %d body=%q", http.StatusFound, rec.Code, rec.Body.String())
+ }
+ completions := sloCallbackEvents()
+ if len(completions) != 1 || !completions[0].Success || completions[0].Details != "SAML SLO complete" {
+ t.Fatalf("expected one successful saml_slo_callback event, got %+v", completions)
+ }
+}
diff --git a/internal/api/saml_handlers.go b/internal/api/saml_handlers.go
index 6ce686e585..b34723de02 100644
--- a/internal/api/saml_handlers.go
+++ b/internal/api/saml_handlers.go
@@ -3,6 +3,7 @@ package api
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"net/http"
"strings"
@@ -384,6 +385,17 @@ func (r *Router) handleSAMLLogout(w http.ResponseWriter, req *http.Request) {
if !requireRequestMethod(w, req, http.MethodPost) {
return
}
+ // The SAML routes are public and skip CSRF so the IdP flows can reach
+ // them, and a cross-site POST withholds the SameSite=Lax session cookie.
+ // A request carrying no session has nothing to log out, yet the deletion
+ // cookies every logout path below writes would log out whichever session
+ // that browser holds. Refuse it, as a deployment with authentication
+ // configured refuses an unauthenticated /api/logout. SP-initiated SAML
+ // logout always needs the browser session it ends.
+ if samlSessionBindingKey(req) == "" {
+ writeErrorResponse(w, http.StatusUnauthorized, "unauthorized", "Authentication required", nil)
+ return
+ }
providerID := extractSAMLProviderID(req.URL.Path, "logout")
if providerID == "" {
// Fall back to regular logout
@@ -413,11 +425,15 @@ func (r *Router) handleSAMLLogout(w http.ResponseWriter, req *http.Request) {
return
}
+ // Bind the LogoutRequest to the session it logs out before clearing it, so
+ // /slo can tell the IdP's answer to this logout from a replayed one.
+ sessionKey := samlSessionBindingKey(req)
+
// Clear local session first
r.clearSession(w, req)
// Attempt SAML SLO
- logoutURL, err := service.MakeLogoutRequest(session.NameID, session.SessionIndex)
+ logoutURL, err := service.MakeLogoutRequest(session.NameID, session.SessionIndex, sessionKey)
if err != nil {
log.Warn().Err(err).Str("provider_id", providerID).Msg("SAML SLO not available, local logout only")
LogAuditEventForTenant(GetOrgID(req.Context()), "saml_logout", "", GetClientIP(req), req.URL.Path, true, "Local logout only (SLO not available)")
@@ -437,6 +453,16 @@ func (r *Router) handleSAMLLogout(w http.ResponseWriter, req *http.Request) {
// logout DoS against any user with a SAML session. Verify the IdP's
// XML-DSig on the LogoutResponse before clearing anything; on validation
// failure log the audit event and refuse to mutate session state.
+//
+// A valid signature alone is not enough: the IdP signs its answer to every
+// user's logout, and this route must take the HTTP-Redirect binding's GET,
+// which carries the SameSite=Lax session cookie on a cross-site navigation and
+// skips the CSRF check. The response must also answer an outstanding
+// LogoutRequest from handleSAMLLogout, once, in a browser carrying either no
+// session (handleSAMLLogout already cleared its cookie) or the session that
+// request logged out. Anything else is a replay or a forced logout and is
+// refused the same way. Completion writes no session state or cookie:
+// handleSAMLLogout already did that before redirecting to the IdP.
func (r *Router) handleSAMLSLO(w http.ResponseWriter, req *http.Request) {
providerID := extractSAMLProviderID(req.URL.Path, "slo")
if providerID == "" || !validateProviderID(providerID) {
@@ -482,7 +508,17 @@ func (r *Router) handleSAMLSLO(w http.ResponseWriter, req *http.Request) {
return
}
- if err := service.ValidateLogoutResponse(req); err != nil {
+ if err := service.ValidateLogoutResponse(req, samlSessionBindingKey(req)); err != nil {
+ if errors.Is(err, errSAMLLogoutResponseUnbound) {
+ log.Warn().
+ Err(err).
+ Str("provider_id", providerID).
+ Str("client_ip", GetClientIP(req)).
+ Msg("SAML LogoutResponse does not answer an outstanding logout for this session — refusing to clear session")
+ LogAuditEventForTenant(GetOrgID(req.Context()), "saml_slo_callback", "", GetClientIP(req), req.URL.Path, false, "LogoutResponse does not answer an outstanding logout request for this session")
+ http.Error(w, "invalid LogoutResponse", http.StatusForbidden)
+ return
+ }
log.Warn().
Err(err).
Str("provider_id", providerID).
@@ -493,7 +529,11 @@ func (r *Router) handleSAMLSLO(w http.ResponseWriter, req *http.Request) {
return
}
- r.clearSession(w, req)
+ // handleSAMLLogout already invalidated the session this response answers
+ // and expired its cookies. Write nothing here: a cross-site HTTP-POST
+ // delivery withholds the SameSite=Lax session cookie, so this request
+ // cannot see which session the browser holds, and deletion cookies would
+ // log out whichever one that is.
LogAuditEventForTenant(GetOrgID(req.Context()), "saml_slo_callback", "", GetClientIP(req), req.URL.Path, true, "SAML SLO complete")
http.Redirect(w, req, "/?logout=success", http.StatusFound)
}
@@ -575,6 +615,18 @@ func (r *Router) getSAMLSessionInfo(req *http.Request) *SAMLSessionInfo {
}
}
+// samlSessionBindingKey identifies the session the request's cookie selects,
+// as the session store's token hash, or returns "" when the request carries
+// none. SLO binds each LogoutRequest to it and checks it again when the IdP's
+// LogoutResponse arrives.
+func samlSessionBindingKey(req *http.Request) string {
+ cookie, err := readSessionCookie(req)
+ if err != nil || cookie.Value == "" {
+ return ""
+ }
+ return sessionHash(cookie.Value)
+}
+
// clearSession clears the current session - properly invalidates server-side session
// and clears both pulse_session and pulse_csrf cookies
func (r *Router) clearSession(w http.ResponseWriter, req *http.Request) {
diff --git a/internal/api/saml_handlers_more_test.go b/internal/api/saml_handlers_more_test.go
index 10c04637bd..82320f9793 100644
--- a/internal/api/saml_handlers_more_test.go
+++ b/internal/api/saml_handlers_more_test.go
@@ -1,13 +1,22 @@
package api
import (
+ "bytes"
+ "compress/flate"
"context"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/pem"
+ "encoding/xml"
+ "io"
"net/http"
"net/http/httptest"
+ "net/url"
"strings"
"testing"
"time"
+ "github.com/crewjam/saml"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
@@ -246,6 +255,333 @@ func TestHandleSAMLSLO_RejectsIDPInitiatedLogoutRequest(t *testing.T) {
}
}
+const samlSLOTestDestination = "https://pulse.example.com/api/saml/okta/slo"
+
+// samlSLOTestIdP signs LogoutResponses with a key the SP under test trusts
+// through its IdP metadata, the way a real IdP answers a LogoutRequest.
+type samlSLOTestIdP struct {
+ signer *saml.ServiceProvider
+}
+
+// newSAMLSLOTestRouter returns a router whose "okta" provider supports SLO and
+// trusts the returned IdP's signing key, with fresh session and CSRF stores.
+func newSAMLSLOTestRouter(t *testing.T) (*Router, *samlSLOTestIdP) {
+ t.Helper()
+ dataPath := t.TempDir()
+ InitSessionStore(dataPath)
+ InitCSRFStore(dataPath)
+
+ certPEM, _, key := generateTestCert(t)
+ block, _ := pem.Decode(certPEM)
+ if block == nil {
+ t.Fatal("decode IdP certificate PEM")
+ }
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ t.Fatalf("parse IdP certificate: %v", err)
+ }
+ metadataXML := `<?xml version="1.0"?>
+<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="idp">
+ <IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
+ <KeyDescriptor use="signing">
+ <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
+ <X509Data><X509Certificate>` + base64.StdEncoding.EncodeToString(block.Bytes) + `</X509Certificate></X509Data>
+ </KeyInfo>
+ </KeyDescriptor>
+ <SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.com/sso"/>
+ <SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.com/slo"/>
+ </IDPSSODescriptor>
+</EntityDescriptor>`
+
+ router := &Router{samlManager: NewSAMLServiceManager("https://pulse.example.com")}
+ router.samlManager.services["okta"] = newTestSAMLService(t, "okta", metadataXML)
+ return router, &samlSLOTestIdP{signer: &saml.ServiceProvider{
+ EntityID: "idp",
+ Key: key,
+ Certificate: cert,
+ SignatureMethod: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
+ }}
+}
+
+// redirectQuery returns the HTTP-Redirect binding query carrying a signed,
+// successful LogoutResponse that answers requestID.
+func (idp *samlSLOTestIdP) redirectQuery(t *testing.T, requestID string) string {
+ t.Helper()
+ resp, err := idp.signer.MakeLogoutResponse(samlSLOTestDestination, requestID)
+ if err != nil {
+ t.Fatalf("sign LogoutResponse: %v", err)
+ }
+ return resp.Redirect("").RawQuery
+}
+
+// postForm returns the HTTP-POST binding form body carrying the same signed
+// LogoutResponse as redirectQuery.
+func (idp *samlSLOTestIdP) postForm(t *testing.T, requestID string) string {
+ t.Helper()
+ query, err := url.ParseQuery(idp.redirectQuery(t, requestID))
+ if err != nil {
+ t.Fatalf("parse redirect query: %v", err)
+ }
+ signedXML := inflateSAMLTestPayload(t, query.Get("SAMLResponse"))
+ return url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString(signedXML)}}.Encode()
+}
+
+func inflateSAMLTestPayload(t *testing.T, payload string) []byte {
+ t.Helper()
+ compressed, err := base64.StdEncoding.DecodeString(payload)
+ if err != nil {
+ t.Fatalf("decode SAML payload: %v", err)
+ }
+ raw, err := io.ReadAll(flate.NewReader(bytes.NewReader(compressed)))
+ if err != nil {
+ t.Fatalf("inflate SAML payload: %v", err)
+ }
+ return raw
+}
+
+// newSAMLTestSession creates a live SAML session with the okta provider.
+func newSAMLTestSession(t *testing.T, nameID string) string {
+ t.Helper()
+ token := generateSessionToken()
+ GetSessionStore().CreateSAMLSession(token, time.Hour, "agent", "127.0.0.1", nameID, &SAMLTokenInfo{
+ ProviderID: "okta",
+ NameID: nameID,
+ SessionIndex: "sess-" + nameID,
+ })
+ return token
+}
+
+// startSAMLTestLogout runs SP-initiated logout for the session and returns the
+// ID of the LogoutRequest sent to the IdP.
+func startSAMLTestLogout(t *testing.T, router *Router, token string) string {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/api/saml/okta/logout", nil)
+ req.AddCookie(&http.Cookie{Name: "pulse_session", Value: token})
+ rec := httptest.NewRecorder()
+ router.handleSAMLLogout(rec, req)
+ if rec.Code != http.StatusFound {
+ t.Fatalf("logout: expected status %d, got %d", http.StatusFound, rec.Code)
+ }
+ location, err := url.Parse(rec.Header().Get("Location"))
+ if err != nil || location.Host != "idp.example.com" {
+ t.Fatalf("logout: unexpected SLO redirect %q (%v)", rec.Header().Get("Location"), err)
+ }
+ var logoutRequest struct {
+ ID string `xml:"ID,attr"`
+ }
+ if err := xml.Unmarshal(inflateSAMLTestPayload(t, location.Query().Get("SAMLRequest")), &logoutRequest); err != nil {
+ t.Fatalf("parse LogoutRequest: %v", err)
+ }
+ if logoutRequest.ID == "" {
+ t.Fatal("LogoutRequest has no ID")
+ }
+ return logoutRequest.ID
+}
+
+// deliverSAMLTestLogoutResponse sends an HTTP-Redirect binding LogoutResponse
+// to /slo from a browser carrying the given session cookie ("" for none).
+func deliverSAMLTestLogoutResponse(router *Router, query, token string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodGet, "/api/saml/okta/slo?"+query, nil)
+ if token != "" {
+ req.AddCookie(&http.Cookie{Name: "pulse_session", Value: token})
+ }
+ rec := httptest.NewRecorder()
+ router.handleSAMLSLO(rec, req)
+ return rec
+}
+
+// postSAMLTestLogoutResponse sends an HTTP-POST binding form body to /slo as a
+// cross-site form POST does: without the SameSite=Lax session cookie.
+func postSAMLTestLogoutResponse(router *Router, form string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPost, "/api/saml/okta/slo", strings.NewReader(form))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ rec := httptest.NewRecorder()
+ router.handleSAMLSLO(rec, req)
+ return rec
+}
+
+func assertSAMLSLORefused(t *testing.T, rec *httptest.ResponseRecorder, label string) {
+ t.Helper()
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("%s: expected status %d, got %d body=%q", label, http.StatusForbidden, rec.Code, rec.Body.String())
+ }
+ if loc := rec.Header().Get("Location"); loc != "" {
+ t.Fatalf("%s: refused SLO must not redirect, got %q", label, loc)
+ }
+ if cookies := rec.Result().Cookies(); len(cookies) != 0 {
+ t.Fatalf("%s: refused SLO must not touch cookies, got %v", label, cookies)
+ }
+}
+
+// The browser that started SP-initiated logout comes back from the IdP without
+// a session cookie, because handleSAMLLogout cleared it before redirecting.
+// The IdP's signed answer to that logout completes it, by either binding.
+func TestHandleSAMLSLO_AcceptsAnswerToOutstandingLogout(t *testing.T) {
+ router, idp := newSAMLSLOTestRouter(t)
+
+ token := newSAMLTestSession(t, "alice")
+ requestID := startSAMLTestLogout(t, router, token)
+ if ValidateSession(token) {
+ t.Fatal("SP-initiated logout must clear the local session before redirecting")
+ }
+
+ rec := deliverSAMLTestLogoutResponse(router, idp.redirectQuery(t, requestID), "")
+ if rec.Code != http.StatusFound {
+ t.Fatalf("redirect binding: expected status %d, got %d body=%q", http.StatusFound, rec.Code, rec.Body.String())
+ }
+ if loc := rec.Header().Get("Location"); loc != "/?logout=success" {
+ t.Fatalf("redirect binding: unexpected redirect %q", loc)
+ }
+
+ token = newSAMLTestSession(t, "alice")
+ requestID = startSAMLTestLogout(t, router, token)
+ rec = postSAMLTestLogoutResponse(router, idp.postForm(t, requestID))
+ if rec.Code != http.StatusFound {
+ t.Fatalf("POST binding: expected status %d, got %d body=%q", http.StatusFound, rec.Code, rec.Body.String())
+ }
+ if loc := rec.Header().Get("Location"); loc != "/?logout=success" {
+ t.Fatalf("POST binding: unexpected redirect %q", loc)
+ }
+}
+
+// Each LogoutRequest is answered once. Replaying the IdP's response, with or
+// without a session cookie, is refused and leaves the presenting session alone.
+func TestHandleSAMLSLO_RefusesReplayedLogoutResponse(t *testing.T) {
+ router, idp := newSAMLSLOTestRouter(t)
+
+ requestID := startSAMLTestLogout(t, router, newSAMLTestSession(t, "alice"))
+ query := idp.redirectQuery(t, requestID)
+ if rec := deliverSAMLTestLogoutResponse(router, query, ""); rec.Code != http.StatusFound {
+ t.Fatalf("first delivery: expected status %d, got %d body=%q", http.StatusFound, rec.Code, rec.Body.String())
+ }
+
+ assertSAMLSLORefused(t, deliverSAMLTestLogoutResponse(router, query, ""), "replay without session")
+
+ victim := newSAMLTestSession(t, "bob")
+ assertSAMLSLORefused(t, deliverSAMLTestLogoutResponse(router, query, victim), "replay into another session")
+ if !ValidateSession(victim) {
+ t.Fatal("replayed LogoutResponse cleared another user's session")
+ }
+}
+
+// A response the IdP signed for one user's logout must not clear a different
+// user's live session, even on its first delivery inside the issue window: a
+// cross-site GET carries the victim's SameSite=Lax cookie and skips CSRF. The
+// misdelivered response spends the request, so it cannot be retried either.
+func TestHandleSAMLSLO_RefusesAnotherSessionsLogoutResponse(t *testing.T) {
+ router, idp := newSAMLSLOTestRouter(t)
+
+ requestID := startSAMLTestLogout(t, router, newSAMLTestSession(t, "attacker"))
+ query := idp.redirectQuery(t, requestID)
+
+ victim := newSAMLTestSession(t, "victim")
+ assertSAMLSLORefused(t, deliverSAMLTestLogoutResponse(router, query, victim), "another session's response")
+ if !ValidateSession(victim) {
+ t.Fatal("another user's LogoutResponse cleared the victim's session")
+ }
+ assertSAMLSLORefused(t, deliverSAMLTestLogoutResponse(router, query, ""), "retry after misdelivery")
+}
+
+// A correctly signed LogoutResponse that answers no LogoutRequest this SP
+// issued (an unsolicited one, or one answering a request the IdP was handed
+// by someone else) is refused without touching the session.
+func TestHandleSAMLSLO_RefusesUnsolicitedLogoutResponse(t *testing.T) {
+ router, idp := newSAMLSLOTestRouter(t)
+ victim := newSAMLTestSession(t, "victim")
+
+ for _, requestID := range []string{"", "id-never-issued-by-this-sp"} {
+ label := "InResponseTo=" + requestID
+ assertSAMLSLORefused(t, deliverSAMLTestLogoutResponse(router, idp.redirectQuery(t, requestID), victim), label)
+ if !ValidateSession(victim) {
+ t.Fatalf("%s: unsolicited LogoutResponse cleared the session", label)
+ }
+ }
+}
+
+// encoding/xml matches an un-namespaced attribute field to any attribute with
+// that local name, a namespace declaration such as xmlns:InResponseTo included,
+// and exclusive canonicalization can leave an unused declaration out of the
+// signed form. Appending one to a signed response must not rebind it to another
+// outstanding LogoutRequest.
+func TestHandleSAMLSLO_InResponseToIgnoresNamespaceDeclarations(t *testing.T) {
+ router, idp := newSAMLSLOTestRouter(t)
+ ownRequestID := startSAMLTestLogout(t, router, newSAMLTestSession(t, "alice"))
+ otherRequestID := startSAMLTestLogout(t, router, newSAMLTestSession(t, "bob"))
+
+ query, err := url.ParseQuery(idp.redirectQuery(t, ownRequestID))
+ if err != nil {
+ t.Fatalf("parse redirect query: %v", err)
+ }
+ signedXML := string(inflateSAMLTestPayload(t, query.Get("SAMLResponse")))
+ genuine := `InResponseTo="` + ownRequestID + `"`
+ if !strings.Contains(signedXML, genuine) {
+ t.Fatalf("signed response has no %s: %s", genuine, signedXML)
+ }
+ spoofed := strings.Replace(signedXML, genuine, genuine+` xmlns:InResponseTo="`+otherRequestID+`"`, 1)
+ form := url.Values{"SAMLResponse": {base64.StdEncoding.EncodeToString([]byte(spoofed))}}.Encode()
+
+ // The signature still verifies, so the response completes the request it
+ // was signed for and nothing else.
+ if rec := postSAMLTestLogoutResponse(router, form); rec.Code != http.StatusFound {
+ t.Fatalf("spoofed delivery: expected status %d, got %d body=%q", http.StatusFound, rec.Code, rec.Body.String())
+ }
+ if rec := deliverSAMLTestLogoutResponse(router, idp.redirectQuery(t, otherRequestID), ""); rec.Code != http.StatusFound {
+ t.Fatalf("a namespace declaration spent another LogoutRequest: genuine answer got %d body=%q", rec.Code, rec.Body.String())
+ }
+ assertSAMLSLORefused(t, deliverSAMLTestLogoutResponse(router, idp.redirectQuery(t, ownRequestID), ""), "signed request after spoofed delivery")
+}
+
+// A cross-site HTTP-POST delivery withholds the SameSite=Lax session cookie,
+// so /slo cannot see which session the browser holds. Completing a logout
+// must therefore write no cookie: a deletion cookie would log out the
+// browser's live session even though the request never presented it.
+func TestHandleSAMLSLO_CompletionWritesNoCookies(t *testing.T) {
+ router, idp := newSAMLSLOTestRouter(t)
+
+ requestID := startSAMLTestLogout(t, router, newSAMLTestSession(t, "attacker"))
+ victim := newSAMLTestSession(t, "victim")
+ rec := postSAMLTestLogoutResponse(router, idp.postForm(t, requestID))
+ if rec.Code != http.StatusFound {
+ t.Fatalf("cookieless POST binding: expected status %d, got %d body=%q", http.StatusFound, rec.Code, rec.Body.String())
+ }
+ if cookies := rec.Result().Cookies(); len(cookies) != 0 {
+ t.Fatalf("cookieless POST binding: SLO completion wrote cookies %v", cookies)
+ }
+ if !ValidateSession(victim) {
+ t.Fatal("SLO completion invalidated an unrelated session")
+ }
+
+ token := newSAMLTestSession(t, "alice")
+ requestID = startSAMLTestLogout(t, router, token)
+ rec = deliverSAMLTestLogoutResponse(router, idp.redirectQuery(t, requestID), token)
+ if rec.Code != http.StatusFound {
+ t.Fatalf("own session: expected status %d, got %d body=%q", http.StatusFound, rec.Code, rec.Body.String())
+ }
+ if cookies := rec.Result().Cookies(); len(cookies) != 0 {
+ t.Fatalf("own session: SLO completion wrote cookies %v", cookies)
+ }
+}
+
+// The SAML routes skip CSRF, and a cross-site POST withholds the
+// SameSite=Lax session cookie, so SP-initiated logout must not answer a
+// request that carries no session with the deletion cookies of a logout.
+func TestHandleSAMLLogout_RefusesRequestsWithoutSession(t *testing.T) {
+ router, _ := newSAMLSLOTestRouter(t)
+
+ for _, path := range []string{"/api/saml/okta/logout", "/api/saml/unknown/logout"} {
+ req := httptest.NewRequest(http.MethodPost, path, nil)
+ rec := httptest.NewRecorder()
+ router.handleSAMLLogout(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("%s: expected status %d, got %d body=%q", path, http.StatusUnauthorized, rec.Code, rec.Body.String())
+ }
+ if cookies := rec.Result().Cookies(); len(cookies) != 0 {
+ t.Fatalf("%s: cookieless logout wrote cookies %v", path, cookies)
+ }
+ }
+}
+
func TestHandleSAMLLogout_SLOUnavailable(t *testing.T) {
dataPath := t.TempDir()
InitSessionStore(dataPath)
diff --git a/internal/api/saml_service.go b/internal/api/saml_service.go
index 01d6fbd187..c020c82f63 100644
--- a/internal/api/saml_service.go
+++ b/internal/api/saml_service.go
@@ -1,9 +1,12 @@
package api
import (
+ "bytes"
+ "compress/flate"
"context"
"crypto/rsa"
"crypto/x509"
+ "encoding/base64"
"encoding/pem"
"encoding/xml"
"errors"
@@ -31,6 +34,93 @@ type SAMLService struct {
httpClient *http.Client
baseURL string
lastRefresh time.Time
+
+ // logoutRequests holds the SP-initiated LogoutRequests still waiting for
+ // the IdP's LogoutResponse.
+ logoutRequests samlLogoutRequestStore
+}
+
+const (
+ // samlLogoutRequestTTL bounds how long the IdP round trip of an
+ // SP-initiated logout may take, matching the OIDC login state lifetime.
+ samlLogoutRequestTTL = 10 * time.Minute
+ maxSAMLLogoutRequestEntries = 1024
+ // samlLogoutResponseMaxBytes matches crewjam/saml's inflate limit for the
+ // HTTP-Redirect binding.
+ samlLogoutResponseMaxBytes = 10 << 20
+)
+
+// errSAMLLogoutResponseUnbound marks a LogoutResponse that verified but does
+// not answer an outstanding LogoutRequest this SP issued for the presenting
+// session.
+var errSAMLLogoutResponseUnbound = errors.New("logout response does not answer an outstanding logout request for this session")
+
+// samlLogoutRequestStore records the LogoutRequests this SP issued, keyed by
+// request ID, with the session each one logged out. crewjam/saml checks a
+// LogoutResponse's signature, destination, issuer, status and age but never
+// its InResponseTo, so without this record any recent signed response from the
+// IdP, including one answering another user's logout, would be accepted.
+type samlLogoutRequestStore struct {
+ mu sync.Mutex
+ entries map[string]samlLogoutRequest
+}
+
+type samlLogoutRequest struct {
+ sessionKey string
+ expiresAt time.Time
+}
+
+func (s *samlLogoutRequestStore) put(requestID, sessionKey string, now time.Time) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.entries == nil {
+ s.entries = make(map[string]samlLogoutRequest)
+ }
+ for id, entry := range s.entries {
+ if !now.Before(entry.expiresAt) {
+ delete(s.entries, id)
+ }
+ }
+ for len(s.entries) >= maxSAMLLogoutRequestEntries {
+ oldestID := ""
+ var oldestExpiry time.Time
+ for id, entry := range s.entries {
+ if oldestID == "" || entry.expiresAt.Before(oldestExpiry) || (entry.expiresAt.Equal(oldestExpiry) && id < oldestID) {
+ oldestID = id
+ oldestExpiry = entry.expiresAt
+ }
+ }
+ delete(s.entries, oldestID)
+ }
+ s.entries[requestID] = samlLogoutRequest{
+ sessionKey: sessionKey,
+ expiresAt: now.Add(samlLogoutRequestTTL),
+ }
+}
+
+// consume spends the outstanding request a verified LogoutResponse answers.
+// sessionKey identifies the session the presenting browser carries, or is
+// empty when it carries none. The response may complete the logout only when
+// it answers an unexpired request and the browser carries either no session
+// or the session that request logged out. The request is spent on every
+// verified presentation, so a response is honored at most once.
+func (s *samlLogoutRequestStore) consume(requestID, sessionKey string, now time.Time) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ entry, ok := s.entries[requestID]
+ if requestID == "" || !ok {
+ return fmt.Errorf("%w: no outstanding request matches InResponseTo %q", errSAMLLogoutResponseUnbound, requestID)
+ }
+ delete(s.entries, requestID)
+ if !now.Before(entry.expiresAt) {
+ return fmt.Errorf("%w: request %q expired", errSAMLLogoutResponseUnbound, requestID)
+ }
+ if sessionKey != "" && sessionKey != entry.sessionKey {
+ return fmt.Errorf("%w: request %q logged out a different session", errSAMLLogoutResponseUnbound, requestID)
+ }
+ return nil
}
func normalizeSAMLBaseURL(baseURL string) (string, error) {
@@ -594,14 +684,19 @@ func (s *SAMLService) GetMetadata() ([]byte, error) {
return xml.MarshalIndent(metadata, "", " ")
}
-// MakeLogoutRequest creates a SAML LogoutRequest for SLO
-func (s *SAMLService) MakeLogoutRequest(nameID, sessionIdx string) (string, error) {
+// MakeLogoutRequest creates a SAML LogoutRequest for SLO and records its ID
+// as outstanding for sessionKey, the session being logged out, so that
+// ValidateLogoutResponse accepts only the IdP's answer to this request.
+func (s *SAMLService) MakeLogoutRequest(nameID, sessionIdx, sessionKey string) (string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if s.sp == nil {
return "", errors.New("service provider not initialized")
}
+ if sessionKey == "" {
+ return "", errors.New("logout request has no session to bind")
+ }
// Check if IdP supports SLO
if len(s.idpMetadata.IDPSSODescriptors) == 0 ||
@@ -619,21 +714,32 @@ func (s *SAMLService) MakeLogoutRequest(nameID, sessionIdx string) (string, erro
// Build redirect URL
redirectURL := req.Redirect("")
- return validateSAMLRedirectTarget(redirectURL.String(), s.idpMetadata.IDPSSODescriptors[0].SingleLogoutServices)
+ validatedURL, err := validateSAMLRedirectTarget(redirectURL.String(), s.idpMetadata.IDPSSODescriptors[0].SingleLogoutServices)
+ if err != nil {
+ return "", err
+ }
+ s.logoutRequests.put(req.ID, sessionKey, time.Now())
+ return validatedURL, nil
}
// ValidateLogoutResponse verifies an incoming IdP-signed SAML LogoutResponse,
// checking the XML-DSig signature against the IdP's published certificate as
-// well as the standard LogoutResponse temporal / target invariants. Returns
-// nil only when the response is genuinely from the configured IdP and bound
-// to the SAML state — anything that fails validation (no payload, bad
-// signature, unknown issuer, expired) returns an error and the caller MUST
-// NOT mutate any session state on the strength of the request.
+// well as the standard LogoutResponse temporal / target invariants, and then
+// binds it to the request it answers: its InResponseTo must name an
+// unexpired LogoutRequest from MakeLogoutRequest, which it spends, and
+// sessionKey (the presenting browser's session, or "" for none) must be empty
+// or the session that request logged out. Returns nil only when all of that
+// holds — anything else (no payload, bad signature, unknown issuer, expired,
+// unsolicited, replayed, or another session's logout) returns an error and
+// the caller MUST NOT mutate any session state on the strength of the
+// request. Binding failures wrap errSAMLLogoutResponseUnbound.
//
-// Without this validation the SLO callback endpoint was an unauthenticated
-// force-logout DoS: a cross-origin POST with no payload, or any forged
-// payload, cleared the user's session.
-func (s *SAMLService) ValidateLogoutResponse(req *http.Request) error {
+// Without signature validation the SLO callback endpoint was an
+// unauthenticated force-logout DoS: a cross-origin POST with no payload, or
+// any forged payload, cleared the user's session. Before the binding, any
+// user could replay the IdP's answer to their own logout through a cross-site
+// GET to clear someone else's session.
+func (s *SAMLService) ValidateLogoutResponse(req *http.Request, sessionKey string) error {
s.mu.RLock()
defer s.mu.RUnlock()
@@ -641,7 +747,81 @@ func (s *SAMLService) ValidateLogoutResponse(req *http.Request) error {
return errors.New("service provider not initialized")
}
- return s.sp.ValidateLogoutResponseRequest(req)
+ inResponseTo, err := s.verifiedLogoutResponseInResponseTo(req)
+ if err != nil {
+ return err
+ }
+ return s.logoutRequests.consume(inResponseTo, sessionKey, time.Now())
+}
+
+// verifiedLogoutResponseInResponseTo selects the SAMLResponse payload the way
+// crewjam/saml's ValidateLogoutResponseRequest does (the HTTP-Redirect query
+// parameter first, then the HTTP-POST form field), has crewjam verify exactly
+// that payload, and reads InResponseTo from the same bytes.
+func (s *SAMLService) verifiedLogoutResponseInResponseTo(req *http.Request) (string, error) {
+ var raw []byte
+ if data := req.URL.Query().Get("SAMLResponse"); data != "" {
+ if err := s.sp.ValidateLogoutResponseRedirect(data); err != nil {
+ return "", err
+ }
+ compressed, err := base64.StdEncoding.DecodeString(data)
+ if err != nil {
+ return "", fmt.Errorf("decode logout response: %w", err)
+ }
+ raw, err = io.ReadAll(io.LimitReader(flate.NewReader(bytes.NewReader(compressed)), samlLogoutResponseMaxBytes))
+ if err != nil {
+ return "", fmt.Errorf("inflate logout response: %w", err)
+ }
+ } else {
+ if err := req.ParseForm(); err != nil {
+ return "", fmt.Errorf("parse logout response form: %w", err)
+ }
+ data := req.PostForm.Get("SAMLResponse")
+ if err := s.sp.ValidateLogoutResponseForm(data); err != nil {
+ return "", err
+ }
+ var err error
+ raw, err = base64.StdEncoding.DecodeString(data)
+ if err != nil {
+ return "", fmt.Errorf("decode logout response: %w", err)
+ }
+ }
+ return logoutResponseInResponseTo(raw)
+}
+
+// logoutResponseInResponseTo returns the root LogoutResponse's InResponseTo
+// attribute as written without a prefix, the one the IdP's enveloped signature
+// covers, or "" when it has none. The attributes are read by hand, lexically,
+// because encoding/xml would also fill an un-namespaced attribute field from a
+// namespace declaration such as xmlns:InResponseTo="...", which exclusive
+// canonicalization can leave out of the signed form when nothing uses it. crewjam
+// has already checked that the root is a protocol LogoutResponse.
+func logoutResponseInResponseTo(raw []byte) (string, error) {
+ decoder := xml.NewDecoder(bytes.NewReader(raw))
+ for {
+ token, err := decoder.RawToken()
+ if err != nil {
+ return "", fmt.Errorf("parse logout response: %w", err)
+ }
+ start, ok := token.(xml.StartElement)
+ if !ok {
+ continue
+ }
+ if start.Name.Local != "LogoutResponse" {
+ return "", fmt.Errorf("parse logout response: unexpected root element %q", start.Name.Local)
+ }
+ inResponseTo, found := "", false
+ for _, attr := range start.Attr {
+ if attr.Name.Space != "" || attr.Name.Local != "InResponseTo" {
+ continue
+ }
+ if found {
+ return "", errors.New("parse logout response: duplicate InResponseTo")
+ }
+ inResponseTo, found = attr.Value, true
+ }
+ return inResponseTo, nil
+ }
}
func validateSAMLRedirectTarget(rawURL string, allowedEndpoints []saml.Endpoint) (string, error) {
diff --git a/internal/api/saml_service_test.go b/internal/api/saml_service_test.go
index 7de7a75704..83743e181a 100644
--- a/internal/api/saml_service_test.go
+++ b/internal/api/saml_service_test.go
@@ -8,6 +8,8 @@ import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
+ "errors"
+ "fmt"
"math/big"
"net/http"
"strings"
@@ -184,7 +186,7 @@ func TestSAMLServiceBasicFlows(t *testing.T) {
t.Fatalf("metadata error: %v", err)
}
- logoutURL, err := service.MakeLogoutRequest("user", "sess")
+ logoutURL, err := service.MakeLogoutRequest("user", "sess", sessionHash("session-token"))
if err != nil || !strings.Contains(logoutURL, "SAMLRequest") {
t.Fatalf("unexpected logout url: %v %s", err, logoutURL)
}
@@ -196,7 +198,7 @@ func TestSAMLServiceBasicFlows(t *testing.T) {
if _, err := service.GetMetadata(); err == nil {
t.Fatal("expected error when sp missing")
}
- if _, err := service.MakeLogoutRequest("user", "sess"); err == nil {
+ if _, err := service.MakeLogoutRequest("user", "sess", sessionHash("session-token")); err == nil {
t.Fatal("expected error when sp missing")
}
if err := service.RefreshMetadata(context.Background()); err == nil {
@@ -204,6 +206,36 @@ func TestSAMLServiceBasicFlows(t *testing.T) {
}
}
+// Outstanding SLO requests expire after samlLogoutRequestTTL, and the store
+// keeps at most maxSAMLLogoutRequestEntries by dropping the oldest.
+func TestSAMLLogoutRequestStoreExpiresAndEvictsOldest(t *testing.T) {
+ var store samlLogoutRequestStore
+ now := time.Now()
+ key := sessionHash("session-token")
+
+ store.put("id-expired", key, now)
+ if err := store.consume("id-expired", key, now.Add(samlLogoutRequestTTL)); !errors.Is(err, errSAMLLogoutResponseUnbound) {
+ t.Fatalf("expected an expired request to be refused, got %v", err)
+ }
+ store.put("id-live", key, now)
+ if err := store.consume("id-live", "", now.Add(samlLogoutRequestTTL-time.Second)); err != nil {
+ t.Fatalf("expected a live request to be accepted, got %v", err)
+ }
+
+ for i := 0; i <= maxSAMLLogoutRequestEntries; i++ {
+ store.put(fmt.Sprintf("id-%04d", i), key, now.Add(time.Duration(i)*time.Millisecond))
+ }
+ if len(store.entries) != maxSAMLLogoutRequestEntries {
+ t.Fatalf("expected %d outstanding requests, got %d", maxSAMLLogoutRequestEntries, len(store.entries))
+ }
+ if err := store.consume("id-0000", key, now); !errors.Is(err, errSAMLLogoutResponseUnbound) {
+ t.Fatalf("expected the oldest request to be evicted, got %v", err)
+ }
+ if err := store.consume(fmt.Sprintf("id-%04d", maxSAMLLogoutRequestEntries), key, now); err != nil {
+ t.Fatalf("expected the newest request to be kept, got %v", err)
+ }
+}
+
func TestValidateSAMLRedirectTarget(t *testing.T) {
allowed := []saml.Endpoint{
{Location: "https://idp.example.com/sso"},