Debian Codegraph @

flask_security/utils.py

raw
1 """
2 flask_security.utils
3 ~~~~~~~~~~~~~~~~~~~~
4
5 Flask-Security utils module
6
7 :copyright: (c) 2012-2019 by Matt Wright.
8 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
9 :license: MIT, see LICENSE for more details.
10 """
11
12 from __future__ import annotations
13
14 import abc
15 import base64
16 import unicodedata
17 from datetime import datetime, timedelta, timezone
18 from functools import partial
19 import hashlib
20 import hmac
21 import time
22 import typing as t
23 from urllib.parse import parse_qsl, quote, urlsplit, urlunsplit, urlencode
24 import urllib.request
25 import urllib.error
26
27 from flask import (
28 Response,
29 current_app,
30 flash,
31 g,
32 redirect,
33 request,
34 render_template,
35 session,
36 url_for,
37 after_this_request,
38 )
39 from flask_login import login_user as _login_user
40 from flask_login import logout_user as _logout_user
41 from flask_login import current_user
42 from flask_login import COOKIE_NAME as REMEMBER_COOKIE_NAME
43 from flask_principal import AnonymousIdentity, Identity, identity_changed, Need
44 from flask_wtf import csrf, FlaskForm
45 from wtforms import ValidationError
46 from itsdangerous import BadSignature, SignatureExpired
47 from werkzeug.local import LocalProxy
48 from werkzeug.datastructures import MultiDict
49
50 from .quart_compat import best, get_quart_status
51 from .proxies import _security, _datastore, _pwd_context, _hashing_context
52 from .signals import user_authenticated
53
54 if t.TYPE_CHECKING: # pragma: no cover
55 from flask import Flask
56 from flask.typing import ResponseValue
57 from flask_security import UserMixin
58
59 localize_callback: t.Callable[..., str] = LocalProxy(
60 lambda: _security.i18n_domain.gettext
61 )
62
63 _FsPermNeed = partial(Need, "fsperm")
64 _FsPermNeed.__doc__ = """A need with the method preset to `"fsperm"`."""
65
66
67 def _(translate: str) -> str:
68 """Identity function to mark strings for translation."""
69 return translate
70
71
72 def get_request_attr(name: str) -> t.Any:
73 """Retrieve a request local attribute.
74
75 Current public attributes are:
76
77 **fs_authn_via**
78 will be set to the authentication mechanism (session, token, basic)
79 that the current request was authenticated with.
80
81 Returns None if attribute doesn't exist.
82
83 .. versionadded:: 4.0.0
84 .. versionchanged:: 4.1.5
85 Use 'g' rather than request_ctx stack which is going away post Flask 2.2
86 """
87 return getattr(g, name, None)
88
89
90 def set_request_attr(name: str, value: t.Any) -> None:
91 """Set an attribute on Flask's application context global object (g).
92
93 :param name: The key/attribute name to store the value under
94 :param value: The value to store in the application context
95 """
96 return setattr(g, name, value)
97
98
99 """
100 Most view functions that modify the DB will call ``after_this_request(view_commit)``
101 Quart compatibility needs an async version
102 """
103 if get_quart_status(): # pragma: no cover
104
105 async def _view_commit(response=None):
106 _datastore.commit()
107 return response
108
109 else:
110
111 def _view_commit(response=None): # type: ignore[misc]
112 _datastore.commit()
113 return response
114
115
116 def aware_utcnow() -> datetime:
117 """Return a timezone-aware UTC datetime object.
118
119 From a miguel grinberg blog around dealing with 3.12.
120 Our default SQLAlchemy Datetime is naive.
121 Note that most code should call _security.datetime_factory()
122
123 :return: Current UTC datetime with timezone information
124 :rtype: datetime
125 """
126 return datetime.now(timezone.utc)
127
128
129 def aware_utcfromtimestamp(timestamp: float) -> datetime:
130 """Create timezone-aware UTC datetime from timestamp.
131
132 :param timestamp: Unix timestamp (seconds since epoch)
133 :type timestamp: float
134 :return: UTC datetime with timezone information
135 :rtype: datetime
136 """
137 return datetime.fromtimestamp(timestamp, timezone.utc)
138
139
140 def naive_utcnow() -> datetime:
141 """Return a naive UTC datetime (tzinfo removed).
142
143 :return: Current UTC datetime without timezone information
144 :rtype: datetime
145 """
146 return aware_utcnow().replace(tzinfo=None)
147
148
149 def naive_utcfromtimestamp(timestamp: float) -> datetime:
150 """Create naive UTC datetime from timestamp.
151
152 :param timestamp: Unix timestamp (seconds since epoch)
153 :type timestamp: float
154 :return: UTC datetime without timezone information
155 :rtype: datetime
156 """
157 return aware_utcfromtimestamp(timestamp).replace(tzinfo=None)
158
159
160 def _find_csrf_field_name() -> t.Optional[str]:
161 """Retrieve the configured CSRF field name from Flask-WTF form configuration.
162
163 This is needed to properly clear CSRF tokens on logout since Flask-WTF doesn't
164 automatically handle this case. The field name can be configured through
165 Flask-WTF's settings or overridden in form classes.
166
167 :return: Configured CSRF field name if found, None otherwise
168 :rtype: Optional[str]
169
170 Note:
171 Uses the field name from the login form as set by the Flask-WTF configuration.
172 Requires a DummyForm class with Flask-WTF's meta configuration.
173 """
174 from .forms import DummyForm
175
176 form = DummyForm(formdata=None)
177 if hasattr(form.meta, "csrf_field_name"):
178 return form.meta.csrf_field_name
179 return None
180
181
182 def is_user_authenticated(user: UserMixin | None) -> bool:
183 """
184 return True if user is authenticated.
185
186 With Flask-Login <=0.6.x and Flask-Security <5.4 current_user was always
187 set - for non-authenticated users it pointed to an AnonymousUser
188 Flask-Login is experimenting (11/5/23) with a LOGIN_NO_ANONYMOUS which will set
189 current_user to None and deprecate is_authenticated (current_user non None implies
190 authenticated).
191 We have a configuration variable ANONYMOUS_USER_DISABLED which if true will force
192 current_user to None on unauthenticated as well
193 """
194 if _config_value("ANONYMOUS_USER_DISABLED"):
195 # Note that user often is current_user which is a proxy and isn't ever actually
196 # 'None'
197 return bool(user)
198 return bool(user and user.is_authenticated)
199
200
201 def login_user(
202 user: UserMixin,
203 remember: bool | None = None,
204 authn_via: list[str] | None = None,
205 ) -> bool:
206 """Perform the login routine.
207
208 If :py:data:`SECURITY_TRACKABLE` is used, make sure you commit changes after this
209 request (i.e. ``app.security.datastore.commit()``).
210
211 :param user: The user to login
212 :param remember: Flag specifying if the remember cookie should be set.
213 If ``None`` use value of :py:data:`SECURITY_DEFAULT_REMEMBER_ME`
214 :param authn_via: A list of strings denoting which mechanism(s) the user
215 authenticated with.
216 These should be one or more of ["password", "sms", "authenticator", "email"] or
217 other 'auto-login' mechanisms.
218 :return: True if user successfully logged in.
219 """
220
221 if remember is None:
222 remember = _config_value("DEFAULT_REMEMBER_ME")
223
224 if not _login_user(user, remember, force=True): # pragma: no cover
225 return False
226
227 if _security.trackable:
228 remote_addr = request.remote_addr or None # make sure it is None
229
230 old_current_login, new_current_login = (
231 user.current_login_at,
232 _security.datetime_factory(),
233 )
234 old_current_ip, new_current_ip = user.current_login_ip, remote_addr
235
236 user.last_login_at = old_current_login or new_current_login
237 user.current_login_at = new_current_login
238 user.last_login_ip = old_current_ip
239 user.current_login_ip = new_current_ip
240 user.login_count = user.login_count + 1 if user.login_count else 1
241
242 _datastore.put(user)
243
244 session["fs_cc"] = "set" # CSRF cookie
245 session["fs_paa"] = time.time() # Primary authentication at - timestamp
246
247 identity_changed.send(
248 current_app._get_current_object(), # type: ignore[attr-defined]
249 _async_wrapper=current_app.ensure_sync, # type: ignore[arg-type]
250 identity=Identity(user.fs_uniquifier),
251 )
252
253 user_authenticated.send(
254 current_app._get_current_object(), # type: ignore[attr-defined]
255 _async_wrapper=current_app.ensure_sync, # type: ignore[arg-type]
256 user=user,
257 authn_via=authn_via,
258 )
259 return True
260
261
262 def logout_user() -> None:
263 """Logs out the current user.
264
265 This will also clean up the remember me cookie if it exists.
266
267 This sends an ``identity_changed`` signal to note that the current
268 identity is now the `AnonymousIdentity`
269 """
270
271 for key in (
272 "identity.name",
273 "identity.auth_type",
274 "fs_paa",
275 "fs_gexp",
276 "fs_oauth_next",
277 ):
278 session.pop(key, None)
279
280 # Clear csrf token between sessions.
281 # Ideally this would be handled by Flask-WTF but...
282 # We don't clear entire session since Flask-Login seems to like having it.
283 csrf_field_name = _find_csrf_field_name()
284 if csrf_field_name:
285 session.pop(csrf_field_name, None)
286 # Flask-WTF 'caches' csrf_token - and only set the session if not already
287 # in 'g'. Be sure to clear both. This affects at least /confirm
288 g.pop(csrf_field_name, None)
289 session["fs_cc"] = "clear"
290 if _config_value("REFRESH_TOKEN") and _config_value("REFRESH_TOKEN_COOKIE_NAME"):
291 from .tokens import clear_refresh_token_cookie
292
293 after_this_request(partial(clear_refresh_token_cookie))
294 identity_changed.send(
295 current_app._get_current_object(), # type: ignore
296 _async_wrapper=current_app.ensure_sync,
297 identity=AnonymousIdentity(),
298 )
299 _logout_user()
300
301
302 def check_and_update_authn_fresh(
303 within: timedelta,
304 grace: timedelta,
305 method: str | None = None,
306 ) -> bool:
307 """Check if user authenticated within specified time and update grace period.
308
309 :param within: A timedelta specifying the maximum time in the past that the caller
310 authenticated that is still considered 'fresh'.
311 :param grace: A timedelta that, if the current session is considered 'fresh'
312 will set a grace period for which freshness won't be checked.
313 The intent here is that the caller shouldn't get part-way though
314 a set of operations and suddenly be required to authenticate again.
315 This is not supported for authentication tokens.
316 :param method: Optional - if set and == "basic" then will always return True.
317 (since basic-auth sends username/password on every request)
318
319 If within.total_seconds() is negative, will always return True (always 'fresh').
320 This effectively just disables this entire mechanism.
321
322 within.total_seconds() == 0 results in undefined behavior.
323
324 If "fs_gexp" is in the session and the current timestamp is less than that,
325 return True and extend grace time (i.e. set fs_gexp to current time + grace).
326
327 Be aware that for this to work, state is required to be sent from the client.
328 Flask security adds this state to the session (cookie) and the auth token.
329 Without this state, 'False' is always returned - (not fresh).
330
331 .. warning::
332 Be sure the caller is already authenticated PRIOR to calling this method.
333
334 .. versionadded:: 3.4.0
335
336 .. versionchanged:: 4.0.0
337 Added `method` parameter.
338
339 .. versionchanged:: 5.5.0
340 Grab 'Primary Authenticated At' from request_attrs
341 which is set from either session or auth token
342 """
343
344 if method == "basic":
345 return True
346
347 if within.total_seconds() < 0:
348 # this means 'always fresh'
349 return True
350
351 if not (paa := get_request_attr("fs_paa")):
352 # No recorded primary authenticated at time, you can't play.
353 return False
354
355 now = naive_utcnow()
356 new_exp = now + grace
357 grace_ts = int(new_exp.timestamp())
358
359 if fs_gexp := session.get("fs_gexp", None):
360 if now.timestamp() < fs_gexp:
361 # Within grace period - extend it, and we're good.
362 session["fs_gexp"] = grace_ts
363 return True
364
365 authn_time = naive_utcfromtimestamp(paa)
366 # allow for some time drift where it's possible authn_time is in the future
367 # but let's be cautious and not allow arbitrary future times
368 delta = now - authn_time
369 if within > delta > -within:
370 session["fs_gexp"] = grace_ts
371 return True
372 return False
373
374
375 def get_hmac(password: str | bytes) -> bytes:
376 """Returns a Base64 encoded HMAC+SHA512 of the password signed with
377 the salt specified by :py:data:`SECURITY_PASSWORD_SALT`.
378
379 :param password: The password to sign
380 """
381 if not (salt := _config_value("PASSWORD_SALT")):
382 raise RuntimeError(
383 "The configuration value `SECURITY_PASSWORD_SALT` must "
384 "not be None when the value of `SECURITY_PASSWORD_HASH` is "
385 'set to "%s"' % _config_value("PASSWORD_HASH")
386 )
387
388 h = hmac.new(_encode_string(salt), _encode_string(password), hashlib.sha512)
389 return base64.b64encode(h.digest())
390
391
392 def verify_password(password: str | bytes, password_hash: str | bytes) -> bool:
393 """Returns ``True`` if the password matches the supplied hash.
394
395 :param password: A plaintext password to verify
396 :param password_hash: The expected hash value of the password
397 (usually from your database)
398
399 .. note::
400 Make sure that the password passed in has already been normalized.
401 """
402 if _use_double_hash(password_hash):
403 password = get_hmac(password)
404 if _pwd_context.identify(password_hash) == "bcrypt":
405 password = password[:72]
406
407 return _pwd_context.verify(password, password_hash)
408
409
410 def verify_and_update_password(password: str | bytes, user: UserMixin) -> bool:
411 """Returns ``True`` if the password is valid for the specified user.
412
413 Additionally, the hashed password in the database is updated if the
414 hashing algorithm happens to have changed.
415
416 N.B. you MUST call DB commit if you are using a session-based datastore
417 (such as SqlAlchemy) since the user instance might have been altered
418 (i.e. ``app.security.datastore.commit()``).
419 This is usually handled in the view.
420
421 :param password: A plaintext password to verify
422 :param user: The user to verify against
423
424 .. tip::
425 This should not be called directly - rather use
426 :meth:`.UserMixin.verify_and_update_password`
427
428 """
429 # Capture the original input in case we need to pass the unaltered
430 # value to hash_password if the hashing algorithm has changed
431 input_password = password
432
433 if _use_double_hash(user.password):
434 password = get_hmac(password)
435 if _pwd_context.identify(user.password) == "bcrypt":
436 password = password[:72]
437 verified = _pwd_context.verify(password, user.password)
438 else:
439 # Try with original password.
440 verified = _pwd_context.verify(password, user.password)
441
442 if verified and (user.password is None or _pwd_context.needs_update(user.password)):
443 user.password = hash_password(input_password)
444 _datastore.put(user)
445 return verified
446
447
448 def hash_password(password: str | bytes) -> str:
449 """Hash the specified plaintext password.
450
451 Unless the hash algorithm (as specified by
452 :py:data:`SECURITY_PASSWORD_HASH`) is listed in
453 the configuration variable :py:data:`SECURITY_PASSWORD_SINGLE_HASH`,
454 perform a double hash - first create an HMAC from the plaintext password
455 and the value of :py:data:`SECURITY_PASSWORD_SALT`,
456 then use the configured hashing algorithm.
457 This satisfies OWASP/ASVS section 2.4.5: 'provide additional
458 iteration of a key derivation'.
459
460 .. versionadded:: 2.0.2
461
462 .. versionchanged:: 5.7.0
463 Explicit check for bcrypt truncation
464
465 :param password: The plaintext password to hash
466 """
467 if _use_double_hash():
468 password = get_hmac(password).decode("ascii")
469
470 # Passing in options as part of hash is deprecated in passlib 1.7
471 # and new algorithms like argon2 don't even support it.
472 if _config_value("PASSWORD_HASH") == "bcrypt":
473 # bcrypt - OWASP says truncation concerns are negligible:
474 # https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#input-limits-of-bcrypt
475 password = password[:72]
476
477 return _pwd_context.hash(
478 password,
479 **_config_value("PASSWORD_HASH_OPTIONS", default={}).get(
480 _config_value("PASSWORD_HASH"), {}
481 ),
482 )
483
484
485 def _encode_string(string: t.Union[str, bytes]) -> bytes:
486 """Encodes a string to bytes, if it isn't already.
487
488 :param string: The string to encode
489 :return: UTF-8 encoded bytes
490 """
491 if isinstance(string, str):
492 string = string.encode("utf-8")
493 return string
494
495
496 def hash_data(data: t.Union[str, bytes]) -> str:
497 """Hashes input data after ensuring proper encoding.
498
499 :param data: Input data to hash (will be encoded if not already bytes)
500 :return: Hashed data as bytes
501
502 Note: Uses application's configured _hashing_context
503 """
504 return _hashing_context.hash(_encode_string(data))
505
506
507 def verify_hash(hashed_data: bytes, compare_data: t.Union[str, bytes]) -> bool:
508 """Verifies data against a previously hashed value.
509
510 :param hashed_data: Previously hashed data to compare against
511 :param compare_data: Input data to verify (will be encoded if not already bytes)
512 :return: True if data matches hash, False otherwise
513
514 Note: Uses application's configured _hashing_context
515 """
516 return _hashing_context.verify(_encode_string(compare_data), hashed_data)
517
518
519 def _suppress_form_csrf():
520 """
521 Return meta contents if we should suppress form from attempting to validate CSRF.
522
523 If app doesn't want CSRF for unauth endpoints then check if caller is authenticated
524 or not (many endpoints can be called either way).
525 """
526 if _config_value("CSRF_IGNORE_UNAUTH_ENDPOINTS") and not is_user_authenticated(
527 current_user
528 ):
529 return {"csrf": False}
530 return {}
531
532
533 def _confirm_redirect(form, identity_attribute):
534 """This is a very specific utility that all open endpoints call
535 to implement the confirm redirect feature.
536 """
537 if (
538 form.requires_confirmation
539 and _config_value("REQUIRES_CONFIRMATION_ERROR_VIEW")
540 and not _config_value("RETURN_GENERIC_RESPONSES")
541 ):
542 do_flash(*get_message("CONFIRMATION_REQUIRED"))
543 return redirect(
544 get_url(
545 _config_value("REQUIRES_CONFIRMATION_ERROR_VIEW"),
546 qparams={identity_attribute: getattr(form.user, identity_attribute)},
547 )
548 )
549 return None
550
551
552 def do_flash(message: str, category: str) -> None:
553 """Flash a message depending on if the `FLASH_MESSAGES` configuration
554 value is set.
555
556 :param message: The flash message
557 :param category: The flash message category
558 """
559 if _config_value("FLASH_MESSAGES"):
560 flash(message, category)
561
562
563 def parse_auth_token(auth_token: str) -> dict[str, t.Any]:
564 """Parse an authentication token.
565 This will raise an exception if not properly signed or expired
566 """
567 tdata = dict()
568
569 # This can raise BadSignature or SignatureExpired exceptions from itsdangerous
570 raw_data = _security.remember_token_serializer.loads(
571 auth_token, max_age=_config_value("TOKEN_MAX_AGE").total_seconds()
572 )
573
574 # Version 3.x generated tokens that map to data with 3 elements,
575 # and fs_uniquifier was on last element.
576 # Version 4.0.0 generates tokens that map to data with only 1 element,
577 # which maps to fs_uniquifier.
578 # Version 5 and up are already a dict (with a version #)
579 if isinstance(raw_data, dict):
580 # new format - starting at ver=5
581 if not all(k in raw_data for k in ["ver", "uid", "exp"]):
582 raise ValueError("Token missing keys")
583 tdata = raw_data
584 if ts := tdata.get("exp"):
585 if ts < int(time.time()):
586 raise SignatureExpired("token[exp] value expired")
587 else:
588 # old tokens that were lists
589 if len(raw_data) == 1:
590 # version 4
591 tdata["ver"] = "4"
592 tdata["uid"] = raw_data[0]
593 else:
594 # version 3
595 tdata["ver"] = "3"
596 tdata["uid"] = raw_data[2]
597
598 return tdata
599
600
601 def get_url(endpoint_or_url: str, qparams: dict[str, str] | None = None) -> str:
602 """Returns a URL if a valid endpoint is found. Otherwise, returns the
603 provided value.
604
605 .. warning::
606 If an endpoint ISN'T provided, then it is assumed that the URL
607 is external to Flask and if the spa configuration REDIRECT_HOST
608 is set will redirect to that host. This could be an issue in
609 development.
610
611 :param endpoint_or_url: The endpoint name or URL to default to
612 :param qparams: additional query params to add to end of url
613 :return: URL
614 """
615 try:
616 return transform_url(url_for(endpoint_or_url), qparams)
617 except Exception:
618 # This is an external URL (no endpoint defined in app)
619 # For (mostly) testing - allow changing/adding the url - for example
620 # add a different host:port for cases where the UI is running
621 # separately.
622 if _config_value("REDIRECT_HOST"):
623 url = transform_url(
624 endpoint_or_url, qparams, netloc=_config_value("REDIRECT_HOST")
625 )
626 else:
627 url = transform_url(endpoint_or_url, qparams)
628
629 return url
630
631
632 def _slash_url_suffix(url: str, suffix: str) -> str:
633 """
634 Formats a suffix to be appended to a URL, ensuring proper slash placement.
635
636 If the given `url` ends with a slash, this function adds a trailing slash
637 to the `suffix`.
638 Otherwise, it adds a leading slash to the `suffix`.
639 This helps prevent double slashes or missing slashes when constructing URLs.
640
641 :param url: The base URL to which the suffix will be appended.
642 :param suffix: The suffix to be appended to the URL.
643 :return: The formatted suffix with the appropriate leading or trailing slash.
644
645 Example:
646 >>> _slash_url_suffix("https://example.com/api", "v1")
647 '/v1'
648 >>> _slash_url_suffix("https://example.com/api/", "v1")
649 'v1/'
650 """
651 return url.endswith("/") and f"{suffix}/" or f"/{suffix}"
652
653
654 def transform_url(
655 url: str, qparams: dict[str, str] | None = None, **kwargs: str
656 ) -> str:
657 """Modify url
658
659 :param url: url to transform (can be relative)
660 :param qparams: additional query params to add to end of url
661 :param kwargs: pieces of URL to modify - e.g. netloc=localhost:8000
662 :return: Modified URL
663
664 .. versionadded:: 3.2.0
665 """
666 link_parse = urlsplit(url)
667 if qparams:
668 current_query = dict(parse_qsl(link_parse.query))
669 current_query.update(qparams)
670 link_parse = link_parse._replace(query=urlencode(current_query))
671 return urlunsplit(link_parse._replace(**kwargs))
672
673
674 def _get_security_endpoint_name(endpoint: str) -> str:
675 """
676 Returns the fully qualified endpoint name by combining the blueprint name
677 and the endpoint.
678
679 :param endpoint: The endpoint name to be combined with the blueprint name.
680 :return: The fully qualified endpoint name in the format '<blueprint>.<endpoint>'.
681
682 Example:
683 >>> _get_security_endpoint_name("login")
684 'my_blueprint.login'
685 """
686 return f"{_config_value('BLUEPRINT_NAME')}.{endpoint}"
687
688
689 def url_for_security(endpoint: str, **values: t.Any) -> str:
690 """Return a URL for the security blueprint
691
692 :param endpoint: the endpoint of the URL (name of the function)
693 :param values: the variable arguments of the URL rule
694 :param _external: if set to `True`, an absolute URL is generated. Server
695 address can be changed via `SERVER_NAME` configuration variable which
696 defaults to `localhost`.
697 :param _anchor: if provided, this is added as anchor to the URL.
698 :param _method: if provided, this explicitly specifies an HTTP method.
699 """
700 endpoint = _get_security_endpoint_name(endpoint)
701 # mypy is complaining about this - but I think it's wrong?
702 return url_for(endpoint, **values) # type: ignore
703
704
705 def validate_redirect_url(url: str) -> bool:
706 """Validate redirect URL
707 In the default configuration only redirects to the same domain (and scheme)
708 are allowed.
709 The REDIRECT_ALLOW_SUBDOMAINS allows ANY subdomain of SERVER_NAME
710 to be a redirect target.
711 The REDIRECT_BASE_DOMAIN and REDIRECT_ALLOWED_SUBDOMAINS allow specifying 'side'
712 redirects.
713 """
714
715 if url is None or url.strip() == "":
716 return False
717
718 # Browsers treat backslashes like forward slashes, while urllib doesn't.
719 # Since we just want to validate scheme and netloc here, we normalize
720 # slashes to those recognized by urllib. We need to test both variants
721 # though because replacing a backslash with a slash can result in different
722 # ways to inject shit.
723 for url_variant in (url, url.replace("\\", "/")):
724 # Browsers are great at accepting crappy data, so `////example.com` is
725 # handled like `//example.com`, even though it's invalid and `urlparse`
726 # will not set a netloc when receiving such a URL.
727 if url_variant.startswith("///"):
728 return False
729 url_info = urlsplit(url_variant)
730 if url_info.scheme and url_info.scheme not in {"http", "https"}:
731 return False
732 if url_info.scheme and not url_info.netloc:
733 return False
734
735 url_next = urlsplit(url)
736 url_base = urlsplit(request.host_url)
737 if (url_next.netloc or url_next.scheme) and url_next.netloc != url_base.netloc:
738 base_domain = current_app.config.get("SERVER_NAME")
739 if (
740 _config_value("REDIRECT_ALLOW_SUBDOMAINS")
741 and base_domain
742 and (
743 url_next.netloc == base_domain
744 or url_next.netloc.endswith(f".{base_domain}")
745 )
746 ):
747 return True
748 base_domain = _config_value("REDIRECT_BASE_DOMAIN")
749 if base_domain:
750 allowable = [
751 base_domain if sub == "." else f"{sub}.{base_domain}"
752 for sub in _config_value("REDIRECT_ALLOWED_SUBDOMAINS")
753 ]
754 return url_next.netloc in allowable
755 return False
756 return True
757
758
759 def _get_post_action_redirect(
760 config_key: str, next_loc: FlaskForm | MultiDict | dict | None
761 ) -> str:
762 """
763 There is a security angle here - the result of this method is
764 sent to Flask::redirect() - and we need to be sure that it can't be
765 interpreted as a user-input external URL - that would mean we would
766 have an 'open-redirect' vulnerability.
767
768 The complexity here is that urlsplit() does pretty well, but browsers even today
769 May 2021 are very lenient in what they accept as URLs - for example:
770 next=\\\\github.com
771 next=%5C%5C%5Cgithub.com
772 next=/////github.com
773 next=%20\\\\github.com
774 next=%20///github.com
775 next=%20//github.com
776 next=%19////github.com - i.e. browser will strip control chars
777 next=%E2%80%8A///github.com - doesn't redirect! That is a unicode thin space.
778
779 All will result in a null netloc and scheme from urlsplit - however many browsers
780 will gladly strip off uninteresting characters and convert backslashes to forward
781 slashes - and the cases above will actually cause a redirect to github.com
782 Sigh.
783
784 Some articles claim that a relative url has to start with a '/' - but that isn't
785 strictly true. From: https://datatracker.ietf.org/doc/html/rfc3986#section-5
786 a relative path can start with a "//", "/", a non-colon, or be empty. So it seems
787 that all the above URLs are valid.
788 By the time we get the URL it may or may not have been unencoded - if part of a
789 query string, then it has been, but if set in the form, not.
790 This means we can't really determine
791 if it is 'valid' since it appears that '/'s can appear in the URL if escaped.
792
793 The solution is to simply 'quote' the path.
794
795 netloc has a same issue: https://amazon.com\\.lp.com will cause many
796 browsers to redirect to amazon.com
797 """
798 rurl = _propagate_next(_find_redirect(config_key), next_loc)
799
800 u = urlsplit(rurl)
801 userinfo = ""
802 if u.username or u.password:
803 userinfo = f"{u.username}:{u.password}@"
804 hostname = quote(u.hostname) if u.hostname else ""
805 if u.port:
806 netloc = f"{userinfo}{hostname}:{u.port}"
807 else:
808 netloc = f"{userinfo}{hostname}"
809
810 safe_url = urlunsplit((u.scheme, netloc, quote(u.path), u.query, u.fragment))
811 return safe_url
812
813
814 def _get_post_login_redirect() -> str:
815 return _get_post_action_redirect("SECURITY_POST_LOGIN_VIEW", request.form)
816
817
818 def _get_post_register_redirect() -> str:
819 return _get_post_action_redirect("SECURITY_POST_REGISTER_VIEW", request.form)
820
821
822 def _get_post_logout_redirect() -> str:
823 return _get_post_action_redirect("SECURITY_POST_LOGOUT_VIEW", request.form)
824
825
826 def _get_post_verify_redirect() -> str:
827 return _get_post_action_redirect("SECURITY_POST_VERIFY_VIEW", request.form)
828
829
830 def _find_redirect(key: str) -> str:
831 """Returns the URL to redirect to.
832
833 :param key: The application configuration key to search for
834 """
835 app_url = None
836 if app_value := current_app.config[key.upper()]:
837 app_url = get_url(app_value)
838 rv = app_url or str(current_app.config.get("APPLICATION_ROOT", "/"))
839 return rv
840
841
842 def _propagate_next(
843 fallback_url: str, form: FlaskForm | MultiDict | dict | None
844 ) -> str:
845 """Compute appropriate redirect URL
846 The application can add a 'next' query parameter or have 'next' as a form field.
847 If either exist, make sure they are valid (not pointing to external location)
848 If neither, return the fallback_url
849
850 Can be passed either request.form
851 (which is really a MultiDict OR a real form OR a dict with a 'next' key).
852 """
853 form_next = None
854 if form and isinstance(form, FlaskForm):
855 if hasattr(form, "next") and form.next.data:
856 form_next = form.next.data
857 elif form and form.get("next", None):
858 form_next = str(form.get("next"))
859 arg_next = request.args.get("next")
860
861 urls = [
862 get_url(form_next) if form_next else None,
863 get_url(arg_next) if arg_next else None,
864 fallback_url,
865 ]
866 for url in urls:
867 if url and validate_redirect_url(url):
868 return url
869 raise ValueError("No valid redirect URL found - configuration error")
870
871
872 def _simplify_url(base_url: str, redirect_url: str) -> str:
873 """
874 Reduces the scheme and host from the redirect_url so it can be passed
875 as a relative URL in a query (e.g. next) param.
876 For this method we aren't worrying about a valid url (e.g. if it points
877 externally) - that will be handled by later requests.
878
879 :param base_url: The URL to simplify 'against'.
880 :param redirect_url: The URL to reduce.
881 """
882 b_url = urlsplit(base_url)
883 r_url = urlsplit(redirect_url)
884
885 if (not r_url.scheme or r_url.scheme == b_url.scheme) and (
886 not r_url.netloc or r_url.netloc == b_url.netloc
887 ):
888 return urlunsplit(("", "", r_url.path, r_url.query, r_url.fragment))
889 return redirect_url
890
891
892 def get_message(key: str, **kwargs: t.Any) -> tuple[str, str]:
893 rv = _config_value("MSG_" + key)
894 return localize_callback(rv[0], **kwargs), rv[1]
895
896
897 def _config_value(key, app=None, default=None, strict=True):
898 """Get a Flask-Security configuration value.
899
900 :param key: The configuration key without the prefix `SECURITY_`
901 :param app: An optional specific application to inspect. Defaults to
902 Flask's `current_app`
903 :param default: An optional default value if the value is not set
904 :param strict: if True, will raise ValueError if key doesn't exist
905 """
906 app = app or current_app
907 key = f"SECURITY_{key.upper()}"
908 # protect against spelling mistakes
909 if strict and key not in app.config:
910 raise ValueError(f"Key {key} doesn't exist")
911 return app.config.get(key, default)
912
913
914 def _td_format(td: timedelta) -> str:
915 """Formats a timedelta object to a string.
916 Use humanize.precisedelta if available otherwise use
917 this simplistic version of what humanize provides (English only).
918 """
919 try:
920 import humanize
921
922 return humanize.precisedelta(td)
923 except ImportError:
924 periods = [
925 ("year", 60 * 60 * 24 * 365),
926 ("month", 60 * 60 * 24 * 30),
927 ("day", 60 * 60 * 24),
928 ("hour", 60 * 60),
929 ("minute", 60),
930 ("second", 1),
931 ]
932
933 seconds = int(td.total_seconds())
934 strings = []
935 for period_name, period_seconds in periods:
936 if seconds >= period_seconds:
937 period_value, seconds = divmod(seconds, period_seconds)
938 has_s = "s" if period_value > 1 else ""
939 strings.append(f"{period_value} {period_name}{has_s}")
940 if len(strings) == 2:
941 return " and ".join(strings)
942 return ", ".join(strings)
943
944
945 def send_mail(
946 subject: str, recipient: str | tuple[str, str], template: str, **context: t.Any
947 ) -> None:
948 """Send an email.
949
950 :param subject: Email subject
951 :param recipient: Email recipient
952 :param template: The path/name of the email template
953 :param context: The context to render the template with
954
955 This formats the email and passes it off to :class:`.MailUtil` to actually send the
956 message.
957 """
958
959 context.setdefault("security", _security)
960 context.update(_security._run_ctx_processor("mail"))
961
962 body = None
963 html = None
964 if _config_value("EMAIL_PLAINTEXT"):
965 body = _security.render_template(f"{template}.txt", **context)
966 if _config_value("EMAIL_HTML"):
967 html = _security.render_template(f"{template}.html", **context)
968
969 subject = localize_callback(subject)
970
971 sender = _config_value("EMAIL_SENDER")
972 if isinstance(sender, LocalProxy):
973 sender = sender._get_current_object()
974
975 _security.mail_util.send_mail(
976 template,
977 subject,
978 recipient,
979 sender,
980 body,
981 html,
982 **context,
983 )
984
985
986 def check_and_get_token_status(
987 token: str, serializer_name: str, within: timedelta
988 ) -> tuple[bool, bool, t.Any]:
989 """Get the status of a token and return data.
990
991 :param token: The token to check
992 :param serializer_name: The name of the serializer. Can be one of the
993 following: ``confirm``, ``login``, ``reset``, ``us_setup``
994 ``remember``, ``tf_validity``, ``tf_setup``,
995 ``wan``, ``change_email``,
996 ``refresh_token``
997 :param within: max age - passed as a timedelta
998
999 :return: a tuple of (expired, invalid, data)
1000
1001 .. versionadded:: 3.4.0
1002 """
1003 serializer = getattr(_security, serializer_name + "_serializer")
1004 max_age = within.total_seconds()
1005 data = None
1006 expired, invalid = False, False
1007
1008 try:
1009 data = serializer.loads(token, max_age=max_age)
1010 except SignatureExpired:
1011 d, data = serializer.loads_unsafe(token)
1012 expired = True
1013 except (BadSignature, TypeError, ValueError):
1014 invalid = True
1015
1016 return expired, invalid, data
1017
1018
1019 def get_identity_attributes(app: Flask | None = None) -> list[str]:
1020 # Return list of keys of identity attributes
1021 # Is it possible to not have any?
1022 app = app or current_app
1023 iattrs = app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"]
1024 if iattrs:
1025 return [[*f][0] for f in iattrs]
1026 return []
1027
1028
1029 def get_identity_attribute(attr: str, app: Flask | None = None) -> dict[str, t.Any]:
1030 """Given a user_identity_attribute, return the defining dict.
1031 A bit annoying since USER_IDENTITY_ATTRIBUTES is a list of dict
1032 where each dict has just one key.
1033 """
1034 app = app or current_app
1035 iattrs = app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"]
1036 if iattrs:
1037 details = [
1038 mapping[attr] for mapping in iattrs if list(mapping.keys())[0] == attr
1039 ]
1040 if details:
1041 return details[0]
1042 return {}
1043
1044
1045 def lookup_identity(identity: str | int) -> UserMixin | None:
1046 """
1047 Lookup identity in DB.
1048 This loops through, in order, :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`,
1049 and first calls the mapper function to normalize.
1050 Then the db.find_user is called on the specified user model attribute.
1051 """
1052 for mapping in _config_value("USER_IDENTITY_ATTRIBUTES"):
1053 attr = list(mapping.keys())[0]
1054 details = mapping[attr]
1055 idata = details["mapper"](identity)
1056 if idata:
1057 user = _datastore.find_user(
1058 case_insensitive=details.get("case_insensitive", False), **{attr: idata}
1059 )
1060 return user
1061 return None
1062
1063
1064 def uia_phone_mapper(identity: str) -> str | None:
1065 """Used to normalize a phone number. This is a simple proxy
1066 to :py:meth:`PhoneUtil.get_canonical_form`
1067
1068 See :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.
1069
1070 .. versionadded:: 3.4.0
1071 """
1072 ph = _security.phone_util.get_canonical_form(identity)
1073 return ph
1074
1075
1076 def uia_email_mapper(identity: str) -> str | None:
1077 """Used to normalize identity as an email.
1078 This is a simple proxy
1079 to :py:meth:`MailUtil.normalize`
1080
1081 :return: Normalized email or None if not valid email.
1082
1083 See :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.
1084
1085 .. versionadded:: 3.4.0
1086 """
1087
1088 try:
1089 return _security.mail_util.normalize(identity)
1090 except ValueError:
1091 return None
1092
1093
1094 def uia_username_mapper(identity: str) -> str | None:
1095 """Used to normalize a username. This is a simple proxy
1096 to :py:meth:`UsernameUtil.normalize`
1097
1098 See :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.
1099
1100 .. versionadded:: 4.1.0
1101 """
1102 return _security.username_util.normalize(identity)
1103
1104
1105 def _use_double_hash(password_hash=None):
1106 """Return a bool indicating whether a password should be hashed twice."""
1107 # Default to plaintext for backward compatibility with
1108 # :py:data:`SECURITY_PASSWORD_SINGLE_HASH` = False
1109 single_hash = _config_value("PASSWORD_SINGLE_HASH") or {"plaintext"}
1110
1111 if password_hash is None:
1112 scheme = _config_value("PASSWORD_HASH")
1113 else:
1114 scheme = _pwd_context.identify(password_hash)
1115
1116 return not (single_hash is True or scheme in single_hash)
1117
1118
1119 def _csrf_cookie_handler(response: Response) -> Response:
1120 """Called at end of every request.
1121 Uses session to track state (set/clear)
1122
1123 Ideally we just need to set this once - however by default
1124 Flask-WTF has a time-out on these tokens governed by *WTF_CSRF_TIME_LIMIT*.
1125 While we could set that to None - and OWASP implies this is fine - that might
1126 not be agreeable to everyone.
1127 So as a basic usability hack - we check if it is expired and re-generate so at least
1128 the user doesn't have to log out and back in (just refresh).
1129 We also support a *CSRF_COOKIE_REFRESH_EACH_REQUEST* analogous to Flask's
1130 *SESSION_REFRESH_EACH_REQUEST*
1131
1132 It is of course removed on logout/session end.
1133 Other info on web suggests replacing on every POST and accepting up to 'age' ago.
1134 """
1135 csrf_cookie = _config_value("CSRF_COOKIE")
1136 csrf_cookie_name = _config_value("CSRF_COOKIE_NAME")
1137 if not csrf_cookie_name:
1138 return response
1139
1140 op = session.get("fs_cc", None)
1141 if not op:
1142 remember_cookie_name = current_app.config.get(
1143 "REMEMBER_COOKIE_NAME", REMEMBER_COOKIE_NAME
1144 )
1145 has_remember_cookie = (
1146 remember_cookie_name in request.cookies
1147 and session.get("remember") != "clear"
1148 )
1149 # Set cookie if successfully logged in with flask_login's remember cookie
1150 if has_remember_cookie and is_user_authenticated(current_user):
1151 op = "set"
1152 else:
1153 return response
1154
1155 if op == "clear":
1156 # Alas delete_cookie only accepts some of the keywords set_cookie does
1157 allowed = ["path", "domain", "secure", "httponly", "samesite"]
1158 args = {k: csrf_cookie.get(k) for k in allowed if k in csrf_cookie}
1159 response.delete_cookie(csrf_cookie_name, **args)
1160 session.pop("fs_cc")
1161 return response
1162
1163 # Send a cookie if any of:
1164 # 1) CSRF_COOKIE_REFRESH_EACH_REQUEST is true
1165 # 2) fs_cc == "set" - this is on first login
1166 # 3) existing cookie has expired
1167 send = False
1168 if op == "set":
1169 send = True
1170 session["fs_cc"] = "sent"
1171 elif _config_value("CSRF_COOKIE_REFRESH_EACH_REQUEST"):
1172 send = True
1173 elif current_app.config["WTF_CSRF_TIME_LIMIT"]:
1174 current_cookie = request.cookies.get(csrf_cookie_name, None)
1175 if current_cookie:
1176 # Let's make sure it isn't expired if app doesn't set TIME_LIMIT to None.
1177 try:
1178 csrf.validate_csrf(current_cookie)
1179 except ValidationError:
1180 send = True
1181
1182 if send:
1183 response.set_cookie(csrf_cookie_name, value=csrf.generate_csrf(), **csrf_cookie)
1184 return response
1185
1186
1187 def _add_cache_control(resp: Response) -> Response:
1188 """Add cache control header attributes to response."""
1189 cc = _config_value("CACHE_CONTROL") or dict()
1190 for attr, v in cc.items():
1191 resp.cache_control[attr] = v
1192 return resp
1193
1194
1195 def allowed_auth_token(user: UserMixin) -> bool:
1196 """When an endpoint could return an auth_token (such as all the authentication
1197 endpoints) - this utility if it should - based on configuration variables."""
1198 if (
1199 _config_value("BACKWARDS_COMPAT_AUTH_TOKEN")
1200 or "include_auth_token" in request.args
1201 ):
1202 return True
1203 return False
1204
1205
1206 def base_render_json(
1207 form: FlaskForm,
1208 include_user: bool = True,
1209 include_auth_token: bool = False,
1210 additional: dict[str, t.Any] | None = None,
1211 error_status_code: int = 400,
1212 ) -> ResponseValue:
1213 """
1214 This method is called by all views that return JSON responses.
1215 This fills in the response and then calls :meth:`.Security.render_json`
1216 which can be overridden by the app.
1217 """
1218 user = getattr(form, "user", None)
1219 if form.errors:
1220 code = error_status_code
1221 # wtforms 3.0 introduces form-level errors - these show up as part of the
1222 # errors dict with a key of 'None'
1223 payload = json_error_response(field_errors=form.errors)
1224 else:
1225 code = 200
1226 payload = dict()
1227 if user:
1228 # This will be false for anonymous GETs via JSON
1229 from .tokens import response_tokens
1230
1231 if include_user:
1232 payload["user"] = user.get_security_payload()
1233
1234 if include_auth_token:
1235 response_tokens(user, payload)
1236
1237 # Return csrf_token on each JSON response - just as every form
1238 # has it rendered.
1239 payload["csrf_token"] = csrf.generate_csrf()
1240 if additional:
1241 payload.update(additional)
1242
1243 return _security._render_json(payload, code, None, user)
1244
1245
1246 def simple_render_json(
1247 additional: dict[str, t.Any] | None = None,
1248 ) -> ResponseValue:
1249 payload = dict(csrf_token=csrf.generate_csrf())
1250 if additional:
1251 payload.update(additional)
1252 return _security._render_json(payload, 200, None, None)
1253
1254
1255 def _default_want_json(req):
1256 """Return True if response should be in json
1257 N.B. do not call this directly - use security._want_json()
1258
1259 :param req: Flask/Werkzeug Request
1260 """
1261 if req.is_json:
1262 return True
1263 # TODO should this handle json sub-types?
1264 accept_mimetypes = req.accept_mimetypes
1265 if not hasattr(req.accept_mimetypes, "best"): # pragma: no cover
1266 # Alright. we don't have the best property, lets add it ourselves.
1267 # This is for quart compatibility
1268 accept_mimetypes.best = best
1269 if accept_mimetypes.best == "application/json":
1270 return True
1271 return False
1272
1273
1274 def json_error_response(
1275 errors: str | list[str] | None = None,
1276 field_errors: dict[str, list[str]] | None = None,
1277 ) -> dict[str, t.Any]:
1278 """Helper to create an error response.
1279
1280 The "errors" key holds a simple list of errors - which is made up of any passed
1281 errors (either a string or list) as well as the (localized) error msgs from the
1282 passed in field_errors.
1283
1284 The "field_errors" key which is exactly what is returned from WTForms - namely
1285 a dict of field-name: [msg].
1286 """
1287 response_json: dict[str, list | dict[str, list]] = dict()
1288 plain_errors = []
1289 if errors:
1290 if isinstance(errors, str):
1291 plain_errors = [errors]
1292 elif isinstance(errors, list):
1293 plain_errors = errors
1294 else:
1295 raise TypeError("The errors argument should be either a str or list.")
1296 if field_errors:
1297 # This is default from WTForms - a dictionary of field name and list of errors
1298 # we return that, as well as create a simple list of errors.
1299 for e in field_errors.values():
1300 plain_errors.extend(e)
1301 response_json["field_errors"] = field_errors # type: ignore
1302 response_json["errors"] = plain_errors
1303
1304 return response_json
1305
1306
1307 def _default_render_template(*args: t.Any, **kwargs: t.Any) -> str:
1308 return render_template(*args, **kwargs)
1309
1310
1311 class SmsSenderBaseClass(metaclass=abc.ABCMeta):
1312 @abc.abstractmethod
1313 def send_sms(
1314 self, from_number: str, to_number: str, msg: str
1315 ) -> None: # pragma: no cover
1316 """Abstract method for sending sms messages
1317
1318 .. versionadded:: 3.2.0
1319 """
1320 return
1321
1322
1323 class DummySmsSender(SmsSenderBaseClass):
1324 def send_sms(
1325 self, from_number: str, to_number: str, msg: str
1326 ) -> None: # pragma: no cover
1327 """Do nothing."""
1328 return None
1329
1330
1331 class SmsSenderFactory:
1332 senders: dict[str, t.Type[SmsSenderBaseClass]] = {"Dummy": DummySmsSender}
1333
1334 @classmethod
1335 def createSender(
1336 cls, name: str, *args: t.Any, **kwargs: t.Any
1337 ) -> SmsSenderBaseClass:
1338 """Initialize an SMS sender.
1339
1340 :param name: Name as registered in SmsSenderFactory:senders (e.g. 'Twilio')
1341
1342 .. versionadded:: 3.2.0
1343 """
1344 return cls.senders[name](*args, **kwargs)
1345
1346
1347 try: # pragma: no cover
1348 from twilio.rest import Client
1349
1350 class TwilioSmsSender(SmsSenderBaseClass):
1351 def __init__(self, *args: t.Any, **kwargs: t.Any):
1352 super().__init__(*args, **kwargs)
1353 self.account_sid: str = _config_value("SMS_SERVICE_CONFIG")["ACCOUNT_SID"]
1354 self.auth_token: str = _config_value("SMS_SERVICE_CONFIG")["AUTH_TOKEN"]
1355
1356 def send_sms(self, from_number: str, to_number: str, msg: str) -> None:
1357 """Send message via twilio account."""
1358 client = Client(self.account_sid, self.auth_token)
1359 client.messages.create(to=to_number, from_=from_number, body=msg)
1360
1361 SmsSenderFactory.senders["Twilio"] = TwilioSmsSender
1362 except Exception:
1363 pass
1364
1365
1366 def password_length_validator(password: str) -> list[str] | None:
1367 """Test password for length.
1368
1369 :param password: Plain text password to check
1370
1371 :return: ``None`` if password conforms to length requirements,
1372 a list of error/suggestions if not.
1373
1374 .. versionadded:: 3.4.0
1375
1376 """
1377 if len(password) < _config_value("PASSWORD_LENGTH_MIN") or len(password) > 128:
1378 return [
1379 get_message(
1380 "PASSWORD_INVALID_LENGTH", length=_config_value("PASSWORD_LENGTH_MIN")
1381 )[0]
1382 ]
1383 return None
1384
1385
1386 def password_complexity_validator(
1387 password: str, is_register: bool, **kwargs: t.Any
1388 ) -> list[str] | None:
1389 """Test password for complexity.
1390
1391 Currently just supports 'zxcvbn'.
1392
1393 :param password: Plain text password to check
1394 :param is_register: if True then kwargs are arbitrary additional info. (e.g.
1395 info from a registration form). If False, must be a SINGLE key "user" that
1396 corresponds to the current_user. All string values will be extracted and
1397 sent to the complexity checker.
1398 :param kwargs:
1399
1400 :return: ``None`` if password is complex enough, a list of error/suggestions if not.
1401 Be aware that zxcvbn does not (easily) provide a way to localize messages.
1402
1403 .. versionadded:: 3.4.0
1404 """
1405
1406 if _config_value("PASSWORD_COMPLEXITY_CHECKER") == "zxcvbn":
1407 import zxcvbn
1408
1409 user_info: list[t.Any] = []
1410 if not is_register:
1411 for v in kwargs["user"].__dict__.values():
1412 if v and isinstance(v, str):
1413 user_info.append(v)
1414 else:
1415 # This is usually all register form values that are in the user_model
1416 if kwargs:
1417 user_info = list(kwargs.values())
1418 results = zxcvbn.zxcvbn(password, user_inputs=user_info)
1419 if results["score"] >= _config_value("ZXCVBN_MINIMUM_SCORE"):
1420 return None
1421 # Should we return suggestions? Default forms don't really know what to do.
1422 if results["feedback"]["warning"]:
1423 # Note that these come from zxcvbn and
1424 # aren't localizable via Flask-Security
1425 return [results["feedback"]["warning"]]
1426 return [get_message("PASSWORD_TOO_SIMPLE")[0]]
1427 else:
1428 return None
1429
1430
1431 def password_breached_validator(password: str) -> list[str] | None:
1432 """Check if password on breached list.
1433 Does nothing unless :py:data:`SECURITY_PASSWORD_CHECK_BREACHED` is set.
1434 If password is found on the breached list, return an error if the count is
1435 greater than or equal to :py:data:`SECURITY_PASSWORD_BREACHED_COUNT`.
1436 Uses :meth:`pwned`.
1437
1438 :param password: Plain text password to check
1439
1440 :return: ``None`` if password passes breached tests, else a list of error messages.
1441
1442 .. versionadded:: 3.4.0
1443 """
1444 if pwn := _config_value("PASSWORD_CHECK_BREACHED"):
1445 try:
1446 cnt = pwned(password)
1447 if cnt >= _config_value("PASSWORD_BREACHED_COUNT"):
1448 return [get_message("PASSWORD_BREACHED")[0]]
1449 except Exception:
1450 if pwn == "strict":
1451 return [get_message("PASSWORD_BREACHED_SITE_ERROR")[0]]
1452 return None
1453
1454
1455 def pwned(password: str) -> int:
1456 """
1457 Check password against pwnedpasswords API using k-Anonymity.
1458 https://haveibeenpwned.com/API/v3
1459
1460 :return: Count of password in DB (0 means hasn't been compromised)
1461
1462 Can raise HTTPError
1463
1464 .. versionadded:: 3.4.0
1465 """
1466
1467 def convert_password_tuple(value):
1468 hash_suffix, count = value.split(":")
1469 return hash_suffix, int(count)
1470
1471 sha1 = hashlib.sha1(password.encode("utf8")).hexdigest()
1472
1473 req = urllib.request.Request(
1474 url=f"https://api.pwnedpasswords.com/range/{sha1[:5].upper()}",
1475 headers={"User-Agent": "Flask-Security (Python)"},
1476 )
1477 # Might raise HTTPError
1478 with urllib.request.urlopen(req) as f:
1479 response = f.read()
1480
1481 raw = response.decode("utf-8-sig")
1482
1483 entries = dict(map(convert_password_tuple, raw.upper().split("\r\n")))
1484 return entries.get(sha1[5:].upper(), 0)
1485
1486
1487 def _handle_already_auth(form, payload=None):
1488 """
1489 Allow already authenticated users. For GET this is useful for
1490 single-page-applications on refresh - session still active but need to
1491 access user info and csrf-token.
1492 For GET with forms - redirect to POST_LOGIN_VIEW.
1493 For POST - redirects to POST_LOGIN_VIEW (forms) or returns 400 (json).
1494
1495 This does NOT use get_post_login_redirect() so that it doesn't look at
1496 'next' - which can cause infinite redirect loops
1497 (see test_basic::test_authenticated_loop)
1498
1499 While it's tempting to try to logout the current user and login the
1500 new requested user - that simply doesn't work with CSRF.
1501 """
1502 if _security._want_json(request):
1503 if request.method == "POST":
1504 payload = json_error_response(
1505 errors=get_message("ANONYMOUS_USER_REQUIRED")[0]
1506 )
1507 return _security._render_json(payload, 400, None, None)
1508 else:
1509 form.user = current_user
1510 return base_render_json(form, additional=payload)
1511 else:
1512 return redirect(get_url(_config_value("POST_LOGIN_VIEW")))
1513
1514
1515 def input_svn(
1516 value: str,
1517 allowed_categories: list[str] | None,
1518 normalize_form: t.Literal["NFC", "NFD", "NFKC", "NFKD"] | None,
1519 ) -> t.Tuple[t.Literal["ok", "illegal", "unallowed"], str | None]:
1520 """
1521 Used to sanitize, validate, and normalize (user/form) input
1522
1523 allowed_categories: list of allowed categories (input to unicodedata.category()).
1524
1525 normalize_form: input to unicodedata.normalize().
1526
1527 Returns a tuple of ("reason", cleaned_input)
1528 If cleaned_input is None, "reason" will be why. The "unallowed" response
1529 is dependent on the input 'allowed_categories' which normally is from a config
1530 variable.
1531
1532 .. versionadded:: 5.9.0
1533 """
1534 import nh3
1535
1536 sanitized = nh3.clean(value.strip(), tags=set())
1537 if sanitized != value.strip():
1538 return "illegal", None
1539 if allowed_categories:
1540 cats = [unicodedata.category(c)[0] for c in sanitized]
1541 if any([cat not in allowed_categories for cat in cats]):
1542 return "unallowed", None
1543 if normalize_form:
1544 return "ok", unicodedata.normalize(normalize_form, sanitized)
1545 return "ok", sanitized