authentik.providers.saml.processors.metadata_parser

SAML ServiceProvider Metadata Parser and dataclass

  1"""SAML ServiceProvider Metadata Parser and dataclass"""
  2
  3from dataclasses import dataclass
  4
  5import xmlsec
  6from cryptography.hazmat.backends import default_backend
  7from cryptography.x509 import InvalidVersion, load_pem_x509_certificate
  8from django.db import transaction
  9from lxml import etree  # nosec
 10from structlog.stdlib import get_logger
 11
 12from authentik.common.saml.constants import (
 13    ENCRYPTION_ALGORITHM_TRANSLATION_MAP,
 14    NS_MAP,
 15    NS_SAML_METADATA,
 16)
 17from authentik.crypto.models import CertificateKeyPair, format_cert
 18from authentik.flows.models import Flow
 19from authentik.lib.xml import lxml_from_string
 20from authentik.providers.saml.models import SAMLBindings, SAMLPropertyMapping, SAMLProvider
 21from authentik.sources.saml.models import SAMLNameIDPolicy
 22
 23LOGGER = get_logger()
 24
 25# Which binding to pick when metadata advertises an endpoint for more than one of them.
 26# POST is preferred as the Redirect binding must not be used to deliver a Response
 27# (SAML 2.0 Profiles, 4.1.2) and only a POST SLS binding allows back-channel logout.
 28BINDING_PREFERENCE = (SAMLBindings.POST, SAMLBindings.REDIRECT)
 29
 30
 31@dataclass(slots=True)
 32class ServiceProviderMetadata:
 33    """SP Metadata Dataclass"""
 34
 35    entity_id: str
 36
 37    acs_binding: str
 38    acs_location: str
 39
 40    auth_n_request_signed: bool
 41    assertion_signed: bool
 42    name_id_policy: SAMLNameIDPolicy
 43
 44    signing_keypair: CertificateKeyPair | None = None
 45    encryption_keypair: CertificateKeyPair | None = None
 46    encryption_algorithm: str | None = None
 47
 48    # Single Logout Service (optional)
 49    sls_binding: str | None = None
 50    sls_location: str | None = None
 51
 52    @transaction.atomic
 53    def to_provider(
 54        self, name: str, authorization_flow: Flow, invalidation_flow: Flow
 55    ) -> SAMLProvider:
 56        """Create a SAMLProvider instance from the details. `name` is required,
 57        as depending on the metadata CertificateKeypairs might have to be created."""
 58        provider = SAMLProvider.objects.create(
 59            name=name, authorization_flow=authorization_flow, invalidation_flow=invalidation_flow
 60        )
 61        provider.sp_binding = self.acs_binding
 62        provider.acs_url = self.acs_location
 63        provider.audience = self.entity_id
 64        provider.default_name_id_policy = self.name_id_policy
 65        # Single Logout Service
 66        if self.sls_location:
 67            provider.sls_url = self.sls_location
 68        if self.sls_binding:
 69            provider.sls_binding = self.sls_binding
 70        if self.signing_keypair and self.auth_n_request_signed:
 71            self.signing_keypair.name = f"Provider {name} - SAML Signing Certificate"
 72            self.signing_keypair.save()
 73            provider.verification_kp = self.signing_keypair
 74        if self.encryption_keypair:
 75            self.encryption_keypair.name = f"Provider {name} - SAML Encryption Certificate"
 76            self.encryption_keypair.save()
 77            provider.encryption_kp = self.encryption_keypair
 78            if self.encryption_algorithm:
 79                provider.encryption_algorithm = self.encryption_algorithm
 80        if self.assertion_signed:
 81            provider.signing_kp = CertificateKeyPair.objects.exclude(key_data__iexact="").first()
 82        # Set all auto-generated Property-mappings as defaults
 83        # They should provide a sane default for most applications:
 84        provider.property_mappings.set(SAMLPropertyMapping.objects.exclude(managed__isnull=True))
 85        provider.save()
 86        return provider
 87
 88
 89class ServiceProviderMetadataParser:
 90    """Service-Provider Metadata Parser"""
 91
 92    def get_signing_cert(self, root: etree.Element) -> CertificateKeyPair | None:
 93        """Extract signing X509Certificate from metadata, when given."""
 94        signing_certs = root.xpath(
 95            '//md:SPSSODescriptor/md:KeyDescriptor[@use="signing"]//ds:X509Certificate/text()',
 96            namespaces=NS_MAP,
 97        )
 98        if len(signing_certs) < 1:
 99            return None
