Skip to content
Tech Interview Prep
Technical interview guide

Multi-Factor Authentication Design

Combining independent authentication factors, and why some MFA methods are meaningfully stronger than others.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v6
Editorial status
Reviewed

Scope: NIST SP 800-63B-4, WebAuthn Level 3, FIDO passkey guidance, TOTP/HOTP, CISA, and OWASP guidance current 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Define MFA and evaluate factor independence.

Answer

Definition. MFA is authentication with two or more authenticators drawn from different factor types (knowledge, possession, inherence) or a single multi-factor cryptographic authenticator activated locally by a PIN or biometric. NIST SP 800-63B rev 3 §4.2 is the reference: AAL2 requires two distinct factor types; §4.3 adds a hardware-based authenticator and verifier impersonation resistance for AAL3. Two passwords, or a password plus a security question, are one factor wearing two hats.

The test that decides it. Not "how many prompts?" but "is there one realistic compromise that defeats both?" Factor type is a proxy for that; independence is the property you actually need.

CombinationIndependent?One compromise that defeats both
Password + TOTP seed in the same password managerNoVault breach, or an unlocked phone
Password + SMS/voice OTPWeaklySIM swap / number port
Password + security questionNoBreach corpus, OSINT
Password + WebAuthn hardware keyYesPhysical key theft and password
Password + push with number matchingMostlyPush fatigue plus a user who approves

Trace: SIM swap against password + SMS OTP. (1) Attacker buys a credential dump containing the victim's email, password, DOB and last-4 SSN. (2) They call the carrier, answer the same four facts, and port the number to a SIM they hold; the victim's phone drops to "no service" within minutes. (3) They log in, the verifier sends the OTP, the attacker's SIM receives it. (4) Both factors fell to one dump and one phone call. The second factor did no independent work, which is why rev 3 §5.1.3.3 marks PSTN out-of-band as restricted and bars it from AAL3.

Alternatives, and when each is right.

OptionPhishing-resistantIndependence risk
TOTP (RFC 6238: 6 digits, 30 s step, HMAC-SHA1)No. Relayable in real timeSeed usually stored beside the password
WebAuthn / FIDO2 hardware keyYes: the assertion is scoped to the RP ID, so a lookalike origin gets nothingKey loss pushes users onto the recovery path
Synced passkeyYes for phishingPlatform-account compromise syncs the credential to the attacker
Push with number matchingNo: a tired user can approvePush fatigue; Microsoft made number matching the default for Authenticator push in May 2023

Deciding criteria: if phishing is in the threat model, it is for anything internet-facing, TOTP and push are both relayable, and only origin-bound WebAuthn closes it. If you need AAL3, synced passkeys don't qualify; the standard wants a hardware-based authenticator.

Where independence actually breaks. Enrollment: if the second factor is added through the first (an email link that registers a phone), the first factor can register an attacker's authenticator. Recovery: the account's assurance is the weakest path, not the login path. A helpdesk that resets on a knowledge question turns an AAL2 login into an AAL1 account. Session continuation: rev 3 §7.2 caps reauthentication at 12 hours for AAL2 and AAL3 (30 days for AAL1), and a stolen session cookie skips the second factor entirely, so bind sessions to the authenticator or keep them short.

What would change the decision. If the population can't hold hardware keys, push with number matching plus a phishing-resistant recovery path is the pragmatic AAL2; if the data justifies AAL3, hardware WebAuthn is the only option on this list. Either way, document the assurance of the account (enrollment, recovery, session) not the prompt count.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Deploy TOTP safely while stating its limits.

Answer

TOTP is a shared-secret, time-based one-time password (RFC 6238, built on HOTP RFC 4226). It stops password replay and credential stuffing. It does not stop a real-time phishing proxy that relays a typed code inside the 30-second step. Deploy it as a fallback or transitional factor, and migrate users to WebAuthn.

Enrollment. Generate a 160-bit secret (20 bytes) from a CSPRNG. RFC 4226 §4 recommends 128 bits minimum, 160 bits recommended. Base32-encode it for the otpauth URI, deliver it once over TLS in an authenticated session, and require the user to enter a current code before the factor is active. Never log the secret or the otpauth URI.

Storage. Encrypt the secret at rest with a KMS key. Limit decrypt access to the auth service. Keep it out of session tokens, error messages, and analytics.

Validation. Use a 30-second step (RFC 6238 §4.2 default). Accept T-1, T, and T+1: a ±1 step window, 90 seconds total. RFC 6238 §5.2 allows a validation window for network delay. Consume each accepted (user_id, time_step) in a cache with TTL ≥ 90 seconds; reject a second use. Throttle to, say, 5 attempts per 30 seconds per user, then exponential backoff (1 s, 2 s, 4 s) or a temporary lockout. That throttle is a chosen policy: tune it to your risk.

Resync. If a user's clock drifts beyond ±1 step, do not widen the window. Require a recovery code or a second factor to re-enroll.

Notify and monitor. Send email or push on enrollment, reset, and fallback use. Alert on fallback rate, failed TOTP rate, and resync requests.

Migration. Offer WebAuthn. Keep TOTP as fallback and track the percentage of logins that use it.

ParameterValueSource / rationale
Secret length160 bits (20 bytes)RFC 4226 §4: 128 bits minimum, 160 recommended
Time step30 sRFC 6238 §4.2 default
Drift window±1 step (T-1, T, T+1)RFC 6238 §5.2 allows a window for network delay
Replay cache TTL≥ 90 scovers all accepted steps
Throttle5 attempts / 30 s per user, then 1 s × 2^n backoffchosen policy
Resyncrecovery code or second factor if drift > ±1avoid widening the window

Trace of the validation logic:

verify(secret, code, now, used, step=30, window=1):
  for w in [-1, 0, 1]:
    t = now + w*30
    if totp(secret, t) == code:
      if t in used: return False
      used.add(t); return True
  return False

Assume the code matches the T=now step. First call: w=-1 fails, w=0 matches, t=now is added to used, returns True. Second call with the same code: w=-1 fails, w=0 matches, t=now is already in used, returns False. That is the replay rejection.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Explain why WebAuthn resists real-time phishing proxies.

Answer

A strong candidate opens with the binding, not the ceremony. WebAuthn resists real-time phishing proxies because the authenticator signs a fresh challenge together with the browser-reported origin and a hash of the RP ID, and the RP verifies all three. A proxy on another origin cannot get a signature that names the legitimate RP, and cannot replay an old one.

Assumptions: the RP configures its RP ID correctly and verifies origin, rpIdHash, challenge, signature and flags; the browser and TLS trust store are uncompromised; the RP does not fall back to a phishable factor.

Mechanism. At registration the authenticator creates a key pair scoped to the RP ID. At authentication the RP sends a fresh challenge. The browser builds clientDataJSON containing type (webauthn.get), the challenge, and the origin of the calling page. The authenticator data includes rpIdHash = SHA-256(RP ID), flags (UP, UV, etc.), and signCount. The authenticator signs authenticatorData || SHA-256(clientDataJSON) with the credential private key. The server checks the challenge is fresh and expected, the origin matches its own, rpIdHash matches its RP ID, the signature verifies, and the flags meet policy.

Why a proxy fails. Suppose the victim visits evil.com, which proxies to legit.example.com. The browser's origin is https://evil.com, so clientDataJSON.origin is https://evil.com. The browser will only use an RP ID that is a registrable domain suffix of that origin, so rpIdHash is SHA-256("evil.com"), not SHA-256("legit.example.com"). The real RP rejects on origin and rpIdHash. The proxy cannot ask the authenticator for the legit.example.com credential because the browser enforces the suffix rule. It cannot edit clientDataJSON after signing because the signature covers it. Relaying a previously captured assertion fails because the challenge is fresh and the server validates it.

TOTPWebAuthn
proxy relays code/assertionsucceeds within the 30s windowfails: origin and rpIdHash mismatch
replayfails if server tracks used codesfails: fresh challenge
what binds the responseshared secretorigin + RP ID + challenge, signed

Failure modes. WebAuthn only protects the WebAuthn path. If the RP still offers password or TOTP fallback, the proxy uses that. A WebAuthn-unaware login page can be proxied unchanged. Enterprise MITM or TLS-terminating proxies with a trusted root can re-serve the real origin, so the browser reports https://legit.example.com and will sign for that RP ID. Origin binding is only as strong as the browser's view of the origin. Endpoint malware or a browser extension with WebAuthn access can also sign. If the RP ID is the eTLD+1, a compromised sibling subdomain can sometimes be used. Server bugs, accepting any origin or skipping rpIdHash, defeat the whole thing. User verification (UV) is local intent, not phishing resistance; it stops a stolen authenticator, not a proxy.

What would change the picture: if the RP does not verify origin and rpIdHash, or if the browser's TLS trust is subverted so the proxy is the real origin, the guarantee collapses to whatever origin the browser believes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Explain biometrics in multi-factor cryptographic authentication.

Answer

Assume the verifier is a web relying party using WebAuthn Level 2/3 and the authenticator is a FIDO2/CTAP2.1 device with built-in user verification. The short answer: the biometric never leaves the authenticator. It is a local user-verification gesture that unlocks a private key; the verifier gets a signed assertion with a UV flag, not a template.

Registration: the RP sends PublicKeyCredentialCreationOptions with rp.id, a random challenge, user.id, pubKeyCredParams, and userVerification. The authenticator generates a key pair, stores the private key in its secure element, and returns the public key, credential ID, and attestation. If UV is required, the biometric gates key creation.

Authentication: the RP sends PublicKeyCredentialRequestOptions with a fresh challenge, allowCredentials, and userVerification. The authenticator matches the biometric locally, unlocks the private key, and signs authenticatorData || SHA-256(clientDataJSON). authenticatorData contains rpIdHash, flags, and signCount. The RP verifies the signature, challenge, origin, RP ID hash, flags, credential ID, and policy.

The flags byte is where biometrics show up cryptographically. Bit 0 is UP (user present), bit 2 is UV (user verified). UV=1 means the authenticator verified the user via biometric or PIN. The RP must check UV if it needs biometric assurance. Other bits: BE/BS for backup eligibility/state, AT for attested credential data, ED for extension data.

