Brute Force and Credential Stuffing: Why Django Never Says 'Too Many Attempts' — and How to Make It

Brute Force and Credential Stuffing: Why Django Never Says 'Too Many Attempts' — and How to Make It

Django Security Series — Post 11 | Series III: Authentication & Session
OWASP A07:2025 — Authentication Failures | Reading time: ~20 min

🧪 Run it yourself. This attack ships as a runnable lab in django-security-lab: two login endpoints and a victim whose deliberately weak password guards a flag. The vulnerable view rate-limits on the client-controlled X-Forwarded-For header, so rotating one forged value from a single machine walks the whole wordlist unthrottled and the flag falls; the secure view counts failures per account and locks out regardless of source. Reproduce both from the command line with curl.

Series II was about users who were already inside. IDOR read objects they didn't own, privilege escalation climbed to staff, CSRF borrowed a browser that was already logged in, and mass assignment wrote columns the form never rendered. Every one of those attacks assumed a valid session existed. Series III steps back to the moment before that: proving who you are at all.

And it opens with the least sophisticated attack in the entire series. There is no payload here. No injected syntax, no traversal sequence, no crafted JSON body. The attacker submits a username and a password, exactly the way the form intends, and then does it again. The only thing that makes it an attack is the number.

What I did not expect, when I started reading for this post, was how explicit Django is about not helping. I had assumed there was some modest built-in protection, a small delay, a soft counter, something. There isn't, and the docs do not hedge about it: "Django does not throttle requests to authenticate users. To protect against brute-force attacks against the authentication system, you may consider deploying a Django plugin or web server module to throttle these requests." That is the whole position. The framework that escapes your templates by default, parameterises your queries by default, and rotates your session key on login will answer an unlimited number of password guesses without complaint.

Worse than a missing control is one that looks like protection. A rate limiter keyed on a value the client controls will pass a naive test — five tries from one address, the sixth blocked — and still be switched off from a single laptop by adding one HTTP header to each request. That is the shape of bug that survives review, because a reviewer looking for a flaw finds a limiter and moves on. Running a real petition site taught me to distrust exactly this kind of "protection"; the companion lab reproduces it end to end, and most of this post is about why the key it chose is the wrong one.


The Attack: What It Is and How It Works

Brute force is guessing. Against a login endpoint it means trying passwords against an account until one works, and its economics are set entirely by two numbers: how many guesses per second you can make, and how large the space of plausible passwords is. That second number is far smaller than people think, which is why the attack survives at all. Nobody enumerates all 95^12 possible passwords. They try 123456, then senha123, then the company name with a 1! on the end, and against a large enough user base one of them lands.

The reason the login endpoint is such a good target is that it is designed to accept anonymous input and answer honestly. Every other attack in this series had to smuggle something past a check. This one uses the front door exactly as built.

The tooling is unglamorous and widely available. Hydra, Patator, Burp Intruder, or forty lines of Python and requests will all do it, and the modern credential-stuffing kits (Sentry MBA and its descendants) are built around config files that describe a target's login form, its success and failure signatures, and its proxy rotation. That last item is the important one, and it is what defeats most naive defences: the attacker distributes their traffic across a residential proxy pool or botnet so that no single IP address is ever interesting.

The lab's attack needs no pool at all. Its vulnerable login does have a limiter — five failures from one client address, then 429 — but it reads that address from the first entry of X-Forwarded-For, a header the client writes. So the attacker sends each guess with a different made-up value in it, 10.0.0.1, then 10.0.0.2, and so on: every guess lands in a fresh bucket, the limit never trips, and the wordlist runs until the victim's weak password logs in. One machine, one header, and a defence that passed review is switched off.

Brute force has relatives that need other controls. Credential stuffing inverts the arithmetic: instead of many passwords against one account, the attacker replays username/password pairs leaked from someone else's breach, testing the hypothesis that people reuse passwords, one attempt per account from many addresses. A per-account counter never fills under that shape, and a pair that works logs straight in, which is why it is answered with a bot check and multi-factor authentication rather than a lockout. Password spraying tries one very common password against every account, to stay under per-account limits on purpose. And before any guessing, account enumeration finds which usernames exist, from a login, registration or reset message that answers "no such user" differently from "wrong password", or from response timing; Django's ModelBackend closes the timing half by hashing the submitted password even for a username that does not exist.


Real-World Incidents