100        raw_cert = format_cert(signing_certs[0])
101        # sanity check, make sure the certificate is valid.
102        try:
103            load_pem_x509_certificate(raw_cert.encode("utf-8"), default_backend())
104        except InvalidVersion as exc:
105            raise ValueError("Certificate in metadata is not a valid X.509 version") from exc
106        return CertificateKeyPair(
107            certificate_data=raw_cert,
108        )
109
110    def get_encryption_cert(self, root: etree.Element) -> CertificateKeyPair | None:
111        """Extract encryption X509Certificate from metadata, when given."""
112        encryption_certs = root.xpath(
113            '//md:SPSSODescriptor/md:KeyDescriptor[@use="encryption"]//ds:X509Certificate/text()',
114            namespaces=NS_MAP,
115        )
116        if len(encryption_certs) < 1:
117            return None
118        raw_cert = format_cert(encryption_certs[0])
119        # sanity check, make sure the certificate is valid.
120        try:
121            load_pem_x509_certificate(raw_cert.encode("utf-8"), default_backend())
122        except InvalidVersion as exc:
123            raise ValueError("Certificate in metadata is not a valid X.509 version") from exc
124        return CertificateKeyPair(
125            certificate_data=raw_cert,
126        )
127
128    def get_encryption_algorithm(self, root: etree.Element) -> str | None:
129        """Extract the SP's preferred encryption algorithm from its metadata, when given.
130
131        The SAML V2.0 Metadata Profile for Algorithm Support advertises supported
132        algorithms as `<md:EncryptionMethod>` elements in the SP's order of preference.
133        We honor that order and return the first block cipher we support."""
134        algorithms = root.xpath(
135            '//md:SPSSODescriptor/md:KeyDescriptor[@use="encryption"]'
136            "/md:EncryptionMethod/@Algorithm",
137            namespaces=NS_MAP,
138        )
139        for algorithm in algorithms:
140            if algorithm in ENCRYPTION_ALGORITHM_TRANSLATION_MAP:
141                return algorithm
142        return None
143
144    def select_endpoint(
145        self, endpoints: list[etree.Element]
146    ) -> tuple[SAMLBindings, str] | tuple[None, None]:
147        """Select the endpoint authentik should use out of `endpoints`, ignoring any endpoint
148        with a binding we don't support. Endpoints are picked by `BINDING_PREFERENCE` first,
149        then by `isDefault`, and lastly by the order they're listed in."""
150        supported = []
151        for endpoint in endpoints:
152            binding = SAMLBindings.from_metadata_binding(endpoint.attrib.get("Binding"))
153            location = endpoint.attrib.get("Location")
154            if not binding or not location:
155                LOGGER.debug(
156                    "Skipping endpoint with unsupported binding",
157                    binding=endpoint.attrib.get("Binding"),
158                    location=location,
159                )
160                continue
161            supported.append((endpoint, binding, location))
162        if not supported:
163            return None, None
164        # sorted() is stable, so endpoints that tie keep the order they're listed in
165        endpoint, binding, location = sorted(
166            supported,
167            key=lambda endpoint: (
168                BINDING_PREFERENCE.index(endpoint[1]),
169                endpoint[0].attrib.get("isDefault", "").lower() != "true",
170            ),
171        )[0]
172        return binding, location
173
174    def check_signature(self, root: etree.Element, keypair: CertificateKeyPair):
175        """If Metadata is signed, check validity of signature"""
176        xmlsec.tree.add_ids(root, ["ID"])
177        signature_nodes = root.xpath("/md:EntityDescriptor/ds:Signature", namespaces=NS_MAP)
178        if len(signature_nodes) != 1:
179            # No Signature
180            return
181
182        signature_node = signature_nodes[0]
183
184        if signature_node is not None:
185            try:
186                ctx = xmlsec.SignatureContext()
187                key = xmlsec.Key.from_memory(
188                    keypair.certificate_data,
189                    xmlsec.constants.KeyDataFormatCertPem,
190                    None,
191                )
192                ctx.key = key
193                ctx.verify(signature_node)
194            except xmlsec.Error as exc:
195                raise ValueError("Failed to verify Metadata signature") from exc
196
197    def parse(self, raw_xml: str) -> ServiceProviderMetadata:
198        """Parse raw XML to ServiceProviderMetadata"""
199        root = lxml_from_string(raw_xml.encode())
200
201        entity_id = root.attrib["entityID"]
202        sp_sso_descriptors = root.findall(f"{{{NS_SAML_METADATA}}}SPSSODescriptor")
203        if len(sp_sso_descriptors) < 1:
204            raise ValueError("no SPSSODescriptor objects found.")
205        # For now we'll only look at the first descriptor.
206        # Even if multiple descriptors exist, we can only configure one
207        descriptor = sp_sso_descriptors[0]
208        auth_n_request_signed = False
209        if "AuthnRequestsSigned" in descriptor.attrib:
210            auth_n_request_signed = descriptor.attrib["AuthnRequestsSigned"].lower() == "true"
211
212        assertion_signed = False
213        if "WantAssertionsSigned" in descriptor.attrib:
214            assertion_signed = descriptor.attrib["WantAssertionsSigned"].lower() == "true"
215
216        acs_services = descriptor.findall(f"{{{NS_SAML_METADATA}}}AssertionConsumerService")
217        if len(acs_services) < 1:
218            raise ValueError("No AssertionConsumerService found.")
219
220        acs_binding, acs_location = self.select_endpoint(acs_services)
221        if not acs_binding:
222            raise ValueError(
223                "No AssertionConsumerService with a supported binding found. "
224                "Only HTTP-POST and HTTP-Redirect are supported."
225            )
226
227        signing_keypair = self.get_signing_cert(root)
228        if signing_keypair:
229            self.check_signature(root, signing_keypair)
230        encryption_keypair = self.get_encryption_cert(root)
231        encryption_algorithm = self.get_encryption_algorithm(root)
232
233        # Use the first NameIDFormat we support, formats we don't know are skipped
234        name_id_policy = SAMLNameIDPolicy.UNSPECIFIED
235        for name_id_format in descriptor.findall(f"{{{NS_SAML_METADATA}}}NameIDFormat"):
236            if name_id_format.text in SAMLNameIDPolicy.values:
237                name_id_policy = SAMLNameIDPolicy(name_id_format.text)
238                break
239            LOGGER.debug("Skipping unsupported NameIDFormat", name_id_format=name_id_format.text)
240
241        # Parse SingleLogoutService (not always present)
242        sls_services = descriptor.findall(f"{{{NS_SAML_METADATA}}}SingleLogoutService")
243        sls_binding, sls_location = self.select_endpoint(sls_services)
244
245        return ServiceProviderMetadata(
246            entity_id=entity_id,
247            acs_binding=acs_binding,
248            acs_location=acs_location,
249            auth_n_request_signed=auth_n_request_signed,
250            assertion_signed=assertion_signed,
251            signing_keypair=signing_keypair,
252            encryption_keypair=encryption_keypair,
253            encryption_algorithm=encryption_algorithm,
254            name_id_policy=name_id_policy,
255            sls_binding=sls_binding,
256            sls_location=sls_location,
257        )
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
BINDING_PREFERENCE = (SAMLBindings.POST, SAMLBindings.REDIRECT)
@dataclass(slots=True)
class ServiceProviderMetadata:
32@dataclass(slots=True)
33class ServiceProviderMetadata:
34    """SP Metadata Dataclass"""
35
36    entity_id: str
37
38    acs_binding: str
39    acs_location: str
40
41    auth_n_request_signed: bool
42    assertion_signed: bool
43    name_id_policy: SAMLNameIDPolicy
44
45    signing_keypair: CertificateKeyPair | None = None
46    encryption_keypair: CertificateKeyPair | None = None
47    encryption_algorithm: str | None = None
48
49    # Single Logout Service (optional)
50    sls_binding: str | None = None
51    sls_location: str | None = None
52
53    @transaction.atomic
54    def to_provider(
55        self, name: str, authorization_flow: Flow, invalidation_flow: Flow
56    ) -> SAMLProvider:
57        """Create a SAMLProvider instance from the details. `name` is required,
58        as depending on the metadata CertificateKeypairs might have to be created."""
59        provider = SAMLProvider.objects.create(
60            name=name, authorization_flow=authorization_flow, invalidation_flow=invalidation_flow
61        )
62        provider.sp_binding = self.acs_binding
63        provider.acs_url = self.acs_location
64        provider.audience = self.entity_id
65        provider.default_name_id_policy = self.name_id_policy
66        # Single Logout Service
67        if self.sls_location:
68            provider.sls_url = self.sls_location
69        if self.sls_binding:
70            provider.sls_binding = self.sls_binding
71        if self.signing_keypair and self.auth_n_request_signed:
72            self.signing_keypair.name = f"Provider {name} - SAML Signing Certificate"
73            self.signing_keypair.save()
74            provider.verification_kp = self.signing_keypair
75        if self.encryption_keypair:
76            self.encryption_keypair.name = f"Provider {name} - SAML Encryption Certificate"
77            self.encryption_keypair.save()
78            provider.encryption_kp = self.encryption_keypair
79            if self.encryption_algorithm:
80                provider.encryption_algorithm = self.encryption_algorithm
81        if self.assertion_signed:
82            provider.signing_kp = CertificateKeyPair.objects.exclude(key_data__iexact="").first()
83        # Set all auto-generated Property-mappings as defaults
84        # They should provide a sane default for most applications:
85        provider.property_mappings.set(SAMLPropertyMapping.objects.exclude(managed__isnull=True))
86        provider.save()
87        return provider