CheckWhat the RP doesWhy it matters for biometrics
ChallengeCompare clientDataJSON.challenge to the stored random valuePrevents replay of a signed biometric assertion
OriginCompare clientDataJSON.origin to the RP's originPrevents phishing sites from collecting assertions
RP ID hashCompare authenticatorData.rpIdHash to SHA-256(rp.id)Binds the key to the RP
UV flagRequire authenticatorData.flags.UV == 1 when userVerification: "required"Ensures biometric/PIN actually happened
SignatureVerify with the stored public key over `authenticatorData
Sign countCompare to stored value; flag if not increasingDetects cloned authenticators

Trace: a successful assertion. RP sends challenge C. User touches sensor. Authenticator matches fingerprint, unlocks key K. It builds authenticatorData = rpIdHash || flags(UP=1, UV=1) || signCount. It computes clientDataJSON = {type:"webauthn.get", challenge:C, origin:"https://example.com"}. It signs authenticatorData || SHA-256(clientDataJSON) with K. RP receives credential ID, authenticatorData, clientDataJSON, signature. RP recomputes SHA-256(clientDataJSON), verifies the signature over authenticatorData || that hash with the public key, checks challenge, origin, rpIdHash, UV=1. If all pass, authentication succeeds.

Trade-offs. Biometrics are convenient and hard to phish because they stay local. But they are not secrets: you cannot rotate a fingerprint. If the template or matcher is compromised, the attacker can unlock the key. So the biometric is an activation factor, not a network credential. A PIN is a fallback for accessibility and coercion resistance; a biometric can be compelled, a PIN can be withheld. CTAP2.1 exposes retry counters: authenticatorGetUVRetries for built-in UV, authenticatorClientPIN with getPinRetries for PIN. YubiKey Bio Series, for example, documents 5 built-in UV attempts and 8 PIN attempts before lockout. The spec does not fix those numbers; the authenticator reports them. WebAuthn's userVerification default is "preferred", so an authenticator may return UV=0. If the RP needs biometric assurance, set userVerification: "required" and check the UV flag. The timeout is a hint, recommended 15s-120s.

Failure modes. Template storage compromise: if the secure element is broken, the attacker can extract or spoof the template. Detect with attestation, device integrity checks, and monitoring for anomalous UV. Replay: a stale challenge lets an attacker reuse a signed assertion. Detect by enforcing single-use random challenges and short timeouts. Phishing: a fake origin cannot get a valid assertion because the signature covers origin and rpIdHash. Fallback downgrade: if the RP accepts UV=0, a stolen PIN or unattended device may pass. Detect by policy checks and logging the UV flag. Retry lockout DoS: an attacker can intentionally fail biometrics to lock the device. Detect by monitoring lockout events and providing PIN fallback. Presentation attack: a fake finger or face may fool the sensor. The RP cannot verify liveness remotely; it relies on the authenticator's certification and sensor quality.

Deeper detail. CTAP2.1 authenticatorGetInfo returns uvModality (fingerprint, face, etc.) and preferredPlatformUvAttempts. The RP can use attestation to learn the authenticator model and its UV capabilities. For high-value operations, require UV and consider requiring a PIN-only authenticator if biometric coercion is in scope. Do not claim the biometric remotely proves civil identity or cannot be shared; it proves the authenticator's local user-verification policy was satisfied.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Implement secure WebAuthn credential registration.

Answer

Assumptions: consumer passwordless migration, RP ID example.com, server-side sessions, no enterprise attestation requirement. Registration is two calls: POST /webauthn/register/begin returns options, POST /webauthn/register/finish verifies and stores.

Begin. Generate the challenge with a CSPRNG: the spec requires ≥16 bytes; use 32. Store it server-side keyed by session, single-use, 5-minute TTL. Return:

JSON
{
  "rp": { "id": "example.com", "name": "Example" },
  "user": { "id": "<base64url, <=64 bytes>", "name": "ada@example.com", "displayName": "Ada" },
  "challenge": "<base64url 32 bytes>",
  "pubKeyCredParams": [
    { "type": "public-key", "alg": -7 },
    { "type": "public-key", "alg": -257 }
  ],
  "authenticatorSelection": { "residentKey": "preferred", "userVerification": "required" },
  "attestation": "none",
  "timeout": 60000,
  "excludeCredentials": [ { "type": "public-key", "id": "<existing cred id>" } ]
}

-7 is ES256 (ECDSA P-256/SHA-256), -257 is RS256. excludeCredentials stops the same authenticator registering twice for one account.

Finish. Verify in this order, fail closed on the first mismatch:

  1. clientDataJSON.type === "webauthn.create".
  2. clientDataJSON.challenge equals the stored challenge (base64url-decoded), then delete it. This is the anti-replay check: without single-use, a captured response replays.
  3. clientDataJSON.origin equals the expected origin exactly. endsWith matching lets evil-example.com through.
  4. authenticatorData.rpIdHash === SHA-256(rpId). Binds the credential to your RP so one minted for another site can't be used.
  5. Flags: UP (0x01) set; UV (0x04) set because we required it. UV is what makes this "user verified" (biometric/PIN) rather than just "user present" (a tap).
  6. Parse the CBOR attestationObject; with fmt: "none" there is no attestation statement to verify, but you still parse authData for the credential ID and COSE public key.
  7. Reject if the credential ID already exists (unique index).

Store credential ID, COSE public key, signCount, transports, AAGUID, BE/BS flags. Biometric material never leaves the authenticator, so there is nothing to store.

Trade-off: attestation policy

policywhat you getcost
noneno attestation; best privacycan't identify authenticator model
indirectanonymized attestation via a CAstill can't pin a model
directfull attestation, AAGUID/modelprivacy loss; you manage FIDO MDS trust anchors
enterpriseenterprise attestation even when anonymizedneeds enterprise policy + MDS

Deciding criterion: use none for consumer passwordless. Most authenticators return self-attestation anyway and attestation adds friction. Use direct/enterprise only when you must allowlist hardware (e.g. only YubiKey 5 series), and then you own MDS trust-anchor rotation.

Failure modes

  • Challenge reuse: if the challenge isn't single-use, a captured registration replays. Detect: alert when a stored challenge is consumed twice.
  • Origin substring match: evil-example.com passes. Detect: unit test with a hostile origin.
  • Duplicate credential ID: attacker registers their own authenticator to a victim account. Detect: unique-constraint violation → alert.
  • Sign count: don't rely on it for passkeys. Synced credentials (BE flag 0x08) report signCount 0 forever, so a non-increasing counter is not evidence of cloning.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Validate a WebAuthn authentication assertion.

Answer

Core answer (what you say first)

The assertion is a signed statement from the authenticator. Verify it server-side, fail closed on the first mismatch, and do the checks in this order:

  1. Look up the stored credential by credentialId (or by user handle in a discoverable flow). If it doesn't exist, reject: never fall back to another account.
  2. Check the challenge matches the one you issued for this ceremony and hasn't been consumed. Delete it before doing anything else.
  3. Parse clientDataJSON: type must be "webauthn.get", challenge must equal the base64url of your issued challenge, and origin must equal your expected origin exactly (scheme + host + port).
  4. Check crossOrigin is absent or false unless you deliberately support iframes; if you do, check topOrigin against an allowlist.
  5. Compute SHA-256(rpId) and compare to the first 32 bytes of authenticatorData.
  6. Verify the signature over authenticatorData || SHA-256(clientDataJSON) using the stored public key and its COSE algorithm (ES256 = -7, RS256 = -257, EdDSA = -8).
  7. Check the flags byte: UP (0x01) must be set; UV (0x04) must be set if you required user verification.
  8. Update the sign counter only if the credential is not backup-eligible.

Why each check exists

  • Challenge: prevents replay. Without it, one captured assertion is valid forever. Issue at least 16 bytes of entropy, single-use, with a short TTL (5 minutes is typical).
  • Origin: stops a phishing page on evil.example from relaying an assertion minted for good.example. The browser sets origin; the RP must check it because the browser will sign for whatever origin the user visits.
  • RP ID hash: binds the credential to your domain, so a credential registered for example.com can't be used at sub.other.com.
  • Signature: proves possession of the private key, which never leaves the authenticator.
  • UP: proves a human gesture (touch, PIN) happened.
  • UV: proves the gesture verified the user (biometric or PIN), not just presence.

Failure modes

  • Counter rollback: only meaningful for single-device credentials. Platform authenticators (Touch ID, Windows Hello) and synced passkeys report signCount = 0 always, and backup-eligible credentials (BE flag 0x08 set) have no meaningful counter. Treat a rollback on BE=1 as noise; treat it on BE=0 as a possible clone and force re-authentication.
  • Challenge reuse: if you don't delete the challenge atomically, a race lets two requests consume it. Use a single-use store with delete-on-read.
  • Challenge expiry: a 5-minute TTL with a client clock 10 minutes off fails. Detect via challenge_expired log spikes; cost is a user-visible retry.
  • Origin mismatch behind a proxy: if TLS terminates at a proxy and the app sees http://internal, the origin check fails. Detect via a spike in origin-mismatch rejections; fix by trusting the forwarded host only from known proxies.

What changes the decision

  • If the credential is backup-eligible (BE=1), skip counter checks entirely.
  • If you required UV at registration, require it at authentication; otherwise preferred is fine.
  • If you support cross-origin iframes, check topOrigin, not just origin.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Choose between synced passkeys and device-bound security keys.

Answer

Answer

Depends on the population and the transaction. For a broad workforce rollout where AAL2 is enough, I ship synced passkeys: they're the only way to get phishing-resistant auth to scale without shipping hardware. For privileged accounts, high-blast-radius actions, or anywhere AAL3 is required, I ship device-bound keys. Most orgs end up doing both.

Assumptions: WebAuthn/CTAP2, modern browsers, RP ID is the same origin. The sync fabric is a platform provider: iCloud Keychain, Google Password Manager, Windows Hello backed by a Microsoft account, not a third-party password manager.

Mechanism

Both are WebAuthn credentials. The authenticator generates a keypair scoped to the RP ID and signs a challenge over the origin. That origin binding is what makes them phishing-resistant: a lookalike domain gets a signature that won't verify.

The difference is where the private key lives and what the RP can see.

Synced passkey: the key is generated on one device, wrapped under a key derived from the user's platform account, and synced through the provider's cloud. The RP sees the BE (backup eligible) flag = 1 and BS (backup state) = 0 or 1 in the authenticator data. The RP cannot tell which device holds the key or how many copies exist.

Device-bound key: the key is generated in the authenticator's secure element and never leaves. BE = 0. The RP knows the credential is bound to one physical device.

NIST SP 800-63B allows syncable authenticators at AAL2 when the sync meets its requirements; AAL3 requires a non-exportable key.

Trust extension

For synced passkeys, the sync fabric's account security is now inside your auth boundary. If the user's iCloud or Google account is compromised (password reuse, a stolen session cookie, a support-desk social-engineering call) the attacker can pull the passkey onto their own device and authenticate as the user. From the RP's side that looks identical to a legitimate login: BE=1, BS=1, valid signature. No signal.

Account recovery is the soft spot. If the platform lets a user reset their account password over SMS or a support call, that path is now a path to your passkeys.

Failure modes

  1. Sole device-bound key lost. User is locked out. Without a backup key or a recovery flow, you're doing identity proofing to re-enroll. Detection: user reports it. Mitigation: issue two keys, or keep a synced passkey as fallback.

  2. Cloud account compromised. Attacker syncs the passkey to their device. Detection during authentication: none. Detection at registration: a new credential ID and AAGUID. Alert on new credential registration for privileged accounts. Mitigation: require a device-bound key for high-value actions, or step up with a separate factor.

  3. Sync fabric outage or account lockout. User can't get the passkey onto a new device. Availability failure, not security, but it drives support load.

Decision table

Synced passkeyDevice-bound key
Key locationProvider cloud, E2E encryptedSecure element, non-exportable
BE flag10
AALAAL2 if the fabric meets requirementsAAL3 with PIN/biometric
RecoveryPlatform account recoveryBackup key or re-enrollment
Cloud account compromiseIn scopeOut of scope
Device lossSurvivableLockout without backup
Rollout costLowProcurement, shipping, support

What would change my answer

  • Threat model includes the user's cloud account (journalist, admin with high blast radius): device-bound.
  • Large, low-risk population: synced passkeys.
  • AAL3 required by policy: device-bound.
  • Platform has no sync fabric: device-bound or third-party.

Close

Expose BE/BS to your risk engine so you can step up when a credential is synced. Allow more than one credential per account. For privileged accounts, require a device-bound key: don't let the sync fabric be the only thing between an attacker and your admin console.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design authenticator enrollment, replacement, and removal.

Answer

Assumptions. Workforce SaaS, WebAuthn (FIDO2) as the primary authenticator, TOTP as fallback, every account has at least one recovery method. The numbers below are example policy, not standards; the standards are named where they apply.

Core answer. Treat enrollment, replacement and removal as three separate ceremonies, each gated on a fresh authentication rather than on the session cookie. The rule that decides the design: a session proves possession of a token, not of an authenticator. So every change requires a new assertion from an existing credential, made within the last 5 minutes, at AAL2 (NIST SP 800-63B: two distinct factors; reauthenticate at 12 hours or 30 minutes idle).

Enrollment: the server issues a single-use challenge bound to the account's user handle and RP ID; the authenticator returns attestation; you verify origin, RP ID hash and challenge, then store the credential ID, public key and sign counter. Replacement is add-then-remove, never an in-place swap: enroll the new credential, verify it, then remove the old one, so a failed ceremony leaves the account usable. Removing the last recovery-capable authenticator is blocked outright; the user must add a replacement first.

Why step-up works. A stolen cookie lets an attacker call your API, but it cannot produce a WebAuthn assertion: that needs the private key on the hardware. Requiring a fresh assertion forces the attacker to also hold the physical key.

Ceremony trace (enrollment).

  1. Client POSTs /webauthn/register/begin with the session.
  2. Server checks the session is ≤5 min old and at AAL2, else 401.
  3. Server returns challenge (32 random bytes), rpId, user.id, pubKeyCredParams.
  4. Authenticator creates a keypair, returns attestation + credential ID.
  5. Server verifies challenge matches, origin and rpId hash are correct, then persists credential ID + public key + counter=0.
  6. Server notifies existing channels; the new credential is active.

Trade-offs.

OperationRequired proofDelay / reviewNotification
Enroll newFresh assertion, ≤5 minnoneemail + push
ReplaceEnroll new, verify, remove oldnoneboth channels
Remove non-lastFresh assertionnoneboth
Remove last recoveryblocked; add replacement first——
New device + new geofresh assertion + out-of-band24 h cooling-offimmediate

A delay beats a review queue when the user is self-service and volume is high; a review queue beats a delay when the account is privileged and a human can judge context. For a single-factor account you cannot step up at all: fall back to out-of-band verification plus the 24 h cooling-off.

Failure modes.

  • Attacker enrolls their own key. Detected by the notification to existing channels and the audit entry; respond by revoking that credential ID, revoking sessions, forcing reauth.
  • Challenge replay. Single-use nonce, 60 s TTL, reject reuse.
  • Cloned authenticator. Sign counter must strictly increase; a non-increasing counter flags a clone.
  • Lockout. Last-factor protection plus pre-issued recovery codes.

What changes the decision: if the account has no second factor to step up with, the whole ceremony collapses to out-of-band verification and a delay. Design that path explicitly rather than discovering it in an incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design account recovery that does not nullify MFA.

Answer

Say this first (60-120 seconds)

Recovery is re-binding a factor, not resetting a credential. Ask one question out loud: which factor does a normal login demand, and can the recovery path get an attacker past it? If yes, you built MFA plus a help desk.

State your assumptions: the owner holds something bound before the incident that the attacker does not control (a second enrolled authenticator, printed recovery codes, a verified channel); the account is worth a targeted campaign; a human can sit in the loop for the residue. Then work a ladder:

  1. A second enrolled authenticator: same assurance, seconds to use, no human. This path only exists if enrollment requires two factors up front - don't let users finish setup holding one.
  2. Single-use recovery codes: 128 bits from a CSPRNG, encoded as 26 Crockford base32 characters (26 * 5 = 130 bits of alphabet, so 128 bits fit), shown once, stored salted and hashed, compared in constant time, deleted on first use. SP 800-63B files these as look-up secrets and sets the bar at 112 bits of entropy when the code is the only factor.
  3. Delayed human re-proof: evidence beyond public records, 24-hour hold, limited session, privileges rebuilt rather than restored. This is identity proofing (SP 800-63A), not authentication - after it, the account is new from an assurance standpoint.

Knowledge-based questions, and a "reset MFA" button in email, are bypasses wearing recovery's name.

Mechanism: why the delay works, and when it doesn't

A delay is not a control by itself; it is a window for the real control, the owner's veto over a channel bound before the incident. Delay with no independent notification is theater. That's also why a recovery email link must only start the clock, never complete the reset: if the mailbox can reset MFA, the MFA is decorative, because mailbox compromise is the precondition for most account takeovers.

Freeze the factor set for that same window. If a recovered session can remove the victim's FIDO key or change the recovery channel, the attacker turns a temporary takeover into permanent eviction. Sessions bound before recovery get revoked; revoking old authenticators immediately is a trade-off, not a rule - it locks out the real owner if the recovery was the attacker's doing.

Choosing a path

PathAssurance vs normal loginTime to accessAttacker costOps cost
Second enrolled authenticatorequalseconds, self-servicesteal an enrolled key/device~0
Recovery code, 128-bit, single uselower: not device-bound, lives in a drawer or password managerseconds, self-servicesteal the printed list or the vault~0
Delayed re-proof (agent + evidence)low until the hold expires, then raised by the owner's veto channel24 h hold + 15 min agentimpersonate the owner to a human, harvest PII, survive callback15 min agent time, roughly USD 8-15 fully loaded (illustrative)

Failure modes and their signals

FailureMechanismDetection
Helpdesk impersonationanswers harvested from a third-party breach dumpaccepted-re-proof rate per agent against peer median; recovery requests in the 30 days after the claimant's email appears in a dump; callback number changed inside the same ticket
Code theft from the vault or notesattacker with mailbox or password-manager accesscode use from an ASN/device never seen on the account; two codes presented for one event
Recovery used to strip MFAattacker recovers, then unenrolls the FIDO keyauthenticator removed inside the hold window; prevent it by freezing the factor set
Denial of service by recovery spamrepeated re-proof requests lock the accountrecovery attempts per account; throttle the recovery path only, never lock the account
Enumeration oracledifferent body or timing for known vs unknown emailsidentical response and comparable latency; alarm on unknown-identifier volume

Numbers worth defending

Online guessing is bounded by throttling, not entropy: 5 code attempts per account per hour against 10 issued codes is 50 guesses/hour on a 2^128 space. SP 800-63B's cap of 100 consecutive failed attempts per account is a ceiling, not a target. Coverage arithmetic shows where to invest: 1M accounts, 4% needing recovery once a year = 40,000 events; with a second factor or codes in place for 65% of them, about 14,000 reach a human, which is 14,000 * 15 min = 3,500 agent-hours, roughly 2 full-time agents. Moving second-factor enrollment from 35% to 70% removes about 7,000 of those events, near 1,750 agent-hours.

When this design is wrong

A managed workforce with MDM and hardware keys should skip printed codes: they end up in the same mailbox the attacker already owns, so re-enrollment after an in-person ID check beats them. A flat 24-hour hold is wrong for safety-critical access such as on-call paging - hold the privileges (payments, factor changes, data export) and keep read and paging live. If the identity is the SSO root for other tenants, scope the delay by blast radius, not by account tier.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Implement recovery-code issuance and use.

Answer

Core answer (first 90 seconds)

Recovery codes are one-time authentication secrets, so treat them like passwords you cannot rehash on the user's behalf: high entropy at generation, a verifier-side representation at rest, and atomic single-use at redemption. Concretely: issue 10 codes, each 10 characters of Crockford base32 (32 symbols, 5 bits each) = 50 bits of entropy. Store HMAC-SHA-256(pepper, code) as a lookup index and Argon2id(code) as the verifier; the pepper lives in KMS, not the database. Redeem with one conditional UPDATE so a code is consumed exactly once. Rate-limit per account and per IP, returning identical responses for unknown accounts. On success, rotate the session, invalidate the others, and notify out-of-band.

Why each step works

Entropy: online guessing is bounded by rate limiting, so 50 bits is far more than enough online. The binding constraint is offline attack if the store leaks. 2^50 ≈ 1.1e15. A fast hash at ~1e9 guesses/sec (labelled assumption) cracks that in ~13 days if the attacker also has the pepper; without it, never. That is the deciding criterion for hash choice.

formatentropyoffline cost if store leaks
8-digit numeric26.6 bits1e8 guesses, seconds
10-char base3250 bits1.1e15, ~13 days at 1e9/s with pepper
16-char base3280 bitsinfeasible

Trade-off: a slow KDF (Argon2id at ~50–100 ms) makes each verification cost that much, and you cannot scan all 10 codes per attempt, so index by HMAC first, then verify the matched row with Argon2id. If you cannot separate the pepper from the store, make Argon2id the primary verifier instead.

Consumption

SQL
UPDATE recovery_codes
SET used_at = now()
WHERE id = $1 AND user_id = $2 AND used_at IS NULL
RETURNING id;

Zero rows returned means already used or wrong owner. This is the atomicity guarantee; a SELECT-then-UPDATE lets two concurrent requests both pass and mint two sessions.

Rate limiting without enumeration

Return the same body and status for "no such account" and "wrong code", and key the limit on the submitted identifier so an attacker cannot distinguish. Log the attempt server-side only.

Failure modes and detection

  • 8-digit numeric codes with no rate limit: 1e8 space, at 1000 req/s distributed ≈ 28 hours to exhaust. Detect: alert on attempts-per-account.
  • Enumeration: differing error strings or timing. Detect: response-diff tests in CI.
  • Double-spend race: two sessions from one code. Detect: audit rows where a code has more than one session created.
  • Codes in logs: they must never hit request-body logging or analytics. Detect: grep the pipeline for the code field.
  • Partial regeneration: old codes stay valid. Detect: assert every code in the old set has used_at set.

Notification and regeneration

Send the alert to the account's verified email, not the session that redeemed: an attacker holding a stolen session should not be able to suppress it. On suspected disclosure, mark the whole set used and issue a fresh one; the user sees only the remaining count, never the codes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Plan lost-device handling for passkey-first accounts.

Answer

Core answer

Assume a WebAuthn Level 2 relying party where passkeys are the only first factor and there is no password fallback. The plan has three parts: make loss survivable at enrollment, let a signed-in user revoke and re-bind, and make total loss a slow, notified, re-proofed recovery rather than a help-desk override.

The fact that decides the design: you cannot tell from a credential alone whether it is device-bound or synced, and you cannot use the signature counter to detect a copied synced passkey. Record what the authenticator reports at registration and re-check it on every assertion.

Mechanism

WebAuthn scopes each credential to an RP ID: your registrable domain. The credential ID is an opaque handle up to 1023 bytes; the user handle (user.id) is up to 64 bytes and must not carry PII. The authenticator data flags byte sits at offset 32 and carries UP (0x01), UV (0x04), BE (0x08) and BS (0x10):

JavaScript
const flags = new Uint8Array(authenticatorData)[32];
const backupEligible = (flags & 0x08) !== 0; // credential can be synced
const backupState    = (flags & 0x10) !== 0; // credential is synced now

BE=1 means the credential is syncable; BE=0 means device-bound. BS says whether it is synced right now. Both can flip after registration, so evaluate them per assertion.

Synced passkeys typically report a signature counter of 0 forever, Apple's iCloud Keychain does not increment it, so counter-based clone detection is dead for most of your users. Don't build on it.

Enrollment

Require a second credential before the first is trusted for recovery. NIST SP 800-63B requires recovery to meet the same assurance level as primary authentication, so one passkey plus a help-desk call is out of policy. Offer, in order: a second passkey on another device, a hardware security key, then single-use recovery codes (128 bits of entropy, Argon2id-hashed at rest, shown once).

TypeBEKey lives inSurvives device loss
iCloud Keychain1Apple ID, E2E encryptedyes, until the Apple ID is lost
Google Password Manager1Google accountyes, until the Google account is lost
1Password / Dashlane1vendor vaultyes, until the vault is lost
YubiKey0the key itselfno
Windows Hello0TPM on the machineno

Inventory and revocation

Show every credential with its AAGUID, creation date, last-used timestamp and BE/BS. Revocation deletes the credential ID from your table, then kills server-side sessions, refresh tokens and OAuth grants: deleting the credential alone leaves live sessions.

Total loss

WebAuthn defines no recovery; it is an RP concern. Flow: identity proofing, notify every registered channel, hold the replacement credential inactive for a delay window (24-72 h) during which the real user can cancel, then bind it and revoke everything else.

Trade-offs

Delay windows cost support tickets and frustrate genuine users; shorten them only when a second independent factor exists. Recovery codes are cheap but get phished and stored in plaintext notes. A second hardware key is strongest and has the lowest enrollment completion.

Failure modes

  • Attacker holds the synced passkey after a cloud-account compromise. Detect with impossible-travel on assertion, a BE=1 credential on a new AAGUID, or a recovery event.
  • The recovery flow becomes the weakest link. Detect by alerting on any recovery that completes without a delay window or from a new ASN.
  • Orphaned credential: the user deletes the device but the synced key survives. Detect via last-used timestamps in the inventory.
  • RP ID migration: credentials are domain-scoped, so moving domains invalidates every passkey. Detect at deploy time with a canary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design risk-adaptive authentication without hidden downgrade.

Answer

Assumptions I'd state first: OIDC/OAuth 2.0 web app; NIST SP 800-63B AAL2 as the baseline for any authenticated session, AAL3 (phishing-resistant, WebAuthn/FIDO2) for high-value actions; the risk engine is advisory and cannot itself grant access.

Core answer (first 90 seconds)

The design has one invariant: policy sets a floor, risk can only raise it. Every action maps to a required assurance level. The risk engine produces a score; the enforcement point takes max(policy_floor, risk_derived). That single max is what makes downgrade impossible: there is no code path where a low score subtracts from the requirement.

Python
# Python 3.12
POLICY_FLOOR = {"read_profile": 1, "change_email": 2, "wire_transfer": 3}

def required_aal(action: str, risk: float) -> int:
    floor = POLICY_FLOOR[action]
    risk_aal = 3 if risk >= 0.8 else 2 if risk >= 0.3 else 1
    return max(floor, risk_aal)   # risk can only raise

Trace it: required_aal("read_profile", 0.95) → floor 1, risk_aal 3, returns 3. required_aal("wire_transfer", 0.0) → floor 3, risk_aal 1, returns 3. A perfect-looking session never drops a wire transfer below AAL3. That property is testable: assert required_aal(a, r) >= POLICY_FLOOR[a] for all inputs.

How the score is computed

Logistic model over signals; each contributes log-odds, score = sigmoid(sum). Thresholds at 0.3 and 0.8.

signalexamplelog-odds
new devicedevice_id unseen 30d+1.5
impossible travel2 logins 9,000 km apart in 20 min+3.0
breached credentialHIBP match+2.5
known device + ASNseen 30d−1.0

Negative signals lower the score only: never the floor. That distinction is the whole point.

Step-up protocol

Use RFC 9470. Return 401 with WWW-Authenticate: Bearer error="insufficient_user_authentication", acr_values="aal3". The client re-authenticates with WebAuthn and gets a token carrying the acr claim. The resource server checks acr, not the score.

Failure modes and detection

  • Hidden downgrade. A "remember this device" cookie sets risk to 0 and some handler reads risk instead of required_aal. Detect: property test over all (action, risk) pairs, plus an alert whenever a granted acr is below the action's floor.
  • Signal spoofing. Attacker copies UA and device_id. Detect: a device_id seen with 50 distinct user_ids in a day; step-up rate per device cohort.
  • False positives. Corporate VPN egress triggers impossible travel. Measure challenge rate, target under 5% of sessions, and let users clear it with WebAuthn re-auth, never a weaker factor.
  • Bias. If a cohort's challenge rate is 3× baseline with no fraud lift, the signal is proxying for something else. Monitor step-up and denial rates by cohort.

Trade-offs

optionwhencost
step-upaction reversible, session can re-authfriction, abandonment
denyirreversible or high blast radiussupport load
allow + monitorread-only, low sensitivitydetection lag

Deciding criterion: reversibility and blast radius. Money movement denies; profile reads allow with audit. Version thresholds, keep device fingerprinting minimal, and show users their security activity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Implement step-up for a high-risk transaction.

Answer

Assumptions first. Web app with server-side sessions, a risk engine that scores each sensitive action, and users who may have enrolled a passkey, TOTP, or neither. I'll use "change payout bank account" as the high-risk action. Figures are illustrative.

The 90-second answer. Step-up means: when risk crosses a threshold, pause the action, require a fresh authentication of a strength matched to the risk, bind that authentication to the exact action and session, and consume it once. Never trust session age or a client-side flag.

Risk decision. I'd set bands: score < 40 → proceed. 40–70 → step-up with TOTP (6-digit, 30s window). > 70 → WebAuthn assertion with userVerification: "required" (passkey/biometric). If the user has no factor at that strength, block and route to support: do not silently downgrade. Freshness: the authentication must have happened within the last 5 minutes; a session that's been open for 8 hours is irrelevant.

Mechanism. Server creates a row:

step_up_challenges(
  id            uuid primary key,
  user_id       uuid,
  session_id    uuid,
  action_type   text,
  action_hash   bytea,   -- sha256 of canonical JSON params
  expires_at    timestamptz,  -- now() + 120s
  consumed_at   timestamptz
)

Client completes the factor. Server verifies it, then issues an opaque 256-bit step-up token tied to id. Client submits the original action with that token. Server consumes atomically:

SQL
UPDATE step_up_challenges
SET consumed_at = now()
WHERE id = $1
  AND consumed_at IS NULL
  AND expires_at > now()
  AND session_id = $2
  AND action_hash = $3;
-- if rowcount = 0, reject

Then executes the action in the same transaction.

Why this defeats the attacks. Replay: the token is single-use; a second UPDATE matches zero rows. Parameter substitution: action_hash is computed over the exact amount, payee, and currency, so a token minted for $100 to Alice fails for $10,000 to Bob. Session theft: session_id binding means a token lifted from another session is useless. Expiry: 120s bounds the window.

Trade-offs.

approachassurancefrictionuse when
re-enter passwordlow (reused, phishable)lowlow-risk, legacy
TOTPmedium (real-time phishable)mediummedium-risk, broad devices
WebAuthn + UVhigh (origin-bound)medium-highhigh-risk, supported
fresh full sessionhigh but heavyvery highsession integrity suspect

Step-up is the wrong tool when the session itself is already compromised, if the attacker can also complete the factor, you need out-of-band confirmation or manual review. It's also wrong for low-value idempotent actions where friction outweighs the risk.

Failure modes and detection.

  • Replay attempt: second consume returns 409. Alert on consumed_at conflict count > 0 per user. Cost: one blocked action.
  • Parameter tamper: action_hash mismatch → 403. Metric step_up_hash_mismatch_total. Cost: user retries.
  • Concurrent tabs: both request step-up; one wins, the other gets "already used". Same detection as replay. UI should re-prompt.
  • Cancellation: challenge expires after 120s. Metric expired_challenges. Cost: cleanup only.
  • Downstream duplicate: retry after timeout executes action twice. Detect via idempotency key unique constraint on the action. Cost: financial. This is the one to get right.

Record the policy version, factor used, and challenge id in the audit log: never the secret.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Protect sessions after successful MFA.

Answer

What I'd say first

Assume a browser app with cookie sessions and MFA at login. The MFA ceremony and the session that follows are separate things. MFA proves the human at the keyboard right now; the session cookie is a bearer token that proves nothing once it's copied. So the job is: make the session unforgeable, make it revocable, and shrink the window where a stolen copy is useful.

Concretely: rotate the session ID at the authentication boundary, keep session state server-side behind a 256-bit opaque ID, set __Host- + Secure + HttpOnly + SameSite=Lax, and cap idle and absolute lifetime by assurance level. The rest is detail on those four.

Why rotation is the fixation fix

Session fixation works because the attacker picks the ID before login and the server keeps it after. Trace:

  1. Attacker plants sid=A in the victim's browser (subdomain XSS, or a link that sets the cookie).
  2. Victim logs in and passes MFA. Server marks session A authenticated.
  3. Attacker sends Cookie: sid=A. Server sees an authenticated session. MFA is bypassed with no credential theft.

Rotation breaks step 3: the record for A is deleted at login, so A resolves to nothing.

Python
# Python 3.12, Flask 3.0
@app.post("/login/mfa")
def mfa_verify():
    if not verify_totp(user, request.form["code"]):
        return "bad code", 401
    sessions.delete(request.cookies.get("sid"))   # kill pre-auth record
    sid = secrets.token_urlsafe(32)               # 256 bits, CSPRNG
    sessions.set(sid, {"uid": user.id, "aal": 2,
                       "created": now(), "last_seen": now()})
    resp = redirect("/")
    resp.set_cookie("__Host-sid", sid, secure=True, httponly=True,
                    samesite="Lax", path="/", max_age=43200)
    return resp

token_urlsafe(32) is 32 random bytes, so guessing isn't a threat. The __Host- prefix stops a subdomain from overwriting the cookie.

Lifetimes

NIST SP 800-63B sets the floor: AAL2 reauthenticate at least every 12 hours or after 30 minutes idle; AAL3 every 12 hours or 15 minutes idle. The step-up windows below are example policy, not the standard.

LevelIdleAbsoluteStep-up valid for
AAL230 min12 h5 min
AAL315 min12 h2 min

Sensitive actions (change password, enroll a factor, change payout account) require a step-up inside that window, recorded on the session record as aal plus a timestamp. A session idle for an hour shouldn't be able to add a new authenticator.

Trade-offs

Server-side sessions cost a store lookup per request and a Redis/DB dependency; that buys instant revocation. Stateless JWTs skip the lookup, but you can't revoke one without a denylist: the state you were trying to avoid. So JWTs fit badly for a session you must kill on password change.

Concurrent-use detection is the other trade-off. Two logins from different ASNs inside a minute is a real signal; the same user on Wi-Fi and LTE, or behind carrier NAT, is not. Alert-only by default, auto-revoke only for AAL3, and expect support tickets either way.

Failure modes and how you see them

  • Fixation: assert in tests that the session ID changes at login; log rotation events and alert if a pre-auth ID is ever seen authenticated.
  • XSS reading the cookie: HttpOnly blocks document.cookie; a strict CSP is the real control. Detect via session use from a new ASN.
  • CSRF: SameSite=Lax plus a per-session token; log origin mismatches.
  • Token in logs or Referer: Referrer-Policy: same-origin, scrub query strings, grep logs for the cookie name.
  • Stolen bearer session: it works until expiry, revocation, or step-up. That's the honest limit: don't tell users MFA protects a cookie copied afterward.

What would change this

If the client is a native app with no cookie jar, drop SameSite and bind the token to a device key (DPoP or mTLS) so it's useless off-device. If sessions must survive a store outage, you're trading instant revocation for availability, and should say so out loud.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Threat-model TOTP seed storage and verification.

Answer

What I'd say in the first two minutes

Assumptions: 160-bit seeds, HMAC-SHA1 per RFC 4226/6238, 30-second step, 6 digits, verifier accepts a ±1 step window. Adversary model: (a) read-only DB dump, (b) application-server compromise that can call the verifier, (c) a network attacker replaying a captured code. I defend (a) and (c) hard, and (b) only partially: a verifier that can mint codes for a user is a lost cause for that user, so the goal there is bounding blast radius and detecting it.

The core decision

You cannot hash the seed one-way. TOTP is HMAC-SHA1(seed, counter) truncated to 6 digits, recomputed on every login, so the server needs the seed in the clear at verification time. A bcrypt/argon2 password hash is useless: you'd have to store the seed reversibly. So the question is where the plaintext exists and for how long, not whether it's reversible.

Design: envelope encryption. Each seed encrypted with AES-256-GCM under a per-record DEK; DEKs wrapped by a KEK that lives in a KMS/HSM and never leaves it. Store ciphertext, nonce and wrapped DEK in the DB. The verifier asks the KMS to unwrap, derives the code, drops the plaintext. A DB dump alone yields nothing without KMS access, which is a separate IAM boundary and every unwrap is auditable.

Stronger variant: keep the seed inside the HSM and run the HMAC there, so plaintext never enters application memory. Costs latency and vendor lock-in; worth it for high-value accounts.

OptionStops DB dumpStops app-server compromiseCost
Plaintext, or reversible with an app keynononone
AES-256-GCM, KEK in KMSyesnoone KMS call per login
HMAC inside HSMyesmostlylatency, lock-in

Verification side

Rate-limit per account and per IP. With 6 digits and a ±1 window, 3 codes out of 10^6 are valid at any instant, about 3×10^-6 per guess, but unlimited guesses break that, so cap at ~5 attempts/minute and lock after N. Consume the accepted step: store the last-used counter and reject any code at or below it, which kills replay inside the 30-second window. Log every verification with account, step and result.

Failure modes

  • KMS unavailable: logins fail closed. Don't cache unwrapped DEKs to paper over it: that puts plaintext back at rest. Alert on unwrap error rate.
  • Backup or log leak: seeds must never hit logs; redact the enrollment secret and QR payload.
  • Key rotation: re-encrypt all seeds under a new KEK, online, with a version tag per record so old and new coexist during the sweep.
  • Compromise scope: if the KEK leaks, every seed is exposed. Rotate the KEK and force re-enrollment for affected users.

What would change my answer

If the threat model is only "DB dump" and there's no KMS, AES-256-GCM with a key in a secrets manager is a reasonable floor. If the accounts are low-value, HSM-resident HMAC is over-engineering.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Diagnose TOTP failures without weakening verification.

Answer

Core answer. TOTP verification compares an HMAC-derived code over a counter derived from wall-clock time: step = floor((T - T0) / X), with RFC 6238 defaults X = 30 s, T0 = 0, 6 digits, HMAC-SHA1. So a TOTP failure is almost always one of four things: client and server disagree on the step (clock drift), they disagree on the parameters (algorithm, digits, period, or shared secret), the code was already used (replay), or the code is simply wrong. Diagnose by narrowing to one of those four without widening the acceptance window: the window is the security budget.

Assumptions: the server clock is the reference; the client's reported time is untrusted input; the shared secret is at least 128 bits (RFC 4226 §4).

Mechanism. Drift maps linearly to step offset: a client 45 s fast with X=30 is 1–2 steps ahead. RFC 6238 §5.2 recommends a validation window of one time step: accept the current step and the immediately adjacent ones, ±1 step, 90 s of coverage. That absorbs ordinary NTP jitter (milliseconds) and small client drift, and nothing more. RFC 6238 §5.2 also requires that a code not be accepted twice, which is why you persist the last accepted step per user and reject any step ≤ it. That single integer is what makes replay impossible even inside the window.

The reason not to disclose near-misses: "expired" vs "invalid" vs "off by one step" are all oracles. An attacker holding a code from a previous step learns it was inside the window; an attacker who learns the offset can shift their clock to match. Return one generic failure for every cause.

Code (Python 3.12, stdlib only):

Python
import hmac, hashlib, struct

def hotp(key: bytes, counter: int, digits: int = 6) -> str:
    mac = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
    off = mac[-1] & 0x0F
    val = struct.unpack(">I", mac[off:off+4])[0] & 0x7FFFFFFF
    return str(val % 10**digits).zfill(digits)

def verify(key, code, now, last_step, period=30, window=1, digits=6):
    step = int(now // period)
    for s in range(step - window, step + window + 1):
        if s <= last_step:                 # replay guard
            continue
        if hmac.compare_digest(hotp(key, s, digits), code):
            return s
    return None

Trace. Key b"12345678901234567890" (the RFC 6238 test key), now = 59, last_step = 0. step = 59 // 30 = 1. Candidates: 0, 1, 2. Step 0 is skipped by the replay guard. Step 1 produces 287082, the 6-digit truncation of RFC 6238's T=59 vector 94287082, and matches, so verify returns 1.

Now the failure case. Server now = 1111111109 → step = 37037036. The client's clock is 45 s fast, so it computed step = 37037038. The server tries 37037035, 37037036, 37037037: all mismatch. The offset is +2 steps, roughly 60 s of drift, outside the ±1 window. Had the client been only 15 s fast (step 37037037), the window would have accepted it. That is the diagnosis: drift, not a wrong code, and the fix belongs on the client's clock, not the server's window.

Exposure arithmetic. 6 digits = 10^6 codes. A ±1 window admits 3 valid codes, so a random guess succeeds with probability 3/10^6 ≈ 3×10^-6. Widening to 24 hours (2880 steps) makes it 2880/10^6 ≈ 0.29% per guess: 960× worse. That is why the window stays at one step.

Throttling. RFC 4226 §7.3 requires a throttling mechanism. Concrete: 5 failures per account per 15 min, then exponential backoff; a separate per-source limit (e.g. 50/15 min); and a global abuse signal. Do not lock the account on failures alone: that turns guessing into a denial-of-service against the legitimate user. Back off, and route to the recovery path.

Triage.

SymptomLikely causeCheck
Failures spike across all users at one instantServer clock driftchronyc tracking offset; alert above 100 ms
Failures on one device/OS, client time off by tens of secondsClient clock driftclient-reported time, as a diagnostic only
One user fails consistently, others fineParameter mismatch or wrong secretstored enrollment (algorithm/digits/period) vs verifier config
Same code accepted twiceMissing or non-atomic last-step guardpersist last accepted step per user

What would change the decision. If failures cluster on one authenticator app version or one IdP, it is a client bug, not drift. If they cluster in time across all users, it is the server clock. If they cluster on one account, it is an attack or a stolen device: throttle and recover, do not widen.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Harden push-based MFA and plan migration.

Answer

Assumptions: Entra ID, Okta or Duo as the IdP; push is the dominant second factor; managed laptops, no smartcard mandate. If every user already holds a FIDO2 key, the answer is "turn push off": the interesting case is the mixed estate.

Core answer (first 90 seconds)

A push is a bearer approval. The IdP checks one thing: someone holding the enrolled device tapped Approve. The attacker never needs the device: they need the victim to tap. That gives three layers of fix, in order of how much they actually buy you:

  1. Make the tap carry information the attacker can't supply: number matching, or Duo Verified Push, where the user types the 3-digit code shown on the login page into the app.
  2. Make the tap scarce and short-lived: per-user push rate limits, a 15–20 s timeout, and binding each approval to one server-side transaction ID so an old approval can't be replayed.
  3. Make the tap unnecessary: WebAuthn/passkeys, which are origin-bound and therefore not relayable.

Be honest about layer 1: number matching is a speed bump, not a wall. A real-time phishing proxy relays the number to the victim, the victim types it into the genuine app, and the attacker still walks off with the token. Only origin-bound credentials close that path. Microsoft enabled number matching by default for Authenticator tenants in February 2023 and enforced it from May 2023, and reported a 99.9% drop in compromised accounts from fatigue attacks: vendor-reported, treat it as directional, not as a guarantee.

Controls, what each breaks, and what to alert on

ControlAttack path it breaksDetection signalCost
Number matching (Authenticator, Okta Verify number challenge)Blind approve; attacker must relay in real timepush→approve latency under ~3 s, or approve from a different ASN than the login~5 s per login
Duo Verified Push (type the on-screen code)Same, and forces the victim to look at the real screencode-entry failure rate per user~10 s per login
Push timeout cut to 15–20 sThe relay windowpushes expiring unansweredmore retries
Per-user rate limit, e.g. 3 pushes / 5 min then fall back to TOTPThe spam itselfmore than 3 pushes per user per hourhelpdesk tickets
Approval bound to a single-use server transaction IDReplay of a stale approvalsame challenge ID approved twicenone

Two signals catch the attack rather than the clumsy user: a push-to-success ratio above roughly 5:1 for one user in a 10-minute window, and a denied event followed by an approval within 60 s. That is the fatigue pattern, not a fat finger.

Migration

  • Week 1: number matching on, timeout cut, rate limit on, alerting live. No user comms beyond a one-line note.
  • Weeks 2–8: enroll WebAuthn, starting with admins, helpdesk, finance, and anyone with a recent push-denied event. That is where the risk is concentrated. Offer security keys to users without a biometric-capable device.
  • Weeks 8–16: make WebAuthn the default prompt and push the fallback. Keep TOTP or a hardware OTP for the accessibility case: no camera, no biometric, shared device. Removing push without a fallback locks people out.
  • After: disable push for the privileged cohort first, then the rest.

Sizing: 4,000 users, 3% privileged = 120 people. At 15 minutes each that is 30 engineer-hours for the entire first wave: cheap enough to do before the next incident.

Failure modes

  • Number matching relayed by a phishing proxy. Detect: login from a new ASN with a matching approval seconds later. Mitigate with WebAuthn, not more matching.
  • Rate limit locks out a user with a flaky phone. Detect: spike in TOTP fallback usage. Mitigate with a self-service re-enroll path.
  • Push disabled before enrollment finishes. Detect: spike in "can't log in" helpdesk tickets. Mitigate with cohort-by-cohort rollout and a rollback flag.
  • Passkey syncs to a personal iCloud or Google account on a shared machine. Detect: credential registered on an unmanaged device. Mitigate with device-bound, non-syncable credentials for privileged users, checked via attestation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design MFA policy for privileged administrators.

Answer

Assumptions. Cloud-first enterprise: Microsoft Entra ID (formerly Azure AD) as IdP, AWS Organizations, on-prem AD at Windows Server 2016 functional level or higher. Threat model: real-time phishing proxies (Evilginx-style), credential theft, session-token theft. Target: NIST SP 800-63B AAL3 for privileged roles.

Core policy. Require phishing-resistant MFA: FIDO2/WebAuthn security keys (YubiKey 5 series, ~$50–70) or TPM-backed platform authenticators (Windows Hello for Business). In Entra ID, Conditional Access → Grant → Require authentication strength → built-in Phishing-resistant MFA (needs Entra ID P1). On the FIDO2 authentication method policy, enable Enforce attestation and restrict enrolment to an AAGUID allowlist so only approved key models register. Admin accounts are cloud-only, separate from daily accounts, with no password sign-in path.

Why not push: FIDO2 binds the credential to the RP ID, so a proxy relaying the login cannot replay the assertion. Synced passkeys (iCloud Keychain, Google Password Manager) are AAL2 at best, 800-63B rev 3 bars syncable authenticators at AAL3, so they are not acceptable for Tier 0.

Step-up. Sensitive operations (IAM policy change, log deletion, key rotation) need a fresh AAL3 assertion. Entra ID: define an authentication context (c1–c25) and request it from the app with the OIDC claims parameter, {"access_token":{"acrs":{"essential":true,"value":"c1"}}}, or via SAML AuthnContextClassRef. In AWS, gate the API, not just the console:

JSON
{"Sid":"DenyIfNoMFA","Effect":"Deny","Action":"*","Resource":"*",
 "Condition":{"BoolIfExists":{"aws:MultiFactorAuthPresent":"false"}}}
{"Sid":"DenyIfMFAStale","Effect":"Deny","Action":"*","Resource":"*",
 "Condition":{"NumericGreaterThan":{"aws:MultiFactorAuthAge":"3600"}}}

Both statements are needed. aws:MultiFactorAuthAge is absent when MFA was not used, so the numeric condition alone never fires for a non-MFA session. BoolIfExists rather than Bool also catches long-lived IAM access keys, which never carry aws:MultiFactorAuthPresent.

Sessions. Entra ID Conditional Access session controls: Sign-in frequency = 1 hour, Persistent browser session = Never persistent. That is stricter than 800-63B, which permits 12 hours or 15 minutes of inactivity at AAL3. Enable Continuous access evaluation so a disabled account or deleted key kills the token in near-real time instead of at expiry. On-prem: put Tier 0 accounts in the Protected Users group (no NTLM, no credential caching, 4-hour TGT) and scope them with Authentication Policy Silos.

Break-glass. Two cloud-only emergency accounts, excluded from Conditional Access, each with a FIDO2 key in a separate safe under dual control. Sign-in on either raises a SIEM alert, records the session, and triggers post-incident review. Lost key: helpdesk identity proofing (video plus manager approval), enrol a new key, delete the old credential object.

Failure modes. Lost key → detected as a failed sign-in in Entra sign-in logs; recovery is dual-control re-enrolment. Break-glass abuse → detected by alert on the emergency account's sign-in; response is session revocation plus credential rotation. IdP outage → break-glass keys plus local on-prem auth; the AWS root user keeps a hardware key and no access keys.

AuthenticatorPhishing-resistantAALAdmin use
FIDO2 security keyYesAAL3Primary
Windows Hello for Business (TPM)YesAAL3Primary on managed device
Synced passkeyYesAAL2Not for Tier 0
TOTP appNoAAL2Temporary, monitored
Push notificationNoAAL2Not allowed
SMS/voiceNoAAL1Never

Trace. Admin signs in to Entra ID with a FIDO2 key; Conditional Access requires Phishing-resistant MFA, token issued, sign-in frequency 1 hour. Admin federates into AWS via IAM Identity Center: aws:MultiFactorAuthPresent=true, aws:MultiFactorAuthAge=0. At minute 70 the admin calls iam:DeletePolicy; age is 4200 > 3600, so DenyIfMFAStale fires and the API returns AccessDenied. The admin re-authenticates with the same key, age resets to 0, and the call succeeds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design MFA abuse controls and safe errors.

Answer

Core answer (first 90 seconds)

Assume TOTP or push as the second factor behind a password, ~10M accounts, counters in Redis keyed per account and per source, and an attacker who already holds valid passwords from a breach, so the second factor is the only thing left. The goal: make online guessing of a 6-digit code economically pointless, keep the legitimate user able to get in, and never let the error response reveal which half of the credential pair was right.

Three controls carry it. First, bind attempts to the challenge, not the account: a challenge lives 30 seconds and accepts 5 verification attempts, then it is dead and the user must request a new one. That caps one challenge at 5/1,000,000 = 5×10⁻⁶ success probability. Second, rate-limit challenge creation per account at 10 per 15 minutes and per source IP at 30 per 15 minutes, with progressive delay on verification: 0s, 0s, 1s, 2s, 4s, 8s, capped at 30s. Third, cap push sends at 3 per 10 minutes per account; past that, fall back to TOTP entry, which kills push-bombing.

Arithmetic that decides it

Without the account limit, an attacker with a valid password gets one challenge per 30s = 2,880 challenges/day × 5 attempts = 14,400 guesses/day → expected 1,000,000/14,400 ≈ 69 days to hit a code. With the 10-per-15-minute account cap they get 960 guesses/day → ≈ 1,041 days. That is the number to say out loud: the account-level limit, not the per-challenge limit, is what makes guessing infeasible.

Failure modes and detection

Distributed bypass: the attacker rotates IPs so per-IP counters never trip. Detect with per-account and per-credential-hash counters, and alert when an account's verification-failure rate exceeds 20 failures/hour across any number of IPs. MFA fatigue: a user approves a push they did not initiate. Detect by pushes-per-account (alert above 5/hour) and by the approval-after-N-pushes ratio; respond by forcing TOTP for that account for 24h. Lockout-as-DoS: the attacker deliberately locks a victim out. Mitigate by keeping lockout temporary (15 min, doubling to a 24h cap), emailing the account owner, and offering a self-service unlock link that itself requires the password.

Tradeoffs

CAPTCHA on challenge creation is cheaper than lockout for stopping scripted floods and does not punish the real user, but it is a weak signal against an attacker with a solver farm: use it as a speed bump, not the control. Account lockout is the strongest anti-guessing control and the biggest DoS risk; scope it to the account, keep it short, and always pair it with recovery. Step-up (require TOTP instead of push) is the right answer to fatigue because it locks nobody out.

Safe errors

Return one generic message, "Authentication failed" plus a request ID, for wrong password, wrong code, unknown account, and unenrolled MFA alike, and keep response time constant (pad to a fixed budget) so timing does not leak which branch ran. Log the detailed reason code internally against the request ID.

What would change the decision

If the second factor is hardware WebAuthn, online guessing is off the table and the rate-limit stack collapses to protecting enrollment and recovery flows. If the population is small and high-value, tighten to 3 attempts per challenge and 5 challenges/hour.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design a helpdesk-assisted MFA reset workflow.

Answer

The 90-second answer. Assume an enterprise IdP (Okta, Entra ID, Keycloak), users on TOTP, push, or FIDO2, accounts tiered by blast radius, and a helpdesk that is itself a phishing target. The design rule: the helpdesk never bypasses MFA, it only re-issues it, and only after evidence proportional to what the account can reach. Default to self-service with an existing factor; escalate to human verification only when that fails; for privileged accounts require a second approver and hardware re-proofing. Every reset revokes all sessions and factors, notifies every registered channel, and holds the account restricted until a cooling period expires.

Mechanism. Three controls carry the weight. First, evidence scales with blast radius, not with how convincing the caller sounds. Second, revocation is total: on reset the system deletes the old TOTP secret, push registrations, and every refresh token, so an attacker who already had a session loses it. Third, the cooling period is a restricted state, not a delay: no password change, no new OAuth grants, no mail-forwarding rules, no further factor enrollment until it expires. That window is what lets the real user cancel a reset they did not request.

TierEvidenceCoolingApprover
Low (email, wiki)OTP to a contact registered ≥30 days ago1 hnone
Medium (CRM, finance read)live video + government ID + callback to the manager's number from the directory4 hhelpdesk lead
High (prod, admin, payroll)in-person, or FIDO2 re-enrollment on a known device + manager + security24 hsecurity team, second approver

Trace: medium-risk reset where the attacker already owns the mailbox.

  • T+0:00 caller requests reset. Agent dials the manager's number from the directory, never one the caller supplies.
  • T+0:08 video ID check passes.
  • T+0:12 ticket opened; lead approves.
  • T+0:13 system revokes all refresh tokens and sessions, deletes the TOTP secret and push registrations.
  • T+0:14 notification to email, SMS, and recovery email, each with a 72-hour cancellation link.
  • T+0:20 user enrolls a new TOTP secret.
  • T+0:20–4:20 restricted: no password change, no new OAuth grants, no forwarding rules, no further factor enrollment.
  • T+4:20 full access.

The attacker sees the email notification because they own the mailbox, but they still fail the video ID check and the directory callback, and the SMS and recovery-email copies reach the real user, who can cancel.

Arithmetic. 500 resets/month, 5% high-risk = 25 × 30 min of security-team time = 12.5 h/month. Medium at 15% = 75 × 10 min of lead time = 12.5 h/month. If 2% of resets get cancelled during cooling, that is 10 tickets/month to investigate: cheap insurance.

Failure modes and detection.

  • Social engineering via KBA. Answers live in breach dumps and on LinkedIn. Drop KBA above the low tier; NIST SP 800-63B advises against knowledge-based authentication. Detect: one agent, one caller pattern, several resets in a week.
  • MFA fatigue. Attacker spams push until the user taps approve. Number matching (default in Microsoft Authenticator since 2023) plus a per-user push rate limit of ~5/minute kills it.
  • Insider collusion. The agent who verifies must not be the agent who approves; every reset writes an immutable audit record keyed to the agent ID.
  • Takeover signature. Alert when a reset is followed within 30 minutes by a password change, a new factor enrollment, or a mail-forwarding rule. That sequence is what a successful social-engineering attack looks like.

Trade-offs. For a low-risk user who lost every factor, manager confirmation plus 24-hour cooling and notification is enough; in-person proofing would burn a day of productivity for no risk reduction. Never relax for accounts that reach production or customer PII: the friction is the point. FIDO2/WebAuthn is the preferred re-enrollment target because it is phishing-resistant; TOTP is the fallback when no hardware is available.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design inclusive MFA enrollment and recovery.

Answer

What I'd say first

Before designing anything I'd pin three things: the assurance level the action needs (NIST SP 800-63B AAL2 vs AAL3), the populations that must get through (screen-reader, switch, motor-impaired, no-smartphone), and the recovery budget. Support minutes per 1,000 users per year. The design changes completely between AAL2 and AAL3.

Then the core answer: enroll two authenticators at signup, not one. Primary is a WebAuthn credential, platform passkey or roaming FIDO2 key, because it's phishing-resistant and needs no shared secret. Second is another WebAuthn credential on a different device, or, where the risk tier allows, a TOTP app. Recovery is a designed flow, not a support ticket.

Why two at enrollment

The dominant recovery driver is one lost authenticator. If a second is already enrolled, "recovery" is "use your other key": no identity proofing, no support call. NIST SP 800-63B §5.1.1.2 requires recovery not be weaker than the primary mechanism, and a second enrolled authenticator is the cheapest way to satisfy that.

Authenticator choice

AuthenticatorAssuranceAccessibilityRecovery role
Platform WebAuthn (passkey)AAL2; AAL3 if hardware-bound + UVWorks with screen readers; UV can be a PIN, not biometricsPrimary
Roaming FIDO2 key (CTAP2)AAL3Needs USB/NFC port; motor costPrimary or backup
TOTP appAAL2Requires a second device; typing 6 digitsBackup only
Recovery codesAAL2Printable, no deviceLast resort

WebAuthn's userVerification can be "preferred" with a PIN, so biometrics are never forced, and 800-63B forbids biometrics as a single factor anyway.

Enrollment mechanics

  • Set the WebAuthn timeout to 60,000 ms. Several libraries default to 10 s, which times out screen-reader users mid-ceremony.
  • Allow residentKey: "preferred" so passkeys sync across the user's devices: that is itself a recovery path.
  • Let users nickname each authenticator ("YubiKey on keyring") so recovery becomes "which one did I lose".
  • Never block paste in the OTP field; 800-63B requires allowing paste for memorized secrets, and the same logic applies to codes.

Recovery design

Three tiers, chosen by what the user still has:

  1. Second enrolled authenticator: self-service, no proofing.
  2. Recovery codes: 10 single-use codes, 128 bits each, stored hashed. Self-service.
  3. Identity proofing: only when both are gone. Expensive; instrument it.

Trace for tier 3: user hits "lost everything" → step-up proofing matching the AAL (video call or in person) → issue a single-use enrollment link valid 15 minutes → force re-enrollment of two authenticators before the session ends.

Failure modes

  • Recovery weaker than primary: an attacker uses the support desk to bypass MFA. Detect by alerting on any recovery path that doesn't demand the same assurance; the cost is the proofing step.
  • Timeout abandonment: measure ceremony completion by cohort. A 10 s timeout shows up as a spike in screen-reader users failing at the UV prompt.
  • Single-authenticator enrollment: track the share of accounts holding one credential; each is a future support ticket.

Arithmetic: if 30% of users enroll one authenticator and 2% of those lose it per year, that's 6 recovery events per 1,000 users/year. At 20 minutes of proofing each, 2 hours of support per 1,000 users: halved by prompting a second enrollment at first login.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Build authenticator and session self-service safely.

Answer

Assumptions first. Web app, server-side sessions in a cookie, WebAuthn/passkeys as the primary factor with TOTP as fallback, one account per user. The page is a read model over credential metadata plus a small set of step-up-gated mutations. The hard part isn't the list: it's the last-factor and total-loss path, so I'd spend the interview there.

Core answer. Show, per credential: type (passkey / platform / roaming security key / TOTP), user nickname, created_at, last_used_at, and for WebAuthn the authenticator-data flags BE (backup eligible) and BS (currently backed up) from WebAuthn Level 2. BE=1 tells the user the passkey is synced and survives device loss; BE=0 means device-bound, so losing the device loses the factor. That distinction is the whole reason to show backup status. Also show the AAGUID-derived model name, but don't gate policy on it: some platform authenticators return an all-zero AAGUID.

Alongside credentials, list active sessions: coarse device/UA, approximate location from IP, last-seen, and a revoke action. Coarse, not fingerprinting: no canvas or font enumeration.

Never render: WebAuthn private keys (they never leave the authenticator; the server holds only the public key and credential ID), TOTP seeds after enrollment, recovery codes, session IDs. TOTP seeds are the one real secret the server stores: encrypt them with a KMS key and show only the label and last-used time.

Step-up gate. Add, rename, revoke, and recovery changes all require a fresh WebAuthn assertion with userVerification: "required", not just a live session. Freshness window 5 minutes, challenge single-use, and rotate the session ID on success so a pre-step-up session ID can't be replayed.

TypeScript
const STEP_UP_TTL_MS = 5 * 60 * 1000;
function requireFreshStepUp(req, res, next) {
  const at = req.session.stepUpAt; // set only by a verified assertion
  if (!at || Date.now() - at > STEP_UP_TTL_MS)
    return res.status(403).json({ error: "step_up_required" });
  next();
}

Last factor and total loss. Two options. Block removing the last viable factor outright: safe, but a user who lost their only device is locked out and support becomes the attack surface. Or allow it behind a cooling-off window with independent notification: recoverable, but there's a window where an attacker holding a live session can strip factors. Deciding criterion: if the account has a recovery path that doesn't run through the session (a recovery code issued at enrollment, or support with identity verification) allow removal with a 24h cooling-off and notify on email and push, cancellable from either. If there's no such path, block and route to support.

Revocation. One transaction: set revoked_at, delete every session row bound to that credential (or all sessions for the user, if sessions aren't credential-scoped), write the audit row (actor, IP, UA, credential ID, idempotency key). Notification goes through an outbox after commit, never inside it. Idempotency: unique index on (user_id, idempotency_key) plus a stored request hash; a replay returns the original response, a key reused with a different body returns 409.

Failure modes. Partial revoke: credential gone, sessions alive, user believes they're safe. Detect with a reconciliation job that alerts on any active session whose credential_id has revoked_at set; cheap with an index on credential_id. Notification inside the transaction: a rollback silently drops the alert, or slow SMTP holds the DB transaction open; watch revoke p99 and use the outbox. Signature-counter alarms on synced passkeys: BE=1 credentials frequently don't increment the counter, so "counter went backwards" fires constantly; only enforce monotonicity when BE=0.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Respond to an MFA-fatigue campaign.

Answer

Assume the attacker already has the user's password and is spamming push notifications. The user hasn't approved yet, or has approved once. The goal is to stop the prompts before the user caves.

First 60 seconds: contain. Revoke all refresh tokens and sessions for that user. In Microsoft Entra ID, that's 'Revoke sessions' in the user blade. In Okta, 'Clear sessions'. Then set the user's MFA prompt limit to zero or disable push for that user. For example, set the IdP's prompt rate limit to 5 per user per 10 minutes normally, but for an active attack, set it to 0. Also reset the password and require re-registration of MFA methods. Notify the user via a channel they already trust (phone call, Slack DM) not email, which the attacker may control.

Why this works: MFA fatigue succeeds because the attacker has valid credentials and only needs one approval. Each push is a coin flip; eventually the user approves to stop the noise. So the first containment is to stop the noise. Rate-limiting alone is insufficient if the attacker already has a session token; revoking sessions kills that.

StepActionWhy
1Revoke sessions/refresh tokensKills attacker's existing access
2Set prompt limit to 0 for userStops the noise immediately
3Reset password, require MFA re-registrationRemoves attacker's persistence
4Notify user out-of-bandConfirms and warns

Investigate. Check sign-in logs for: successful MFA approvals from unusual IPs, new MFA methods added (e.g., attacker registers their own authenticator), recovery email/phone changes, and OAuth grants. In Entra ID, look at 'Authentication methods' and 'Sign-in logs' filtered by user. In Okta, System Log. If you see a successful approval, assume compromise: revoke all sessions, reset password, remove unknown MFA methods, and check for mailbox rules or OAuth app consents.

Failure modes: If you only rate-limit but don't revoke sessions, attacker continues. If you permanently lock the account, you create a DoS. Detection: alert on >5 prompts per user per 10 minutes, or multiple denied prompts followed by an approval. Operational cost: users get frustrated; helpdesk calls increase. So communicate.

Trade-offs: Number matching (Microsoft Authenticator default since May 2023, Duo Push) reduces accidental approvals but adds a step. Phishing-resistant MFA (FIDO2/WebAuthn, passkeys) eliminates push fatigue but requires hardware keys or platform authenticators, and legacy apps may not support it. If full rollout is not possible, number matching + conditional access (require compliant device, trusted location) + prompt rate limiting reduces risk significantly. Accept partial mitigation when the population is large and legacy systems block FIDO2.

Closing decision: If the user confirms 'not me', treat as compromise and revoke everything. If they approved, still revoke and reset because the attacker had access. Then migrate that user or population to phishing-resistant auth.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Respond to suspected MFA bypass or authenticator compromise.

Answer

Clarify first. "Suspected" is doing a lot of work here. I'd ask: do we have a confirmed bypass, or an anomaly that looks like one? And what's the blast radius: one user, one authenticator model, or a shared token-signing path? My assumption for the rest: I'm the on-call identity engineer with IdP admin rights and centralized logs. If that's wrong, the answer changes, because without log access you can't tell a bypass from a user fat-fingering a code.

The core answer. Contain the session and the factor, not just the account. Disabling a user's password does nothing if a stolen session cookie is still valid, and resetting a password does nothing if the attacker enrolled their own authenticator. So the order is: kill live sessions, remove the attacker-controlled factor, then force re-enrollment through a path the attacker can't intercept.

Why bypasses happen: three families, and they need different containment.

VectorWhat it looks like in logsFirst containment
Push bombing / MFA fatigueBurst of denied push challenges, then one approval, same IP/deviceRemove push factor; move user to number-matching or WebAuthn
SIM swap / SMS OTPPhone-number change event shortly before a sign-in from a new ASNRemove SMS factor; block number changes without re-auth
AiTM phishing (Evilginx-style)Valid MFA challenge, then the session cookie replayed from a different IP/ASN minutes laterRevoke sessions; the factor itself was never broken
Recovery / enrollment abuseNew authenticator enrolled or recovery code used, then immediate privileged actionRevoke the new authenticator; audit the enrollment path

That last row is the one people miss. If self-service MFA reset doesn't require a fresh strong auth, an attacker with mailbox access just resets the factor and walks in.

Trade-offs, stated as decisions. Revoke this user's sessions or everyone's? Org-wide revocation on one anomaly causes a mass re-auth (helpdesk spike, lost work) so I scope to the user plus any session sharing the same token family, and widen only if a token-signing key or shared app secret is implicated. Second decision: notify now or watch? If the attacker controls the mailbox, notifying through the inbox tips them off. I notify out-of-band (phone, secondary address, or the user's manager) and keep monitoring the account.

Failure modes and how I'd catch them.

  • Recovery-code reuse. Codes are single-use, but users screenshot them. Hash stored codes and alert if the same code appears in two sign-ins.
  • Stale enrolled authenticator. After a device swap, the old phone is still enrolled; whoever holds it passes MFA. Compare each authenticator's last-used timestamp against the device-management record.
  • Revocation that doesn't revoke. Revoking at the IdP doesn't kill a JWT a downstream app validates locally. Test by replaying the old token against the app; if it still works, the app caches. Fix with short access-token TTLs (5–15 min) plus refresh-token revocation.

A worked trace. AiTM compromise: 09:14 user completes WebAuthn challenge from IP A; 09:14 session cookie issued; 09:19 same cookie used from IP B, different ASN, no new challenge; 09:21 mailbox rule created forwarding to an external address. The tell is step three: a valid session with no fresh challenge from a new network. Containment: revoke sessions, remove the forwarding rule, force re-enrollment, then check whether the same IP hit other accounts.

Restore. Fix the weakest path, usually enrollment or recovery, add a regression test that replays the bypass, and only then return to normal policy. If push or SMS was the vector, the durable fix is phishing-resistant WebAuthn, which is what NIST SP 800-63B AAL3 requires and which removes the push-bombing and SIM-swap classes entirely.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Define success and safety metrics for an MFA program.

Answer

Two families, and they pull against each other. Success answers "can people get in, and do they use the strong factor?" Safety answers "when an account is compromised or lost, how fast and how completely do we cut it off?" State the assumptions first: a workforce deployment, ~10k accounts, FIDO2/WebAuthn as the primary factor, a legacy TOTP/SMS tail, an IdP (Okta, Entra ID) fronting SaaS apps. The metric set changes for consumer accounts, where abandonment dominates.

MetricDefinitionIllustrative targetWhy it matters
Phishing-resistant enrollment% active accounts with a registered WebAuthn credential≥90% in two quartersSMS/TOTP are phishable through a real-time proxy (Evilginx); WebAuthn binds the assertion to the origin, so a proxied login yields nothing replayable
Phishing-resistant use% of authentications completed with WebAuthn, not just enrolled≥85%Enrollment without use is shelf-ware; users fall back to TOTP under pressure
Recovery independence% accounts with ≥2 recovery methods that don't share one reset path≥95%Two keys behind the same password reset are one method
Disable-to-revokep95 seconds from account disable to all sessions and refresh tokens revoked<300sDisabling in the IdP leaves OAuth refresh tokens alive; the attacker keeps access
Prompt denial ratio / time-to-approveDenied+ignored vs approved; median approve latencyFlag approvals under 2sMFA fatigue: attacker spams push, user taps approve
Support override rateHelpdesk MFA resets per 1000 users/month<2Every reset is a social-engineering surface

Disable-to-revoke is the safety-critical interval. Disabling an account in the IdP does not kill an already-issued OAuth refresh token or an app session. If the token TTL is 60 minutes and revocation fails silently, the attacker retains access for up to an hour after you think you've locked them out. Measure the real interval with a synthetic test: disable a canary account, then poll a protected resource until it returns 401. That number, not the config value, is the metric.

Measure failure, abandonment, accessibility, latency and support burden by cohort: role, device, region. An average that looks healthy can hide a broken cohort: a 3% abandonment rate overall can be 20% on older Android devices, which is where your field staff live.

Trade-offs and deciding criteria. If you're regulated (PCI, FedRAMP), disable-to-revoke and recovery independence dominate: a single compromised admin is the blast radius you're pricing. If you're consumer-facing, abandonment and support burden dominate, because a locked-out user churns. The deciding question is the blast radius of one compromised account versus the cost of one lockout. Pick the two or three metrics that move with that ratio and ignore the rest.

Anti-metrics. Raw prompt totals and raw enrollment counts reward the wrong behavior: they go up when you push weak SMS adoption, when users fatigue-approve, and when recovery is so brittle people get locked out. Pair every enrollment number with a use number, and every safety number with a support-burden number, so no single metric can be gamed in isolation.

Curated: · Written: · Reviewed:

Difficulty: Medium