These are the notes for Cybersecurity Fundamentals (defensive), episode 48. Episode 47 made uploads, paths and saved objects safe. Today we defend the login page: how guessing works and how to slow it without locking out real users, how the page itself can leak which accounts exist, how password reset and "remember me" tokens go wrong, and how to log and alert so an attack is noticed while it happens. Every term is explained the first time it appears; the Glossary at the end defines them all again.
Neha, Ravi, the shop and every value are made up. The "bot" is a loop over a ten-word list inside our own program, all IP addresses come from the ranges reserved for documentation, and nothing outside the machine is contacted. Python samples run on 12 Nov 2026 with Python 3.13; every output below is copied from a real run. Timings and random tokens differ a little each run.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| A bot guesses its way in | brute force, common passwords, password spraying, credential stuffing |
| Locking the account locks out its owner | account lockout vs throttling (rate limiting), per-account caps |
| Bots that look like people | CAPTCHA / bot challenges, risk signals, MFA |
| "No account with that email" | account enumeration through messages and timing |
| A reset link anyone can rebuild | secure password reset tokens: random, hashed, single use, expiring |
| A cookie that says "admin" | remember-me tokens: random, rotating, revocable |
| Logs that leak and lie | security events, what never to log, log injection, structured logs |
| An attack nobody noticed | alerting on auth anomalies, SIEM |
Problem 1: unlimited guesses
Basic words first:
- Authentication means proving who you are (episode 28), usually with a password.
- Authentication failures is OWASP Top 10 category A07. In 2021 it was called Identification and Authentication Failures; the 2025 list "maintains its position at #7 with a slight name change" to A07:2025 Authentication Failures, to "more accurately reflect the 36 CWEs in this category".
- A brute-force attack tries guess after guess until one works. Real attackers start with lists of common passwords.
- Password spraying tries one common password against many accounts, so no single account sees many failures.
- Credential stuffing tries email/password pairs leaked from another site, because people reuse passwords.
Real-life example: a three-dial bike lock has 1,000 combinations; a thief starts with 000 and 123.
Demo 1: a login with no limit
# A login with no limit on guesses. The bot has a list of common passwords.
import hmac
USERS = {"neha": "sunshine1"} # toy: real apps store a hash (ep 14)
COMMON = ["123456", "password", "qwerty", "india123", "iloveyou",
"welcome", "sunshine", "sunshine1", "admin", "abc123"]
def login(user, password):
return hmac.compare_digest(USERS.get(user, ""), password)
for tries, guess in enumerate(COMMON, start=1):
if login("neha", guess):
print(f"bot got in after {tries} guesses: {guess!r}")
break
# How many guesses could it make in one day?
per_second = 50 # a slow, single bot
print(f"guesses per day with no limit: {per_second * 86_400:,}")
Real output:
bot got in after 8 guesses: 'sunshine1'
guesses per day with no limit: 4,320,000
Why it failed: nothing limited how many guesses one caller could make.
Problem 2: account lockout vs throttling
- Account lockout blocks an account after N failures (like an ATM keeping your card after three wrong PINs). The danger: an attacker who knows a username can lock its owner out on purpose, a denial of service (making a service unavailable to its real users).
- Throttling (also rate limiting) slows guessing down: each failure makes the next attempt wait longer. Counting per source (device or IP address) slows the bot without stopping the owner on her own phone.
Demo 2: lockout vs throttling
The clock is simulated, so a whole day runs instantly.
# Two ways to stop guessing. The clock is simulated (seconds).
class Lockout: # 5 failures -> account locked 15 min
fails, until = 0, 0
def login(self, pw, now):
if now < self.until: return "LOCKED"
if pw == "sunshine1": self.fails = 0; return "ok"
self.fails += 1
if self.fails >= 5: self.until = now + 900
return "wrong"
class Throttle: # wait 2^n s after n failures, max 1 h
def __init__(self): self.fails, self.next_try = {}, {}
def login(self, pw, now, source): # counted per device / IP
if now < self.next_try.get(source, 0): return "WAIT"
if pw == "sunshine1": self.fails[source] = 0; return "ok"
n = self.fails[source] = self.fails.get(source, 0) + 1
self.next_try[source] = now + min(2 ** n, 3600)
return "wrong"
lock, thr = Lockout(), Throttle()
for t in range(5): # the attacker sends 5 wrong guesses
lock.login("x", t); thr.login("x", t * 40, "bot-ip")
print("lockout : Neha, right password ->", lock.login("sunshine1", 10))
print("throttle: Neha, right password ->",
thr.login("sunshine1", 210, "nehas-phone"))
t, guesses = 0, 0
while t < 86_400: # bot guesses in one day
guesses += thr.login("x", t, "bot-ip") == "wrong"
t = max(t + 1, thr.next_try["bot-ip"])
print("throttle: bot guesses in 24 h ->", guesses)
Real output:
lockout : Neha, right password -> LOCKED
throttle: Neha, right password -> ok
throttle: bot guesses in 24 h -> 29
Attackers change IP addresses (a botnet is many machines under one controller, episode 5), so add a per-account cap too: Practice 1 below.
Problem 2b: the full guessing defence
- NIST SP 800-63B (the US government's digital identity guideline) says to limit failed attempts to "no more than 100" per authenticator, and suggests escalating waits, for example from 30 seconds up to an hour.
- A CAPTCHA is a small test easy for people and hard for programs (pick the pictures with buses). NIST calls this a "bot detection and mitigation challenge", shown when something looks automated.
- Risk-based (adaptive) checks use signals such as IP address, location, timing and browser details: a new device or country can trigger an extra check.
- MFA and passkeys (episode 29) make a guessed password useless on its own.
- Block known-leaked passwords at sign-up and password change (episode 14).
Problem 3: account enumeration
- Account enumeration means finding out which usernames or emails have accounts, from differences in messages, status codes or response time (how long the server takes to answer).
- A list of real customers makes credential stuffing and phishing (episode 6) far more effective.
- A password hash (episode 14) such as PBKDF2 is deliberately slow to make guessing expensive, which is exactly why skipping it for unknown users shows up as a timing difference.
- Timing leak / timing side channel: information revealed by how long something takes.
Demo 3: messages and timing
# Does the login page tell a stranger which accounts exist?
import hashlib, os, time, hmac
def slow_hash(pw, salt): # a password hash, slow on purpose (ep 14)
return hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, 300_000)
SALT = os.urandom(16)
USERS = {"neha@shop.in": slow_hash("sunshine1", SALT)}
def login_v1(email, pw):
if email not in USERS:
return "No account with that email" # skips the hash: fast
if not hmac.compare_digest(USERS[email], slow_hash(pw, SALT)):
return "Wrong password"
return "Welcome"
DUMMY = slow_hash("dummy", SALT)
def login_v2(email, pw):
stored = USERS.get(email, DUMMY) # always hash, same work
ok = hmac.compare_digest(stored, slow_hash(pw, SALT)) and email in USERS
return "Welcome" if ok else "Incorrect email or password"
for fn in (login_v1, login_v2):
for email in ("neha@shop.in", "nobody@shop.in"):
runs = []
for _ in range(5): # best of 5 runs: less noise
start = time.perf_counter(); msg = fn(email, "guess")
runs.append((time.perf_counter() - start) * 1000)
print(f"{fn.__name__} {email:15} {min(runs):6.1f} ms {msg}")
Real output (timings vary a little per run):
login_v1 neha@shop.in 40.5 ms Wrong password
login_v1 nobody@shop.in 0.0 ms No account with that email
login_v2 neha@shop.in 51.1 ms Incorrect email or password
login_v2 nobody@shop.in 47.9 ms Incorrect email or password
OWASP's Forgot Password Cheat Sheet: "Return a consistent message for both existent and non-existent accounts." and "Ensure that the time taken for the user response message is uniform." The same applies to login, sign-up ("this email is already registered") and reset pages.
Problem 4: password reset
- A reset token is the secret code inside a "forgot password" link; whoever has it can set a new password, so it is as valuable as the password itself.
- A predictable token is built from values an attacker knows (email, time, a counter) and can be recomputed.
- A CSPRNG (cryptographically secure random number generator, episode 10) such as Python's
secretsmodule makes unguessable tokens.
Real-life example: a spare key under the doormat (predictable) vs a hotel key card (random, one guest, dead at checkout).
Demo 4: reset tokens
# Password reset links: https://shop.in/reset?token=...
import hashlib, secrets
def token_v1(email, minute): # "unique enough": email + the minute
return hashlib.md5(f"{email}{minute}".encode()).hexdigest()
sent = token_v1("neha@shop.in", 29_384_100) # emailed to Neha
guess = token_v1("neha@shop.in", 29_384_100) # anyone who knows her email
print("v1 attacker's token matches:", guess == sent)
RESETS = {} # sha256(token) -> [email, expires, used]
def h(token): return hashlib.sha256(token.encode()).hexdigest()
def make_token(email, now):
token = secrets.token_urlsafe(32) # 256 random bits
RESETS[h(token)] = [email, now + 900, False] # store only the hash
return token
def use_token(token, now):
entry = RESETS.get(h(token))
if not entry: return "invalid link"
if entry[2]: return "link already used"
if now > entry[1]: return "link expired"
entry[2] = True; return f"set a new password for {entry[0]}"
t = make_token("neha@shop.in", now=0)
print("v2 token:", t[:16] + "...", len(t), "chars")
for now in (60, 120):
print(f"v2 use at {now:>4} s ->", use_token(t, now))
print("v2 use at 1000 s ->", use_token(make_token("neha@shop.in", 0), 1000))
Real output (the token differs each run):
v1 attacker's token matches: True
v2 token: 3QsYRpzaLlh0-_cw... 43 chars
v2 use at 60 s -> set a new password for neha@shop.in
v2 use at 120 s -> link already used
v2 use at 1000 s -> link expired
OWASP's rules for reset tokens: "Randomly generated using a cryptographically safe algorithm", "Sufficiently long to protect against brute-force attacks", "Single use and expire after an appropriate period". Store only a hash of the token, so a leaked database can't be turned into working links. After a reset, "Don't automatically log the user in", and invalidate the user's existing sessions.
Problem 5: remember-me tokens
- A cookie (episode 28) is a small value the browser stores and sends back; the user can read and edit it.
- Remember me keeps a user signed in for days or weeks with a long-lived cookie.
- Token rotation: each token works once and is replaced by a new one at every use.
- Revocation: deleting tokens on the server so they stop working (logout, password change, suspected theft).
Real-life example: a note saying "I'm a member, Ravi" (anyone can write one) vs a numbered gym band checked against the desk's list and swapped at every visit.
Demo 5: remember-me tokens
# "Remember me": stay signed in for 30 days without the password
import secrets, hashlib
def remember_v1(cookie): # the cookie just says who you are
return f"signed in as {cookie['remember']}"
print("v1 forged cookie ->", remember_v1({"remember": "admin"}))
TOKENS = {} # sha256(token) -> user
def h(t): return hashlib.sha256(t.encode()).hexdigest()
def issue(user):
t = secrets.token_urlsafe(32); TOKENS[h(t)] = user; return t
def remember_v2(token):
user = TOKENS.pop(h(token), None) # each token works ONCE...
if user is None:
return "rejected: unknown or already used token", None
return f"signed in as {user}", issue(user) # ...and is replaced
print("v2 forged cookie ->", remember_v2("admin")[0])
t1 = issue("neha")
msg, t2 = remember_v2(t1); print("v2 Neha's laptop ->", msg)
print("v2 stolen old t1 ->", remember_v2(t1)[0])
for k in [k for k, u in TOKENS.items() if u == "neha"]:
del TOKENS[k] # Neha logs out: revoke her tokens
print("v2 after logout ->", remember_v2(t2)[0])
Real output:
v1 forged cookie -> signed in as admin
v2 forged cookie -> rejected: unknown or already used token
v2 Neha's laptop -> signed in as neha
v2 stolen old t1 -> rejected: unknown or already used token
v2 after logout -> rejected: unknown or already used token
If an old, already-rotated token is ever presented again, someone copied it: that is worth an alert and revoking all of that user's tokens.
Problem 6: security logging failures
- A log is the record an app writes of what happened.
- A security event is anything that matters for spotting or investigating an attack.
- OWASP category A09:2025 Security Logging & Alerting Failures ("retains its position at #9"; renamed from Security Logging and Monitoring Failures to stress alerting): "Great logging with no alerting is of minimal value in identifying security incidents."
What to log, from the OWASP Logging Cheat Sheet ("Where possible, always log"):
| Always log | Never log (mask, hash or remove instead) |
|---|---|
| Authentication successes and failures | Authentication passwords |
| Authorization (access control) failures | Session identification values |
| Input validation failures | Access tokens |
| Session management failures (bad cookies, suspicious JWTs) | Encryption keys and other primary secrets |
| Account changes: resets, MFA changes, new admins, role changes | Database connection strings |
Each event needs when, who, from where, what, and the result (time, user, IP, action, success/failure).
- Log injection: "Log Injection occurs when an application includes untrusted data in an application log message" (OWASP). A newline (
\n, the invisible character that ends a line) inside a username can create a fake log line. - A structured log stores each event as fields (one JSON object per line) instead of free text, so user data can't break the format. OWASP: "use structured log formats, such as JSON" and "Limit the size of the user input value used to create the log message."
Demo 6: logs that leak, logs that lie
# What does our login write to the log?
import json
def log_v1(user, pw, ok): # plain text, and too much
print(f"login {'ok' if ok else 'failed'} user={user} pw={pw}")
def log_v2(user, ok, ip): # structured: one JSON object per event
event = {"ev": "login", "ok": ok,
"user": user[:64], "ip": ip} # no password, size-limited
print(json.dumps(event, separators=(",", ":")))
print("--- v1")
log_v1("neha", "sunshin1", False) # her typo, now in the log
log_v1("x\nlogin ok user=admin", "-", False) # a newline in the name
print("--- v2")
log_v2("neha", False, "203.0.113.7")
log_v2("x\nlogin ok user=admin", False, "203.0.113.7")
Real output:
--- v1
login failed user=neha pw=sunshin1
login failed user=x
login ok user=admin pw=-
--- v2
{"ev":"login","ok":false,"user":"neha","ip":"203.0.113.7"}
{"ev":"login","ok":false,"user":"x\nlogin ok user=admin","ip":"203.0.113.7"}
v1 stored Neha's typo (one letter from her real password) and printed a forged login ok user=admin line. v2 keeps the newline escaped as \n inside the user field and never stores a password.
Problem 6b: alerting on auth anomalies
- An anomaly is something unusual compared with normal behaviour.
- An alert is a message to a person (or ticket, or page) when a rule matches.
- A SIEM (security information and event management system) collects logs from many systems and runs rules like these over them.
Demo 7: three alert rules
# Logs nobody reads catch nothing. Rules turn events into alerts.
from collections import Counter, defaultdict
EVENTS = ([("10:01", "neha", "198.51.100.4", False),
("10:01", "neha", "198.51.100.4", True)]
+ [("10:02", f"user{i}", "203.0.113.9", False) for i in range(40)]
+ [("10:03", "ravi", "192.0.2.50", False)] * 25
+ [("10:04", "ravi", "192.0.2.50", True)])
def alerts(events):
users_failed_from = defaultdict(set); fails = Counter(); out = []
for t, user, ip, ok in events:
if not ok:
users_failed_from[ip].add(user); fails[user] += 1
elif fails[user] >= 10: # finally right, after many wrong
out.append(f"{t} success after {fails[user]} failures: {user}")
for ip, users in users_failed_from.items():
if len(users) >= 20: # one IP, many accounts
out.append(f"{ip} failed on {len(users)} accounts: spraying?")
for user, n in fails.items():
if n >= 20: # one account, many guesses
out.append(f"{user} has {n} failures: brute force?")
return out
for a in alerts(EVENTS):
print("ALERT", a)
Real output:
ALERT 10:04 success after 25 failures: ravi
ALERT 203.0.113.9 failed on 40 accounts: spraying?
ALERT ravi has 25 failures: brute force?
Neha's single typo raised nothing. Tune rules so real attacks alert and normal mistakes don't, or people will learn to ignore alerts (alert fatigue).
The whole chain
- A bot got in after 8 guesses → limit guessing.
- Lockout locked Neha out → throttle per source, plus a per-account cap; CAPTCHA, risk signals and MFA.
- Messages and 0 ms answers leaked accounts → same message, same work.
- A reset link could be rebuilt → random, hashed, single-use, expiring tokens; no auto-login; end sessions.
- A cookie said "admin" → random, rotating, revocable remember-me tokens.
- Logs leaked and lied, and nobody looked → structured JSON security events without secrets, and alert rules.
Common mistakes (and what they cause)
| Mistake | Real message / result | Why it's wrong | Fix |
|---|---|---|---|
| No limit on guesses | bot got in after 8 guesses: 'sunshine1' |
millions of guesses a day | throttling + per-account cap |
| Lock after 5 failures | lockout : Neha, right password -> LOCKED |
attackers lock out owners | throttle per source |
| "No account with that email" | login_v1 nobody@shop.in 0.0 ms No account with that email |
message and timing leak | same message, dummy hash |
| Token from email + time | v1 attacker's token matches: True |
built from known values | secrets.token_urlsafe(32), stored hashed |
| Token usable forever | (v2 shows link expired / link already used) |
stolen links keep working | expiry + single use |
| Username in the remember-me cookie | v1 forged cookie -> signed in as admin |
users edit cookies | random rotating tokens |
| Password in the log | login failed user=neha pw=sunshin1 |
logs become a target | never log secrets |
| Plain-text logs with user input | login ok user=admin pw=- (forged line) |
newline makes a new entry | JSON, size limits |
| Logs with no alerts | (nobody noticed for three weeks) | logs alone stop nothing | alert rules, SIEM |
Mini project: a defended login service
Throttling per (account, source) with a per-account cap, one generic message with equal work, JSON security events without passwords, and an alert rule.
# Mini project: a defended login service
# throttling per (account, source) + per-account cap, one generic message with equal
# work, structured JSON security events without secrets, and simple alert rules.
import hashlib, hmac, json, os
from collections import Counter
def slow_hash(pw, salt):
return hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, 100_000)
class LoginService:
CAP = 100
def __init__(self):
self.salt = os.urandom(16)
self.users = {"neha@shop.in": slow_hash("sunshine1", self.salt)}
self.dummy = slow_hash("dummy", self.salt)
self.fails, self.next_try, self.account_fails = {}, {}, Counter()
self.events = []
def log(self, **event):
event["user"] = str(event.get("user", ""))[:64] # size-limited
self.events.append(json.dumps(event, separators=(",", ":")))
def login(self, email, pw, ip, now):
key = (email, ip)
if self.account_fails[email] >= self.CAP or now < self.next_try.get(key, 0):
self.log(ev="login", ok=False, reason="throttled", user=email, ip=ip)
return "Too many attempts. Try again later."
stored = self.users.get(email, self.dummy) # equal work
ok = hmac.compare_digest(stored, slow_hash(pw, self.salt)) and email in self.users
self.log(ev="login", ok=ok, user=email, ip=ip) # never the password
if ok:
self.fails[key] = 0; self.account_fails[email] = 0
return "Welcome"
n = self.fails[key] = self.fails.get(key, 0) + 1
self.account_fails[email] += 1
self.next_try[key] = now + min(2 ** n, 3600)
return "Incorrect email or password"
def alerts(self):
evs = [json.loads(e) for e in self.events]
per_ip = Counter(e["ip"] for e in evs if not e["ok"])
return [f"{ip}: {n} failed logins" for ip, n in per_ip.items() if n >= 5]
svc = LoginService()
print(svc.login("neha@shop.in", "sunshin1", "198.51.100.4", 0))
print(svc.login("nobody@shop.in", "x", "198.51.100.4", 10))
for t in range(0, 600, 60):
svc.login("neha@shop.in", "guess", "203.0.113.9", t)
print(svc.login("neha@shop.in", "sunshine1", "198.51.100.4", 700))
print("last event:", svc.events[-1])
print("alerts :", svc.alerts())
Real output:
Incorrect email or password
Incorrect email or password
Welcome
last event: {"ev":"login","ok":true,"user":"neha@shop.in","ip":"198.51.100.4"}
alerts : ['203.0.113.9: 10 failed logins']
Practice
- Add a per-account cap (NIST's 100) to the throttle, so a botnet using many IPs is still stopped.
- Add an alert rule: "signed in from a country this account has never used".
- Should
use_tokencompare tokens in constant time? Explain, and write a version that does. - Write down five things your app must never log.
Practice 1 solution
# Practice 1 solution: throttle per source AND cap failures per account
class Throttle:
ACCOUNT_CAP = 100 # NIST SP 800-63B: no more than 100
def __init__(self):
self.fails, self.next_try, self.account_fails = {}, {}, {}
def login(self, user, pw, now, source, real_pw="sunshine1"):
if self.account_fails.get(user, 0) >= self.ACCOUNT_CAP:
return "DISABLED: reset via email / support"
key = (user, source)
if now < self.next_try.get(key, 0): return "WAIT"
if pw == real_pw:
self.fails[key] = 0; self.account_fails[user] = 0; return "ok"
n = self.fails[key] = self.fails.get(key, 0) + 1
self.account_fails[user] = self.account_fails.get(user, 0) + 1
self.next_try[key] = now + min(2 ** n, 3600)
return "wrong"
thr = Throttle()
# a botnet: 150 different IPs, one guess each (no single IP is slowed down)
results = [thr.login("neha", "guess", 0, f"bot-{i}") for i in range(150)]
print("wrong:", results.count("wrong"), "| disabled:", results.count("DISABLED: reset via email / support"))
print("next try from a new IP ->", thr.login("neha", "guess", 0, "bot-999"))
wrong: 100 | disabled: 50
next try from a new IP -> DISABLED: reset via email / support
After 100 failures across all sources the account needs an out-of-band step (email link, support) instead of more guesses.
Practice 2 solution
# Practice 2 solution: alert when an account signs in from a new country
from collections import defaultdict
EVENTS = [("09:00", "neha", "IN", True), ("12:30", "neha", "IN", True),
("13:05", "neha", "BR", True), ("18:00", "ravi", "IN", True)]
def new_country_alerts(events):
seen = defaultdict(set); out = []
for t, user, country, ok in events:
if ok and seen[user] and country not in seen[user]:
out.append(f"{t} {user} signed in from new country {country} "
f"(before: {', '.join(sorted(seen[user]))})")
if ok: seen[user].add(country)
return out
for a in new_country_alerts(EVENTS):
print("ALERT", a)
ALERT 13:05 neha signed in from new country BR (before: IN)
Practice 3 solution
# Practice 3 solution: why use_token is already safe, and an explicit version
import hashlib, hmac, secrets
# use_token looks the token up by its SHA-256 hash. An attacker can't learn
# anything from lookup timing, because changing one character of a guess
# changes the whole hash. If tokens are stored per user instead, compare them
# with hmac.compare_digest, which takes the same time wherever they differ.
STORED = {"neha": hashlib.sha256(b"real-token-value").hexdigest()}
def check(user, token):
want = STORED.get(user, "0" * 64)
got = hashlib.sha256(token.encode()).hexdigest()
return hmac.compare_digest(want, got)
print(check("neha", "real-token-value"), check("neha", "real-token-valuX"),
check("nobody", secrets.token_urlsafe(32)))
True False False
Practice 4 discussion
Passwords (even wrong ones), session IDs, access and refresh tokens, reset tokens and links, API keys, encryption keys, database connection strings, full card numbers, and one-time codes. Log a hash or the last few characters if you need to correlate events.
Quick quiz
def forgot(email):
if email in USERS:
send_reset_email(email) # takes ~400 ms
return "If that email exists, we sent a link"
return "If that email exists, we sent a link"
What does this page still leak? A: nothing, the messages match. B: whether the email exists, by time. C: the reset token. D: the user's password.
Answer
B. Only real accounts wait about 400 ms while the email is sent, so the response time reveals which emails exist. Put the email on a background queue (or do equal work on both paths) so both return equally fast.
Interview questions
- Account lockout or throttling? Throttling: it slows attackers without letting them lock out real users. Add a per-account cap (NIST: at most 100 failures) and step-up checks (CAPTCHA, MFA) instead of hard locks.
- What is password spraying and how do you detect it? One common password tried on many accounts; detect many accounts failing from one source, or a site-wide rise in failures.
- What is credential stuffing? Trying username/password pairs leaked elsewhere; defend with MFA, leaked-password checks, throttling and bot detection.
- How can a login page enumerate accounts, and how do you stop it? Different messages, status codes or timing for unknown users; use one generic message and do the same work (dummy hash) for both.
- Design a secure password reset flow. Same response for all emails; random token from a CSPRNG, stored hashed, short expiry, single use; no auto-login; end other sessions; notify the user.
- How should remember-me work? A random token stored hashed on the server, rotated on each use, revoked on logout and password change; reuse of an old token signals theft.
- Which security events should an app log, and what should it never log? Auth successes/failures, access-control failures, validation failures, session failures, account changes; never passwords, tokens, session IDs, keys or connection strings.
- What is log injection? Untrusted input that forges or breaks log entries (e.g. a newline); use structured logs, encode, and limit sizes.
- Why does OWASP stress alerting? Logs nobody reads don't stop attacks; rules over the logs must notify a person while the attack is happening.
Glossary
| Term | Meaning, with an example |
|---|---|
| Authentication | Proving who you are, e.g. with a password and an MFA code. |
| Authentication failures (A07) | OWASP category for weak login, session and credential handling. |
| Brute force | Trying guess after guess until one works. |
| Common-password list | The most-used passwords, tried first by attackers, e.g. 123456. |
| Password spraying | One common password tried on many accounts. |
| Credential stuffing | Trying email/password pairs leaked from other sites. |
| Account lockout | Blocking an account after N failures; can lock out the owner. |
| Denial of service | Making a service unavailable to its real users. |
| Throttling / rate limiting | Slowing attempts with growing waits instead of blocking. |
| Per-account cap | A maximum number of failures for one account across all sources. |
| Botnet | Many machines controlled by one attacker (episode 5). |
| CAPTCHA | A test easy for people, hard for programs; NIST: a bot detection challenge. |
| Risk-based authentication | Extra checks when signals look unusual (new device, country, time). |
| MFA | Multi-factor authentication: something you know plus something you have or are (episode 29). |
| Account enumeration | Discovering which accounts exist from messages or timing. |
| Timing side channel | Information leaked through how long an operation takes. |
| Password hash / PBKDF2 | A slow one-way function used to store passwords (episode 14). |
| Dummy hash | A hash computed for unknown users so both paths take the same time. |
| Reset token | The secret in a password reset link. |
| CSPRNG | A cryptographically secure random generator, e.g. Python's secrets. |
| Remember-me token | A long-lived random token that keeps a user signed in. |
| Token rotation | Replacing a token with a new one each time it is used. |
| Revocation | Making tokens or sessions stop working on the server. |
| Log | The record an application writes of what happened. |
| Security event | A logged action relevant to detecting or investigating attacks. |
| Security logging & alerting failures (A09) | OWASP category for missing logs, missing alerts or unsafe logs. |
| Log injection | Untrusted data that forges or breaks log entries, e.g. via a newline. |
Newline (\n) |
The invisible character that ends a line of text. |
| Structured log | Each event stored as named fields, e.g. one JSON object per line. |
| Anomaly | Something unusual compared with normal behaviour. |
| Alert | A notification to a person when a rule matches. |
| Alert fatigue | People ignoring alerts because too many are false alarms. |
| SIEM | Security information and event management: collects logs and runs alert rules. |
Summary
- Limit guessing without locking out owners: throttle per source, cap per account (NIST: no more than 100), add bot challenges, risk checks and MFA.
- Don't enumerate: the same message, status and timing for every account.
- Reset and remember-me tokens are passwords: random from a CSPRNG, stored hashed, short-lived, single use or rotating, and revocable.
- Log security events as structured JSON with when, who, where, what and result; never log secrets; limit and encode user input.
- Alert on the patterns that matter (spraying, brute force, success after many failures, new countries); logs without alerts are of minimal value.
Next episode: API security part 1: the OWASP API Security Top 10 (2023), items 1 to 3.