SP Metadata Dataclass

ServiceProviderMetadata( entity_id: str, acs_binding: str, acs_location: str, auth_n_request_signed: bool, assertion_signed: bool, name_id_policy: authentik.sources.saml.models.SAMLNameIDPolicy, signing_keypair: authentik.crypto.models.CertificateKeyPair | None = None, encryption_keypair: authentik.crypto.models.CertificateKeyPair | None = None, encryption_algorithm: str | None = None, sls_binding: str | None = None, sls_location: str | None = None)
entity_id: str
acs_binding: str
acs_location: str
auth_n_request_signed: bool
assertion_signed: bool
encryption_keypair: authentik.crypto.models.CertificateKeyPair | None
encryption_algorithm: str | None
sls_binding: str | None
sls_location: str | None
@transaction.atomic
def to_provider( self, name: str, authorization_flow: authentik.flows.models.Flow, invalidation_flow: authentik.flows.models.Flow) -> authentik.providers.saml.models.SAMLProvider:
53    @transaction.atomic
54    def to_provider(
55        self, name: str, authorization_flow: Flow, invalidation_flow: Flow
56    ) -> SAMLProvider:
57        """Create a SAMLProvider instance from the details. `name` is required,
58        as depending on the metadata CertificateKeypairs might have to be created."""
59        provider = SAMLProvider.objects.create(
60            name=name, authorization_flow=authorization_flow, invalidation_flow=invalidation_flow
61        )
62        provider.sp_binding = self.acs_binding
63        provider.acs_url = self.acs_location
64        provider.audience = self.entity_id
65        provider.default_name_id_policy = self.name_id_policy
66        # Single Logout Service
67        if self.sls_location:
68            provider.sls_url = self.sls_location
69        if self.sls_binding:
70            provider.sls_binding = self.sls_binding
71        if self.signing_keypair and self.auth_n_request_signed:
72            self.signing_keypair.name = f"Provider {name} - SAML Signing Certificate"
73            self.signing_keypair.save()
74            provider.verification_kp = self.signing_keypair
75        if self.encryption_keypair:
76            self.encryption_keypair.name = f"Provider {name} - SAML Encryption Certificate"
77            self.encryption_keypair.save()
78            provider.encryption_kp = self.encryption_keypair
79            if self.encryption_algorithm:
80                provider.encryption_algorithm = self.encryption_algorithm
81        if self.assertion_signed:
82            provider.signing_kp = CertificateKeyPair.objects.exclude(key_data__iexact="").first()
83        # Set all auto-generated Property-mappings as defaults
84        # They should provide a sane default for most applications:
85        provider.property_mappings.set(SAMLPropertyMapping.objects.exclude(managed__isnull=True))
86        provider.save()
87        return provider

Create a SAMLProvider instance from the details. name is required, as depending on the metadata CertificateKeypairs might have to be created.

class ServiceProviderMetadataParser:
 90class ServiceProviderMetadataParser:
 91    """Service-Provider Metadata Parser"""
 92
 93    def get_signing_cert(self, root: etree.Element) -> CertificateKeyPair | None:
 94        """Extract signing X509Certificate from metadata, when given."""
 95        signing_certs = root.xpath(
 96            '//md:SPSSODescriptor/md:KeyDescriptor[@use="signing"]//ds:X509Certificate/text()',
 97            namespaces=NS_MAP,
 98        )
 99        if len(signing_certs) < 1:
100            return None
101        raw_cert = format_cert(signing_certs[0])
102        # sanity check, make sure the certificate is valid.
103        try:
104            load_pem_x509_certificate(raw_cert.encode("utf-8"), default_backend())
105        except InvalidVersion as exc:
106            raise ValueError("Certificate in metadata is not a valid X.509 version") from exc
107        return CertificateKeyPair(
108            certificate_data=raw_cert,
109        )
110
111    def get_encryption_cert(self, root: etree.Element) -> CertificateKeyPair | None:
112        """Extract encryption X509Certificate from metadata, when given."""
113        encryption_certs = root.xpath(
114            '//md:SPSSODescriptor/md:KeyDescriptor[@use="encryption"]//ds:X509Certificate/text()',
115            namespaces=NS_MAP,
116        )
117        if len(encryption_certs) < 1:
118            return None
119        raw_cert = format_cert(encryption_certs[0])
120        # sanity check, make sure the certificate is valid.
121        try:
122            load_pem_x509_certificate(raw_cert.encode("utf-8"), default_backend())
123        except InvalidVersion as exc:
124            raise ValueError("Certificate in metadata is not a valid X.509 version") from exc
125        return CertificateKeyPair(
126            certificate_data=raw_cert,
127        )
128
129    def get_encryption_algorithm(self, root: etree.Element) -> str | None:
130        """Extract the SP's preferred encryption algorithm from its metadata, when given.
131
132        The SAML V2.0 Metadata Profile for Algorithm Support advertises supported
133        algorithms as `<md:EncryptionMethod>` elements in the SP's order of preference.
134        We honor that order and return the first block cipher we support."""
135        algorithms = root.xpath(
136            '//md:SPSSODescriptor/md:KeyDescriptor[@use="encryption"]'
137            "/md:EncryptionMethod/@Algorithm",
138            namespaces=NS_MAP,
139        )
140        for algorithm in algorithms:
141            if algorithm in ENCRYPTION_ALGORITHM_TRANSLATION_MAP:
142                return algorithm
143        return None
144
145    def select_endpoint(
146        self, endpoints: list[etree.Element]
147    ) -> tuple[SAMLBindings, str] | tuple[None, None]:
148        """Select the endpoint authentik should use out of `endpoints`, ignoring any endpoint
149        with a binding we don't support. Endpoints are picked by `BINDING_PREFERENCE` first,
150        then by `isDefault`, and lastly by the order they're listed in."""
151        supported = []
152        for endpoint in endpoints:
153            binding = SAMLBindings.from_metadata_binding(endpoint.attrib.get("Binding"))
154            location = endpoint.attrib.get("Location")
155            if not binding or not location:
156                LOGGER.debug(
157                    "Skipping endpoint with unsupported binding",
158                    binding=endpoint.attrib.get("Binding"),
159                    location=location,
160                )
161                continue
162            supported.append((endpoint, binding, location))
163        if not supported:
164            return None, None
165        # sorted() is stable, so endpoints that tie keep the order they're listed in
166        endpoint, binding, location = sorted(
167            supported,
168            key=lambda endpoint: (
169                BINDING_PREFERENCE.index(endpoint[1]),
170                endpoint[0].attrib.get("isDefault", "").lower() != "true",
171            ),
172        )[0]
173        return binding, location
174
175    def check_signature(self, root: etree.Element, keypair: CertificateKeyPair):
176        """If Metadata is signed, check validity of signature"""
177        xmlsec.tree.add_ids(root, ["ID"])
178        signature_nodes = root.xpath("/md:EntityDescriptor/ds:Signature", namespaces=NS_MAP)
179        if len(signature_nodes) != 1:
180            # No Signature
181            return
182
183        signature_node = signature_nodes[0]
184
185        if signature_node is not None:
186            try:
187                ctx = xmlsec.SignatureContext()
188                key = xmlsec.Key.from_memory(
189                    keypair.certificate_data,
190                    xmlsec.constants.KeyDataFormatCertPem,
191                    None,
192                )
193                ctx.key = key
194                ctx.verify(signature_node)
195            except xmlsec.Error as exc:
196                raise ValueError("Failed to verify Metadata signature") from exc
197
198    def parse(self, raw_xml: str) -> ServiceProviderMetadata:
199        """Parse raw XML to ServiceProviderMetadata"""
200        root = lxml_from_string(raw_xml.encode())
201
202        entity_id = root.attrib["entityID"]
203        sp_sso_descriptors = root.findall(f"{{{NS_SAML_METADATA}}}SPSSODescriptor")
204        if len(sp_sso_descriptors) < 1:
205            raise ValueError("no SPSSODescriptor objects found.")
206        # For now we'll only look at the first descriptor.
207        # Even if multiple descriptors exist, we can only configure one
208        descriptor = sp_sso_descriptors[0]
209        auth_n_request_signed = False
210        if "AuthnRequestsSigned" in descriptor.attrib:
211            auth_n_request_signed = descriptor.attrib["AuthnRequestsSigned"].lower() == "true"
212
213        assertion_signed = False
214        if "WantAssertionsSigned" in descriptor.attrib:
215            assertion_signed = descriptor.attrib["WantAssertionsSigned"].lower() == "true"
216
217        acs_services = descriptor.findall(f"{{{NS_SAML_METADATA}}}AssertionConsumerService")
218        if len(acs_services) < 1:
219            raise ValueError("No AssertionConsumerService found.")
220
221        acs_binding, acs_location = self.select_endpoint(acs_services)
222        if not acs_binding:
223            raise ValueError(
224                "No AssertionConsumerService with a supported binding found. "
225                "Only HTTP-POST and HTTP-Redirect are supported."
226            )
227
228        signing_keypair = self.get_signing_cert(root)
229        if signing_keypair:
230            self.check_signature(root, signing_keypair)
231        encryption_keypair = self.get_encryption_cert(root)
232        encryption_algorithm = self.get_encryption_algorithm(root)
233
234        # Use the first NameIDFormat we support, formats we don't know are skipped
235        name_id_policy = SAMLNameIDPolicy.UNSPECIFIED
236        for name_id_format in descriptor.findall(f"{{{NS_SAML_METADATA}}}NameIDFormat"):
237            if name_id_format.text in SAMLNameIDPolicy.values:
238                name_id_policy = SAMLNameIDPolicy(name_id_format.text)
239                break
240            LOGGER.debug("Skipping unsupported NameIDFormat", name_id_format=name_id_format.text)
241
242        # Parse SingleLogoutService (not always present)
243        sls_services = descriptor.findall(f"{{{NS_SAML_METADATA}}}SingleLogoutService")
244        sls_binding, sls_location = self.select_endpoint(sls_services)
245
246        return ServiceProviderMetadata(
247            entity_id=entity_id,
248            acs_binding=acs_binding,
249            acs_location=acs_location,
250            auth_n_request_signed=auth_n_request_signed,
251            assertion_signed=assertion_signed,
252            signing_keypair=signing_keypair,
253            encryption_keypair=encryption_keypair,
254            encryption_algorithm=encryption_algorithm,
255            name_id_policy=name_id_policy,
256            sls_binding=sls_binding,
257            sls_location=sls_location,
258        )

