authentik.sources.saml.processors.response

authentik saml source processor

  1"""authentik saml source processor"""
  2
  3from base64 import b64decode
  4from datetime import UTC, datetime
  5from hashlib import sha256
  6from time import mktime
  7from typing import TYPE_CHECKING
  8from uuid import uuid4
  9
 10import xmlsec
 11from django.core.cache import cache
 12from django.core.exceptions import SuspiciousOperation
 13from django.http import HttpRequest
 14from django.urls import reverse
 15from django.utils.timezone import now
 16from lxml import etree  # nosec
 17from lxml.etree import _Element  # nosec
 18from structlog.stdlib import get_logger
 19
 20from authentik.common.saml.constants import (
 21    NS_MAP,
 22    NS_SAML_ASSERTION,
 23    NS_SAML_PROTOCOL,
 24    SAML_NAME_ID_FORMAT_EMAIL,
 25    SAML_NAME_ID_FORMAT_PERSISTENT,
 26    SAML_NAME_ID_FORMAT_TRANSIENT,
 27    SAML_NAME_ID_FORMAT_UNSPECIFIED,
 28    SAML_NAME_ID_FORMAT_WINDOWS,
 29    SAML_NAME_ID_FORMAT_X509,
 30    SAML_STATUS_SUCCESS,
 31)
 32from authentik.common.saml.utils import get_element_text
 33from authentik.core.models import (
 34    USER_ATTRIBUTE_DELETE_ON_LOGOUT,
 35    USER_ATTRIBUTE_EXPIRES,
 36    USER_ATTRIBUTE_GENERATED,
 37    USER_ATTRIBUTE_SOURCES,
 38    USERNAME_MAX_LENGTH,
 39    User,
 40)
 41from authentik.core.sources.flow_manager import SourceFlowManager
 42from authentik.lib.utils.time import timedelta_from_string
 43from authentik.lib.xml import lxml_from_string
 44from authentik.sources.saml.exceptions import (
 45    InvalidEncryption,
 46    InvalidSignature,
 47    InvalidTime,
 48    MismatchedAudience,
 49    MismatchedBinding,
 50    MismatchedRequestID,
 51    MissingNameID,
 52    MissingSAMLResponse,
 53    SAMLException,
 54    UnsuccessfulStatus,
 55    UnsupportedNameIDFormat,
 56)
 57from authentik.sources.saml.models import (
 58    GroupSAMLSourceConnection,
 59    SAMLSource,
 60    UserSAMLSourceConnection,
 61)
 62from authentik.sources.saml.processors.request import SESSION_KEY_REQUEST_ID
 63
 64LOGGER = get_logger()
 65if TYPE_CHECKING:
 66    from xml.etree.ElementTree import Element  # nosec
 67
 68# One entry for each Source and assertion
 69CACHE_SEEN_ASSERTION_ID = "goauthentik.io/sources/saml/seen_assertion/%s/%s"
 70# 24 hours, longer than the validity of most assertions
 71CACHE_SEEN_ASSERTION_TIMEOUT = 60 * 60 * 24
 72SAML_SUBJECT_CONFIRMATION_METHOD_BEARER = "urn:oasis:names:tc:SAML:2.0:cm:bearer"
 73
 74
 75class ResponseProcessor:
 76    """SAML Response Processor"""
 77
 78    _source: SAMLSource
 79
 80    _root: _Element
 81    _root_xml: bytes
 82
 83    _http_request: HttpRequest
 84
 85    _assertion: _Element | None = None
 86
 87    def __init__(self, source: SAMLSource, request: HttpRequest):
 88        self._source = source
 89        self._http_request = request
 90
 91    def parse(self):
 92        """Check if `request` contains SAML Response data, parse and validate it."""
 93        # First off, check if we have any SAML Data at all.
 94        raw_response = self._http_request.POST.get("SAMLResponse", None)
 95        if not raw_response:
 96            raise MissingSAMLResponse("Request does not contain 'SAMLResponse'")
 97        # Check if response is compressed, b64 decode it
 98        self._root_xml = b64decode(raw_response.encode())
 99        self._root = lxml_from_string(self._root_xml)
