authentik.enterprise.providers.ws_federation.processors.assertion_saml11

SAML 1.1 Assertion generator for WS-Federation

  1"""SAML 1.1 Assertion generator for WS-Federation"""
  2
  3from hashlib import sha256
  4from types import GeneratorType
  5
  6import xmlsec
  7from lxml.etree import Element, SubElement, _Element  # nosec
  8from structlog.stdlib import get_logger
  9
 10from authentik.common.saml.constants import (
 11    NS_SIGNATURE,
 12    SIGN_ALGORITHM_TRANSFORM_MAP,
 13)
 14from authentik.core.expression.exceptions import PropertyMappingExpressionException
 15from authentik.events.models import Event, EventAction
 16from authentik.events.signals import get_login_event
 17from authentik.providers.saml.models import SAMLPropertyMapping
 18from authentik.providers.saml.processors.assertion import AssertionProcessor
 19from authentik.providers.saml.processors.signature import sign_xml_element
 20from authentik.sources.saml.exceptions import InvalidSignature
 21from authentik.stages.password.stage import PLAN_CONTEXT_METHOD
 22
 23LOGGER = get_logger()
 24
 25# SAML 1.0 and 1.1 share this namespace; version is set via MajorVersion/MinorVersion attributes
 26NS_SAML11_ASSERTION = "urn:oasis:names:tc:SAML:1.0:assertion"
 27NS_MAP_SAML11 = {"saml": NS_SAML11_ASSERTION, "ds": NS_SIGNATURE}
 28
 29SAML11_CM_BEARER = "urn:oasis:names:tc:SAML:1.0:cm:bearer"
 30SAML11_AM_PASSWORD = "urn:oasis:names:tc:SAML:1.0:am:password"
 31SAML11_AM_UNSPECIFIED = "urn:oasis:names:tc:SAML:1.0:am:unspecified"
 32WSFED_ATTRIBUTE_NAMESPACE = "http://schemas.xmlsoap.org/claims"
 33
 34
 35class SAML11AssertionProcessor(AssertionProcessor):
 36    """SAML 1.1 assertion builder, overriding the SAML 2.0 methods that differ."""
 37
 38    def get_name_id(self) -> _Element:
 39        # same value/format resolution as SAML 2.0, wrapped as NameIdentifier instead of NameID
 40        name_id = super().get_name_id()
 41        name_identifier = Element(f"{{{NS_SAML11_ASSERTION}}}NameIdentifier")
 42        name_identifier.attrib["Format"] = name_id.attrib["Format"]
 43        name_identifier.text = name_id.text
 44        return name_identifier
 45
 46    def get_assertion_subject(self) -> _Element:
 47        # SAML 1.1 has no assertion-level Subject; each statement embeds its own
 48        subject = Element(f"{{{NS_SAML11_ASSERTION}}}Subject")
 49        subject.append(self.get_name_id())
 50
 51        subject_confirmation = SubElement(subject, f"{{{NS_SAML11_ASSERTION}}}SubjectConfirmation")
 52        confirmation_method = SubElement(
 53            subject_confirmation, f"{{{NS_SAML11_ASSERTION}}}ConfirmationMethod"
 54        )
 55        confirmation_method.text = SAML11_CM_BEARER
 56        return subject
 57
 58    def get_assertion_conditions(self) -> _Element:
 59        conditions = Element(f"{{{NS_SAML11_ASSERTION}}}Conditions")
 60        conditions.attrib["NotBefore"] = self._valid_not_before
 61        conditions.attrib["NotOnOrAfter"] = self._valid_not_on_or_after
 62        if self.provider.audience != "":
 63            audience_restriction_condition = SubElement(
 64                conditions, f"{{{NS_SAML11_ASSERTION}}}AudienceRestrictionCondition"
 65            )
 66            audience = SubElement(
 67                audience_restriction_condition, f"{{{NS_SAML11_ASSERTION}}}Audience"
 68            )
 69            audience.text = self.provider.audience
 70        return conditions
 71
 72    def get_assertion_auth_n_statement(self) -> _Element:
 73        auth_statement = Element(f"{{{NS_SAML11_ASSERTION}}}AuthenticationStatement")
 74        auth_statement.attrib["AuthenticationInstant"] = self._auth_instant
 75        auth_statement.attrib["AuthenticationMethod"] = SAML11_AM_UNSPECIFIED
 76        self.session_index = sha256(
 77            self.http_request.session.session_key.encode("ascii")
 78        ).hexdigest()
 79        event = get_login_event(self.http_request)
 80        if event and event.context.get(PLAN_CONTEXT_METHOD, "") == "password":
 81            auth_statement.attrib["AuthenticationMethod"] = SAML11_AM_PASSWORD
 82
 83        if self.provider.authn_context_class_ref_mapping:
 84            try:
 85                value = self.provider.authn_context_class_ref_mapping.evaluate(
 86                    user=self.http_request.user,
 87                    request=self.http_request,
 88                    provider=self.provider,
 89                )
 90                if value is not None:
 91                    auth_statement.attrib["AuthenticationMethod"] = str(value)
 92            except PropertyMappingExpressionException as exc:
 93                Event.new(
 94                    EventAction.CONFIGURATION_ERROR,
 95                    message=(
 96                        "Failed to evaluate property-mapping: "
 97                        f"'{self.provider.authn_context_class_ref_mapping.name}'"
 98                    ),
 99                    provider=self.provider,
100                    mapping=self.provider.authn_context_class_ref_mapping,
101                ).from_http(self.http_request)
102                LOGGER.warning("Failed to evaluate property mapping", exc=exc)
103
104        auth_statement.append(self.get_assertion_subject())
105        return auth_statement
106
107    def get_attributes(self) -> _Element | None:
108        # None if empty: SAML 1.1's schema requires at least one Attribute per AttributeStatement
109        attribute_statement = Element(f"{{{NS_SAML11_ASSERTION}}}AttributeStatement")
110        attribute_statement.append(self.get_assertion_subject())
111        user = self.http_request.user
112        has_attribute = False
113        for mapping in SAMLPropertyMapping.objects.filter(provider=self.provider).order_by(
114            "saml_name"
115        ):
116            try:
117                mapping: SAMLPropertyMapping
118                value = mapping.evaluate(
119                    user=user,
120                    request=self.http_request,
121                    provider=self.provider,
122                )
123                if value is None:
124                    continue
125
126                attribute = Element(f"{{{NS_SAML11_ASSERTION}}}Attribute")
127                attribute.attrib["AttributeName"] = mapping.saml_name
128                attribute.attrib["AttributeNamespace"] = WSFED_ATTRIBUTE_NAMESPACE
129
130                if not isinstance(value, list | GeneratorType):
131                    value = [value]
132
133                for value_item in value:
134                    attribute_value = SubElement(
135                        attribute, f"{{{NS_SAML11_ASSERTION}}}AttributeValue"
136                    )
137                    str_value = str(value_item) if not isinstance(value_item, str) else value_item
138                    attribute_value.text = str_value
139
140                attribute_statement.append(attribute)
141                has_attribute = True
142            except (PropertyMappingExpressionException, ValueError) as exc:
143                Event.new(
144                    EventAction.CONFIGURATION_ERROR,
145                    message=f"Failed to evaluate property-mapping: '{mapping.name}'",
146                    provider=self.provider,
147                    mapping=mapping,
148                ).from_http(self.http_request)
149                LOGGER.warning("Failed to evaluate property mapping", exc=exc)
150                continue
151        if not has_attribute:
152            return None
153        return attribute_statement
154
155    def get_assertion(self) -> _Element:
156        assertion = Element(f"{{{NS_SAML11_ASSERTION}}}Assertion", nsmap=NS_MAP_SAML11)
157        assertion.attrib["MajorVersion"] = "1"
158        assertion.attrib["MinorVersion"] = "1"
159        assertion.attrib["AssertionID"] = self._assertion_id
160        assertion.attrib["IssueInstant"] = self._issue_instant
161        self.issuer = self._get_issuer_value()
162        assertion.attrib["Issuer"] = self.issuer
163
164        assertion.append(self.get_assertion_conditions())
165        assertion.append(self.get_assertion_auth_n_statement())
166        attribute_statement = self.get_attributes()
167        if attribute_statement is not None:
168            assertion.append(attribute_statement)
169
170        # unlike SAML 2.0, ds:Signature must be the last child of Assertion
171        if self.provider.signing_kp and self.provider.sign_assertion:
172            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
173                self.provider.signature_algorithm, xmlsec.constants.TransformRsaSha1
174            )
175            signature = xmlsec.template.create(
176                assertion,
177                xmlsec.constants.TransformExclC14N,
178                sign_algorithm_transform,
179                ns=xmlsec.constants.DSigNs,
180            )
181            assertion.append(signature)
182
183        return assertion
184
185    def _sign(self, element: _Element) -> None:
186        try:
187            sign_xml_element(element, self.provider, id_attribute="AssertionID")
188        except xmlsec.Error as exc:
189            raise InvalidSignature() from exc
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
NS_SAML11_ASSERTION = 'urn:oasis:names:tc:SAML:1.0:assertion'
NS_MAP_SAML11 = {'saml': 'urn:oasis:names:tc:SAML:1.0:assertion', 'ds': 'http://www.w3.org/2000/09/xmldsig#'}
SAML11_CM_BEARER = 'urn:oasis:names:tc:SAML:1.0:cm:bearer'
SAML11_AM_PASSWORD = 'urn:oasis:names:tc:SAML:1.0:am:password'
SAML11_AM_UNSPECIFIED = 'urn:oasis:names:tc:SAML:1.0:am:unspecified'
WSFED_ATTRIBUTE_NAMESPACE = 'http://schemas.xmlsoap.org/claims'
class SAML11AssertionProcessor(authentik.providers.saml.processors.assertion.AssertionProcessor):
 36class SAML11AssertionProcessor(AssertionProcessor):
 37    """SAML 1.1 assertion builder, overriding the SAML 2.0 methods that differ."""
 38
 39    def get_name_id(self) -> _Element:
 40        # same value/format resolution as SAML 2.0, wrapped as NameIdentifier instead of NameID
 41        name_id = super().get_name_id()
 42        name_identifier = Element(f"{{{NS_SAML11_ASSERTION}}}NameIdentifier")
 43        name_identifier.attrib["Format"] = name_id.attrib["Format"]
 44        name_identifier.text = name_id.text
 45        return name_identifier
 46
 47    def get_assertion_subject(self) -> _Element:
 48        # SAML 1.1 has no assertion-level Subject; each statement embeds its own
 49        subject = Element(f"{{{NS_SAML11_ASSERTION}}}Subject")
 50        subject.append(self.get_name_id())
 51
 52        subject_confirmation = SubElement(subject, f"{{{NS_SAML11_ASSERTION}}}SubjectConfirmation")
 53        confirmation_method = SubElement(
 54            subject_confirmation, f"{{{NS_SAML11_ASSERTION}}}ConfirmationMethod"
 55        )
 56        confirmation_method.text = SAML11_CM_BEARER
 57        return subject
 58
 59    def get_assertion_conditions(self) -> _Element:
 60        conditions = Element(f"{{{NS_SAML11_ASSERTION}}}Conditions")
 61        conditions.attrib["NotBefore"] = self._valid_not_before
 62        conditions.attrib["NotOnOrAfter"] = self._valid_not_on_or_after
 63        if self.provider.audience != "":
 64            audience_restriction_condition = SubElement(
 65                conditions, f"{{{NS_SAML11_ASSERTION}}}AudienceRestrictionCondition"
 66            )
 67            audience = SubElement(
 68                audience_restriction_condition, f"{{{NS_SAML11_ASSERTION}}}Audience"
 69            )
 70            audience.text = self.provider.audience
 71        return conditions
 72
 73    def get_assertion_auth_n_statement(self) -> _Element:
 74        auth_statement = Element(f"{{{NS_SAML11_ASSERTION}}}AuthenticationStatement")
 75        auth_statement.attrib["AuthenticationInstant"] = self._auth_instant
 76        auth_statement.attrib["AuthenticationMethod"] = SAML11_AM_UNSPECIFIED
 77        self.session_index = sha256(
 78            self.http_request.session.session_key.encode("ascii")
 79        ).hexdigest()
 80        event = get_login_event(self.http_request)
 81        if event and event.context.get(PLAN_CONTEXT_METHOD, "") == "password":
 82            auth_statement.attrib["AuthenticationMethod"] = SAML11_AM_PASSWORD
 83
 84        if self.provider.authn_context_class_ref_mapping:
 85            try:
 86                value = self.provider.authn_context_class_ref_mapping.evaluate(
 87                    user=self.http_request.user,
 88                    request=self.http_request,
 89                    provider=self.provider,
 90                )
 91                if value is not None:
 92                    auth_statement.attrib["AuthenticationMethod"] = str(value)
 93            except PropertyMappingExpressionException as exc:
 94                Event.new(
 95                    EventAction.CONFIGURATION_ERROR,
 96                    message=(
 97                        "Failed to evaluate property-mapping: "
 98                        f"'{self.provider.authn_context_class_ref_mapping.name}'"
 99                    ),
100                    provider=self.provider,
101                    mapping=self.provider.authn_context_class_ref_mapping,
102                ).from_http(self.http_request)
103                LOGGER.warning("Failed to evaluate property mapping", exc=exc)
104
105        auth_statement.append(self.get_assertion_subject())
106        return auth_statement
107
108    def get_attributes(self) -> _Element | None:
109        # None if empty: SAML 1.1's schema requires at least one Attribute per AttributeStatement
110        attribute_statement = Element(f"{{{NS_SAML11_ASSERTION}}}AttributeStatement")
111        attribute_statement.append(self.get_assertion_subject())
112        user = self.http_request.user
113        has_attribute = False
114        for mapping in SAMLPropertyMapping.objects.filter(provider=self.provider).order_by(
115            "saml_name"
116        ):
117            try:
118                mapping: SAMLPropertyMapping
119                value = mapping.evaluate(
120                    user=user,
121                    request=self.http_request,
122                    provider=self.provider,
123                )
124                if value is None:
125                    continue
126
127                attribute = Element(f"{{{NS_SAML11_ASSERTION}}}Attribute")
128                attribute.attrib["AttributeName"] = mapping.saml_name
129                attribute.attrib["AttributeNamespace"] = WSFED_ATTRIBUTE_NAMESPACE
130
131                if not isinstance(value, list | GeneratorType):
132                    value = [value]
133
134                for value_item in value:
135                    attribute_value = SubElement(
136                        attribute, f"{{{NS_SAML11_ASSERTION}}}AttributeValue"
137                    )
138                    str_value = str(value_item) if not isinstance(value_item, str) else value_item
139                    attribute_value.text = str_value
140
141                attribute_statement.append(attribute)
142                has_attribute = True
143            except (PropertyMappingExpressionException, ValueError) as exc:
144                Event.new(
145                    EventAction.CONFIGURATION_ERROR,
146                    message=f"Failed to evaluate property-mapping: '{mapping.name}'",
147                    provider=self.provider,
148                    mapping=mapping,
149                ).from_http(self.http_request)
150                LOGGER.warning("Failed to evaluate property mapping", exc=exc)
151                continue
152        if not has_attribute:
153            return None
154        return attribute_statement
155
156    def get_assertion(self) -> _Element:
157        assertion = Element(f"{{{NS_SAML11_ASSERTION}}}Assertion", nsmap=NS_MAP_SAML11)
158        assertion.attrib["MajorVersion"] = "1"
159        assertion.attrib["MinorVersion"] = "1"
160        assertion.attrib["AssertionID"] = self._assertion_id
161        assertion.attrib["IssueInstant"] = self._issue_instant
162        self.issuer = self._get_issuer_value()
163        assertion.attrib["Issuer"] = self.issuer
164
165        assertion.append(self.get_assertion_conditions())
166        assertion.append(self.get_assertion_auth_n_statement())
167        attribute_statement = self.get_attributes()
168        if attribute_statement is not None:
169            assertion.append(attribute_statement)
170
171        # unlike SAML 2.0, ds:Signature must be the last child of Assertion
172        if self.provider.signing_kp and self.provider.sign_assertion:
173            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
174                self.provider.signature_algorithm, xmlsec.constants.TransformRsaSha1
175            )
176            signature = xmlsec.template.create(
177                assertion,
178                xmlsec.constants.TransformExclC14N,
179                sign_algorithm_transform,
180                ns=xmlsec.constants.DSigNs,
181            )
182            assertion.append(signature)
183
184        return assertion
185
186    def _sign(self, element: _Element) -> None:
187        try:
188            sign_xml_element(element, self.provider, id_attribute="AssertionID")
189        except xmlsec.Error as exc:
190            raise InvalidSignature() from exc

