These are the notes for Cybersecurity Fundamentals (defensive), episode 29. Last time we built solid sessions (episode 28). But every session starts with a login, and a password alone keeps failing. Today we invent, one problem at a time, stronger logins: MFA and 2FA, the OTP (one-time password), SMS OTP weaknesses and SIM swapping, HOTP and TOTP built from their RFCs, authenticator apps, push notifications, MFA fatigue (MFA bombing), number matching, adversary-in-the-middle (AiTM) phishing, FIDO2, WebAuthn, origin binding, hardware security keys, passkeys, phishing-resistant MFA, recovery codes, account recovery as the weak link, and the trade-offs of biometrics. Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Priya, every password, secret, code, bank and URL here are made up (bank.example and bank-1ogin.example use the reserved .example name), and everything runs locally on toy data. Every code sample runs with Python 3.13 and the cryptography package (50.0.1); outputs are real, copied from actual runs. Codes based on the current time, random keys and random recovery codes change on every run; the results do not.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| Priya's password leaked from another site | Credential stuffing, MFA, 2FA, different kinds of factor |
| The second factor arrives by SMS | OTP, SMS interception, SIM swapping |
| Make the code on the phone itself | Shared secret, HMAC, counter, HOTP (RFC 4226) |
| Counters drift apart | TOTP (RFC 6238), time step, authenticator apps |
| Typing codes is a chore; push approvals get bombed | Push notifications, MFA fatigue, number matching |
| A look-alike site relays password + code | Adversary-in-the-middle phishing |
| Proof tied to the real site's address | FIDO2, WebAuthn, CTAP, challenge, origin binding |
| Where the key lives | Hardware security keys, passkeys, phishing-resistant MFA |
| The phone falls in the river | Recovery codes, account recovery as the weak link |
| Fingerprints and faces | Biometrics trade-offs: false accepts, false rejects, liveness |
Problem 1: one factor isn't enough
A gaming site Priya once used is breached and its password list leaks. She used the same password on her bank. Attackers automatically try leaked username-password pairs on other sites: credential stuffing (episode 14). It works, because the bank only asked for something she knows, and anything you know can be stolen, guessed or tricked out of you.
A parcel delivery OTP
| Parcel delivery | Logging in |
|---|---|
| Your address: plenty of people know it | The password (knowledge factor) |
| A code sent to your phone; only the phone's holder sees it | A one-time password (OTP): works once, for a short time (possession factor) |
| The parcel is handed over only with address AND code | Multi-factor authentication (MFA) |
MFA means proving your identity with two or more different kinds of factor (episode 28): knowledge, possession, inherence. With exactly two it's two-factor authentication (2FA). Two passwords are still one factor.
Problem 2: codes by SMS
The simplest second factor: the bank texts a code. It stops most credential stuffing, but:
- Interception: the SMS travels through the phone network and is not encrypted end to end.
- SIM swapping: an attacker persuades the mobile carrier (with stolen personal details, or an inside helper) to move Priya's number to a SIM card the attacker holds. Every code now goes to them.
- Malware on the phone can read messages.
- And the code can still be typed into a fake site (Problem 5).
SMS OTP is better than a password alone, but it's the weakest kind of MFA. Better: make the code inside the phone, so nothing travels.
Problem 3: invent the code generator
At setup, the bank and Priya's phone agree on one shared secret key, usually by scanning a QR code shown by the bank. After that, nothing has to be sent. Both sides keep a counter. To make a code, run HMAC (a keyed fingerprint, episode 12) over the counter with the secret key, and keep six digits. Both sides get the same six digits; nobody without the key can.
That's HOTP, the HMAC-based One-Time Password, published as RFC 4226 in 2005. An RFC ("request for comments") is one of the internet's standards documents.
Demo 1: HOTP from RFC 4226
import hmac, hashlib, struct
def hotp(secret, counter, digits=6): # RFC 4226 (2005)
mac = hmac.new(secret, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = mac[-1] & 0x0F # "dynamic truncation": pick 4 bytes
number = int.from_bytes(mac[offset:offset + 4], "big") & 0x7FFFFFFF
return str(number % 10 ** digits).zfill(digits) # keep the last 6 digits
SECRET = b"12345678901234567890" # the RFC's own test secret
for counter in range(4): # phone and server both count button presses
print("press", counter, "->", hotp(SECRET, counter))
phone, server = 7, 3 # Priya pressed 4 times without logging in
print("phone shows", hotp(SECRET, phone), "| server expects", hotp(SECRET, server))
Output:
press 0 -> 755224
press 1 -> 287082
press 2 -> 359152
press 3 -> 969429
phone shows 162583 | server expects 969429
Line by line:
struct.pack(">Q", counter)turns the counter into 8 bytes, big-endian (most significant byte first), as the RFC requires.hmac.new(..., hashlib.sha1)computes HMAC-SHA-1: 20 bytes. (SHA-1 is broken for collisions, episode 13, but HMAC-SHA-1 is still considered safe for this use; HMAC doesn't rely on collision resistance.)- Dynamic truncation: the low 4 bits of the last byte (
& 0x0F) pick an offset from 0 to 15; we read 4 bytes from there and clear the top bit (& 0x7FFFFFFF) so the number is positive. % 10 ** digitskeeps the last 6 digits;zfilladds leading zeros.
The four codes are exactly the test values printed in RFC 4226 for that secret. But the last line shows the problem: Priya pressed the button four times without logging in, so her phone is at counter 7 while the server is at 3. Counters drift apart. Servers accept a few counters ahead (a "look-ahead window") and resynchronise, but there is a neater fix.
Demo 2: TOTP, the clock as the counter (RFC 6238)
Both sides already know the time. Unix time is the number of seconds since 1 January 1970 (UTC). Divide it by a time step of 30 seconds, and that's the counter: TOTP, the Time-based One-Time Password, RFC 6238 (May 2011). The RFC's formula: TOTP = HOTP(K, T), with T = (current Unix time − T0) / X, where X = 30 seconds and T0 = 0 by default.
import hmac, hashlib, struct, time
def hotp(secret, counter, digits=6):
mac = hmac.new(secret, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = mac[-1] & 0x0F
return str((int.from_bytes(mac[offset:offset + 4], "big") & 0x7FFFFFFF) % 10 ** digits).zfill(digits)
def totp(secret, unix_time, step=30, digits=6): # RFC 6238 (2011): the counter IS the clock
return hotp(secret, int(unix_time // step), digits)
SECRET = b"12345678901234567890"
print("RFC 6238 test, time 59, 8 digits:", totp(SECRET, 59, digits=8)) # the RFC says 94287082
for t in (0, 29, 30, 59, 60):
print(f"t={t:2}s window {t // 30} code {totp(SECRET, t)}")
print("right now:", totp(SECRET, time.time()), "| valid for", 30 - int(time.time()) % 30, "more seconds")
Output (the last line depends on the current time):
RFC 6238 test, time 59, 8 digits: 94287082
t= 0s window 0 code 755224
t=29s window 0 code 755224
t=30s window 1 code 287082
t=59s window 1 code 287082
t=60s window 2 code 359152
right now: 904636 | valid for 10 more seconds
94287082 is the SHA-1 test value RFC 6238 lists for time 59. Seconds 0-29 share one code, 30-59 the next. This is what authenticator apps do: the shared secret from the QR code plus the phone's clock, no network needed. Servers usually also accept the previous window (slow typists, slightly wrong clocks) and must refuse a code that was already used (see the mini project).
Problem 4: MFA fatigue and number matching
Typing six digits is a chore, so many apps send a push notification instead: "Someone is signing in. Approve?" One tap.
Now an attacker who has the password presses "log in" again and again, at 1 AM. Buzz, buzz, buzz. MFA fatigue (also MFA bombing or push bombing) is spamming a user with MFA prompts until they approve one, by mistake or just to make it stop.
A real case: Uber, September 2022. As reported by InfoQ, Uber said the attacker likely bought a contractor's corporate password on the dark web, spammed the contractor with repeated MFA requests, then contacted them on WhatsApp claiming to be from Uber IT and saying the only way to stop the notifications was to accept one. The contractor accepted, and the attacker reached Uber's internal network.
Demo 3: plain push vs number matching
Number matching: the login screen shows a two-digit number, and the phone asks the user to type that number to approve.
import random
random.seed(7) # (fixed so the run is repeatable)
def tired_priya_taps_approve(): # 1 AM, phone buzzing again and again...
return random.random() < 0.08 # ...an 8% chance she taps Approve to stop it
# the attacker already has the password and keeps pressing "log in" (MFA bombing)
for prompt in range(1, 41):
if tired_priya_taps_approve():
print(f"plain push: attacker in after {prompt} prompts"); break
# number matching: the login screen shows 2 digits; Priya must TYPE them into her phone
for prompt in range(1, 41):
on_attackers_screen = random.randint(10, 99) # only the person logging in can see them
priya_types = None # Priya isn't logging in: she has no number
if tired_priya_taps_approve() and priya_types == on_attackers_screen:
print("attacker in"); break
else:
print("number matching: 40 prompts, attacker never got in")
Output:
plain push: attacker in after 4 prompts
number matching: 40 prompts, attacker never got in
(for ... else: the else block runs only if the loop finished without break.) With number matching, the number exists only on the screen of whoever is logging in. Priya isn't logging in, so a tired tap isn't enough. Also: show where the login comes from (city, device), limit how many prompts can be sent, add a "this wasn't me" button that alerts the security team, and teach the lesson of the Uber case: real IT never asks you to approve a login you didn't start.
Problem 5: real-time phishing (adversary in the middle)
Priya gets an email: "Your account is locked, log in here." The link goes to a look-alike site, one letter different (episode 6). She types her password, then the code from her authenticator app. Behind the scenes, the fake site passes both to the real bank instantly, while the code is still valid. The bank sees a correct password and a correct code and issues a session to the attacker.
This is adversary-in-the-middle (AiTM) phishing: the attacker's server sits between the victim and the real site, relaying everything in real time.
Demo 4: relaying a TOTP code
import hmac, hashlib, struct, time
def totp(secret, t):
mac = hmac.new(secret, struct.pack(">Q", int(t // 30)), hashlib.sha1).digest()
o = mac[-1] & 0x0F
return str((int.from_bytes(mac[o:o + 4], "big") & 0x7FFFFFFF) % 10 ** 6).zfill(6)
SECRET, PASSWORD = b"priya-shared-secret-20b", "mango#Tree92"
def real_bank_login(password, code): # the real site checks password + code
ok = password == PASSWORD and code == totp(SECRET, time.time())
return "200 logged in, session issued" if ok else "401 rejected"
def fake_site(typed_password, typed_code): # bank-1ogin.example, a look-alike page
print("fake site got:", typed_password, typed_code)
return real_bank_login(typed_password, typed_code) # relays both to the real bank AT ONCE
priya_phone_code = totp(SECRET, time.time()) # Priya reads the code from her app
print("attacker's result:", fake_site("mango#Tree92", priya_phone_code))
Output (the code changes with the time):
fake site got: mango#Tree92 596128
attacker's result: 200 logged in, session issued
MFA was on, and it didn't help. Why? A code is just digits: it doesn't know which website it was typed into, and people can't reliably tell look-alike sites apart. SMS codes, app codes and push approvals all share this weakness. (Even number matching: Priya would read the number off the fake page and type it.) We need proof that is tied to the real website's address.
Problem 6: FIDO2, WebAuthn and passkeys
A key cut for one door
| Real keys | WebAuthn |
|---|---|
| A key cut for your house door; useless anywhere else | A separate key pair (episode 15) made for one website |
| At a fake door, the key simply doesn't fit, so you can't hand anything over | Origin binding: the browser checks the site's address |
| The lock tests the key without keeping a copy | The site stores only the public key and checks a digital signature (episode 16) |
An origin is a website's address as the browser sees it: scheme (https) + host (bank.example) + port (443 by default). https://bank-1ogin.example is a different origin from https://bank.example, however similar it looks.
How a WebAuthn login works
FIDO2 is a set of standards from the FIDO Alliance (an industry group). It has two parts:
- WebAuthn (Web Authentication): a W3C standard browser API that web pages call to create and use credentials.
- CTAP (Client to Authenticator Protocol): how the browser talks to an authenticator, the device that holds the keys (a phone, a laptop's secure chip, or a USB/NFC security key).
The login:
- Registration (once): the authenticator creates a new key pair for this origin; the site stores the public key.
- The server sends a challenge: a fresh random number, different every login, so an old answer can't be replayed.
- The browser adds the real origin of the page; the page itself cannot fake it.
- The authenticator signs (challenge + origin) with the private key made for that origin.
- The server verifies the signature with the stored public key and checks the origin is its own.
Because the origin is inside the signature, a look-alike site gets either nothing (no key exists for its origin) or a signature for the wrong origin. That is what phishing-resistant means.
Demo 5: a toy authenticator with real Ed25519 signatures
import os
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.exceptions import InvalidSignature
class Authenticator: # Priya's phone or security key
def __init__(self): self.keys = {} # one key pair PER WEBSITE ORIGIN
def register(self, origin):
self.keys[origin] = Ed25519PrivateKey.generate(); return self.keys[origin].public_key()
def sign(self, origin, challenge): # the BROWSER fills in origin, not the page
if origin not in self.keys: return None # no passkey for this site at all
return self.keys[origin].sign(origin.encode() + challenge)
phone = Authenticator()
BANK = "https://bank.example"
bank_public_key = phone.register(BANK) # sign-up: the bank keeps only the public key
def bank_verify(challenge, signature): # signed data must name the REAL bank's origin
if signature is None: return "401 no credential"
try: bank_public_key.verify(signature, BANK.encode() + challenge); return "200 logged in"
except InvalidSignature: return "401 signed for a different site"
for origin in [BANK, "https://bank-1ogin.example"]: # where Priya's browser actually is
challenge = os.urandom(32) # a fresh random challenge from the real bank
print(f"{origin:28} -> {bank_verify(challenge, phone.sign(origin, challenge))}")
Output:
https://bank.example -> 200 logged in
https://bank-1ogin.example -> 401 no credential
Ed25519 is a fast elliptic-curve signature algorithm (episode 16). Real WebAuthn signs more (a hash of the "client data" with the origin and challenge, plus "authenticator data" with a counter and flags), but the idea is exactly this. Same Priya, same fake email as Demo 4, and this time the phishing fails without her needing to spot the fake.
Hardware security keys and passkeys
- A hardware security key is a small USB or NFC device; the private key is created inside it and never leaves it.
- A passkey is a FIDO credential stored on your phone or laptop, often synced across your devices by your platform or password manager, so losing one device doesn't lose it. Passkeys replace the password entirely.
- You unlock either with a fingerprint, your face or a device PIN, checked on the device: that acts as a second factor on top of having the device.
What the authorities and the industry say (fetched sources):
- CISA (the US Cybersecurity and Infrastructure Security Agency), November 2022: "FIDO standards and the WebAuthn protocol are the only widely available phishing-resistant forms of MFA"; FIDO2 authenticators can be USB tokens or built into laptops and phones.
- NIST SP 800-63B-4: "AAL3 authentication SHALL use a hardware-based authenticator and an authenticator that provides phishing resistance"; at AAL2, verifiers "SHOULD encourage the use of phishing-resistant authenticators ... whenever practical".
- FIDO Alliance Passkey Index (October 2025): over 3 billion passkeys in use securing consumer accounts, and a 93 percent sign-in success rate reported by organisations using them.
Comparing second factors
| Method | Factor | Phishing-resistant? | Main weaknesses |
|---|---|---|---|
| SMS OTP | Possession (phone number) | No | Interception, SIM swapping, relay |
| Authenticator app (TOTP) | Possession (shared secret on the phone) | No | Relay by AiTM sites; the secret can be copied at setup |
| Plain push approval | Possession (phone) | No | MFA fatigue, relay |
| Push with number matching | Possession (phone) | No (resists blind approval, not AiTM) | The number can be read off a fake page |
| Security key / passkey (FIDO2) | Possession + PIN or biometric | Yes (origin-bound) | Lost devices (plan recovery); older devices may lack support |
Problem 7: account recovery and biometrics
Priya's phone falls in a river, with her authenticator app. Many sites offer "Forgot? We'll email a link" or "We'll send an SMS". But an attacker can use that same path: if recovery needs only an email or an SMS, the strong MFA is skipped entirely. Account recovery is often the weakest link.
Demo 6: recovery codes
import secrets, hashlib
def h(code): return hashlib.sha256(code.encode()).hexdigest() # store only hashes (episode 14)
codes = ["-".join(secrets.token_hex(2) for _ in range(2)) for _ in range(8)]
print("show Priya ONCE, she prints them:", codes[:3], "...")
stored = {h(c) for c in codes} # the server keeps 8 hashes, never the codes
def use_recovery_code(code):
if h(code) in stored:
stored.remove(h(code)) # single use: burn it
return f"200 in; {len(stored)} codes left. Set up a new passkey now."
return "401 invalid or already used"
print(use_recovery_code(codes[0]))
print(use_recovery_code(codes[0])) # the same code a second time
print(use_recovery_code("1234-5678")) # a guess
Output (the codes are random):
show Priya ONCE, she prints them: ['f7c0-e7fb', '1086-aca9', '4f23-57ff'] ...
200 in; 7 codes left. Set up a new passkey now.
401 invalid or already used
401 invalid or already used
Recovery codes are random, single-use codes shown once at setup and kept offline (printed, or in a password manager). The server stores only their hashes. Here each code has 32 random bits; a fast hash like SHA-256 is acceptable only together with strict rate limits on attempts, and longer codes or a slow hash (episode 14) are safer. Other good practice: register two security keys or passkeys; make recovery as strong as login (waiting periods, alerts to every device and the old email, trained staff checks for high-value accounts).
Biometrics: handy, with limits
- Pros: fast; nothing to remember or type.
- You can't change your fingerprint if it leaks, the way you change a password.
- A match is a probability: a false accept lets the wrong person in; a false reject locks the right person out. Tuning trades one for the other.
- Fingerprints and faces can sometimes be copied from photos or prints; liveness checks try to detect a real, present person.
- Best design (what passkeys do): the biometric only unlocks the private key on your own device; it is never sent to the website, so there's no fingerprint database to leak.
The next problem
We're now sure it's really Priya, with a passkey that can't be phished. Next question: what may she do? See payroll? Edit prices? Share a folder? That's authorization: episode 30, authorization models.
The whole chain
- Leaked password → MFA: two different kinds of factor.
- SMS intercepted, SIM swapped → make codes on the phone.
- Shared secret + counter + HMAC → HOTP (RFC 4226).
- Counters drift → the clock as counter: TOTP (RFC 6238).
- Push bombing → number matching, rate limits, "this wasn't me".
- Codes relayed by a fake site → FIDO2, WebAuthn, passkeys: the origin is signed.
- Lost phone → recovery codes, recovery as strong as login, biometrics unlocking keys locally.
...and you just invented phishing-resistant authentication.
Common mistakes (and what they print)
| Mistake | What you see | Why it's wrong | Fix |
|---|---|---|---|
| Password only | Credential stuffing: 200 logged in |
Knowledge factors leak | Add a second factor |
| SMS as the only second factor for high-value accounts | Codes go to the attacker after a SIM swap | The phone number is not the phone | App codes at least; passkeys best |
| Plain push approvals | plain push: attacker in after 4 prompts |
Tired users tap Approve | Number matching, rate limits, context |
| Trusting one-time codes against phishing | attacker's result: 200 logged in, session issued |
A code doesn't know which site it was typed into | FIDO2 / WebAuthn / passkeys |
| Accepting a TOTP code twice | A relayed or shoulder-surfed code works again | No replay protection | Remember the last used window |
random for codes or recovery codes |
Predictable values (episode 10) | Not a CSPRNG | secrets |
| Storing recovery codes in plain text | A database leak exposes every account's backdoor | Codes are passwords | Store hashes; single use |
| Recovery by email or SMS only | MFA skipped entirely | The weakest path wins | Recovery codes, two keys, waiting periods, alerts |
Comparing codes with == |
Timing leaks (episode 27) | Early-exit comparison | hmac.compare_digest |
Mini project: a careful TOTP verifier
The verifier a real server needs: accept the current or the previous 30-second window, compare in constant time, and never accept the same code twice.
# A careful TOTP verifier: accepts the previous window too, but never the same code twice
import hmac, hashlib, struct
def totp(secret, t, step=30):
mac = hmac.new(secret, struct.pack(">Q", int(t // step)), hashlib.sha1).digest()
o = mac[-1] & 0x0F
return str((int.from_bytes(mac[o:o + 4], "big") & 0x7FFFFFFF) % 10 ** 6).zfill(6)
class Verifier:
def __init__(self, secret): self.secret, self.last_window = secret, -1
def check(self, code, now, step=30):
for window in (int(now // step), int(now // step) - 1): # now, or one step late
expected = totp(self.secret, window * step)
if hmac.compare_digest(code, expected): # constant time (episode 27)
if window <= self.last_window: return "reject: code already used"
self.last_window = window; return "accept"
return "reject: wrong or expired code"
SECRET = b"12345678901234567890"
v = Verifier(SECRET)
code = totp(SECRET, 1000) # Priya's phone shows this at t=1000 s
print("t=1000 typed on time: ", v.check(code, 1000))
print("t=1005 same code again: ", v.check(code, 1005)) # a relay or a shoulder-surfer replays it
print("t=1025 slow typist: ", Verifier(SECRET).check(totp(SECRET, 1000), 1025))
print("t=1100 far too late: ", Verifier(SECRET).check(totp(SECRET, 1000), 1100))
print("t=1000 a guess 000000: ", Verifier(SECRET).check("000000", 1000))
Output:
t=1000 typed on time: accept
t=1005 same code again: reject: code already used
t=1025 slow typist: accept
t=1100 far too late: reject: wrong or expired code
t=1000 a guess 000000: reject: wrong or expired code
At t=1025 the clock is in the next window (1020-1049), but the previous window is still accepted. Ideas to extend it: lock the account for a while after 5 wrong codes; store last_window per user in a database; log every rejection for the security team (episode 48).
Practice
1. 60-second windows. Compare 30-second and 60-second TOTP codes for t = 0, 30, 59, 60, 119, 120.
Solution
import hmac, hashlib, struct
def totp(secret, t, step):
mac = hmac.new(secret, struct.pack(">Q", int(t // step)), hashlib.sha1).digest()
o = mac[-1] & 0x0F
return str((int.from_bytes(mac[o:o + 4], "big") & 0x7FFFFFFF) % 10 ** 6).zfill(6)
SECRET = b"12345678901234567890"
for t in (0, 30, 59, 60, 119, 120):
print(f"t={t:3}s 30-second code {totp(SECRET, t, 30)} 60-second code {totp(SECRET, t, 60)}")
t= 0s 30-second code 755224 60-second code 755224
t= 30s 30-second code 287082 60-second code 755224
t= 59s 30-second code 287082 60-second code 755224
t= 60s 30-second code 359152 60-second code 287082
t=119s 30-second code 969429 60-second code 287082
t=120s 30-second code 338314 60-second code 359152
A 60-second step means each code lives twice as long: easier for users, but a relayed or overheard code stays useful longer. 30 seconds is the RFC's default.
2. How good is a 6-digit guess? What is the chance one random guess is right? With 5 tries before lock-out and two windows accepted?
Solution
# How likely is a random 6-digit guess? And with 5 tries before lock-out?
p = 1 / 10**6
print(f"one guess: {p:.6%}")
print(f"5 guesses, 2 windows accepted: {1 - (1 - 2 * p) ** 5:.4%}")
one guess: 0.000100%
5 guesses, 2 windows accepted: 0.0010%
Tiny, as long as attempts are limited. Without rate limiting, an attacker could try thousands of codes per window, which is why lock-outs and throttling (episode 48) are part of MFA.
3. Which factor? Classify: (a) a TOTP app, (b) a fingerprint on a phone that unlocks a passkey, (c) a "mother's maiden name" question, (d) a USB security key.
Solution
(a) Possession (the secret on the phone). (b) Inherence, used locally to unlock a possession factor: the passkey login is two factors in one step. (c) Knowledge, and a weak one: often findable online. (d) Possession.
4. Why doesn't number matching stop AiTM phishing? Explain in two sentences.
Solution
In AiTM phishing Priya is actively logging in, just on the attacker's page, which relays the real site's number to her. She reads it and types it into her phone, approving the attacker's session; only origin-bound credentials (FIDO2) break the relay.
5. Design recovery. Priya's bank wants passkeys for everyone. List three things its recovery flow should do.
Solution
Examples: let her register a second passkey or security key; offer single-use recovery codes stored as hashes; add a waiting period and alerts to all devices and the old email before recovery completes; require trained-staff identity checks for high-value accounts; end all existing sessions after recovery.
Quick quiz
Priya clicks a phishing link to a look-alike login page that relays everything in real time. Which second factor still protects her?
- A: a code by SMS
- B: a TOTP authenticator app
- C: push approval with number matching
- D: a passkey (FIDO2 / WebAuthn)
Answer
D. SMS and TOTP codes can be typed into the fake page and relayed, and with number matching she would read the number off the fake page too. A passkey signs the real origin reported by the browser, so the look-alike gets nothing usable.
Interview questions
- What is MFA, and why must factors differ in kind? Proving identity with two or more of knowledge, possession and inherence. Two knowledge factors fail together (both can be phished or leaked); different kinds need different attacks.
- Why is SMS OTP considered weak? Interception, SIM swapping, phone malware, and relay through phishing pages. Still much better than a password alone.
- Explain HOTP. Code = truncate(HMAC-SHA-1(secret, counter)) to 6-8 digits (RFC 4226). Both sides share the secret and a counter; the server allows a small look-ahead window to resynchronise.
- Explain TOTP. HOTP with the counter = floor((Unix time − T0) / 30) (RFC 6238). Servers accept a small clock-skew window and must reject reused codes.
- What is MFA fatigue and how is it mitigated? Bombing a user with push prompts until one is approved. Mitigate with number matching, rate limits, location/device context, "report this" buttons, and phishing-resistant methods.
- What is adversary-in-the-middle phishing? A proxy phishing site relays credentials and one-time codes to the real site in real time and captures the resulting session. It defeats SMS, TOTP and push MFA.
- How does WebAuthn resist phishing? Credentials are scoped to an origin; the browser supplies the origin and the authenticator signs a fresh challenge plus that origin. A look-alike origin has no credential, and signatures for the wrong origin fail verification.
- FIDO2 vs WebAuthn vs CTAP vs passkeys? FIDO2 is the umbrella standard set; WebAuthn is the W3C browser API; CTAP is the browser-to-authenticator protocol; a passkey is a FIDO credential, often synced across a user's devices.
- Why is account recovery called the weak link? Attackers take the easiest path; if recovery needs only email or SMS, strong MFA is bypassed. Recovery must be as strong as login.
- Biometrics trade-offs? Convenient, but not secret and not changeable; matches are probabilistic (false accept/false reject); spoofing risk needs liveness checks. Best used locally to unlock a device-bound key, never sent to servers.
Glossary
| Term | Meaning in plain words | Example |
|---|---|---|
| Credential stuffing | Trying leaked username-password pairs on other sites (episode 14) | A gaming site's leak used on a bank |
| MFA | Multi-factor authentication: two or more different kinds of factor | Password + passkey |
| 2FA | Two-factor authentication: exactly two factors | Password + TOTP code |
| OTP | One-time password: a code that works once, for a short time | 755224 |
| SMS OTP | An OTP sent by text message | "Your code is 482913" |
| SIM swapping | Tricking a mobile carrier into moving a victim's number to the attacker's SIM | Codes now arrive on the attacker's phone |
| Shared secret | A key both the server and the authenticator hold | Set up by scanning a QR code |
| HMAC | A keyed fingerprint of data (episode 12) | hmac.new(secret, counter, sha1) |
| HOTP | HMAC-based OTP: HMAC of a counter, truncated to digits (RFC 4226) | Demo 1 |
| RFC | "Request for comments": an internet standards document | RFC 4226, RFC 6238 |
| Dynamic truncation | HOTP's way of picking 4 bytes of the HMAC, chosen by its last byte | mac[-1] & 0x0F |
| Counter drift | Client and server counters getting out of step | phone shows 162583 \| server expects 969429 |
| Unix time | Seconds since 1 January 1970 (UTC) | time.time() |
| Time step | How long one TOTP code lasts | 30 seconds |
| TOTP | Time-based OTP: HOTP with the counter = time / 30 (RFC 6238) | Demo 2 |
| Authenticator app | A phone app that computes TOTP codes from a shared secret | The six digits Priya types |
| Push notification (MFA) | An "Approve sign-in?" prompt sent to the phone | One tap |
| MFA fatigue / MFA bombing | Spamming push prompts until the user approves | Uber, 2022 |
| Number matching | The user must type a number shown on the login screen into the phone | Demo 3 |
| AiTM phishing | Adversary-in-the-middle: a fake site relays credentials and codes in real time | Demo 4 |
| Relay | Passing captured credentials to the real site immediately | fake_site → real_bank_login |
| FIDO Alliance | The industry group behind FIDO2 and passkeys | Publishes the Passkey Index |
| FIDO2 | The standards for phishing-resistant, public-key logins: WebAuthn + CTAP | Security keys, passkeys |
| WebAuthn | The W3C browser API for creating and using public-key credentials | navigator.credentials |
| CTAP | Client to Authenticator Protocol: browser ↔ authenticator | Talking to a USB key |
| Authenticator | The device or chip holding the private keys | A phone, a security key |
| Origin | Scheme + host + port of a website | https://bank.example |
| Origin binding | Credentials work only for the origin they were made for | Demo 5 |
| Challenge | A fresh random value the server asks to be signed | os.urandom(32) |
| Replay | Re-sending an old valid answer | Stopped by fresh challenges, used-code checks |
| Ed25519 | A fast elliptic-curve signature algorithm (episode 16) | Ed25519PrivateKey |
| Hardware security key | A USB/NFC device that keeps private keys inside it | A FIDO2 key on a keyring |
| Passkey | A FIDO credential on a phone or laptop, often synced across devices | Login with a fingerprint, no password |
| Phishing-resistant MFA | MFA that a look-alike site cannot capture and reuse | FIDO2 / WebAuthn |
| CISA | US Cybersecurity and Infrastructure Security Agency | Nov 2022 phishing-resistant MFA guidance |
| AAL3 | NIST's highest authenticator assurance level: hardware-based and phishing-resistant | Security keys |
| Recovery code | A single-use backup code shown once at setup | f7c0-e7fb |
| Account recovery | How a user regains access after losing a factor | "Forgot password" flows |
| Biometrics | Using body traits to authenticate | Fingerprint, face |
| False accept / false reject | A biometric wrongly letting someone in / wrongly keeping the owner out | A sibling unlocks the phone |
| Liveness check | Detecting a real, present person rather than a photo or mould | Blink or depth checks |
Summary
- A password alone falls to leaks and credential stuffing: use MFA, with different kinds of factor.
- SMS OTP is the weakest second factor (interception, SIM swapping, relay).
- HOTP (RFC 4226) = HMAC of a counter, truncated; TOTP (RFC 6238) uses time / 30 s as the counter. We reproduced both RFCs' test values (755224..., 94287082).
- Push approvals fall to MFA fatigue (Uber, 2022): use number matching, limits and context.
- AiTM phishing relays passwords and codes in real time; codes don't know which site they were typed into.
- FIDO2 / WebAuthn sign a fresh challenge plus the origin the browser reports, so look-alike sites get nothing: phishing-resistant. Security keys and passkeys use it (CISA: the only widely available phishing-resistant MFA; FIDO Alliance: over 3 billion passkeys in use, Oct 2025).
- Recovery is the weak link: single-use recovery codes, two keys, and recovery as strong as login. Biometrics should only unlock keys locally.
Next episode: authorization models: DAC, MAC, RBAC, ABAC, ReBAC, ACLs vs capabilities, PDP and PEP, deny by default, privilege creep, policy as code, and Google Zanzibar.
Sources: RFC 4226 (HOTP, 2005) and RFC 6238 (TOTP, May 2011), datatracker.ietf.org; InfoQ (24 Sep 2022), "Uber breach: MFA fatigue"; Cybersecurity Dive (4 Nov 2022), "CISA urges phishing-resistant MFA"; NIST SP 800-63B-4, "Authenticator Assurance Levels"; Mobile ID World (14 Oct 2025), "FIDO Alliance Reports 3 Billion Passkeys in Use". Code outputs from Python 3.13 and cryptography 50.0.1. Fetched 4 Nov 2026.