authentik.stages.authenticator_validate.challenge

Validation stage challenge checking

  1"""Validation stage challenge checking"""
  2
  3from typing import TYPE_CHECKING
  4from urllib.parse import urlencode
  5
  6from cryptography.exceptions import InternalError, UnsupportedAlgorithm
  7from cryptography.hazmat.backends.openssl.backend import backend
  8from django.db import transaction
  9from django.http import HttpRequest
 10from django.http.response import Http404
 11from django.shortcuts import get_object_or_404
 12from django.utils.translation import gettext_lazy as _
 13from rest_framework.fields import CharField, ChoiceField, DateTimeField
 14from rest_framework.serializers import ValidationError
 15from structlog.stdlib import get_logger
 16from webauthn.authentication.generate_authentication_options import generate_authentication_options
 17from webauthn.authentication.verify_authentication_response import verify_authentication_response
 18from webauthn.helpers import parse_authentication_credential_json
 19from webauthn.helpers.base64url_to_bytes import base64url_to_bytes
 20from webauthn.helpers.exceptions import UnsupportedAlgorithm as WebAuthnUnsupportedAlgorithm
 21from webauthn.helpers.exceptions import UnsupportedPublicKey, WebAuthnException
 22from webauthn.helpers.options_to_json_dict import options_to_json_dict
 23from webauthn.helpers.structs import PublicKeyCredentialType, UserVerificationRequirement
 24
 25from authentik.core.api.utils import JSONDictField, PassiveSerializer
 26from authentik.core.models import Application, User
 27from authentik.core.signals import login_failed
 28from authentik.events.middleware import audit_ignore
 29from authentik.events.models import Event, EventAction
 30from authentik.flows.planner import PLAN_CONTEXT_APPLICATION
 31from authentik.flows.stage import StageView
 32from authentik.lib.utils.email import mask_email
 33from authentik.lib.utils.time import timedelta_from_string
 34from authentik.root.middleware import ClientIPMiddleware
 35from authentik.stages.authenticator import devices_for_user
 36from authentik.stages.authenticator.models import Device, ThrottlingMixin
 37from authentik.stages.authenticator_duo.models import AuthenticatorDuoStage, DuoDevice
 38from authentik.stages.authenticator_email.models import EmailDevice
 39from authentik.stages.authenticator_sms.models import SMSDevice
 40from authentik.stages.authenticator_validate.models import AuthenticatorValidateStage, DeviceClasses
 41from authentik.stages.authenticator_webauthn.algorithms import credential_key_type
 42from authentik.stages.authenticator_webauthn.models import UserVerification, WebAuthnDevice
 43from authentik.stages.authenticator_webauthn.stage import PLAN_CONTEXT_WEBAUTHN_CHALLENGE
 44from authentik.stages.authenticator_webauthn.utils import get_expected_origins, get_rp_id
 45from authentik.stages.password.stage import PLAN_CONTEXT_METHOD_ARGS
 46
 47if TYPE_CHECKING:
 48    from authentik.stages.authenticator_validate.stage import AuthenticatorValidateStageView
 49
 50LOGGER = get_logger()
 51
 52
 53class DeviceChallenge(PassiveSerializer):
 54    """Single device challenge"""
 55
 56    device_class = ChoiceField(choices=DeviceClasses.choices)
 57    device_uid = CharField()
 58    challenge = JSONDictField()
 59    last_used = DateTimeField(allow_null=True)
 60
 61
 62def get_challenge_for_device(
 63    stage_view: AuthenticatorValidateStageView, stage: AuthenticatorValidateStage, device: Device
 64) -> dict:
 65    """Generate challenge for a single device"""
 66    if isinstance(device, WebAuthnDevice):
 67        return get_webauthn_challenge(stage_view, stage, device)
 68    if isinstance(device, EmailDevice):
 69        return {"email": mask_email(device.email)}
 70    # Code-based challenges have no hints
 71    return {}
 72
 73
 74def get_webauthn_challenge_without_user(
 75    stage_view: AuthenticatorValidateStageView, stage: AuthenticatorValidateStage
 76) -> dict:
 77    """Same as `get_webauthn_challenge`, but allows any client device. We can then later check
 78    who the device belongs to."""
 79    authentication_options = generate_authentication_options(
 80        rp_id=get_rp_id(stage_view.request),
 81        challenge=stage_view.executor.plan.context.get(PLAN_CONTEXT_WEBAUTHN_CHALLENGE),
 82        allow_credentials=[],
 83        user_verification=UserVerificationRequirement(stage.webauthn_user_verification),
 84    )
 85    stage_view.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = (
 86        authentication_options.challenge
 87    )
 88
 89    options_dict = options_to_json_dict(authentication_options)
 90    if stage.webauthn_hints:
 91        options_dict["hints"] = list(stage.webauthn_hints)
 92    return options_dict
 93
 94
 95def get_webauthn_challenge(
 96    stage_view: AuthenticatorValidateStageView,
 97    stage: AuthenticatorValidateStage,
 98    device: WebAuthnDevice | None = None,
 99) -> dict:
100    """Send the client a challenge that we'll check later"""
101    allowed_credentials = []
102
103    if device:
104        # We want all the user's WebAuthn devices and merge their challenges
105        for user_device in WebAuthnDevice.objects.filter(user=device.user).order_by("name"):
106            user_device: WebAuthnDevice
107            allowed_credentials.append(user_device.descriptor)
108
109    authentication_options = generate_authentication_options(
110        rp_id=get_rp_id(stage_view.request),
111        challenge=stage_view.executor.plan.context.get(PLAN_CONTEXT_WEBAUTHN_CHALLENGE),
112        allow_credentials=allowed_credentials,
113        user_verification=UserVerificationRequirement(stage.webauthn_user_verification),
114    )
115
116    stage_view.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = (
117        authentication_options.challenge
118    )
119
120    options_dict = options_to_json_dict(authentication_options)
121    if stage.webauthn_hints:
122        options_dict["hints"] = list(stage.webauthn_hints)
123    return options_dict
124
125
126def select_challenge(request: HttpRequest, device: Device):
127    """Callback when the user selected a challenge in the frontend."""
128    if isinstance(device, SMSDevice):
129        select_challenge_sms(request, device)
130    elif isinstance(device, EmailDevice):
131        select_challenge_email(request, device)
132
133
134def select_challenge_sms(request: HttpRequest, device: SMSDevice):
135    """Send SMS"""
136    device.generate_token()
137    device.stage.send(request, device.token, device)
138
139
140def select_challenge_email(request: HttpRequest, device: EmailDevice):
141    """Send Email"""
142    valid_secs: int = timedelta_from_string(device.stage.token_expiry).total_seconds()
143    device.generate_token(valid_secs=valid_secs)
144    device.stage.send(request, device)
145
146
147def validate_challenge_code(
148    code: str, stage_view: StageView, user: User, challenges: list[dict]
149) -> Device:
150    """Validate code-based challenges against eligible devices.
151
152    TOTP and static challenges represent all of the user's devices of that class,
153    while email and SMS challenges are bound to a specific device.
154    """
155    stage = stage_view.executor.current_stage
156    class_wide_challenges = {
157        challenge["device_class"]
158        for challenge in challenges
159        if challenge["device_class"] in (DeviceClasses.TOTP, DeviceClasses.STATIC)
160    }
161    device_specific_challenges = {
162        (challenge["device_class"], challenge["device_uid"])
163        for challenge in challenges
164        if challenge["device_class"] in (DeviceClasses.EMAIL, DeviceClasses.SMS)
165    }
166
167    # audit_ignore decorator to prevent them being logged during authentication,
168    # and to send them via SSF
169
170    with transaction.atomic(), audit_ignore():
171        for device in devices_for_user(user, for_verify=True):
172            device_class = DeviceClasses.from_model_label(device.model_label())
173            if device_class not in stage.device_classes:
174                continue
175            if device_class in (DeviceClasses.TOTP, DeviceClasses.STATIC):
176                # One challenge covers all enrolled devices of this class.
177                if device_class not in class_wide_challenges:
178                    continue
179            elif device_class in (DeviceClasses.EMAIL, DeviceClasses.SMS):
180                # Delivery-based codes must belong to the challenged device.
181                if (device_class, str(device.pk)) not in device_specific_challenges:
182                    continue
183            else:
184                # Other device classes cannot authenticate through the code field.
185                continue
186            if isinstance(device, ThrottlingMixin):
187                throttling_factor = stage.get_throttling_factor(device_class)
188                if throttling_factor is not None:
189                    device.set_throttle_factor(throttling_factor)
190            if device.verify_token(code):
191                break
192        else:
193            device = None
194
195    if not device:
196        login_failed.send(
197            sender=__name__,
198            credentials={"username": user.username},
199            request=stage_view.request,
200            stage=stage_view.executor.current_stage,
201            context={
202                PLAN_CONTEXT_METHOD_ARGS: {
203                    "device_class": DeviceClasses.TOTP.value,
204                }
205            },
206        )
207        raise ValidationError(
208            _("Invalid Token. Please ensure the time on your device is accurate and try again.")
209        )
210    return device
211
212
213def validate_challenge_webauthn(
214    data: dict,
215    stage_view: StageView,
216    user: User,
217    stage: AuthenticatorValidateStage | None = None,
218) -> Device:
219    """Validate WebAuthn Challenge"""
220    request = stage_view.request
221    challenge = stage_view.executor.plan.context.get(PLAN_CONTEXT_WEBAUTHN_CHALLENGE)
222    stage = stage or stage_view.executor.current_stage
223
224    if "MinuteMaid" in request.META.get("HTTP_USER_AGENT", ""):
225        # Workaround for Android sign-in, when signing into Google Workspace on android while
226        # adding the account to the system (not in Chrome), for some reason `type` is not set
227        # so in that case we fall back to `public-key`
228        # since that's the only option we support anyways
229        data.setdefault("type", PublicKeyCredentialType.PUBLIC_KEY)
230    try:
231        credential = parse_authentication_credential_json(data)
232    # py_webauthn wraps most decoding errors in InvalidAuthenticationResponse, but not those of
233    # userHandle, which raise ValueError
234    except (WebAuthnException, ValueError) as exc:
235        LOGGER.warning("Invalid WebAuthn challenge response", exc=exc)
236        raise ValidationError("Invalid device", "invalid") from None
237
238    device = WebAuthnDevice.objects.filter(credential_id=credential.id).first()
239    if not device:
240        raise ValidationError("Invalid device", "invalid")
241    # We can only check the device's user if the user we're given isn't anonymous
242    # as this validation is also used for password-less login where webauthn is the very first
243    # step done by a user. Only if this validation happens at a later stage we can check
244    # that the device belongs to the user
245    if not user.is_anonymous and device.user != user:
246        raise ValidationError("Invalid device", "invalid")
247    # When a device_type was set when creating the device (2024.4+), and we have a limitation,
248    # make sure the device type is allowed.
249    if (
250        device.device_type
251        and stage.webauthn_allowed_device_types.exists()
252        and not stage.webauthn_allowed_device_types.filter(pk=device.device_type.pk).exists()
253    ):
254        raise ValidationError(
255            _("Invalid device type. Contact your {brand} administrator for help.").format(
256                brand=stage_view.request.brand.branding_title
257            ),
258            "invalid",
259        )
260    try:
261        authentication_verification = verify_authentication_response(
262            credential=credential,
263            expected_challenge=challenge,
264            expected_rp_id=get_rp_id(request),
265            expected_origin=get_expected_origins(
266                request, stage.webauthn_additional_accepted_origins
267            ),
268            credential_public_key=base64url_to_bytes(device.public_key),
269            credential_current_sign_count=device.sign_count,
270            require_user_verification=stage.webauthn_user_verification == UserVerification.REQUIRED,
271        )
272    except (WebAuthnException, ValueError, InternalError, UnsupportedAlgorithm) as exc:
273        error = _("Assertion failed")
274        event_context = {}
275        if isinstance(
276            exc,
277            ValueError
278            | InternalError
279            | UnsupportedAlgorithm
280            | UnsupportedPublicKey
281            | WebAuthnUnsupportedAlgorithm,
282        ):
283            # TODO: Remove when OpenSSL/FIPS is updated
284            # The credential's public key could not be loaded or used because its algorithm has
285            # no implementation in the current OpenSSL configuration, for example an Ed25519 or
286            # ML-DSA credential under the validated FIPS provider. cryptography reports a missing
287            # Ed25519 implementation as a key-length ValueError; py_webauthn wraps the ML-DSA
288            # failure in UnsupportedPublicKey.
289            key_type = credential_key_type(base64url_to_bytes(device.public_key))
290            fips_enabled = backend._fips_enabled
291            if fips_enabled:
292                detail = f"Cannot log in with {key_type} security key while FIPS mode is enabled"
293            else:
294                detail = (
295                    f"Cannot log in with {key_type} security key: the key type is not available "
296                    "in the current OpenSSL configuration"
297                )
298            LOGGER.warning(
299                detail, key_type=key_type, fips_enabled=fips_enabled, device=device, exc=exc
300            )
301            # The user gets a generic error; the details are for administrators in the log and
302            # event. Event context keys containing "key" are masked, hence "algorithm".
303            error = _("Invalid security key. Please re-register or contact an administrator.")
304            event_context = {"message": detail, "algorithm": key_type, "fips_enabled": fips_enabled}
305        else:
306            LOGGER.warning("Assertion failed", exc=exc)
307        login_failed.send(
308            sender=__name__,
309            credentials={"username": user.username},
310            request=stage_view.request,
311            stage=stage_view.executor.current_stage,
312            context={
313                PLAN_CONTEXT_METHOD_ARGS: {
314                    "device": device,
315                    "device_class": DeviceClasses.WEBAUTHN.value,
316                    "device_type": device.device_type,
317                },
318                **event_context,
319            },
320        )
321        raise ValidationError(error) from exc
322
323    # Challenges are single-use. The generators reuse a pending challenge until an assertion
324    # verifies, so consume it here for every caller before accepting another assertion.
325    stage_view.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
326    with audit_ignore():
327        device.set_sign_count(authentication_verification.new_sign_count)
328    return device
329
330
331def validate_challenge_duo(device_pk: int, stage_view: StageView, user: User) -> Device:
332    """Duo authentication"""
333    device = get_object_or_404(DuoDevice, pk=device_pk)
334    if device.user != user:
335        LOGGER.warning("device mismatch")
336        raise Http404
337    stage: AuthenticatorDuoStage = device.stage
338
339    # Get additional context for push
340    pushinfo = {
341        str(_("Domain")): stage_view.request.get_host(),
342    }
343    if PLAN_CONTEXT_APPLICATION in stage_view.executor.plan.context:
344        pushinfo[str(_("Application"))] = stage_view.executor.plan.context.get(
345            PLAN_CONTEXT_APPLICATION, Application()
346        ).name
347
348    try:
349        response = stage.auth_client().auth(
350            "auto",
351            user_id=device.duo_user_id,
352            ipaddr=ClientIPMiddleware.get_client_ip(stage_view.request),
353            type=_("{brand_name} Login request").format(
354                brand_name=stage_view.request.brand.branding_title
355            ),
356            display_username=user.username,
357            device="auto",
358            pushinfo=urlencode(pushinfo),
359        )
360        # {'result': 'allow', 'status': 'allow', 'status_msg': 'Success. Logging you in...'}
361        if response["result"] == "deny":
362            LOGGER.debug("duo push response", result=response["result"], msg=response["status_msg"])
363            login_failed.send(
364                sender=__name__,
365                credentials={"username": user.username},
366                request=stage_view.request,
367                stage=stage_view.executor.current_stage,
368                context={
369                    PLAN_CONTEXT_METHOD_ARGS: {
370                        "device_class": DeviceClasses.DUO.value,
371                        "duo_response": response,
372                    }
373                },
374            )
375            raise ValidationError("Duo denied access", code="denied")
376        return device
377    except RuntimeError as exc:
378        Event.new(
379            EventAction.CONFIGURATION_ERROR,
380            message=f"Failed to DUO authenticate user: {str(exc)}",
381            user=user,
382        ).from_http(stage_view.request, user)
383        raise ValidationError("Duo denied access", code="denied") from exc
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class DeviceChallenge(authentik.core.api.utils.PassiveSerializer):
54class DeviceChallenge(PassiveSerializer):
55    """Single device challenge"""
56
57    device_class = ChoiceField(choices=DeviceClasses.choices)
58    device_uid = CharField()
59    challenge = JSONDictField()
60    last_used = DateTimeField(allow_null=True)

Single device challenge

device_class
device_uid
challenge
last_used
def get_challenge_for_device(unknown):
63def get_challenge_for_device(
64    stage_view: AuthenticatorValidateStageView, stage: AuthenticatorValidateStage, device: Device
65) -> dict:
66    """Generate challenge for a single device"""
67    if isinstance(device, WebAuthnDevice):
68        return get_webauthn_challenge(stage_view, stage, device)
69    if isinstance(device, EmailDevice):
70        return {"email": mask_email(device.email)}
71    # Code-based challenges have no hints
72    return {}

Generate challenge for a single device

def get_webauthn_challenge_without_user(unknown):
75def get_webauthn_challenge_without_user(
76    stage_view: AuthenticatorValidateStageView, stage: AuthenticatorValidateStage
77) -> dict:
78    """Same as `get_webauthn_challenge`, but allows any client device. We can then later check
79    who the device belongs to."""
80    authentication_options = generate_authentication_options(
81        rp_id=get_rp_id(stage_view.request),
82        challenge=stage_view.executor.plan.context.get(PLAN_CONTEXT_WEBAUTHN_CHALLENGE),
83        allow_credentials=[],
84        user_verification=UserVerificationRequirement(stage.webauthn_user_verification),
85    )
86    stage_view.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = (
87        authentication_options.challenge
88    )
89
90    options_dict = options_to_json_dict(authentication_options)
91    if stage.webauthn_hints:
92        options_dict["hints"] = list(stage.webauthn_hints)
93    return options_dict

