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

@@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.OptionalLong;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -84,6 +85,20 @@ class TotpTest {
assertFalse(Totp.matchesCode(RFC6238_SECRET, Totp.codeAt(other, Totp.stepAt(now)), 1, now));
}
@Test
void matchingStepNamesTheStepTheCodeWasGeneratedFor() {
Instant now = Instant.ofEpochSecond(1_700_000_000L);
long current = Totp.stepAt(now);
for (long step = current - 1; step <= current + 1; step++) {
assertEquals(OptionalLong.of(step),
Totp.matchingStep(RFC6238_SECRET, Totp.codeAt(RFC6238_SECRET, step), 1, now));
}
assertEquals(OptionalLong.empty(),
Totp.matchingStep(RFC6238_SECRET, Totp.codeAt(RFC6238_SECRET, current - 2), 1, now));
assertEquals(OptionalLong.empty(), Totp.matchingStep(RFC6238_SECRET, "abcdef", 1, now));
assertEquals(OptionalLong.empty(), Totp.matchingStep(null, "123456", 1, now));
}
@Test
void anythingThatIsNotSixDigitsIsNotACode() {
assertTrue(Totp.isSixDigits("000000"));
@@ -12,6 +12,7 @@ import java.time.Clock;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -91,5 +92,22 @@ class CognitoTotpMfaIntegrationTest {
"ChallengeResponses":{"USERNAME":"totp-user","SOFTWARE_TOKEN_MFA_CODE":"%s"}}
""".formatted(clientId, later.path("Session").asText(), code);
cognitoAction("RespondToAuthChallenge", replay).then().statusCode(400);
String reuseSession = cognitoJson("InitiateAuth", loginRequest).path("Session").asText();
String challengeResponse = """
{"ClientId":"%s","ChallengeName":"SOFTWARE_TOKEN_MFA","Session":"%s",
"ChallengeResponses":{"USERNAME":"totp-user","SOFTWARE_TOKEN_MFA_CODE":"%s"}}
""";
cognitoAction("RespondToAuthChallenge", challengeResponse.formatted(clientId, reuseSession, code))
.then().statusCode(400)
.body("__type", equalTo("ExpiredCodeException"))
.body("message", equalTo("Your software token has already been used once."))
.body("AuthenticationResult", nullValue());
String nextStepCode = CognitoTotp.code(associated.path("SecretCode").asText(),
clock.instant().plusSeconds(30));
JsonNode nextStep = cognitoJson("RespondToAuthChallenge",
challengeResponse.formatted(clientId, reuseSession, nextStepCode));
assertFalse(nextStep.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
@@ -357,6 +358,87 @@ class CognitoTotpMfaTest {
return Arrays.copyOf(mac.doFinal(), 16);
}
@Test
void codeThatAnsweredAChallengeCannotAnswerAnother() {
String secret = registerSoftwareToken();
String code = CognitoTotp.code(secret, clock.instant());
assertNotNull(answerSoftwareTokenChallenge((String) passwordLogin().get("Session"), code)
.get("AuthenticationResult"));
String session = (String) passwordLogin().get("Session");
AwsException reused = assertThrows(AwsException.class, () -> answerSoftwareTokenChallenge(session, code));
assertEquals("ExpiredCodeException", reused.getErrorCode());
assertEquals("Your software token has already been used once.", reused.getMessage());
assertEquals(400, reused.getHttpStatus());
String wrongCode = code.equals("000000") ? "000001" : "000000";
assertEquals("CodeMismatchException", assertThrows(AwsException.class,
() -> answerSoftwareTokenChallenge(session, wrongCode)).getErrorCode());
clock.advance(Duration.ofSeconds(30));
assertEquals("ExpiredCodeException", assertThrows(AwsException.class,
() -> answerSoftwareTokenChallenge(session, code)).getErrorCode(),
"a used code stays refused while it is still inside the drift window");
assertNotNull(answerSoftwareTokenChallenge(session, CognitoTotp.code(secret, clock.instant()))
.get("AuthenticationResult"));
}
@Test
void codeFromAnEarlierStepIsRefusedOnceALaterOneWasAccepted() {
String secret = registerSoftwareToken();
String earlier = CognitoTotp.code(secret, clock.instant());
String later = CognitoTotp.code(secret, clock.instant().plusSeconds(30));
assertNotNull(answerSoftwareTokenChallenge((String) passwordLogin().get("Session"), later)
.get("AuthenticationResult"));
assertEquals("ExpiredCodeException", assertThrows(AwsException.class,
() -> answerSoftwareTokenChallenge((String) passwordLogin().get("Session"), earlier))
.getErrorCode());
}
@Test
void newlyVerifiedSoftwareTokenStartsWithoutAUsedStep() {
String secret = registerSoftwareToken();
Map<String, Object> signedIn = answerSoftwareTokenChallenge((String) passwordLogin().get("Session"),
CognitoTotp.code(secret, clock.instant()));
String accessToken = (String) ((Map<?, ?>) signedIn.get("AuthenticationResult")).get("AccessToken");
String replacement = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
service.verifySoftwareToken(accessToken, null, CognitoTotp.code(replacement, clock.instant()));
assertNull(service.adminGetUser(pool.getId(), USERNAME).getLastSoftwareTokenMfaStep());
assertNotNull(answerSoftwareTokenChallenge((String) passwordLogin().get("Session"),
CognitoTotp.code(replacement, clock.instant())).get("AuthenticationResult"));
}
@Test
void usedStepSurvivesUserSerializationAndOlderUsersHaveNone() throws Exception {
String secret = registerSoftwareToken();
answerSoftwareTokenChallenge((String) passwordLogin().get("Session"), CognitoTotp.code(secret, clock.instant()));
ObjectMapper mapper = new ObjectMapper();
CognitoUser persisted = service.adminGetUser(pool.getId(), USERNAME);
CognitoUser restored = mapper.readValue(mapper.writeValueAsBytes(persisted), CognitoUser.class);
assertEquals(Totp.stepAt(clock.instant()), restored.getLastSoftwareTokenMfaStep());
CognitoUser older = mapper.readValue("{\"username\":\"bob\",\"softwareTokenMfaSecret\":\"" + secret + "\"}",
CognitoUser.class);
assertNull(older.getLastSoftwareTokenMfaStep());
}
private String registerSoftwareToken() {
Map<String, Object> associated = service.associateSoftwareToken(null, (String) passwordLogin().get("Session"));
String secret = (String) associated.get("SecretCode");
String verifiedSession = (String) service.verifySoftwareToken(null, (String) associated.get("Session"),
CognitoTotp.code(secret, clock.instant())).get("Session");
service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP", verifiedSession,
Map.of("USERNAME", USERNAME));
return secret;
}
private Map<String, Object> answerSoftwareTokenChallenge(String session, String code) {
return service.respondToAuthChallenge(client.getClientId(), "SOFTWARE_TOKEN_MFA", session,
Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", code));
}
private Map<String, Object> passwordLogin() {
return service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD));