authentik.enterprise.endpoints.connectors.microsoft_intune.stage

 1from cryptography.x509 import (
 2    Certificate,
 3    ExtensionNotFound,
 4    NameOID,
 5    SubjectAlternativeName,
 6    UniformResourceIdentifier,
 7)
 8from django.db.models import Q
 9from rest_framework.exceptions import PermissionDenied
10
11from authentik.brands.models import Brand
12from authentik.crypto.models import CertificateKeyPair, fingerprint_sha256
13from authentik.endpoints.models import Device, EndpointStage, StageMode
14from authentik.enterprise.stages.mtls.stage import PLAN_CONTEXT_CERTIFICATE, MTLSStageView
15from authentik.flows.planner import PLAN_CONTEXT_DEVICE
16
17# Cisco ISE's `ID:<vendor>:GUID:<id>` SAN URI scheme, which is commonly used in Intune SCEP/PKCS
18# profiles, either as `ID:Intune:GUID:{{DeviceId}}` or
19# `ID:Microsoft Endpoint Manager:GUID:{{DeviceId}}`
20# https://www.cisco.com/c/en/us/td/docs/security/ise/UEM-MDM-Server-Integration/b_MDM_UEM_Servers_CiscoISE.pdf
21# (chapter "Integrate Microsoft Endpoint Manager Intune")
22# https://community.cisco.com/t5/network-access-control/integrating-ise-with-azure-intune-as-mdm/m-p/4686559
23GUID_URI_MARKER = "GUID:"
24VENDOR_PREFIX = "deviceconnection__devicefactsnapshot__data__vendor__intune.microsoft.com"
25
26
27class MicrosoftIntuneStageView(MTLSStageView):
28    def get_authorities(self):
29        # Intune certificates are issued by the customer's CA (Cloud PKI, ADCS/NDES, etc),
30        # which is configured on the connector, falling back to the brand's client certificates
31        stage: EndpointStage = self.executor.current_stage
32        cas = CertificateKeyPair.objects.filter(microsoftintuneconnector=stage.connector_id)
33        if cas.exists():
34            return cas.order_by("name")
35        brand: Brand = self.request.brand
36        if brand.client_certificates.exists():
37            return brand.client_certificates.order_by("name")
38        return None
39
40    def get_device_ids(self, cert: Certificate) -> list[str]:
41        """Collect candidate device IDs from the certificate's CN and SAN URIs.
42        Intune profiles set these with `{{DeviceId}}` (Intune device ID) or
43        `{{AAD_Device_ID}}`/`{{AzureADDeviceId}}` (Entra device ID), see "Subject name format"
44        https://learn.microsoft.com/en-us/intune/device-configuration/certificates/scep-profiles"""
45        values = [x.value for x in cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)]
46        try:
47            san_ext = cert.extensions.get_extension_for_class(SubjectAlternativeName)
48            values.extend(san_ext.value.get_values_for_type(UniformResourceIdentifier))
49        except ExtensionNotFound:
50            # SAN is optional; fall back to CN-derived identifiers only.
51            pass
52        return [str(x).rpartition(GUID_URI_MARKER)[2].lower() for x in values]
53
54    def lookup_device(self, cert: Certificate, mode: StageMode):
55        stage: EndpointStage = self.executor.current_stage
56        values = self.get_device_ids(cert)
57        self.logger.debug("Looking for devices with ID", intune_device_id=values)
58        # `id` is the Intune device ID and `azureADDeviceId` the Entra device ID, see
59        # https://learn.microsoft.com/en-us/graph/api/resources/intune-devices-manageddevice?view=graph-rest-1.0
60        device = (
61            Device.objects.filter(deviceconnection__connector=stage.connector_id)
62            .filter(
63                Q(**{f"{VENDOR_PREFIX}__id__in": values})
64                | Q(**{f"{VENDOR_PREFIX}__azure_a_d_device_id__in": values})
65            )
66            .first()
67        )
68        if not device and mode == StageMode.REQUIRED:
69            raise PermissionDenied("Failed to find device")
70        self.executor.plan.context[PLAN_CONTEXT_DEVICE] = device
71        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
72        return self.executor.stage_ok()
73
74    def dispatch(self, request, *args, **kwargs):
75        stage: EndpointStage = self.executor.current_stage
76        try:
77            cert = self.get_cert(stage.mode)
78            if not cert:
79                return self.executor.stage_ok()
80            self.logger.debug("Received certificate", cert=fingerprint_sha256(cert))
81            return self.lookup_device(cert, stage.mode)
82        except PermissionDenied as exc:
83            return self.executor.stage_invalid(error_message=exc.detail)
GUID_URI_MARKER = 'GUID:'
VENDOR_PREFIX = 'deviceconnection__devicefactsnapshot__data__vendor__intune.microsoft.com'
class MicrosoftIntuneStageView(authentik.enterprise.stages.mtls.stage.MTLSStageView):
28class MicrosoftIntuneStageView(MTLSStageView):
29    def get_authorities(self):
30        # Intune certificates are issued by the customer's CA (Cloud PKI, ADCS/NDES, etc),
31        # which is configured on the connector, falling back to the brand's client certificates
32        stage: EndpointStage = self.executor.current_stage
33        cas = CertificateKeyPair.objects.filter(microsoftintuneconnector=stage.connector_id)
34        if cas.exists():
35            return cas.order_by("name")
36        brand: Brand = self.request.brand
37        if brand.client_certificates.exists():
38            return brand.client_certificates.order_by("name")
39        return None
40
41    def get_device_ids(self, cert: Certificate) -> list[str]:
42        """Collect candidate device IDs from the certificate's CN and SAN URIs.
43        Intune profiles set these with `{{DeviceId}}` (Intune device ID) or
44        `{{AAD_Device_ID}}`/`{{AzureADDeviceId}}` (Entra device ID), see "Subject name format"
45        https://learn.microsoft.com/en-us/intune/device-configuration/certificates/scep-profiles"""
46        values = [x.value for x in cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)]
47        try:
48            san_ext = cert.extensions.get_extension_for_class(SubjectAlternativeName)
49            values.extend(san_ext.value.get_values_for_type(UniformResourceIdentifier))
50        except ExtensionNotFound:
51            # SAN is optional; fall back to CN-derived identifiers only.
52            pass
53        return [str(x).rpartition(GUID_URI_MARKER)[2].lower() for x in values]
54
55    def lookup_device(self, cert: Certificate, mode: StageMode):
56        stage: EndpointStage = self.executor.current_stage
57        values = self.get_device_ids(cert)
58        self.logger.debug("Looking for devices with ID", intune_device_id=values)
59        # `id` is the Intune device ID and `azureADDeviceId` the Entra device ID, see
60        # https://learn.microsoft.com/en-us/graph/api/resources/intune-devices-manageddevice?view=graph-rest-1.0
61        device = (
62            Device.objects.filter(deviceconnection__connector=stage.connector_id)
63            .filter(
64                Q(**{f"{VENDOR_PREFIX}__id__in": values})
65                | Q(**{f"{VENDOR_PREFIX}__azure_a_d_device_id__in": values})
66            )
67            .first()
68        )
69        if not device and mode == StageMode.REQUIRED:
70            raise PermissionDenied("Failed to find device")
71        self.executor.plan.context[PLAN_CONTEXT_DEVICE] = device
72        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
73        return self.executor.stage_ok()
74
75    def dispatch(self, request, *args, **kwargs):
76        stage: EndpointStage = self.executor.current_stage
77        try:
78            cert = self.get_cert(stage.mode)
79            if not cert:
80                return self.executor.stage_ok()
81            self.logger.debug("Received certificate", cert=fingerprint_sha256(cert))
82            return self.lookup_device(cert, stage.mode)
83        except PermissionDenied as exc:
84            return self.executor.stage_invalid(error_message=exc.detail)

Stage view which response with a challenge

def get_authorities(self):
29    def get_authorities(self):
30        # Intune certificates are issued by the customer's CA (Cloud PKI, ADCS/NDES, etc),
31        # which is configured on the connector, falling back to the brand's client certificates
32        stage: EndpointStage = self.executor.current_stage
33        cas = CertificateKeyPair.objects.filter(microsoftintuneconnector=stage.connector_id)
34        if cas.exists():
35            return cas.order_by("name")
36        brand: Brand = self.request.brand
37        if brand.client_certificates.exists():
38            return brand.client_certificates.order_by("name")
39        return None
def get_device_ids( self, cert: cryptography.hazmat.bindings._rust.x509.Certificate) -> list[str]:
41    def get_device_ids(self, cert: Certificate) -> list[str]:
42        """Collect candidate device IDs from the certificate's CN and SAN URIs.
43        Intune profiles set these with `{{DeviceId}}` (Intune device ID) or
44        `{{AAD_Device_ID}}`/`{{AzureADDeviceId}}` (Entra device ID), see "Subject name format"
45        https://learn.microsoft.com/en-us/intune/device-configuration/certificates/scep-profiles"""
46        values = [x.value for x in cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)]
47        try:
48            san_ext = cert.extensions.get_extension_for_class(SubjectAlternativeName)
49            values.extend(san_ext.value.get_values_for_type(UniformResourceIdentifier))
50        except ExtensionNotFound:
51            # SAN is optional; fall back to CN-derived identifiers only.
52            pass
53        return [str(x).rpartition(GUID_URI_MARKER)[2].lower() for x in values]

Collect candidate device IDs from the certificate's CN and SAN URIs. Intune profiles set these with {{DeviceId}} (Intune device ID) or {{AAD_Device_ID}}/{{AzureADDeviceId}} (Entra device ID), see "Subject name format" https://learn.microsoft.com/en-us/intune/device-configuration/certificates/scep-profiles

def lookup_device( self, cert: cryptography.hazmat.bindings._rust.x509.Certificate, mode: authentik.endpoints.models.StageMode):
55    def lookup_device(self, cert: Certificate, mode: StageMode):
56        stage: EndpointStage = self.executor.current_stage
57        values = self.get_device_ids(cert)
58        self.logger.debug("Looking for devices with ID", intune_device_id=values)
59        # `id` is the Intune device ID and `azureADDeviceId` the Entra device ID, see
60        # https://learn.microsoft.com/en-us/graph/api/resources/intune-devices-manageddevice?view=graph-rest-1.0
61        device = (
62            Device.objects.filter(deviceconnection__connector=stage.connector_id)
63            .filter(
64                Q(**{f"{VENDOR_PREFIX}__id__in": values})
65                | Q(**{f"{VENDOR_PREFIX}__azure_a_d_device_id__in": values})
66            )
67            .first()
68        )
69        if not device and mode == StageMode.REQUIRED:
70            raise PermissionDenied("Failed to find device")
71        self.executor.plan.context[PLAN_CONTEXT_DEVICE] = device
72        self.executor.plan.context[PLAN_CONTEXT_CERTIFICATE] = self._cert_to_dict(cert)
73        return self.executor.stage_ok()
def dispatch(self, request, *args, **kwargs):
75    def dispatch(self, request, *args, **kwargs):
76        stage: EndpointStage = self.executor.current_stage
77        try:
78            cert = self.get_cert(stage.mode)
79            if not cert:
80                return self.executor.stage_ok()
81            self.logger.debug("Received certificate", cert=fingerprint_sha256(cert))
82            return self.lookup_device(cert, stage.mode)
83        except PermissionDenied as exc:
84            return self.executor.stage_invalid(error_message=exc.detail)