Same as get_webauthn_challenge, but allows any client device. We can then later check who the device belongs to.

def get_webauthn_challenge(unknown):
 96def get_webauthn_challenge(
 97    stage_view: AuthenticatorValidateStageView,
 98    stage: AuthenticatorValidateStage,
 99    device: WebAuthnDevice | None = None,
100) -> dict:
101    """Send the client a challenge that we'll check later"""
102    allowed_credentials = []
103
104    if device:
105        # We want all the user's WebAuthn devices and merge their challenges
106        for user_device in WebAuthnDevice.objects.filter(user=device.user).order_by("name"):
107            user_device: WebAuthnDevice
108            allowed_credentials.append(user_device.descriptor)
109
110    authentication_options = generate_authentication_options(
111        rp_id=get_rp_id(stage_view.request),
112        challenge=stage_view.executor.plan.context.get(PLAN_CONTEXT_WEBAUTHN_CHALLENGE),
113        allow_credentials=allowed_credentials,
114        user_verification=UserVerificationRequirement(stage.webauthn_user_verification),
115    )
116
117    stage_view.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = (
118        authentication_options.challenge
119    )
120
121    options_dict = options_to_json_dict(authentication_options)
122    if stage.webauthn_hints:
123        options_dict["hints"] = list(stage.webauthn_hints)
124    return options_dict