Dunkin' Brands — New York Attorney General consent order (attacks from 2015; settled September 15, 2020)

I picked this one over the flashier breaches because it is the rare case where a regulator wrote down, in an enforceable document, what a company was supposed to have done about credential stuffing. Beginning in early 2015, attackers ran credential-stuffing attacks against DD Perks, Dunkin's rewards programme, whose accounts held stored value that can be spent or transferred. This is worth pausing on: the attackers were not after Dunkin's systems. They were after money that customers had already loaded onto cards, which made every compromised account directly monetisable, and which is why a doughnut loyalty scheme was worth industrialising an attack against at all.

MITRE ATT&CK maps this family as T1110 — Brute Force, and the Dunkin' case is squarely its T1110.004 — Credential Stuffing sub-technique: the attackers were not guessing passwords but replaying pairs leaked from other breaches. The inverse trick, T1110.003 — Password Spraying, tries one very common password against every account precisely to stay under per-account limits. Whichever variant lands, the follow-on is T1078 — Valid Accounts — from the first success the attacker is no longer attacking anything; they are simply logged in, and every control in Series II is what stands between them and the data.

Dunkin's third-party app developer repeatedly alerted the company to the ongoing attempts and handed over a list of nearly 20,000 accounts compromised in a single five-day sample period. According to the Attorney General, Dunkin' then failed to investigate, failed to notify the affected customers, failed to reset their passwords, and failed to implement safeguards against further attacks; the AG's own investigation later identified thousands of additional accounts compromised between 2015 and 2018. The resulting consent order, announced September 15, 2020, required $650,000 in penalties and costs, plus customer notification, password resets, refunds for fraudulent card use, and a commitment to maintain safeguards against credential stuffing and to follow incident-response procedures going forward. The claims were brought under New York's data-breach notification statute (GBL § 899-aa) and its consumer-protection provisions (Executive Law § 63(12), GBL §§ 349–350), the latter because Dunkin' had told customers it took reasonable measures to protect their information while, the AG alleged, it was doing none of these things.

Dunkin' was not penalised for being attacked, and credential stuffing is not a vulnerability in any code Dunkin' wrote. It was penalised for knowing and not acting. So when your logs record user_login_failed ten thousand times against one account overnight and nobody looks, you have not merely missed an attack. You have created a documented, dated record that the warning was in your hands.

Source: NY Attorney General — Attorney General James Gets Dunkin' to Fill Holes in Security, Reimburse Hacked Customers (2020)


Django's Default Protections

There is no throttle. There is no lockout. There is no counter. LoginView will process your ten millionth failed POST with the same equanimity as your first, and authenticate() has no memory of the previous attempt.

What Django does give you is a password storage layer that makes each guess expensive to verify and a set of primitives that make the missing controls easy to bolt on. The default hasher is PBKDF2 with a deliberately high iteration count, which is a real if indirect brute-force defence: it sets a floor on how long your server takes to check a candidate password, which caps the attacker's online guess rate as a side effect of CPU cost, and it is what makes an offline attack against a stolen hash dump expensive rather than trivial. (Hashing gets its own treatment later in the series; here it matters only as the thing that makes each guess cost something.)

What Django does NOT protect automatically:

  • Any limit whatsoever on the number of authentication attempts, per IP, per account, or globally.
  • Account lockout after repeated failures.
  • Bot or automation detection on the login form.
  • DRF's token endpoints, which are login endpoints wearing different clothes: ObtainAuthToken sets throttle_classes = () itself, so even a project-wide DEFAULT_THROTTLE_CLASSES never reaches it, and simplejwt's views inherit the defaults, which are empty unless you set them.

The Vulnerable Pattern and the Fix

Pattern 1 — The Bare Login View

This is not a mistake so much as an omission, and it is what you get by following the tutorial and stopping: path('login/', LoginView.as_view(), name='login'). Nothing in it is wrong. There is no bad code to point at, which is precisely why it survives review: a reviewer looks for a flaw and finds none, because the flaw is a control that was never written. The same shape applies to DRF, where obtain_auth_token and simplejwt's TokenObtainPairView are login endpoints that happen to return a token instead of a cookie. The fix is the missing control, and django-axes is the canonical one, because it tracks failures per account, in the database, across processes:

-INSTALLED_APPS = [...]
+INSTALLED_APPS = [..., 'axes']
-MIDDLEWARE = [...]
+MIDDLEWARE = [..., 'axes.middleware.AxesMiddleware']    # last
+AUTHENTICATION_BACKENDS = [
+    'axes.backends.AxesStandaloneBackend',              # first
+    'django.contrib.auth.backends.ModelBackend',
+]
+AXES_FAILURE_LIMIT = 5
+AXES_COOLOFF_TIME = 1                                   # hours; None locks until reset
+AXES_RESET_ON_SUCCESS = True
+AXES_LOCKOUT_PARAMETERS = [["username"], ["ip_address"]]
+AXES_CLIENT_IP_CALLABLE = 'myproject.net.client_ip_from_forwarded_for'  # Pattern 2

AXES_LOCKOUT_PARAMETERS is the setting that is easy to get wrong. It defaults to ["ip_address"], so installing axes, setting a failure limit and a cool-off, and watching the lockout template render in testing does not give you account lockout: it gives you an IP lockout with a nicer template, dodged by a rotating source in exactly the same way. The nesting is meaningful and easy to misread: the outer list is OR, the inner lists are AND. [["username"], ["ip_address"]] locks when either the username OR the IP crosses the limit. [["username", "ip_address"]] (one inner list) only locks a specific username-from-a-specific-IP pair, which sounds tighter and is in fact the weakest of the three, because rotating either half resets the counter.

The last line of the diff matters behind any proxy. Left alone, axes reads the address from REMOTE_ADDR, which behind Heroku's router or a load balancer is the proxy, so every visitor shares one ip_address counter and five failures from anyone lock everyone out. AXES_CLIENT_IP_CALLABLE points it at the trusted-hop function Pattern 2 ends with (its AXES_IPWARE_* settings take effect only with django-ipware installed).

Here is the part I am genuinely not settled on. Locking by username means anyone who knows your email can lock you out of your own account by failing five logins, which converts an authentication control into a denial-of-service tool aimed at your users. In axes the lever is the cool-off, and the common advice is that a short cool-off (minutes, not hours) plus alerting is the right trade. I've gone with the OR configuration and a one-hour cool-off on this blog because it is a personal site where locking me out is a nuisance rather than a business event. I would not be as confident on a public civic platform, where locking a citizen out of signing during a petition deadline has consequences I would rather not have to explain to a regulator. This is a real trade-off with no clean answer, and anyone who tells you otherwise is selling something.

Pattern 2 — A Rate Limiter Keyed on a Header the Client Controls

This one is worse than Pattern 1, because it produces the feeling of protection. It is also, almost verbatim, what I found in my own project, and it is how the lab's vulnerable view resolves the "client IP" it rate-limits on. The fix trusts only the hop your own proxy wrote:

 def client_ip_from_forwarded_for(request):
     xff = request.META.get("HTTP_X_FORWARDED_FOR")
-    if xff:
-        return xff.split(",")[0].strip()  # DANGER: attacker-controlled
+    if xff and settings.TRUST_PROXY_HEADERS:
+        return xff.split(",")[-1].strip()  # the hop our own proxy appended
     return request.META.get("REMOTE_ADDR", "")

X-Forwarded-For is a breadcrumb trail that each proxy appends to. When a request arrives at a Heroku dyno, the router has appended the real client address to whatever the client already sent, so the header reads <whatever the attacker typed>, <real client IP>. Taking split(',')[0] reads the attacker's entry. Rotating that header per request hands the attacker a brand-new rate-limit bucket every time, from one machine, with no proxy pool at all: in the lab, the wordlist runs to the end and the flag falls. The correct entry to trust is the one your proxy appended, which behind exactly one proxy is the last, not the first. The number of hops you can trust is deployment knowledge that has to be configured rather than guessed: TRUST_PROXY_HEADERS is a setting of your own, not Django's, to switch on only when every request reaches you through that proxy. With no proxy in front of you, leave it off, and the function falls back to REMOTE_ADDR, which the client cannot forge. The helper is in the lab's _throttle.py; the lab's secure view does not fix it, it stops keying on the address at all, which is Pattern 3.

Pattern 3 — IP-Keyed Limits as the Only Control

Fix the address and a limit keyed on it still answers the wrong question. The lab's secure view changes the key, not the resolver:

 def login_view(request):
     ...