100
101        # Verify response signature BEFORE decryption (signature covers encrypted content)
102        if self._source.verification_kp and self._source.signed_response:
103            self._verify_response_signature()
104
105        if self._source.encryption_kp:
106            self._decrypt_response()
107
108        # Verify assertion signature AFTER decryption (signature is inside encrypted content)
109        if self._source.verification_kp and self._source.signed_assertion:
110            self._verify_assertion_signature()
111
112        self._verify_request_id()
113        self._verify_status()
114        self._verify_conditions()
115        self._verify_destination()
116        self._verify_subject_confirmation()
117        self._verify_not_seen_before()
118
119    def _decrypt_response(self):
120        """Decrypt SAMLResponse EncryptedAssertion Element"""
121        manager = xmlsec.KeysManager()
122        key = xmlsec.Key.from_memory(
123            self._source.encryption_kp.key_data,
124            xmlsec.constants.KeyDataFormatPem,
125        )
126
127        manager.add_key(key)
128        encryption_context = xmlsec.EncryptionContext(manager)
129
130        encrypted_assertion = self._root.find(f".//{{{NS_SAML_ASSERTION}}}EncryptedAssertion")
131        if encrypted_assertion is None:
132            raise InvalidEncryption("Response does not contain an EncryptedAssertion element.")
133        # Register Id attributes so a KeyInfo RetrievalMethod referencing a sibling
134        # EncryptedKey by #Id can be resolved by xmlsec
135        xmlsec.tree.add_ids(encrypted_assertion, ["Id"])
136        encrypted_data = xmlsec.tree.find_child(
137            encrypted_assertion, "EncryptedData", xmlsec.constants.EncNs
138        )
139        try:
140            decrypted_assertion = encryption_context.decrypt(encrypted_data)
141        except xmlsec.Error as exc:
142            raise InvalidEncryption(f"Failed to decrypt assertion: {exc}") from exc
143
144        index_of = self._root.index(encrypted_assertion)
145        self._root.remove(encrypted_assertion)
146        self._root.insert(
147            index_of,
148            decrypted_assertion,
149        )
150        self._assertion = decrypted_assertion
151
152    def _verify_conditions(self):
153        conditions = self.get_assertion().find(f"{{{NS_SAML_ASSERTION}}}Conditions")
154        if conditions is None:
155            return
156        _now = now()
157        before = conditions.attrib.get("NotBefore")
158        if before:
159            if datetime.fromisoformat(before).replace(tzinfo=UTC) > _now:
160                raise InvalidTime()
161        on_or_after = conditions.attrib.get("NotOnOrAfter")
162        if on_or_after:
163            if datetime.fromisoformat(on_or_after).replace(tzinfo=UTC) < _now:
164                raise InvalidTime()
165        self._verify_audience(conditions)
166
167    def _verify_audience(self, conditions: _Element):
168        """Verify that our entity ID is listed as an audience of the assertion. Each
169        AudienceRestriction is evaluated independently and must contain a matching Audience."""
170        entity_id = self._source.get_issuer(self._http_request)
171        for restriction in conditions.findall(f"{{{NS_SAML_ASSERTION}}}AudienceRestriction"):
172            audiences = [
173                get_element_text(audience).strip()
174                for audience in restriction.findall(f"{{{NS_SAML_ASSERTION}}}Audience")
175            ]
176            if entity_id not in audiences:
177                LOGGER.warning(
178                    "Assertion audience does not match source entity ID",
179                    entity_id=entity_id,
180                    audiences=audiences,
181                )
182                raise MismatchedAudience()
183
184    def _verify_signature(self, signature_node: _Element, target: _Element):
185        """Verify a single signature node against the given target element."""
186        target_id = target.attrib.get("ID")
187        if not target_id:
188            raise InvalidSignature("Signed element is missing an ID attribute.")
189        refs = signature_node.xpath("./ds:SignedInfo/ds:Reference", namespaces=NS_MAP)
190        if len(refs) != 1:
191            raise InvalidSignature("Signature must contain exactly one Reference.")
192        ref_uri = refs[0].get("URI", "")
193        if ref_uri not in ("", f"#{target_id}"):
194            raise InvalidSignature(
195                "Signature Reference URI does not match the signed element's ID."
196            )
197
198        xmlsec.tree.add_ids(target, ["ID"])
199
200        ctx = xmlsec.SignatureContext()
201        key = xmlsec.Key.from_memory(
202            self._source.verification_kp.certificate_data,
203            xmlsec.constants.KeyDataFormatCertPem,
204        )
205        ctx.key = key
206
207        ctx.set_enabled_key_data([xmlsec.constants.KeyDataX509])
208        try:
209            ctx.verify(signature_node)
210        except xmlsec.Error as exc:
211            raise InvalidSignature(
212                "The signature of the SAML object is either missing or invalid."
213            ) from exc
214        LOGGER.debug("Successfully verified signature")
215
216    def _verify_response_signature(self):
217        """Verify SAML Response's Signature (before decryption)"""
218        signature_nodes = self._root.xpath("/samlp:Response/ds:Signature", namespaces=NS_MAP)
219
220        if len(signature_nodes) != 1:
221            raise InvalidSignature("Expected exactly one Signature in the Response element.")
222
223        self._verify_signature(signature_nodes[0], self._root)
224
225    def _verify_assertion_signature(self):
226        """Verify SAML Assertion's Signature (after decryption)"""
227        signature_nodes = self._root.xpath(
228            "/samlp:Response/saml:Assertion/ds:Signature", namespaces=NS_MAP
229        )
230        if len(signature_nodes) != 1:
231            raise InvalidSignature("Expected exactly one signed Assertion in the Response.")
232        signature_node = signature_nodes[0]
233        assertion = signature_node.getparent()
234
235        self._verify_signature(signature_node, assertion)
236        self._assertion = assertion
237
238    def _verify_request_id(self):
239        if self._source.allow_idp_initiated:
240            return
241        # The Response and the assertion can both name the request that they answer. Read
242        # both, as only the value inside the assertion is covered by the signature. The
243        # value inside the assertion is checked in _verify_subject_confirmation.
244        in_response_to = self._root.attrib.get("InResponseTo")
245        confirmed_ids = [
246            data.attrib.get("InResponseTo") for data in self._get_bearer_confirmation_data()
247        ]
248        if SESSION_KEY_REQUEST_ID not in self._http_request.session or not any(
249            [in_response_to, *confirmed_ids]
250        ):
251            raise MismatchedRequestID(
252                "Missing InResponseTo and IdP-initiated Logins are not allowed"
253            )
254        if in_response_to and in_response_to != self._http_request.session[SESSION_KEY_REQUEST_ID]:
255            raise MismatchedRequestID("Mismatched request ID")
256
257    def _get_bearer_confirmation_data(self) -> list[_Element]:
258        """Get the SubjectConfirmationData of every bearer SubjectConfirmation of the
259        assertion."""
260        assertion = self.get_assertion()
261        if assertion is None:
262            return []
263        confirmations = []
264        for confirmation in assertion.findall(
265            f"{{{NS_SAML_ASSERTION}}}Subject/{{{NS_SAML_ASSERTION}}}SubjectConfirmation"
266        ):
267            method = confirmation.attrib.get("Method")
268            if method is not None and method != SAML_SUBJECT_CONFIRMATION_METHOD_BEARER:
269                continue
270            data = confirmation.find(f"{{{NS_SAML_ASSERTION}}}SubjectConfirmationData")
271            if data is None:
272                continue
273            confirmations.append(data)
274        return confirmations
275
276    def _verify_destination(self):
277        """Verify that the Response names the ACS URL of this Source"""
278        destination = self._root.attrib.get("Destination")
279        if not destination:
280            return
281        acs_url = self._http_request.build_absolute_uri(
282            reverse("authentik_sources_saml:acs", kwargs={"source_slug": self._source.slug})
283        )
284        if destination.lower() != acs_url.lower():
285            LOGGER.warning(
286                "Destination of Response does not match ACS URL",
287                destination=destination,
288                acs_url=acs_url,
289            )
290            raise MismatchedBinding("The Destination does not match the ACS URL of this Source.")
291
292    def _verify_subject_confirmation(self):
293        """One confirmation of the subject must name this Source. An assertion can carry
294        more than one, and satisfying one of them is enough."""
295        first_error = None
296        for data in self._get_bearer_confirmation_data():
297            try:
298                self._check_subject_confirmation(data)
299                return
300            except SAMLException as exc:
301                if first_error is None:
302                    first_error = exc
303        if first_error is not None:
304            raise first_error
305        raise MismatchedBinding(
306            "The assertion carries no confirmation of the subject for this Source."
307        )
308
309    def _check_subject_confirmation(self, data: _Element):
310        """Check one SubjectConfirmationData"""
311        recipient = data.attrib.get("Recipient")
312        if recipient:
313            acs_url = self._http_request.build_absolute_uri(
314                reverse("authentik_sources_saml:acs", kwargs={"source_slug": self._source.slug})
315            )
316            if recipient.lower() != acs_url.lower():
317                LOGGER.warning(
318                    "Recipient of assertion does not match ACS URL",
319                    recipient=recipient,
320                    acs_url=acs_url,
321                )
322                raise MismatchedBinding("The Recipient does not match the ACS URL of this Source.")
323        on_or_after = data.attrib.get("NotOnOrAfter")
324        if on_or_after:
325            if datetime.fromisoformat(on_or_after).replace(tzinfo=UTC) < now():
326                raise InvalidTime()
327        in_response_to = data.attrib.get("InResponseTo")
328        if in_response_to and not self._source.allow_idp_initiated:
329            if in_response_to != self._http_request.session.get(SESSION_KEY_REQUEST_ID):
330                raise MismatchedRequestID("Mismatched request ID")
331
332    def _verify_not_seen_before(self):
333        """Verify that the assertion was not used before"""
334        assertion = self.get_assertion()
335        if assertion is None:
336            return
337        assertion_id = assertion.attrib.get("ID")
338        if not assertion_id:
339            LOGGER.warning("Assertion has no ID, cannot check for re-use")
340            return
341        key = CACHE_SEEN_ASSERTION_ID % (
342            self._source.pk,
343            sha256(assertion_id.encode()).hexdigest(),
344        )
345        marker = uuid4().hex
346        cache.add(key, marker, timeout=CACHE_SEEN_ASSERTION_TIMEOUT)
347        if cache.get(key) != marker:
348            raise SuspiciousOperation("Replay attack detected")
349
350    def _verify_status(self):
351        """Check for SAML Status elements"""
352        status = self._root.find(f"{{{NS_SAML_PROTOCOL}}}Status")
353        if status is None:
354            return
355        status_code = status.find(f"{{{NS_SAML_PROTOCOL}}}StatusCode")
356        status_value = status_code.attrib.get("Value") if status_code is not None else None
357        # The second-level StatusCode carries the actual reason (e.g. RequestDenied, AuthnFailed);
358        # the top-level code only says which party is at fault
359        nested_status_code = (
360            status_code.find(f"{{{NS_SAML_PROTOCOL}}}StatusCode")
361            if status_code is not None
362            else None
363        )
364        nested_value = (
365            nested_status_code.attrib.get("Value") if nested_status_code is not None else None
366        )
367        message = status.find(f"{{{NS_SAML_PROTOCOL}}}StatusMessage")
368        message_text = message.text if message is not None else None
369        detail = status.find(f"{{{NS_SAML_PROTOCOL}}}StatusDetail")
370        detail_text = etree.tostring(detail, encoding="unicode") if detail is not None else None
371        if status_value != SAML_STATUS_SUCCESS:
372            LOGGER.warning(
373                "SAML Response has an unsuccessful status",
374                status_code=status_value,
375                nested_status_code=nested_value,
376                message=message_text,
377                detail=detail_text,
378            )
379            parts = [nested_value or status_value or "SAML Status", message_text, detail_text]
380            raise UnsuccessfulStatus(": ".join(part for part in parts if part))
381        if message_text or detail_text:
382            LOGGER.debug("SAML Status message", message=message_text, detail=detail_text)
383
384    def _handle_name_id_transient(self) -> SourceFlowManager:
385        """Handle a NameID with the Format of Transient. This is a bit more complex than other
386        formats, as we need to create a temporary User that is used in the session. This
387        user has an attribute that refers to our Source for cleanup. The user is also deleted
388        on logout and periodically."""
389        # Create a temporary User
390        name_id_el, name_id = self._get_name_id()
391        # trim username to ensure it is max 150 chars
392        username = f"ak-{name_id[: USERNAME_MAX_LENGTH - 14]}-transient"
393        expiry = mktime(
394            (now() + timedelta_from_string(self._source.temporary_user_delete_after)).timetuple()
395        )
396        user: User = User.objects.create(
397            username=username,
398            attributes={
399                USER_ATTRIBUTE_GENERATED: True,
400                USER_ATTRIBUTE_SOURCES: [
401                    self._source.name,
402                ],
403                USER_ATTRIBUTE_DELETE_ON_LOGOUT: True,
404                USER_ATTRIBUTE_EXPIRES: expiry,
405            },
406            path=self._source.get_user_path(),
407        )
408        LOGGER.debug("Created temporary user for NameID Transient", username=name_id)
409        UserSAMLSourceConnection.objects.create(source=self._source, user=user, identifier=name_id)
410        return SAMLSourceFlowManager(
411            source=self._source,
412            request=self._http_request,
413            identifier=str(name_id),
414            user_info={
415                "root": self._root,
416                "assertion": self.get_assertion(),
417                "name_id": name_id_el,
418            },
419            policy_context={},
420        )
421
422    def get_assertion(self) -> Element | None:
423        """Get assertion element, if we have a signed assertion"""
424        if self._assertion is not None:
425            return self._assertion
426        return self._root.find(f"{{{NS_SAML_ASSERTION}}}Assertion")
427
428    def _get_name_id(self) -> tuple[Element, str]:
429        """Get NameID Element"""
430        assertion = self.get_assertion()
431        if assertion is None:
432            raise MissingNameID("Assertion element not found")
433        subject = assertion.find(f"{{{NS_SAML_ASSERTION}}}Subject")
434        if subject is None:
435            raise MissingNameID("Subject element not found")
436        name_id = subject.find(f"{{{NS_SAML_ASSERTION}}}NameID")
437        if name_id is None:
438            raise MissingNameID("NameID element not found")
439        return name_id, get_element_text(name_id)
440
441    def _get_name_id_filter(self) -> dict[str, str]:
442        """Returns the subject's NameID as a Filter for the `User`"""
443        name_id_el, name_id = self._get_name_id()
444        if not name_id:
445            raise UnsupportedNameIDFormat("Subject's NameID is empty.")
446        _format = name_id_el.attrib.get("Format", SAML_NAME_ID_FORMAT_UNSPECIFIED)
447        if _format == SAML_NAME_ID_FORMAT_EMAIL:
448            return {"email": name_id}
449        if _format == SAML_NAME_ID_FORMAT_PERSISTENT:
450            return {"username": name_id}
451        if _format == SAML_NAME_ID_FORMAT_X509:
452            # This attribute is statically set by the LDAP source
453            return {"attributes__distinguishedName": name_id}
454        if _format == SAML_NAME_ID_FORMAT_WINDOWS:
455            if "\\" in name_id:
456                name_id = name_id.split("\\")[1]
457            return {"username": name_id}
458        raise UnsupportedNameIDFormat(
459            f"Assertion contains NameID with unsupported format {_format}."
460        )
461
462    def prepare_flow_manager(self) -> SourceFlowManager:
463        """Prepare flow plan depending on whether or not the user exists"""
464        name_id_el, name_id = self._get_name_id()
465        # The Format attribute is optional, and defaults to unspecified
466        name_id_format = name_id_el.attrib.get("Format", SAML_NAME_ID_FORMAT_UNSPECIFIED)
467        # Sanity check, show a warning if NameIDPolicy doesn't match what we go
468        if self._source.name_id_policy != name_id_format:
469            LOGGER.warning(
470                "NameID from IdP doesn't match our policy",
471                expected=self._source.name_id_policy,
472                got=name_id_format,
473            )
474        # transient NameIDs are handled separately as they don't have to go through flows.
475        if name_id_format == SAML_NAME_ID_FORMAT_TRANSIENT:
476            return self._handle_name_id_transient()
477
478        return SAMLSourceFlowManager(
479            source=self._source,
480            request=self._http_request,
481            identifier=str(name_id),
482            user_info={
483                "root": self._root,
484                "assertion": self.get_assertion(),
485                "name_id": name_id_el,
486            },
487            policy_context={
488                "saml_response": etree.tostring(self._root),
489            },
490        )
491
492
493class SAMLSourceFlowManager(SourceFlowManager):
494    """Source flow manager for SAML Sources"""
495
496    user_connection_type = UserSAMLSourceConnection
497    group_connection_type = GroupSAMLSourceConnection
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
CACHE_SEEN_ASSERTION_ID = 'goauthentik.io/sources/saml/seen_assertion/%s/%s'
CACHE_SEEN_ASSERTION_TIMEOUT = 86400
SAML_SUBJECT_CONFIRMATION_METHOD_BEARER = 'urn:oasis:names:tc:SAML:2.0:cm:bearer'
class ResponseProcessor:
 76class ResponseProcessor:
 77    """SAML Response Processor"""
 78
 79    _source: SAMLSource
 80
 81    _root: _Element
 82    _root_xml: bytes
 83
 84    _http_request: HttpRequest
 85
 86    _assertion: _Element | None = None
 87
 88    def __init__(self, source: SAMLSource, request: HttpRequest):
 89        self._source = source
 90        self._http_request = request
 91
 92    def parse(self):
 93        """Check if `request` contains SAML Response data, parse and validate it."""
 94        # First off, check if we have any SAML Data at all.
 95        raw_response = self._http_request.POST.get("SAMLResponse", None)
 96        if not raw_response:
 97            raise MissingSAMLResponse("Request does not contain 'SAMLResponse'")
 98        # Check if response is compressed, b64 decode it
 99        self._root_xml = b64decode(raw_response.encode())