Send the client a challenge that we'll check later

def select_challenge( request: django.http.request.HttpRequest, device: authentik.stages.authenticator.models.Device):
127def select_challenge(request: HttpRequest, device: Device):
128    """Callback when the user selected a challenge in the frontend."""
129    if isinstance(device, SMSDevice):
130        select_challenge_sms(request, device)
131    elif isinstance(device, EmailDevice):
132        select_challenge_email(request, device)

Callback when the user selected a challenge in the frontend.

def select_challenge_sms( request: django.http.request.HttpRequest, device: authentik.stages.authenticator_sms.models.SMSDevice):
135def select_challenge_sms(request: HttpRequest, device: SMSDevice):
136    """Send SMS"""
137    device.generate_token()
138    device.stage.send(request, device.token, device)

Send SMS

def select_challenge_email( request: django.http.request.HttpRequest, device: authentik.stages.authenticator_email.models.EmailDevice):
141def select_challenge_email(request: HttpRequest, device: EmailDevice):
142    """Send Email"""
143    valid_secs: int = timedelta_from_string(device.stage.token_expiry).total_seconds()
144    device.generate_token(valid_secs=valid_secs)
145    device.stage.send(request, device)

Send Email

def validate_challenge_code( code: str, stage_view: authentik.flows.stage.StageView, user: authentik.core.models.User, challenges: list[dict]) -> authentik.stages.authenticator.models.Device:
148def validate_challenge_code(
149    code: str, stage_view: StageView, user: User, challenges: list[dict]
150) -> Device:
151    """Validate code-based challenges against eligible devices.
152
153    TOTP and static challenges represent all of the user's devices of that class,
154    while email and SMS challenges are bound to a specific device.
155    """
156    stage = stage_view.executor.current_stage
157    class_wide_challenges = {
158        challenge["device_class"]
159        for challenge in challenges
160        if challenge["device_class"] in (DeviceClasses.TOTP, DeviceClasses.STATIC)
161    }
162    device_specific_challenges = {
163        (challenge["device_class"], challenge["device_uid"])
164        for challenge in challenges
165        if challenge["device_class"] in (DeviceClasses.EMAIL, DeviceClasses.SMS)
166    }
167
168    # audit_ignore decorator to prevent them being logged during authentication,
169    # and to send them via SSF
170
171    with transaction.atomic(), audit_ignore():
172        for device in devices_for_user(user, for_verify=True):
173            device_class = DeviceClasses.from_model_label(device.model_label())
174            if device_class not in stage.device_classes:
175                continue
176            if device_class in (DeviceClasses.TOTP, DeviceClasses.STATIC):
177                # One challenge covers all enrolled devices of this class.
178                if device_class not in class_wide_challenges:
179                    continue
180            elif device_class in (DeviceClasses.EMAIL, DeviceClasses.SMS):
181                # Delivery-based codes must belong to the challenged device.
182                if (device_class, str(device.pk)) not in device_specific_challenges:
183                    continue
184            else:
185                # Other device classes cannot authenticate through the code field.
186                continue
187            if isinstance(device, ThrottlingMixin):
188                throttling_factor = stage.get_throttling_factor(device_class)
189                if throttling_factor is not None:
190                    device.set_throttle_factor(throttling_factor)
191            if device.verify_token(code):
192                break
193        else:
194            device = None
195
196    if not device:
197        login_failed.send(
198            sender=__name__,
199            credentials={"username": user.username},
200            request=stage_view.request,
201            stage=stage_view.executor.current_stage,
202            context={
203                PLAN_CONTEXT_METHOD_ARGS: {
204                    "device_class": DeviceClasses.TOTP.value,
205                }
206            },
207        )
208        raise ValidationError(
209            _("Invalid Token. Please ensure the time on your device is accurate and try again.")
210        )
211    return device

