authentik.sources.saml.processors.request

SAML AuthnRequest Processor

  1"""SAML AuthnRequest Processor"""
  2
  3from base64 import b64encode
  4from urllib.parse import quote_plus
  5
  6import xmlsec
  7from django.http import HttpRequest
  8from django.urls import reverse
  9from lxml import etree  # nosec
 10from lxml.etree import Element  # nosec
 11
 12from authentik.common.saml.constants import (
 13    DIGEST_ALGORITHM_TRANSLATION_MAP,
 14    NS_MAP,
 15    NS_SAML_ASSERTION,
 16    NS_SAML_PROTOCOL,
 17    SAML_BINDING_POST,
 18    SIGN_ALGORITHM_TRANSFORM_MAP,
 19)
 20from authentik.lib.xml import remove_xml_newlines
 21from authentik.providers.saml.utils import get_random_id
 22from authentik.providers.saml.utils.encoding import deflate_and_base64_encode
 23from authentik.providers.saml.utils.time import get_time_string
 24from authentik.sources.saml.models import SAMLBindingTypes, SAMLSource
 25
 26SESSION_KEY_REQUEST_ID = "authentik/sources/saml/request_id"
 27
 28
 29class RequestProcessor:
 30    """SAML AuthnRequest Processor"""
 31
 32    source: SAMLSource
 33    http_request: HttpRequest
 34
 35    relay_state: str
 36
 37    request_id: str
 38    issue_instant: str
 39
 40    def __init__(self, source: SAMLSource, request: HttpRequest, relay_state: str):
 41        self.source = source
 42        self.http_request = request
 43        self.relay_state = relay_state
 44        self.request_id = get_random_id()
 45        self.http_request.session[SESSION_KEY_REQUEST_ID] = self.request_id
 46        self.issue_instant = get_time_string()
 47
 48    def get_issuer(self) -> Element:
 49        """Get Issuer Element"""
 50        issuer = Element(f"{{{NS_SAML_ASSERTION}}}Issuer")
 51        issuer.text = self.source.get_issuer(self.http_request)
 52        return issuer
 53
 54    def get_name_id_policy(self) -> Element:
 55        """Get NameID Policy Element"""
 56        name_id_policy = Element(f"{{{NS_SAML_PROTOCOL}}}NameIDPolicy")
 57        name_id_policy.attrib["Format"] = self.source.name_id_policy
 58        return name_id_policy
 59
 60    def get_auth_n(self) -> Element:
 61        """Get full AuthnRequest"""
 62        auth_n_request = Element(f"{{{NS_SAML_PROTOCOL}}}AuthnRequest", nsmap=NS_MAP)
 63        auth_n_request.attrib["AssertionConsumerServiceURL"] = self.http_request.build_absolute_uri(
 64            reverse("authentik_sources_saml:acs", kwargs={"source_slug": self.source.slug})
 65        )
 66        auth_n_request.attrib["Destination"] = self.source.sso_url
 67        auth_n_request.attrib["ID"] = self.request_id
 68        auth_n_request.attrib["IssueInstant"] = self.issue_instant
 69        auth_n_request.attrib["ProtocolBinding"] = SAML_BINDING_POST
 70        auth_n_request.attrib["Version"] = "2.0"
 71        if self.source.force_authn:
 72            auth_n_request.attrib["ForceAuthn"] = "true"
 73        # Create issuer object
 74        auth_n_request.append(self.get_issuer())
 75
 76        if self.source.signing_kp and self.source.binding_type != SAMLBindingTypes.REDIRECT:
 77            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
 78                self.source.signature_algorithm, xmlsec.constants.TransformRsaSha1
 79            )
 80            signature = xmlsec.template.create(
 81                auth_n_request,
 82                xmlsec.constants.TransformExclC14N,
 83                sign_algorithm_transform,
 84                ns=xmlsec.constants.DSigNs,
 85            )
 86            auth_n_request.append(signature)
 87
 88        # Create NameID Policy Object
 89        auth_n_request.append(self.get_name_id_policy())
 90        return auth_n_request
 91
 92    def build_auth_n(self) -> str:
 93        """Get Signed string representation of AuthN Request
 94        (used for POST Bindings)"""
 95        auth_n_request = self.get_auth_n()
 96
 97        if self.source.signing_kp and self.source.binding_type != SAMLBindingTypes.REDIRECT:
 98            xmlsec.tree.add_ids(auth_n_request, ["ID"])
 99
