authentik.enterprise.stages.mtls.stage

  1from binascii import hexlify
  2from enum import IntFlag, auto
  3from urllib.parse import unquote_plus
  4
  5from cryptography.exceptions import InvalidSignature
  6from cryptography.hazmat.primitives import hashes
  7from cryptography.x509 import (
  8    Certificate,
  9    ExtensionNotFound,
 10    NameOID,
 11    ObjectIdentifier,
 12    RFC822Name,
 13    SubjectAlternativeName,
 14    UnsupportedGeneralNameType,
 15    load_pem_x509_certificate,
 16)
 17from cryptography.x509.general_name import GeneralName
 18from cryptography.x509.verification import PolicyBuilder, Store, VerificationError
 19from django.utils.timezone import now
 20from django.utils.translation import gettext_lazy as _
 21from rest_framework.exceptions import PermissionDenied
 22
 23from authentik.brands.models import Brand
 24from authentik.core.models import User
 25from authentik.crypto.models import CertificateKeyPair, fingerprint_sha256, format_cert
 26from authentik.endpoints.models import StageMode
 27from authentik.enterprise.stages.mtls.models import (
 28    CertAttributes,
 29    MutualTLSStage,
 30    UserAttributes,
 31)
 32from authentik.flows.models import FlowDesignation
 33from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER
 34from authentik.flows.stage import ChallengeStageView
 35from authentik.lib.utils.reflection import all_subclasses
 36from authentik.root.middleware import ClientIPMiddleware
 37from authentik.stages.password.stage import PLAN_CONTEXT_METHOD, PLAN_CONTEXT_METHOD_ARGS
 38from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
 39
 40# All of these headers must only be accepted from "trusted" reverse proxies
 41# See internal/web/proxy.go:39
 42HEADER_PROXY_FORWARDED = "X-Forwarded-Client-Cert"
 43HEADER_NGINX_FORWARDED = "SSL-Client-Cert"
 44HEADER_TRAEFIK_FORWARDED = "X-Forwarded-TLS-Client-Cert"
 45HEADER_OUTPOST_FORWARDED = "X-Authentik-Outpost-Certificate"
 46
 47
 48PLAN_CONTEXT_CERTIFICATE = "certificate"
 49
 50
 51class ParseOptions(IntFlag):
 52
 53    # URL unquote the string
 54    UNQUOTE = auto()
 55    # Re-add PEM Header & footer, and chunk it into 64 character lines
 56    FORMAT = auto()
 57
 58
 59class MTLSStageView(ChallengeStageView):
 60
 61    def __parse_single_cert(self, raw: str | None, *options: ParseOptions) -> list[Certificate]:
 62        """Helper to parse a single certificate"""
 63        if not raw:
 64            return []
 65        for opt in options:
 66            match opt:
 67                case ParseOptions.FORMAT:
 68                    raw = format_cert(raw)
 69                case ParseOptions.UNQUOTE:
 70                    raw = unquote_plus(raw)
 71        try:
 72            cert = load_pem_x509_certificate(raw.encode())
 73            return [cert]
 74        except ValueError as exc:
 75            self.logger.info("Failed to parse certificate", exc=exc)
 76            return []
 77
 78    def _parse_cert_xfcc(self) -> list[Certificate]:
 79        """Parse certificates in the format given to us in
 80        the format of the authentik router/envoy"""
 81        # https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers#x-forwarded-client-cert
 82        xfcc_raw = self.request.headers.get(HEADER_PROXY_FORWARDED)
 83        if not xfcc_raw:
 84            return []
 85        certs = []
 86        for r_cert in xfcc_raw.split(","):
 87            el = r_cert.split(";")
 88            raw_cert = {k.split("=")[0]: k.split("=")[1] for k in el}
 89            if "Cert" not in raw_cert:
 90                continue
 91            certs.extend(self.__parse_single_cert(raw_cert["Cert"], ParseOptions.UNQUOTE))
 92        return certs
 93
 94    def _parse_cert_nginx(self) -> list[Certificate]:
 95        """Parse certificates in the format nginx-ingress gives to us"""
 96        # https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#client-certificate-authentication
 97        # https://github.com/kubernetes/ingress-nginx/blob/78f593b24494a0674b362faf551079f06d71b5a9/rootfs/etc/nginx/template/nginx.tmpl#L1096
 98        sslcc_raw = self.request.headers.get(HEADER_NGINX_FORWARDED)
 99        return self.__parse_single_cert(sslcc_raw, ParseOptions.UNQUOTE)
