authentik icon indicating copy to clipboard operation
authentik copied to clipboard

SAML upstream logout doesn't happen - security issue

Open headlesssetup opened this issue 10 months ago • 5 comments

Describe the bug

We use Authentik as an Identity Broker: [some SAAS] ---oidc---> [Authentik] ---saml--->[Corporate IDP].

Logging in works fine. We have a problem with users (not) logging out.

What happens on logout:

  • user logs out of SAAS
  • SAAS triggers OIDC logout to Authentik
  • Authentik invalidates the session in a simple flow: 10) "default-invalidation-logout" User Logout Stage terminates the session, then 20) Redirect Stage sends them to some page
  • ⚠️ IDP keeps their session because nobody told them to logout ⚠️

Resulting security Issue:

  • anybody using this browser will be able to log in to any app that uses IDP, because the IDP session is happily active until it times out hours later

What I expect to happen:

  • user logs out of SAAS
  • SAAS triggers OIDC logout to Authentik
  • Authentik terminates the session and sends a SAML LogoutRequest to IDP
  • IDP terminates the session and redirects to wherever it is configured to redirect on logout

What I tried:

  • In SAML Source page, I added a SLO endpoint. I expected Authentik to send a properly formed LogoutRequest there. It didn't happen. The SLO endpoint is never triggered during a User Logout Stage.
  • I dug through the code and noticed that if I visit a URL of https://my-authentik-server.com/source/saml/slug/slo/, I am redirected to the abovementioned SLO url from the "slug" SAML source. It is a simple redirect, no query string, no payload.

What I need:

  • I need Authentik to send a properly formed LogoutRequest to upstream IDP when a user logs out of Authentik. Otherwise it creates a security risk where anybody can re-authenticate via that same source.

How to reproduce

  1. Create a SAML Source for an upstream IDP
  2. Log into Authentik using the SAML Source
  3. Log out of Authentik
  4. You will be logged out of Authentik but NOT the SAML Source.
  5. Try to log into Authentik again via the same source. You will log in immediately, because nobody terminated the upstream session.

Expected behavior

As above.

Screenshots

No response

Additional context

No response

Deployment Method

Docker

Version

2025.12.1

Relevant log output


headlesssetup avatar Jan 30 '26 14:01 headlesssetup

Since my project cannot wait, I have built this functionality over the weekend. Here is the summary of the changes I made. This might give you an idea of how to implement thsi in the official version. Probably for the attention of @dewi-tik and @PeshekDotDev ? If you have any questions, I am happy to help.


SAML Source SLO (SP-Initiated) — Implementation Guideline

Authentik currently supports SLO for SAML Providers (authentik-as-IdP). This describes what's needed to add the missing SLO for SAML Sources (authentik-as-SP), and the non-obvious issues we encountered while implementing it.

1. Data Model Changes

  • New fields on SAMLSource: slo_binding (REDIRECT or POST — no POST_AUTO since the browser must visit the IdP) and sign_logout_request (boolean).
  • New model SAMLSourceSession: tracks each login-via-SAML-source with the IdP's SessionIndex, NameID, and NameIDFormat. Linked to both the User and the AuthenticatedSession via FKs. Supports expiry via ExpiringModel using the assertion's SessionNotOnOrAfter.

2. Capturing Session Data at Login Time

  • ResponseProcessor must extract SessionIndex, NameID, NameIDFormat, and SessionNotOnOrAfter from the SAML assertion's <AuthnStatement> during response validation.
  • Data needs to be stored in two places: (a) request.session and (b) on the processor instance. This dual-path is necessary because django.contrib.auth.login() may flush/cycle the session, losing session-stored data.
  • A user_logged_in signal handler picks up the session data and creates the SAMLSourceSession record. The AuthenticatedSession may not exist yet at signal time (ordering of signal handlers is not guaranteed), so get_or_create logic is needed.

3. The LINK Action Path

  • When a user is already authenticated and authenticates again via a SAML source, the SourceFlowManager takes the LINK action, not AUTH. user_logged_in never fires in this case.
  • SAMLSourceFlowManager.handle_existing_link() must create the SAMLSourceSession directly, bypassing the signal path entirely.

4. Reusing LogoutRequestProcessor

  • The existing LogoutRequestProcessor is tightly coupled to SAMLProvider. To reuse it for sources, introduce a SAMLLogoutConfig Protocol class so the processor works with any object providing signing_kp, sign_logout_request, signature_algorithm, and digest_algorithm.
  • Custom issuer: SAMLSource doesn't have an issuer property the same way providers do. For a source acting as SP, the issuer is its SP metadata URL. Add an issuer parameter to the constructor to support this.

5. Hooking into the Logout Flow

  • Reuse the existing flow_pre_user_logout signal and the existing NativeLogoutStageView (the in-memory stage + frontend component that redirects/POSTs the user to the external IdP).
  • Critical: merge, don't overwrite. Both source and provider SLO handlers write to PLAN_CONTEXT_SAML_LOGOUT_NATIVE_SESSIONS. The current code overwrites the context key. Both handlers must append to the existing list. Similarly, both must check if NativeLogoutStageView is already in the plan before injecting a duplicate.