100            ctx = xmlsec.SignatureContext()
101
102            key = xmlsec.Key.from_memory(
103                self.source.signing_kp.key_data, xmlsec.constants.KeyDataFormatPem, None
104            )
105            key.load_cert_from_memory(
106                self.source.signing_kp.certificate_data,
107                xmlsec.constants.KeyDataFormatCertPem,
108            )
109            ctx.key = key
110
111            digest_algorithm_transform = DIGEST_ALGORITHM_TRANSLATION_MAP.get(
112                self.source.digest_algorithm, xmlsec.constants.TransformSha1
113            )
114
115            signature_node = xmlsec.tree.find_node(auth_n_request, xmlsec.constants.NodeSignature)
116
117            ref = xmlsec.template.add_reference(
118                signature_node,
119                digest_algorithm_transform,
120                uri="#" + auth_n_request.attrib["ID"],
121            )
122            xmlsec.template.add_transform(ref, xmlsec.constants.TransformEnveloped)
123            xmlsec.template.add_transform(ref, xmlsec.constants.TransformExclC14N)
124            key_info = xmlsec.template.ensure_key_info(signature_node)
125            xmlsec.template.add_x509_data(key_info)
126
127            ctx.sign(remove_xml_newlines(auth_n_request, signature_node))
128
129        return etree.tostring(auth_n_request).decode()
130
131    def build_auth_n_detached(self) -> dict[str, str]:
132        """Get Dict AuthN Request for Redirect bindings, with detached
133        Signature. See https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf"""
134        auth_n_request = self.get_auth_n()
135
136        saml_request = deflate_and_base64_encode(etree.tostring(auth_n_request).decode())
137
138        response_dict = {
139            "SAMLRequest": saml_request,
140        }
141
142        if self.relay_state != "":
143            response_dict["RelayState"] = self.relay_state
144
145        if self.source.signing_kp:
146            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
147                self.source.signature_algorithm, xmlsec.constants.TransformRsaSha1
148            )
149
150            # Create the full querystring in the correct order to be signed
151            querystring = f"SAMLRequest={quote_plus(saml_request)}&"
152            if "RelayState" in response_dict:
153                querystring += f"RelayState={quote_plus(response_dict['RelayState'])}&"
154            querystring += f"SigAlg={quote_plus(self.source.signature_algorithm)}"
155
156            ctx = xmlsec.SignatureContext()
157
158            key = xmlsec.Key.from_memory(
159                self.source.signing_kp.key_data, xmlsec.constants.KeyDataFormatPem, None
160            )
161            key.load_cert_from_memory(
162                self.source.signing_kp.certificate_data,
163                xmlsec.constants.KeyDataFormatPem,
164            )
165            ctx.key = key
166
167            signature = ctx.sign_binary(querystring.encode("utf-8"), sign_algorithm_transform)
168            response_dict["Signature"] = b64encode(signature).decode()
169            response_dict["SigAlg"] = self.source.signature_algorithm
170
171        return response_dict
SESSION_KEY_REQUEST_ID = 'authentik/sources/saml/request_id'
class RequestProcessor:
 30class RequestProcessor:
 31    """SAML AuthnRequest Processor"""
 32
 33    source: SAMLSource
 34    http_request: HttpRequest
 35
 36    relay_state: str
 37
 38    request_id: str
 39    issue_instant: str
 40
 41    def __init__(self, source: SAMLSource, request: HttpRequest, relay_state: str):
 42        self.source = source
 43        self.http_request = request
 44        self.relay_state = relay_state
 45        self.request_id = get_random_id()
 46        self.http_request.session[SESSION_KEY_REQUEST_ID] = self.request_id
 47        self.issue_instant = get_time_string()
 48
 49    def get_issuer(self) -> Element:
 50        """Get Issuer Element"""
 51        issuer = Element(f"{{{NS_SAML_ASSERTION}}}Issuer")
 52        issuer.text = self.source.get_issuer(self.http_request)
 53        return issuer
 54
 55    def get_name_id_policy(self) -> Element:
 56        """Get NameID Policy Element"""
 57        name_id_policy = Element(f"{{{NS_SAML_PROTOCOL}}}NameIDPolicy")
 58        name_id_policy.attrib["Format"] = self.source.name_id_policy
 59        return name_id_policy
 60
 61    def get_auth_n(self) -> Element:
 62        """Get full AuthnRequest"""
 63        auth_n_request = Element(f"{{{NS_SAML_PROTOCOL}}}AuthnRequest", nsmap=NS_MAP)
 64        auth_n_request.attrib["AssertionConsumerServiceURL"] = self.http_request.build_absolute_uri(
 65            reverse("authentik_sources_saml:acs", kwargs={"source_slug": self.source.slug})
 66        )
 67        auth_n_request.attrib["Destination"] = self.source.sso_url
 68        auth_n_request.attrib["ID"] = self.request_id
 69        auth_n_request.attrib["IssueInstant"] = self.issue_instant
 70        auth_n_request.attrib["ProtocolBinding"] = SAML_BINDING_POST
 71        auth_n_request.attrib["Version"] = "2.0"
 72        if self.source.force_authn:
 73            auth_n_request.attrib["ForceAuthn"] = "true"
 74        # Create issuer object
 75        auth_n_request.append(self.get_issuer())
 76
 77        if self.source.signing_kp and self.source.binding_type != SAMLBindingTypes.REDIRECT:
 78            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
 79                self.source.signature_algorithm, xmlsec.constants.TransformRsaSha1
 80            )
 81            signature = xmlsec.template.create(
 82                auth_n_request,
 83                xmlsec.constants.TransformExclC14N,
 84                sign_algorithm_transform,
 85                ns=xmlsec.constants.DSigNs,
 86            )
 87            auth_n_request.append(signature)
 88
 89        # Create NameID Policy Object
 90        auth_n_request.append(self.get_name_id_policy())
 91        return auth_n_request
 92
 93    def build_auth_n(self) -> str:
 94        """Get Signed string representation of AuthN Request
 95        (used for POST Bindings)"""
 96        auth_n_request = self.get_auth_n()
 97
 98        if self.source.signing_kp and self.source.binding_type != SAMLBindingTypes.REDIRECT:
 99            xmlsec.tree.add_ids(auth_n_request, ["ID"])
