| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import base64 |
| 4 |
import hashlib |
| 5 |
import hmac |
| 6 |
import secrets |
| 7 |
import struct |
| 8 |
import time |
| 9 |
from collections.abc import Iterator |
| 10 |
|
| 11 |
from django.contrib.auth.base_user import AbstractBaseUser |
| 12 |
from django.core.cache import cache |
| 13 |
from django.http import HttpRequest |
| 14 |
|
| 15 |
from allauth.core import context |
| 16 |
from allauth.mfa import app_settings |
| 17 |
from allauth.mfa.models import Authenticator |
| 18 |
from allauth.mfa.utils import decrypt, encrypt |
| 19 |
|
| 20 |
|
| 21 |
SECRET_SESSION_KEY = "mfa.totp.secret" # nosec |
| 22 |
|
| 23 |
|
| 24 |
def generate_totp_secret(length: int = 20) -> str: |
| 25 |
random_bytes = secrets.token_bytes(length) |
| 26 |
return base64.b32encode(random_bytes).decode("utf-8") |
| 27 |
|
| 28 |
|
| 29 |
def get_totp_secret(regenerate: bool = False) -> str: |
| 30 |
secret = None |
| 31 |
if not regenerate: |
| 32 |
secret = context.request.session.get(SECRET_SESSION_KEY) |
| 33 |
if not secret: |
| 34 |
secret = context.request.session[SECRET_SESSION_KEY] = generate_totp_secret() |
| 35 |
return secret |
| 36 |
|
| 37 |
|
| 38 |
def clear_totp_secret(request: HttpRequest) -> None: |
| 39 |
request.session.pop(SECRET_SESSION_KEY, None) |
| 40 |
|
| 41 |
|
| 42 |
def yield_hotp_counters_from_time() -> Iterator[int]: |
| 43 |
current_time = int(time.time()) # Get the current Unix timestamp |
| 44 |
counter = current_time // app_settings.TOTP_PERIOD |
| 45 |
for i in range(-app_settings.TOTP_TOLERANCE, app_settings.TOTP_TOLERANCE + 1): |
| 46 |
yield counter + i |
| 47 |
|
| 48 |
|
| 49 |
def hotp_value(secret: str, counter: int) -> int: |
| 50 |
# Convert the counter to a byte array using big-endian encoding |
| 51 |
counter_bytes = struct.pack(">Q", counter) |
| 52 |
secret_enc = base64.b32decode(secret.encode("ascii"), casefold=True) |
| 53 |
# Calculate the HMAC-SHA1 hash using the secret and counter |
| 54 |
hmac_result = hmac.new(secret_enc, counter_bytes, hashlib.sha1).digest() |
| 55 |
# Get the last 4 bits of the HMAC result to determine the offset |
| 56 |
offset = hmac_result[-1] & 0x0F |
| 57 |
# Extract an 31-bit slice from the HMAC result starting at the offset + 1 bit |
| 58 |
truncated_hash = bytearray(hmac_result[offset : offset + 4]) |
| 59 |
truncated_hash[0] = truncated_hash[0] & 0x7F |
| 60 |
# Convert the truncated hash to an integer value |
| 61 |
value = struct.unpack(">I", truncated_hash)[0] |
| 62 |
# Apply modulo to get a value within the specified number of digits |
| 63 |
value %= 10**app_settings.TOTP_DIGITS |
| 64 |
return value |
| 65 |
|
| 66 |
|
| 67 |
def format_hotp_value(value: int) -> str: |
| 68 |
return f"{value:0{app_settings.TOTP_DIGITS}}" |
| 69 |
|
| 70 |
|
| 71 |
def _is_insecure_bypass(code: str) -> bool: |
| 72 |
return bool(code and app_settings.TOTP_INSECURE_BYPASS_CODE == code) |
| 73 |
|
| 74 |
|
| 75 |
def validate_totp_code(secret: str, code: str) -> bool: |
| 76 |
if _is_insecure_bypass(code): |
| 77 |
return True |
| 78 |
counters = yield_hotp_counters_from_time() |
| 79 |
for counter in counters: |
| 80 |
value = hotp_value(secret, counter) |
| 81 |
if secrets.compare_digest(code, format_hotp_value(value)): |
| 82 |
return True |
| 83 |
return False |
| 84 |
|
| 85 |
|
| 86 |
class TOTP: |
| 87 |
def __init__(self, instance: Authenticator) -> None: |
| 88 |
self.instance = instance |
| 89 |
|
| 90 |
@classmethod |
| 91 |
def activate(cls, user: AbstractBaseUser, secret: str) -> "TOTP": |
| 92 |
instance = Authenticator( |
| 93 |
user=user, # type:ignore[misc] |
| 94 |
type=Authenticator.Type.TOTP, |
| 95 |
data={"secret": encrypt(secret)}, |
| 96 |
) |
| 97 |
instance.save() |
| 98 |
return cls(instance) |
| 99 |
|
| 100 |
def validate_code(self, code: str) -> bool: |
| 101 |
if _is_insecure_bypass(code): |
| 102 |
return True |
| 103 |
if self._is_code_used(code): |
| 104 |
return False |
| 105 |
|
| 106 |
secret = decrypt(self.instance.data["secret"]) |
| 107 |
valid = validate_totp_code(secret, code) |
| 108 |
if valid: |
| 109 |
self._mark_code_used(code) |
| 110 |
return valid |
| 111 |
|
| 112 |
def _get_used_cache_key(self, code: str) -> str: |
| 113 |
return f"allauth.mfa.totp.used?user={self.instance.user_id}&code={code}" |
| 114 |
|
| 115 |
def _is_code_used(self, code: str) -> bool: |
| 116 |
return cache.get(self._get_used_cache_key(code)) == "y" |
| 117 |
|
| 118 |
def _mark_code_used(self, code: str) -> None: |
| 119 |
cache.set(self._get_used_cache_key(code), "y", timeout=app_settings.TOTP_PERIOD) |