| 1 |
""" |
| 2 |
flask_security.totp |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
Flask-Security TOTP (Timed-One-Time-Passwords) module |
| 6 |
|
| 7 |
:copyright: (c) 2019-2024 by J. Christopher Wagner (jwag). |
| 8 |
:license: MIT, see LICENSE for more details. |
| 9 |
""" |
| 10 |
|
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
import base64 |
| 14 |
import io |
| 15 |
import typing as t |
| 16 |
|
| 17 |
from passlib.totp import TOTP, TokenError, TotpMatch |
| 18 |
from passlib.pwd import genword |
| 19 |
|
| 20 |
if t.TYPE_CHECKING: # pragma: no cover |
| 21 |
from flask_security import UserMixin |
| 22 |
|
| 23 |
|
| 24 |
class Totp: |
| 25 |
"""Encapsulate usage of Passlib TOTP functionality. |
| 26 |
|
| 27 |
Flask-Security doesn't implement any replay-attack protection out of the box |
| 28 |
as suggested by: |
| 29 |
https://passlib.readthedocs.io/en/stable/narr/totp-tutorial.html#match-verify |
| 30 |
|
| 31 |
Subclass this and implement the get/set last_counter methods. Your subclass can |
| 32 |
be registered at Flask-Security creation/initialization time. |
| 33 |
|
| 34 |
.. versionadded:: 3.4.0 |
| 35 |
|
| 36 |
""" |
| 37 |
|
| 38 |
def __init__(self, secrets: dict[str, str] | dict[int, str], issuer: str): |
| 39 |
"""Initialize a totp factory. |
| 40 |
secrets are used to encrypt the per-user totp_secret on disk. |
| 41 |
""" |
| 42 |
# This should be a dict with at least one entry |
| 43 |
if not isinstance(secrets, dict) or len(secrets) < 1: |
| 44 |
raise ValueError("secrets needs to be a dict with at least one entry") |
| 45 |
self._totp = TOTP.using(issuer=issuer, secrets=secrets) |
| 46 |
|
| 47 |
def generate_totp_password(self, totp_secret: str) -> str: |
| 48 |
"""Get time-based one-time password on the basis of given secret and time |
| 49 |
:param totp_secret: the unique shared secret of the user |
| 50 |
""" |
| 51 |
tt = self._totp.from_source(totp_secret).generate() |
| 52 |
return tt.token # type: ignore[return-value] |
| 53 |
|
| 54 |
def generate_totp_secret(self) -> str: |
| 55 |
"""Create new user-unique totp_secret. |
| 56 |
|
| 57 |
We return an encrypted json string so that when sent in a cookie or |
| 58 |
sent to DB - it is encrypted. |
| 59 |
|
| 60 |
""" |
| 61 |
return self._totp.new().to_json(encrypt=True) |
| 62 |
|
| 63 |
def verify_totp( |
| 64 |
self, token: str, totp_secret: str, user: UserMixin, window: int = 0 |
| 65 |
) -> bool: |
| 66 |
"""Verifies token for specific user. |
| 67 |
|
| 68 |
:param token: token to be check against user's secret |
| 69 |
:param totp_secret: the unique shared secret of the user |
| 70 |
:param user: User model |
| 71 |
:param window: optional. How far backward and forward in time to search |
| 72 |
for a match. Measured in seconds. |
| 73 |
:return: True if match |
| 74 |
""" |
| 75 |
|
| 76 |
# TODO - in old implementation using onetimepass window was described |
| 77 |
# as 'compensate for clock skew) and 'interval_length' would say how long |
| 78 |
# the token is good for. |
| 79 |
# In passlib - 'window' means how far back and forward to look and 'clock_skew' |
| 80 |
# is specifically for well, clock slew. |
| 81 |
try: |
| 82 |
tmatch = self._totp.verify( |
| 83 |
token, |
| 84 |
totp_secret, |
| 85 |
window=window, |
| 86 |
last_counter=self.get_last_counter(user), |
| 87 |
) |
| 88 |
self.set_last_counter(user, tmatch) |
| 89 |
return True |
| 90 |
|
| 91 |
except TokenError: |
| 92 |
return False |
| 93 |
|
| 94 |
def get_totp_uri(self, username: str, totp_secret: str) -> str: |
| 95 |
"""Generate provisioning url for use with the qrcode |
| 96 |
scanner built into the app |
| 97 |
|
| 98 |
:param username: username/email of the current user |
| 99 |
:param totp_secret: a unique shared secret of the user |
| 100 |
""" |
| 101 |
tp = self._totp.from_source(totp_secret) |
| 102 |
return tp.to_uri(username) |
| 103 |
|
| 104 |
def get_totp_pretty_key(self, totp_secret: str) -> str: |
| 105 |
"""Generate pretty key for manual input |
| 106 |
|
| 107 |
:param totp_secret: a unique shared secret of the user |
| 108 |
|
| 109 |
.. versionadded:: 4.0.0 |
| 110 |
""" |
| 111 |
tp = self._totp.from_source(totp_secret) |
| 112 |
return tp.pretty_key() |
| 113 |
|
| 114 |
def get_totp_b32_key(self, totp_secret: str) -> str: |
| 115 |
"""Generate b32 key for creating a otpauth url |
| 116 |
|
| 117 |
:param totp_secret: a unique shared secret of the user |
| 118 |
|
| 119 |
.. versionadded:: 5.8.0 |
| 120 |
""" |
| 121 |
tp = self._totp.from_source(totp_secret) |
| 122 |
return tp.base32_key |
| 123 |
|
| 124 |
def fetch_setup_values(self, totp: str, user: UserMixin) -> dict[str, str]: |
| 125 |
"""Generate various values user needs to setup authenticator app. |
| 126 |
Returns dict with keys: |
| 127 |
'key': totp key |
| 128 |
'b32key': totp key in base32 |
| 129 |
'uri': provisioning url |
| 130 |
'image': image as string (useful for <img src=xx>) |
| 131 |
'username: qrcode best practice |
| 132 |
'issuer': qrcode best practice |
| 133 |
|
| 134 |
.. versionadded:: 4.0.0 |
| 135 |
|
| 136 |
.. versionchanged:: 5.8.0 |
| 137 |
Added keys b32key and uri |
| 138 |
""" |
| 139 |
|
| 140 |
r = dict() |
| 141 |
|
| 142 |
# By convention, the URI should have the username that the user |
| 143 |
# logs in with. |
| 144 |
username = user.calc_username() or "Unknown" |
| 145 |
assert self._totp.issuer |
| 146 |
r["username"] = username |
| 147 |
r["key"] = self.get_totp_pretty_key(totp) |
| 148 |
r["b32key"] = self.get_totp_b32_key(totp) |
| 149 |
r["issuer"] = self._totp.issuer |
| 150 |
r["image"] = self.generate_qrcode(username, totp) |
| 151 |
r["uri"] = self.get_totp_uri(username, totp) |
| 152 |
return r |
| 153 |
|
| 154 |
def generate_qrcode(self, username: str, totp: str) -> str: |
| 155 |
"""Generate QRcode |
| 156 |
Using username, totp, generate the actual QRcode image. |
| 157 |
This method can be overridden to fine-tune how the image is created - |
| 158 |
such as size, color etc. |
| 159 |
|
| 160 |
It must return a string suitable for use in an <img src=xx> tag. |
| 161 |
|
| 162 |
.. versionadded:: 4.0.0 |
| 163 |
""" |
| 164 |
try: |
| 165 |
import qrcode |
| 166 |
import qrcode.image.svg |
| 167 |
|
| 168 |
image = qrcode.make( |
| 169 |
self.get_totp_uri(username, totp), |
| 170 |
image_factory=qrcode.image.svg.SvgImage, |
| 171 |
) |
| 172 |
with io.BytesIO() as virtual_file: |
| 173 |
image.save(virtual_file) |
| 174 |
image_as_str = base64.b64encode(virtual_file.getvalue()).decode("ascii") |
| 175 |
|
| 176 |
return f"data:image/svg+xml;base64,{image_as_str}" |
| 177 |
except ImportError: # pragma: no cover |
| 178 |
# This should have been checked at app init. |
| 179 |
raise |
| 180 |
|
| 181 |
def generate_recovery_codes(self, number: int) -> list[str]: |
| 182 |
"""Generate a set of secure passwords - used for 2FA recovery codes. |
| 183 |
# this is nice for english - but not for others |
| 184 |
return genphrase(entropy="fair", wordset="eff_short", sep="-", |
| 185 |
returns=number) |
| 186 |
|
| 187 |
.. versionadded:: 5.0.0 |
| 188 |
""" |
| 189 |
pwds = genword(length=12, charset="hex", returns=number) |
| 190 |
# make this a bit easier to type - 3 sets of 4 characters |
| 191 |
spwds = [] |
| 192 |
for pwd in pwds: |
| 193 |
spwds.append( |
| 194 |
"-".join([pwd[i : i + 4] for i in range(0, len(pwd), 4)]) # noqa: E203 |
| 195 |
) |
| 196 |
return spwds |
| 197 |
|
| 198 |
def get_last_counter(self, user: UserMixin) -> int | None: |
| 199 |
"""Implement this to fetch stored last_counter from cache. |
| 200 |
|
| 201 |
:param user: User model |
| 202 |
:return: last_counter as stored in set_last_counter() |
| 203 |
""" |
| 204 |
return None |
| 205 |
|
| 206 |
def set_last_counter(self, user: UserMixin, tmatch: TotpMatch) -> None: |
| 207 |
"""Implement this to cache last_counter. |
| 208 |
|
| 209 |
:param user: User model |
| 210 |
:param tmatch: a TotpMatch as returned from totp.verify() |
| 211 |
""" |
| 212 |
pass |