100
101            ctx = xmlsec.SignatureContext()
102
103            key = xmlsec.Key.from_memory(
104                self.source.signing_kp.key_data, xmlsec.constants.KeyDataFormatPem, None
105            )
106            key.load_cert_from_memory(
107                self.source.signing_kp.certificate_data,
108                xmlsec.constants.KeyDataFormatCertPem,
109            )
110            ctx.key = key
111
112            digest_algorithm_transform = DIGEST_ALGORITHM_TRANSLATION_MAP.get(
113                self.source.digest_algorithm, xmlsec.constants.TransformSha1
114            )
115
116            signature_node = xmlsec.tree.find_node(auth_n_request, xmlsec.constants.NodeSignature)
117
118            ref = xmlsec.template.add_reference(
119                signature_node,
120                digest_algorithm_transform,
121                uri="#" + auth_n_request.attrib["ID"],
122            )
123            xmlsec.template.add_transform(ref, xmlsec.constants.TransformEnveloped)
124            xmlsec.template.add_transform(ref, xmlsec.constants.TransformExclC14N)
125            key_info = xmlsec.template.ensure_key_info(signature_node)
126            xmlsec.template.add_x509_data(key_info)
127
128            ctx.sign(remove_xml_newlines(auth_n_request, signature_node))
129
130        return etree.tostring(auth_n_request).decode()
131
132    def build_auth_n_detached(self) -> dict[str, str]:
133        """Get Dict AuthN Request for Redirect bindings, with detached
134        Signature. See https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf"""
135        auth_n_request = self.get_auth_n()
136
137        saml_request = deflate_and_base64_encode(etree.tostring(auth_n_request).decode())
138
139        response_dict = {
140            "SAMLRequest": saml_request,
141        }
142
143        if self.relay_state != "":
144            response_dict["RelayState"] = self.relay_state
145
146        if self.source.signing_kp:
147            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
148                self.source.signature_algorithm, xmlsec.constants.TransformRsaSha1
149            )
150
151            # Create the full querystring in the correct order to be signed
152            querystring = f"SAMLRequest={quote_plus(saml_request)}&"
153            if "RelayState" in response_dict:
154                querystring += f"RelayState={quote_plus(response_dict['RelayState'])}&"
155            querystring += f"SigAlg={quote_plus(self.source.signature_algorithm)}"
156
157            ctx = xmlsec.SignatureContext()
158
159            key = xmlsec.Key.from_memory(
160                self.source.signing_kp.key_data, xmlsec.constants.KeyDataFormatPem, None
161            )
162            key.load_cert_from_memory(
163                self.source.signing_kp.certificate_data,
164                xmlsec.constants.KeyDataFormatPem,
165            )
166            ctx.key = key
167
168            signature = ctx.sign_binary(querystring.encode("utf-8"), sign_algorithm_transform)
169            response_dict["Signature"] = b64encode(signature).decode()
170            response_dict["SigAlg"] = self.source.signature_algorithm
171
172        return response_dict