Service-Provider Metadata Parser

def get_signing_cert( self, root: lxml.etree.Element) -> authentik.crypto.models.CertificateKeyPair | None:
 93    def get_signing_cert(self, root: etree.Element) -> CertificateKeyPair | None:
 94        """Extract signing X509Certificate from metadata, when given."""
 95        signing_certs = root.xpath(
 96            '//md:SPSSODescriptor/md:KeyDescriptor[@use="signing"]//ds:X509Certificate/text()',
 97            namespaces=NS_MAP,
 98        )
 99        if len(signing_certs) < 1:
100            return None
101        raw_cert = format_cert(signing_certs[0])
102        # sanity check, make sure the certificate is valid.
103        try:
104            load_pem_x509_certificate(raw_cert.encode("utf-8"), default_backend())
105        except InvalidVersion as exc:
106            raise ValueError("Certificate in metadata is not a valid X.509 version") from exc
107        return CertificateKeyPair(
108            certificate_data=raw_cert,
109        )

Extract signing X509Certificate from metadata, when given.

def get_encryption_cert( self, root: lxml.etree.Element) -> authentik.crypto.models.CertificateKeyPair | None:
111    def get_encryption_cert(self, root: etree.Element) -> CertificateKeyPair | None:
112        """Extract encryption X509Certificate from metadata, when given."""
113        encryption_certs = root.xpath(
114            '//md:SPSSODescriptor/md:KeyDescriptor[@use="encryption"]//ds:X509Certificate/text()',
115            namespaces=NS_MAP,
116        )
117        if len(encryption_certs) < 1:
118            return None
119        raw_cert = format_cert(encryption_certs[0])
120        # sanity check, make sure the certificate is valid.
121        try:
122            load_pem_x509_certificate(raw_cert.encode("utf-8"), default_backend())
123        except InvalidVersion as exc:
124            raise ValueError("Certificate in metadata is not a valid X.509 version") from exc
125        return CertificateKeyPair(
126            certificate_data=raw_cert,
127        )