SAML 1.1 assertion builder, overriding the SAML 2.0 methods that differ.

def get_name_id(self) -> lxml.etree._Element:
39    def get_name_id(self) -> _Element:
40        # same value/format resolution as SAML 2.0, wrapped as NameIdentifier instead of NameID
41        name_id = super().get_name_id()
42        name_identifier = Element(f"{{{NS_SAML11_ASSERTION}}}NameIdentifier")
43        name_identifier.attrib["Format"] = name_id.attrib["Format"]
44        name_identifier.text = name_id.text
45        return name_identifier

Get NameID Element

def get_assertion_subject(self) -> lxml.etree._Element:
47    def get_assertion_subject(self) -> _Element:
48        # SAML 1.1 has no assertion-level Subject; each statement embeds its own
49        subject = Element(f"{{{NS_SAML11_ASSERTION}}}Subject")
50        subject.append(self.get_name_id())
51
52        subject_confirmation = SubElement(subject, f"{{{NS_SAML11_ASSERTION}}}SubjectConfirmation")
53        confirmation_method = SubElement(
54            subject_confirmation, f"{{{NS_SAML11_ASSERTION}}}ConfirmationMethod"
55        )
56        confirmation_method.text = SAML11_CM_BEARER
57        return subject

Generate Subject Element with NameID and SubjectConfirmation Objects