SAML AuthnRequest Processor

RequestProcessor( source: authentik.sources.saml.models.SAMLSource, request: django.http.request.HttpRequest, relay_state: str)
41    def __init__(self, source: SAMLSource, request: HttpRequest, relay_state: str):
42        self.source = source
43        self.http_request = request
44        self.relay_state = relay_state
45        self.request_id = get_random_id()
46        self.http_request.session[SESSION_KEY_REQUEST_ID] = self.request_id
47        self.issue_instant = get_time_string()
http_request: django.http.request.HttpRequest
relay_state: str
request_id: str
issue_instant: str
def get_issuer(self) -> lxml.etree.Element:
49    def get_issuer(self) -> Element:
50        """Get Issuer Element"""
51        issuer = Element(f"{{{NS_SAML_ASSERTION}}}Issuer")
52        issuer.text = self.source.get_issuer(self.http_request)
53        return issuer

Get Issuer Element

def get_name_id_policy(self) -> lxml.etree.Element:
55    def get_name_id_policy(self) -> Element:
56        """Get NameID Policy Element"""
57        name_id_policy = Element(f"{{{NS_SAML_PROTOCOL}}}NameIDPolicy")
58        name_id_policy.attrib["Format"] = self.source.name_id_policy
59        return name_id_policy

Get NameID Policy Element

def get_auth_n(self) -> lxml.etree.Element:
61    def get_auth_n(self) -> Element:
62        """Get full AuthnRequest"""
63        auth_n_request = Element(f"{{{NS_SAML_PROTOCOL}}}AuthnRequest", nsmap=NS_MAP)
64        auth_n_request.attrib["AssertionConsumerServiceURL"] = self.http_request.build_absolute_uri(
65            reverse("authentik_sources_saml:acs", kwargs={"source_slug": self.source.slug})
66        )
67        auth_n_request.attrib["Destination"] = self.source.sso_url
68        auth_n_request.attrib["ID"] = self.request_id
69        auth_n_request.attrib["IssueInstant"] = self.issue_instant
70        auth_n_request.attrib["ProtocolBinding"] = SAML_BINDING_POST
71        auth_n_request.attrib["Version"] = "2.0"
72        if self.source.force_authn:
73            auth_n_request.attrib["ForceAuthn"] = "true"
74        # Create issuer object
75        auth_n_request.append(self.get_issuer())
76
77        if self.source.signing_kp and self.source.binding_type != SAMLBindingTypes.REDIRECT:
78            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
79                self.source.signature_algorithm, xmlsec.constants.TransformRsaSha1
80            )
81            signature = xmlsec.template.create(
82                auth_n_request,
83                xmlsec.constants.TransformExclC14N,
84                sign_algorithm_transform,
85                ns=xmlsec.constants.DSigNs,
86            )
87            auth_n_request.append(signature)
88
89        # Create NameID Policy Object
90        auth_n_request.append(self.get_name_id_policy())
91        return auth_n_request

