authentik.stages.authenticator_validate.tests.test_webauthn
Test validator stage
1"""Test validator stage""" 2 3from time import sleep 4from unittest import skipIf 5from unittest.mock import patch 6 7from cryptography.hazmat.backends.openssl.backend import backend 8from django.urls.base import reverse 9from rest_framework.serializers import ValidationError 10from webauthn.helpers.base64url_to_bytes import base64url_to_bytes 11from webauthn.helpers.bytes_to_base64url import bytes_to_base64url 12from webauthn.helpers.cose import COSEAlgorithmIdentifier 13 14from authentik.core.tests.utils import RequestFactory, create_test_admin_user, create_test_flow 15from authentik.events.models import Event, EventAction 16from authentik.flows.models import Flow, FlowDesignation, FlowStageBinding, NotConfiguredAction 17from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan 18from authentik.flows.stage import StageView 19from authentik.flows.tests import APIFlowTestCase 20from authentik.flows.views.executor import SESSION_KEY_PLAN, FlowExecutorView 21from authentik.lib.generators import generate_id 22from authentik.stages.authenticator_validate.challenge import ( 23 get_challenge_for_device, 24 get_webauthn_challenge_without_user, 25 validate_challenge_webauthn, 26) 27from authentik.stages.authenticator_validate.models import AuthenticatorValidateStage, DeviceClasses 28from authentik.stages.authenticator_validate.stage import ( 29 PLAN_CONTEXT_DEVICE_CHALLENGES, 30 AuthenticatorValidateStageView, 31) 32from authentik.stages.authenticator_webauthn.models import ( 33 UserVerification, 34 WebAuthnDevice, 35 WebAuthnDeviceType, 36 WebAuthnHint, 37) 38from authentik.stages.authenticator_webauthn.stage import PLAN_CONTEXT_WEBAUTHN_CHALLENGE 39from authentik.stages.authenticator_webauthn.tasks import webauthn_mds_import 40from authentik.stages.authenticator_webauthn.tests.credentials import SoftwareCredential 41from authentik.stages.identification.models import IdentificationStage, UserFields 42from authentik.stages.user_login.models import UserLoginStage 43 44 45class AuthenticatorValidateStageWebAuthnTests(APIFlowTestCase): 46 """Test validator stage""" 47 48 def setUp(self) -> None: 49 self.user = create_test_admin_user() 50 self.request_factory = RequestFactory() 51 52 def test_last_auth_threshold(self): 53 """Test last_auth_threshold""" 54 ident_stage = IdentificationStage.objects.create( 55 name=generate_id(), 56 user_fields=[ 57 UserFields.USERNAME, 58 ], 59 ) 60 device: WebAuthnDevice = WebAuthnDevice.objects.create( 61 user=self.user, 62 confirmed=True, 63 ) 64 device.set_sign_count(device.sign_count + 1) 65 stage = AuthenticatorValidateStage.objects.create( 66 name=generate_id(), 67 last_auth_threshold="milliseconds=0", 68 not_configured_action=NotConfiguredAction.CONFIGURE, 69 device_classes=[DeviceClasses.WEBAUTHN], 70 ) 71 sleep(1) 72 stage.configuration_stages.set([ident_stage]) 73 flow = create_test_flow() 74 FlowStageBinding.objects.create(target=flow, stage=ident_stage, order=0) 75 FlowStageBinding.objects.create(target=flow, stage=stage, order=1) 76 77 response = self.client.post( 78 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 79 {"uid_field": self.user.username}, 80 ) 81 self.assertEqual(response.status_code, 302) 82 response = self.client.get( 83 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 84 follow=True, 85 ) 86 self.assertStageResponse( 87 response, 88 flow, 89 component="ak-stage-authenticator-validate", 90 ) 91 92 def test_device_challenge_webauthn(self): 93 """Test webauthn""" 94 request = self.request_factory.get("/") 95 request.user = self.user 96 97 webauthn_device = WebAuthnDevice.objects.create( 98 user=self.user, 99 public_key=bytes_to_base64url(b"qwerqwerqre"), 100 credential_id=bytes_to_base64url(b"foobarbaz"), 101 sign_count=0, 102 rp_id=generate_id(), 103 ) 104 stage = AuthenticatorValidateStage.objects.create( 105 name=generate_id(), 106 last_auth_threshold="milliseconds=0", 107 not_configured_action=NotConfiguredAction.CONFIGURE, 108 device_classes=[DeviceClasses.WEBAUTHN], 109 webauthn_user_verification=UserVerification.PREFERRED, 110 ) 111 plan = FlowPlan("") 112 stage_view = AuthenticatorValidateStageView( 113 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 114 ) 115 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 116 del challenge["challenge"] 117 self.assertEqual( 118 challenge, 119 { 120 "allowCredentials": [ 121 { 122 "id": "Zm9vYmFyYmF6", 123 "type": "public-key", 124 } 125 ], 126 "rpId": "testserver", 127 "timeout": 60000, 128 "userVerification": "preferred", 129 }, 130 ) 131 132 with self.assertRaises(ValidationError): 133 validate_challenge_webauthn( 134 {}, 135 StageView(FlowExecutorView(current_stage=stage, plan=plan), request=request), 136 self.user, 137 ) 138 139 def test_device_challenge_webauthn_restricted(self): 140 """Test webauthn (getting device challenges with a webauthn 141 device that is not allowed due to aaguid restrictions)""" 142 webauthn_mds_import.send(force=True).get_result() 143 request = self.request_factory.get("/") 144 request.user = self.user 145 146 WebAuthnDevice.objects.create( 147 user=self.user, 148 public_key=bytes_to_base64url(b"qwerqwerqre"), 149 credential_id=bytes_to_base64url(b"foobarbaz"), 150 sign_count=0, 151 rp_id=generate_id(), 152 device_type=WebAuthnDeviceType.objects.get( 153 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 154 ), 155 ) 156 flow = create_test_flow() 157 stage = AuthenticatorValidateStage.objects.create( 158 name=generate_id(), 159 last_auth_threshold="milliseconds=0", 160 not_configured_action=NotConfiguredAction.DENY, 161 device_classes=[DeviceClasses.WEBAUTHN], 162 webauthn_user_verification=UserVerification.PREFERRED, 163 ) 164 stage.webauthn_allowed_device_types.set( 165 WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series") 166 ) 167 session = self.client.session 168 plan = FlowPlan(flow_pk=flow.pk.hex) 169 plan.append_stage(stage) 170 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 171 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 172 session[SESSION_KEY_PLAN] = plan 173 session.save() 174 175 response = self.client.get( 176 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 177 ) 178 self.assertStageResponse( 179 response, 180 flow, 181 component="ak-stage-access-denied", 182 error_message="No (allowed) MFA authenticator configured.", 183 ) 184 185 def test_raw_get_challenge(self): 186 """Test webauthn""" 187 request = self.request_factory.get("/") 188 request.user = self.user 189 190 stage = AuthenticatorValidateStage.objects.create( 191 name=generate_id(), 192 last_auth_threshold="milliseconds=0", 193 not_configured_action=NotConfiguredAction.CONFIGURE, 194 device_classes=[DeviceClasses.WEBAUTHN], 195 webauthn_user_verification=UserVerification.PREFERRED, 196 ) 197 webauthn_device = WebAuthnDevice.objects.create( 198 user=self.user, 199 public_key=( 200 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 201 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 202 ), 203 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 204 sign_count=0, 205 rp_id=generate_id(), 206 ) 207 plan = FlowPlan("") 208 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 209 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 210 ) 211 stage_view = AuthenticatorValidateStageView( 212 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 213 ) 214 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 215 self.assertEqual( 216 challenge["allowCredentials"], 217 [ 218 { 219 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 220 "type": "public-key", 221 } 222 ], 223 ) 224 self.assertIsNotNone(challenge["challenge"]) 225 self.assertEqual( 226 challenge["rpId"], 227 "testserver", 228 ) 229 self.assertEqual( 230 challenge["timeout"], 231 60000, 232 ) 233 self.assertEqual( 234 challenge["userVerification"], 235 "preferred", 236 ) 237 238 def test_get_challenge_userless(self): 239 """Test webauthn (userless)""" 240 request = self.request_factory.get("/") 241 stage = AuthenticatorValidateStage.objects.create( 242 name=generate_id(), webauthn_user_verification=UserVerification.PREFERRED 243 ) 244 stage.refresh_from_db() 245 WebAuthnDevice.objects.create( 246 user=self.user, 247 public_key=( 248 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 249 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 250 ), 251 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 252 sign_count=0, 253 rp_id=generate_id(), 254 ) 255 plan = FlowPlan("") 256 stage_view = AuthenticatorValidateStageView( 257 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 258 ) 259 challenge = get_webauthn_challenge_without_user(stage_view, stage) 260 self.assertEqual(challenge["allowCredentials"], []) 261 self.assertIsNotNone(challenge["challenge"]) 262 self.assertEqual(challenge["rpId"], "testserver") 263 self.assertEqual(challenge["timeout"], 60000) 264 self.assertEqual(challenge["userVerification"], "preferred") 265 266 def test_device_challenge_webauthn_with_hints(self): 267 """Test that webauthn hints are included in authentication challenge""" 268 request = self.request_factory.get("/") 269 request.user = self.user 270 271 webauthn_device = WebAuthnDevice.objects.create( 272 user=self.user, 273 public_key=bytes_to_base64url(b"qwerqwerqre"), 274 credential_id=bytes_to_base64url(b"foobarbaz"), 275 sign_count=0, 276 rp_id=generate_id(), 277 ) 278 stage = AuthenticatorValidateStage.objects.create( 279 name=generate_id(), 280 last_auth_threshold="milliseconds=0", 281 not_configured_action=NotConfiguredAction.CONFIGURE, 282 device_classes=[DeviceClasses.WEBAUTHN], 283 webauthn_user_verification=UserVerification.PREFERRED, 284 webauthn_hints=[WebAuthnHint.CLIENT_DEVICE, WebAuthnHint.HYBRID], 285 ) 286 plan = FlowPlan("") 287 stage_view = AuthenticatorValidateStageView( 288 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 289 ) 290 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 291 self.assertEqual(challenge["hints"], ["client-device", "hybrid"]) 292 293 def test_device_challenge_webauthn_no_hints(self): 294 """Test that hints key is absent when no hints configured""" 295 request = self.request_factory.get("/") 296 request.user = self.user 297 298 webauthn_device = WebAuthnDevice.objects.create( 299 user=self.user, 300 public_key=bytes_to_base64url(b"qwerqwerqre"), 301 credential_id=bytes_to_base64url(b"foobarbaz"), 302 sign_count=0, 303 rp_id=generate_id(), 304 ) 305 stage = AuthenticatorValidateStage.objects.create( 306 name=generate_id(), 307 last_auth_threshold="milliseconds=0", 308 not_configured_action=NotConfiguredAction.CONFIGURE, 309 device_classes=[DeviceClasses.WEBAUTHN], 310 webauthn_user_verification=UserVerification.PREFERRED, 311 ) 312 plan = FlowPlan("") 313 stage_view = AuthenticatorValidateStageView( 314 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 315 ) 316 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 317 self.assertNotIn("hints", challenge) 318 319 def test_get_challenge_userless_with_hints(self): 320 """Test that hints are included in userless/passwordless challenge""" 321 request = self.request_factory.get("/") 322 stage = AuthenticatorValidateStage.objects.create( 323 name=generate_id(), 324 webauthn_user_verification=UserVerification.PREFERRED, 325 webauthn_hints=[WebAuthnHint.SECURITY_KEY, WebAuthnHint.CLIENT_DEVICE], 326 ) 327 plan = FlowPlan("") 328 stage_view = AuthenticatorValidateStageView( 329 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 330 ) 331 challenge = get_webauthn_challenge_without_user(stage_view, stage) 332 self.assertEqual(challenge["hints"], ["security-key", "client-device"]) 333 334 def test_device_challenge_webauthn_hints_order_preserved(self): 335 """Test that hint order is preserved in authentication challenge""" 336 request = self.request_factory.get("/") 337 request.user = self.user 338 339 webauthn_device = WebAuthnDevice.objects.create( 340 user=self.user, 341 public_key=bytes_to_base64url(b"qwerqwerqre"), 342 credential_id=bytes_to_base64url(b"foobarbaz"), 343 sign_count=0, 344 rp_id=generate_id(), 345 ) 346 stage = AuthenticatorValidateStage.objects.create( 347 name=generate_id(), 348 last_auth_threshold="milliseconds=0", 349 not_configured_action=NotConfiguredAction.CONFIGURE, 350 device_classes=[DeviceClasses.WEBAUTHN], 351 webauthn_user_verification=UserVerification.PREFERRED, 352 webauthn_hints=[ 353 WebAuthnHint.HYBRID, 354 WebAuthnHint.SECURITY_KEY, 355 WebAuthnHint.CLIENT_DEVICE, 356 ], 357 ) 358 plan = FlowPlan("") 359 stage_view = AuthenticatorValidateStageView( 360 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 361 ) 362 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 363 self.assertEqual(challenge["hints"], ["hybrid", "security-key", "client-device"]) 364 365 def test_validate_challenge_unrestricted(self): 366 """Test webauthn authentication (unrestricted webauthn device)""" 367 webauthn_mds_import.send(force=True).get_result() 368 device = WebAuthnDevice.objects.create( 369 user=self.user, 370 public_key=( 371 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FFIlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 372 ), 373 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 374 sign_count=2, 375 rp_id=generate_id(), 376 device_type=WebAuthnDeviceType.objects.get( 377 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 378 ), 379 ) 380 flow = create_test_flow() 381 stage = AuthenticatorValidateStage.objects.create( 382 name=generate_id(), 383 not_configured_action=NotConfiguredAction.CONFIGURE, 384 device_classes=[DeviceClasses.WEBAUTHN], 385 ) 386 session = self.client.session 387 plan = FlowPlan(flow_pk=flow.pk.hex) 388 plan.append_stage(stage) 389 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 390 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 391 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 392 { 393 "device_class": device.__class__.__name__.lower().replace("device", ""), 394 "device_uid": device.pk, 395 "challenge": {}, 396 "last_used": None, 397 } 398 ] 399 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 400 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 401 ) 402 session[SESSION_KEY_PLAN] = plan 403 session.save() 404 405 response = self.client.post( 406 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 407 data={ 408 "webauthn": { 409 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 410 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 411 "type": "public-key", 412 "assertionClientExtensions": "{}", 413 "response": { 414 "clientDataJSON": ( 415 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 416 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 417 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 418 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 419 "cm9zc09yaWdpbiI6ZmFsc2V9" 420 ), 421 "signature": ( 422 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 423 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 424 ), 425 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 426 "userHandle": None, 427 }, 428 }, 429 }, 430 SERVER_NAME="localhost", 431 SERVER_PORT="9000", 432 ) 433 self.assertEqual(response.status_code, 302) 434 response = self.client.get( 435 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 436 ) 437 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 438 439 def test_validate_challenge_restricted(self): 440 """Test webauthn authentication (restricted device type, failure)""" 441 webauthn_mds_import.send(force=True).get_result() 442 device = WebAuthnDevice.objects.create( 443 user=self.user, 444 public_key=( 445 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FFIlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 446 ), 447 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 448 sign_count=2, 449 rp_id=generate_id(), 450 device_type=WebAuthnDeviceType.objects.get( 451 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 452 ), 453 ) 454 flow = create_test_flow() 455 stage = AuthenticatorValidateStage.objects.create( 456 name=generate_id(), 457 not_configured_action=NotConfiguredAction.CONFIGURE, 458 device_classes=[DeviceClasses.WEBAUTHN], 459 ) 460 stage.webauthn_allowed_device_types.set( 461 WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series") 462 ) 463 session = self.client.session 464 plan = FlowPlan(flow_pk=flow.pk.hex) 465 plan.append_stage(stage) 466 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 467 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 468 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 469 { 470 "device_class": device.__class__.__name__.lower().replace("device", ""), 471 "device_uid": device.pk, 472 "challenge": {}, 473 "last_used": None, 474 } 475 ] 476 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 477 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 478 ) 479 session[SESSION_KEY_PLAN] = plan 480 session.save() 481 482 response = self.client.post( 483 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 484 data={ 485 "webauthn": { 486 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 487 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 488 "type": "public-key", 489 "assertionClientExtensions": "{}", 490 "response": { 491 "clientDataJSON": ( 492 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 493 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 494 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 495 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 496 "cm9zc09yaWdpbiI6ZmFsc2V9" 497 ), 498 "signature": ( 499 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 500 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 501 ), 502 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 503 "userHandle": None, 504 }, 505 } 506 }, 507 SERVER_NAME="localhost", 508 SERVER_PORT="9000", 509 ) 510 self.assertEqual(response.status_code, 200) 511 self.assertStageResponse( 512 response, 513 flow, 514 component="ak-stage-authenticator-validate", 515 response_errors={ 516 "webauthn": [ 517 { 518 "string": ( 519 "Invalid device type. Contact your authentik administrator for help." 520 ), 521 "code": "invalid", 522 } 523 ] 524 }, 525 ) 526 527 def test_validate_challenge_malformed(self): 528 """Test that an assertion whose fields can't be decoded is rejected as an invalid 529 device""" 530 flow = create_test_flow() 531 stage = AuthenticatorValidateStage.objects.create( 532 name=generate_id(), 533 not_configured_action=NotConfiguredAction.CONFIGURE, 534 device_classes=[DeviceClasses.WEBAUTHN], 535 ) 536 plan = FlowPlan(flow.pk.hex) 537 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b"\x01" * 64 538 stage_view = AuthenticatorValidateStageView( 539 FlowExecutorView(flow=flow, current_stage=stage, plan=plan), 540 request=self.request_factory.get("/"), 541 ) 542 for field, value in ( 543 ("rawId", "a"), 544 ("clientDataJSON", "a"), 545 ("authenticatorData", "a"), 546 ("signature", "\u00e9"), 547 ("userHandle", "a"), 548 ("userHandle", "\u00e9"), 549 ): 550 assertion = { 551 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 552 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 553 "type": "public-key", 554 "response": { 555 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0", 556 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ", 557 "signature": "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI", 558 "userHandle": None, 559 }, 560 } 561 if field == "rawId": 562 assertion[field] = value 563 else: 564 assertion["response"][field] = value 565 with self.subTest(field=field, value=value): 566 with self.assertRaises(ValidationError) as cm: 567 validate_challenge_webauthn(assertion, stage_view, self.user) 568 self.assertEqual(str(cm.exception.detail[0]), "Invalid device") 569 self.assertEqual(cm.exception.detail[0].code, "invalid") 570 571 def test_validate_challenge_malformed_userless(self): 572 """Test that a malformed assertion in a passwordless flow gets a validation error""" 573 flow = create_test_flow(FlowDesignation.AUTHENTICATION) 574 stage = AuthenticatorValidateStage.objects.create( 575 name=generate_id(), 576 not_configured_action=NotConfiguredAction.DENY, 577 device_classes=[DeviceClasses.WEBAUTHN], 578 ) 579 FlowStageBinding.objects.create(target=flow, stage=stage, order=0) 580 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 581 response = self.client.get(url) 582 self.assertStageResponse(response, flow, component="ak-stage-authenticator-validate") 583 584 response = self.client.post( 585 url, 586 data={ 587 "webauthn": { 588 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 589 "rawId": "a", 590 "type": "public-key", 591 "response": { 592 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0", 593 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ", 594 "signature": "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI", 595 "userHandle": None, 596 }, 597 }, 598 }, 599 ) 600 self.assertStageResponse( 601 response, 602 flow, 603 component="ak-stage-authenticator-validate", 604 response_errors={"webauthn": [{"string": "Invalid device", "code": "invalid"}]}, 605 ) 606 607 def test_validate_challenge_userless(self): 608 """Test webauthn""" 609 device = WebAuthnDevice.objects.create( 610 user=self.user, 611 public_key=( 612 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 613 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 614 ), 615 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 616 sign_count=4, 617 rp_id=generate_id(), 618 ) 619 flow = create_test_flow() 620 stage = AuthenticatorValidateStage.objects.create( 621 name=generate_id(), 622 not_configured_action=NotConfiguredAction.CONFIGURE, 623 device_classes=[DeviceClasses.WEBAUTHN], 624 ) 625 session = self.client.session 626 plan = FlowPlan(flow_pk=flow.pk.hex) 627 plan.append_stage(stage) 628 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 629 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 630 { 631 "device_class": device.__class__.__name__.lower().replace("device", ""), 632 "device_uid": device.pk, 633 "challenge": {}, 634 "last_used": None, 635 } 636 ] 637 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 638 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 639 ) 640 session[SESSION_KEY_PLAN] = plan 641 session.save() 642 643 response = self.client.post( 644 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 645 data={ 646 "webauthn": { 647 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 648 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 649 "type": "public-key", 650 "assertionClientExtensions": "{}", 651 "response": { 652 "clientDataJSON": ( 653 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2Wlhv" 654 "NWx4TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGcz" 655 "QWdPNFdoLUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9j" 656 "YWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2Fu" 657 "X2JlX2FkZGVkX2hlcmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBh" 658 "Z2FpbnN0IGEgdGVtcGxhdGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 659 ), 660 "signature": ( 661 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 662 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 663 ), 664 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 665 "userHandle": None, 666 }, 667 }, 668 }, 669 SERVER_NAME="localhost", 670 SERVER_PORT="9000", 671 ) 672 self.assertEqual(response.status_code, 302) 673 response = self.client.get( 674 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 675 ) 676 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 677 678 def test_validate_challenge_single_use(self): 679 """Test that a challenge is removed after an assertion verifies""" 680 device = WebAuthnDevice.objects.create( 681 user=self.user, 682 public_key=( 683 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FF" 684 "IlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 685 ), 686 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 687 sign_count=2, 688 rp_id=generate_id(), 689 ) 690 stage = AuthenticatorValidateStage.objects.create( 691 name=generate_id(), 692 not_configured_action=NotConfiguredAction.CONFIGURE, 693 device_classes=[DeviceClasses.WEBAUTHN], 694 ) 695 plan = FlowPlan("") 696 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 697 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 698 ) 699 request = self.request_factory.post("/", SERVER_NAME="localhost", SERVER_PORT="9000") 700 request.user = self.user 701 stage_view = StageView(FlowExecutorView(current_stage=stage, plan=plan), request=request) 702 assertion = { 703 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 704 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 705 "type": "public-key", 706 "assertionClientExtensions": "{}", 707 "response": { 708 "clientDataJSON": ( 709 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 710 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 711 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 712 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 713 "cm9zc09yaWdpbiI6ZmFsc2V9" 714 ), 715 "signature": ( 716 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 717 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 718 ), 719 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 720 "userHandle": None, 721 }, 722 } 723 724 self.assertEqual(validate_challenge_webauthn(assertion, stage_view, self.user), device) 725 self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context) 726 727 def test_validate_challenge_invalid(self): 728 """Test webauthn""" 729 request = self.request_factory.get("/") 730 request.user = self.user 731 732 WebAuthnDevice.objects.create( 733 user=self.user, 734 public_key=( 735 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc4" 736 "3i0JH6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 737 ), 738 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 739 # One more sign count than above, make it invalid 740 sign_count=5, 741 rp_id=generate_id(), 742 ) 743 flow = create_test_flow() 744 stage = AuthenticatorValidateStage.objects.create( 745 name=generate_id(), 746 not_configured_action=NotConfiguredAction.CONFIGURE, 747 device_classes=[DeviceClasses.WEBAUTHN], 748 ) 749 plan = FlowPlan(flow.pk.hex) 750 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 751 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 752 ) 753 request = self.request_factory.get("/") 754 755 stage_view = AuthenticatorValidateStageView( 756 FlowExecutorView(flow=flow, current_stage=stage, plan=plan), request=request 757 ) 758 request.META["SERVER_NAME"] = "localhost" 759 request.META["SERVER_PORT"] = "9000" 760 with self.assertRaises(ValidationError): 761 validate_challenge_webauthn( 762 { 763 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 764 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 765 "type": "public-key", 766 "assertionClientExtensions": "{}", 767 "response": { 768 "clientDataJSON": ( 769 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2WlhvNWx4" 770 "TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGczQWdPNFdo" 771 "LUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0Ojkw" 772 "MDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2FuX2JlX2FkZGVkX2hl" 773 "cmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBhZ2FpbnN0IGEgdGVtcGxh" 774 "dGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 775 ), 776 "signature": ( 777 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 778 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 779 ), 780 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 781 "userHandle": None, 782 }, 783 }, 784 stage_view, 785 self.user, 786 ) 787 788 def _validate_unavailable_algorithm( 789 self, alg: COSEAlgorithmIdentifier, public_key_class: str, fips_enabled: bool 790 ) -> str: 791 """Authenticate with a credential whose public key cryptography refuses to load, as it 792 does for Ed25519 and ML-DSA under the validated OpenSSL FIPS provider""" 793 credential = SoftwareCredential(rp_id="localhost", origin="http://localhost:9000", alg=alg) 794 device = WebAuthnDevice.objects.create( 795 user=self.user, 796 public_key=bytes_to_base64url(credential.cose_public_key), 797 credential_id=bytes_to_base64url(credential.credential_id), 798 sign_count=0, 799 rp_id="localhost", 800 ) 801 flow = create_test_flow() 802 stage = AuthenticatorValidateStage.objects.create( 803 name=generate_id(), 804 not_configured_action=NotConfiguredAction.CONFIGURE, 805 device_classes=[DeviceClasses.WEBAUTHN], 806 ) 807 challenge = b"\x03" * 64 808 plan = FlowPlan(flow.pk.hex) 809 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge 810 request = self.request_factory.get("/") 811 request.META["SERVER_NAME"] = "localhost" 812 request.META["SERVER_PORT"] = "9000" 813 stage_view = AuthenticatorValidateStageView( 814 FlowExecutorView(flow=flow, current_stage=stage, plan=plan), request=request 815 ) 816 with ( 817 patch( 818 f"webauthn.helpers.decoded_public_key_to_cryptography.{public_key_class}." 819 "from_public_bytes", 820 side_effect=ValueError(f"An {public_key_class} is 32 bytes long"), 821 ), 822 patch( 823 "authentik.stages.authenticator_validate.challenge.backend._fips_enabled", 824 fips_enabled, 825 ), 826 self.assertRaises(ValidationError) as cm, 827 ): 828 validate_challenge_webauthn( 829 credential.assertion_response(challenge), stage_view, self.user 830 ) 831 # The user sees a generic error; the details go to the log and the event 832 self.assertEqual( 833 str(cm.exception.detail[0]), 834 "Invalid security key. Please re-register or contact an administrator.", 835 ) 836 event = Event.objects.filter( 837 action=EventAction.LOGIN_FAILED, context__stage__pk=stage.pk.hex 838 ).first() 839 self.assertIsNotNone(event) 840 self.assertEqual(event.context["fips_enabled"], fips_enabled) 841 self.assertIn(event.context["algorithm"], ("EdDSA (Ed25519)", "ML-DSA-44")) 842 device.refresh_from_db() 843 self.assertEqual(device.sign_count, 0) 844 return event.context["message"] 845 846 @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519") 847 def test_validate_challenge_unavailable_algorithm_eddsa(self): 848 """cryptography raises its misleading key-length ValueError directly for Ed25519; 849 with FIPS enabled the event names the key type and FIPS""" 850 detail = self._validate_unavailable_algorithm( 851 COSEAlgorithmIdentifier.EDDSA, "Ed25519PublicKey", fips_enabled=True 852 ) 853 self.assertEqual( 854 detail, "Cannot log in with EdDSA (Ed25519) security key while FIPS mode is enabled" 855 ) 856 857 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 858 def test_validate_challenge_unavailable_algorithm_mldsa(self): 859 """py_webauthn wraps the ML-DSA failure in its own UnsupportedPublicKey; without FIPS 860 the event still names the key type""" 861 detail = self._validate_unavailable_algorithm( 862 COSEAlgorithmIdentifier.ML_DSA_44, "MLDSA44PublicKey", fips_enabled=False 863 ) 864 self.assertEqual( 865 detail, 866 "Cannot log in with ML-DSA-44 security key: the key type is not available in the " 867 "current OpenSSL configuration", 868 ) 869 870 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 871 def test_validate_challenge_mldsa(self): 872 """Test webauthn authentication with an ML-DSA-44 (FIPS 204) credential""" 873 credential = SoftwareCredential(rp_id="localhost", origin="http://localhost:9000") 874 device = WebAuthnDevice.objects.create( 875 user=self.user, 876 public_key=bytes_to_base64url(credential.cose_public_key), 877 credential_id=bytes_to_base64url(credential.credential_id), 878 sign_count=0, 879 rp_id="localhost", 880 ) 881 flow = create_test_flow() 882 stage = AuthenticatorValidateStage.objects.create( 883 name=generate_id(), 884 not_configured_action=NotConfiguredAction.CONFIGURE, 885 device_classes=[DeviceClasses.WEBAUTHN], 886 ) 887 challenge = b"\x02" * 64 888 session = self.client.session 889 plan = FlowPlan(flow_pk=flow.pk.hex) 890 plan.append_stage(stage) 891 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 892 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 893 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 894 { 895 "device_class": device.__class__.__name__.lower().replace("device", ""), 896 "device_uid": device.pk, 897 "challenge": {}, 898 "last_used": None, 899 } 900 ] 901 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge 902 session[SESSION_KEY_PLAN] = plan 903 session.save() 904 905 response = self.client.post( 906 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 907 data={"webauthn": credential.assertion_response(challenge)}, 908 SERVER_NAME="localhost", 909 SERVER_PORT="9000", 910 ) 911 self.assertEqual(response.status_code, 302) 912 response = self.client.get( 913 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 914 ) 915 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 916 device.refresh_from_db() 917 self.assertEqual(device.sign_count, 1) 918 919 def _plan_at_webauthn_stage(self, pending_user: bool = True) -> Flow: 920 """Create a flow with its plan stored in the session, currently at a WebAuthn 921 validation stage""" 922 WebAuthnDevice.objects.create( 923 user=self.user, 924 public_key=( 925 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 926 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 927 ), 928 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 929 sign_count=4, 930 rp_id=generate_id(), 931 ) 932 flow = create_test_flow(FlowDesignation.AUTHENTICATION) 933 stage = AuthenticatorValidateStage.objects.create( 934 name=generate_id(), 935 not_configured_action=NotConfiguredAction.DENY, 936 device_classes=[DeviceClasses.WEBAUTHN], 937 ) 938 session = self.client.session 939 plan = FlowPlan(flow_pk=flow.pk.hex) 940 plan.append_stage(stage) 941 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 942 if pending_user: 943 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 944 session[SESSION_KEY_PLAN] = plan 945 session.save() 946 return flow 947 948 def _render_stage(self, flow: Flow) -> dict: 949 response = self.client.get( 950 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 951 SERVER_NAME="localhost", 952 SERVER_PORT="9000", 953 ) 954 self.assertStageResponse(response, flow, component="ak-stage-authenticator-validate") 955 return self.client.session[SESSION_KEY_PLAN].context 956 957 def test_render_reuses_webauthn_challenge(self): 958 """Test that rendering the stage again doesn't replace the pending challenge""" 959 flow = self._plan_at_webauthn_stage() 960 961 first = self._render_stage(flow) 962 second = self._render_stage(flow) 963 964 self.assertIsNotNone(first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]) 965 self.assertEqual( 966 first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE], second[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] 967 ) 968 self.assertEqual( 969 first[PLAN_CONTEXT_DEVICE_CHALLENGES], second[PLAN_CONTEXT_DEVICE_CHALLENGES] 970 ) 971 972 def test_render_reuses_webauthn_challenge_userless(self): 973 """Test that rendering the stage again doesn't replace the pending challenge 974 (user-less)""" 975 flow = self._plan_at_webauthn_stage(pending_user=False) 976 977 first = self._render_stage(flow) 978 second = self._render_stage(flow) 979 980 self.assertIsNotNone(first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]) 981 self.assertEqual( 982 first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE], second[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] 983 ) 984 985 def test_validate_challenge_after_render(self): 986 """Test that a response to a challenge is still accepted after the stage was 987 rendered again (e.g. by another tab), and that the challenge can't be answered 988 again afterwards""" 989 flow = self._plan_at_webauthn_stage() 990 session = self.client.session 991 plan: FlowPlan = session[SESSION_KEY_PLAN] 992 # The challenge the assertion below was signed for 993 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 994 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 995 ) 996 session[SESSION_KEY_PLAN] = plan 997 session.save() 998 999 # Render the stage twice, e.g. the original tab and another tab 1000 self._render_stage(flow) 1001 self._render_stage(flow) 1002 1003 response = self.client.post( 1004 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 1005 data={ 1006 "webauthn": { 1007 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 1008 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 1009 "type": "public-key", 1010 "assertionClientExtensions": "{}", 1011 "response": { 1012 "clientDataJSON": ( 1013 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2Wlhv" 1014 "NWx4TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGcz" 1015 "QWdPNFdoLUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9j" 1016 "YWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2Fu" 1017 "X2JlX2FkZGVkX2hlcmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBh" 1018 "Z2FpbnN0IGEgdGVtcGxhdGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 1019 ), 1020 "signature": ( 1021 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 1022 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 1023 ), 1024 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 1025 "userHandle": None, 1026 }, 1027 }, 1028 }, 1029 SERVER_NAME="localhost", 1030 SERVER_PORT="9000", 1031 ) 1032 self.assertEqual(response.status_code, 302) 1033 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 1034 self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context)
46class AuthenticatorValidateStageWebAuthnTests(APIFlowTestCase): 47 """Test validator stage""" 48 49 def setUp(self) -> None: 50 self.user = create_test_admin_user() 51 self.request_factory = RequestFactory() 52 53 def test_last_auth_threshold(self): 54 """Test last_auth_threshold""" 55 ident_stage = IdentificationStage.objects.create( 56 name=generate_id(), 57 user_fields=[ 58 UserFields.USERNAME, 59 ], 60 ) 61 device: WebAuthnDevice = WebAuthnDevice.objects.create( 62 user=self.user, 63 confirmed=True, 64 ) 65 device.set_sign_count(device.sign_count + 1) 66 stage = AuthenticatorValidateStage.objects.create( 67 name=generate_id(), 68 last_auth_threshold="milliseconds=0", 69 not_configured_action=NotConfiguredAction.CONFIGURE, 70 device_classes=[DeviceClasses.WEBAUTHN], 71 ) 72 sleep(1) 73 stage.configuration_stages.set([ident_stage]) 74 flow = create_test_flow() 75 FlowStageBinding.objects.create(target=flow, stage=ident_stage, order=0) 76 FlowStageBinding.objects.create(target=flow, stage=stage, order=1) 77 78 response = self.client.post( 79 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 80 {"uid_field": self.user.username}, 81 ) 82 self.assertEqual(response.status_code, 302) 83 response = self.client.get( 84 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 85 follow=True, 86 ) 87 self.assertStageResponse( 88 response, 89 flow, 90 component="ak-stage-authenticator-validate", 91 ) 92 93 def test_device_challenge_webauthn(self): 94 """Test webauthn""" 95 request = self.request_factory.get("/") 96 request.user = self.user 97 98 webauthn_device = WebAuthnDevice.objects.create( 99 user=self.user, 100 public_key=bytes_to_base64url(b"qwerqwerqre"), 101 credential_id=bytes_to_base64url(b"foobarbaz"), 102 sign_count=0, 103 rp_id=generate_id(), 104 ) 105 stage = AuthenticatorValidateStage.objects.create( 106 name=generate_id(), 107 last_auth_threshold="milliseconds=0", 108 not_configured_action=NotConfiguredAction.CONFIGURE, 109 device_classes=[DeviceClasses.WEBAUTHN], 110 webauthn_user_verification=UserVerification.PREFERRED, 111 ) 112 plan = FlowPlan("") 113 stage_view = AuthenticatorValidateStageView( 114 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 115 ) 116 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 117 del challenge["challenge"] 118 self.assertEqual( 119 challenge, 120 { 121 "allowCredentials": [ 122 { 123 "id": "Zm9vYmFyYmF6", 124 "type": "public-key", 125 } 126 ], 127 "rpId": "testserver", 128 "timeout": 60000, 129 "userVerification": "preferred", 130 }, 131 ) 132 133 with self.assertRaises(ValidationError): 134 validate_challenge_webauthn( 135 {}, 136 StageView(FlowExecutorView(current_stage=stage, plan=plan), request=request), 137 self.user, 138 ) 139 140 def test_device_challenge_webauthn_restricted(self): 141 """Test webauthn (getting device challenges with a webauthn 142 device that is not allowed due to aaguid restrictions)""" 143 webauthn_mds_import.send(force=True).get_result() 144 request = self.request_factory.get("/") 145 request.user = self.user 146 147 WebAuthnDevice.objects.create( 148 user=self.user, 149 public_key=bytes_to_base64url(b"qwerqwerqre"), 150 credential_id=bytes_to_base64url(b"foobarbaz"), 151 sign_count=0, 152 rp_id=generate_id(), 153 device_type=WebAuthnDeviceType.objects.get( 154 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 155 ), 156 ) 157 flow = create_test_flow() 158 stage = AuthenticatorValidateStage.objects.create( 159 name=generate_id(), 160 last_auth_threshold="milliseconds=0", 161 not_configured_action=NotConfiguredAction.DENY, 162 device_classes=[DeviceClasses.WEBAUTHN], 163 webauthn_user_verification=UserVerification.PREFERRED, 164 ) 165 stage.webauthn_allowed_device_types.set( 166 WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series") 167 ) 168 session = self.client.session 169 plan = FlowPlan(flow_pk=flow.pk.hex) 170 plan.append_stage(stage) 171 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 172 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 173 session[SESSION_KEY_PLAN] = plan 174 session.save() 175 176 response = self.client.get( 177 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 178 ) 179 self.assertStageResponse( 180 response, 181 flow, 182 component="ak-stage-access-denied", 183 error_message="No (allowed) MFA authenticator configured.", 184 ) 185 186 def test_raw_get_challenge(self): 187 """Test webauthn""" 188 request = self.request_factory.get("/") 189 request.user = self.user 190 191 stage = AuthenticatorValidateStage.objects.create( 192 name=generate_id(), 193 last_auth_threshold="milliseconds=0", 194 not_configured_action=NotConfiguredAction.CONFIGURE, 195 device_classes=[DeviceClasses.WEBAUTHN], 196 webauthn_user_verification=UserVerification.PREFERRED, 197 ) 198 webauthn_device = WebAuthnDevice.objects.create( 199 user=self.user, 200 public_key=( 201 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 202 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 203 ), 204 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 205 sign_count=0, 206 rp_id=generate_id(), 207 ) 208 plan = FlowPlan("") 209 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 210 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 211 ) 212 stage_view = AuthenticatorValidateStageView( 213 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 214 ) 215 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 216 self.assertEqual( 217 challenge["allowCredentials"], 218 [ 219 { 220 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 221 "type": "public-key", 222 } 223 ], 224 ) 225 self.assertIsNotNone(challenge["challenge"]) 226 self.assertEqual( 227 challenge["rpId"], 228 "testserver", 229 ) 230 self.assertEqual( 231 challenge["timeout"], 232 60000, 233 ) 234 self.assertEqual( 235 challenge["userVerification"], 236 "preferred", 237 ) 238 239 def test_get_challenge_userless(self): 240 """Test webauthn (userless)""" 241 request = self.request_factory.get("/") 242 stage = AuthenticatorValidateStage.objects.create( 243 name=generate_id(), webauthn_user_verification=UserVerification.PREFERRED 244 ) 245 stage.refresh_from_db() 246 WebAuthnDevice.objects.create( 247 user=self.user, 248 public_key=( 249 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 250 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 251 ), 252 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 253 sign_count=0, 254 rp_id=generate_id(), 255 ) 256 plan = FlowPlan("") 257 stage_view = AuthenticatorValidateStageView( 258 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 259 ) 260 challenge = get_webauthn_challenge_without_user(stage_view, stage) 261 self.assertEqual(challenge["allowCredentials"], []) 262 self.assertIsNotNone(challenge["challenge"]) 263 self.assertEqual(challenge["rpId"], "testserver") 264 self.assertEqual(challenge["timeout"], 60000) 265 self.assertEqual(challenge["userVerification"], "preferred") 266 267 def test_device_challenge_webauthn_with_hints(self): 268 """Test that webauthn hints are included in authentication challenge""" 269 request = self.request_factory.get("/") 270 request.user = self.user 271 272 webauthn_device = WebAuthnDevice.objects.create( 273 user=self.user, 274 public_key=bytes_to_base64url(b"qwerqwerqre"), 275 credential_id=bytes_to_base64url(b"foobarbaz"), 276 sign_count=0, 277 rp_id=generate_id(), 278 ) 279 stage = AuthenticatorValidateStage.objects.create( 280 name=generate_id(), 281 last_auth_threshold="milliseconds=0", 282 not_configured_action=NotConfiguredAction.CONFIGURE, 283 device_classes=[DeviceClasses.WEBAUTHN], 284 webauthn_user_verification=UserVerification.PREFERRED, 285 webauthn_hints=[WebAuthnHint.CLIENT_DEVICE, WebAuthnHint.HYBRID], 286 ) 287 plan = FlowPlan("") 288 stage_view = AuthenticatorValidateStageView( 289 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 290 ) 291 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 292 self.assertEqual(challenge["hints"], ["client-device", "hybrid"]) 293 294 def test_device_challenge_webauthn_no_hints(self): 295 """Test that hints key is absent when no hints configured""" 296 request = self.request_factory.get("/") 297 request.user = self.user 298 299 webauthn_device = WebAuthnDevice.objects.create( 300 user=self.user, 301 public_key=bytes_to_base64url(b"qwerqwerqre"), 302 credential_id=bytes_to_base64url(b"foobarbaz"), 303 sign_count=0, 304 rp_id=generate_id(), 305 ) 306 stage = AuthenticatorValidateStage.objects.create( 307 name=generate_id(), 308 last_auth_threshold="milliseconds=0", 309 not_configured_action=NotConfiguredAction.CONFIGURE, 310 device_classes=[DeviceClasses.WEBAUTHN], 311 webauthn_user_verification=UserVerification.PREFERRED, 312 ) 313 plan = FlowPlan("") 314 stage_view = AuthenticatorValidateStageView( 315 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 316 ) 317 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 318 self.assertNotIn("hints", challenge) 319 320 def test_get_challenge_userless_with_hints(self): 321 """Test that hints are included in userless/passwordless challenge""" 322 request = self.request_factory.get("/") 323 stage = AuthenticatorValidateStage.objects.create( 324 name=generate_id(), 325 webauthn_user_verification=UserVerification.PREFERRED, 326 webauthn_hints=[WebAuthnHint.SECURITY_KEY, WebAuthnHint.CLIENT_DEVICE], 327 ) 328 plan = FlowPlan("") 329 stage_view = AuthenticatorValidateStageView( 330 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 331 ) 332 challenge = get_webauthn_challenge_without_user(stage_view, stage) 333 self.assertEqual(challenge["hints"], ["security-key", "client-device"]) 334 335 def test_device_challenge_webauthn_hints_order_preserved(self): 336 """Test that hint order is preserved in authentication challenge""" 337 request = self.request_factory.get("/") 338 request.user = self.user 339 340 webauthn_device = WebAuthnDevice.objects.create( 341 user=self.user, 342 public_key=bytes_to_base64url(b"qwerqwerqre"), 343 credential_id=bytes_to_base64url(b"foobarbaz"), 344 sign_count=0, 345 rp_id=generate_id(), 346 ) 347 stage = AuthenticatorValidateStage.objects.create( 348 name=generate_id(), 349 last_auth_threshold="milliseconds=0", 350 not_configured_action=NotConfiguredAction.CONFIGURE, 351 device_classes=[DeviceClasses.WEBAUTHN], 352 webauthn_user_verification=UserVerification.PREFERRED, 353 webauthn_hints=[ 354 WebAuthnHint.HYBRID, 355 WebAuthnHint.SECURITY_KEY, 356 WebAuthnHint.CLIENT_DEVICE, 357 ], 358 ) 359 plan = FlowPlan("") 360 stage_view = AuthenticatorValidateStageView( 361 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 362 ) 363 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 364 self.assertEqual(challenge["hints"], ["hybrid", "security-key", "client-device"]) 365 366 def test_validate_challenge_unrestricted(self): 367 """Test webauthn authentication (unrestricted webauthn device)""" 368 webauthn_mds_import.send(force=True).get_result() 369 device = WebAuthnDevice.objects.create( 370 user=self.user, 371 public_key=( 372 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FFIlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 373 ), 374 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 375 sign_count=2, 376 rp_id=generate_id(), 377 device_type=WebAuthnDeviceType.objects.get( 378 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 379 ), 380 ) 381 flow = create_test_flow() 382 stage = AuthenticatorValidateStage.objects.create( 383 name=generate_id(), 384 not_configured_action=NotConfiguredAction.CONFIGURE, 385 device_classes=[DeviceClasses.WEBAUTHN], 386 ) 387 session = self.client.session 388 plan = FlowPlan(flow_pk=flow.pk.hex) 389 plan.append_stage(stage) 390 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 391 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 392 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 393 { 394 "device_class": device.__class__.__name__.lower().replace("device", ""), 395 "device_uid": device.pk, 396 "challenge": {}, 397 "last_used": None, 398 } 399 ] 400 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 401 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 402 ) 403 session[SESSION_KEY_PLAN] = plan 404 session.save() 405 406 response = self.client.post( 407 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 408 data={ 409 "webauthn": { 410 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 411 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 412 "type": "public-key", 413 "assertionClientExtensions": "{}", 414 "response": { 415 "clientDataJSON": ( 416 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 417 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 418 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 419 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 420 "cm9zc09yaWdpbiI6ZmFsc2V9" 421 ), 422 "signature": ( 423 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 424 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 425 ), 426 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 427 "userHandle": None, 428 }, 429 }, 430 }, 431 SERVER_NAME="localhost", 432 SERVER_PORT="9000", 433 ) 434 self.assertEqual(response.status_code, 302) 435 response = self.client.get( 436 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 437 ) 438 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 439 440 def test_validate_challenge_restricted(self): 441 """Test webauthn authentication (restricted device type, failure)""" 442 webauthn_mds_import.send(force=True).get_result() 443 device = WebAuthnDevice.objects.create( 444 user=self.user, 445 public_key=( 446 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FFIlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 447 ), 448 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 449 sign_count=2, 450 rp_id=generate_id(), 451 device_type=WebAuthnDeviceType.objects.get( 452 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 453 ), 454 ) 455 flow = create_test_flow() 456 stage = AuthenticatorValidateStage.objects.create( 457 name=generate_id(), 458 not_configured_action=NotConfiguredAction.CONFIGURE, 459 device_classes=[DeviceClasses.WEBAUTHN], 460 ) 461 stage.webauthn_allowed_device_types.set( 462 WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series") 463 ) 464 session = self.client.session 465 plan = FlowPlan(flow_pk=flow.pk.hex) 466 plan.append_stage(stage) 467 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 468 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 469 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 470 { 471 "device_class": device.__class__.__name__.lower().replace("device", ""), 472 "device_uid": device.pk, 473 "challenge": {}, 474 "last_used": None, 475 } 476 ] 477 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 478 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 479 ) 480 session[SESSION_KEY_PLAN] = plan 481 session.save() 482 483 response = self.client.post( 484 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 485 data={ 486 "webauthn": { 487 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 488 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 489 "type": "public-key", 490 "assertionClientExtensions": "{}", 491 "response": { 492 "clientDataJSON": ( 493 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 494 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 495 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 496 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 497 "cm9zc09yaWdpbiI6ZmFsc2V9" 498 ), 499 "signature": ( 500 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 501 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 502 ), 503 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 504 "userHandle": None, 505 }, 506 } 507 }, 508 SERVER_NAME="localhost", 509 SERVER_PORT="9000", 510 ) 511 self.assertEqual(response.status_code, 200) 512 self.assertStageResponse( 513 response, 514 flow, 515 component="ak-stage-authenticator-validate", 516 response_errors={ 517 "webauthn": [ 518 { 519 "string": ( 520 "Invalid device type. Contact your authentik administrator for help." 521 ), 522 "code": "invalid", 523 } 524 ] 525 }, 526 ) 527 528 def test_validate_challenge_malformed(self): 529 """Test that an assertion whose fields can't be decoded is rejected as an invalid 530 device""" 531 flow = create_test_flow() 532 stage = AuthenticatorValidateStage.objects.create( 533 name=generate_id(), 534 not_configured_action=NotConfiguredAction.CONFIGURE, 535 device_classes=[DeviceClasses.WEBAUTHN], 536 ) 537 plan = FlowPlan(flow.pk.hex) 538 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b"\x01" * 64 539 stage_view = AuthenticatorValidateStageView( 540 FlowExecutorView(flow=flow, current_stage=stage, plan=plan), 541 request=self.request_factory.get("/"), 542 ) 543 for field, value in ( 544 ("rawId", "a"), 545 ("clientDataJSON", "a"), 546 ("authenticatorData", "a"), 547 ("signature", "\u00e9"), 548 ("userHandle", "a"), 549 ("userHandle", "\u00e9"), 550 ): 551 assertion = { 552 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 553 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 554 "type": "public-key", 555 "response": { 556 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0", 557 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ", 558 "signature": "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI", 559 "userHandle": None, 560 }, 561 } 562 if field == "rawId": 563 assertion[field] = value 564 else: 565 assertion["response"][field] = value 566 with self.subTest(field=field, value=value): 567 with self.assertRaises(ValidationError) as cm: 568 validate_challenge_webauthn(assertion, stage_view, self.user) 569 self.assertEqual(str(cm.exception.detail[0]), "Invalid device") 570 self.assertEqual(cm.exception.detail[0].code, "invalid") 571 572 def test_validate_challenge_malformed_userless(self): 573 """Test that a malformed assertion in a passwordless flow gets a validation error""" 574 flow = create_test_flow(FlowDesignation.AUTHENTICATION) 575 stage = AuthenticatorValidateStage.objects.create( 576 name=generate_id(), 577 not_configured_action=NotConfiguredAction.DENY, 578 device_classes=[DeviceClasses.WEBAUTHN], 579 ) 580 FlowStageBinding.objects.create(target=flow, stage=stage, order=0) 581 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 582 response = self.client.get(url) 583 self.assertStageResponse(response, flow, component="ak-stage-authenticator-validate") 584 585 response = self.client.post( 586 url, 587 data={ 588 "webauthn": { 589 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 590 "rawId": "a", 591 "type": "public-key", 592 "response": { 593 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0", 594 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ", 595 "signature": "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI", 596 "userHandle": None, 597 }, 598 }, 599 }, 600 ) 601 self.assertStageResponse( 602 response, 603 flow, 604 component="ak-stage-authenticator-validate", 605 response_errors={"webauthn": [{"string": "Invalid device", "code": "invalid"}]}, 606 ) 607 608 def test_validate_challenge_userless(self): 609 """Test webauthn""" 610 device = WebAuthnDevice.objects.create( 611 user=self.user, 612 public_key=( 613 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 614 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 615 ), 616 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 617 sign_count=4, 618 rp_id=generate_id(), 619 ) 620 flow = create_test_flow() 621 stage = AuthenticatorValidateStage.objects.create( 622 name=generate_id(), 623 not_configured_action=NotConfiguredAction.CONFIGURE, 624 device_classes=[DeviceClasses.WEBAUTHN], 625 ) 626 session = self.client.session 627 plan = FlowPlan(flow_pk=flow.pk.hex) 628 plan.append_stage(stage) 629 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 630 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 631 { 632 "device_class": device.__class__.__name__.lower().replace("device", ""), 633 "device_uid": device.pk, 634 "challenge": {}, 635 "last_used": None, 636 } 637 ] 638 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 639 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 640 ) 641 session[SESSION_KEY_PLAN] = plan 642 session.save() 643 644 response = self.client.post( 645 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 646 data={ 647 "webauthn": { 648 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 649 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 650 "type": "public-key", 651 "assertionClientExtensions": "{}", 652 "response": { 653 "clientDataJSON": ( 654 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2Wlhv" 655 "NWx4TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGcz" 656 "QWdPNFdoLUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9j" 657 "YWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2Fu" 658 "X2JlX2FkZGVkX2hlcmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBh" 659 "Z2FpbnN0IGEgdGVtcGxhdGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 660 ), 661 "signature": ( 662 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 663 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 664 ), 665 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 666 "userHandle": None, 667 }, 668 }, 669 }, 670 SERVER_NAME="localhost", 671 SERVER_PORT="9000", 672 ) 673 self.assertEqual(response.status_code, 302) 674 response = self.client.get( 675 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 676 ) 677 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 678 679 def test_validate_challenge_single_use(self): 680 """Test that a challenge is removed after an assertion verifies""" 681 device = WebAuthnDevice.objects.create( 682 user=self.user, 683 public_key=( 684 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FF" 685 "IlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 686 ), 687 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 688 sign_count=2, 689 rp_id=generate_id(), 690 ) 691 stage = AuthenticatorValidateStage.objects.create( 692 name=generate_id(), 693 not_configured_action=NotConfiguredAction.CONFIGURE, 694 device_classes=[DeviceClasses.WEBAUTHN], 695 ) 696 plan = FlowPlan("") 697 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 698 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 699 ) 700 request = self.request_factory.post("/", SERVER_NAME="localhost", SERVER_PORT="9000") 701 request.user = self.user 702 stage_view = StageView(FlowExecutorView(current_stage=stage, plan=plan), request=request) 703 assertion = { 704 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 705 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 706 "type": "public-key", 707 "assertionClientExtensions": "{}", 708 "response": { 709 "clientDataJSON": ( 710 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 711 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 712 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 713 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 714 "cm9zc09yaWdpbiI6ZmFsc2V9" 715 ), 716 "signature": ( 717 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 718 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 719 ), 720 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 721 "userHandle": None, 722 }, 723 } 724 725 self.assertEqual(validate_challenge_webauthn(assertion, stage_view, self.user), device) 726 self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context) 727 728 def test_validate_challenge_invalid(self): 729 """Test webauthn""" 730 request = self.request_factory.get("/") 731 request.user = self.user 732 733 WebAuthnDevice.objects.create( 734 user=self.user, 735 public_key=( 736 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc4" 737 "3i0JH6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 738 ), 739 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 740 # One more sign count than above, make it invalid 741 sign_count=5, 742 rp_id=generate_id(), 743 ) 744 flow = create_test_flow() 745 stage = AuthenticatorValidateStage.objects.create( 746 name=generate_id(), 747 not_configured_action=NotConfiguredAction.CONFIGURE, 748 device_classes=[DeviceClasses.WEBAUTHN], 749 ) 750 plan = FlowPlan(flow.pk.hex) 751 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 752 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 753 ) 754 request = self.request_factory.get("/") 755 756 stage_view = AuthenticatorValidateStageView( 757 FlowExecutorView(flow=flow, current_stage=stage, plan=plan), request=request 758 ) 759 request.META["SERVER_NAME"] = "localhost" 760 request.META["SERVER_PORT"] = "9000" 761 with self.assertRaises(ValidationError): 762 validate_challenge_webauthn( 763 { 764 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 765 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 766 "type": "public-key", 767 "assertionClientExtensions": "{}", 768 "response": { 769 "clientDataJSON": ( 770 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2WlhvNWx4" 771 "TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGczQWdPNFdo" 772 "LUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0Ojkw" 773 "MDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2FuX2JlX2FkZGVkX2hl" 774 "cmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBhZ2FpbnN0IGEgdGVtcGxh" 775 "dGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 776 ), 777 "signature": ( 778 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 779 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 780 ), 781 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 782 "userHandle": None, 783 }, 784 }, 785 stage_view, 786 self.user, 787 ) 788 789 def _validate_unavailable_algorithm( 790 self, alg: COSEAlgorithmIdentifier, public_key_class: str, fips_enabled: bool 791 ) -> str: 792 """Authenticate with a credential whose public key cryptography refuses to load, as it 793 does for Ed25519 and ML-DSA under the validated OpenSSL FIPS provider""" 794 credential = SoftwareCredential(rp_id="localhost", origin="http://localhost:9000", alg=alg) 795 device = WebAuthnDevice.objects.create( 796 user=self.user, 797 public_key=bytes_to_base64url(credential.cose_public_key), 798 credential_id=bytes_to_base64url(credential.credential_id), 799 sign_count=0, 800 rp_id="localhost", 801 ) 802 flow = create_test_flow() 803 stage = AuthenticatorValidateStage.objects.create( 804 name=generate_id(), 805 not_configured_action=NotConfiguredAction.CONFIGURE, 806 device_classes=[DeviceClasses.WEBAUTHN], 807 ) 808 challenge = b"\x03" * 64 809 plan = FlowPlan(flow.pk.hex) 810 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge 811 request = self.request_factory.get("/") 812 request.META["SERVER_NAME"] = "localhost" 813 request.META["SERVER_PORT"] = "9000" 814 stage_view = AuthenticatorValidateStageView( 815 FlowExecutorView(flow=flow, current_stage=stage, plan=plan), request=request 816 ) 817 with ( 818 patch( 819 f"webauthn.helpers.decoded_public_key_to_cryptography.{public_key_class}." 820 "from_public_bytes", 821 side_effect=ValueError(f"An {public_key_class} is 32 bytes long"), 822 ), 823 patch( 824 "authentik.stages.authenticator_validate.challenge.backend._fips_enabled", 825 fips_enabled, 826 ), 827 self.assertRaises(ValidationError) as cm, 828 ): 829 validate_challenge_webauthn( 830 credential.assertion_response(challenge), stage_view, self.user 831 ) 832 # The user sees a generic error; the details go to the log and the event 833 self.assertEqual( 834 str(cm.exception.detail[0]), 835 "Invalid security key. Please re-register or contact an administrator.", 836 ) 837 event = Event.objects.filter( 838 action=EventAction.LOGIN_FAILED, context__stage__pk=stage.pk.hex 839 ).first() 840 self.assertIsNotNone(event) 841 self.assertEqual(event.context["fips_enabled"], fips_enabled) 842 self.assertIn(event.context["algorithm"], ("EdDSA (Ed25519)", "ML-DSA-44")) 843 device.refresh_from_db() 844 self.assertEqual(device.sign_count, 0) 845 return event.context["message"] 846 847 @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519") 848 def test_validate_challenge_unavailable_algorithm_eddsa(self): 849 """cryptography raises its misleading key-length ValueError directly for Ed25519; 850 with FIPS enabled the event names the key type and FIPS""" 851 detail = self._validate_unavailable_algorithm( 852 COSEAlgorithmIdentifier.EDDSA, "Ed25519PublicKey", fips_enabled=True 853 ) 854 self.assertEqual( 855 detail, "Cannot log in with EdDSA (Ed25519) security key while FIPS mode is enabled" 856 ) 857 858 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 859 def test_validate_challenge_unavailable_algorithm_mldsa(self): 860 """py_webauthn wraps the ML-DSA failure in its own UnsupportedPublicKey; without FIPS 861 the event still names the key type""" 862 detail = self._validate_unavailable_algorithm( 863 COSEAlgorithmIdentifier.ML_DSA_44, "MLDSA44PublicKey", fips_enabled=False 864 ) 865 self.assertEqual( 866 detail, 867 "Cannot log in with ML-DSA-44 security key: the key type is not available in the " 868 "current OpenSSL configuration", 869 ) 870 871 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 872 def test_validate_challenge_mldsa(self): 873 """Test webauthn authentication with an ML-DSA-44 (FIPS 204) credential""" 874 credential = SoftwareCredential(rp_id="localhost", origin="http://localhost:9000") 875 device = WebAuthnDevice.objects.create( 876 user=self.user, 877 public_key=bytes_to_base64url(credential.cose_public_key), 878 credential_id=bytes_to_base64url(credential.credential_id), 879 sign_count=0, 880 rp_id="localhost", 881 ) 882 flow = create_test_flow() 883 stage = AuthenticatorValidateStage.objects.create( 884 name=generate_id(), 885 not_configured_action=NotConfiguredAction.CONFIGURE, 886 device_classes=[DeviceClasses.WEBAUTHN], 887 ) 888 challenge = b"\x02" * 64 889 session = self.client.session 890 plan = FlowPlan(flow_pk=flow.pk.hex) 891 plan.append_stage(stage) 892 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 893 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 894 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 895 { 896 "device_class": device.__class__.__name__.lower().replace("device", ""), 897 "device_uid": device.pk, 898 "challenge": {}, 899 "last_used": None, 900 } 901 ] 902 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge 903 session[SESSION_KEY_PLAN] = plan 904 session.save() 905 906 response = self.client.post( 907 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 908 data={"webauthn": credential.assertion_response(challenge)}, 909 SERVER_NAME="localhost", 910 SERVER_PORT="9000", 911 ) 912 self.assertEqual(response.status_code, 302) 913 response = self.client.get( 914 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 915 ) 916 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 917 device.refresh_from_db() 918 self.assertEqual(device.sign_count, 1) 919 920 def _plan_at_webauthn_stage(self, pending_user: bool = True) -> Flow: 921 """Create a flow with its plan stored in the session, currently at a WebAuthn 922 validation stage""" 923 WebAuthnDevice.objects.create( 924 user=self.user, 925 public_key=( 926 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 927 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 928 ), 929 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 930 sign_count=4, 931 rp_id=generate_id(), 932 ) 933 flow = create_test_flow(FlowDesignation.AUTHENTICATION) 934 stage = AuthenticatorValidateStage.objects.create( 935 name=generate_id(), 936 not_configured_action=NotConfiguredAction.DENY, 937 device_classes=[DeviceClasses.WEBAUTHN], 938 ) 939 session = self.client.session 940 plan = FlowPlan(flow_pk=flow.pk.hex) 941 plan.append_stage(stage) 942 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 943 if pending_user: 944 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 945 session[SESSION_KEY_PLAN] = plan 946 session.save() 947 return flow 948 949 def _render_stage(self, flow: Flow) -> dict: 950 response = self.client.get( 951 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 952 SERVER_NAME="localhost", 953 SERVER_PORT="9000", 954 ) 955 self.assertStageResponse(response, flow, component="ak-stage-authenticator-validate") 956 return self.client.session[SESSION_KEY_PLAN].context 957 958 def test_render_reuses_webauthn_challenge(self): 959 """Test that rendering the stage again doesn't replace the pending challenge""" 960 flow = self._plan_at_webauthn_stage() 961 962 first = self._render_stage(flow) 963 second = self._render_stage(flow) 964 965 self.assertIsNotNone(first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]) 966 self.assertEqual( 967 first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE], second[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] 968 ) 969 self.assertEqual( 970 first[PLAN_CONTEXT_DEVICE_CHALLENGES], second[PLAN_CONTEXT_DEVICE_CHALLENGES] 971 ) 972 973 def test_render_reuses_webauthn_challenge_userless(self): 974 """Test that rendering the stage again doesn't replace the pending challenge 975 (user-less)""" 976 flow = self._plan_at_webauthn_stage(pending_user=False) 977 978 first = self._render_stage(flow) 979 second = self._render_stage(flow) 980 981 self.assertIsNotNone(first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]) 982 self.assertEqual( 983 first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE], second[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] 984 ) 985 986 def test_validate_challenge_after_render(self): 987 """Test that a response to a challenge is still accepted after the stage was 988 rendered again (e.g. by another tab), and that the challenge can't be answered 989 again afterwards""" 990 flow = self._plan_at_webauthn_stage() 991 session = self.client.session 992 plan: FlowPlan = session[SESSION_KEY_PLAN] 993 # The challenge the assertion below was signed for 994 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 995 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 996 ) 997 session[SESSION_KEY_PLAN] = plan 998 session.save() 999 1000 # Render the stage twice, e.g. the original tab and another tab 1001 self._render_stage(flow) 1002 self._render_stage(flow) 1003 1004 response = self.client.post( 1005 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 1006 data={ 1007 "webauthn": { 1008 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 1009 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 1010 "type": "public-key", 1011 "assertionClientExtensions": "{}", 1012 "response": { 1013 "clientDataJSON": ( 1014 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2Wlhv" 1015 "NWx4TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGcz" 1016 "QWdPNFdoLUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9j" 1017 "YWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2Fu" 1018 "X2JlX2FkZGVkX2hlcmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBh" 1019 "Z2FpbnN0IGEgdGVtcGxhdGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 1020 ), 1021 "signature": ( 1022 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 1023 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 1024 ), 1025 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 1026 "userHandle": None, 1027 }, 1028 }, 1029 }, 1030 SERVER_NAME="localhost", 1031 SERVER_PORT="9000", 1032 ) 1033 self.assertEqual(response.status_code, 302) 1034 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 1035 self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context)
Test validator stage
49 def setUp(self) -> None: 50 self.user = create_test_admin_user() 51 self.request_factory = RequestFactory()
Hook method for setting up the test fixture before exercising it.
53 def test_last_auth_threshold(self): 54 """Test last_auth_threshold""" 55 ident_stage = IdentificationStage.objects.create( 56 name=generate_id(), 57 user_fields=[ 58 UserFields.USERNAME, 59 ], 60 ) 61 device: WebAuthnDevice = WebAuthnDevice.objects.create( 62 user=self.user, 63 confirmed=True, 64 ) 65 device.set_sign_count(device.sign_count + 1) 66 stage = AuthenticatorValidateStage.objects.create( 67 name=generate_id(), 68 last_auth_threshold="milliseconds=0", 69 not_configured_action=NotConfiguredAction.CONFIGURE, 70 device_classes=[DeviceClasses.WEBAUTHN], 71 ) 72 sleep(1) 73 stage.configuration_stages.set([ident_stage]) 74 flow = create_test_flow() 75 FlowStageBinding.objects.create(target=flow, stage=ident_stage, order=0) 76 FlowStageBinding.objects.create(target=flow, stage=stage, order=1) 77 78 response = self.client.post( 79 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 80 {"uid_field": self.user.username}, 81 ) 82 self.assertEqual(response.status_code, 302) 83 response = self.client.get( 84 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 85 follow=True, 86 ) 87 self.assertStageResponse( 88 response, 89 flow, 90 component="ak-stage-authenticator-validate", 91 )
Test last_auth_threshold
93 def test_device_challenge_webauthn(self): 94 """Test webauthn""" 95 request = self.request_factory.get("/") 96 request.user = self.user 97 98 webauthn_device = WebAuthnDevice.objects.create( 99 user=self.user, 100 public_key=bytes_to_base64url(b"qwerqwerqre"), 101 credential_id=bytes_to_base64url(b"foobarbaz"), 102 sign_count=0, 103 rp_id=generate_id(), 104 ) 105 stage = AuthenticatorValidateStage.objects.create( 106 name=generate_id(), 107 last_auth_threshold="milliseconds=0", 108 not_configured_action=NotConfiguredAction.CONFIGURE, 109 device_classes=[DeviceClasses.WEBAUTHN], 110 webauthn_user_verification=UserVerification.PREFERRED, 111 ) 112 plan = FlowPlan("") 113 stage_view = AuthenticatorValidateStageView( 114 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 115 ) 116 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 117 del challenge["challenge"] 118 self.assertEqual( 119 challenge, 120 { 121 "allowCredentials": [ 122 { 123 "id": "Zm9vYmFyYmF6", 124 "type": "public-key", 125 } 126 ], 127 "rpId": "testserver", 128 "timeout": 60000, 129 "userVerification": "preferred", 130 }, 131 ) 132 133 with self.assertRaises(ValidationError): 134 validate_challenge_webauthn( 135 {}, 136 StageView(FlowExecutorView(current_stage=stage, plan=plan), request=request), 137 self.user, 138 )
Test webauthn
140 def test_device_challenge_webauthn_restricted(self): 141 """Test webauthn (getting device challenges with a webauthn 142 device that is not allowed due to aaguid restrictions)""" 143 webauthn_mds_import.send(force=True).get_result() 144 request = self.request_factory.get("/") 145 request.user = self.user 146 147 WebAuthnDevice.objects.create( 148 user=self.user, 149 public_key=bytes_to_base64url(b"qwerqwerqre"), 150 credential_id=bytes_to_base64url(b"foobarbaz"), 151 sign_count=0, 152 rp_id=generate_id(), 153 device_type=WebAuthnDeviceType.objects.get( 154 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 155 ), 156 ) 157 flow = create_test_flow() 158 stage = AuthenticatorValidateStage.objects.create( 159 name=generate_id(), 160 last_auth_threshold="milliseconds=0", 161 not_configured_action=NotConfiguredAction.DENY, 162 device_classes=[DeviceClasses.WEBAUTHN], 163 webauthn_user_verification=UserVerification.PREFERRED, 164 ) 165 stage.webauthn_allowed_device_types.set( 166 WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series") 167 ) 168 session = self.client.session 169 plan = FlowPlan(flow_pk=flow.pk.hex) 170 plan.append_stage(stage) 171 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 172 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 173 session[SESSION_KEY_PLAN] = plan 174 session.save() 175 176 response = self.client.get( 177 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 178 ) 179 self.assertStageResponse( 180 response, 181 flow, 182 component="ak-stage-access-denied", 183 error_message="No (allowed) MFA authenticator configured.", 184 )
Test webauthn (getting device challenges with a webauthn device that is not allowed due to aaguid restrictions)
186 def test_raw_get_challenge(self): 187 """Test webauthn""" 188 request = self.request_factory.get("/") 189 request.user = self.user 190 191 stage = AuthenticatorValidateStage.objects.create( 192 name=generate_id(), 193 last_auth_threshold="milliseconds=0", 194 not_configured_action=NotConfiguredAction.CONFIGURE, 195 device_classes=[DeviceClasses.WEBAUTHN], 196 webauthn_user_verification=UserVerification.PREFERRED, 197 ) 198 webauthn_device = WebAuthnDevice.objects.create( 199 user=self.user, 200 public_key=( 201 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 202 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 203 ), 204 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 205 sign_count=0, 206 rp_id=generate_id(), 207 ) 208 plan = FlowPlan("") 209 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 210 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 211 ) 212 stage_view = AuthenticatorValidateStageView( 213 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 214 ) 215 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 216 self.assertEqual( 217 challenge["allowCredentials"], 218 [ 219 { 220 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 221 "type": "public-key", 222 } 223 ], 224 ) 225 self.assertIsNotNone(challenge["challenge"]) 226 self.assertEqual( 227 challenge["rpId"], 228 "testserver", 229 ) 230 self.assertEqual( 231 challenge["timeout"], 232 60000, 233 ) 234 self.assertEqual( 235 challenge["userVerification"], 236 "preferred", 237 )
Test webauthn
239 def test_get_challenge_userless(self): 240 """Test webauthn (userless)""" 241 request = self.request_factory.get("/") 242 stage = AuthenticatorValidateStage.objects.create( 243 name=generate_id(), webauthn_user_verification=UserVerification.PREFERRED 244 ) 245 stage.refresh_from_db() 246 WebAuthnDevice.objects.create( 247 user=self.user, 248 public_key=( 249 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 250 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 251 ), 252 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 253 sign_count=0, 254 rp_id=generate_id(), 255 ) 256 plan = FlowPlan("") 257 stage_view = AuthenticatorValidateStageView( 258 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 259 ) 260 challenge = get_webauthn_challenge_without_user(stage_view, stage) 261 self.assertEqual(challenge["allowCredentials"], []) 262 self.assertIsNotNone(challenge["challenge"]) 263 self.assertEqual(challenge["rpId"], "testserver") 264 self.assertEqual(challenge["timeout"], 60000) 265 self.assertEqual(challenge["userVerification"], "preferred")
Test webauthn (userless)
267 def test_device_challenge_webauthn_with_hints(self): 268 """Test that webauthn hints are included in authentication challenge""" 269 request = self.request_factory.get("/") 270 request.user = self.user 271 272 webauthn_device = WebAuthnDevice.objects.create( 273 user=self.user, 274 public_key=bytes_to_base64url(b"qwerqwerqre"), 275 credential_id=bytes_to_base64url(b"foobarbaz"), 276 sign_count=0, 277 rp_id=generate_id(), 278 ) 279 stage = AuthenticatorValidateStage.objects.create( 280 name=generate_id(), 281 last_auth_threshold="milliseconds=0", 282 not_configured_action=NotConfiguredAction.CONFIGURE, 283 device_classes=[DeviceClasses.WEBAUTHN], 284 webauthn_user_verification=UserVerification.PREFERRED, 285 webauthn_hints=[WebAuthnHint.CLIENT_DEVICE, WebAuthnHint.HYBRID], 286 ) 287 plan = FlowPlan("") 288 stage_view = AuthenticatorValidateStageView( 289 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 290 ) 291 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 292 self.assertEqual(challenge["hints"], ["client-device", "hybrid"])
Test that webauthn hints are included in authentication challenge
294 def test_device_challenge_webauthn_no_hints(self): 295 """Test that hints key is absent when no hints configured""" 296 request = self.request_factory.get("/") 297 request.user = self.user 298 299 webauthn_device = WebAuthnDevice.objects.create( 300 user=self.user, 301 public_key=bytes_to_base64url(b"qwerqwerqre"), 302 credential_id=bytes_to_base64url(b"foobarbaz"), 303 sign_count=0, 304 rp_id=generate_id(), 305 ) 306 stage = AuthenticatorValidateStage.objects.create( 307 name=generate_id(), 308 last_auth_threshold="milliseconds=0", 309 not_configured_action=NotConfiguredAction.CONFIGURE, 310 device_classes=[DeviceClasses.WEBAUTHN], 311 webauthn_user_verification=UserVerification.PREFERRED, 312 ) 313 plan = FlowPlan("") 314 stage_view = AuthenticatorValidateStageView( 315 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 316 ) 317 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 318 self.assertNotIn("hints", challenge)
Test that hints key is absent when no hints configured
320 def test_get_challenge_userless_with_hints(self): 321 """Test that hints are included in userless/passwordless challenge""" 322 request = self.request_factory.get("/") 323 stage = AuthenticatorValidateStage.objects.create( 324 name=generate_id(), 325 webauthn_user_verification=UserVerification.PREFERRED, 326 webauthn_hints=[WebAuthnHint.SECURITY_KEY, WebAuthnHint.CLIENT_DEVICE], 327 ) 328 plan = FlowPlan("") 329 stage_view = AuthenticatorValidateStageView( 330 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 331 ) 332 challenge = get_webauthn_challenge_without_user(stage_view, stage) 333 self.assertEqual(challenge["hints"], ["security-key", "client-device"])
Test that hints are included in userless/passwordless challenge
335 def test_device_challenge_webauthn_hints_order_preserved(self): 336 """Test that hint order is preserved in authentication challenge""" 337 request = self.request_factory.get("/") 338 request.user = self.user 339 340 webauthn_device = WebAuthnDevice.objects.create( 341 user=self.user, 342 public_key=bytes_to_base64url(b"qwerqwerqre"), 343 credential_id=bytes_to_base64url(b"foobarbaz"), 344 sign_count=0, 345 rp_id=generate_id(), 346 ) 347 stage = AuthenticatorValidateStage.objects.create( 348 name=generate_id(), 349 last_auth_threshold="milliseconds=0", 350 not_configured_action=NotConfiguredAction.CONFIGURE, 351 device_classes=[DeviceClasses.WEBAUTHN], 352 webauthn_user_verification=UserVerification.PREFERRED, 353 webauthn_hints=[ 354 WebAuthnHint.HYBRID, 355 WebAuthnHint.SECURITY_KEY, 356 WebAuthnHint.CLIENT_DEVICE, 357 ], 358 ) 359 plan = FlowPlan("") 360 stage_view = AuthenticatorValidateStageView( 361 FlowExecutorView(flow=None, current_stage=stage, plan=plan), request=request 362 ) 363 challenge = get_challenge_for_device(stage_view, stage, webauthn_device) 364 self.assertEqual(challenge["hints"], ["hybrid", "security-key", "client-device"])
Test that hint order is preserved in authentication challenge
366 def test_validate_challenge_unrestricted(self): 367 """Test webauthn authentication (unrestricted webauthn device)""" 368 webauthn_mds_import.send(force=True).get_result() 369 device = WebAuthnDevice.objects.create( 370 user=self.user, 371 public_key=( 372 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FFIlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 373 ), 374 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 375 sign_count=2, 376 rp_id=generate_id(), 377 device_type=WebAuthnDeviceType.objects.get( 378 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 379 ), 380 ) 381 flow = create_test_flow() 382 stage = AuthenticatorValidateStage.objects.create( 383 name=generate_id(), 384 not_configured_action=NotConfiguredAction.CONFIGURE, 385 device_classes=[DeviceClasses.WEBAUTHN], 386 ) 387 session = self.client.session 388 plan = FlowPlan(flow_pk=flow.pk.hex) 389 plan.append_stage(stage) 390 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 391 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 392 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 393 { 394 "device_class": device.__class__.__name__.lower().replace("device", ""), 395 "device_uid": device.pk, 396 "challenge": {}, 397 "last_used": None, 398 } 399 ] 400 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 401 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 402 ) 403 session[SESSION_KEY_PLAN] = plan 404 session.save() 405 406 response = self.client.post( 407 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 408 data={ 409 "webauthn": { 410 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 411 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 412 "type": "public-key", 413 "assertionClientExtensions": "{}", 414 "response": { 415 "clientDataJSON": ( 416 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 417 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 418 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 419 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 420 "cm9zc09yaWdpbiI6ZmFsc2V9" 421 ), 422 "signature": ( 423 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 424 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 425 ), 426 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 427 "userHandle": None, 428 }, 429 }, 430 }, 431 SERVER_NAME="localhost", 432 SERVER_PORT="9000", 433 ) 434 self.assertEqual(response.status_code, 302) 435 response = self.client.get( 436 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 437 ) 438 self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
Test webauthn authentication (unrestricted webauthn device)
440 def test_validate_challenge_restricted(self): 441 """Test webauthn authentication (restricted device type, failure)""" 442 webauthn_mds_import.send(force=True).get_result() 443 device = WebAuthnDevice.objects.create( 444 user=self.user, 445 public_key=( 446 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FFIlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 447 ), 448 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 449 sign_count=2, 450 rp_id=generate_id(), 451 device_type=WebAuthnDeviceType.objects.get( 452 aaguid="2fc0579f-8113-47ea-b116-bb5a8db9202a" 453 ), 454 ) 455 flow = create_test_flow() 456 stage = AuthenticatorValidateStage.objects.create( 457 name=generate_id(), 458 not_configured_action=NotConfiguredAction.CONFIGURE, 459 device_classes=[DeviceClasses.WEBAUTHN], 460 ) 461 stage.webauthn_allowed_device_types.set( 462 WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series") 463 ) 464 session = self.client.session 465 plan = FlowPlan(flow_pk=flow.pk.hex) 466 plan.append_stage(stage) 467 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 468 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 469 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 470 { 471 "device_class": device.__class__.__name__.lower().replace("device", ""), 472 "device_uid": device.pk, 473 "challenge": {}, 474 "last_used": None, 475 } 476 ] 477 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 478 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 479 ) 480 session[SESSION_KEY_PLAN] = plan 481 session.save() 482 483 response = self.client.post( 484 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 485 data={ 486 "webauthn": { 487 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 488 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 489 "type": "public-key", 490 "assertionClientExtensions": "{}", 491 "response": { 492 "clientDataJSON": ( 493 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 494 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 495 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 496 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 497 "cm9zc09yaWdpbiI6ZmFsc2V9" 498 ), 499 "signature": ( 500 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 501 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 502 ), 503 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 504 "userHandle": None, 505 }, 506 } 507 }, 508 SERVER_NAME="localhost", 509 SERVER_PORT="9000", 510 ) 511 self.assertEqual(response.status_code, 200) 512 self.assertStageResponse( 513 response, 514 flow, 515 component="ak-stage-authenticator-validate", 516 response_errors={ 517 "webauthn": [ 518 { 519 "string": ( 520 "Invalid device type. Contact your authentik administrator for help." 521 ), 522 "code": "invalid", 523 } 524 ] 525 }, 526 )
Test webauthn authentication (restricted device type, failure)
528 def test_validate_challenge_malformed(self): 529 """Test that an assertion whose fields can't be decoded is rejected as an invalid 530 device""" 531 flow = create_test_flow() 532 stage = AuthenticatorValidateStage.objects.create( 533 name=generate_id(), 534 not_configured_action=NotConfiguredAction.CONFIGURE, 535 device_classes=[DeviceClasses.WEBAUTHN], 536 ) 537 plan = FlowPlan(flow.pk.hex) 538 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b"\x01" * 64 539 stage_view = AuthenticatorValidateStageView( 540 FlowExecutorView(flow=flow, current_stage=stage, plan=plan), 541 request=self.request_factory.get("/"), 542 ) 543 for field, value in ( 544 ("rawId", "a"), 545 ("clientDataJSON", "a"), 546 ("authenticatorData", "a"), 547 ("signature", "\u00e9"), 548 ("userHandle", "a"), 549 ("userHandle", "\u00e9"), 550 ): 551 assertion = { 552 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 553 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 554 "type": "public-key", 555 "response": { 556 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0", 557 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ", 558 "signature": "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI", 559 "userHandle": None, 560 }, 561 } 562 if field == "rawId": 563 assertion[field] = value 564 else: 565 assertion["response"][field] = value 566 with self.subTest(field=field, value=value): 567 with self.assertRaises(ValidationError) as cm: 568 validate_challenge_webauthn(assertion, stage_view, self.user) 569 self.assertEqual(str(cm.exception.detail[0]), "Invalid device") 570 self.assertEqual(cm.exception.detail[0].code, "invalid")
Test that an assertion whose fields can't be decoded is rejected as an invalid device
572 def test_validate_challenge_malformed_userless(self): 573 """Test that a malformed assertion in a passwordless flow gets a validation error""" 574 flow = create_test_flow(FlowDesignation.AUTHENTICATION) 575 stage = AuthenticatorValidateStage.objects.create( 576 name=generate_id(), 577 not_configured_action=NotConfiguredAction.DENY, 578 device_classes=[DeviceClasses.WEBAUTHN], 579 ) 580 FlowStageBinding.objects.create(target=flow, stage=stage, order=0) 581 url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}) 582 response = self.client.get(url) 583 self.assertStageResponse(response, flow, component="ak-stage-authenticator-validate") 584 585 response = self.client.post( 586 url, 587 data={ 588 "webauthn": { 589 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 590 "rawId": "a", 591 "type": "public-key", 592 "response": { 593 "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0", 594 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ", 595 "signature": "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI", 596 "userHandle": None, 597 }, 598 }, 599 }, 600 ) 601 self.assertStageResponse( 602 response, 603 flow, 604 component="ak-stage-authenticator-validate", 605 response_errors={"webauthn": [{"string": "Invalid device", "code": "invalid"}]}, 606 )
Test that a malformed assertion in a passwordless flow gets a validation error
608 def test_validate_challenge_userless(self): 609 """Test webauthn""" 610 device = WebAuthnDevice.objects.create( 611 user=self.user, 612 public_key=( 613 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc43i0J" 614 "H6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 615 ), 616 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 617 sign_count=4, 618 rp_id=generate_id(), 619 ) 620 flow = create_test_flow() 621 stage = AuthenticatorValidateStage.objects.create( 622 name=generate_id(), 623 not_configured_action=NotConfiguredAction.CONFIGURE, 624 device_classes=[DeviceClasses.WEBAUTHN], 625 ) 626 session = self.client.session 627 plan = FlowPlan(flow_pk=flow.pk.hex) 628 plan.append_stage(stage) 629 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 630 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 631 { 632 "device_class": device.__class__.__name__.lower().replace("device", ""), 633 "device_uid": device.pk, 634 "challenge": {}, 635 "last_used": None, 636 } 637 ] 638 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 639 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 640 ) 641 session[SESSION_KEY_PLAN] = plan 642 session.save() 643 644 response = self.client.post( 645 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 646 data={ 647 "webauthn": { 648 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 649 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 650 "type": "public-key", 651 "assertionClientExtensions": "{}", 652 "response": { 653 "clientDataJSON": ( 654 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2Wlhv" 655 "NWx4TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGcz" 656 "QWdPNFdoLUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9j" 657 "YWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2Fu" 658 "X2JlX2FkZGVkX2hlcmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBh" 659 "Z2FpbnN0IGEgdGVtcGxhdGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 660 ), 661 "signature": ( 662 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 663 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 664 ), 665 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 666 "userHandle": None, 667 }, 668 }, 669 }, 670 SERVER_NAME="localhost", 671 SERVER_PORT="9000", 672 ) 673 self.assertEqual(response.status_code, 302) 674 response = self.client.get( 675 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 676 ) 677 self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
Test webauthn
679 def test_validate_challenge_single_use(self): 680 """Test that a challenge is removed after an assertion verifies""" 681 device = WebAuthnDevice.objects.create( 682 user=self.user, 683 public_key=( 684 "pQECAyYgASFYIF-N4GvQJdTJMAmTOxFX9_boL00zBiSrP0DY9xvJl_FF" 685 "IlggnyZloVSVofdJNTLMeMdjQHgW2Rzmd5_Xt5AWtNztcdo" 686 ), 687 credential_id="X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 688 sign_count=2, 689 rp_id=generate_id(), 690 ) 691 stage = AuthenticatorValidateStage.objects.create( 692 name=generate_id(), 693 not_configured_action=NotConfiguredAction.CONFIGURE, 694 device_classes=[DeviceClasses.WEBAUTHN], 695 ) 696 plan = FlowPlan("") 697 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 698 "aCC6ak_DP45xMH1qyxzUM5iC2xc4QthQb09v7m4qDBmY8FvWvhxFzSuFlDYQmclrh5fWS5q0TPxgJGF4vimcFQ" 699 ) 700 request = self.request_factory.post("/", SERVER_NAME="localhost", SERVER_PORT="9000") 701 request.user = self.user 702 stage_view = StageView(FlowExecutorView(current_stage=stage, plan=plan), request=request) 703 assertion = { 704 "id": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 705 "rawId": "X43ga9Al1MkwCZM7EXD1r8Sxj7aXnNsuR013XM7he4kZ-GS9TaA-u3i36wsswjPm", 706 "type": "public-key", 707 "assertionClientExtensions": "{}", 708 "response": { 709 "clientDataJSON": ( 710 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiYUNDN" 711 "mFrX0RQNDV4TUgxcXl4elVNNWlDMnhjNFF0aFFiMDl2N200cURCbV" 712 "k4RnZXdmh4RnpTdUZsRFlRbWNscmg1ZldTNXEwVFB4Z0pHRjR2aW1" 713 "jRlEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJj" 714 "cm9zc09yaWdpbiI6ZmFsc2V9" 715 ), 716 "signature": ( 717 "MEQCIAHQCGfE_PX1z6mBDaXUNqK_NrllhXylNOmETUD3Khv9AiBTl" 718 "rX3GDRj5OaOfTToOwUwAhtd74tu0T6DZAVHPb_hlQ==" 719 ), 720 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABg==", 721 "userHandle": None, 722 }, 723 } 724 725 self.assertEqual(validate_challenge_webauthn(assertion, stage_view, self.user), device) 726 self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context)
Test that a challenge is removed after an assertion verifies
728 def test_validate_challenge_invalid(self): 729 """Test webauthn""" 730 request = self.request_factory.get("/") 731 request.user = self.user 732 733 WebAuthnDevice.objects.create( 734 user=self.user, 735 public_key=( 736 "pQECAyYgASFYIGsBLkklToCQkT7qJT_bJYN1sEc1oJdbnmoOc4" 737 "3i0JH6IlggLTXytuhzFVYYAK4PQNj8_coGrbbzSfUxdiPAcZTQCyU" 738 ), 739 credential_id="QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 740 # One more sign count than above, make it invalid 741 sign_count=5, 742 rp_id=generate_id(), 743 ) 744 flow = create_test_flow() 745 stage = AuthenticatorValidateStage.objects.create( 746 name=generate_id(), 747 not_configured_action=NotConfiguredAction.CONFIGURE, 748 device_classes=[DeviceClasses.WEBAUTHN], 749 ) 750 plan = FlowPlan(flow.pk.hex) 751 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 752 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 753 ) 754 request = self.request_factory.get("/") 755 756 stage_view = AuthenticatorValidateStageView( 757 FlowExecutorView(flow=flow, current_stage=stage, plan=plan), request=request 758 ) 759 request.META["SERVER_NAME"] = "localhost" 760 request.META["SERVER_PORT"] = "9000" 761 with self.assertRaises(ValidationError): 762 validate_challenge_webauthn( 763 { 764 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 765 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 766 "type": "public-key", 767 "assertionClientExtensions": "{}", 768 "response": { 769 "clientDataJSON": ( 770 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2WlhvNWx4" 771 "TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGczQWdPNFdo" 772 "LUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0Ojkw" 773 "MDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2FuX2JlX2FkZGVkX2hl" 774 "cmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBhZ2FpbnN0IGEgdGVtcGxh" 775 "dGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 776 ), 777 "signature": ( 778 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 779 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 780 ), 781 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 782 "userHandle": None, 783 }, 784 }, 785 stage_view, 786 self.user, 787 )
Test webauthn
871 @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA") 872 def test_validate_challenge_mldsa(self): 873 """Test webauthn authentication with an ML-DSA-44 (FIPS 204) credential""" 874 credential = SoftwareCredential(rp_id="localhost", origin="http://localhost:9000") 875 device = WebAuthnDevice.objects.create( 876 user=self.user, 877 public_key=bytes_to_base64url(credential.cose_public_key), 878 credential_id=bytes_to_base64url(credential.credential_id), 879 sign_count=0, 880 rp_id="localhost", 881 ) 882 flow = create_test_flow() 883 stage = AuthenticatorValidateStage.objects.create( 884 name=generate_id(), 885 not_configured_action=NotConfiguredAction.CONFIGURE, 886 device_classes=[DeviceClasses.WEBAUTHN], 887 ) 888 challenge = b"\x02" * 64 889 session = self.client.session 890 plan = FlowPlan(flow_pk=flow.pk.hex) 891 plan.append_stage(stage) 892 plan.append_stage(UserLoginStage.objects.create(name=generate_id())) 893 plan.context[PLAN_CONTEXT_PENDING_USER] = self.user 894 plan.context[PLAN_CONTEXT_DEVICE_CHALLENGES] = [ 895 { 896 "device_class": device.__class__.__name__.lower().replace("device", ""), 897 "device_uid": device.pk, 898 "challenge": {}, 899 "last_used": None, 900 } 901 ] 902 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge 903 session[SESSION_KEY_PLAN] = plan 904 session.save() 905 906 response = self.client.post( 907 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 908 data={"webauthn": credential.assertion_response(challenge)}, 909 SERVER_NAME="localhost", 910 SERVER_PORT="9000", 911 ) 912 self.assertEqual(response.status_code, 302) 913 response = self.client.get( 914 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 915 ) 916 self.assertStageRedirects(response, reverse("authentik_core:root-redirect")) 917 device.refresh_from_db() 918 self.assertEqual(device.sign_count, 1)
Test webauthn authentication with an ML-DSA-44 (FIPS 204) credential
958 def test_render_reuses_webauthn_challenge(self): 959 """Test that rendering the stage again doesn't replace the pending challenge""" 960 flow = self._plan_at_webauthn_stage() 961 962 first = self._render_stage(flow) 963 second = self._render_stage(flow) 964 965 self.assertIsNotNone(first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]) 966 self.assertEqual( 967 first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE], second[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] 968 ) 969 self.assertEqual( 970 first[PLAN_CONTEXT_DEVICE_CHALLENGES], second[PLAN_CONTEXT_DEVICE_CHALLENGES] 971 )
Test that rendering the stage again doesn't replace the pending challenge
973 def test_render_reuses_webauthn_challenge_userless(self): 974 """Test that rendering the stage again doesn't replace the pending challenge 975 (user-less)""" 976 flow = self._plan_at_webauthn_stage(pending_user=False) 977 978 first = self._render_stage(flow) 979 second = self._render_stage(flow) 980 981 self.assertIsNotNone(first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]) 982 self.assertEqual( 983 first[PLAN_CONTEXT_WEBAUTHN_CHALLENGE], second[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] 984 )
Test that rendering the stage again doesn't replace the pending challenge (user-less)
986 def test_validate_challenge_after_render(self): 987 """Test that a response to a challenge is still accepted after the stage was 988 rendered again (e.g. by another tab), and that the challenge can't be answered 989 again afterwards""" 990 flow = self._plan_at_webauthn_stage() 991 session = self.client.session 992 plan: FlowPlan = session[SESSION_KEY_PLAN] 993 # The challenge the assertion below was signed for 994 plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = base64url_to_bytes( 995 "g98I51mQvZXo5lxLfhrD2zfolhZbLRyCgqkkYap1jwSaJ13BguoJWCF9_Lg3AgO4Wh-Bqa556JE20oKsYbl6RA" 996 ) 997 session[SESSION_KEY_PLAN] = plan 998 session.save() 999 1000 # Render the stage twice, e.g. the original tab and another tab 1001 self._render_stage(flow) 1002 self._render_stage(flow) 1003 1004 response = self.client.post( 1005 reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), 1006 data={ 1007 "webauthn": { 1008 "id": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 1009 "rawId": "QKZ97ASJAOIDyipAs6mKUxDUZgDrWrbAsUb5leL7-oU", 1010 "type": "public-key", 1011 "assertionClientExtensions": "{}", 1012 "response": { 1013 "clientDataJSON": ( 1014 "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZzk4STUxbVF2Wlhv" 1015 "NWx4TGZockQyemZvbGhaYkxSeUNncWtrWWFwMWp3U2FKMTNCZ3VvSldDRjlfTGcz" 1016 "QWdPNFdoLUJxYTU1NkpFMjBvS3NZYmw2UkEiLCJvcmlnaW4iOiJodHRwOi8vbG9j" 1017 "YWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2UsIm90aGVyX2tleXNfY2Fu" 1018 "X2JlX2FkZGVkX2hlcmUiOiJkbyBub3QgY29tcGFyZSBjbGllbnREYXRhSlNPTiBh" 1019 "Z2FpbnN0IGEgdGVtcGxhdGUuIFNlZSBodHRwczovL2dvby5nbC95YWJQZXgifQ==" 1020 ), 1021 "signature": ( 1022 "MEQCIFNlrHf9ablJAalXLWkrqvHB8oIu8kwvRpH3X3rbJVpI" 1023 "AiAqtOK6mIZPk62kZN0OzFsHfuvu_RlOl7zlqSNzDdz_Ag==" 1024 ), 1025 "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ==", 1026 "userHandle": None, 1027 }, 1028 }, 1029 }, 1030 SERVER_NAME="localhost", 1031 SERVER_PORT="9000", 1032 ) 1033 self.assertEqual(response.status_code, 302) 1034 plan: FlowPlan = self.client.session[SESSION_KEY_PLAN] 1035 self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context)
Test that a response to a challenge is still accepted after the stage was rendered again (e.g. by another tab), and that the challenge can't be answered again afterwards