6. Stage Insertion Index

  • The current code inserts NativeLogoutStageView at a hardcoded index=2. This breaks in two scenarios:
    • OIDC-triggered logout: EndSessionView appends a SessionEndStage to the plan. If the native logout stage lands after SessionEndStage, the user gets redirected away before SLO executes.
    • Custom invalidation flows with stages after UserLogoutStage (e.g., a redirect stage to a corporate homepage).
  • Fix: Insert NativeLogoutStageView at index=1 (right after the current UserLogoutStage at index 0), so SLO always runs before any downstream stages.

7. SLO Callback View (SLOView)

  • CSRF exemption required: The IdP POSTs a LogoutResponse cross-origin, identical to how the ACS endpoint works. Must use @csrf_exempt.
  • Remove LoginRequiredMixin: By the time the IdP redirects back, UserLogoutStage has already called logout(). The user is anonymous. Requiring login would 302 to the login page.
  • Redirect back to the flow, not to the IdP: The current SLOView does redirect(source.slo_url) which would loop. Must redirect back to the flow executor so remaining stages can execute.

8. RelayState and the 80-Byte Limit

  • SAML 2.0 Bindings spec (sections 3.4.3, 3.5.3) limits RelayState to 80 bytes for both Redirect and POST bindings. A full absolute URL does not fit.
  • Solution: Store the absolute flow return URL in the flow plan context (PLAN_CONTEXT_SAML_RELAY_STATE). Send only the relative path (e.g., /if/flow/default-invalidation-flow/) as RelayState to the IdP. The SLOView resolves the return URL in priority order: (1) plan context from session, (2) RelayState from IdP response, (3) fallback to user interface.
  • Note: stage_ok() persists the plan to the new (post-logout) session, so the plan context survives the logout() call.

9. SP Metadata

  • When slo_url is configured on the source, the SP metadata (/source/saml/<slug>/metadata/) should include a <SingleLogoutService> element advertising the SLO callback URL and binding. This allows IdPs consuming the metadata to auto-discover the SLO endpoint.

10. Frontend

  • Add SLO Binding dropdown and Sign Logout Requests toggle to the SAML Source admin form.

11. Binding Value Casing (Non-Obvious)

  • The source model stores binding values as uppercase ("REDIRECT", "POST"). However, the frontend's TypeScript SAMLBindingsEnum (used by NativeLogoutStageView) expects lowercase ("redirect", "post"). When building the logout_data dict for the plan context, translate to the lowercase enum values.

Files Touched (for reference)

File Change Type
sources/saml/models.py New model + fields
sources/saml/migrations/0022_* Migration
sources/saml/signals.py Two new signal handlers
sources/saml/processors/response.py Session data extraction + FlowManager override
sources/saml/processors/metadata.py SingleLogoutService in SP metadata
sources/saml/views.py SLOView rewrite
sources/saml/api/source.py Serializer + viewset fields
providers/saml/processors/logout_request.py Generalize to work with sources (Protocol class)
providers/saml/signals.py Fix merge bug + dedup stage injection
stages/user_logout/stage.py No functional change (logging only)
web/src/admin/sources/saml/SAMLSourceForm.ts UI fields

headlesssetup avatar Feb 15 '26 18:02 headlesssetup

Hey @headlesssetup, thank you for the pointers. I'll check some of the things you pointed out against my implementation. I wrote one last week, but I need some time to sync with other team members on minor implementation details. It will definitely be out by next release, but will probably take a week or two or review before it gets merged

PeshekDotDev avatar Feb 15 '26 19:02 PeshekDotDev

That was quick, already next release, wow. Thank you so much @PeshekDotDev !

Out of curiosity, I asked Claude 4.6 to compare two implementations and highlight anything that might be useful for your PR. Here they are below. My semi-professional opinion is that no. 10 is important as the upgrade will break the existing SAML sources.

Suggestions for PR #20323 / SAML Source SLO

1. Add session expiry support to SAMLSourceSession

The PR's SAMLSourceSession is a plain models.Model with no expiry mechanism. SAML IdPs can include SessionNotOnOrAfter in the AuthnStatement, which defines when the session should be considered expired. Without honoring this, stale SAMLSourceSession records accumulate and could trigger logout requests for sessions the IdP has already expired. Consider inheriting from ExpiringModel (or at least adding a session_not_on_or_after field) and parsing the attribute from the SAML response during session creation.

2. Handle the LINK action path for session creation

The SAMLPostSourceStage approach creates SAMLSourceSession after a successful authentication flow. However, when a user is already authenticated and authenticates again via a SAML source, the SourceFlowManager takes the LINK action instead of AUTH. In this case, the full authentication flow may not run, and the post-source stage might not fire. This means SLO won't work for linked sessions. Consider explicitly handling this in SAMLSourceFlowManager or ensuring the stage runs for all action types.

3. LogoutResponseParser.verify_status() returns True on missing status elements