Get full AuthnRequest

def build_auth_n(self) -> str:
 93    def build_auth_n(self) -> str:
 94        """Get Signed string representation of AuthN Request
 95        (used for POST Bindings)"""
 96        auth_n_request = self.get_auth_n()
 97
 98        if self.source.signing_kp and self.source.binding_type != SAMLBindingTypes.REDIRECT:
 99            xmlsec.tree.add_ids(auth_n_request, ["ID"])
100
101            ctx = xmlsec.SignatureContext()
102
103            key = xmlsec.Key.from_memory(
104                self.source.signing_kp.key_data, xmlsec.constants.KeyDataFormatPem, None
105            )
106            key.load_cert_from_memory(
107                self.source.signing_kp.certificate_data,
108                xmlsec.constants.KeyDataFormatCertPem,
109            )
110            ctx.key = key
111
112            digest_algorithm_transform = DIGEST_ALGORITHM_TRANSLATION_MAP.get(
113                self.source.digest_algorithm, xmlsec.constants.TransformSha1
114            )
115
116            signature_node = xmlsec.tree.find_node(auth_n_request, xmlsec.constants.NodeSignature)
117
118            ref = xmlsec.template.add_reference(
119                signature_node,
120                digest_algorithm_transform,
121                uri="#" + auth_n_request.attrib["ID"],
122            )
123            xmlsec.template.add_transform(ref, xmlsec.constants.TransformEnveloped)
124            xmlsec.template.add_transform(ref, xmlsec.constants.TransformExclC14N)
125            key_info = xmlsec.template.ensure_key_info(signature_node)
126            xmlsec.template.add_x509_data(key_info)
127
128            ctx.sign(remove_xml_newlines(auth_n_request, signature_node))
129
130        return etree.tostring(auth_n_request).decode()

Get Signed string representation of AuthN Request (used for POST Bindings)

def build_auth_n_detached(self) -> dict[str, str]:
132    def build_auth_n_detached(self) -> dict[str, str]:
133        """Get Dict AuthN Request for Redirect bindings, with detached
134        Signature. See https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf"""
135        auth_n_request = self.get_auth_n()
136
137        saml_request = deflate_and_base64_encode(etree.tostring(auth_n_request).decode())
138
139        response_dict = {
140            "SAMLRequest": saml_request,
141        }
142
143        if self.relay_state != "":
144            response_dict["RelayState"] = self.relay_state
145
146        if self.source.signing_kp:
147            sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
148                self.source.signature_algorithm, xmlsec.constants.TransformRsaSha1
149            )
150
151            # Create the full querystring in the correct order to be signed
152            querystring = f"SAMLRequest={quote_plus(saml_request)}&"
153            if "RelayState" in response_dict:
154                querystring += f"RelayState={quote_plus(response_dict['RelayState'])}&"
155            querystring += f"SigAlg={quote_plus(self.source.signature_algorithm)}"
156
157            ctx = xmlsec.SignatureContext()
158
159            key = xmlsec.Key.from_memory(
160                self.source.signing_kp.key_data, xmlsec.constants.KeyDataFormatPem, None
161            )
162            key.load_cert_from_memory(
163                self.source.signing_kp.certificate_data,
164                xmlsec.constants.KeyDataFormatPem,
165            )
166            ctx.key = key
167
168            signature = ctx.sign_binary(querystring.encode("utf-8"), sign_algorithm_transform)
169            response_dict["Signature"] = b64encode(signature).decode()
170            response_dict["SigAlg"] = self.source.signature_algorithm
171
172        return response_dict

Get Dict AuthN Request for Redirect bindings, with detached Signature. See https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf