Password Login Done Right
A login form looks like the simplest page of an application: two fields and a button. Behind it sit at least six decisions that attackers test one by one: how the password is stored, what the error message says, how long the answer takes, how many guesses are allowed, which passwords are accepted, and what happens to the session afterwards. Getting any one of them wrong gives away accounts. OWASP 2025 files these mistakes under A07 Authentication Failures. This lesson builds a login the wrong way, lists what an attacker learns from it, and then rebuilds it with each decision made properly. The cryptography of password hashing (why fast hashes fail, salts, Argon2id, bcrypt, scrypt) is in Applied Cryptography; here we use it.
Definitions
- Password hash: a deliberately slow, salted one-way function (Argon2id, scrypt, bcrypt, PBKDF2) stored instead of the password. A salt is a random per-user value that makes identical passwords hash differently. A pepper is an extra server-side secret, kept outside the database.
- Online attack: guessing through the login form, limited by the server's rate limits. Offline attack: guessing against a stolen hash database, limited only by the hash's cost and the attacker's hardware.
- Credential stuffing: trying username/password pairs leaked from other sites. Password spraying: one common password against many accounts, to stay under per-account lockouts (Brute Force and Password Spraying).
- User enumeration: learning which accounts exist from different messages, status codes or response times.
Why the hash's cost matters
If a password is chosen uniformly from symbols with length , there are candidates, and the expected time to find it at guesses per second is
The site controls twice: online through rate limiting (a few guesses per minute per account), and offline through the hash function (a fast hash allows billions of guesses per second per GPU, a tuned slow hash a few thousand). Move the sliders: the same 10-character password survives a year against SHA-256 and millions of years against bcrypt in this model.
A login that leaks
The first version stores unsalted SHA-256, says which field was wrong, and only hashes when the user exists. The example counts hash computations instead of measuring time (wall-clock timing would make the output change from run to run); each count is a proxy for how long the server took.
import hashlib
USERS = {"alice": hashlib.sha256(b"Winter2026!").hexdigest(),
"bob": hashlib.sha256(b"Winter2026!").hexdigest()}
hash_calls = 0
def login_bad(user, password):
global hash_calls
if user not in USERS:
return "404 no such user"
hash_calls += 1
if hashlib.sha256(password.encode()).hexdigest() != USERS[user]:
return "401 wrong password"
return "200 welcome"
for user, pw in [("alice", "guess"), ("mallory", "guess"), ("bob", "Winter2026!")]:
before = hash_calls
print(f"{user:8} -> {login_bad(user, pw):20} hashes computed: {hash_calls - before}")
print("alice and bob have the same stored hash:", USERS["alice"] == USERS["bob"])
print("stored value:", USERS["alice"][:16] + "...")alice -> 401 wrong password hashes computed: 1
mallory -> 404 no such user hashes computed: 0
bob -> 200 welcome hashes computed: 1
alice and bob have the same stored hash: True
stored value: 204294a2a33e5c0c...
An attacker learns three things: mallory doesn't exist and alice does (message, status code and timing differ), and two users share a password (equal hashes). A stolen copy of USERS falls to a GPU in hours, because SHA-256 is designed to be fast.
A login done right
The fixed version hashes with Argon2id (argon2-cffi, parameters from OWASP's Password Storage Cheat Sheet: 19 MiB of memory, 2 iterations, 1 lane), returns one message for every failure, verifies against a dummy hash when the user doesn't exist so every attempt costs the same, counts failures per account, rejects passwords on a blocklist, and rehashes when the parameters are raised.
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
BLOCKLIST = {"password", "123456", "winter2026!", "qwerty123"} # real systems: a large breached-password list
DUMMY = ph.hash("dummy password for unknown users")
users, failures = {}, {}
hash_calls = 0
def register(user, password):
if len(password) < 8 or password.lower() in BLOCKLIST:
return "rejected: too short or known to be breached"
users[user] = ph.hash(password)
return "ok"
def login(user, password, max_failures=5):
global hash_calls
if failures.get(user, 0) >= max_failures:
return "429 too many attempts, try later"
stored = users.get(user, DUMMY) # same work whether or not the user exists
hash_calls += 1
try:
ph.verify(stored, password)
ok = user in users
except VerifyMismatchError:
ok = False
if not ok:
failures[user] = failures.get(user, 0) + 1
return "401 invalid username or password"
failures[user] = 0
if ph.check_needs_rehash(stored):
users[user] = ph.hash(password)
return "200 welcome"
print("register bob, Winter2026!:", register("bob", "Winter2026!"))
print("register alice, a passphrase:", register("alice", "correct horse battery staple"))
print("register carol, same passphrase:", register("carol", "correct horse battery staple"))
print("alice and carol hashes differ (salts):", users["alice"] != users["carol"])
print("stored format:", users["alice"].split("quot;)[1:4])
for user, pw in [("alice", "guess"), ("mallory", "guess"), ("alice", "correct horse battery staple")]:
before = hash_calls
print(f"{user:8} -> {login(user, pw):35} hashes computed: {hash_calls - before}")
for _ in range(5):
last = login("carol", "wrong")
print("carol after 5 failures:", last, "|", login("carol", "correct horse battery staple"))register bob, Winter2026!: rejected: too short or known to be breached
register alice, a passphrase: ok
register carol, same passphrase: ok
alice and carol hashes differ (salts): True
stored format: ['argon2id', 'v=19', 'm=19456,t=2,p=1']
alice -> 401 invalid username or password hashes computed: 1
mallory -> 401 invalid username or password hashes computed: 1
alice -> 200 welcome hashes computed: 1
carol after 5 failures: 401 invalid username or password | 429 too many attempts, try later
The salts are random (that is the point, and why the example prints a comparison rather than the hashes). The stored string carries the algorithm and its parameters, so check_needs_rehash can upgrade old hashes at the next successful login. Every failure looks the same, and the unknown user costs one hash like everyone else.
How login weaknesses are detected
- Testing: compare responses (status, body, length, headers, time) for an existing and a non-existing user, at login, registration ("this e-mail is already taken") and password reset; try 20 wrong passwords and see whether anything changes; try
passwordand123456at registration. - Logs and alerts: many failures for one account (brute force), one password across many accounts (spraying: count distinct users per source and per password-hash prefix in failures), logins from many IPs with a high failure rate (stuffing), and success after a run of failures.
- Code review:
md5(,sha1(,sha256(on passwords; comparisons with==on secrets; different code paths for "no such user".
How it is fixed
- Store Argon2id (or scrypt, or bcrypt with cost , or PBKDF2-HMAC-SHA256 with 600,000 iterations where FIPS is required), with library-managed salts.
- One generic message and equal work for every failure; the same for registration and reset flows ("if an account exists, we sent an e-mail").
- Throttle per account and per source: exponential back-off or temporary locks, CAPTCHAs after several failures. Permanent lockouts let attackers lock out victims, so prefer delays.
- Check new passwords against breached lists (NIST SP 800-63B, as revised in 2025, requires a blocklist and drops composition rules and forced periodic changes); allow long passphrases (at least 64 characters) and paste.
- Offer and encourage MFA and passkeys (next two lessons), and start a new session at login.
Pitfalls
- Truncation and normalisation: bcrypt ignores bytes after 72; decide how Unicode is normalised before hashing (NFC/NFKC) and apply it at registration and login alike.
- Rate limits keyed only on IP: attackers rotate through proxies; add per-account limits.
- Logging the password field on failed logins (debug logs, request dumps). Users often type a password into the username field, too.
Practice
1. A reset form answers "No account with that e-mail" or "Reset link sent". Rewrite it.
Always answer "If an account exists for that address, we have sent a reset link", with the same status and similar timing (send the e-mail asynchronously so the response time doesn't reveal it).
2. Your logs show 3,000 failed logins in an hour, each for a different username, all with the same password. What is it and what do you do?
Password spraying. Per-account limits don't trigger; alert on many distinct accounts per source or per password guess, block or challenge the sources, check which attempts succeeded and force resets plus MFA for those accounts.
Test yourself
Why did the fixed login verify against a dummy hash for unknown users?
- To create the account
- So unknown and known users take the same work, and timing doesn't reveal which accounts exist
- To make the hash stronger
- To log the attempt
In the leaky version, why did alice and bob have equal stored hashes?
- SHA-256 collision
- No salt: identical passwords give identical hashes
- They are the same user
- Argon2 was used
In the sim's model, which change moves offline guessing time the most for a fixed password?
- Rate limiting the login form
- Switching from SHA-256 to bcrypt
- Adding HTTPS
- A longer session timeout
What does current NIST guidance (SP 800-63B) say about composition rules and forced periodic changes?
- Both are required
- Neither should be required; check against breached-password lists instead
- Only periodic changes
- Only composition rules