| 1 |
from logging import getLogger |
| 2 |
from typing import Optional |
| 3 |
|
| 4 |
from django.db import transaction |
| 5 |
from django.db.models import F, Sum, Value, Q |
| 6 |
from django.db.models.functions import Concat |
| 7 |
from django.utils import timezone |
| 8 |
|
| 9 |
from axes.attempts import ( |
| 10 |
clean_expired_user_attempts, |
| 11 |
get_user_attempts, |
| 12 |
reset_user_attempts, |
| 13 |
) |
| 14 |
from axes.conf import settings |
| 15 |
from axes.handlers.base import AxesBaseHandler, AbstractAxesHandler |
| 16 |
from axes.helpers import ( |
| 17 |
get_client_str, |
| 18 |
get_client_username, |
| 19 |
get_credentials, |
| 20 |
get_failure_limit, |
| 21 |
get_query_str, |
| 22 |
) |
| 23 |
from axes.models import AccessLog, AccessAttempt, AccessFailureLog |
| 24 |
from axes.signals import user_locked_out |
| 25 |
|
| 26 |
log = getLogger(__name__) |
| 27 |
|
| 28 |
|
| 29 |
class AxesDatabaseHandler(AbstractAxesHandler, AxesBaseHandler): |
| 30 |
""" |
| 31 |
Signal handler implementation that records user login attempts to database and locks users out if necessary. |
| 32 |
|
| 33 |
.. note:: The get_user_attempts function is called several time during the authentication and lockout |
| 34 |
process, caching its output can be dangerous. |
| 35 |
""" |
| 36 |
|
| 37 |
def reset_attempts( |
| 38 |
self, |
| 39 |
*, |
| 40 |
ip_address: Optional[str] = None, |
| 41 |
username: Optional[str] = None, |
| 42 |
ip_or_username: bool = False, |
| 43 |
) -> int: |
| 44 |
attempts = AccessAttempt.objects.all() |
| 45 |
|
| 46 |
if ip_or_username: |
| 47 |
attempts = attempts.filter(Q(ip_address=ip_address) | Q(username=username)) |
| 48 |
else: |
| 49 |
if ip_address: |
| 50 |
attempts = attempts.filter(ip_address=ip_address) |
| 51 |
if username: |
| 52 |
attempts = attempts.filter(username=username) |
| 53 |
|
| 54 |
count, _ = attempts.delete() |
| 55 |
log.info("AXES: Reset %d access attempts from database.", count) |
| 56 |
|
| 57 |
return count |
| 58 |
|
| 59 |
def reset_logs(self, *, age_days: Optional[int] = None) -> int: |
| 60 |
if age_days is None: |
| 61 |
count, _ = AccessLog.objects.all().delete() |
| 62 |
log.info("AXES: Reset all %d access logs from database.", count) |
| 63 |
else: |
| 64 |
limit = timezone.now() - timezone.timedelta(days=age_days) |
| 65 |
count, _ = AccessLog.objects.filter(attempt_time__lte=limit).delete() |
| 66 |
log.info( |
| 67 |
"AXES: Reset %d access logs older than %d days from database.", |
| 68 |
count, |
| 69 |
age_days, |
| 70 |
) |
| 71 |
|
| 72 |
return count |
| 73 |
|
| 74 |
def reset_failure_logs(self, *, age_days: Optional[int] = None) -> int: |
| 75 |
if age_days is None: |
| 76 |
count, _ = AccessFailureLog.objects.all().delete() |
| 77 |
log.info("AXES: Reset all %d access failure logs from database.", count) |
| 78 |
else: |
| 79 |
limit = timezone.now() - timezone.timedelta(days=age_days) |
| 80 |
count, _ = AccessFailureLog.objects.filter(attempt_time__lte=limit).delete() |
| 81 |
log.info( |
| 82 |
"AXES: Reset %d access failure logs older than %d days from database.", |
| 83 |
count, |
| 84 |
age_days, |
| 85 |
) |
| 86 |
|
| 87 |
return count |
| 88 |
|
| 89 |
def remove_out_of_limit_failure_logs( |
| 90 |
self, |
| 91 |
*, |
| 92 |
username: str, |
| 93 |
limit: Optional[int] = settings.AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT, |
| 94 |
) -> int: |
| 95 |
count = 0 |
| 96 |
failures = AccessFailureLog.objects.filter(username=username) |
| 97 |
out_of_limit_failures_logs = failures.count() - limit |
| 98 |
if out_of_limit_failures_logs > 0: |
| 99 |
for failure in failures[:out_of_limit_failures_logs]: |
| 100 |
failure.delete() |
| 101 |
count += 1 |
| 102 |
return count |
| 103 |
|
| 104 |
def get_failures(self, request, credentials: Optional[dict] = None) -> int: |
| 105 |
attempts_list = get_user_attempts(request, credentials) |
| 106 |
attempt_count = max( |
| 107 |
( |
| 108 |
attempts.aggregate(Sum("failures_since_start"))[ |
| 109 |
"failures_since_start__sum" |
| 110 |
] |
| 111 |
or 0 |
| 112 |
) |
| 113 |
for attempts in attempts_list |
| 114 |
) |
| 115 |
return attempt_count |
| 116 |
|
| 117 |
def user_login_failed(self, sender, credentials: dict, request=None, **kwargs): |
| 118 |
"""When user login fails, save AccessFailureLog record in database, |
| 119 |
save AccessAttempt record in database, mark request with |
| 120 |
lockout attribute and emit lockout signal. |
| 121 |
|
| 122 |
""" |
| 123 |
|
| 124 |
log.info("AXES: User login failed, running database handler for failure.") |
| 125 |
|
| 126 |
if request is None: |
| 127 |
log.error( |
| 128 |
"AXES: AxesDatabaseHandler.user_login_failed does not function without a request." |
| 129 |
) |
| 130 |
return |
| 131 |
|
| 132 |
# 1. database query: Clean up expired user attempts from the database before logging new attempts |
| 133 |
clean_expired_user_attempts(request.axes_attempt_time) |
| 134 |
|
| 135 |
username = get_client_username(request, credentials) |
| 136 |
client_str = get_client_str( |
| 137 |
username, |
| 138 |
request.axes_ip_address, |
| 139 |
request.axes_user_agent, |
| 140 |
request.axes_path_info, |
| 141 |
request, |
| 142 |
) |
| 143 |
|
| 144 |
# If axes denied access, don't record the failed attempt as that would reset the lockout time. |
| 145 |
if ( |
| 146 |
not settings.AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT |
| 147 |
and request.axes_locked_out |
| 148 |
): |
| 149 |
request.axes_credentials = credentials |
| 150 |
user_locked_out.send( |
| 151 |
"axes", |
| 152 |
request=request, |
| 153 |
username=username, |
| 154 |
ip_address=request.axes_ip_address, |
| 155 |
) |
| 156 |
return |
| 157 |
|
| 158 |
# This replaces null byte chars that crash saving failures. |
| 159 |
get_data = get_query_str(request.GET).replace("\0", "0x00") |
| 160 |
post_data = get_query_str(request.POST).replace("\0", "0x00") |
| 161 |
|
| 162 |
if self.is_whitelisted(request, credentials): |
| 163 |
log.info("AXES: Login failed from whitelisted client %s.", client_str) |
| 164 |
return |
| 165 |
|
| 166 |
# 2. database query: Get or create access record with the new failure data |
| 167 |
if settings.AXES_ONLY_USER_FAILURES and username is None: |
| 168 |
log.warning( |
| 169 |
"AXES: Username is None and AXES_ONLY_USER_FAILURES is enabled, new record will NOT be created." |
| 170 |
) |
| 171 |
else: |
| 172 |
with transaction.atomic(): |
| 173 |
( |
| 174 |
attempt, |
| 175 |
created, |
| 176 |
) = AccessAttempt.objects.select_for_update().get_or_create( |
| 177 |
username=username, |
| 178 |
ip_address=request.axes_ip_address, |
| 179 |
user_agent=request.axes_user_agent, |
| 180 |
defaults={ |
| 181 |
"get_data": get_data, |
| 182 |
"post_data": post_data, |
| 183 |
"http_accept": request.axes_http_accept, |
| 184 |
"path_info": request.axes_path_info, |
| 185 |
"failures_since_start": 1, |
| 186 |
"attempt_time": request.axes_attempt_time, |
| 187 |
}, |
| 188 |
) |
| 189 |
|
| 190 |
# Record failed attempt with all the relevant information. |
| 191 |
# Filtering based on username, IP address and user agent handled elsewhere, |
| 192 |
# and this handler just records the available information for further use. |
| 193 |
if created: |
| 194 |
log.warning( |
| 195 |
"AXES: New login failure by %s. Created new record in the database.", |
| 196 |
client_str, |
| 197 |
) |
| 198 |
|
| 199 |
# 3. database query if there were previous attempts in the database |
| 200 |
# Update failed attempt information but do not touch the username, IP address, or user agent fields, |
| 201 |
# because attackers can request the site with multiple different configurations |
| 202 |
# in order to bypass the defense mechanisms that are used by the site. |
| 203 |
else: |
| 204 |
separator = "\n---------\n" |
| 205 |
|
| 206 |
attempt.get_data = Concat("get_data", Value(separator + get_data)) |
| 207 |
attempt.post_data = Concat( |
| 208 |
"post_data", Value(separator + post_data) |
| 209 |
) |
| 210 |
attempt.http_accept = request.axes_http_accept |
| 211 |
attempt.path_info = request.axes_path_info |
| 212 |
attempt.failures_since_start = F("failures_since_start") + 1 |
| 213 |
attempt.attempt_time = request.axes_attempt_time |
| 214 |
attempt.save() |
| 215 |
|
| 216 |
log.warning( |
| 217 |
"AXES: Repeated login failure by %s. Updated existing record in the database.", |
| 218 |
client_str, |
| 219 |
) |
| 220 |
|
| 221 |
# 3. or 4. database query: Calculate the current maximum failure number from the existing attempts |
| 222 |
failures_since_start = self.get_failures(request, credentials) |
| 223 |
request.axes_failures_since_start = failures_since_start |
| 224 |
|
| 225 |
if ( |
| 226 |
settings.AXES_LOCK_OUT_AT_FAILURE |
| 227 |
and failures_since_start >= get_failure_limit(request, credentials) |
| 228 |
): |
| 229 |
log.warning( |
| 230 |
"AXES: Locking out %s after repeated login failures.", client_str |
| 231 |
) |
| 232 |
|
| 233 |
request.axes_locked_out = True |
| 234 |
request.axes_credentials = credentials |
| 235 |
user_locked_out.send( |
| 236 |
"axes", |
| 237 |
request=request, |
| 238 |
username=username, |
| 239 |
ip_address=request.axes_ip_address, |
| 240 |
) |
| 241 |
|
| 242 |
# 5. database entry: Log for ever the attempt in the AccessFailureLog |
| 243 |
if settings.AXES_ENABLE_ACCESS_FAILURE_LOG: |
| 244 |
with transaction.atomic(): |
| 245 |
AccessFailureLog.objects.create( |
| 246 |
username=username, |
| 247 |
ip_address=request.axes_ip_address, |
| 248 |
user_agent=request.axes_user_agent, |
| 249 |
http_accept=request.axes_http_accept, |
| 250 |
path_info=request.axes_path_info, |
| 251 |
attempt_time=request.axes_attempt_time, |
| 252 |
locked_out=request.axes_locked_out, |
| 253 |
) |
| 254 |
self.remove_out_of_limit_failure_logs(username=username) |
| 255 |
|
| 256 |
def user_logged_in(self, sender, request, user, **kwargs): |
| 257 |
""" |
| 258 |
When user logs in, update the AccessLog related to the user. |
| 259 |
""" |
| 260 |
|
| 261 |
# 1. database query: Clean up expired user attempts from the database |
| 262 |
clean_expired_user_attempts(request.axes_attempt_time) |
| 263 |
|
| 264 |
username = user.get_username() |
| 265 |
credentials = get_credentials(username) |
| 266 |
client_str = get_client_str( |
| 267 |
username, |
| 268 |
request.axes_ip_address, |
| 269 |
request.axes_user_agent, |
| 270 |
request.axes_path_info, |
| 271 |
request, |
| 272 |
) |
| 273 |
|
| 274 |
log.info("AXES: Successful login by %s.", client_str) |
| 275 |
|
| 276 |
if not settings.AXES_DISABLE_ACCESS_LOG: |
| 277 |
# 2. database query: Insert new access logs with login time |
| 278 |
AccessLog.objects.create( |
| 279 |
username=username, |
| 280 |
ip_address=request.axes_ip_address, |
| 281 |
user_agent=request.axes_user_agent, |
| 282 |
http_accept=request.axes_http_accept, |
| 283 |
path_info=request.axes_path_info, |
| 284 |
attempt_time=request.axes_attempt_time, |
| 285 |
) |
| 286 |
|
| 287 |
if settings.AXES_RESET_ON_SUCCESS: |
| 288 |
# 3. database query: Reset failed attempts for the logging in user |
| 289 |
count = reset_user_attempts(request, credentials) |
| 290 |
log.info( |
| 291 |
"AXES: Deleted %d failed login attempts by %s from database.", |
| 292 |
count, |
| 293 |
client_str, |
| 294 |
) |
| 295 |
|
| 296 |
def user_logged_out(self, sender, request, user, **kwargs): |
| 297 |
""" |
| 298 |
When user logs out, update the AccessLog related to the user. |
| 299 |
""" |
| 300 |
|
| 301 |
# 1. database query: Clean up expired user attempts from the database |
| 302 |
clean_expired_user_attempts(request.axes_attempt_time) |
| 303 |
|
| 304 |
username = user.get_username() if user else None |
| 305 |
client_str = get_client_str( |
| 306 |
username, |
| 307 |
request.axes_ip_address, |
| 308 |
request.axes_user_agent, |
| 309 |
request.axes_path_info, |
| 310 |
request, |
| 311 |
) |
| 312 |
|
| 313 |
log.info("AXES: Successful logout by %s.", client_str) |
| 314 |
|
| 315 |
if username and not settings.AXES_DISABLE_ACCESS_LOG: |
| 316 |
# 2. database query: Update existing attempt logs with logout time |
| 317 |
AccessLog.objects.filter( |
| 318 |
username=username, logout_time__isnull=True |
| 319 |
).update(logout_time=request.axes_attempt_time) |
| 320 |
|
| 321 |
def post_save_access_attempt(self, instance, **kwargs): |
| 322 |
""" |
| 323 |
Handles the ``axes.models.AccessAttempt`` object post save signal. |
| 324 |
|
| 325 |
When needed, all post_save actions for this backend should be located |
| 326 |
here. |
| 327 |
""" |
| 328 |
|
| 329 |
def post_delete_access_attempt(self, instance, **kwargs): |
| 330 |
""" |
| 331 |
Handles the ``axes.models.AccessAttempt`` object post delete signal. |
| 332 |
|
| 333 |
When needed, all post_delete actions for this backend should be located |
| 334 |
here. |
| 335 |
""" |