100        self._root = lxml_from_string(self._root_xml)
101
102        # Verify response signature BEFORE decryption (signature covers encrypted content)
103        if self._source.verification_kp and self._source.signed_response:
104            self._verify_response_signature()
105
106        if self._source.encryption_kp:
107            self._decrypt_response()
108
109        # Verify assertion signature AFTER decryption (signature is inside encrypted content)
110        if self._source.verification_kp and self._source.signed_assertion:
111            self._verify_assertion_signature()
112
113        self._verify_request_id()
114        self._verify_status()
115        self._verify_conditions()
116        self._verify_destination()
117        self._verify_subject_confirmation()
118        self._verify_not_seen_before()
119
120    def _decrypt_response(self):
121        """Decrypt SAMLResponse EncryptedAssertion Element"""
122        manager = xmlsec.KeysManager()
123        key = xmlsec.Key.from_memory(
124            self._source.encryption_kp.key_data,
125            xmlsec.constants.KeyDataFormatPem,
126        )
127
128        manager.add_key(key)
129        encryption_context = xmlsec.EncryptionContext(manager)
130
131        encrypted_assertion = self._root.find(f".//{{{NS_SAML_ASSERTION}}}EncryptedAssertion")
132        if encrypted_assertion is None:
133            raise InvalidEncryption("Response does not contain an EncryptedAssertion element.")
134        # Register Id attributes so a KeyInfo RetrievalMethod referencing a sibling
135        # EncryptedKey by #Id can be resolved by xmlsec
136        xmlsec.tree.add_ids(encrypted_assertion, ["Id"])
137        encrypted_data = xmlsec.tree.find_child(
138            encrypted_assertion, "EncryptedData", xmlsec.constants.EncNs
139        )
140        try:
141            decrypted_assertion = encryption_context.decrypt(encrypted_data)
142        except xmlsec.Error as exc:
143            raise InvalidEncryption(f"Failed to decrypt assertion: {exc}") from exc
144
145        index_of = self._root.index(encrypted_assertion)
146        self._root.remove(encrypted_assertion)
147        self._root.insert(
148            index_of,
149            decrypted_assertion,
150        )
151        self._assertion = decrypted_assertion
152
153    def _verify_conditions(self):
154        conditions = self.get_assertion().find(f"{{{NS_SAML_ASSERTION}}}Conditions")
155        if conditions is None:
156            return
157        _now = now()
158        before = conditions.attrib.get("NotBefore")
159        if before:
160            if datetime.fromisoformat(before).replace(tzinfo=UTC) > _now:
161                raise InvalidTime()
162        on_or_after = conditions.attrib.get("NotOnOrAfter")
163        if on_or_after:
164            if datetime.fromisoformat(on_or_after).replace(tzinfo=UTC) < _now:
165                raise InvalidTime()
166        self._verify_audience(conditions)
167
168    def _verify_audience(self, conditions: _Element):
169        """Verify that our entity ID is listed as an audience of the assertion. Each
170        AudienceRestriction is evaluated independently and must contain a matching Audience."""
171        entity_id = self._source.get_issuer(self._http_request)
172        for restriction in conditions.findall(f"{{{NS_SAML_ASSERTION}}}AudienceRestriction"):
173            audiences = [
174                get_element_text(audience).strip()
175                for audience in restriction.findall(f"{{{NS_SAML_ASSERTION}}}Audience")
176            ]
177            if entity_id not in audiences:
178                LOGGER.warning(
179                    "Assertion audience does not match source entity ID",
180                    entity_id=entity_id,
181                    audiences=audiences,
182                )
183                raise MismatchedAudience()
184
185    def _verify_signature(self, signature_node: _Element, target: _Element):
186        """Verify a single signature node against the given target element."""
187        target_id = target.attrib.get("ID")
188        if not target_id:
189            raise InvalidSignature("Signed element is missing an ID attribute.")
190        refs = signature_node.xpath("./ds:SignedInfo/ds:Reference", namespaces=NS_MAP)
191        if len(refs) != 1:
192            raise InvalidSignature("Signature must contain exactly one Reference.")
193        ref_uri = refs[0].get("URI", "")
194        if ref_uri not in ("", f"#{target_id}"):
195            raise InvalidSignature(
196                "Signature Reference URI does not match the signed element's ID."
197            )
198
199        xmlsec.tree.add_ids(target, ["ID"])
200
201        ctx = xmlsec.SignatureContext()
202        key = xmlsec.Key.from_memory(
203            self._source.verification_kp.certificate_data,
204            xmlsec.constants.KeyDataFormatCertPem,
205        )
206        ctx.key = key
207
208        ctx.set_enabled_key_data([xmlsec.constants.KeyDataX509])
209        try:
210            ctx.verify(signature_node)
211        except xmlsec.Error as exc:
212            raise InvalidSignature(
213                "The signature of the SAML object is either missing or invalid."
214            ) from exc
215        LOGGER.debug("Successfully verified signature")
216
217    def _verify_response_signature(self):
218        """Verify SAML Response's Signature (before decryption)"""
219        signature_nodes = self._root.xpath("/samlp:Response/ds:Signature", namespaces=NS_MAP)
220
221        if len(signature_nodes) != 1:
222            raise InvalidSignature("Expected exactly one Signature in the Response element.")
223
224        self._verify_signature(signature_nodes[0], self._root)
225
226    def _verify_assertion_signature(self):
227        """Verify SAML Assertion's Signature (after decryption)"""
228        signature_nodes = self._root.xpath(
229            "/samlp:Response/saml:Assertion/ds:Signature", namespaces=NS_MAP
230        )
231        if len(signature_nodes) != 1:
232            raise InvalidSignature("Expected exactly one signed Assertion in the Response.")
233        signature_node = signature_nodes[0]
234        assertion = signature_node.getparent()
235
236        self._verify_signature(signature_node, assertion)
237        self._assertion = assertion
238
239    def _verify_request_id(self):
240        if self._source.allow_idp_initiated:
241            return
242        # The Response and the assertion can both name the request that they answer. Read
243        # both, as only the value inside the assertion is covered by the signature. The
244        # value inside the assertion is checked in _verify_subject_confirmation.
245        in_response_to = self._root.attrib.get("InResponseTo")
246        confirmed_ids = [
247            data.attrib.get("InResponseTo") for data in self._get_bearer_confirmation_data()
248        ]
249        if SESSION_KEY_REQUEST_ID not in self._http_request.session or not any(
250            [in_response_to, *confirmed_ids]
251        ):
252            raise MismatchedRequestID(
253                "Missing InResponseTo and IdP-initiated Logins are not allowed"
254            )
255        if in_response_to and in_response_to != self._http_request.session[SESSION_KEY_REQUEST_ID]:
256            raise MismatchedRequestID("Mismatched request ID")
257
258    def _get_bearer_confirmation_data(self) -> list[_Element]:
259        """Get the SubjectConfirmationData of every bearer SubjectConfirmation of the
260        assertion."""
261        assertion = self.get_assertion()
262        if assertion is None:
263            return []
264        confirmations = []
265        for confirmation in assertion.findall(
266            f"{{{NS_SAML_ASSERTION}}}Subject/{{{NS_SAML_ASSERTION}}}SubjectConfirmation"
267        ):
268            method = confirmation.attrib.get("Method")
269            if method is not None and method != SAML_SUBJECT_CONFIRMATION_METHOD_BEARER:
270                continue
271            data = confirmation.find(f"{{{NS_SAML_ASSERTION}}}SubjectConfirmationData")
272            if data is None:
273                continue
274            confirmations.append(data)
275        return confirmations
276
277    def _verify_destination(self):
278        """Verify that the Response names the ACS URL of this Source"""
279        destination = self._root.attrib.get("Destination")
280        if not destination:
281            return
282        acs_url = self._http_request.build_absolute_uri(
283            reverse("authentik_sources_saml:acs", kwargs={"source_slug": self._source.slug})
284        )
285        if destination.lower() != acs_url.lower():
286            LOGGER.warning(
287                "Destination of Response does not match ACS URL",
288                destination=destination,
289                acs_url=acs_url,
290            )
291            raise MismatchedBinding("The Destination does not match the ACS URL of this Source.")
292
293    def _verify_subject_confirmation(self):
294        """One confirmation of the subject must name this Source. An assertion can carry
295        more than one, and satisfying one of them is enough."""
296        first_error = None
297        for data in self._get_bearer_confirmation_data():
298            try:
299                self._check_subject_confirmation(data)
300                return
301            except SAMLException as exc:
302                if first_error is None:
303                    first_error = exc
304        if first_error is not None:
305            raise first_error
306        raise MismatchedBinding(
307            "The assertion carries no confirmation of the subject for this Source."
308        )
309
310    def _check_subject_confirmation(self, data: _Element):
311        """Check one SubjectConfirmationData"""
312        recipient = data.attrib.get("Recipient")
313        if recipient:
314            acs_url = self._http_request.build_absolute_uri(
315                reverse("authentik_sources_saml:acs", kwargs={"source_slug": self._source.slug})
316            )
317            if recipient.lower() != acs_url.lower():
318                LOGGER.warning(
319                    "Recipient of assertion does not match ACS URL",
320                    recipient=recipient,
321                    acs_url=acs_url,
322                )
323                raise MismatchedBinding("The Recipient does not match the ACS URL of this Source.")
324        on_or_after = data.attrib.get("NotOnOrAfter")
325        if on_or_after:
326            if datetime.fromisoformat(on_or_after).replace(tzinfo=UTC) < now():
327                raise InvalidTime()
328        in_response_to = data.attrib.get("InResponseTo")
329        if in_response_to and not self._source.allow_idp_initiated:
330            if in_response_to != self._http_request.session.get(SESSION_KEY_REQUEST_ID):
331                raise MismatchedRequestID("Mismatched request ID")
332
333    def _verify_not_seen_before(self):
334        """Verify that the assertion was not used before"""
335        assertion = self.get_assertion()
336        if assertion is None:
337            return
338        assertion_id = assertion.attrib.get("ID")
339        if not assertion_id:
340            LOGGER.warning("Assertion has no ID, cannot check for re-use")
341            return
342        key = CACHE_SEEN_ASSERTION_ID % (
343            self._source.pk,
344            sha256(assertion_id.encode()).hexdigest(),
345        )
346        marker = uuid4().hex
347        cache.add(key, marker, timeout=CACHE_SEEN_ASSERTION_TIMEOUT)
348        if cache.get(key) != marker:
349            raise SuspiciousOperation("Replay attack detected")
350
351    def _verify_status(self):
352        """Check for SAML Status elements"""
353        status = self._root.find(f"{{{NS_SAML_PROTOCOL}}}Status")
354        if status is None:
355            return
356        status_code = status.find(f"{{{NS_SAML_PROTOCOL}}}StatusCode")
357        status_value = status_code.attrib.get("Value") if status_code is not None else None
358        # The second-level StatusCode carries the actual reason (e.g. RequestDenied, AuthnFailed);
359        # the top-level code only says which party is at fault
360        nested_status_code = (
361            status_code.find(f"{{{NS_SAML_PROTOCOL}}}StatusCode")
362            if status_code is not None
363            else None
364        )
365        nested_value = (
366            nested_status_code.attrib.get("Value") if nested_status_code is not None else None
367        )
368        message = status.find(f"{{{NS_SAML_PROTOCOL}}}StatusMessage")
369        message_text = message.text if message is not None else None
370        detail = status.find(f"{{{NS_SAML_PROTOCOL}}}StatusDetail")
371        detail_text = etree.tostring(detail, encoding="unicode") if detail is not None else None
372        if status_value != SAML_STATUS_SUCCESS:
373            LOGGER.warning(
374                "SAML Response has an unsuccessful status",
375                status_code=status_value,
376                nested_status_code=nested_value,
377                message=message_text,
378                detail=detail_text,
379            )
380            parts = [nested_value or status_value or "SAML Status", message_text, detail_text]
381            raise UnsuccessfulStatus(": ".join(part for part in parts if part))
382        if message_text or detail_text:
383            LOGGER.debug("SAML Status message", message=message_text, detail=detail_text)
384
385    def _handle_name_id_transient(self) -> SourceFlowManager:
386        """Handle a NameID with the Format of Transient. This is a bit more complex than other
387        formats, as we need to create a temporary User that is used in the session. This
388        user has an attribute that refers to our Source for cleanup. The user is also deleted
389        on logout and periodically."""
390        # Create a temporary User
391        name_id_el, name_id = self._get_name_id()
392        # trim username to ensure it is max 150 chars
393        username = f"ak-{name_id[: USERNAME_MAX_LENGTH - 14]}-transient"
394        expiry = mktime(
395            (now() + timedelta_from_string(self._source.temporary_user_delete_after)).timetuple()
396        )
397        user: User = User.objects.create(
398            username=username,
399            attributes={
400                USER_ATTRIBUTE_GENERATED: True,
401                USER_ATTRIBUTE_SOURCES: [
402                    self._source.name,
403                ],
404                USER_ATTRIBUTE_DELETE_ON_LOGOUT: True,
405                USER_ATTRIBUTE_EXPIRES: expiry,
406            },
407            path=self._source.get_user_path(),
408        )
409        LOGGER.debug("Created temporary user for NameID Transient", username=name_id)
410        UserSAMLSourceConnection.objects.create(source=self._source, user=user, identifier=name_id)
411        return SAMLSourceFlowManager(
412            source=self._source,
413            request=self._http_request,
414            identifier=str(name_id),
415            user_info={
416                "root": self._root,
417                "assertion": self.get_assertion(),
418                "name_id": name_id_el,
419            },
420            policy_context={},
421        )
422
423    def get_assertion(self) -> Element | None:
424        """Get assertion element, if we have a signed assertion"""
425        if self._assertion is not None:
426            return self._assertion
427        return self._root.find(f"{{{NS_SAML_ASSERTION}}}Assertion")
428
429    def _get_name_id(self) -> tuple[Element, str]:
430        """Get NameID Element"""
431        assertion = self.get_assertion()
432        if assertion is None:
433            raise MissingNameID("Assertion element not found")
434        subject = assertion.find(f"{{{NS_SAML_ASSERTION}}}Subject")
435        if subject is None:
436            raise MissingNameID("Subject element not found")
437        name_id = subject.find(f"{{{NS_SAML_ASSERTION}}}NameID")
438        if name_id is None:
439            raise MissingNameID("NameID element not found")
440        return name_id, get_element_text(name_id)
441
442    def _get_name_id_filter(self) -> dict[str, str]:
443        """Returns the subject's NameID as a Filter for the `User`"""
444        name_id_el, name_id = self._get_name_id()
445        if not name_id:
446            raise UnsupportedNameIDFormat("Subject's NameID is empty.")
447        _format = name_id_el.attrib.get("Format", SAML_NAME_ID_FORMAT_UNSPECIFIED)
448        if _format == SAML_NAME_ID_FORMAT_EMAIL:
449            return {"email": name_id}
450        if _format == SAML_NAME_ID_FORMAT_PERSISTENT:
451            return {"username": name_id}
452        if _format == SAML_NAME_ID_FORMAT_X509:
453            # This attribute is statically set by the LDAP source
454            return {"attributes__distinguishedName": name_id}
455        if _format == SAML_NAME_ID_FORMAT_WINDOWS:
456            if "\\" in name_id:
457                name_id = name_id.split("\\")[1]
458            return {"username": name_id}
459        raise UnsupportedNameIDFormat(
460            f"Assertion contains NameID with unsupported format {_format}."
461        )
462
463    def prepare_flow_manager(self) -> SourceFlowManager:
464        """Prepare flow plan depending on whether or not the user exists"""
465        name_id_el, name_id = self._get_name_id()
466        # The Format attribute is optional, and defaults to unspecified
467        name_id_format = name_id_el.attrib.get("Format", SAML_NAME_ID_FORMAT_UNSPECIFIED)
468        # Sanity check, show a warning if NameIDPolicy doesn't match what we go
469        if self._source.name_id_policy != name_id_format:
470            LOGGER.warning(
471                "NameID from IdP doesn't match our policy",
472                expected=self._source.name_id_policy,
473                got=name_id_format,
474            )
475        # transient NameIDs are handled separately as they don't have to go through flows.
476        if name_id_format == SAML_NAME_ID_FORMAT_TRANSIENT:
477            return self._handle_name_id_transient()
478
479        return SAMLSourceFlowManager(
480            source=self._source,
481            request=self._http_request,
482            identifier=str(name_id),
483            user_info={
484                "root": self._root,
485                "assertion": self.get_assertion(),
486                "name_id": name_id_el,
487            },
488            policy_context={
489                "saml_response": etree.tostring(self._root),
490            },
491        )

