Multi-Factor Authentication and TOTP
Passwords leak: through phishing, reuse across sites, breaches of other services, malware. Multi-factor authentication (MFA) asks for a second, different kind of proof, so a stolen password alone no longer opens the account. It is the single most effective control against credential stuffing and spraying. But "MFA" covers very different mechanisms, from an SMS code that a SIM-swapper can receive to a hardware key that no phishing site can use, and the server side of each has its own mistakes. This lesson implements the most common one, the time-based one-time password (TOTP) of authenticator apps, checks it against the RFC's test vectors, and then lists how MFA is bypassed and how each bypass is closed. The survey lesson is Authentication and MFA.
Definitions
- Factors: something you know (password, PIN), have (phone, security key), are (fingerprint, face). Two passwords are one factor twice.
- HOTP (RFC 4226):
code = Truncate(HMAC-SHA1(K, counter)) mod 10^d. TOTP (RFC 6238): HOTP withcounter = floor(unix_time / 30). The shared secretKis provisioned once, usually as a QR code containing anotpauth://totp/…?secret=BASE32…URI. - Verification window: accepting the previous and next time step as well, to tolerate clock drift.
- Phishing-resistant MFA: a factor bound to the real site's origin so a look-alike site can't relay it (FIDO2/WebAuthn, smart cards). OTP codes and push approvals are not phishing-resistant.
TOTP from the RFC
RFC 6238 Appendix B gives test values for the ASCII secret 12345678901234567890 with 8 digits. The implementation below follows RFC 4226's dynamic truncation: take the low 4 bits of the last HMAC byte as an offset, read 4 bytes there, clear the top bit.
import hmac, hashlib, struct
def hotp(key, counter, digits=6):
mac = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = mac[-1] & 0x0F
value = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
return str(value % 10 ** digits).zfill(digits)
def totp(key, unix_time, digits=6, step=30):
return hotp(key, unix_time // step, digits)
K = b"12345678901234567890"
for t, expected in [(59, "94287082"), (1111111109, "07081804"), (1234567890, "89005924"), (2000000000, "69279037")]:
got = totp(K, t, digits=8)
print(t, got, "ok" if got == expected else "MISMATCH")59 94287082 ok
1111111109 07081804 ok
1234567890 89005924 ok
2000000000 69279037 ok
All four codes match the RFC's SHA-1 column, so the arithmetic is right. The server and the app share K and a clock; neither ever sends K again after enrolment.
The verifier is where bugs live
A correct code generator is easy; a correct verifier has four more rules: a small window, constant-time comparison, no reuse of an accepted code, and a limit on attempts. The example fixes the clock at a known time so the output is stable (real code uses time.time()), and compares a naive verifier with a careful one.
import hmac, hashlib, struct
def hotp(key, counter, digits=6):
mac = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
o = mac[-1] & 0x0F
return str((struct.unpack(">I", mac[o:o + 4])[0] & 0x7FFFFFFF) % 10 ** digits).zfill(digits)
KEY = b"lab-only-totp-secret-20b" # real secrets: secrets.token_bytes(20)
NOW = 1_790_000_000 # a fixed "now"
def naive_verify(code, now=NOW):
return any(code == hotp(KEY, now // 30 + d) for d in range(-10, 11)) # +-5 minutes, reusable, unlimited
class Verifier:
def __init__(self):
self.last_step, self.failures = -1, 0
def verify(self, code, now=NOW):
if self.failures >= 5:
return "locked: too many wrong codes"
for d in (-1, 0, 1): # +-30 s for clock drift
step = now // 30 + d
if hmac.compare_digest(code, hotp(KEY, step)):
if step <= self.last_step:
return "rejected: code already used"
self.last_step, self.failures = step, 0
return "ok"
self.failures += 1
return "wrong code"
current = hotp(KEY, NOW // 30)
old = hotp(KEY, NOW // 30 - 8) # a code from 4 minutes ago, e.g. phished earlier
print("current code:", current)
print("naive accepts a 4-minute-old code:", naive_verify(old))
v = Verifier()
print("careful, 4-minute-old code:", v.verify(old))
print("careful, current code:", v.verify(current))
print("careful, same code replayed:", v.verify(current))
for guess in ["000000", "111111", "222222", "333333", "444444"]:
r = v.verify(guess)
print("after 5 wrong guesses:", r, "|", v.verify(hotp(KEY, NOW // 30 + 1)))
print(f"chance per guess with a 3-step window: {3 / 10**6:.6f}; naive 21 steps, no limit: 1 in {10**6 // 21:,} per guess")current code: 991456
naive accepts a 4-minute-old code: True
careful, 4-minute-old code: wrong code
careful, current code: ok
careful, same code replayed: rejected: code already used
after 5 wrong guesses: wrong code | locked: too many wrong codes
chance per guess with a 3-step window: 0.000003; naive 21 steps, no limit: 1 in 47,619 per guess
The naive verifier accepts any of 21 codes (ten minutes of them), forever, without counting failures: an attacker who knows the password can try codes as fast as the server answers and, at 21 valid codes in a million, expects success after about 48,000 attempts, a few hours of requests. The careful verifier accepts three codes, refuses a replay of the code that just worked (a phished code is usually replayed within seconds), and locks after five wrong codes.
How MFA is bypassed, and detected
| Bypass | Mechanism | Detection | Fix |
|---|---|---|---|
| Real-time phishing (adversary in the middle) | a proxy site relays password and OTP to the real site and keeps the session cookie | logins from hosting-provider IPs right after a link click; new device + impossible travel | phishing-resistant MFA: passkeys / FIDO2 |
| Push fatigue | the attacker triggers dozens of push prompts until the user taps "approve" | many denied pushes then one approval | number matching, rate limits on prompts, report button |
| SIM swap | the attacker moves the victim's number and receives SMS codes | carrier change notifications, SMS factor used from a new device | don't use SMS for high-value accounts; prefer app or key |
| Skippable step | the second step is a separate page; the API behind it doesn't check that it was completed | requests to post-login endpoints from sessions in "password-only" state | the session records mfa_done; every protected endpoint checks it |
| Weak recovery | "lost your phone?" falls back to e-mail or security questions | recovery used shortly before a suspicious login | recovery codes (hashed, one-time), strong identity checks, notify the user |
| Brute-forcing the code | no attempt limit, as in the naive verifier | many OTP failures per session | limit attempts per session and per account |
How MFA is implemented well
- Store TOTP secrets encrypted, compare in constant time, window ±1 step, reject reuse, limit attempts.
- Make MFA state part of the server-side session, checked by every protected route, not just the page after login.
- Prefer passkeys/WebAuthn for phishing resistance; keep TOTP as a fallback; avoid SMS where you can.
- Require re-authentication with MFA for sensitive actions (changing e-mail, password, MFA settings, payouts).
- Log enrolment, removal, failures and recovery-code use, and notify the user of each.
Pitfalls
- Returning the secret or QR code again from a settings API after enrolment: anyone with a session can clone the authenticator.
- "Remember this device" cookies that never expire or aren't bound to the session.
- MFA only on the web login, not on the API tokens, mobile app or legacy protocols (IMAP, SMTP basic auth) that reach the same account.
Practice
1. Why does the careful verifier store last_step instead of the last code?
Two different steps can produce the same 6-digit code by chance; and storing the step also rejects older valid codes inside the window after a newer one was used, which is what RFC 6238 §5.2 recommends.
2. A user reports 30 push notifications at 3 a.m. and says they accidentally approved one. What happened and what do you do?
Push fatigue: the attacker has the password. Revoke the sessions created after the approval, reset the password, review the account's activity, and turn on number matching (the user must type a number shown on the login screen) and push rate limits.
Test yourself
What does the TOTP counter consist of?
- A random number per login
- floor(unix_time / 30)
- The user id
- The number of logins so far
Why is a TOTP code not phishing-resistant?
- It is too short
- A proxy site can collect it and relay it to the real site within its validity window
- It uses SHA-1
- It is sent by SMS
Which verifier rule stops a phished code from being reused after the user has logged in with it?
- A ±1 step window
- Rejecting codes whose step is not newer than the last accepted step
- hmac.compare_digest
- Six digits instead of eight
The second factor is checked on /mfa, but /api/orders only checks that a session exists. What is the bug?
- None
- The MFA step can be skipped by calling the API directly after the password step
- TOTP is broken
- The API needs CORS