Skip to content

Commit 7e559e6

Browse files
committed
feat: Implement TOTP secret generation and validation improvements
- Added tests to ensure TOTP secrets are generated using a cryptographically secure random number generator. - Enhanced TOTP verification to enforce single-use codes as per RFC 6238. - Updated the Remember My Browser functionality to bind cookies to all enrolled factors, not just TOTP. - Improved rate limiting to prevent concurrent attempts from overwriting each other's increments. - Secured the Django admin interface by preventing direct editing of Authenticator instances. - Updated documentation to clarify the behavior of MFA_SECRET_ENCRYPTION_KEYS and the handling of TOTP secrets. - Bumped version to 4.0.1 to reflect these changes.
1 parent 80e7e8c commit 7e559e6

21 files changed

Lines changed: 1017 additions & 97 deletions

‎django_mfa/adapters/recovery_codes.py‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from django.contrib.auth.hashers import check_password, make_password
66

7+
from django_mfa.atomic import update_data
78
from django_mfa.models import Authenticator
89
from django_mfa.registry import Adapter
910
from django_mfa.utils import strings_equal
@@ -52,17 +53,29 @@ def complete_verify(self, request, user, data):
5253
if auth is None:
5354
return False
5455
submitted = data.get("code", "")
55-
used = set(auth.data.get("used", []))
56-
plaintext = auth.data.get("migrated_plaintext", False)
5756

58-
for index, stored in enumerate(auth.data.get("codes", [])):
59-
if index in used:
60-
continue
61-
matched = (strings_equal(stored, submitted) if plaintext
62-
else check_password(submitted, stored))
63-
if matched:
64-
auth.data["used"] = sorted(used | {index})
65-
auth.save(update_fields=["data"])
66-
auth.record_usage()
67-
return True
68-
return False
57+
def spend(current):
58+
"""Match and mark one code, against the blob as committed.
59+
60+
Deliberately does the matching *inside* the compare-and-set
61+
rather than before it: the `used` set this consults has to be the
62+
one the write is conditioned on, or a code another request spent
63+
microseconds ago still reads as unspent here. Returning None
64+
declines the write, which update_data() reports as a failed
65+
verification.
66+
"""
67+
used = set(current.get("used", []))
68+
plaintext = current.get("migrated_plaintext", False)
69+
for index, stored in enumerate(current.get("codes", [])):
70+
if index in used:
71+
continue
72+
matched = (strings_equal(stored, submitted) if plaintext
73+
else check_password(submitted, stored))
74+
if matched:
75+
return {**current, "used": sorted(used | {index})}
76+
return None
77+
78+
if not update_data(auth, spend):
79+
return False
80+
auth.record_usage()
81+
return True

‎django_mfa/adapters/totp.py‎

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import base64
2-
import codecs
3-
import random
42
import re
3+
import secrets
54

65
from django_mfa import totp as totp_mod
6+
from django_mfa.atomic import update_data
77
from django_mfa.conf import settings as mfa_settings
88
from django_mfa.crypto import decrypt, encrypt
99
from django_mfa.models import Authenticator
@@ -18,10 +18,26 @@
1818
TOTP_VALID_WINDOW = 1
1919

2020

21+
#: RFC 4226 R6: "The algorithm MUST use a strong shared secret. The length of
22+
#: the shared secret MUST be at least 128 bits. This document RECOMMENDs a
23+
#: shared secret length of 160 bits." 20 bytes also base32-encodes to exactly
24+
#: 32 characters with no '=' padding, which matters: OTP.byte_secret() re-pads
25+
#: self.secret in place and provisioning_uri() embeds the secret verbatim in
26+
#: the otpauth:// query string, so a padded secret would put '=' mid-URI.
27+
SECRET_BYTES = 20
28+
29+
2130
def generate_secret():
22-
raw = codecs.decode(codecs.encode(f"{random.getrandbits(80):020x}"),
23-
"hex_codec")
24-
return base64.b32encode(raw).decode("utf-8")
31+
"""Return a fresh base32 TOTP shared secret.
32+
33+
Uses `secrets` (os.urandom) rather than the `random` module. This
34+
previously drew from random.getrandbits(80): the Mersenne Twister is not
35+
a CSPRNG -- its 19937-bit state is recoverable from 624 observed 32-bit
36+
outputs, after which every subsequently issued secret is predictable --
37+
and it is the process-global instance shared with all other application
38+
code. 80 bits was also below the RFC 4226 floor.
39+
"""
40+
return base64.b32encode(secrets.token_bytes(SECRET_BYTES)).decode("utf-8")
2541

2642

2743
class TOTPAdapter(Adapter):
@@ -51,8 +67,27 @@ def complete_verify(self, request, user, data):
5167
auth = self.get_instances(user).first()
5268
if auth is None:
5369
return False
54-
if totp_mod.TOTP(decrypt(auth.data["secret"])).verify(
55-
data.get("code", ""), valid_window=TOTP_VALID_WINDOW):
56-
auth.record_usage()
57-
return True
58-
return False
70+
counter = totp_mod.TOTP(decrypt(auth.data["secret"])).match(
71+
data.get("code", ""), valid_window=TOTP_VALID_WINDOW)
72+
if counter is None:
73+
return False
74+
# RFC 6238 section 5.2: an OTP must not be accepted twice. Rejecting
75+
# any counter at or below the last accepted one closes both the
76+
# straight replay of the same code and the replay of an *earlier*
77+
# still-in-window code after a later one has been used -- with
78+
# TOTP_VALID_WINDOW = 1 a code would otherwise stay replayable for
79+
# about 90 seconds, which is ample for a shoulder-surfed or
80+
# phished-then-forwarded code.
81+
#
82+
# The compare-and-set is what makes this hold under concurrency: two
83+
# simultaneous POSTs of the same code both match here, and without it
84+
# both would go on to succeed.
85+
def spend(data):
86+
if counter <= data.get("last_verified_counter", -1):
87+
return None
88+
return {**data, "last_verified_counter": counter}
89+
90+
if not update_data(auth, spend):
91+
return False
92+
auth.record_usage()
93+
return True

‎django_mfa/adapters/webauthn.py‎

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
PublicKeyCredentialUserEntity,
2020
)
2121

22+
from django_mfa.atomic import update_data
2223
from django_mfa.conf import settings as mfa_settings
2324
from django_mfa.handles import user_handle_for
2425
from django_mfa.models import Authenticator
@@ -251,30 +252,48 @@ def complete_verify(self, request, user, data):
251252
# still propagate unchanged, since that is a distinct,
252253
# deliberate "reject this" signal, not a missing-row race.
253254
return False
254-
stored = auth.data.get("sign_count", 0)
255255
# The return value of authenticate_complete() carries no counter at
256256
# all in fido2 2.2.1, so the new counter has to be recovered
257257
# independently by re-parsing the same response the client sent.
258258
# Confirmed empirically (task-14-report.md) that this equals the
259259
# authenticator's own idea of its counter.
260260
new_count = AuthenticationResponse.from_dict(
261261
credential).response.authenticator_data.counter
262-
# Clone detection: a signature counter that fails to advance
263-
# suggests the authenticator (or its key material) has been cloned
264-
# and a second device is replaying/racing assertions. But counters
265-
# are OPTIONAL in the WebAuthn spec -- many authenticators
266-
# (notably Apple/iCloud passkeys) never implement one and always
267-
# report 0. Treat "both stored and new are 0" as the legitimate
268-
# counter-less case and accept it unconditionally; for every other
269-
# case, the new counter must be strictly greater than the stored
270-
# one or this assertion is rejected as a possible clone. Do NOT
271-
# simplify this to a plain "new > stored" check -- that would lock
272-
# out every user of a counter-less authenticator, which today is a
273-
# very large share of them.
274-
if not (new_count == 0 and stored == 0) and new_count <= stored:
275-
raise ValueError("Authenticator sign count did not increase.")
276262

277-
auth.data["sign_count"] = new_count
278-
auth.save(update_fields=["data"])
263+
def advance(current):
264+
"""Clone-check against the committed counter, then advance it.
265+
266+
Runs inside the compare-and-set rather than before it, and for
267+
the same reason clone detection exists at all: two racing
268+
assertions from a cloned credential would otherwise both read the
269+
pre-advance counter, both clear the check below, and the loser's
270+
write would drag the stored counter *backwards* -- leaving the
271+
clone undetected and every subsequent replay looking fresh.
272+
"""
273+
stored = current.get("sign_count", 0)
274+
# Clone detection: a signature counter that fails to advance
275+
# suggests the authenticator (or its key material) has been
276+
# cloned and a second device is replaying/racing assertions. But
277+
# counters are OPTIONAL in the WebAuthn spec -- many
278+
# authenticators (notably Apple/iCloud passkeys) never implement
279+
# one and always report 0. Treat "both stored and new are 0" as
280+
# the legitimate counter-less case and accept it
281+
# unconditionally; for every other case, the new counter must be
282+
# strictly greater than the stored one or this assertion is
283+
# rejected as a possible clone. Do NOT simplify this to a plain
284+
# "new > stored" check -- that would lock out every user of a
285+
# counter-less authenticator, which today is a very large share
286+
# of them.
287+
#
288+
# Raising (rather than returning None to decline) is deliberate:
289+
# it propagates straight out of update_data() without retrying,
290+
# keeping "this is a clone" a distinct, loud signal from "this
291+
# assertion simply could not be honoured".
292+
if not (new_count == 0 and stored == 0) and new_count <= stored:
293+
raise ValueError("Authenticator sign count did not increase.")
294+
return {**current, "sign_count": new_count}
295+
296+
if not update_data(auth, advance):
297+
return False
279298
auth.record_usage()
280299
return True

‎django_mfa/admin.py‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,56 @@
11
from django.contrib import admin
2+
from django.contrib.auth import get_user_model
23

34
from .models import Authenticator
45

5-
admin.site.register(Authenticator)
6+
7+
@admin.register(Authenticator)
8+
class AuthenticatorAdmin(admin.ModelAdmin):
9+
"""Inspect-and-revoke only. Never exposes ``Authenticator.data``.
10+
11+
That blob holds the TOTP shared secret, the recovery-code hashes and the
12+
WebAuthn credential. Under the default ModelAdmin it was rendered as an
13+
editable form field, which made the admin a privilege-escalation surface:
14+
any staff account with ``view_authenticator`` could read another user's
15+
TOTP secret -- including a superuser's -- and generate valid codes for
16+
them, and one with ``change_authenticator`` could overwrite it with a
17+
secret of its own choosing. ``MFA_SECRET_ENCRYPTION_KEYS`` is not a
18+
mitigation: django_mfa.crypto *signs*, it does not encrypt, and the
19+
payload is plain base64 that recovers without any key (see
20+
docs/security.md).
21+
22+
``data`` is therefore absent from ``fields``, ``list_display`` and
23+
``get_search_fields()`` alike -- a searchable ``data`` would leak the
24+
secret a character at a time even while never rendering it -- and adding
25+
and editing are switched off outright, since nothing in this model is
26+
meaningfully hand-editable and every write to it is a way to weaken
27+
somebody's second factor.
28+
29+
Deleting is deliberately still allowed. Revoking a lost or stolen
30+
authenticator on behalf of a locked-out user is the one legitimate
31+
support operation here, and removing it would push operators towards
32+
editing the database by hand.
33+
"""
34+
35+
list_display = ("user", "type", "name", "created_at", "last_used_at")
36+
list_filter = ("type", "created_at", "last_used_at")
37+
date_hierarchy = "created_at"
38+
ordering = ("user", "type", "created_at")
39+
40+
#: Everything except `data`. Also the complete readonly set -- with
41+
#: has_change_permission() off these render as an inspectable, read-only
42+
#: detail page rather than a form.
43+
fields = ("user", "type", "name", "created_at", "last_used_at")
44+
readonly_fields = fields
45+
46+
def get_search_fields(self, request):
47+
# Derived from USERNAME_FIELD rather than hardcoding "username":
48+
# AUTH_USER_MODEL is swappable and a host project's user model need
49+
# not have that field at all.
50+
return ("name", f"user__{get_user_model().USERNAME_FIELD}")
51+
52+
def has_add_permission(self, request):
53+
return False
54+
55+
def has_change_permission(self, request, obj=None):
56+
return False