Extract encryption X509Certificate from metadata, when given.

def get_encryption_algorithm(self, root: lxml.etree.Element) -> str | None:
129    def get_encryption_algorithm(self, root: etree.Element) -> str | None:
130        """Extract the SP's preferred encryption algorithm from its metadata, when given.
131
132        The SAML V2.0 Metadata Profile for Algorithm Support advertises supported
133        algorithms as `<md:EncryptionMethod>` elements in the SP's order of preference.
134        We honor that order and return the first block cipher we support."""
135        algorithms = root.xpath(
136            '//md:SPSSODescriptor/md:KeyDescriptor[@use="encryption"]'
137            "/md:EncryptionMethod/@Algorithm",
138            namespaces=NS_MAP,
139        )
140        for algorithm in algorithms:
141            if algorithm in ENCRYPTION_ALGORITHM_TRANSLATION_MAP:
142                return algorithm
143        return None

Extract the SP's preferred encryption algorithm from its metadata, when given.

The SAML V2.0 Metadata Profile for Algorithm Support advertises supported algorithms as <md:EncryptionMethod> elements in the SP's order of preference. We honor that order and return the first block cipher we support.

def select_endpoint( self, endpoints: list[lxml.etree.Element]) -> tuple[authentik.providers.saml.models.SAMLBindings, str] | tuple[None, None]:
145    def select_endpoint(
146        self, endpoints: list[etree.Element]
147    ) -> tuple[SAMLBindings, str] | tuple[None, None]:
148        """Select the endpoint authentik should use out of `endpoints`, ignoring any endpoint
149        with a binding we don't support. Endpoints are picked by `BINDING_PREFERENCE` first,
150        then by `isDefault`, and lastly by the order they're listed in."""
151        supported = []
152        for endpoint in endpoints:
153            binding = SAMLBindings.from_metadata_binding(endpoint.attrib.get("Binding"))
154            location = endpoint.attrib.get("Location")
155            if not binding or not location:
156                LOGGER.debug(
157                    "Skipping endpoint with unsupported binding",
158                    binding=endpoint.attrib.get("Binding"),
159                    location=location,
160                )
161                continue
162            supported.append((endpoint, binding, location))
163        if not supported:
164            return None, None
165        # sorted() is stable, so endpoints that tie keep the order they're listed in
166        endpoint, binding, location = sorted(
167            supported,
168            key=lambda endpoint: (
169                BINDING_PREFERENCE.index(endpoint[1]),
170                endpoint[0].attrib.get("isDefault", "").lower() != "true",
171            ),
172        )[0]
173        return binding, location