Validate code-based challenges against eligible devices.

TOTP and static challenges represent all of the user's devices of that class, while email and SMS challenges are bound to a specific device.

214def validate_challenge_webauthn(
215    data: dict,
216    stage_view: StageView,
217    user: User,
218    stage: AuthenticatorValidateStage | None = None,
219) -> Device:
220    """Validate WebAuthn Challenge"""
221    request = stage_view.request
222    challenge = stage_view.executor.plan.context.get(PLAN_CONTEXT_WEBAUTHN_CHALLENGE)
223    stage = stage or stage_view.executor.current_stage
224
225    if "MinuteMaid" in request.META.get("HTTP_USER_AGENT", ""):
226        # Workaround for Android sign-in, when signing into Google Workspace on android while
227        # adding the account to the system (not in Chrome), for some reason `type` is not set
228        # so in that case we fall back to `public-key`
229        # since that's the only option we support anyways
230        data.setdefault("type", PublicKeyCredentialType.PUBLIC_KEY)
231    try:
232        credential = parse_authentication_credential_json(data)
233    # py_webauthn wraps most decoding errors in InvalidAuthenticationResponse, but not those of
234    # userHandle, which raise ValueError
235    except (WebAuthnException, ValueError) as exc:
236        LOGGER.warning("Invalid WebAuthn challenge response", exc=exc)
237        raise ValidationError("Invalid device", "invalid") from None
238
239    device = WebAuthnDevice.objects.filter(credential_id=credential.id).first()
240    if not device:
241        raise ValidationError("Invalid device", "invalid")
242    # We can only check the device's user if the user we're given isn't anonymous
243    # as this validation is also used for password-less login where webauthn is the very first
244    # step done by a user. Only if this validation happens at a later stage we can check
245    # that the device belongs to the user
246    if not user.is_anonymous and device.user != user:
247        raise ValidationError("Invalid device", "invalid")
248    # When a device_type was set when creating the device (2024.4+), and we have a limitation,
249    # make sure the device type is allowed.
250    if (
251        device.device_type
252        and stage.webauthn_allowed_device_types.exists()
253        and not stage.webauthn_allowed_device_types.filter(pk=device.device_type.pk).exists()
254    ):
255        raise ValidationError(
256            _("Invalid device type. Contact your {brand} administrator for help.").format(
257                brand=stage_view.request.brand.branding_title
258            ),
259            "invalid",
260        )
261    try:
262        authentication_verification = verify_authentication_response(
263            credential=credential,
264            expected_challenge=challenge,
265            expected_rp_id=get_rp_id(request),
266            expected_origin=get_expected_origins(
267                request, stage.webauthn_additional_accepted_origins
268            ),
269            credential_public_key=base64url_to_bytes(device.public_key),
270            credential_current_sign_count=device.sign_count,
271            require_user_verification=stage.webauthn_user_verification == UserVerification.REQUIRED,
272        )
273    except (WebAuthnException, ValueError, InternalError, UnsupportedAlgorithm) as exc:
274        error = _("Assertion failed")
275        event_context = {}
276        if isinstance(
277            exc,
278            ValueError
279            | InternalError
280            | UnsupportedAlgorithm
281            | UnsupportedPublicKey
282            | WebAuthnUnsupportedAlgorithm,
283        ):
284            # TODO: Remove when OpenSSL/FIPS is updated
285            # The credential's public key could not be loaded or used because its algorithm has
286            # no implementation in the current OpenSSL configuration, for example an Ed25519 or
287            # ML-DSA credential under the validated FIPS provider. cryptography reports a missing
288            # Ed25519 implementation as a key-length ValueError; py_webauthn wraps the ML-DSA
289            # failure in UnsupportedPublicKey.
290            key_type = credential_key_type(base64url_to_bytes(device.public_key))
291            fips_enabled = backend._fips_enabled
292            if fips_enabled:
293                detail = f"Cannot log in with {key_type} security key while FIPS mode is enabled"
294            else:
295                detail = (
296                    f"Cannot log in with {key_type} security key: the key type is not available "
297                    "in the current OpenSSL configuration"
298                )
299            LOGGER.warning(
300                detail, key_type=key_type, fips_enabled=fips_enabled, device=device, exc=exc
301            )
302            # The user gets a generic error; the details are for administrators in the log and
303            # event. Event context keys containing "key" are masked, hence "algorithm".
304            error = _("Invalid security key. Please re-register or contact an administrator.")
305            event_context = {"message": detail, "algorithm": key_type, "fips_enabled": fips_enabled}
306        else:
307            LOGGER.warning("Assertion failed", exc=exc)
308        login_failed.send(
309            sender=__name__,
310            credentials={"username": user.username},
311            request=stage_view.request,
312            stage=stage_view.executor.current_stage,
313            context={
314                PLAN_CONTEXT_METHOD_ARGS: {
315                    "device": device,
316                    "device_class": DeviceClasses.WEBAUTHN.value,
317                    "device_type": device.device_type,
318                },
319                **event_context,
320            },
321        )
322        raise ValidationError(error) from exc
323
324    # Challenges are single-use. The generators reuse a pending challenge until an assertion
325    # verifies, so consume it here for every caller before accepting another assertion.
326    stage_view.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
327    with audit_ignore():
328        device.set_sign_count(authentication_verification.new_sign_count)
329    return device