‎django_mfa/atomic.py‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# django_mfa/atomic.py
2+
#
3+
# Race-free updates to an Authenticator's `data` JSON blob.
4+
#
5+
# Every factor that consumes something one-time-only keeps that state inside
6+
# `Authenticator.data`: the TOTP counter that was last accepted, the recovery
7+
# codes already spent, the WebAuthn signature counter. All three were written
8+
# as a plain read-modify-write --
9+
#
10+
# row = ...get()
11+
# row.data["used"].append(i)
12+
# row.save(update_fields=["data"])
13+
#
14+
# -- which is a lost update under concurrency. Two simultaneous POSTs both
15+
# read the pre-update blob, both decide the credential is unspent, and the
16+
# second save() overwrites the first. That is not a theoretical concern for
17+
# this package specifically: it defeats the single-use guarantee that is the
18+
# entire security property of a recovery code (docs/security.md) and of
19+
# WebAuthn clone detection, and it lets one TOTP code be redeemed twice.
20+
#
21+
# `select_for_update()` is the usual Django answer and is deliberately NOT
22+
# used here: Django's SQLite backend sets has_select_for_update = False, so it
23+
# is silently a no-op there, and a lock that quietly does nothing on one of
24+
# the supported backends is worse than no lock at all.
25+
#
26+
# Instead this is an optimistic compare-and-set: read the blob, compute the
27+
# new one, then UPDATE ... WHERE data = <the blob we read>. That WHERE clause
28+
# is a plain JSONField exact match, which every backend Django supports can
29+
# evaluate (jsonb equality on PostgreSQL, text equality elsewhere), so it
30+
# behaves identically everywhere including SQLite. A caller that loses the
31+
# race matches zero rows, re-reads, and re-applies on top of the winner.
32+
import copy
33+
34+
#: Attempts before giving up. Each retry only happens when another writer
35+
#: committed to the same row in the microseconds between this one's SELECT and
36+
#: its UPDATE, so anything beyond a couple is already pathological; the bound
37+
#: exists so a permanently-contended row can never spin forever inside a
38+
#: request. Exhausting it returns False, which every caller treats as "this
39+
#: verification did not succeed" -- fail closed.
40+
MAX_ATTEMPTS = 5
41+
42+
43+
def update_data(authenticator, apply):
44+
"""Atomically transform ``authenticator.data``.
45+
46+
``apply`` is called with the blob as currently committed (never the
47+
caller's possibly-stale in-memory copy) and returns either the new blob
48+
or ``None`` to decline. Declining is how a caller says "having now seen
49+
the real current state, this attempt is not valid after all" -- e.g. a
50+
recovery code that a concurrent request consumed first.
51+
52+
Returns True only if a write actually landed, in which case
53+
``authenticator.data`` is updated in place to match. Returns False if
54+
``apply`` declined, if the row has been deleted, or if this caller lost
55+
the race ``MAX_ATTEMPTS`` times.
56+
"""
57+
model = type(authenticator)
58+
for _ in range(MAX_ATTEMPTS):
59+
current = model.objects.filter(pk=authenticator.pk).values_list(
60+
"data", flat=True).first()
61+
if current is None:
62+
# The row was deleted -- e.g. the user removed this authenticator
63+
# from another tab while this verification was in flight. There is
64+
# nothing left to consume.
65+
return False
66+
67+
# deepcopy so a caller that mutates the dict it is handed (rather than
68+
# building a new one) cannot corrupt the value used in the WHERE
69+
# clause, which must stay exactly what was read.
70+
new_data = apply(copy.deepcopy(current))
71+
if new_data is None:
72+
return False
73+
74+
updated = model.objects.filter(
75+
pk=authenticator.pk, data=current).update(data=new_data)
76+
if updated:
77+
authenticator.data = new_data
78+
return True
79+
return False

‎django_mfa/ratelimit.py‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,48 @@ def check(user, factor_type):
4040

4141

4242
def record_failure(user, factor_type):
43+
"""Count one failed attempt against ``user``'s budget for ``factor_type``.
44+
45+
add()-then-incr(), not get()-then-set(). The latter is a read-modify-write
46+
and loses increments whenever two attempts interleave -- which is not a
47+
rare edge case here but the exact shape of the attack this function
48+
exists to stop: an attacker sending guesses in parallel rather than in
49+
series had most of their failures silently discarded, so a "5 per 5
50+
minutes" limit stopped binding at their chosen concurrency.
51+
52+
add() seeds the counter (and its expiry) exactly once, being a no-op when
53+
the key already exists; incr() is then a single operation, evaluated
54+
server-side and atomically by every shared cache backend Django ships for
55+
production use (redis, memcached), and under its own lock in LocMemCache.
56+
57+
Note this makes the window fixed from the first failure rather than
58+
sliding forward on each one, since only add() carries a timeout. That is
59+
the ordinary reading of "5/5m" and is the stricter-to-reason-about of the
60+
two; the previous behaviour extended the lockout on every attempt.
61+
"""
4362
_limit, window = parse(mfa_settings.MFA_VERIFY_RATE_LIMIT)
4463
key = _key(user, factor_type)
45-
cache.set(key, cache.get(key, 0) + 1, window)
64+
try:
65+
cache.incr(key)
66+
return
67+
except ValueError:
68+
pass # No counter yet (or it just expired) -- seed one below.
69+
70+
# add(), never set(), for the seed: add() is a no-op when the key already
71+
# exists, so a request that raced another one to seed the counter cannot
72+
# reset it to a lower value. Seeding straight to 1 (rather than 0 and then
73+
# incrementing) keeps this to a single write, so there is no window in
74+
# which the counter sits at 0 and a concurrent increment can be lost.
75+
if cache.add(key, 1, window):
76+
return
77+
try:
78+
# Lost the race to seed: the winner's counter is live, count on top.
79+
cache.incr(key)
80+
except ValueError:
81+
# It expired again in the meantime. Vanishingly unlikely, and the
82+
# throttle already fails open on an evicted counter by design (see
83+
# check()), so a single lost failure here is consistent with that.
84+
cache.set(key, 1, window)
4685

4786

4887
def clear(user, factor_type):

0 commit comments

Comments
 (0)