In authentik/common/saml/parsers/logout_response.py, verify_status() returns True (success) when <Status> or <StatusCode> elements are missing. Per the SAML spec (section 3.2.2), <Status> is a required element in <LogoutResponse>. Treating its absence as success is overly permissive. Consider returning False or raising an exception when <Status> is absent, as it likely indicates a malformed response.

4. _handle_logout_request doesn't verify signatures on incoming LogoutRequests

In SLOView._handle_logout_request(), the incoming LogoutRequest from the IdP is parsed but never signature-verified, even when the source has a verification_kp configured. A malicious actor could forge a LogoutRequest to log users out. The LogoutRequestParser should support optional signature verification using the IdP's certificate (similar to how ResponseProcessor verifies assertion/response signatures).

5. _handle_logout_request filters sessions by request.user, which may be anonymous

In SLOView._handle_logout_request():

SAMLSourceSession.objects.filter(
    source=source,
    user=request.user,
).delete()

If the IdP sends a LogoutRequest via a back-channel or after the user's session cookie has expired, request.user would be AnonymousUser, and this filter would match nothing. The LogoutRequest contains a NameID and SessionIndex -- consider looking up the SAMLSourceSession by those fields instead, which is how the SAML spec intends session resolution to work.

6. POST-binding LogoutResponse falls back to redirect when there's no flow

In SLOView._send_logout_response():

def _send_logout_response(self, response_builder, relay_state=None):
    return redirect(response_builder.get_redirect_url(relay_state))

Even when the source's slo_binding is POST, this fallback always uses a redirect. If the IdP only supports POST-binding LogoutResponse, this would fail. Consider rendering a minimal auto-submit form directly (without needing a flow) as the fallback.

7. Flow plan manipulation in _handle_logout_response is fragile

In SLOView._handle_logout_response():

if relay_state and SESSION_KEY_PLAN in request.session:
    plan: FlowPlan = request.session[SESSION_KEY_PLAN]
    if plan.bindings:
        plan.pop()
        request.session[SESSION_KEY_PLAN] = plan
    return redirect(relay_state)

This blindly pops the current stage from the plan assuming it's the RedirectStage that sent the user to the IdP. If anything else modifies the plan between the redirect and the callback, the wrong stage gets popped. Consider verifying the stage type before popping, or using a stage-specific marker/token to ensure the correct stage is advanced.

8. LogoutRequestParser should be made truly shared

The PR moves LogoutRequestParser to authentik/common/saml/parsers/ but it still imports decode_base64_and_inflate from authentik.providers.saml.utils.encoding. If the goal is a shared common module, the encoding utilities should also be moved to authentik/common/saml/ to avoid the source module depending on the provider module. The same applies to LogoutResponseParser and LogoutResponseBuilder, which both import from authentik.providers.saml.utils.

9. Metadata should include ResponseLocation for flexibility

The PR advertises both REDIRECT and POST bindings for SingleLogoutService, both pointing to the same Location. The SAML metadata spec allows an optional ResponseLocation attribute (for receiving LogoutResponse at a different URL than LogoutRequest). While not strictly required, documenting the assumption that both requests and responses arrive at the same endpoint would help administrators troubleshooting interop issues.

10. Consider adding a sign_authn_request migration for existing sources

The PR adds sign_authn_request with default=False, which changes the existing behavior. Previously, AuthnRequests were signed whenever a signing_kp was set. After the migration, existing sources with a signing keypair will stop signing AuthnRequests unless an admin manually enables the new flag. This is a silent behavioral regression that could break SSO for existing deployments. Consider defaulting sign_authn_request to True in the migration (or setting it based on whether signing_kp is non-null) to preserve backward compatibility.

11. SP-initiated SLO via _initiate_logout doesn't associate with a specific source

SLOView._initiate_logout() delegates to the brand's invalidation flow, which then triggers the flow_pre_user_logout signal. But the signal handler iterates over all SAMLSourceSession records for the user. If the user navigated to /source/saml/<specific-source>/slo/, the intent was likely to log out of that specific source only. Consider passing the source context through the flow plan so the signal handler can filter to just the intended source.

12. Clean up SAMLSourceSession records on session expiry / cleanup

There's no periodic task or signal to clean up SAMLSourceSession records when the underlying AuthenticatedSession expires or is deleted. While the CASCADE on the foreign key handles DB-level cleanup when the AuthenticatedSession row is deleted, Django session expiry doesn't always trigger row deletion immediately. Consider adding a periodic cleanup task or hooking into the session cleanup mechanism.


headlesssetup avatar Feb 19 '26 11:02 headlesssetup

@dewi-tik you mentioned this would come in one of this years updates, and I do see a lot of SAML work (some of my customizations are now official, e.g. ForceAuthn). However, this is still not done - any timeframe? Thank you very much!

headlesssetup avatar Jun 26 '26 15:06 headlesssetup

No strict timeframe at the moment but the linked PR (https://github.com/goauthentik/authentik/pull/20323) will address this.

dewi-tik avatar Jun 27 '26 15:06 dewi-tik