100
101    def _parse_cert_traefik(self) -> list[Certificate]:
102        """Parse certificates in the format traefik gives to us"""
103        # https://doc.traefik.io/traefik/reference/routing-configuration/http/middlewares/passtlsclientcert/
104        ftcc_raw = self.request.headers.get(HEADER_TRAEFIK_FORWARDED)
105        if not ftcc_raw:
106            return []
107        certs = []
108        for cert in ftcc_raw.split(","):
109            certs.extend(self.__parse_single_cert(cert, ParseOptions.FORMAT))
110        return certs
111
112    def _parse_cert_outpost(self) -> list[Certificate]:
113        """Parse certificates in the format outposts give to us. Also authenticates
114        the outpost to ensure it has the permission to do so"""
115        user = ClientIPMiddleware.get_outpost_user(self.request)
116        if not user:
117            return []
118        if not user.has_perm(
119            "pass_outpost_certificate", self.executor.current_stage
120        ) and not user.has_perm("authentik_stages_mtls.pass_outpost_certificate"):
121            return []
122        outpost_raw = self.request.headers.get(HEADER_OUTPOST_FORWARDED)
123        return self.__parse_single_cert(outpost_raw, ParseOptions.UNQUOTE)
124
125    def get_authorities(self) -> list[CertificateKeyPair] | None:
126        # We can't access `certificate_authorities` on `self.executor.current_stage`, as that would
127        # load the certificate into the directly referenced foreign key, which we have to pickle
128        # as part of the flow plan, and cryptography certs can't be pickled
129        stage: MutualTLSStage = (
130            MutualTLSStage.objects.filter(pk=self.executor.current_stage.pk)
131            .prefetch_related("certificate_authorities")
132            .first()
133        )
134        if stage.certificate_authorities.exists():
135            return stage.certificate_authorities.order_by("name")
136        brand: Brand = self.request.brand
137        if brand.client_certificates.exists():
138            return brand.client_certificates.order_by("name")
139        return None
140
141    def validate_cert(self, authorities: list[CertificateKeyPair], certs: list[Certificate]):
142        authorities_cert = [x.certificate for x in authorities]
143        for _cert in certs:
144            try:
145                PolicyBuilder().store(Store(authorities_cert)).time(
146                    now()
147                ).build_client_verifier().verify(_cert, [])
148                return _cert
149            except (
150                InvalidSignature,
151                TypeError,
152                ValueError,
153                VerificationError,
154                UnsupportedGeneralNameType,
155            ) as exc:
156                self.logger.warning("Discarding invalid certificate", cert=_cert, exc=exc)
157                continue
158        return None
159
160    def check_if_user(self, cert: Certificate):
161        stage: MutualTLSStage = self.executor.current_stage
162        cert_attr = None
163        user_attr = None
164        match stage.cert_attribute:
165            case CertAttributes.SUBJECT:
166                cert_attr = cert.subject.rfc4514_string()
167            case CertAttributes.COMMON_NAME:
168                cert_attr = self.get_cert_attribute(cert, NameOID.COMMON_NAME)
169            case CertAttributes.EMAIL:
170                cert_attr = self.get_cert_email(cert)
171        match stage.user_attribute:
172            case UserAttributes.USERNAME:
173                user_attr = "username"
174            case UserAttributes.EMAIL:
175                user_attr = "email"
176        if not user_attr or not cert_attr:
177            return None
178        return User.objects.filter(**{user_attr: cert_attr}).first()
179
180    def _cert_to_dict(self, cert: Certificate) -> dict:
181        """Represent a certificate in a dictionary, as certificate objects cannot be pickled"""
182        cert_dict = {
183            "serial_number": str(cert.serial_number),
184            "subject": cert.subject.rfc4514_string(),
185            "issuer": cert.issuer.rfc4514_string(),
186            "fingerprint_sha256": hexlify(cert.fingerprint(hashes.SHA256()), ":").decode("utf-8"),
187            "fingerprint_sha1": hexlify(cert.fingerprint(hashes.SHA1()), ":").decode(  # nosec
188                "utf-8"
189            ),
190            "san": {},
191        }
192        try:
193            san_ext = cert.extensions.get_extension_for_class(SubjectAlternativeName)
194        except ExtensionNotFound:
195            return cert_dict
196        # Map all SAN values into the dict, grouped by their type
197        for san_type in all_subclasses(GeneralName):
198            for san in san_ext.value.get_values_for_type(san_type):
199                type_str = san_type.__name__
200                if type_str not in cert_dict["san"]:
201                    cert_dict["san"][type_str] = []
202                cert_dict["san"][type_str].append(san)
203        return cert_dict
204
205    def auth_user(self, user: User, cert: Certificate):
206        self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = user
207        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD, "mtls")
208        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
209        self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
210            {"certificate": self._cert_to_dict(cert)}
211        )
212        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
213
214    def enroll_prepare_user(self, cert: Certificate):
215        self.executor.plan.context.setdefault(PLAN_CONTEXT_PROMPT, {})
216        self.executor.plan.context[PLAN_CONTEXT_PROMPT].update(
217            {
218                "email": self.get_cert_email(cert),
219                "name": self.get_cert_attribute(cert, NameOID.COMMON_NAME),
220            }
221        )
222        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
223
224    def get_cert_attribute(self, cert: Certificate, oid: ObjectIdentifier) -> str | None:
225        attr = cert.subject.get_attributes_for_oid(oid)
226        if len(attr) < 1:
227            return None
228        return str(attr[0].value)
229
230    def get_cert_email(self, cert: Certificate) -> str | None:
231        ext = cert.extensions.get_extension_for_class(SubjectAlternativeName)
232        _cert_attr = ext.value.get_values_for_type(RFC822Name)
233        if len(_cert_attr) < 1:
234            return None
235        return str(_cert_attr[0])
236
237    def get_cert(self, mode: StageMode):
238        certs = [
239            *self._parse_cert_xfcc(),
240            *self._parse_cert_nginx(),
241            *self._parse_cert_traefik(),
242            *self._parse_cert_outpost(),
243        ]
244        authorities = self.get_authorities()
245        if not authorities:
246            self.logger.warning("No Certificate authority found")
247            if mode == StageMode.OPTIONAL:
248                return None
249            if mode == StageMode.REQUIRED:
250                raise PermissionDenied("Unknown error")
251        cert = self.validate_cert(authorities, certs)
252        if not cert and mode == StageMode.REQUIRED:
253            self.logger.warning("Client certificate required but no certificates given")
254            raise PermissionDenied(str(_("Certificate required but no certificate was given.")))
255        if not cert and mode == StageMode.OPTIONAL:
256            self.logger.info("No certificate given, continuing")
257            return None
258        return cert
259
260    def dispatch(self, request, *args, **kwargs):
261        stage: MutualTLSStage = self.executor.current_stage
262        try:
263            cert = self.get_cert(stage.mode)
264        except PermissionDenied as exc:
265            return self.executor.stage_invalid(error_message=exc.detail)
266        if not cert:
267            return self.executor.stage_ok()
268        self.logger.debug("Received certificate", cert=fingerprint_sha256(cert))
269        existing_user = self.check_if_user(cert)
270        if self.executor.flow.designation == FlowDesignation.ENROLLMENT:
271            self.enroll_prepare_user(cert)
272        elif existing_user:
273            self.auth_user(existing_user, cert)
274        else:
275            return self.executor.stage_invalid(_("No user found for certificate."))
276        return self.executor.stage_ok()
HEADER_PROXY_FORWARDED = 'X-Forwarded-Client-Cert'
HEADER_NGINX_FORWARDED = 'SSL-Client-Cert'
HEADER_TRAEFIK_FORWARDED = 'X-Forwarded-TLS-Client-Cert'
HEADER_OUTPOST_FORWARDED = 'X-Authentik-Outpost-Certificate'
PLAN_CONTEXT_CERTIFICATE = 'certificate'
class ParseOptions(enum.IntFlag):
52class ParseOptions(IntFlag):
53
54    # URL unquote the string
55    UNQUOTE = auto()
56    # Re-add PEM Header & footer, and chunk it into 64 character lines
57    FORMAT = auto()