def get_assertion_conditions(self) -> lxml.etree._Element:
59    def get_assertion_conditions(self) -> _Element:
60        conditions = Element(f"{{{NS_SAML11_ASSERTION}}}Conditions")
61        conditions.attrib["NotBefore"] = self._valid_not_before
62        conditions.attrib["NotOnOrAfter"] = self._valid_not_on_or_after
63        if self.provider.audience != "":
64            audience_restriction_condition = SubElement(
65                conditions, f"{{{NS_SAML11_ASSERTION}}}AudienceRestrictionCondition"
66            )
67            audience = SubElement(
68                audience_restriction_condition, f"{{{NS_SAML11_ASSERTION}}}Audience"
69            )
70            audience.text = self.provider.audience
71        return conditions

Generate Conditions with AudienceRestriction and Audience Elements.

def get_assertion_auth_n_statement(self) -> lxml.etree._Element:
 73    def get_assertion_auth_n_statement(self) -> _Element:
 74        auth_statement = Element(f"{{{NS_SAML11_ASSERTION}}}AuthenticationStatement")
 75        auth_statement.attrib["AuthenticationInstant"] = self._auth_instant
 76        auth_statement.attrib["AuthenticationMethod"] = SAML11_AM_UNSPECIFIED
 77        self.session_index = sha256(
 78            self.http_request.session.session_key.encode("ascii")
 79        ).hexdigest()
 80        event = get_login_event(self.http_request)
 81        if event and event.context.get(PLAN_CONTEXT_METHOD, "") == "password":
 82            auth_statement.attrib["AuthenticationMethod"] = SAML11_AM_PASSWORD
 83
 84        if self.provider.authn_context_class_ref_mapping:
 85            try:
 86                value = self.provider.authn_context_class_ref_mapping.evaluate(
 87                    user=self.http_request.user,
 88                    request=self.http_request,
 89                    provider=self.provider,
 90                )
 91                if value is not None:
 92                    auth_statement.attrib["AuthenticationMethod"] = str(value)
 93            except PropertyMappingExpressionException as exc:
 94                Event.new(
 95                    EventAction.CONFIGURATION_ERROR,
 96                    message=(
 97                        "Failed to evaluate property-mapping: "
 98                        f"'{self.provider.authn_context_class_ref_mapping.name}'"
 99                    ),
100                    provider=self.provider,
101                    mapping=self.provider.authn_context_class_ref_mapping,
102                ).from_http(self.http_request)
103                LOGGER.warning("Failed to evaluate property mapping", exc=exc)
104
105        auth_statement.append(self.get_assertion_subject())
106        return auth_statement

Generate AuthnStatement with AuthnContext and ContextClassRef Elements.

def get_attributes(self) -> lxml.etree._Element | None:
108    def get_attributes(self) -> _Element | None:
109        # None if empty: SAML 1.1's schema requires at least one Attribute per AttributeStatement
110        attribute_statement = Element(f"{{{NS_SAML11_ASSERTION}}}AttributeStatement")
111        attribute_statement.append(self.get_assertion_subject())
112        user = self.http_request.user
113        has_attribute = False
114        for mapping in SAMLPropertyMapping.objects.filter(provider=self.provider).order_by(
115            "saml_name"
116        ):
117            try:
118                mapping: SAMLPropertyMapping
119                value = mapping.evaluate(
120                    user=user,
121                    request=self.http_request,
122                    provider=self.provider,
123                )
124                if value is None:
125                    continue
126
127                attribute = Element(f"{{{NS_SAML11_ASSERTION}}}Attribute")
128                attribute.attrib["AttributeName"] = mapping.saml_name
129                attribute.attrib["AttributeNamespace"] = WSFED_ATTRIBUTE_NAMESPACE
130
131                if not isinstance(value, list | GeneratorType):
132                    value = [value]
133
134                for value_item in value:
135                    attribute_value = SubElement(
136                        attribute, f"{{{NS_SAML11_ASSERTION}}}AttributeValue"
137                    )
138                    str_value = str(value_item) if not isinstance(value_item, str) else value_item
139                    attribute_value.text = str_value
140
141                attribute_statement.append(attribute)
142                has_attribute = True
143            except (PropertyMappingExpressionException, ValueError) as exc:
144                Event.new(
145                    EventAction.CONFIGURATION_ERROR,
146                    message=f"Failed to evaluate property-mapping: '{mapping.name}'",
147                    provider=self.provider,
148                    mapping=mapping,
149                ).from_http(self.http_request)
150                LOGGER.warning("Failed to evaluate property mapping", exc=exc)
151                continue
152        if not has_attribute:
153            return None
154        return attribute_statement