SAML Response Processor

ResponseProcessor( source: authentik.sources.saml.models.SAMLSource, request: django.http.request.HttpRequest)
88    def __init__(self, source: SAMLSource, request: HttpRequest):
89        self._source = source
90        self._http_request = request
def parse(self):
 92    def parse(self):
 93        """Check if `request` contains SAML Response data, parse and validate it."""
 94        # First off, check if we have any SAML Data at all.
 95        raw_response = self._http_request.POST.get("SAMLResponse", None)
 96        if not raw_response:
 97            raise MissingSAMLResponse("Request does not contain 'SAMLResponse'")
 98        # Check if response is compressed, b64 decode it
 99        self._root_xml = b64decode(raw_response.encode())
100        self._root = lxml_from_string(self._root_xml)
101
102        # Verify response signature BEFORE decryption (signature covers encrypted content)
103        if self._source.verification_kp and self._source.signed_response:
104            self._verify_response_signature()
105
106        if self._source.encryption_kp:
107            self._decrypt_response()
108
109        # Verify assertion signature AFTER decryption (signature is inside encrypted content)
110        if self._source.verification_kp and self._source.signed_assertion:
111            self._verify_assertion_signature()
112
113        self._verify_request_id()
114        self._verify_status()
115        self._verify_conditions()
116        self._verify_destination()
117        self._verify_subject_confirmation()
118        self._verify_not_seen_before()