Validate WebAuthn Challenge

def validate_challenge_duo( device_pk: int, stage_view: authentik.flows.stage.StageView, user: authentik.core.models.User) -> authentik.stages.authenticator.models.Device:
332def validate_challenge_duo(device_pk: int, stage_view: StageView, user: User) -> Device:
333    """Duo authentication"""
334    device = get_object_or_404(DuoDevice, pk=device_pk)
335    if device.user != user:
336        LOGGER.warning("device mismatch")
337        raise Http404
338    stage: AuthenticatorDuoStage = device.stage
339
340    # Get additional context for push
341    pushinfo = {
342        str(_("Domain")): stage_view.request.get_host(),
343    }
344    if PLAN_CONTEXT_APPLICATION in stage_view.executor.plan.context:
345        pushinfo[str(_("Application"))] = stage_view.executor.plan.context.get(
346            PLAN_CONTEXT_APPLICATION, Application()
347        ).name
348
349    try:
350        response = stage.auth_client().auth(
351            "auto",
352            user_id=device.duo_user_id,
353            ipaddr=ClientIPMiddleware.get_client_ip(stage_view.request),
354            type=_("{brand_name} Login request").format(
355                brand_name=stage_view.request.brand.branding_title
356            ),
357            display_username=user.username,
358            device="auto",
359            pushinfo=urlencode(pushinfo),
360        )
361        # {'result': 'allow', 'status': 'allow', 'status_msg': 'Success. Logging you in...'}
362        if response["result"] == "deny":
363            LOGGER.debug("duo push response", result=response["result"], msg=response["status_msg"])
364            login_failed.send(
365                sender=__name__,
366                credentials={"username": user.username},
367                request=stage_view.request,
368                stage=stage_view.executor.current_stage,
369                context={
370                    PLAN_CONTEXT_METHOD_ARGS: {
371                        "device_class": DeviceClasses.DUO.value,
372                        "duo_response": response,
373                    }
374                },
375            )
376            raise ValidationError("Duo denied access", code="denied")
377        return device
378    except RuntimeError as exc:
379        Event.new(
380            EventAction.CONFIGURATION_ERROR,
381            message=f"Failed to DUO authenticate user: {str(exc)}",
382            user=user,
383        ).from_http(stage_view.request, user)
384        raise ValidationError("Duo denied access", code="denied") from exc

Duo authentication