CAPSTONE: HARDEN A LOGIN FLOW
Everything in this path, in one sign-in form
Your login returns "Invalid username or password" for both an unknown user and a wrong password. It hashes the password only when the user exists, with an 80 ms hash. Can an attacker tell which usernames exist?
A login form is the place where every earlier lesson meets. Each layer stops one attack and nothing else. A parameterized query stops injection. A salted slow hash protects passwords if the table leaks. One error message, with the same work on both paths, stops enumeration. A per-account+IP limit stops guessing without letting an attacker lock the owner out. HttpOnly stops a script from stealing the session cookie, though not from using the session in place. SameSite stops other sites from riding it. Skip any one, and the attacker goes through that gap; the others never get asked.
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const [user] = await db.query(
`SELECT * FROM users WHERE username = '${username}'`); // injection
if (!user) return res.status(401).send('Unknown user'); // enumeration
if (user.password !== password) // plaintext
return res.status(401).send('Wrong password');
res.cookie('sid', newSession(user.id)); // script-readable, sent cross-site
res.send('Welcome');
}); // no rate limitconst DUMMY = await argon2.hash('dummy-password');
app.post('/login', async (req, res) => {
const { username, password } = req.body;
if (!(await limiter.consume(`${username}|${req.ip}`)))
return res.status(429).send('Too many attempts');
const [user] = await db.query('SELECT * FROM users WHERE username = $1', [username]);
// same work whether or not the user exists
const ok = await argon2.verify(user ? user.hash : DUMMY, password);
if (!user || !ok) return res.status(401).send('Invalid username or password');
res.cookie('sid', newSession(user.id), { httpOnly: true, secure: true, sameSite: 'lax' });
res.send('Welcome');
}); Watch the ATTACKER box and both invariants. NAIVE LOGIN fails both: the error message names the missing user, the injection signs in as alice, the twelfth guess works, and the cookie is read by a script and sent with a cross-site POST. HARDENED LOGIN runs the same six attacks and keeps both green, and alice still signs in at the end.
Every layer is in place except one. Pick the attack and the moment that gets the attacker into alice's account.
GOAL: the attacker acts as alice
Harden login. Use a parameterized query (? or $1 placeholder); compare hashes with db.equal (digests are objects, so === never matches); return the same status, body and work for an unknown user as for a wrong password; allow 5 attempts per username and IP with limiter.hit(key); set an HttpOnly; Secure; SameSite=Lax cookie. Time is virtual: a query costs 1 ms, db.hash 80 ms.
Every sign-in endpoint, password reset (“if that email exists, we sent a link”), and sign-up (“username taken” is enumeration too). Framework pieces: ORM parameter binding, argon2/bcrypt libraries, rate limiters keyed on account and IP, Set-Cookie: HttpOnly; Secure; SameSite=Lax. OWASP's Authentication Cheat Sheet lists the same layers.
“Design a secure login endpoint” or “Review this login code.” Walk the request in order: limiter, parameterized lookup, slow hash with a dummy for unknown users, constant-time compare, one generic error, session cookie flags. Then say what each layer does not cover: MFA for stolen passwords, breached-password checks, and distributed guessing across many IPs.
USED IN
Chapters that build on this lesson.
- A security engineer's weekSecurity
- Authentication and authorisation for a multi-tenant SaaS and its public APISecurity
- Fraud and abuse: where security meets the productSecurity
- Identity, access and secretsSecurity
- Secure code review and AppSecSecurity
- Security philosophies: defence in depth, least privilege, assume breach, risk not fearSecurity
- Triaging researcher reports: running a disclosure programme day to daySecurity
- Why security engineering existsSecurity