| 1 |
""" |
| 2 |
flask_security.tf_plugin |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
Flask-Security Two-Factor Plugin Module |
| 6 |
|
| 7 |
:copyright: (c) 2022-2026 by J. Christopher Wagner (jwag). |
| 8 |
:license: MIT, see LICENSE for more details. |
| 9 |
|
| 10 |
TODO: |
| 11 |
- add localized callback for select choices. |
| 12 |
""" |
| 13 |
|
| 14 |
from __future__ import annotations |
| 15 |
|
| 16 |
import typing as t |
| 17 |
|
| 18 |
from flask import request, redirect, session |
| 19 |
|
| 20 |
from .decorators import unauth_csrf |
| 21 |
from .forms import ( |
| 22 |
build_form_from_request, |
| 23 |
get_form_field_xlate, |
| 24 |
Form, |
| 25 |
RadioField, |
| 26 |
SubmitField, |
| 27 |
) |
| 28 |
from .proxies import _datastore, _security |
| 29 |
from .utils import ( |
| 30 |
_, |
| 31 |
base_render_json, |
| 32 |
check_and_get_token_status, |
| 33 |
config_value as cv, |
| 34 |
do_flash, |
| 35 |
get_message, |
| 36 |
get_within_delta, |
| 37 |
get_url, |
| 38 |
login_user, |
| 39 |
propagate_next, |
| 40 |
simple_render_json, |
| 41 |
url_for_security, |
| 42 |
) |
| 43 |
|
| 44 |
if t.TYPE_CHECKING: # pragma: no cover |
| 45 |
import flask |
| 46 |
from flask.typing import ResponseValue |
| 47 |
from flask import Response |
| 48 |
from flask_security import Security, UserMixin |
| 49 |
|
| 50 |
|
| 51 |
class TwoFactorSelectForm(Form): |
| 52 |
which = RadioField(get_form_field_xlate(_("Available Second Factor Methods:"))) |
| 53 |
submit = SubmitField(get_form_field_xlate(_("Select"))) |
| 54 |
|
| 55 |
def __init__(self, *args, **kwargs): |
| 56 |
super().__init__(*args, **kwargs) |
| 57 |
|
| 58 |
|
| 59 |
@unauth_csrf() |
| 60 |
def tf_select() -> ResponseValue: |
| 61 |
# Ask user which MFA method they want to use. |
| 62 |
# This is used when a user has setup more than one type of 2FA. |
| 63 |
form = t.cast( |
| 64 |
TwoFactorSelectForm, build_form_from_request("two_factor_select_form") |
| 65 |
) |
| 66 |
|
| 67 |
# This endpoint is unauthenticated - make sure we're in a valid state |
| 68 |
if not all(k in session for k in ["tf_user_id", "tf_select"]): |
| 69 |
# illegal call on this endpoint |
| 70 |
tf_clean_session() |
| 71 |
return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW")) |
| 72 |
|
| 73 |
user = _datastore.find_user(fs_uniquifier=session["tf_user_id"]) |
| 74 |
if not user: # pragma no cover |
| 75 |
# hard to imagine - someone deletes the user while they are logging in. |
| 76 |
tf_clean_session() |
| 77 |
return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW")) |
| 78 |
|
| 79 |
setup_methods = _security.two_factor_plugins.get_setup_tf_methods(user) |
| 80 |
form.which.choices = setup_methods # type: ignore[assignment] |
| 81 |
|
| 82 |
if form.validate_on_submit(): |
| 83 |
response = None |
| 84 |
tf_impl = _security.two_factor_plugins.method_to_impl(user, form.which.data) |
| 85 |
if tf_impl: |
| 86 |
json_payload = {"tf_required": True} |
| 87 |
response = tf_impl.tf_login( |
| 88 |
user, json_payload, next_loc=propagate_next(request.url, None) |
| 89 |
) |
| 90 |
if not response: # pragma no cover |
| 91 |
# This really can't happen unless between the time the started logging in |
| 92 |
# and now, they deleted a second factor (which they would have to do |
| 93 |
# in another window). |
| 94 |
tf_clean_session() |
| 95 |
return tf_illegal_state(form, cv("TWO_FACTOR_ERROR_VIEW")) |
| 96 |
return response |
| 97 |
|
| 98 |
if _security._want_json(request): |
| 99 |
payload = {"tf_select": True, "tf_setup_methods": [k for k, v in setup_methods]} |
| 100 |
return base_render_json(form, include_user=False, additional=payload) |
| 101 |
|
| 102 |
return _security.render_template( |
| 103 |
cv("TWO_FACTOR_SELECT_TEMPLATE"), |
| 104 |
two_factor_select_form=form, |
| 105 |
**_security._run_ctx_processor("tf_select"), |
| 106 |
) |
| 107 |
|
| 108 |
|
| 109 |
class TfPluginBase: # pragma no cover |
| 110 |
def __init__(self, app: flask.Flask): |
| 111 |
pass |
| 112 |
|
| 113 |
def create_blueprint( |
| 114 |
self, app: flask.Flask, bp: flask.Blueprint, state: Security |
| 115 |
) -> None: |
| 116 |
raise NotImplementedError |
| 117 |
|
| 118 |
def get_setup_methods(self, user: UserMixin) -> list[tuple[str, str]]: |
| 119 |
"""Return a list of tuples representing currently configured methods. |
| 120 |
The tuple is (value, label) - suitable for use in a FlaskForm Select element. |
| 121 |
""" |
| 122 |
raise NotImplementedError |
| 123 |
|
| 124 |
def tf_login( |
| 125 |
self, user: UserMixin, json_payload: dict[str, t.Any], next_loc: str | None |
| 126 |
) -> ResponseValue: |
| 127 |
""" |
| 128 |
Called from first/primary authenticated views if the user successfully |
| 129 |
authenticated, and required a second method of authentication. |
| 130 |
This method returns the necessary information for the user UI to continue. |
| 131 |
For forms, this is usually a redirect to a secondary sign in form. For JSON |
| 132 |
it is just a payload that describes what the user has to do next. |
| 133 |
""" |
| 134 |
raise NotImplementedError |
| 135 |
|
| 136 |
|
| 137 |
class TfPlugin: |
| 138 |
""" |
| 139 |
Two-Factor plugin support. |
| 140 |
|
| 141 |
Enables multiple independent two-factor implementations to be configured for a given |
| 142 |
app. See TfPluginBase for what a new implementation must provide. |
| 143 |
""" |
| 144 |
|
| 145 |
def __init__(self) -> None: |
| 146 |
self._tf_impls: dict[str, TfPluginBase] = {} |
| 147 |
|
| 148 |
def register_tf_impl( |
| 149 |
# N.B. all methods must be unique across all implementations. |
| 150 |
self, |
| 151 |
app: flask.Flask, |
| 152 |
name: str, |
| 153 |
impl: t.Type[TfPluginBase], |
| 154 |
) -> None: |
| 155 |
self._tf_impls[name] = impl(app) |
| 156 |
|
| 157 |
def create_blueprint( |
| 158 |
self, app: flask.Flask, bp: flask.Blueprint, state: Security |
| 159 |
) -> None: |
| 160 |
if state.support_mfa: |
| 161 |
for impl in self._tf_impls.values(): |
| 162 |
impl.create_blueprint(app, bp, state) |
| 163 |
# Add our route for selecting between multiple active two-factor |
| 164 |
# mechanisms. |
| 165 |
bp.route( |
| 166 |
cv("TWO_FACTOR_SELECT_URL", app), |
| 167 |
methods=["GET", "POST"], |
| 168 |
endpoint="tf_select", |
| 169 |
)(tf_select) |
| 170 |
|
| 171 |
def method_to_impl(self, user: UserMixin, method: str) -> TfPluginBase | None: |
| 172 |
# reverse map a method to the implementation. |
| 173 |
# N.B. again - requires that methods be unique across all implementations. |
| 174 |
# There is a small window that a previously setup method was removed. |
| 175 |
for impl in self._tf_impls.values(): |
| 176 |
setup_methods = impl.get_setup_methods(user) |
| 177 |
if method in [k for k, v in setup_methods]: |
| 178 |
return impl |
| 179 |
return None # pragma no cover |
| 180 |
|
| 181 |
def get_setup_tf_methods(self, user: UserMixin) -> list[tuple[str, str]]: |
| 182 |
"""Return a list of tuples representing currently configured methods. |
| 183 |
The tuple is (value, translated(value)) - suitable for use in a |
| 184 |
FlaskForm Select element. |
| 185 |
""" |
| 186 |
methods = [] |
| 187 |
for impl in self._tf_impls.values(): |
| 188 |
methods.extend(impl.get_setup_methods(user)) |
| 189 |
return methods |
| 190 |
|
| 191 |
def tf_enter( |
| 192 |
self, |
| 193 |
user: UserMixin, |
| 194 |
remember_me: bool | None, |
| 195 |
primary_authn_via: str, |
| 196 |
next_loc: str | None, |
| 197 |
) -> ResponseValue | None: |
| 198 |
"""Check if two-factor is required and if so, start the process. |
| 199 |
Must be called in a request context. |
| 200 |
remember_me controls 2 cookies - the remember_me cookie and the tf_validity |
| 201 |
cookie. We use the session to hold the fact that the user requested 'remember' |
| 202 |
across the second factor. |
| 203 |
""" |
| 204 |
json_payload: dict[str, t.Any] |
| 205 |
if _security.support_mfa: |
| 206 |
tf_setup_methods = self.get_setup_tf_methods(user) |
| 207 |
tf_fresh = tf_verify_validity_token(user.fs_uniquifier) |
| 208 |
tf_required, tf_available_methods = user.check_tf_required( |
| 209 |
tf_setup_methods, tf_fresh |
| 210 |
) |
| 211 |
if tf_required: |
| 212 |
tf_setup_methods_keys = [t1 for t1, t2 in tf_setup_methods] |
| 213 |
# Clean out any potential old session info - in case of previous |
| 214 |
# aborted 2FA attempt. |
| 215 |
tf_clean_session() |
| 216 |
|
| 217 |
json_payload = {"tf_required": True} |
| 218 |
if remember_me: |
| 219 |
session["tf_remember_login"] = remember_me |
| 220 |
|
| 221 |
session["tf_user_id"] = user.fs_uniquifier |
| 222 |
# A backwards compat hack - the original twofactor could be setup |
| 223 |
# as part of initial login. |
| 224 |
if len(tf_setup_methods) == 0: |
| 225 |
# only initial two-factor implementation supports this |
| 226 |
return self._tf_impls["code"].tf_login(user, json_payload, next_loc) |
| 227 |
elif len(tf_setup_methods) == 1: |
| 228 |
# method_to_impl can't return None here since we just |
| 229 |
# got the methods up above. |
| 230 |
impl = t.cast( |
| 231 |
TfPluginBase, |
| 232 |
self.method_to_impl(user, tf_setup_methods_keys[0]), |
| 233 |
) |
| 234 |
return impl.tf_login(user, json_payload, next_loc) |
| 235 |
else: |
| 236 |
session["tf_select"] = True |
| 237 |
if not _security._want_json(request): |
| 238 |
values = dict(next=next_loc) if next_loc else dict() |
| 239 |
return redirect(url_for_security("tf_select", **values)) |
| 240 |
# Let's force app to go through tf-select just in case we want |
| 241 |
# to do further validation... However, provide the choices |
| 242 |
# so they can just do a POST |
| 243 |
json_payload.update( |
| 244 |
{ |
| 245 |
"tf_select": True, |
| 246 |
"tf_setup_methods": tf_setup_methods_keys, |
| 247 |
} |
| 248 |
) |
| 249 |
return simple_render_json(json_payload) |
| 250 |
return None |
| 251 |
|
| 252 |
def tf_complete(self, user: UserMixin, dologin: bool) -> str | None: |
| 253 |
remember = session.pop("tf_remember_login", None) |
| 254 |
|
| 255 |
if dologin: |
| 256 |
login_user(user, remember=remember) |
| 257 |
tf_clean_session() |
| 258 |
token = None |
| 259 |
# return a token to avoid future two-factor prompts (for a period of time) |
| 260 |
if not cv("TWO_FACTOR_ALWAYS_VALIDATE") and remember: |
| 261 |
token = generate_tf_validity_token(user.fs_uniquifier) |
| 262 |
return token |
| 263 |
|
| 264 |
|
| 265 |
def generate_tf_validity_token(fs_uniquifier): |
| 266 |
"""Generates a unique token for the specified user. |
| 267 |
|
| 268 |
:param fs_uniquifier: The fs_uniquifier of a user to whom the token belongs to |
| 269 |
""" |
| 270 |
return _security.tf_validity_serializer.dumps(fs_uniquifier) |
| 271 |
|
| 272 |
|
| 273 |
def tf_validity_token_status(token): |
| 274 |
"""Returns the expired status, invalid status, and user of a |
| 275 |
Two-Factor Validity token. |
| 276 |
For example:: |
| 277 |
|
| 278 |
expired, invalid, user = tf_validity_token_status('...') |
| 279 |
|
| 280 |
:param token: The Two-Factor Validity token |
| 281 |
""" |
| 282 |
return check_and_get_token_status( |
| 283 |
token, "tf_validity", get_within_delta("TWO_FACTOR_LOGIN_VALIDITY") |
| 284 |
) |
| 285 |
|
| 286 |
|
| 287 |
def tf_verify_validity_token(fs_uniquifier: str) -> bool: |
| 288 |
"""Returns the status of the Two-Factor Validity token based on the current |
| 289 |
request. |
| 290 |
|
| 291 |
:param fs_uniquifier: The ``fs_uniquifier`` of the submitting user. |
| 292 |
""" |
| 293 |
token = request.cookies.get("tf_validity", default=None) |
| 294 |
if token is None: |
| 295 |
return False |
| 296 |
|
| 297 |
expired, invalid, uniquifier = tf_validity_token_status(token) |
| 298 |
if expired or invalid or (fs_uniquifier != uniquifier): |
| 299 |
return False |
| 300 |
|
| 301 |
return True |
| 302 |
|
| 303 |
|
| 304 |
def tf_set_validity_token_cookie(response: Response, token: str) -> Response: |
| 305 |
"""Sets the Two-Factor validity token for a specific user given that is |
| 306 |
configured and the user selects remember me |
| 307 |
|
| 308 |
:param response: The response with which to set the set_cookie |
| 309 |
:param token: validity token |
| 310 |
""" |
| 311 |
cookie_kwargs = cv("TWO_FACTOR_VALIDITY_COOKIE") |
| 312 |
max_age = int(get_within_delta("TWO_FACTOR_LOGIN_VALIDITY").total_seconds()) |
| 313 |
response.set_cookie("tf_validity", value=token, max_age=max_age, **cookie_kwargs) |
| 314 |
# This is likely overkill since so far we only return this on a POST which is |
| 315 |
# unlikely to be cached. |
| 316 |
response.vary.add("Cookie") |
| 317 |
return response |
| 318 |
|
| 319 |
|
| 320 |
def tf_check_state(allowed_states: list[str]) -> UserMixin | None: |
| 321 |
if ( |
| 322 |
not all(k in session for k in ["tf_user_id", "tf_state"]) |
| 323 |
or session["tf_state"] not in allowed_states |
| 324 |
): |
| 325 |
tf_clean_session() |
| 326 |
return None |
| 327 |
|
| 328 |
user = _datastore.find_user(fs_uniquifier=session["tf_user_id"]) |
| 329 |
if not user: |
| 330 |
tf_clean_session() |
| 331 |
return user |
| 332 |
|
| 333 |
|
| 334 |
def tf_illegal_state(form, redirect_to): |
| 335 |
m, c = get_message("TWO_FACTOR_PERMISSION_DENIED") |
| 336 |
if not _security._want_json(request): |
| 337 |
do_flash(m, c) |
| 338 |
return redirect(get_url(redirect_to)) |
| 339 |
else: |
| 340 |
form.form_errors.append(m) |
| 341 |
return base_render_json(form, include_user=False) |
| 342 |
|
| 343 |
|
| 344 |
def tf_clean_session(): |
| 345 |
""" |
| 346 |
Clean out ALL stuff stored in session (e.g. on logout or restart of a session) |
| 347 |
""" |
| 348 |
if cv("TWO_FACTOR"): |
| 349 |
for k in [ |
| 350 |
"tf_state", |
| 351 |
"tf_user_id", |
| 352 |
"tf_primary_method", |
| 353 |
"tf_remember_login", |
| 354 |
"tf_totp_secret", |
| 355 |
"tf_select", |
| 356 |
]: |
| 357 |
session.pop(k, None) |