Debian Codegraph @

flask_security/webauthn.py

raw
1 """
2 flask_security.webauthn
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security WebAuthn module
6
7 :copyright: (c) 2021-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9
10 This implements support for webauthn/FIDO2 Level 2 using the py_webauthn package.
11
12 Check out: https://golb.hplar.ch/2019/08/webauthn.html
13 for some ideas on recovery and adding additional authenticators.
14
15 For testing - you can see your YubiKey (or other) resident keys in chrome!
16 chrome://settings/securityKeys
17
18 Observation: if key isn't resident than Chrome for example won't let you use
19 it if it isn't part of allowedCredentials - throw error: referencing:
20 https://www.w3.org/TR/webauthn-2/#sctn-privacy-considerations-client
21
22 TODO:
23 - update/add examples to support webauthn
24 - should we universally add endpoint urls to JSON responses?
25 - Add a way to order registered credentials so we can return an ordered list
26 in allowCredentials.
27 - #sctn-usecase-new-device-registration - allow more than one "first" key
28 and have them not necessarily be cross-platform.. add form option?
29
30 Research:
31 - should we store things like user verified in 'last use'...
32 - By insisting on 2FA if user has registered a webauthn - things
33 get interesting if they try to log in on a different device....
34 How would they register a security key for a new device? They would need
35 some OTHER 2FA? Force them to register a NEW webauthn key?
36
37 """
38
39 from __future__ import annotations
40
41 import json
42 import time
43 import typing as t
44 from functools import partial
45
46 from flask import abort, after_this_request, request, session
47 from flask import current_app
48 from flask_login import current_user
49 from wtforms import BooleanField, HiddenField, RadioField, StringField, SubmitField
50 from .forms import NextFormMixin
51
52 try:
53 import webauthn
54 from webauthn.authentication.verify_authentication_response import (
55 VerifiedAuthentication,
56 )
57 from webauthn.registration.verify_registration_response import VerifiedRegistration
58 from webauthn.helpers import (
59 options_to_json_dict,
60 parse_registration_credential_json,
61 parse_authentication_credential_json,
62 )
63 from webauthn.helpers.exceptions import (
64 InvalidAuthenticationResponse,
65 InvalidJSONStructure,
66 InvalidRegistrationResponse,
67 )
68 from webauthn.helpers.structs import (
69 AuthenticatorTransport,
70 PublicKeyCredentialDescriptor,
71 PublicKeyCredentialType,
72 UserVerificationRequirement,
73 )
74 from webauthn.helpers import bytes_to_base64url
75 except ImportError: # pragma: no cover
76 pass
77
78 from .decorators import anonymous_user_required, auth_required, unauth_csrf
79 from .forms import (
80 Form,
81 RequiredLocalize,
82 _build_form_from_request,
83 _build_form,
84 _get_form_field_label,
85 get_form_field_xlate,
86 _setup_methods_xlate,
87 IsString,
88 )
89 from .proxies import _security, _datastore
90 from .quart_compat import get_quart_status
91 from .signals import wan_registered, wan_deleted
92 from .tf_plugin import TfPluginBase, tf_set_validity_token_cookie
93 from .utils import (
94 _,
95 base_render_json,
96 check_and_get_token_status,
97 _config_value as cv,
98 do_flash,
99 get_message,
100 _get_post_login_redirect,
101 _get_post_verify_redirect,
102 get_url,
103 login_user,
104 lookup_identity,
105 _propagate_next,
106 simple_render_json,
107 url_for_security,
108 _view_commit,
109 localize_callback,
110 allowed_auth_token,
111 _td_format,
112 )
113
114 if t.TYPE_CHECKING: # pragma: no cover
115 import flask
116 from flask.typing import ResponseValue, ResponseReturnValue
117 from flask_security import Security, UserMixin, WebAuthnMixin
118
119 if get_quart_status(): # pragma: no cover
120 from quart import redirect
121 else:
122 from flask import redirect
123
124
125 class WebAuthnRegisterForm(Form):
126 name: StringField = StringField(
127 get_form_field_xlate(_("Nickname")),
128 validators=[IsString(), RequiredLocalize(message="WEBAUTHN_NAME_REQUIRED")],
129 )
130 usage: RadioField = RadioField(
131 get_form_field_xlate(_("Usage")),
132 choices=[
133 ("first", get_form_field_xlate(_("Use as a first authentication factor"))),
134 (
135 "secondary",
136 get_form_field_xlate(_("Use as a secondary authentication factor")),
137 ),
138 ],
139 default="secondary",
140 validate_choice=True,
141 )
142 submit: SubmitField = SubmitField(
143 label=_get_form_field_label("submit"), id="wan_register"
144 )
145 clean_name: str | None
146
147 def validate(self, **kwargs: t.Any) -> bool:
148 if not super().validate(**kwargs):
149 return False
150 assert isinstance(self.name.errors, list)
151 assert self.name.data
152 msg, self.clean_name = _security.webauthn_util.name_svn(self.name.data)
153 if msg:
154 self.name.errors.append(msg)
155 return False
156 if any([self.clean_name == cred.name for cred in current_user.webauthn]):
157 msg = get_message("WEBAUTHN_NAME_INUSE", name=self.clean_name)[0]
158 self.name.errors.append(msg)
159 return False
160 if not cv("WAN_ALLOW_AS_FIRST_FACTOR"):
161 self.usage.data = "secondary"
162 return True
163
164
165 class WebAuthnRegisterResponseForm(Form):
166 credential: HiddenField = HiddenField()
167 submit: SubmitField = SubmitField(label=_get_form_field_label("submit"))
168
169 # from state
170 challenge: str
171 name: str
172 usage: str
173 user_verification: bool
174 # this is returned to caller (not part of the client form)
175 registration_verification: VerifiedRegistration
176 transports: list[AuthenticatorTransport] = []
177 extensions: str
178
179 def validate(self, **kwargs: t.Any) -> bool:
180 if not super().validate(**kwargs):
181 return False # pragma: no cover
182 assert isinstance(self.credential.errors, list)
183 if not self.credential.data:
184 self.credential.errors.append(get_message("API_ERROR")[0])
185 return False
186 inuse = any([self.name == cred.name for cred in current_user.webauthn])
187 if inuse:
188 msg = get_message("WEBAUTHN_NAME_INUSE", name=self.name)[0]
189 self.credential.errors.append(msg)
190 return False
191 try:
192 reg_cred = parse_registration_credential_json(self.credential.data)
193 except (
194 ValueError,
195 KeyError,
196 InvalidJSONStructure,
197 InvalidRegistrationResponse,
198 ):
199 self.credential.errors.append(get_message("API_ERROR")[0])
200 return False
201 try:
202 self.registration_verification = webauthn.verify_registration_response(
203 credential=reg_cred,
204 expected_challenge=self.challenge.encode(),
205 expected_origin=_security.webauthn_util.origin(),
206 expected_rp_id=request.host.split(":")[0],
207 require_user_verification=self.user_verification,
208 )
209 if _datastore.find_webauthn(credential_id=reg_cred.raw_id):
210 msg = get_message("WEBAUTHN_CREDENTIAL_ID_INUSE")[0]
211 self.credential.errors.append(msg)
212 return False
213 except KeyError:
214 self.credential.errors.append(get_message("API_ERROR")[0])
215 return False
216 except InvalidRegistrationResponse as exc:
217 self.credential.errors.append(
218 get_message("WEBAUTHN_NO_VERIFY", cause=str(exc))[0]
219 )
220 return False
221
222 self.transports = (
223 reg_cred.response.transports if reg_cred.response.transports else []
224 )
225 # Alas py_webauthn doesn't support extensions
226 response_full = json.loads(self.credential.data)
227 # TODO - verify this is JSON (created with JSON.stringify)
228 self.extensions = response_full.get("extensions", None)
229 return True
230
231
232 class WebAuthnSigninForm(Form, NextFormMixin):
233 identity: StringField = StringField(
234 _get_form_field_label("identity"), validators=[IsString()]
235 )
236 remember: BooleanField = BooleanField(
237 _get_form_field_label("remember_me"),
238 default=lambda: cv("DEFAULT_REMEMBER_ME", app=current_app),
239 )
240 submit: SubmitField = SubmitField(
241 label=get_form_field_xlate(_("Start")), id="wan_signin"
242 )
243
244 user: UserMixin | None = None
245 # set by caller - is this a second factor authentication?
246 is_secondary: bool
247
248 def __init__(self, *args: t.Any, **kwargs: t.Any):
249 super().__init__(*args, **kwargs)
250
251 def validate(self, **kwargs: t.Any) -> bool:
252 if not super().validate(**kwargs):
253 return False # pragma: no cover
254 user = None
255 if self.is_secondary:
256 if "tf_user_id" in session:
257 user = _datastore.find_user(fs_uniquifier=session["tf_user_id"])
258 elif cv("WAN_ALLOW_USER_HINTS"):
259 # If we allow HINTS - provide them - but don't error
260 # out if an unknown or disabled account - that would provide too
261 # much 'discovery' capability of un-authenticated users.
262 if self.identity.data:
263 user = lookup_identity(self.identity.data)
264 if user and user.is_active:
265 self.user = user
266 return True
267
268
269 class WebAuthnSigninResponseForm(Form, NextFormMixin):
270 """
271 This form is used both for signin (primary/first or secondary) and verify.
272 """
273
274 remember: HiddenField = HiddenField()
275 submit: SubmitField = SubmitField(label=_get_form_field_label("submit"))
276 credential: HiddenField = HiddenField()
277
278 # set by caller
279 challenge: str
280 user_verification: bool
281 is_secondary: bool
282 is_verify: bool
283 # returned to caller
284 authentication_verification: VerifiedAuthentication
285 user: UserMixin | None = None
286 cred: WebAuthnMixin | None = None
287 # Set to True if this authentication qualifies as 'multifactor'
288 mf_check: bool = False
289
290 def validate(self, **kwargs: t.Any) -> bool:
291 if not super().validate(**kwargs):
292 return False # pragma: no cover
293 assert isinstance(self.credential.errors, list)
294 if not self.credential.data:
295 self.credential.errors.append(get_message("API_ERROR")[0])
296 return False
297 try:
298 auth_cred = parse_authentication_credential_json(self.credential.data)
299 except (
300 ValueError,
301 KeyError,
302 InvalidJSONStructure,
303 InvalidAuthenticationResponse,
304 ):
305 self.credential.errors.append(get_message("API_ERROR")[0])
306 return False
307
308 # Look up credential Id (raw_id) and user. 7.2.6/7
309 self.cred = _datastore.find_webauthn(credential_id=auth_cred.raw_id)
310 if not self.cred:
311 self.credential.errors.append(
312 get_message("WEBAUTHN_UNKNOWN_CREDENTIAL_ID")[0]
313 )
314 return False
315 # This shouldn't be able to happen if datastore properly cascades
316 # delete
317 self.user = _datastore.find_user_from_webauthn(self.cred)
318 if not self.user: # pragma: no cover
319 self.credential.errors.append(
320 get_message("WEBAUTHN_ORPHAN_CREDENTIAL_ID")[0]
321 )
322 return False
323
324 # Verify user Handle. 7.2.6
325 if auth_cred.response.user_handle:
326 if (
327 auth_cred.response.user_handle
328 != self.user.fs_webauthn_user_handle.encode()
329 ):
330 self.credential.errors.append(
331 get_message("WEBAUTHN_MISMATCH_USER_HANDLE")[0]
332 )
333 return False
334
335 # Make sure the usage of credential matches configured
336 if self.is_verify:
337 usage = cv("WAN_ALLOW_AS_VERIFY")
338 elif self.is_secondary:
339 usage = "secondary"
340 else:
341 usage = "first"
342 if not _is_cred_usable(self.cred, usage):
343 self.credential.errors.append(
344 get_message("WEBAUTHN_CREDENTIAL_WRONG_USAGE")[0]
345 )
346 return False
347
348 if not self.user.is_active:
349 self.credential.errors.append(get_message("DISABLED_ACCOUNT")[0])
350 if self.user.is_locked(self.credential.errors):
351 return False
352
353 verify = partial(
354 webauthn.verify_authentication_response,
355 credential=auth_cred,
356 expected_challenge=self.challenge.encode(),
357 expected_origin=_security.webauthn_util.origin(),
358 expected_rp_id=request.host.split(":")[0],
359 credential_public_key=self.cred.public_key,
360 credential_current_sign_count=self.cred.sign_count,
361 )
362 # Start by verifying requiring user_verification - if that succeeds, then
363 # this authn could be used for both primary and secondary.
364 # If it fails, then try to verify with user_verification == False - unless
365 # as part of signin the app required user_verification (as stored in the state)
366 try:
367 self.authentication_verification = verify(require_user_verification=True)
368 self.mf_check = True
369 except InvalidAuthenticationResponse:
370 try:
371 self.authentication_verification = verify(
372 require_user_verification=self.user_verification
373 )
374 except InvalidAuthenticationResponse as exc:
375 self.credential.errors.append(
376 get_message("WEBAUTHN_NO_VERIFY", cause=str(exc))[0]
377 )
378 self.user.track_failed_authn("passkey")
379 return False
380 return True
381
382
383 class WebAuthnDeleteForm(Form):
384 # Change id of name since this shows up on register form that ALSO has a name
385 # element.
386 name: StringField = StringField(
387 get_form_field_xlate(_("Nickname")),
388 validators=[IsString(), RequiredLocalize(message="WEBAUTHN_NAME_REQUIRED")],
389 id="delete-name",
390 )
391 submit: SubmitField = SubmitField(label=_get_form_field_label("delete"))
392 clean_name: str | None
393
394 def validate(self, **kwargs: t.Any) -> bool:
395 if not super().validate(**kwargs):
396 return False
397 assert isinstance(self.name.errors, list)
398 assert self.name.data
399 msg, self.clean_name = _security.webauthn_util.name_svn(self.name.data)
400 if msg:
401 self.name.errors.append(msg)
402 return False
403 if not any([self.clean_name == cred.name for cred in current_user.webauthn]):
404 self.name.errors.append(
405 get_message("WEBAUTHN_NAME_NOT_FOUND", name=self.name.data)[0]
406 )
407 return False
408 return True
409
410
411 class WebAuthnVerifyForm(Form):
412 submit: SubmitField = SubmitField(
413 label=_get_form_field_label("submit"), id="wan_verify"
414 )
415
416 user: UserMixin
417
418 def validate(self, **kwargs: t.Any) -> bool:
419 if not super().validate(**kwargs):
420 return False # pragma: no cover
421 # We are always authenticated - so return possible credentials.
422 self.user = current_user
423 return True
424
425
426 @auth_required(
427 lambda: cv("API_ENABLED_METHODS"),
428 within=lambda: cv("FRESHNESS"),
429 grace=lambda: cv("FRESHNESS_GRACE_PERIOD"),
430 )
431 def webauthn_register() -> ResponseReturnValue:
432 """Start Registration for an existing authenticated user
433
434 Note that it requires a POST to start the registration and must send 'name'
435 in. We check here that user hasn't already registered an authenticator with that
436 name.
437 Also - this requires that the user already be logged in - so we can provide info
438 as part of the GET that could otherwise be considered leaking user info.
439 """
440 payload: dict[str, t.Any]
441
442 form: WebAuthnRegisterForm = t.cast(
443 WebAuthnRegisterForm, _build_form_from_request("wan_register_form")
444 )
445
446 if form.validate_on_submit():
447 challenge = _security.webauthn_util.generate_challenge(
448 cv("WAN_CHALLENGE_BYTES")
449 )
450 if not current_user.fs_webauthn_user_handle:
451 # set a user handle. This allows an easy migration when adding this
452 # column (and not requiring as part of schema change to update all existing
453 # records). New users will have this set as part of user creation.
454 after_this_request(_view_commit)
455 _datastore.set_webauthn_user_handle(current_user)
456
457 ro = dict(
458 challenge=challenge.encode(),
459 rp_name=cv("WAN_RP_NAME"),
460 rp_id=request.host.split(":")[0],
461 user_id=current_user.fs_webauthn_user_handle.encode(),
462 user_name=current_user.calc_username(),
463 timeout=cv("WAN_REGISTER_TIMEOUT"),
464 exclude_credentials=_create_credential_list(
465 current_user, ["first", "secondary"]
466 ),
467 )
468 ro = _security.webauthn_util.registration_options(
469 current_user, form.usage.data, ro
470 )
471 credential_options = webauthn.generate_registration_options(**ro)
472 co_json = options_to_json_dict(credential_options)
473 co_json["extensions"] = {"credProps": True}
474
475 # If we ask for UserVerification then we need to check that in the response.
476 uv = False
477 if credential_options.authenticator_selection:
478 uv = (
479 credential_options.authenticator_selection.user_verification
480 == UserVerificationRequirement.REQUIRED
481 )
482 state = {
483 "challenge": challenge,
484 "name": form.clean_name,
485 "usage": form.usage.data,
486 "user_verification": uv,
487 }
488 state_token = _security.wan_serializer.dumps(state)
489
490 if _security._want_json(request):
491 payload = {
492 "credential_options": co_json,
493 "wan_state": state_token,
494 }
495 return base_render_json(form, include_user=False, additional=payload)
496
497 return _security.render_template(
498 cv("WAN_REGISTER_TEMPLATE"),
499 wan_register_form=form,
500 wan_register_response_form=_build_form("wan_register_response_form"),
501 wan_state=state_token,
502 credential_options=json.dumps(co_json),
503 **_security._run_ctx_processor("wan_register"),
504 )
505
506 current_creds = []
507 cred: WebAuthnMixin
508 for cred in current_user.webauthn:
509 cl = {
510 "name": cred.name,
511 "credential_id": bytes_to_base64url(cred.credential_id),
512 "transports": cred.transports,
513 "lastuse": cred.lastuse_datetime.isoformat(),
514 "usage": cred.usage,
515 "backup_state": (
516 cred.backup_state if hasattr(cred, "backup_state") else False
517 ),
518 "device_type": (
519 cred.device_type if hasattr(cred, "device_type") else "Unknown"
520 ),
521 }
522 # TODO: i18n
523 discoverable = "Unknown"
524 if cred.extensions:
525 extensions = json.loads(cred.extensions)
526 if "credProps" in extensions:
527 discoverable = extensions["credProps"].get("rk", "Unknown")
528 cl["discoverable"] = discoverable
529 current_creds.append(cl)
530
531 payload = {"registered_credentials": current_creds}
532 if _security._want_json(request):
533 return base_render_json(form, additional=payload)
534 return _security.render_template(
535 cv("WAN_REGISTER_TEMPLATE"),
536 wan_register_form=form,
537 wan_delete_form=_build_form("wan_delete_form"),
538 registered_credentials=current_creds,
539 **_security._run_ctx_processor("wan_register"),
540 )
541
542
543 @auth_required(lambda: cv("API_ENABLED_METHODS"))
544 def webauthn_register_response(token: str) -> ResponseReturnValue:
545 """Response from browser."""
546 form: WebAuthnRegisterResponseForm = t.cast(
547 WebAuthnRegisterResponseForm,
548 _build_form_from_request("wan_register_response_form"),
549 )
550
551 expired, invalid, state = check_and_get_token_status(
552 token, "wan", cv("WAN_REGISTER_WITHIN")
553 )
554 if invalid:
555 m, c = get_message("API_ERROR")
556 if expired:
557 m, c = get_message(
558 "WEBAUTHN_EXPIRED", within=_td_format(cv("WAN_REGISTER_WITHIN"))
559 )
560 if invalid or expired:
561 if _security._want_json(request):
562 form.form_errors.append(m)
563 return base_render_json(form, include_user=False)
564 do_flash(m, c)
565 return redirect(url_for_security("wan_register"))
566
567 form.challenge = state["challenge"]
568 form.name = state["name"]
569 form.usage = state["usage"]
570 form.user_verification = state["user_verification"]
571 if form.validate_on_submit():
572 # store away successful registration
573 after_this_request(_view_commit)
574 _datastore.create_webauthn(
575 current_user._get_current_object(), # Not needed with Werkzeug >2.0.0
576 name=state["name"],
577 credential_id=form.registration_verification.credential_id,
578 public_key=form.registration_verification.credential_public_key,
579 sign_count=form.registration_verification.sign_count,
580 backup_state=getattr(
581 form.registration_verification, "credential_backed_up", False
582 ),
583 device_type=getattr(
584 form.registration_verification,
585 "credential_device_type",
586 "single_device",
587 ),
588 transports=list(form.transports),
589 extensions=form.extensions,
590 usage=form.usage,
591 )
592 wan_registered.send(
593 current_app._get_current_object(), # type: ignore
594 _async_wrapper=current_app.ensure_sync, # type: ignore[arg-type]
595 user=current_user,
596 name=state["name"],
597 )
598
599 if _security._want_json(request):
600 return base_render_json(form)
601 msg, c = get_message("WEBAUTHN_REGISTER_SUCCESSFUL", name=state["name"])
602 do_flash(msg, c)
603 return redirect(get_url(cv("WAN_POST_REGISTER_VIEW")))
604
605 if _security._want_json(request):
606 return base_render_json(form)
607 if form.errors:
608 for v in form.errors.values():
609 do_flash(v[0], "error")
610 return redirect(url_for_security("wan_register"))
611
612
613 def _signin_common(user: UserMixin | None, usage: list[str]) -> tuple[t.Any, str]:
614 """
615 Common code between signin and verify - once form has been verified.
616 """
617 challenge = _security.webauthn_util.generate_challenge(cv("WAN_CHALLENGE_BYTES"))
618
619 # Populate allowedCredentials if identity passed and allowed
620 allow_credentials = None
621 if user:
622 allow_credentials = _create_credential_list(user, usage)
623
624 ao = dict(
625 rp_id=request.host.split(":")[0],
626 challenge=challenge.encode(),
627 timeout=cv("WAN_SIGNIN_TIMEOUT"),
628 allow_credentials=allow_credentials,
629 )
630 ao = _security.webauthn_util.authentication_options(user, usage, ao)
631 options = webauthn.generate_authentication_options(**ao)
632
633 # If we ask for UserVerification then we need to check that in the response.
634 uv = False
635 if options.user_verification == UserVerificationRequirement.REQUIRED:
636 uv = True
637 state = {
638 "challenge": challenge,
639 "user_verification": uv,
640 }
641
642 o_json = options_to_json_dict(options)
643 state_token = t.cast( # type: ignore[redundant-cast]
644 str, _security.wan_serializer.dumps(state)
645 )
646 return o_json, state_token
647
648
649 @anonymous_user_required
650 @unauth_csrf()
651 def webauthn_signin() -> ResponseReturnValue:
652 # This view can be called either as a 'first' authentication or as part of
653 # 2FA.
654 is_secondary = all(k in session for k in ["tf_user_id", "tf_state"]) and session[
655 "tf_state"
656 ] in ["ready"]
657 if is_secondary or cv("WAN_ALLOW_AS_FIRST_FACTOR"):
658 pass
659 else:
660 abort(404)
661
662 form = t.cast(WebAuthnSigninForm, _build_form_from_request("wan_signin_form"))
663 form.is_secondary = is_secondary
664 if form.validate_on_submit():
665 o_json, state_token = _signin_common(
666 form.user, ["secondary"] if is_secondary else ["first"]
667 )
668 if _security._want_json(request):
669 payload = {
670 "credential_options": o_json,
671 "wan_state": state_token,
672 "remember": form.remember.data,
673 "is_secondary": is_secondary,
674 }
675 return base_render_json(form, include_user=False, additional=payload)
676
677 # Copy the user's remember field into the next form - since that is
678 # auto-submitted.
679 return _security.render_template(
680 cv("WAN_SIGNIN_TEMPLATE"),
681 wan_signin_form=form,
682 wan_signin_response_form=_build_form(
683 "wan_signin_response_form",
684 remember=form.remember.data,
685 next=form.next.data,
686 ),
687 wan_state=state_token,
688 credential_options=json.dumps(o_json),
689 is_secondary=is_secondary,
690 **_security._run_ctx_processor("wan_signin"),
691 )
692
693 if _security._want_json(request):
694 return base_render_json(form, additional={"is_secondary": is_secondary})
695 return _security.render_template(
696 cv("WAN_SIGNIN_TEMPLATE"),
697 wan_signin_form=form,
698 wan_signin_response_form=_build_form("wan_signin_response_form"),
699 is_secondary=is_secondary,
700 **_security._run_ctx_processor("wan_signin"),
701 )
702
703
704 @unauth_csrf()
705 def webauthn_signin_response(token: str) -> ResponseReturnValue:
706 is_secondary = all(k in session for k in ["tf_user_id", "tf_state"]) and session[
707 "tf_state"
708 ] in ["ready"]
709
710 form = t.cast(
711 WebAuthnSigninResponseForm, _build_form_from_request("wan_signin_response_form")
712 )
713
714 expired, invalid, state = check_and_get_token_status(
715 token, "wan", cv("WAN_SIGNIN_WITHIN")
716 )
717 if invalid:
718 m, c = get_message("API_ERROR")
719 if expired:
720 m, c = get_message(
721 "WEBAUTHN_EXPIRED", within=_td_format(cv("WAN_SIGNIN_WITHIN"))
722 )
723 if invalid or expired:
724 if _security._want_json(request):
725 form.form_errors.append(m)
726 return base_render_json(form, include_user=False)
727 do_flash(m, c)
728 return redirect(url_for_security("wan_signin"))
729
730 form.challenge = state["challenge"]
731 form.user_verification = state["user_verification"]
732 form.is_secondary = is_secondary
733 form.is_verify = False
734
735 if form.validate_on_submit():
736 # update last use and sign count
737 after_this_request(_view_commit)
738 assert form.cred
739 assert form.user
740 form.cred.lastuse_datetime = _security.datetime_factory()
741 form.cred.sign_count = form.authentication_verification.new_sign_count
742 form.cred.backup_state = getattr(
743 form.authentication_verification, "credential_backed_up", False
744 )
745 form.cred.device_type = getattr(
746 form.authentication_verification, "credential_device_type", "single_device"
747 )
748 _datastore.put(form.cred)
749
750 json_payload: dict[str, t.Any] = {}
751 if is_secondary:
752 tf_token = _security.two_factor_plugins.tf_complete(form.user, True)
753 if tf_token:
754 after_this_request(
755 partial(tf_set_validity_token_cookie, token=tf_token)
756 )
757 else:
758 # Need Two-factor?:
759 # - Is it required?
760 # - Did this credential provide 2-factor and
761 # is WAN_ALLOW_AS_MULTI_FACTOR set
762 # - Is another 2FA setup?
763 remember_me = bool(form.remember.data)
764 if form.mf_check and cv("WAN_ALLOW_AS_MULTI_FACTOR"):
765 pass
766 else:
767 response = _security.two_factor_plugins.tf_enter(
768 form.user,
769 remember_me,
770 "webauthn",
771 next_loc=_propagate_next(request.url, form),
772 )
773 if response:
774 return response
775 # login user
776 login_user(form.user, remember=remember_me, authn_via=["webauthn"])
777
778 goto_url = _get_post_login_redirect()
779 if _security._want_json(request):
780 # Tell caller where we would go if forms based - they can use it or
781 # not.
782 json_payload["post_login_url"] = goto_url
783 json_payload["tf_required"] = False
784 return base_render_json(
785 form,
786 include_auth_token=allowed_auth_token(form.user),
787 additional=json_payload,
788 )
789 return redirect(goto_url)
790
791 # Here on validate error
792 if _security._want_json(request):
793 return base_render_json(form)
794
795 # Since the response is auto submitted - we go back to
796 # signin form - for now use flash.
797 if form.errors:
798 for v in form.errors.values():
799 do_flash(v[0], "error")
800 return redirect(url_for_security("wan_signin"))
801
802
803 @auth_required(
804 lambda: cv("API_ENABLED_METHODS"),
805 within=lambda: cv("FRESHNESS"),
806 grace=lambda: cv("FRESHNESS_GRACE_PERIOD"),
807 )
808 def webauthn_delete() -> ResponseReturnValue:
809 """Deletes an existing registered credential."""
810 form = t.cast(WebAuthnDeleteForm, _build_form_from_request("wan_delete_form"))
811
812 if form.validate_on_submit():
813 # validate made sure form.name.data exists.
814 cred = [c for c in current_user.webauthn if c.name == form.clean_name][0]
815 after_this_request(_view_commit)
816
817 wan_deleted.send(
818 current_app._get_current_object(), # type: ignore
819 _async_wrapper=current_app.ensure_sync, # type: ignore[arg-type]
820 user=current_user,
821 name=cred.name,
822 )
823 _datastore.delete_webauthn(cred)
824 if _security._want_json(request):
825 return base_render_json(form)
826 msg, c = get_message("WEBAUTHN_CREDENTIAL_DELETED", name=form.clean_name)
827 do_flash(msg, c)
828
829 if _security._want_json(request):
830 return base_render_json(form)
831 if form.name.errors:
832 do_flash(form.name.errors[0], "error")
833 return redirect(url_for_security("wan_register"))
834
835
836 @auth_required(lambda: cv("API_ENABLED_METHODS"))
837 def webauthn_verify() -> ResponseReturnValue:
838 """
839 Re-authenticate to reset freshness time.
840 This is likely the result of a reauthn_handler redirect, which
841 will have filled in ?next=xxx - which we want to carefully not lose as we
842 go through these steps.
843 """
844 form = t.cast(WebAuthnVerifyForm, _build_form_from_request("wan_verify_form"))
845
846 if form.validate_on_submit():
847 o_json, state_token = _signin_common(form.user, cv("WAN_ALLOW_AS_VERIFY"))
848 if _security._want_json(request):
849 payload = {"credential_options": o_json, "wan_state": state_token}
850 return base_render_json(form, include_user=False, additional=payload)
851
852 return _security.render_template(
853 cv("WAN_VERIFY_TEMPLATE"),
854 wan_verify_form=form,
855 wan_signin_response_form=_build_form("wan_signin_response_form"),
856 wan_state=state_token,
857 credential_options=json.dumps(o_json),
858 **_security._run_ctx_processor("wan_verify"),
859 )
860
861 if _security._want_json(request):
862 return base_render_json(form)
863 return _security.render_template(
864 cv("WAN_VERIFY_TEMPLATE"),
865 wan_verify_form=form,
866 wan_signin_response_form=_build_form("wan_signin_response_form"),
867 skip_login_menu=True,
868 **_security._run_ctx_processor("wan_verify"),
869 )
870
871
872 @auth_required(lambda: cv("API_ENABLED_METHODS"))
873 def webauthn_verify_response(token: str) -> ResponseReturnValue:
874 form = t.cast(
875 WebAuthnSigninResponseForm, _build_form_from_request("wan_signin_response_form")
876 )
877
878 expired, invalid, state = check_and_get_token_status(
879 token, "wan", cv("WAN_SIGNIN_WITHIN")
880 )
881 if invalid:
882 m, c = get_message("API_ERROR")
883 if expired:
884 m, c = get_message(
885 "WEBAUTHN_EXPIRED", within=_td_format(cv("WAN_SIGNIN_WITHIN"))
886 )
887 if invalid or expired:
888 if _security._want_json(request):
889 form.form_errors.append(m)
890 return base_render_json(form, include_user=False)
891 do_flash(m, c)
892 return redirect(url_for_security("wan_verify"))
893
894 form.challenge = state["challenge"]
895 form.user_verification = state["user_verification"]
896 form.is_secondary = False
897 form.is_verify = True
898
899 if form.validate_on_submit():
900 assert form.cred
901 assert form.user
902 # The assertion was cryptographically valid for `form.user`. For the
903 # reauthentication / verify flow, that user must also be the user
904 # currently logged in to this session - otherwise an attacker who
905 # owns any registered credential could satisfy a victim session's
906 # freshness gate by submitting their own credential's assertion.
907 if form.user.email != current_user.email:
908 m, c = get_message("WEBAUTHN_MISMATCH_USER_HANDLE")
909 if _security._want_json(request):
910 form.form_errors.append(m)
911 return base_render_json(form, include_user=False)
912 do_flash(m, c)
913 return redirect(url_for_security("wan_verify"))
914
915 # update last use and sign count
916 after_this_request(_view_commit)
917 form.cred.lastuse_datetime = _security.datetime_factory()
918 form.cred.sign_count = form.authentication_verification.new_sign_count
919 _datastore.put(form.cred)
920
921 # verified - so set freshness time.
922 session["fs_paa"] = time.time()
923
924 if _security._want_json(request):
925 return base_render_json(
926 form, include_auth_token=allowed_auth_token(form.user)
927 )
928
929 do_flash(*get_message("REAUTHENTICATION_SUCCESSFUL"))
930 return redirect(_get_post_verify_redirect())
931
932 # Here on validate error (only POST is allowed on this endpoint)
933 if _security._want_json(request):
934 return base_render_json(form)
935
936 # Since the response is auto submitted - we go back to
937 # verify form - for now use flash.
938 if form.credential.errors:
939 do_flash(form.credential.errors[0], "error")
940 return redirect(url_for_security("wan_verify"))
941
942
943 def _is_cred_usable(cred: WebAuthnMixin, usage: str | list[str]) -> bool:
944 # Return True is cred can be used for the requested usage/verify
945 if not isinstance(usage, list):
946 usage = [usage]
947 assert "verify" not in usage
948 return cred.usage in usage
949
950
951 def has_webauthn(user: UserMixin, usage: str | list[str]) -> bool:
952 # Return True if ``user`` has one or more keys with requested usage.
953 # Usage: either "first" or "secondary"
954 if not isinstance(usage, list):
955 usage = [usage]
956 wan_keys = getattr(user, "webauthn", [])
957 for cred in wan_keys:
958 if _is_cred_usable(cred, usage):
959 return True
960 return False
961
962
963 def _create_credential_list(
964 user: UserMixin, usage: list[str]
965 ) -> list[PublicKeyCredentialDescriptor]:
966 # Return a list of registered credentials - filtered by whether they apply to our
967 # authentication state (first or secondary)
968 cl = []
969
970 for cred in user.webauthn:
971 if not _is_cred_usable(cred, usage):
972 continue
973 descriptor = PublicKeyCredentialDescriptor(
974 type=PublicKeyCredentialType.PUBLIC_KEY, id=cred.credential_id
975 )
976 if cred.transports:
977 tlist = cred.transports
978 transports = [AuthenticatorTransport(transport) for transport in tlist]
979 descriptor.transports = transports
980 # TODO order is important - figure out a way to add 'weight'
981 cl.append(descriptor)
982
983 return cl
984
985
986 class WebAuthnTfPlugin(TfPluginBase):
987 def __init__(self, app: flask.Flask):
988 super().__init__(app)
989
990 def create_blueprint(
991 self, app: flask.Flask, bp: flask.Blueprint, state: Security
992 ) -> None:
993 """Our endpoints are already registered since webauthn can be both
994 a 'first' or 'secondary' authentication mechanism.
995 """
996 pass
997
998 def get_setup_methods(self, user: UserMixin) -> list[tuple[str, str]]:
999 if has_webauthn(user, "secondary"):
1000 return [("webauthn", localize_callback(_setup_methods_xlate["webauthn"]))]
1001 return []
1002
1003 def tf_login(
1004 self, user: UserMixin, json_payload: dict[str, t.Any], next_loc: str | None
1005 ) -> ResponseValue:
1006 session["tf_state"] = "ready"
1007 if not _security._want_json(request):
1008 values = dict(next=next_loc) if next_loc else dict()
1009 return redirect(url_for_security("wan_signin", **values))
1010
1011 # JSON response
1012 json_payload["tf_signin_url"] = url_for_security("wan_signin")
1013 json_payload["tf_state"] = "ready"
1014 json_payload["tf_method"] = "webauthn"
1015 return simple_render_json(additional=json_payload)