-    ip = client_ip_from_forwarded_for(request)
-    key = f"bf:vuln:{ip}"  # DANGER: keyed on a client-controlled value
+    username = request.POST.get("username", "")
+    key = f"bf:secure:{username.lower()}"  # keyed on the ACCOUNT, not the source
     if is_locked(key):
-        return HttpResponse("rate limited\n", status=429)
+        return HttpResponse("account locked — too many failures\n", status=403)

An IP-keyed limit, the lab's or @ratelimit(key='ip', rate='5/m', block=True), correctly stops one IP from making six attempts a minute. It has no opinion whatsoever about the same attacker arriving from a new address on every attempt, which is what a forged header gives one machine and a proxy pool gives everyone else. An IP-keyed limit answers "is this source noisy?" The question you also need answered is "is this account under attack?", and no amount of tuning the first question will ever produce the second. Both views are in the lab: views_vulnerable.py and views_secure.py. In production, django-axes (Pattern 1) is this counter, kept in the database and shared across processes.

Rate limiting and lockout are different controls, and the difference is worth being precise about: the limiter blunts volume from a source, the lockout protects an account from accumulated failures. Use both, and key the limiter on the username as well as the address: with django-ratelimit, ratelimit(key='post:username', rate='5/5m', method='POST', block=True) beside a key='ip' one, applied to the view's post through method_decorator. method='POST' keeps page loads out of the budget, so a user reloading the login page never spends a guess; over the limit, block=True raises Ratelimited, a 403 unless RatelimitMiddleware is installed and RATELIMIT_VIEW names another view. It also needs a shared cache with atomic increments, such as Redis or Memcached: on Django's default LocMemCache each worker process keeps its own count, and with django_ratelimit in INSTALLED_APPS its system check rejects that cache (django_ratelimit.E003). DRF brings both traps back. Give the token endpoint its own throttle, since ObtainAuthToken opts out of the defaults, and set NUM_PROXIES: DRF identifies an anonymous client with get_ident(), which uses the whole X-Forwarded-For value when NUM_PROXIES is unset, so a forged header mints a fresh bucket — Pattern 2 inside the framework.


The Analyst's View

Brute force is where a CySA+ analyst's control vocabulary earns its keep, because no single control above covers the whole attack — the layering is the defence. The expensive PBKDF2 hash is a preventive control that caps the online guess rate; per-account lockout (django-axes) is a preventive control against sustained guessing at one account; rate limiting is a preventive throttle on volume from a source; and a bot check and MFA are further preventive layers that stay standing when the password itself is weak or already known. Read that list against the attack and the blind spots line up on purpose: an IP-keyed limit sees a noisy source but not one that changes address on every attempt, while a per-account lockout sees the targeted account but can be turned into a denial-of-service against your own users. Defence in depth here is not a slogan — it is the specific admission that each control has a gap another one is there to cover.

The habit the attack rewards is a single question asked of every counter you deploy: what is this keyed on, and who controls that value? A limit keyed on X-Forwarded-For[0] lets the attacker write the answer; a limit keyed on the source IP answers a question a proxy pool stopped asking years ago; only a per-account key answers "is this account under attack?" The same discipline runs past prevention into detection and response: a spike of user_login_failed events is only a control if the identifier you record is one you can act on — a hashed address you cannot drop into a firewall rule is a record of the attack, not a response to it.


Catching It Automatically

Testing Your Defence

The assertion is about the attempts after the fifth, so the test makes the failing ones first, each from a new forged address. This is the one the lab uses:

def test_lockout_survives_source_rotation(self):
    # The regression that matters: the same rotated attack, but the secure
    # login keys on the ACCOUNT, so rotating the source cannot dodge it.
    statuses = []
    for i, pw in enumerate(WORDLIST):
        resp = self.client.post(
            "/brute-force/secure/login/",
            {"username": "victim", "password": pw},
            HTTP_X_FORWARDED_FOR=f"10.0.0.{i}",
        )
        statuses.append(resp.status_code)
    self.assertIn(403, statuses)          # the account locked
    self.assertNotIn(200, statuses)       # the password was never reached
    # And the flag stays out of reach (never authenticated).
    self.assertNotEqual(self.client.get("/brute-force/note/").status_code, 200)