Check if request contains SAML Response data, parse and validate it.

def get_assertion(unknown):
423    def get_assertion(self) -> Element | None:
424        """Get assertion element, if we have a signed assertion"""
425        if self._assertion is not None:
426            return self._assertion
427        return self._root.find(f"{{{NS_SAML_ASSERTION}}}Assertion")

Get assertion element, if we have a signed assertion

def prepare_flow_manager(self) -> authentik.core.sources.flow_manager.SourceFlowManager:
463    def prepare_flow_manager(self) -> SourceFlowManager:
464        """Prepare flow plan depending on whether or not the user exists"""
465        name_id_el, name_id = self._get_name_id()
466        # The Format attribute is optional, and defaults to unspecified
467        name_id_format = name_id_el.attrib.get("Format", SAML_NAME_ID_FORMAT_UNSPECIFIED)
468        # Sanity check, show a warning if NameIDPolicy doesn't match what we go
469        if self._source.name_id_policy != name_id_format:
470            LOGGER.warning(
471                "NameID from IdP doesn't match our policy",
472                expected=self._source.name_id_policy,
473                got=name_id_format,
474            )
475        # transient NameIDs are handled separately as they don't have to go through flows.
476        if name_id_format == SAML_NAME_ID_FORMAT_TRANSIENT:
477            return self._handle_name_id_transient()
478
479        return SAMLSourceFlowManager(
480            source=self._source,
481            request=self._http_request,
482            identifier=str(name_id),
483            user_info={
484                "root": self._root,
485                "assertion": self.get_assertion(),
486                "name_id": name_id_el,
487            },
488            policy_context={
489                "saml_response": etree.tostring(self._root),
490            },
491        )

Prepare flow plan depending on whether or not the user exists

class SAMLSourceFlowManager(authentik.core.sources.flow_manager.SourceFlowManager):
494class SAMLSourceFlowManager(SourceFlowManager):
495    """Source flow manager for SAML Sources"""
496
497    user_connection_type = UserSAMLSourceConnection
498    group_connection_type = GroupSAMLSourceConnection

Source flow manager for SAML Sources