Get AttributeStatement Element with Attributes from Property Mappings.

def get_assertion(self) -> lxml.etree._Element:
156    def get_assertion(self) -> _Element:
157        assertion = Element(f"{{{NS_SAML11_ASSERTION}}}Assertion", nsmap=NS_MAP_SAML11)
158        assertion.attrib["MajorVersion"] = "1"
159        assertion.attrib["MinorVersion"] = "1"
160        assertion.attrib["AssertionID"] = self._assertion_id
161        assertion.attrib["IssueInstant"] = self._issue_instant
162        self.issuer = self._get_issuer_value()
163        assertion.attrib["Issuer"] = self.issuer
164
165        assertion.append(self.get_assertion_conditions())
166        assertion.append(self.get_assertion_auth_n_statement())
167        attribute_statement = self.get_attributes()
168        if attribute_statement is not None:
169            assertion.append(attribute_statement)
170
171        # unlike SAML 2.0, ds:Signature must be the last child of Assertion
172        if self.provider.signing_kp and self.provider.sign_assertion:
173            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
174                self.provider.signature_algorithm, xmlsec.constants.TransformRsaSha1
175            )
176            signature = xmlsec.template.create(
177                assertion,
178                xmlsec.constants.TransformExclC14N,
179                sign_algorithm_transform,
180                ns=xmlsec.constants.DSigNs,
181            )
182            assertion.append(signature)
183
184        return assertion

Generate Main Assertion Element