WORDLIST holds six wrong passwords and then the victim's real one, last. Point the test at /brute-force/vulnerable/login/ and it fails: the IP-keyed limit never trips, the seventh attempt logs in, and the note hands over the flag. The lab's tests.py also runs that exploit and checks that a correct password on an unlocked account still logs in, so a view that refused everyone could not pass. Against your deployed stack, run the same rotation once from outside with curl: it is the only check that exercises your real proxy chain. A Django login form also needs its CSRF cookie and token on every POST, or each attempt answers 403 before the limiter is ever consulted.

Scanning It

This is the post in the series where the scanners come up empty — and that result is worth as much as any finding. Bandit walks the Python AST for risky constructs; run against the lab it reports only a B105 on the seed's deliberately weak password, nothing on either login view. Semgrep's community packs (p/django, p/python, p/owasp-top-ten) — the rulesets an analyst runs by default — report zero. And because the CSRF post (Post 8) taught us a rule can hide in Semgrep's audit tier, the detection pass checked that too (r/python.django, r/python); it surfaces only unrelated audit findings (unvalidated-password on the seed, the XSS rule direct-use-of-httpresponse on the views), nothing about the throttle.

bandit -r labs/post_11_brute_force/                 # only B105 on the seed password
semgrep scan --config p/django --config p/python --config p/owasp-top-ten labs/post_11_brute_force/   # 0 findings
semgrep scan --config r/python.django --config r/python labs/post_11_brute_force/                     # audit tier: unrelated findings only

No tier we ran finds it — and, unlike the other "miss" cases in this series, a custom rule would not rescue it. The two flaws defeat static analysis for different reasons. The vulnerable view trusts the wrong key: whether X-Forwarded-For[0] is safe to rely on is a judgement about who controls that value. A narrow rule could flag split(",")[0] on that header, but it lives in the helper module both views import; a rule on calls to this lab's resolver would fire on the vulnerable view and stay silent on the secure one, but it would be matching one helper's name, not the flaw. And the deeper gap — no per-account counter at all — is an absence. A rule can flag a missing call only relative to code that should sit beside it, and both views make the same is_locked check; they differ only in what it is keyed on. That is the line between this lab and IDOR or mass assignment (Post 6; Posts 7 and 10): the standard tools missed those too, but the vulnerable shape itself — an owner-unscoped lookup, a fields='__all__' — is the flaw, so a custom rule on it says something true. Here a rule could tell the two views apart only by a helper's name, so it would be theatre.

The signal here is dynamic — but deliberately not a DAST scanner, and it is worth being precise about why, because the reflex of a CySA+ analyst is to reach for one. DAST tools like sqlmap (Post 1) work by firing a crafted payload and reading a signature in the response; brute force leaves no signature to read. Its symptom is behaviour across many requests, not something in one response. Testing a declared policy is bounded — OWASP's testing guide (WSTG-ATHN-03) checks a lockout with a few failed attempts and then the correct password, which is what the lab's test does — but a scanner that knows no policy could only be sure a limit is missing by hammering the endpoint until it either blocks or falls over, which is a denial-of-service, not a scan. OWASP ZAP's active scan has no rule for "missing rate limit," and there is no push-button equivalent of sqlmap here.

Worse, a generic tool would get this lab backwards. Point Hydra or a ZAP fuzzer at the vulnerable login without rotating the header and it is blocked after five tries and finds no password, so the run reads as an endpoint that is protected: a clean false negative. The bypass only appears to a probe that already knows to forge and rotate X-Forwarded-For, and that knowledge comes from reading the threat model, not from any scanner's rule set. So the probe we keep is exactly that, made deterministic: point curl (or the Django test client in tests.py) at the booted lab, rotate the forged header, and watch the limit fail to trigger — the lab README's loop, promoted to the thing that proves the bug. A scripted guessing run (Hydra, Patator, a ZAP fuzzing loop) with the same rotation would show the same effect; none is captured here, because the lab's test is the deterministic version of it. The honest CySA+ lesson of the whole post is right here: some findings come from reading the threat model and running a probe, not from a scanner. The captured runs and the full write-up are under scans/.


The habit this post left me with: every counter gets one question before it ships, what it is keyed on and who controls that value, and on a login the answer has to include the account.

Post 12 continues Series III with Session Hijacking and Fixation, where the attacker skips all of this. Instead of guessing the password, they hand the victim a session id before login and let the login make it valuable, and we look at why Django already rotates your session key on login() and how easily a hand-rolled auth flow undoes it.

Further Reading

← Back to the series