Support for integer-based Flags

UNQUOTE = <ParseOptions.UNQUOTE: 1>
FORMAT = <ParseOptions.FORMAT: 2>
class MTLSStageView(authentik.flows.stage.ChallengeStageView):
 60class MTLSStageView(ChallengeStageView):
 61
 62    def __parse_single_cert(self, raw: str | None, *options: ParseOptions) -> list[Certificate]:
 63        """Helper to parse a single certificate"""
 64        if not raw:
 65            return []
 66        for opt in options:
 67            match opt:
 68                case ParseOptions.FORMAT:
 69                    raw = format_cert(raw)
 70                case ParseOptions.UNQUOTE:
 71                    raw = unquote_plus(raw)
 72        try:
 73            cert = load_pem_x509_certificate(raw.encode())
 74            return [cert]
 75        except ValueError as exc:
 76            self.logger.info("Failed to parse certificate", exc=exc)
 77            return []
 78
 79    def _parse_cert_xfcc(self) -> list[Certificate]:
 80        """Parse certificates in the format given to us in
 81        the format of the authentik router/envoy"""
 82        # https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers#x-forwarded-client-cert
 83        xfcc_raw = self.request.headers.get(HEADER_PROXY_FORWARDED)
 84        if not xfcc_raw:
 85            return []
 86        certs = []
 87        for r_cert in xfcc_raw.split(","):
 88            el = r_cert.split(";")
 89            raw_cert = {k.split("=")[0]: k.split("=")[1] for k in el}
 90            if "Cert" not in raw_cert:
 91                continue
 92            certs.extend(self.__parse_single_cert(raw_cert["Cert"], ParseOptions.UNQUOTE))
 93        return certs
 94
 95    def _parse_cert_nginx(self) -> list[Certificate]:
 96        """Parse certificates in the format nginx-ingress gives to us"""
 97        # https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#client-certificate-authentication
 98        # https://github.com/kubernetes/ingress-nginx/blob/78f593b24494a0674b362faf551079f06d71b5a9/rootfs/etc/nginx/template/nginx.tmpl#L1096
 99        sslcc_raw = self.request.headers.get(HEADER_NGINX_FORWARDED)
