fix(cognito): refuse a reused TOTP code for SOFTWARE_TOKEN_MFA (#6808)

A software-token code now answers one SOFTWARE_TOKEN_MFA challenge only. The step of the
last accepted code is stored on the user, and a code from that step or an earlier one fails
with ExpiredCodeException, as AWS does (RFC 6238 section 5.2). VerifySoftwareToken does not
record a step, and activating a new authenticator clears it.

Fixes #6804
This commit is contained in:
Daniël van Ziel authored and GitHub committed 2026-10-28 07:20:05 -04:00
1 parent ad2089e662
commit 0ee1d10659
9 files changed
+183 -10

No files matched your search

@@ -9,6 +9,7 @@ import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Locale;
import java.util.OptionalLong;
/**
* Time-based one-time passwords as specified in RFC 6238: HMAC-SHA1 over the number of 30-second
@@ -80,16 +81,25 @@ public final class Totp {
* between the authenticator and this process.
*/
public static boolean matchesCode(String base32Secret, String code, int driftSteps, Instant now) {
return matchingStep(base32Secret, code, driftSteps, now).isPresent();
}
/**
* The step counter {@code code} was generated for, searched over the same window as
* {@link #matchesCode}, or empty when it matches none. A caller that must refuse a replayed
* code (RFC 6238 section 5.2) records this step and rejects any code at or before it.
*/
public static OptionalLong matchingStep(String base32Secret, String code, int driftSteps, Instant now) {
if (base32Secret == null || !isSixDigits(code)) {
return false;
return OptionalLong.empty();
}
long current = stepAt(now);
for (long counter = current - driftSteps; counter <= current + driftSteps; counter++) {
for (long counter = current + driftSteps; counter >= current - driftSteps; counter--) {
if (codeEquals(codeAt(base32Secret, counter), code)) {
return true;
return OptionalLong.of(counter);
}
}
return false;
return OptionalLong.empty();
}
/** Whether the value has the shape of a code at all, before any secret is touched. */
@@ -34,6 +34,7 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalLong;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
@@ -449,13 +450,21 @@ final class CognitoAuthFlowHandler {
if (!state.secret().equals(user.getSoftwareTokenMfaSecret())) {
throw new AwsException("NotAuthorizedException", "Software token is not verified", 400);
}
} else if (!state.secret().equals(user.getSoftwareTokenMfaSecret())
|| !CognitoTotp.validCode(state.secret(),
responses.get("SOFTWARE_TOKEN_MFA_CODE"), clock.instant())) {
if (state.failedAttempts().incrementAndGet() >= CognitoTotp.MAX_FAILED_ATTEMPTS) {
totpSessions.remove(session, state);
} else {
OptionalLong step = state.secret().equals(user.getSoftwareTokenMfaSecret())
? CognitoTotp.matchingStep(state.secret(), responses.get("SOFTWARE_TOKEN_MFA_CODE"),
clock.instant())
: OptionalLong.empty();
if (step.isEmpty()) {
countFailedTotpAttempt(session, state);
throw new AwsException("CodeMismatchException",
"Invalid verification code provided, please try again.", 400);
}
if (!service.consumeSoftwareTokenStep(pool.getId(), user.getUsername(), step.getAsLong())) {
countFailedTotpAttempt(session, state);
throw new AwsException("ExpiredCodeException",
"Your software token has already been used once.", 400);
}
throw new AwsException("CodeMismatchException", "Invalid verification code provided, please try again.", 400);
}
if (!totpSessions.remove(session, state)) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
@@ -469,6 +478,12 @@ final class CognitoAuthFlowHandler {
return authenticationResult(pool, client, user, state.triggerSource(), metadata);
}
private void countFailedTotpAttempt(String session, TotpSession state) {
if (state.failedAttempts().incrementAndGet() >= CognitoTotp.MAX_FAILED_ATTEMPTS) {
totpSessions.remove(session, state);
}
}
private Map<String, Object> processChallenge(UserPool pool, UserPoolClient client, String challengeName,
String session, Map<String, String> responses,
Map<String, String> clientMetadata) {
@@ -3771,6 +3771,7 @@ public class CognitoService implements ResourceProvider {
return false;
}
user.setSoftwareTokenMfaSecret(pending);
user.setLastSoftwareTokenMfaStep(null);
user.setSoftwareTokenMfaDeviceName(friendlyDeviceName == null || friendlyDeviceName.isEmpty()
? null : friendlyDeviceName);
user.setPendingSoftwareTokenMfaSecret(null);
@@ -3781,6 +3782,23 @@ public class CognitoService implements ResourceProvider {
}
}
/**
* Records {@code step} as the user's last accepted software-token step, refusing it when a code
* from that step or an earlier one already answered a challenge (RFC 6238 section 5.2).
*/
boolean consumeSoftwareTokenStep(String poolId, String username, long step) {
synchronized (userLock(poolId, username)) {
CognitoUser user = adminGetUser(poolId, username);
Long last = user.getLastSoftwareTokenMfaStep();
if (last != null && step <= last) {
return false;
}
user.setLastSoftwareTokenMfaStep(step);
userStore.put(userKey(poolId, user.getUsername()), user);
return true;
}
}
// ──────────────────────────── Passkeys (WebAuthn) ────────────────────────────
/** StartWebAuthnRegistration: creation options for the access token's user, whose challenge the app client must answer. */
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cognito;
import io.github.hectorvent.floci.core.common.Totp;
import java.time.Instant;
import java.util.OptionalLong;
/**
* Cognito's software-token MFA view of {@link Totp}: a single code, accepted one step either side
@@ -24,6 +25,11 @@ final class CognitoTotp {
return Totp.matchesCode(secret, code, DRIFT_STEPS, now);
}
/** The step {@code code} belongs to, or empty when it is not a valid code for {@code secret}. */
static OptionalLong matchingStep(String secret, String code, Instant now) {
return Totp.matchingStep(secret, code, DRIFT_STEPS, now);
}
static String code(String secret, Instant now) {
return Totp.codeAt(secret, Totp.stepAt(now));
}
@@ -32,6 +32,7 @@ public class CognitoUser {
private String softwareTokenMfaDeviceName;
private String pendingSoftwareTokenMfaSecret;
private Integer pendingSoftwareTokenMfaAttemptsRemaining;
private Long lastSoftwareTokenMfaStep;
private List<WebAuthnCredential> webAuthnCredentials = new ArrayList<>();
private boolean webAuthnMfaEnabled;
private String federatedProviderName;
@@ -118,6 +119,10 @@ public class CognitoUser {
public String getPendingSoftwareTokenMfaSecret() { return pendingSoftwareTokenMfaSecret; }
public void setPendingSoftwareTokenMfaSecret(String secret) { this.pendingSoftwareTokenMfaSecret = secret; }
/** The TOTP step of the last code that answered a SOFTWARE_TOKEN_MFA challenge, or null when none has. */
public Long getLastSoftwareTokenMfaStep() { return lastSoftwareTokenMfaStep; }
public void setLastSoftwareTokenMfaStep(Long step) { this.lastSoftwareTokenMfaStep = step; }
public Integer getPendingSoftwareTokenMfaAttemptsRemaining() { return pendingSoftwareTokenMfaAttemptsRemaining; }
public void setPendingSoftwareTokenMfaAttemptsRemaining(Integer attempts) {
this.pendingSoftwareTokenMfaAttemptsRemaining = attempts;