summaryrefslogtreecommitdiff
path: root/django/contrib/auth/backends.py
diff options
context:
space:
mode:
authorafenoum <anja1catus@gmail.com>2026-04-20 12:44:42 +0200
committerSarah Boyce <42296566+sarahboyce@users.noreply.github.com>2026-04-27 16:22:04 +0200
commitc63591d4da533944af31ccb46a77eb221dbdba0a (patch)
treeab4d05769d45452c21670062bfe410d1e7823538 /django/contrib/auth/backends.py
parent017d7f6f12e597e6179de7ffdf330a52c2b22053 (diff)
Fixed #36901 -- Centralized auth timing attack mitigations.
Thank you Mar Bartolome and Tim Schilling for reviews.
Diffstat (limited to 'django/contrib/auth/backends.py')
-rw-r--r--django/contrib/auth/backends.py32
1 files changed, 17 insertions, 15 deletions
diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py
index 0793a238d7..514c670602 100644
--- a/django/contrib/auth/backends.py
+++ b/django/contrib/auth/backends.py
@@ -1,6 +1,10 @@
from asgiref.sync import sync_to_async
-from django.contrib.auth import get_user_model
+from django.contrib.auth import (
+ acheck_password_with_timing_attack_mitigation,
+ check_password_with_timing_attack_mitigation,
+ get_user_model,
+)
from django.contrib.auth.models import Permission
from django.db.models import Exists, OuterRef, Q
from django.views.decorators.debug import sensitive_variables
@@ -66,12 +70,12 @@ class ModelBackend(BaseBackend):
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
- # Run the default password hasher once to reduce the timing
- # difference between an existing and a nonexistent user (#20760).
- UserModel().set_password(password)
- else:
- if user.check_password(password) and self.user_can_authenticate(user):
- return user
+ user = None
+
+ if check_password_with_timing_attack_mitigation(
+ user, password
+ ) and self.user_can_authenticate(user):
+ return user
@sensitive_variables("password")
async def aauthenticate(self, request, username=None, password=None, **kwargs):
@@ -82,14 +86,12 @@ class ModelBackend(BaseBackend):
try:
user = await UserModel._default_manager.aget_by_natural_key(username)
except UserModel.DoesNotExist:
- # Run the default password hasher once to reduce the timing
- # difference between an existing and a nonexistent user (#20760).
- UserModel().set_password(password)
- else:
- if await user.acheck_password(password) and self.user_can_authenticate(
- user
- ):
- return user
+ user = None
+
+ if await acheck_password_with_timing_attack_mitigation(
+ user, password
+ ) and self.user_can_authenticate(user):
+ return user
def user_can_authenticate(self, user):
"""