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