100        return self.__parse_single_cert(sslcc_raw, ParseOptions.UNQUOTE)
101
102    def _parse_cert_traefik(self) -> list[Certificate]:
103        """Parse certificates in the format traefik gives to us"""
104        # https://doc.traefik.io/traefik/reference/routing-configuration/http/middlewares/passtlsclientcert/
105        ftcc_raw = self.request.headers.get(HEADER_TRAEFIK_FORWARDED)
106        if not ftcc_raw:
107            return []
108        certs = []
109        for cert in ftcc_raw.split(","):
110            certs.extend(self.__parse_single_cert(cert, ParseOptions.FORMAT))
111        return certs
112
113    def _parse_cert_outpost(self) -> list[Certificate]:
114        """Parse certificates in the format outposts give to us. Also authenticates
115        the outpost to ensure it has the permission to do so"""
116        user = ClientIPMiddleware.get_outpost_user(self.request)
117        if not user:
118            return []
119        if not user.has_perm(
120            "pass_outpost_certificate", self.executor.current_stage
121        ) and not user.has_perm("authentik_stages_mtls.pass_outpost_certificate"):
122            return []
123        outpost_raw = self.request.headers.get(HEADER_OUTPOST_FORWARDED)
124        return self.__parse_single_cert(outpost_raw, ParseOptions.UNQUOTE)
125
126    def get_authorities(self) -> list[CertificateKeyPair] | None:
127        # We can't access `certificate_authorities` on `self.executor.current_stage`, as that would
128        # load the certificate into the directly referenced foreign key, which we have to pickle
129        # as part of the flow plan, and cryptography certs can't be pickled
130        stage: MutualTLSStage = (
131            MutualTLSStage.objects.filter(pk=self.executor.current_stage.pk)
132            .prefetch_related("certificate_authorities")
133            .first()
134        )
135        if stage.certificate_authorities.exists():
136            return stage.certificate_authorities.order_by("name")
137        brand: Brand = self.request.brand
138        if brand.client_certificates.exists():
139            return brand.client_certificates.order_by("name")
140        return None
141
142    def validate_cert(self, authorities: list[CertificateKeyPair], certs: list[Certificate]):
143        authorities_cert = [x.certificate for x in authorities]
144        for _cert in certs:
145            try:
146                PolicyBuilder().store(Store(authorities_cert)).time(
147                    now()
148                ).build_client_verifier().verify(_cert, [])
149                return _cert
150            except (
151                InvalidSignature,
152                TypeError,
153                ValueError,
154                VerificationError,
155                UnsupportedGeneralNameType,
156            ) as exc:
157                self.logger.warning("Discarding invalid certificate", cert=_cert, exc=exc)
158                continue
159        return None
160
161    def check_if_user(self, cert: Certificate):
162        stage: MutualTLSStage = self.executor.current_stage
163        cert_attr = None
164        user_attr = None
165        match stage.cert_attribute:
166            case CertAttributes.SUBJECT:
167                cert_attr = cert.subject.rfc4514_string()
168            case CertAttributes.COMMON_NAME:
169                cert_attr = self.get_cert_attribute(cert, NameOID.COMMON_NAME)
170            case CertAttributes.EMAIL:
171                cert_attr = self.get_cert_email(cert)
172        match stage.user_attribute:
173            case UserAttributes.USERNAME:
174                user_attr = "username"
175            case UserAttributes.EMAIL:
176                user_attr = "email"
177        if not user_attr or not cert_attr:
178            return None
179        return User.objects.filter(**{user_attr: cert_attr}).first()
180
181    def _cert_to_dict(self, cert: Certificate) -> dict:
182        """Represent a certificate in a dictionary, as certificate objects cannot be pickled"""
183        cert_dict = {
184            "serial_number": str(cert.serial_number),
185            "subject": cert.subject.rfc4514_string(),
186            "issuer": cert.issuer.rfc4514_string(),
187            "fingerprint_sha256": hexlify(cert.fingerprint(hashes.SHA256()), ":").decode("utf-8"),
188            "fingerprint_sha1": hexlify(cert.fingerprint(hashes.SHA1()), ":").decode(  # nosec
189                "utf-8"
190            ),
191            "san": {},
192        }
193        try:
194            san_ext = cert.extensions.get_extension_for_class(SubjectAlternativeName)
195        except ExtensionNotFound:
196            return cert_dict
197        # Map all SAN values into the dict, grouped by their type
198        for san_type in all_subclasses(GeneralName):
199            for san in san_ext.value.get_values_for_type(san_type):
200                type_str = san_type.__name__
201                if type_str not in cert_dict["san"]:
202                    cert_dict["san"][type_str] = []
203                cert_dict["san"][type_str].append(san)
204        return cert_dict
205
206    def auth_user(self, user: User, cert: Certificate):
207        self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = user
208        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD, "mtls")
209        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
210        self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
211            {"certificate": self._cert_to_dict(cert)}
212        )
213        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
214
215    def enroll_prepare_user(self, cert: Certificate):
216        self.executor.plan.context.setdefault(PLAN_CONTEXT_PROMPT, {})
217        self.executor.plan.context[PLAN_CONTEXT_PROMPT].update(
218            {
219                "email": self.get_cert_email(cert),
220                "name": self.get_cert_attribute(cert, NameOID.COMMON_NAME),
221            }
222        )
223        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
224
225    def get_cert_attribute(self, cert: Certificate, oid: ObjectIdentifier) -> str | None:
226        attr = cert.subject.get_attributes_for_oid(oid)
227        if len(attr) < 1:
228            return None
229        return str(attr[0].value)
230
231    def get_cert_email(self, cert: Certificate) -> str | None:
232        ext = cert.extensions.get_extension_for_class(SubjectAlternativeName)
233        _cert_attr = ext.value.get_values_for_type(RFC822Name)
234        if len(_cert_attr) < 1:
235            return None
236        return str(_cert_attr[0])
237
238    def get_cert(self, mode: StageMode):
239        certs = [
240            *self._parse_cert_xfcc(),
241            *self._parse_cert_nginx(),
242            *self._parse_cert_traefik(),
243            *self._parse_cert_outpost(),
244        ]
245        authorities = self.get_authorities()
246        if not authorities:
247            self.logger.warning("No Certificate authority found")
248            if mode == StageMode.OPTIONAL:
249                return None
250            if mode == StageMode.REQUIRED:
251                raise PermissionDenied("Unknown error")
252        cert = self.validate_cert(authorities, certs)
253        if not cert and mode == StageMode.REQUIRED:
254            self.logger.warning("Client certificate required but no certificates given")
255            raise PermissionDenied(str(_("Certificate required but no certificate was given.")))
256        if not cert and mode == StageMode.OPTIONAL:
257            self.logger.info("No certificate given, continuing")
258            return None
259        return cert
260
261    def dispatch(self, request, *args, **kwargs):
262        stage: MutualTLSStage = self.executor.current_stage
263        try:
264            cert = self.get_cert(stage.mode)
265        except PermissionDenied as exc:
266            return self.executor.stage_invalid(error_message=exc.detail)
267        if not cert:
268            return self.executor.stage_ok()
269        self.logger.debug("Received certificate", cert=fingerprint_sha256(cert))
270        existing_user = self.check_if_user(cert)
271        if self.executor.flow.designation == FlowDesignation.ENROLLMENT:
272            self.enroll_prepare_user(cert)
273        elif existing_user:
274            self.auth_user(existing_user, cert)
275        else:
276            return self.executor.stage_invalid(_("No user found for certificate."))
277        return self.executor.stage_ok()

Stage view which response with a challenge

def get_authorities(self) -> list[authentik.crypto.models.CertificateKeyPair] | None:
126    def get_authorities(self) -> list[CertificateKeyPair] | None:
127        # We can't access `certificate_authorities` on `self.executor.current_stage`, as that would
128        # load the certificate into the directly referenced foreign key, which we have to pickle
129        # as part of the flow plan, and cryptography certs can't be pickled
130        stage: MutualTLSStage = (
131            MutualTLSStage.objects.filter(pk=self.executor.current_stage.pk)
132            .prefetch_related("certificate_authorities")
133            .first()
134        )
135        if stage.certificate_authorities.exists():
136            return stage.certificate_authorities.order_by("name")
137        brand: Brand = self.request.brand
138        if brand.client_certificates.exists():
139            return brand.client_certificates.order_by("name")
140        return None
def validate_cert( self, authorities: list[authentik.crypto.models.CertificateKeyPair], certs: list[cryptography.hazmat.bindings._rust.x509.Certificate]):
142    def validate_cert(self, authorities: list[CertificateKeyPair], certs: list[Certificate]):
143        authorities_cert = [x.certificate for x in authorities]
144        for _cert in certs:
145            try:
146                PolicyBuilder().store(Store(authorities_cert)).time(
147                    now()
148                ).build_client_verifier().verify(_cert, [])
149                return _cert
150            except (
151                InvalidSignature,
152                TypeError,
153                ValueError,
154                VerificationError,
155                UnsupportedGeneralNameType,
156            ) as exc:
157                self.logger.warning("Discarding invalid certificate", cert=_cert, exc=exc)
158                continue
159        return None
def check_if_user(self, cert: cryptography.hazmat.bindings._rust.x509.Certificate):
161    def check_if_user(self, cert: Certificate):
162        stage: MutualTLSStage = self.executor.current_stage
163        cert_attr = None
164        user_attr = None
165        match stage.cert_attribute:
166            case CertAttributes.SUBJECT:
167                cert_attr = cert.subject.rfc4514_string()
168            case CertAttributes.COMMON_NAME:
169                cert_attr = self.get_cert_attribute(cert, NameOID.COMMON_NAME)
170            case CertAttributes.EMAIL:
171                cert_attr = self.get_cert_email(cert)
172        match stage.user_attribute:
173            case UserAttributes.USERNAME:
174                user_attr = "username"
175            case UserAttributes.EMAIL:
176                user_attr = "email"
177        if not user_attr or not cert_attr:
178            return None
179        return User.objects.filter(**{user_attr: cert_attr}).first()
def auth_user( self, user: authentik.core.models.User, cert: cryptography.hazmat.bindings._rust.x509.Certificate):
206    def auth_user(self, user: User, cert: Certificate):
207        self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = user
208        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD, "mtls")
209        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
210        self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
211            {"certificate": self._cert_to_dict(cert)}
212        )
213        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
def enroll_prepare_user(self, cert: cryptography.hazmat.bindings._rust.x509.Certificate):
215    def enroll_prepare_user(self, cert: Certificate):
216        self.executor.plan.context.setdefault(PLAN_CONTEXT_PROMPT, {})
217        self.executor.plan.context[PLAN_CONTEXT_PROMPT].update(
218            {
219                "email": self.get_cert_email(cert),
220                "name": self.get_cert_attribute(cert, NameOID.COMMON_NAME),
221            }
222        )
223        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
def get_cert_attribute( self, cert: cryptography.hazmat.bindings._rust.x509.Certificate, oid: cryptography.hazmat.bindings._rust.ObjectIdentifier) -> str | None:
225    def get_cert_attribute(self, cert: Certificate, oid: ObjectIdentifier) -> str | None:
226        attr = cert.subject.get_attributes_for_oid(oid)
227        if len(attr) < 1:
228            return None
229        return str(attr[0].value)
def get_cert_email( self, cert: cryptography.hazmat.bindings._rust.x509.Certificate) -> str | None:
231    def get_cert_email(self, cert: Certificate) -> str | None:
232        ext = cert.extensions.get_extension_for_class(SubjectAlternativeName)
233        _cert_attr = ext.value.get_values_for_type(RFC822Name)
234        if len(_cert_attr) < 1:
235            return None
236        return str(_cert_attr[0])
def get_cert(self, mode: authentik.endpoints.models.StageMode):
238    def get_cert(self, mode: StageMode):
239        certs = [
240            *self._parse_cert_xfcc(),
241            *self._parse_cert_nginx(),
242            *self._parse_cert_traefik(),
243            *self._parse_cert_outpost(),
244        ]
245        authorities = self.get_authorities()
246        if not authorities:
247            self.logger.warning("No Certificate authority found")
248            if mode == StageMode.OPTIONAL:
249                return None
250            if mode == StageMode.REQUIRED:
251                raise PermissionDenied("Unknown error")
252        cert = self.validate_cert(authorities, certs)
253        if not cert and mode == StageMode.REQUIRED:
254            self.logger.warning("Client certificate required but no certificates given")
255            raise PermissionDenied(str(_("Certificate required but no certificate was given.")))
256        if not cert and mode == StageMode.OPTIONAL:
257            self.logger.info("No certificate given, continuing")
258            return None
259        return cert
def dispatch(self, request, *args, **kwargs):
261    def dispatch(self, request, *args, **kwargs):
262        stage: MutualTLSStage = self.executor.current_stage
263        try:
264            cert = self.get_cert(stage.mode)
265        except PermissionDenied as exc:
266            return self.executor.stage_invalid(error_message=exc.detail)
267        if not cert:
268            return self.executor.stage_ok()
269        self.logger.debug("Received certificate", cert=fingerprint_sha256(cert))
270        existing_user = self.check_if_user(cert)
271        if self.executor.flow.designation == FlowDesignation.ENROLLMENT:
272            self.enroll_prepare_user(cert)
273        elif existing_user:
274            self.auth_user(existing_user, cert)
275        else:
276            return self.executor.stage_invalid(_("No user found for certificate."))
277        return self.executor.stage_ok()