authentik.enterprise.endpoints.connectors.agent.views.apple_token
1from base64 import b64encode, urlsafe_b64decode, urlsafe_b64encode 2from typing import Any 3from urllib.parse import parse_qs, urlparse 4from uuid import UUID 5 6from cryptography import x509 7from cryptography.hazmat.primitives import hashes, serialization 8from cryptography.hazmat.primitives.asymmetric.ec import ( 9 ECDH, 10 SECP256R1, 11 EllipticCurvePublicKey, 12 generate_private_key, 13) 14from cryptography.x509.oid import NameOID 15from django.http import HttpRequest, HttpResponse 16from django.urls import reverse 17from django.utils.decorators import method_decorator 18from django.utils.timezone import now 19from django.views import View 20from django.views.decorators.csrf import csrf_exempt 21from jwt import PyJWTError, decode, encode, get_unverified_header 22from rest_framework.exceptions import ValidationError 23from structlog.stdlib import get_logger 24 25from authentik.common.oauth.constants import TOKEN_TYPE 26from authentik.core.models import AuthenticatedSession, Session, User 27from authentik.core.sessions import SessionStore 28from authentik.crypto.apps import MANAGED_KEY 29from authentik.crypto.models import CertificateKeyPair 30from authentik.endpoints.connectors.agent.models import ( 31 AgentConnector, 32 AgentDeviceConnection, 33 AgentDeviceUserBinding, 34 AppleAuthorizationCode, 35 AppleIndependentSecureEnclave, 36 AppleNonce, 37 AppleUnlockKey, 38 DeviceAuthenticationToken, 39) 40from authentik.enterprise.endpoints.connectors.agent.http import JWEResponse 41from authentik.events.models import Event, EventAction 42from authentik.events.signals import SESSION_LOGIN_EVENT 43from authentik.flows.planner import PLAN_CONTEXT_DEVICE 44from authentik.lib.utils.time import timedelta_from_string 45from authentik.providers.oauth2.id_token import IDToken 46from authentik.providers.oauth2.models import JWTAlgorithms 47from authentik.root.middleware import SessionMiddleware 48 49LOGGER = get_logger() 50 51 52@method_decorator(csrf_exempt, name="dispatch") 53class TokenView(View): 54 device_connection: AgentDeviceConnection 55 connector: AgentConnector 56 57 def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 58 # This is a plain Django View, so DRF's exception handler never runs and a 59 # ValidationError raised below would surface as a 500 instead of a 400. 60 try: 61 return super().dispatch(request, *args, **kwargs) 62 except ValidationError as exc: 63 LOGGER.warning("Invalid Platform SSO token request", exc=exc) 64 return HttpResponse(status=400) 65 66 def post(self, request: HttpRequest) -> HttpResponse: 67 assertion = request.POST.get("assertion", request.POST.get("request")) 68 if not assertion: 69 return HttpResponse(status=400) 70 self.now = now() 71 try: 72 self.jwt_request = self.validate_request_token(assertion) 73 except PyJWTError as exc: 74 LOGGER.warning("failed to parse JWT", exc=exc) 75 raise ValidationError("Invalid request") from exc 76 if self.jwt_request is None: 77 return HttpResponse(status=400) 78 version = request.POST.get("platform_sso_version") 79 grant_type = request.POST.get("grant_type") 80 handler_func = ( 81 f"handle_v{version}_{grant_type}".replace("-", "_") 82 .replace("+", "_") 83 .replace(":", "_") 84 .replace(".", "_") 85 ) 86 handler = getattr(self, handler_func, None) 87 if not handler: 88 LOGGER.debug("Handler not found", handler=handler_func) 89 return HttpResponse(status=400) 90 LOGGER.debug("sending to handler", handler=handler_func) 91 return handler() 92 93 def validate_request_token(self, assertion: str) -> dict[str, Any] | None: 94 # Decode without validation to get header 95 header = get_unverified_header(assertion) 96 expected_kid = header["kid"] 97 LOGGER.debug("token header", typ=header.get("typ"), kid=expected_kid) 98 99 self.device_connection = ( 100 AgentDeviceConnection.objects.filter(apple_sign_key_id=expected_kid) 101 .select_related("device") 102 .first() 103 ) 104 if not self.device_connection: 105 LOGGER.warning("No device connection found for key ID", kid=expected_kid) 106 return None 107 self.connector = AgentConnector.objects.get(pk=self.device_connection.connector.pk) 108 if not self.device_connection.apple_signing_key: 109 LOGGER.warning("Failed to issue token for device, no apple_signing_key") 110 raise ValidationError("Invalid request") 111 112 kwargs = {"issuer": str(self.connector.pk)} 113 # Only login requests carry an audience claim, key requests/exchanges don't 114 if header["typ"] == "platformsso-login-request+jwt": 115 kwargs["audience"] = self.request.build_absolute_uri( 116 reverse("authentik_enterprise_endpoints_connectors_agent:psso-token") 117 ) 118 # Properly decode the JWT with the key from the device 119 decoded = decode( 120 assertion, self.device_connection.apple_signing_key, algorithms=["ES256"], **kwargs 121 ) 122 self.remote_nonce = decoded.get("nonce") 123 124 # Check that the nonce hasn't been used before 125 nonce = AppleNonce.objects.filter(nonce=decoded["request_nonce"]).first() 126 if not nonce: 127 raise ValidationError("Invalid nonce") 128 self.nonce = nonce 129 nonce.delete() 130 return decoded 131 132 def validate_embedded_assertion( 133 self, assertion: str 134 ) -> tuple[AgentDeviceUserBinding | AppleIndependentSecureEnclave, dict]: 135 """Decode an embedded assertion and validate it by looking up the matching device user""" 136 decode_unvalidated = get_unverified_header(assertion) 137 expected_kid = decode_unvalidated["kid"] 138 139 device_user = AgentDeviceUserBinding.objects.filter( 140 target=self.device_connection.device, apple_enclave_key_id=expected_kid 141 ).first() 142 if not device_user: 143 independent_user = AppleIndependentSecureEnclave.objects.filter( 144 apple_enclave_key_id=expected_kid 145 ).first() 146 if not independent_user: 147 LOGGER.warning("Could not find device user binding or independent enclave for user") 148 raise ValidationError("Invalid request") 149 device_user = independent_user 150 decoded: dict[str, Any] = decode( 151 assertion, 152 device_user.apple_secure_enclave_key, 153 audience=str(self.device_connection.device.pk), 154 algorithms=["ES256"], 155 ) 156 if decoded.get("nonce") != self.jwt_request.get("nonce"): 157 LOGGER.warning("Mis-matched nonce to outer assertion") 158 raise ValidationError("Invalid nonce") 159 return device_user, decoded 160 161 @staticmethod 162 def ecdh_shared_key(cert_private_key_pem: str, other_publickey_b64: str) -> bytes: 163 """ECDH between our unlock key and the device's ephemeral public key. The device 164 regenerates its side per-request, so `other_publickey` must come from the request 165 being handled, never from registration or a previous request.""" 166 private_key = serialization.load_pem_private_key( 167 cert_private_key_pem.encode(), password=None 168 ) 169 other_pubkey_bytes = urlsafe_b64decode( 170 other_publickey_b64 + "=" * (-len(other_publickey_b64) % 4) 171 ) 172 other_public_key = EllipticCurvePublicKey.from_encoded_point( 173 SECP256R1(), other_pubkey_bytes 174 ) 175 return private_key.exchange(ECDH(), other_public_key) 176 177 def create_auth_session(self, user: User): 178 event = Event.new( 179 EventAction.LOGIN, 180 app="authentik.endpoints.connectors.agent", 181 **{ 182 PLAN_CONTEXT_DEVICE: self.device_connection.device, 183 }, 184 ).from_http(self.request, user=user) 185 store = SessionStore() 186 store[SESSION_LOGIN_EVENT] = event 187 store.save() 188 session = Session.objects.filter(session_key=store.session_key).first() 189 session.expires = self.now + timedelta_from_string(self.connector.auth_session_duration) 190 AuthenticatedSession.objects.create(session=session, user=user) 191 session = SessionMiddleware.encode_session(store.session_key, user) 192 return session 193 194 def create_id_token(self, user: User, **kwargs): 195 claims = kwargs.pop("claims", {}) 196 # Only http(s) avatars are usable by the client, the initials fallback is an 197 # inline SVG data URI which macOS can't decode 198 avatar = user.avatar 199 if avatar.startswith(("http://", "https://")): 200 claims["picture"] = avatar 201 issuer = self.request.build_absolute_uri( 202 reverse("authentik_enterprise_endpoints_connectors_agent:psso-token") 203 ) 204 id_token = IDToken( 205 iss=issuer, 206 sub=str(user.uuid), 207 aud=str(self.connector.pk), 208 exp=int( 209 (self.now + timedelta_from_string(self.connector.auth_session_duration)).timestamp() 210 ), 211 iat=int(now().timestamp()), 212 claims=claims, 213 **kwargs, 214 ) 215 kp = CertificateKeyPair.objects.filter(managed=MANAGED_KEY).first() 216 return encode( 217 id_token.to_dict(), 218 kp.private_key, 219 headers={ 220 "kid": kp.kid, 221 }, 222 algorithm=JWTAlgorithms.from_private_key(kp.private_key), 223 ) 224 225 def login_response(self, user: User) -> JWEResponse: 226 """Build the shared login response for both the jwt-bearer and authorization_code 227 grants, optionally including the ECDH key material for lock-screen unlock.""" 228 auth_token = DeviceAuthenticationToken.objects.create( 229 device=self.device_connection.device, 230 connector=self.connector, 231 user=user, 232 device_token=self.nonce.device_token, 233 ) 234 body = { 235 "refresh_token": auth_token.token, 236 "refresh_token_expires_in": int((auth_token.expires - self.now).total_seconds()), 237 "id_token": self.create_id_token(user), 238 "token_type": TOKEN_TYPE, 239 "session_key": self.create_auth_session(user), 240 } 241 if "urn:apple:platformsso:auth:unlock" in self.jwt_request.get("scope", ""): 242 unlock_key = ( 243 AppleUnlockKey.objects.filter( 244 device_user__user=user, 245 device_user__target=self.device_connection.device, 246 ) 247 .order_by("-expires") 248 .first() 249 ) 250 other_publickey = self.jwt_request.get("other_publickey") 251 if not unlock_key or not other_publickey: 252 LOGGER.warning( 253 "auth:unlock requested without a provisioned key or public key", user=user 254 ) 255 else: 256 body["key"] = b64encode( 257 self.ecdh_shared_key(unlock_key.private_key, other_publickey) 258 ).decode() 259 body["key_context"] = str(unlock_key.identifier) 260 LOGGER.debug("Attached unlock key", key_context=unlock_key.identifier) 261 return JWEResponse( 262 body, 263 device=self.device_connection, 264 apv=self.jwt_request["jwe_crypto"]["apv"], 265 ) 266 267 def redeem_authorization_code(self, code: str | None) -> User: 268 """Redeem the authorization code of a web login, and return the user it was issued to""" 269 auth_code = None 270 if code: 271 # Bound to the device, so that no other device of the connector can redeem it 272 auth_code = AppleAuthorizationCode.objects.filter( 273 code=code, 274 connector=self.connector, 275 device_connection=self.device_connection, 276 ).first() 277 if not auth_code or auth_code.is_expired: 278 LOGGER.warning("Invalid authorization code") 279 raise ValidationError("Invalid request") 280 user = auth_code.user 281 auth_code.delete() 282 # Platform SSO doesn't call the extension to register the user for web logins, and 283 # requests the user's keys right after this, which needs the binding 284 device = self.device_connection.device 285 if not AgentDeviceUserBinding.objects.filter(target=device, user=user).exists(): 286 AgentDeviceUserBinding.objects.create( 287 target=device, 288 user=user, 289 connector=self.connector, 290 is_primary=not AgentDeviceUserBinding.objects.filter(target=device).exists(), 291 order=0, 292 ) 293 return user 294 295 def handle_v1_0_urn_ietf_params_oauth_grant_type_jwt_bearer(self) -> HttpResponse: 296 if self.jwt_request.get("grant_type") == "urn:ietf:params:oauth:grant-type:token-exchange": 297 # Web login. The subject token is the callback URL the authorization endpoint 298 # redirected to, which carries the authorization code 299 query = parse_qs(urlparse(self.jwt_request.get("subject_token", "")).query) 300 return self.login_response(self.redeem_authorization_code(query.get("code", [""])[0])) 301 try: 302 device_user, _ = self.validate_embedded_assertion(self.jwt_request["assertion"]) 303 except PyJWTError as exc: 304 LOGGER.warning("failed to validate inner assertion", exc=exc) 305 raise ValidationError("Invalid request") from exc 306 return self.login_response(device_user.user) 307 308 def handle_v1_0_authorization_code(self) -> HttpResponse: 309 return self.login_response(self.redeem_authorization_code(self.request.POST.get("code"))) 310 311 def handle_v2_0_urn_ietf_params_oauth_grant_type_jwt_bearer(self) -> HttpResponse: 312 request_type = self.jwt_request.get("request_type") 313 LOGGER.debug("v2.0 request", request_type=request_type) 314 if request_type == "key_request": 315 return self.handle_key_request() 316 if request_type == "key_exchange": 317 return self.handle_key_exchange() 318 LOGGER.debug("Unknown request_type for v2.0", request_type=request_type) 319 return HttpResponse(status=400) 320 321 def validate_refresh_token(self) -> DeviceAuthenticationToken: 322 auth_token = ( 323 DeviceAuthenticationToken.objects.filter( 324 token=self.jwt_request.get("refresh_token"), 325 device=self.device_connection.device, 326 ) 327 .select_related("user") 328 .first() 329 ) 330 if not auth_token: 331 raise ValidationError("Invalid refresh token") 332 return auth_token 333 334 def handle_key_request(self) -> HttpResponse: 335 auth_token = self.validate_refresh_token() 336 device_user = AgentDeviceUserBinding.objects.filter( 337 target=self.device_connection.device, 338 user=auth_token.user, 339 ).first() 340 if not device_user: 341 LOGGER.warning("No device user binding found for key request") 342 return HttpResponse(status=400) 343 344 expires_at = self.now + timedelta_from_string(self.connector.auth_session_duration) 345 # Return the same certificate bytes for as long as the key is valid, so macOS sees an 346 # identical tokenID (SHA-1 of the public key) and doesn't attempt to rotate the key, 347 # which would require com.apple.PlatformSSO.login.service-xpc. 348 unlock_key = ( 349 AppleUnlockKey.objects.filter(device_user=device_user) 350 .exclude(certificate_der="") 351 .first() 352 ) 353 if unlock_key: 354 LOGGER.debug("Reusing unlock key", key_context=unlock_key.identifier) 355 else: 356 private_key = generate_private_key(SECP256R1()) 357 subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, auth_token.user.username)]) 358 cert = ( 359 x509.CertificateBuilder() 360 .subject_name(subject) 361 .issuer_name(subject) 362 .public_key(private_key.public_key()) 363 .serial_number(x509.random_serial_number()) 364 .not_valid_before(self.now) 365 .not_valid_after(expires_at) 366 .add_extension( 367 x509.KeyUsage( 368 digital_signature=True, 369 key_agreement=True, 370 key_cert_sign=False, 371 content_commitment=False, 372 key_encipherment=False, 373 data_encipherment=False, 374 crl_sign=False, 375 encipher_only=False, 376 decipher_only=False, 377 ), 378 critical=True, 379 ) 380 .add_extension( 381 x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()), 382 critical=False, 383 ) 384 .sign(private_key, hashes.SHA256()) 385 ) 386 unlock_key = AppleUnlockKey.objects.create( 387 device_user=device_user, 388 private_key=private_key.private_bytes( 389 encoding=serialization.Encoding.PEM, 390 format=serialization.PrivateFormat.PKCS8, 391 encryption_algorithm=serialization.NoEncryption(), 392 ).decode(), 393 certificate_der=urlsafe_b64encode(cert.public_bytes(serialization.Encoding.DER)) 394 .rstrip(b"=") 395 .decode(), 396 expires=expires_at, 397 ) 398 LOGGER.debug("Created unlock key", key_context=unlock_key.identifier) 399 return JWEResponse( 400 { 401 "certificate": unlock_key.certificate_der, 402 "exp": int(expires_at.timestamp()), 403 "iat": int(self.now.timestamp()), 404 "key_context": str(unlock_key.identifier), 405 }, 406 device=self.device_connection, 407 apv=self.jwt_request["jwe_crypto"]["apv"], 408 typ="platformsso-key-response+jwt", 409 ) 410 411 def handle_key_exchange(self) -> HttpResponse: 412 auth_token = self.validate_refresh_token() 413 try: 414 key_context = UUID(self.jwt_request.get("key_context", "")) 415 except ValueError: 416 LOGGER.warning("Missing or invalid key_context in key exchange request") 417 return HttpResponse(status=400) 418 unlock_key = AppleUnlockKey.objects.filter( 419 identifier=key_context, 420 device_user__user=auth_token.user, 421 device_user__target=self.device_connection.device, 422 ).first() 423 if not unlock_key: 424 LOGGER.warning("No unlock key found for key_context", key_context=key_context) 425 return HttpResponse(status=400) 426 427 expires_at = self.now + timedelta_from_string(self.connector.auth_session_duration) 428 return JWEResponse( 429 { 430 "key": b64encode( 431 self.ecdh_shared_key( 432 unlock_key.private_key, self.jwt_request["other_publickey"] 433 ) 434 ).decode(), 435 "exp": int(expires_at.timestamp()), 436 "iat": int(self.now.timestamp()), 437 "key_context": str(unlock_key.identifier), 438 }, 439 device=self.device_connection, 440 apv=self.jwt_request["jwe_crypto"]["apv"], 441 typ="platformsso-key-response+jwt", 442 )
LOGGER =
<BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
@method_decorator(csrf_exempt, name='dispatch')
class
TokenView53@method_decorator(csrf_exempt, name="dispatch") 54class TokenView(View): 55 device_connection: AgentDeviceConnection 56 connector: AgentConnector 57 58 def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 59 # This is a plain Django View, so DRF's exception handler never runs and a 60 # ValidationError raised below would surface as a 500 instead of a 400. 61 try: 62 return super().dispatch(request, *args, **kwargs) 63 except ValidationError as exc: 64 LOGGER.warning("Invalid Platform SSO token request", exc=exc) 65 return HttpResponse(status=400) 66 67 def post(self, request: HttpRequest) -> HttpResponse: 68 assertion = request.POST.get("assertion", request.POST.get("request")) 69 if not assertion: 70 return HttpResponse(status=400) 71 self.now = now() 72 try: 73 self.jwt_request = self.validate_request_token(assertion) 74 except PyJWTError as exc: 75 LOGGER.warning("failed to parse JWT", exc=exc) 76 raise ValidationError("Invalid request") from exc 77 if self.jwt_request is None: 78 return HttpResponse(status=400) 79 version = request.POST.get("platform_sso_version") 80 grant_type = request.POST.get("grant_type") 81 handler_func = ( 82 f"handle_v{version}_{grant_type}".replace("-", "_") 83 .replace("+", "_") 84 .replace(":", "_") 85 .replace(".", "_") 86 ) 87 handler = getattr(self, handler_func, None) 88 if not handler: 89 LOGGER.debug("Handler not found", handler=handler_func) 90 return HttpResponse(status=400) 91 LOGGER.debug("sending to handler", handler=handler_func) 92 return handler() 93 94 def validate_request_token(self, assertion: str) -> dict[str, Any] | None: 95 # Decode without validation to get header 96 header = get_unverified_header(assertion) 97 expected_kid = header["kid"] 98 LOGGER.debug("token header", typ=header.get("typ"), kid=expected_kid) 99 100 self.device_connection = ( 101 AgentDeviceConnection.objects.filter(apple_sign_key_id=expected_kid) 102 .select_related("device") 103 .first() 104 ) 105 if not self.device_connection: 106 LOGGER.warning("No device connection found for key ID", kid=expected_kid) 107 return None 108 self.connector = AgentConnector.objects.get(pk=self.device_connection.connector.pk) 109 if not self.device_connection.apple_signing_key: 110 LOGGER.warning("Failed to issue token for device, no apple_signing_key") 111 raise ValidationError("Invalid request") 112 113 kwargs = {"issuer": str(self.connector.pk)} 114 # Only login requests carry an audience claim, key requests/exchanges don't 115 if header["typ"] == "platformsso-login-request+jwt": 116 kwargs["audience"] = self.request.build_absolute_uri( 117 reverse("authentik_enterprise_endpoints_connectors_agent:psso-token") 118 ) 119 # Properly decode the JWT with the key from the device 120 decoded = decode( 121 assertion, self.device_connection.apple_signing_key, algorithms=["ES256"], **kwargs 122 ) 123 self.remote_nonce = decoded.get("nonce") 124 125 # Check that the nonce hasn't been used before 126 nonce = AppleNonce.objects.filter(nonce=decoded["request_nonce"]).first() 127 if not nonce: 128 raise ValidationError("Invalid nonce") 129 self.nonce = nonce 130 nonce.delete() 131 return decoded 132 133 def validate_embedded_assertion( 134 self, assertion: str 135 ) -> tuple[AgentDeviceUserBinding | AppleIndependentSecureEnclave, dict]: 136 """Decode an embedded assertion and validate it by looking up the matching device user""" 137 decode_unvalidated = get_unverified_header(assertion) 138 expected_kid = decode_unvalidated["kid"] 139 140 device_user = AgentDeviceUserBinding.objects.filter( 141 target=self.device_connection.device, apple_enclave_key_id=expected_kid 142 ).first() 143 if not device_user: 144 independent_user = AppleIndependentSecureEnclave.objects.filter( 145 apple_enclave_key_id=expected_kid 146 ).first() 147 if not independent_user: 148 LOGGER.warning("Could not find device user binding or independent enclave for user") 149 raise ValidationError("Invalid request") 150 device_user = independent_user 151 decoded: dict[str, Any] = decode( 152 assertion, 153 device_user.apple_secure_enclave_key, 154 audience=str(self.device_connection.device.pk), 155 algorithms=["ES256"], 156 ) 157 if decoded.get("nonce") != self.jwt_request.get("nonce"): 158 LOGGER.warning("Mis-matched nonce to outer assertion") 159 raise ValidationError("Invalid nonce") 160 return device_user, decoded 161 162 @staticmethod 163 def ecdh_shared_key(cert_private_key_pem: str, other_publickey_b64: str) -> bytes: 164 """ECDH between our unlock key and the device's ephemeral public key. The device 165 regenerates its side per-request, so `other_publickey` must come from the request 166 being handled, never from registration or a previous request.""" 167 private_key = serialization.load_pem_private_key( 168 cert_private_key_pem.encode(), password=None 169 ) 170 other_pubkey_bytes = urlsafe_b64decode( 171 other_publickey_b64 + "=" * (-len(other_publickey_b64) % 4) 172 ) 173 other_public_key = EllipticCurvePublicKey.from_encoded_point( 174 SECP256R1(), other_pubkey_bytes 175 ) 176 return private_key.exchange(ECDH(), other_public_key) 177 178 def create_auth_session(self, user: User): 179 event = Event.new( 180 EventAction.LOGIN, 181 app="authentik.endpoints.connectors.agent", 182 **{ 183 PLAN_CONTEXT_DEVICE: self.device_connection.device, 184 }, 185 ).from_http(self.request, user=user) 186 store = SessionStore() 187 store[SESSION_LOGIN_EVENT] = event 188 store.save() 189 session = Session.objects.filter(session_key=store.session_key).first() 190 session.expires = self.now + timedelta_from_string(self.connector.auth_session_duration) 191 AuthenticatedSession.objects.create(session=session, user=user) 192 session = SessionMiddleware.encode_session(store.session_key, user) 193 return session 194 195 def create_id_token(self, user: User, **kwargs): 196 claims = kwargs.pop("claims", {}) 197 # Only http(s) avatars are usable by the client, the initials fallback is an 198 # inline SVG data URI which macOS can't decode 199 avatar = user.avatar 200 if avatar.startswith(("http://", "https://")): 201 claims["picture"] = avatar 202 issuer = self.request.build_absolute_uri( 203 reverse("authentik_enterprise_endpoints_connectors_agent:psso-token") 204 ) 205 id_token = IDToken( 206 iss=issuer, 207 sub=str(user.uuid), 208 aud=str(self.connector.pk), 209 exp=int( 210 (self.now + timedelta_from_string(self.connector.auth_session_duration)).timestamp() 211 ), 212 iat=int(now().timestamp()), 213 claims=claims, 214 **kwargs, 215 ) 216 kp = CertificateKeyPair.objects.filter(managed=MANAGED_KEY).first() 217 return encode( 218 id_token.to_dict(), 219 kp.private_key, 220 headers={ 221 "kid": kp.kid, 222 }, 223 algorithm=JWTAlgorithms.from_private_key(kp.private_key), 224 ) 225 226 def login_response(self, user: User) -> JWEResponse: 227 """Build the shared login response for both the jwt-bearer and authorization_code 228 grants, optionally including the ECDH key material for lock-screen unlock.""" 229 auth_token = DeviceAuthenticationToken.objects.create( 230 device=self.device_connection.device, 231 connector=self.connector, 232 user=user, 233 device_token=self.nonce.device_token, 234 ) 235 body = { 236 "refresh_token": auth_token.token, 237 "refresh_token_expires_in": int((auth_token.expires - self.now).total_seconds()), 238 "id_token": self.create_id_token(user), 239 "token_type": TOKEN_TYPE, 240 "session_key": self.create_auth_session(user), 241 } 242 if "urn:apple:platformsso:auth:unlock" in self.jwt_request.get("scope", ""): 243 unlock_key = ( 244 AppleUnlockKey.objects.filter( 245 device_user__user=user, 246 device_user__target=self.device_connection.device, 247 ) 248 .order_by("-expires") 249 .first() 250 ) 251 other_publickey = self.jwt_request.get("other_publickey") 252 if not unlock_key or not other_publickey: 253 LOGGER.warning( 254 "auth:unlock requested without a provisioned key or public key", user=user 255 ) 256 else: 257 body["key"] = b64encode( 258 self.ecdh_shared_key(unlock_key.private_key, other_publickey) 259 ).decode() 260 body["key_context"] = str(unlock_key.identifier) 261 LOGGER.debug("Attached unlock key", key_context=unlock_key.identifier) 262 return JWEResponse( 263 body, 264 device=self.device_connection, 265 apv=self.jwt_request["jwe_crypto"]["apv"], 266 ) 267 268 def redeem_authorization_code(self, code: str | None) -> User: 269 """Redeem the authorization code of a web login, and return the user it was issued to""" 270 auth_code = None 271 if code: 272 # Bound to the device, so that no other device of the connector can redeem it 273 auth_code = AppleAuthorizationCode.objects.filter( 274 code=code, 275 connector=self.connector, 276 device_connection=self.device_connection, 277 ).first() 278 if not auth_code or auth_code.is_expired: 279 LOGGER.warning("Invalid authorization code") 280 raise ValidationError("Invalid request") 281 user = auth_code.user 282 auth_code.delete() 283 # Platform SSO doesn't call the extension to register the user for web logins, and 284 # requests the user's keys right after this, which needs the binding 285 device = self.device_connection.device 286 if not AgentDeviceUserBinding.objects.filter(target=device, user=user).exists(): 287 AgentDeviceUserBinding.objects.create( 288 target=device, 289 user=user, 290 connector=self.connector, 291 is_primary=not AgentDeviceUserBinding.objects.filter(target=device).exists(), 292 order=0, 293 ) 294 return user 295 296 def handle_v1_0_urn_ietf_params_oauth_grant_type_jwt_bearer(self) -> HttpResponse: 297 if self.jwt_request.get("grant_type") == "urn:ietf:params:oauth:grant-type:token-exchange": 298 # Web login. The subject token is the callback URL the authorization endpoint 299 # redirected to, which carries the authorization code 300 query = parse_qs(urlparse(self.jwt_request.get("subject_token", "")).query) 301 return self.login_response(self.redeem_authorization_code(query.get("code", [""])[0])) 302 try: 303 device_user, _ = self.validate_embedded_assertion(self.jwt_request["assertion"]) 304 except PyJWTError as exc: 305 LOGGER.warning("failed to validate inner assertion", exc=exc) 306 raise ValidationError("Invalid request") from exc 307 return self.login_response(device_user.user) 308 309 def handle_v1_0_authorization_code(self) -> HttpResponse: 310 return self.login_response(self.redeem_authorization_code(self.request.POST.get("code"))) 311 312 def handle_v2_0_urn_ietf_params_oauth_grant_type_jwt_bearer(self) -> HttpResponse: 313 request_type = self.jwt_request.get("request_type") 314 LOGGER.debug("v2.0 request", request_type=request_type) 315 if request_type == "key_request": 316 return self.handle_key_request() 317 if request_type == "key_exchange": 318 return self.handle_key_exchange() 319 LOGGER.debug("Unknown request_type for v2.0", request_type=request_type) 320 return HttpResponse(status=400) 321 322 def validate_refresh_token(self) -> DeviceAuthenticationToken: 323 auth_token = ( 324 DeviceAuthenticationToken.objects.filter( 325 token=self.jwt_request.get("refresh_token"), 326 device=self.device_connection.device, 327 ) 328 .select_related("user") 329 .first() 330 ) 331 if not auth_token: 332 raise ValidationError("Invalid refresh token") 333 return auth_token 334 335 def handle_key_request(self) -> HttpResponse: 336 auth_token = self.validate_refresh_token() 337 device_user = AgentDeviceUserBinding.objects.filter( 338 target=self.device_connection.device, 339 user=auth_token.user, 340 ).first() 341 if not device_user: 342 LOGGER.warning("No device user binding found for key request") 343 return HttpResponse(status=400) 344 345 expires_at = self.now + timedelta_from_string(self.connector.auth_session_duration) 346 # Return the same certificate bytes for as long as the key is valid, so macOS sees an 347 # identical tokenID (SHA-1 of the public key) and doesn't attempt to rotate the key, 348 # which would require com.apple.PlatformSSO.login.service-xpc. 349 unlock_key = ( 350 AppleUnlockKey.objects.filter(device_user=device_user) 351 .exclude(certificate_der="") 352 .first() 353 ) 354 if unlock_key: 355 LOGGER.debug("Reusing unlock key", key_context=unlock_key.identifier) 356 else: 357 private_key = generate_private_key(SECP256R1()) 358 subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, auth_token.user.username)]) 359 cert = ( 360 x509.CertificateBuilder() 361 .subject_name(subject) 362 .issuer_name(subject) 363 .public_key(private_key.public_key()) 364 .serial_number(x509.random_serial_number()) 365 .not_valid_before(self.now) 366 .not_valid_after(expires_at) 367 .add_extension( 368 x509.KeyUsage( 369 digital_signature=True, 370 key_agreement=True, 371 key_cert_sign=False, 372 content_commitment=False, 373 key_encipherment=False, 374 data_encipherment=False, 375 crl_sign=False, 376 encipher_only=False, 377 decipher_only=False, 378 ), 379 critical=True, 380 ) 381 .add_extension( 382 x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()), 383 critical=False, 384 ) 385 .sign(private_key, hashes.SHA256()) 386 ) 387 unlock_key = AppleUnlockKey.objects.create( 388 device_user=device_user, 389 private_key=private_key.private_bytes( 390 encoding=serialization.Encoding.PEM, 391 format=serialization.PrivateFormat.PKCS8, 392 encryption_algorithm=serialization.NoEncryption(), 393 ).decode(), 394 certificate_der=urlsafe_b64encode(cert.public_bytes(serialization.Encoding.DER)) 395 .rstrip(b"=") 396 .decode(), 397 expires=expires_at, 398 ) 399 LOGGER.debug("Created unlock key", key_context=unlock_key.identifier) 400 return JWEResponse( 401 { 402 "certificate": unlock_key.certificate_der, 403 "exp": int(expires_at.timestamp()), 404 "iat": int(self.now.timestamp()), 405 "key_context": str(unlock_key.identifier), 406 }, 407 device=self.device_connection, 408 apv=self.jwt_request["jwe_crypto"]["apv"], 409 typ="platformsso-key-response+jwt", 410 ) 411 412 def handle_key_exchange(self) -> HttpResponse: 413 auth_token = self.validate_refresh_token() 414 try: 415 key_context = UUID(self.jwt_request.get("key_context", "")) 416 except ValueError: 417 LOGGER.warning("Missing or invalid key_context in key exchange request") 418 return HttpResponse(status=400) 419 unlock_key = AppleUnlockKey.objects.filter( 420 identifier=key_context, 421 device_user__user=auth_token.user, 422 device_user__target=self.device_connection.device, 423 ).first() 424 if not unlock_key: 425 LOGGER.warning("No unlock key found for key_context", key_context=key_context) 426 return HttpResponse(status=400) 427 428 expires_at = self.now + timedelta_from_string(self.connector.auth_session_duration) 429 return JWEResponse( 430 { 431 "key": b64encode( 432 self.ecdh_shared_key( 433 unlock_key.private_key, self.jwt_request["other_publickey"] 434 ) 435 ).decode(), 436 "exp": int(expires_at.timestamp()), 437 "iat": int(self.now.timestamp()), 438 "key_context": str(unlock_key.identifier), 439 }, 440 device=self.device_connection, 441 apv=self.jwt_request["jwe_crypto"]["apv"], 442 typ="platformsso-key-response+jwt", 443 )
Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking.
device_connection: authentik.endpoints.connectors.agent.models.AgentDeviceConnection
def
dispatch( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
58 def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 59 # This is a plain Django View, so DRF's exception handler never runs and a 60 # ValidationError raised below would surface as a 500 instead of a 400. 61 try: 62 return super().dispatch(request, *args, **kwargs) 63 except ValidationError as exc: 64 LOGGER.warning("Invalid Platform SSO token request", exc=exc) 65 return HttpResponse(status=400)
def
post( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
67 def post(self, request: HttpRequest) -> HttpResponse: 68 assertion = request.POST.get("assertion", request.POST.get("request")) 69 if not assertion: 70 return HttpResponse(status=400) 71 self.now = now() 72 try: 73 self.jwt_request = self.validate_request_token(assertion) 74 except PyJWTError as exc: 75 LOGGER.warning("failed to parse JWT", exc=exc) 76 raise ValidationError("Invalid request") from exc 77 if self.jwt_request is None: 78 return HttpResponse(status=400) 79 version = request.POST.get("platform_sso_version") 80 grant_type = request.POST.get("grant_type") 81 handler_func = ( 82 f"handle_v{version}_{grant_type}".replace("-", "_") 83 .replace("+", "_") 84 .replace(":", "_") 85 .replace(".", "_") 86 ) 87 handler = getattr(self, handler_func, None) 88 if not handler: 89 LOGGER.debug("Handler not found", handler=handler_func) 90 return HttpResponse(status=400) 91 LOGGER.debug("sending to handler", handler=handler_func) 92 return handler()
def
validate_request_token(self, assertion: str) -> dict[str, Any] | None:
94 def validate_request_token(self, assertion: str) -> dict[str, Any] | None: 95 # Decode without validation to get header 96 header = get_unverified_header(assertion) 97 expected_kid = header["kid"] 98 LOGGER.debug("token header", typ=header.get("typ"), kid=expected_kid) 99 100 self.device_connection = ( 101 AgentDeviceConnection.objects.filter(apple_sign_key_id=expected_kid) 102 .select_related("device") 103 .first() 104 ) 105 if not self.device_connection: 106 LOGGER.warning("No device connection found for key ID", kid=expected_kid) 107 return None 108 self.connector = AgentConnector.objects.get(pk=self.device_connection.connector.pk) 109 if not self.device_connection.apple_signing_key: 110 LOGGER.warning("Failed to issue token for device, no apple_signing_key") 111 raise ValidationError("Invalid request") 112 113 kwargs = {"issuer": str(self.connector.pk)} 114 # Only login requests carry an audience claim, key requests/exchanges don't 115 if header["typ"] == "platformsso-login-request+jwt": 116 kwargs["audience"] = self.request.build_absolute_uri( 117 reverse("authentik_enterprise_endpoints_connectors_agent:psso-token") 118 ) 119 # Properly decode the JWT with the key from the device 120 decoded = decode( 121 assertion, self.device_connection.apple_signing_key, algorithms=["ES256"], **kwargs 122 ) 123 self.remote_nonce = decoded.get("nonce") 124 125 # Check that the nonce hasn't been used before 126 nonce = AppleNonce.objects.filter(nonce=decoded["request_nonce"]).first() 127 if not nonce: 128 raise ValidationError("Invalid nonce") 129 self.nonce = nonce 130 nonce.delete() 131 return decoded
def
validate_embedded_assertion( self, assertion: str) -> tuple[authentik.endpoints.connectors.agent.models.AgentDeviceUserBinding | authentik.endpoints.connectors.agent.models.AppleIndependentSecureEnclave, dict]:
133 def validate_embedded_assertion( 134 self, assertion: str 135 ) -> tuple[AgentDeviceUserBinding | AppleIndependentSecureEnclave, dict]: 136 """Decode an embedded assertion and validate it by looking up the matching device user""" 137 decode_unvalidated = get_unverified_header(assertion) 138 expected_kid = decode_unvalidated["kid"] 139 140 device_user = AgentDeviceUserBinding.objects.filter( 141 target=self.device_connection.device, apple_enclave_key_id=expected_kid 142 ).first() 143 if not device_user: 144 independent_user = AppleIndependentSecureEnclave.objects.filter( 145 apple_enclave_key_id=expected_kid 146 ).first() 147 if not independent_user: 148 LOGGER.warning("Could not find device user binding or independent enclave for user") 149 raise ValidationError("Invalid request") 150 device_user = independent_user 151 decoded: dict[str, Any] = decode( 152 assertion, 153 device_user.apple_secure_enclave_key, 154 audience=str(self.device_connection.device.pk), 155 algorithms=["ES256"], 156 ) 157 if decoded.get("nonce") != self.jwt_request.get("nonce"): 158 LOGGER.warning("Mis-matched nonce to outer assertion") 159 raise ValidationError("Invalid nonce") 160 return device_user, decoded
Decode an embedded assertion and validate it by looking up the matching device user
178 def create_auth_session(self, user: User): 179 event = Event.new( 180 EventAction.LOGIN, 181 app="authentik.endpoints.connectors.agent", 182 **{ 183 PLAN_CONTEXT_DEVICE: self.device_connection.device, 184 }, 185 ).from_http(self.request, user=user) 186 store = SessionStore() 187 store[SESSION_LOGIN_EVENT] = event 188 store.save() 189 session = Session.objects.filter(session_key=store.session_key).first() 190 session.expires = self.now + timedelta_from_string(self.connector.auth_session_duration) 191 AuthenticatedSession.objects.create(session=session, user=user) 192 session = SessionMiddleware.encode_session(store.session_key, user) 193 return session
195 def create_id_token(self, user: User, **kwargs): 196 claims = kwargs.pop("claims", {}) 197 # Only http(s) avatars are usable by the client, the initials fallback is an 198 # inline SVG data URI which macOS can't decode 199 avatar = user.avatar 200 if avatar.startswith(("http://", "https://")): 201 claims["picture"] = avatar 202 issuer = self.request.build_absolute_uri( 203 reverse("authentik_enterprise_endpoints_connectors_agent:psso-token") 204 ) 205 id_token = IDToken( 206 iss=issuer, 207 sub=str(user.uuid), 208 aud=str(self.connector.pk), 209 exp=int( 210 (self.now + timedelta_from_string(self.connector.auth_session_duration)).timestamp() 211 ), 212 iat=int(now().timestamp()), 213 claims=claims, 214 **kwargs, 215 ) 216 kp = CertificateKeyPair.objects.filter(managed=MANAGED_KEY).first() 217 return encode( 218 id_token.to_dict(), 219 kp.private_key, 220 headers={ 221 "kid": kp.kid, 222 }, 223 algorithm=JWTAlgorithms.from_private_key(kp.private_key), 224 )
def
login_response( self, user: authentik.core.models.User) -> authentik.enterprise.endpoints.connectors.agent.http.JWEResponse:
226 def login_response(self, user: User) -> JWEResponse: 227 """Build the shared login response for both the jwt-bearer and authorization_code 228 grants, optionally including the ECDH key material for lock-screen unlock.""" 229 auth_token = DeviceAuthenticationToken.objects.create( 230 device=self.device_connection.device, 231 connector=self.connector, 232 user=user, 233 device_token=self.nonce.device_token, 234 ) 235 body = { 236 "refresh_token": auth_token.token, 237 "refresh_token_expires_in": int((auth_token.expires - self.now).total_seconds()), 238 "id_token": self.create_id_token(user), 239 "token_type": TOKEN_TYPE, 240 "session_key": self.create_auth_session(user), 241 } 242 if "urn:apple:platformsso:auth:unlock" in self.jwt_request.get("scope", ""): 243 unlock_key = ( 244 AppleUnlockKey.objects.filter( 245 device_user__user=user, 246 device_user__target=self.device_connection.device, 247 ) 248 .order_by("-expires") 249 .first() 250 ) 251 other_publickey = self.jwt_request.get("other_publickey") 252 if not unlock_key or not other_publickey: 253 LOGGER.warning( 254 "auth:unlock requested without a provisioned key or public key", user=user 255 ) 256 else: 257 body["key"] = b64encode( 258 self.ecdh_shared_key(unlock_key.private_key, other_publickey) 259 ).decode() 260 body["key_context"] = str(unlock_key.identifier) 261 LOGGER.debug("Attached unlock key", key_context=unlock_key.identifier) 262 return JWEResponse( 263 body, 264 device=self.device_connection, 265 apv=self.jwt_request["jwe_crypto"]["apv"], 266 )
Build the shared login response for both the jwt-bearer and authorization_code grants, optionally including the ECDH key material for lock-screen unlock.
def
handle_v1_0_urn_ietf_params_oauth_grant_type_jwt_bearer(self) -> django.http.response.HttpResponse:
296 def handle_v1_0_urn_ietf_params_oauth_grant_type_jwt_bearer(self) -> HttpResponse: 297 if self.jwt_request.get("grant_type") == "urn:ietf:params:oauth:grant-type:token-exchange": 298 # Web login. The subject token is the callback URL the authorization endpoint 299 # redirected to, which carries the authorization code 300 query = parse_qs(urlparse(self.jwt_request.get("subject_token", "")).query) 301 return self.login_response(self.redeem_authorization_code(query.get("code", [""])[0])) 302 try: 303 device_user, _ = self.validate_embedded_assertion(self.jwt_request["assertion"]) 304 except PyJWTError as exc: 305 LOGGER.warning("failed to validate inner assertion", exc=exc) 306 raise ValidationError("Invalid request") from exc 307 return self.login_response(device_user.user)
def
handle_v2_0_urn_ietf_params_oauth_grant_type_jwt_bearer(self) -> django.http.response.HttpResponse:
312 def handle_v2_0_urn_ietf_params_oauth_grant_type_jwt_bearer(self) -> HttpResponse: 313 request_type = self.jwt_request.get("request_type") 314 LOGGER.debug("v2.0 request", request_type=request_type) 315 if request_type == "key_request": 316 return self.handle_key_request() 317 if request_type == "key_exchange": 318 return self.handle_key_exchange() 319 LOGGER.debug("Unknown request_type for v2.0", request_type=request_type) 320 return HttpResponse(status=400)
def
validate_refresh_token( self) -> authentik.endpoints.connectors.agent.models.DeviceAuthenticationToken:
322 def validate_refresh_token(self) -> DeviceAuthenticationToken: 323 auth_token = ( 324 DeviceAuthenticationToken.objects.filter( 325 token=self.jwt_request.get("refresh_token"), 326 device=self.device_connection.device, 327 ) 328 .select_related("user") 329 .first() 330 ) 331 if not auth_token: 332 raise ValidationError("Invalid refresh token") 333 return auth_token
def
handle_key_request(self) -> django.http.response.HttpResponse:
335 def handle_key_request(self) -> HttpResponse: 336 auth_token = self.validate_refresh_token() 337 device_user = AgentDeviceUserBinding.objects.filter( 338 target=self.device_connection.device, 339 user=auth_token.user, 340 ).first() 341 if not device_user: 342 LOGGER.warning("No device user binding found for key request") 343 return HttpResponse(status=400) 344 345 expires_at = self.now + timedelta_from_string(self.connector.auth_session_duration) 346 # Return the same certificate bytes for as long as the key is valid, so macOS sees an 347 # identical tokenID (SHA-1 of the public key) and doesn't attempt to rotate the key, 348 # which would require com.apple.PlatformSSO.login.service-xpc. 349 unlock_key = ( 350 AppleUnlockKey.objects.filter(device_user=device_user) 351 .exclude(certificate_der="") 352 .first() 353 ) 354 if unlock_key: 355 LOGGER.debug("Reusing unlock key", key_context=unlock_key.identifier) 356 else: 357 private_key = generate_private_key(SECP256R1()) 358 subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, auth_token.user.username)]) 359 cert = ( 360 x509.CertificateBuilder() 361 .subject_name(subject) 362 .issuer_name(subject) 363 .public_key(private_key.public_key()) 364 .serial_number(x509.random_serial_number()) 365 .not_valid_before(self.now) 366 .not_valid_after(expires_at) 367 .add_extension( 368 x509.KeyUsage( 369 digital_signature=True, 370 key_agreement=True, 371 key_cert_sign=False, 372 content_commitment=False, 373 key_encipherment=False, 374 data_encipherment=False, 375 crl_sign=False, 376 encipher_only=False, 377 decipher_only=False, 378 ), 379 critical=True, 380 ) 381 .add_extension( 382 x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()), 383 critical=False, 384 ) 385 .sign(private_key, hashes.SHA256()) 386 ) 387 unlock_key = AppleUnlockKey.objects.create( 388 device_user=device_user, 389 private_key=private_key.private_bytes( 390 encoding=serialization.Encoding.PEM, 391 format=serialization.PrivateFormat.PKCS8, 392 encryption_algorithm=serialization.NoEncryption(), 393 ).decode(), 394 certificate_der=urlsafe_b64encode(cert.public_bytes(serialization.Encoding.DER)) 395 .rstrip(b"=") 396 .decode(), 397 expires=expires_at, 398 ) 399 LOGGER.debug("Created unlock key", key_context=unlock_key.identifier) 400 return JWEResponse( 401 { 402 "certificate": unlock_key.certificate_der, 403 "exp": int(expires_at.timestamp()), 404 "iat": int(self.now.timestamp()), 405 "key_context": str(unlock_key.identifier), 406 }, 407 device=self.device_connection, 408 apv=self.jwt_request["jwe_crypto"]["apv"], 409 typ="platformsso-key-response+jwt", 410 )
def
handle_key_exchange(self) -> django.http.response.HttpResponse:
412 def handle_key_exchange(self) -> HttpResponse: 413 auth_token = self.validate_refresh_token() 414 try: 415 key_context = UUID(self.jwt_request.get("key_context", "")) 416 except ValueError: 417 LOGGER.warning("Missing or invalid key_context in key exchange request") 418 return HttpResponse(status=400) 419 unlock_key = AppleUnlockKey.objects.filter( 420 identifier=key_context, 421 device_user__user=auth_token.user, 422 device_user__target=self.device_connection.device, 423 ).first() 424 if not unlock_key: 425 LOGGER.warning("No unlock key found for key_context", key_context=key_context) 426 return HttpResponse(status=400) 427 428 expires_at = self.now + timedelta_from_string(self.connector.auth_session_duration) 429 return JWEResponse( 430 { 431 "key": b64encode( 432 self.ecdh_shared_key( 433 unlock_key.private_key, self.jwt_request["other_publickey"] 434 ) 435 ).decode(), 436 "exp": int(expires_at.timestamp()), 437 "iat": int(self.now.timestamp()), 438 "key_context": str(unlock_key.identifier), 439 }, 440 device=self.device_connection, 441 apv=self.jwt_request["jwe_crypto"]["apv"], 442 typ="platformsso-key-response+jwt", 443 )