Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): refuse a reused TOTP code for SOFTWARE_TOKEN_MFA (#6808)
Daniël van Ziel0ee1d10659d7
diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex dad1091b17..5a6a2f75f5 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -364,6 +364,10 @@ requires a fresh code in `SOFTWARE_TOKEN_MFA_CODE`. Its `ChallengeParameters` ca`USER_ID_FOR_SRP`, the user's actual username rather than an alias (the `sub` in a poolwith `UsernameAttributes`), to send back as `USERNAME` and to compute `SECRET_HASH` from,plus `FRIENDLY_DEVICE_NAME` when `VerifySoftwareToken` was given a `FriendlyDeviceName`.+As on AWS, a code is accepted for one `SOFTWARE_TOKEN_MFA` challenge only: answering+another with a code from the same 30-second step, or an earlier one, fails with+`ExpiredCodeException` (`Your software token has already been used once.`) until the+authenticator shows its next code. The code given to `VerifySoftwareToken` is not counted.Both token-management actions also accept an access token for an already authenticateduser. Sessions expire with the app client's `AuthSessionValidity` and cannot be replayedafter completion.diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Totp.java b/src/main/java/io/github/hectorvent/floci/core/common/Totp.javaindex db1d5da8a9..671a9c07eb 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/Totp.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/Totp.java@@ -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. */diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.javaindex 7eed22f0a7..d47acd5bef 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java@@ -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) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.javaindex 229fbe8c53..a2f79f9841 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java@@ -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. */diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.javaindex 1701c8c26c..479ca67313 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoTotp.java@@ -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));}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.javaindex 720000051e..77b43c2f66 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java@@ -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;diff --git a/src/test/java/io/github/hectorvent/floci/core/common/TotpTest.java b/src/test/java/io/github/hectorvent/floci/core/common/TotpTest.javaindex 94ca2017a4..cc46ecc640 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/TotpTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/TotpTest.java@@ -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));+ }+@Testvoid anythingThatIsNotSixDigitsIsNotACode() {assertTrue(Totp.isSixDigits("000000"));diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaIntegrationTest.javaindex 7ddd0d7eb5..276835464f 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaIntegrationTest.java@@ -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());}}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.javaindex 998609772a..4284b0b521 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java@@ -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));