Select the endpoint authentik should use out of endpoints, ignoring any endpoint with a binding we don't support. Endpoints are picked by BINDING_PREFERENCE first, then by isDefault, and lastly by the order they're listed in.

def check_signature( self, root: lxml.etree.Element, keypair: authentik.crypto.models.CertificateKeyPair):
175    def check_signature(self, root: etree.Element, keypair: CertificateKeyPair):
176        """If Metadata is signed, check validity of signature"""
177        xmlsec.tree.add_ids(root, ["ID"])
178        signature_nodes = root.xpath("/md:EntityDescriptor/ds:Signature", namespaces=NS_MAP)
179        if len(signature_nodes) != 1:
180            # No Signature
181            return
182
183        signature_node = signature_nodes[0]
184
185        if signature_node is not None:
186            try:
187                ctx = xmlsec.SignatureContext()
188                key = xmlsec.Key.from_memory(
189                    keypair.certificate_data,
190                    xmlsec.constants.KeyDataFormatCertPem,
191                    None,
192                )
193                ctx.key = key
194                ctx.verify(signature_node)
195            except xmlsec.Error as exc:
196                raise ValueError("Failed to verify Metadata signature") from exc

If Metadata is signed, check validity of signature

def parse( self, raw_xml: str) -> ServiceProviderMetadata:
198    def parse(self, raw_xml: str) -> ServiceProviderMetadata:
199        """Parse raw XML to ServiceProviderMetadata"""
200        root = lxml_from_string(raw_xml.encode())
201
202        entity_id = root.attrib["entityID"]
203        sp_sso_descriptors = root.findall(f"{{{NS_SAML_METADATA}}}SPSSODescriptor")
204        if len(sp_sso_descriptors) < 1:
205            raise ValueError("no SPSSODescriptor objects found.")
206        # For now we'll only look at the first descriptor.
207        # Even if multiple descriptors exist, we can only configure one
208        descriptor = sp_sso_descriptors[0]
209        auth_n_request_signed = False
210        if "AuthnRequestsSigned" in descriptor.attrib:
211            auth_n_request_signed = descriptor.attrib["AuthnRequestsSigned"].lower() == "true"
212
213        assertion_signed = False
214        if "WantAssertionsSigned" in descriptor.attrib:
215            assertion_signed = descriptor.attrib["WantAssertionsSigned"].lower() == "true"
216
217        acs_services = descriptor.findall(f"{{{NS_SAML_METADATA}}}AssertionConsumerService")
218        if len(acs_services) < 1:
219            raise ValueError("No AssertionConsumerService found.")
220
221        acs_binding, acs_location = self.select_endpoint(acs_services)
222        if not acs_binding:
223            raise ValueError(
224                "No AssertionConsumerService with a supported binding found. "
225                "Only HTTP-POST and HTTP-Redirect are supported."
226            )
227
228        signing_keypair = self.get_signing_cert(root)
229        if signing_keypair:
230            self.check_signature(root, signing_keypair)
231        encryption_keypair = self.get_encryption_cert(root)
232        encryption_algorithm = self.get_encryption_algorithm(root)
233
234        # Use the first NameIDFormat we support, formats we don't know are skipped
235        name_id_policy = SAMLNameIDPolicy.UNSPECIFIED
236        for name_id_format in descriptor.findall(f"{{{NS_SAML_METADATA}}}NameIDFormat"):
237            if name_id_format.text in SAMLNameIDPolicy.values:
238                name_id_policy = SAMLNameIDPolicy(name_id_format.text)
239                break
240            LOGGER.debug("Skipping unsupported NameIDFormat", name_id_format=name_id_format.text)
241
242        # Parse SingleLogoutService (not always present)
243        sls_services = descriptor.findall(f"{{{NS_SAML_METADATA}}}SingleLogoutService")
244        sls_binding, sls_location = self.select_endpoint(sls_services)
245
246        return ServiceProviderMetadata(
247            entity_id=entity_id,
248            acs_binding=acs_binding,
249            acs_location=acs_location,
250            auth_n_request_signed=auth_n_request_signed,
251            assertion_signed=assertion_signed,
252            signing_keypair=signing_keypair,
253            encryption_keypair=encryption_keypair,
254            encryption_algorithm=encryption_algorithm,
255            name_id_policy=name_id_policy,
256            sls_binding=sls_binding,
257            sls_location=sls_location,
258        )

Parse raw XML to ServiceProviderMetadata