diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index c53f3bffe..2c16f3c9f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -289,6 +289,7 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager; import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; import org.whispersystems.textsecuregcm.storage.Subscriptions; +import org.whispersystems.textsecuregcm.storage.TotpManager; import org.whispersystems.textsecuregcm.storage.VerificationSessionManager; import org.whispersystems.textsecuregcm.storage.VerificationSessions; import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager; @@ -814,6 +815,7 @@ public class WhisperServerService extends Application implemen private final ScheduledExecutorService messagesPollExecutor; private final ScheduledExecutorService retryExecutor; private final Clock clock; - private final Duration maxTotpValidationDelay; - private final KeyGenerator totpKeyGenerator; + private final TotpManager totpManager; private final WebAuthnCeremonyManager webAuthnCeremonyManager; private final Key verificationTokenKey; @@ -211,12 +207,6 @@ public class AccountsManager extends RedisPubSubAdapter implemen @VisibleForTesting static final String LINK_DEVICE_VERIFICATION_TOKEN_ALGORITHM = "HmacSHA256"; - @VisibleForTesting - public static final TimeBasedOneTimePasswordGenerator TOTP = new TimeBasedOneTimePasswordGenerator(); - - private static final TotpParameters TOTP_PARAMETERS = - new TotpParameters(TOTP.getAlgorithm(), TOTP.getPasswordLength(), TOTP.getTimeStep()); - public static final int MAX_TOTP_KEYS = 2; public static final int MAX_MFA_KEYS = 10; @@ -314,8 +304,8 @@ public class AccountsManager extends RedisPubSubAdapter implemen final ScheduledExecutorService retryExecutor, final Clock clock, final byte[] linkDeviceSecret, - final Duration maxTotpValidationDelay, - final WebAuthnCeremonyManager webAuthnCeremonyManager) { + final WebAuthnCeremonyManager webAuthnCeremonyManager, + final TotpManager totpManager) { this.accounts = accounts; this.phoneNumberIdentifiers = phoneNumberIdentifiers; this.cacheCluster = cacheCluster; @@ -332,13 +322,6 @@ public class AccountsManager extends RedisPubSubAdapter implemen this.messagesPollExecutor = messagesPollExecutor; this.retryExecutor = retryExecutor; this.clock = requireNonNull(clock); - - if (maxTotpValidationDelay.compareTo(TOTP.getTimeStep()) > 0) { - throw new IllegalArgumentException("Max TOTP validation delay must be less than or equal to TOTP time step"); - } - - this.maxTotpValidationDelay = maxTotpValidationDelay; - this.verificationTokenKey = new SecretKeySpec(linkDeviceSecret, LINK_DEVICE_VERIFICATION_TOKEN_ALGORITHM); // Fail fast: reject bad keys @@ -348,27 +331,11 @@ public class AccountsManager extends RedisPubSubAdapter implemen throw new IllegalArgumentException(e); } - try { - this.totpKeyGenerator = KeyGenerator.getInstance(TOTP.getAlgorithm()); - totpKeyGenerator.init(getTotpKeyLengthBits()); - } catch (final NoSuchAlgorithmException e) { - throw new AssertionError("Every implementation of the Java platform is required to support the HmacSHA256 KeyGenerator algorithm", e); - } - this.webAuthnCeremonyManager = webAuthnCeremonyManager; + this.totpManager = totpManager; this.pubSubConnection = pubSubRedisClient.createPubSubConnection(); } - @VisibleForTesting - static int getTotpKeyLengthBits() { - try { - // The HOTP/TOTP spec recommends using a key length that's the same as the HMAC block length - return Mac.getInstance(TOTP.getAlgorithm()).getMacLength() * 8; - } catch (final NoSuchAlgorithmException e) { - throw new AssertionError("Algorithm used by TOTP generator not found", e); - } - } - @Override public void start() { pubSubConnection.usePubSubConnection(connection -> { @@ -2052,8 +2019,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen /// @throws TooManyTotpKeysException if the target account already has at least [#MAX_TOTP_KEYS] TOTP keys /// @throws TooManyMfaKeysException if the target account already has at least [#MAX_MFA_KEYS] total MFA keys public TotpKey generatePendingTotpKey(final UUID accountIdentifier) throws TooManyTotpKeysException, TooManyMfaKeysException { - final SecretKey secretKey = totpKeyGenerator.generateKey(); - final TotpKey pendingTotpKey = new TotpKey(TOTP_PARAMETERS, secretKey.getEncoded()); + final TotpKey pendingTotpKey = totpManager.generateTotpKey(); try { update(accountIdentifier, account -> { @@ -2105,7 +2071,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen final TotpKey pendingTotpKey = maybePendingTotpKey.get(); try { - if (verifyTotp(pendingTotpKey, timestamp, oneTimePassword)) { + if (totpManager.checkTotpMatches(accountIdentifier, pendingTotpKey, timestamp, oneTimePassword)) { final AtomicInteger keyId = new AtomicInteger(); update(accountIdentifier, account -> { @@ -2148,7 +2114,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen .max(Map.Entry.comparingByKey()) .filter(entry -> { try { - return verifyTotp((AnnotatedTotpKey) entry.getValue(), timestamp, oneTimePassword); + return totpManager.checkTotpMatches(accountIdentifier, (AnnotatedTotpKey) entry.getValue(), timestamp, oneTimePassword); } catch (final InvalidKeyException e) { ImpossibleEvents.logImpossible(logger, "Invalid TOTP key for account {}", accountIdentifier, e); return false; @@ -2158,36 +2124,7 @@ public class AccountsManager extends RedisPubSubAdapter implemen } public boolean verifyTotp(final Account account, final Instant validationTimestamp, @Nullable final Integer oneTimePassword) { - final List totpKeys = account.getMfaKeys().values().stream().filter(AnnotatedTotpKey.class::isInstance).map(AnnotatedTotpKey.class::cast).toList(); - if (totpKeys.isEmpty()) { - return oneTimePassword == null; - } - - if (oneTimePassword == null) { - // The account has TOTP keys, but the caller hasn't provided a one-time password - return false; - } - - for (final SecretKey totpKey : totpKeys) { - try { - if (verifyTotp(totpKey, validationTimestamp, oneTimePassword)) { - return true; - } - } catch (final InvalidKeyException e) { - ImpossibleEvents.logImpossible(logger, "Invalid TOTP key for account {}", account.getAccountIdentifier(), e); - } - } - - return false; - } - - private boolean verifyTotp(final SecretKey totpKey, final Instant validationTimestamp, final int oneTimePassword) throws InvalidKeyException { - for (final Instant timestamp : new Instant[]{validationTimestamp, validationTimestamp.minus(maxTotpValidationDelay)}) { - if (TOTP.validateOneTimePassword(totpKey, timestamp, oneTimePassword)) { - return true; - } - } - return false; + return totpManager.verifyTotp(account, validationTimestamp, oneTimePassword); } /// Returns server-generated parameters needed to initiate a WebAuthn registration ceremony for the given account. diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/TotpManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/TotpManager.java new file mode 100644 index 000000000..5cdf77bdc --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/TotpManager.java @@ -0,0 +1,148 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.storage; + +import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator; +import com.google.common.annotations.VisibleForTesting; +import io.lettuce.core.SetArgs; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import javax.annotation.Nullable; +import javax.crypto.KeyGenerator; +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; +import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents; + +public class TotpManager { + private static final Logger logger = LoggerFactory.getLogger(TotpManager.class); + + @VisibleForTesting + public static final TimeBasedOneTimePasswordGenerator TOTP = new TimeBasedOneTimePasswordGenerator(); + private static final TotpParameters TOTP_PARAMETERS = + new TotpParameters(TOTP.getAlgorithm(), TOTP.getPasswordLength(), TOTP.getTimeStep()); + + private final FaultTolerantRedisClusterClient rateLimitCluster; + private final Duration maxTotpValidationDelay; + private final KeyGenerator totpKeyGenerator; + + + public TotpManager(final FaultTolerantRedisClusterClient rateLimitCluster, final Duration maxTotpValidationDelay) { + if (maxTotpValidationDelay.compareTo(TOTP.getTimeStep()) > 0) { + throw new IllegalArgumentException("Max TOTP validation delay must be less than or equal to TOTP time step"); + } + + this.rateLimitCluster = rateLimitCluster; + this.maxTotpValidationDelay = maxTotpValidationDelay; + try { + this.totpKeyGenerator = KeyGenerator.getInstance(TOTP.getAlgorithm()); + totpKeyGenerator.init(getTotpKeyLengthBits()); + } catch (final NoSuchAlgorithmException e) { + throw new AssertionError("Every implementation of the Java platform is required to support the HmacSHA256 KeyGenerator algorithm", e); + } + + } + + public TotpKey generateTotpKey() { + final SecretKey secretKey = totpKeyGenerator.generateKey(); + return new TotpKey(TOTP_PARAMETERS, secretKey.getEncoded()); + } + + + /// Verifies the provided `oneTimePassword` against the account's registered TOTP keys. + /// + /// TOTPs are checked against the provided `validationTimestamp` but allow for some staleness configured via + /// `maxTotpValidationDelay`. An OTP can only be used once per time-window. + /// + /// @param account The account to check + /// @param validationTimestamp The current time to check against + /// @param oneTimePassword The `oneTimePassword` to check against the account + /// + /// @return true if the `oneTimePassword` matches at least one of the keys registered in the account, or if the + /// account has no keys AND the provided `oneTimePassword` is `null`. + public boolean verifyTotp(final Account account, final Instant validationTimestamp, @Nullable final Integer oneTimePassword) { + final List totpKeys = account.getMfaKeys().values().stream().filter(AnnotatedTotpKey.class::isInstance).map(AnnotatedTotpKey.class::cast).toList(); + if (totpKeys.isEmpty()) { + return oneTimePassword == null; + } + + if (oneTimePassword == null) { + // The account has TOTP keys, but the caller hasn't provided a one-time password + return false; + } + + for (final SecretKey totpKey : totpKeys) { + try { + if (evaluateTotp(account.getAccountIdentifier(), totpKey, validationTimestamp, oneTimePassword) == TotpOutcome.MATCH) { + return true; + } + } catch (final InvalidKeyException e) { + ImpossibleEvents.logImpossible(logger, "Invalid TOTP key for account {}", account.getAccountIdentifier(), e); + } + } + + return false; + } + + + /// Check the provided `oneTimePassword` against a specific `totpKey`. This can be used to confirm that a specific key + /// matches the provided `oneTimePassword`. This method marks the provided `oneTimePassword` as used, but does not + /// fail if the password is used multiple times. + /// + /// @return true if the `oneTimePassword` matches the provided `totpKey`, regardless of whether it has been checked before + boolean checkTotpMatches(final UUID aci, final SecretKey totpKey, final Instant validationTimestamp, final int oneTimePassword) throws InvalidKeyException { + return switch(evaluateTotp(aci, totpKey, validationTimestamp, oneTimePassword)) { + case MISMATCH -> false; + case REUSED, MATCH -> true; + }; + } + + private enum TotpOutcome { + /// The TOTP matched the key and this is the first time the TOTP was seen + MATCH, + /// The TOTP did not match the key + MISMATCH, + /// The TOTP matched the key, but has been seen before + REUSED + } + + /// Check the provided `oneTimePassword` against a specific `totpKey` + private TotpOutcome evaluateTotp(final UUID aci, final SecretKey totpKey, final Instant validationTimestamp, final int oneTimePassword) throws InvalidKeyException { + for (final Instant timestamp : new Instant[]{validationTimestamp, validationTimestamp.minus(maxTotpValidationDelay)}) { + if (TOTP.validateOneTimePassword(totpKey, timestamp, oneTimePassword)) { + return claimTotp(aci, oneTimePassword) ? TotpOutcome.MATCH : TotpOutcome.REUSED; + } + } + return TotpOutcome.MISMATCH; + } + + /// @return true if this was the first time this OTP was used + private boolean claimTotp(final UUID aci, final int oneTimePassword) { + return rateLimitCluster.withCluster(conn -> + "OK".equals(conn.sync().set(getTotpFreshnessKey(aci, oneTimePassword), "", SetArgs.Builder + .nx() + .ex(TOTP.getTimeStep().plus(maxTotpValidationDelay))))); + } + + private static String getTotpFreshnessKey(final UUID aci, final int oneTimePassword) { + return "totp_used::" + aci + "::" + oneTimePassword; + } + + @VisibleForTesting + static int getTotpKeyLengthBits() { + try { + // The HOTP/TOTP spec recommends using a key length that's the same as the HMAC block length + return Mac.getInstance(TOTP.getAlgorithm()).getMacLength() * 8; + } catch (final NoSuchAlgorithmException e) { + throw new AssertionError("Algorithm used by TOTP generator not found", e); + } + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index 6a8d07e1b..df83d404e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -85,6 +85,7 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager; import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; import org.whispersystems.textsecuregcm.storage.Subscriptions; +import org.whispersystems.textsecuregcm.storage.TotpManager; import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase; import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher; @@ -379,6 +380,9 @@ public record CommandDependencies( configuration.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient); final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager( changeNumberWaitingPeriods, configuration.getChangeNumber().postRegistrationWaitingPeriod(), clock); + final TotpManager totpManager = new TotpManager( + rateLimitersCluster, + configuration.getRegistrationTotpConfiguration().maxValidationDelay()); final WebAuthnCeremonyManager webAuthnCeremonyManager = new WebAuthnCeremonyManager( configuration.getRegistrationWebAuthnConfiguration().relyingPartyId(), configuration.getRegistrationWebAuthnConfiguration().origin(), @@ -390,8 +394,7 @@ public record CommandDependencies( changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager, phoneNumberRecoveryPasswordsManager, messagePollExecutor, retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), - configuration.getRegistrationTotpConfiguration().maxValidationDelay(), - webAuthnCeremonyManager); + webAuthnCeremonyManager, totpManager); RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor); final BackupsDb backupsDb = new BackupsDb(dynamoDbAsyncClient, configuration.getDynamoDbTables().getBackups().getTableName(), clock); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java index 59aa1661c..82530a992 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java @@ -150,6 +150,7 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsMana import org.whispersystems.textsecuregcm.storage.TooManyMfaKeysException; import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException; import org.whispersystems.textsecuregcm.storage.TotpKey; +import org.whispersystems.textsecuregcm.storage.TotpManager; import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException; import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; @@ -182,9 +183,9 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest mfaKeys, - final Instant timestamp, - @Nullable final Integer oneTimePassword, - final boolean expectVerified) { - - final Account account = mock(Account.class); - when(account.getMfaKeys()).thenReturn(mfaKeys); - - assertEquals(expectVerified, accountsManager.verifyTotp(account, timestamp, oneTimePassword)); - } - - private static List verifyTotp() throws NoSuchAlgorithmException, InvalidKeyException { - final Instant timestamp = Instant.now(); - - final AnnotatedTotpKey totpKey; - final AnnotatedTotpKey secondTotpKey; - { - final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP.getAlgorithm()); - totpKeyGenerator.init(AccountsManager.getTotpKeyLengthBits()); - - totpKey = new AnnotatedTotpKey( - new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()), - TestRandomUtil.nextBytes(16)); - - secondTotpKey = new AnnotatedTotpKey( - new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()), - TestRandomUtil.nextBytes(16)); - } - - return List.of( - Arguments.argumentSet("No keys, no password provided", - Collections.emptyMap(), timestamp, null, true), - - Arguments.argumentSet("No keys, password provided", - Collections.emptyMap(), timestamp, 123456, false), - - Arguments.argumentSet("Has key, correct password provided", - Map.of((byte) 1, totpKey), timestamp, AccountsManager.TOTP.generateOneTimePassword(totpKey, timestamp), true), - - Arguments.argumentSet("Has key, incorrect password provided", - Map.of((byte) 1, totpKey), timestamp, AccountsManager.TOTP.generateOneTimePassword(totpKey, timestamp) + 1, false), - - Arguments.argumentSet("Has key, no password provided", - Map.of((byte) 1, totpKey), timestamp, null, false), - - Arguments.argumentSet("Has multiple keys, correct password provided for one key", - Map.of((byte) 1, totpKey, (byte) 2, secondTotpKey), timestamp, AccountsManager.TOTP.generateOneTimePassword(totpKey, timestamp), true) - ); - } - - @RepeatedTest(value = 10, failureThreshold = 2) - void verifyTotpWithDelay() throws NoSuchAlgorithmException, InvalidKeyException, TooManyMfaKeysException { - final AnnotatedTotpKey totpKey; - { - final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP.getAlgorithm()); - totpKeyGenerator.init(AccountsManager.getTotpKeyLengthBits()); - - totpKey = new AnnotatedTotpKey( - new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()), - TestRandomUtil.nextBytes(16)); - } - - final Account account = mock(Account.class); - when(account.getMfaKeys()).thenReturn(Map.of((byte) 1, totpKey)); - - final Instant beginningOfTotpWindow = totpWindowStart(Instant.now()); - final int oneTimePassword = AccountsManager.TOTP.generateOneTimePassword(totpKey, beginningOfTotpWindow); - - assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow, oneTimePassword), - "One-time password should be valid at the start of the window in which it was generated"); - - assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep()), oneTimePassword), - "One-time password should be valid at the start of the window after which it was generated"); - - assertTrue(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY).minusMillis(1), oneTimePassword), - "One-time password should be valid up until max delay after end of current TOTP window"); - - // With six-digit OTPs, there's a one-in-a-million chance of this returning a false positive, and so we repeat the - // test several allowing for failure - assertFalse(accountsManager.verifyTotp(account, beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY), oneTimePassword), - "One-time password should not be valid after max delay past end of current TOTP window"); - } - private static Instant totpWindowStart(final Instant instant) { - return Instant.ofEpochMilli((instant.toEpochMilli() / AccountsManager.TOTP.getTimeStep().toMillis()) * - AccountsManager.TOTP.getTimeStep().toMillis()); + return Instant.ofEpochMilli((instant.toEpochMilli() / TotpManager.TOTP.getTimeStep().toMillis()) * + TotpManager.TOTP.getTimeStep().toMillis()); } @Nested diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerUsernameIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerUsernameIntegrationTest.java index 96056ff20..27f9c5f61 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerUsernameIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerUsernameIntegrationTest.java @@ -157,7 +157,7 @@ class AccountsManagerUsernameIntegrationTest { Executors.newSingleThreadScheduledExecutor(), Clock.systemUTC(), "link-device-secret".getBytes(StandardCharsets.UTF_8), - AccountsManager.TOTP.getTimeStep().dividedBy(2), + null, null); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java index f747f4248..3a80fcddf 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java @@ -156,7 +156,7 @@ public class AddRemoveDeviceIntegrationTest { scheduledExecutorService, clock, "link-device-secret".getBytes(StandardCharsets.UTF_8), - AccountsManager.TOTP.getTimeStep().dividedBy(2), + null, null); accountsManager.start(); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/TotpManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/TotpManagerTest.java new file mode 100644 index 000000000..90673f7c1 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/TotpManagerTest.java @@ -0,0 +1,166 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.Instant; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.annotation.Nullable; +import javax.crypto.KeyGenerator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; + +class TotpManagerTest { + + @RegisterExtension + private static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); + + private static final Duration MAX_TOTP_VALIDATION_DELAY = TotpManager.TOTP.getTimeStep().dividedBy(2); + + private static final TotpParameters TOTP_PARAMETERS = new TotpParameters(TotpManager.TOTP.getAlgorithm(), + TotpManager.TOTP.getPasswordLength(), + TotpManager.TOTP.getTimeStep()); + + private TotpManager totpManager; + + @BeforeEach + void setUp() { + totpManager = new TotpManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), MAX_TOTP_VALIDATION_DELAY); + } + + private static AnnotatedTotpKey generateTotpKey() throws NoSuchAlgorithmException { + final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(TotpManager.TOTP.getAlgorithm()); + totpKeyGenerator.init(TotpManager.getTotpKeyLengthBits()); + + return new AnnotatedTotpKey(new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()), + TestRandomUtil.nextBytes(16)); + } + + private static Instant totpWindowStart(final Instant instant) { + return Instant.ofEpochMilli((instant.toEpochMilli() / TotpManager.TOTP.getTimeStep().toMillis()) * + TotpManager.TOTP.getTimeStep().toMillis()); + } + + + @Test + void checkTotpAcceptsReuse() throws NoSuchAlgorithmException, InvalidKeyException { + final AnnotatedTotpKey totpKey = generateTotpKey(); + + final Instant timestamp = Instant.now(); + final int oneTimePassword = TotpManager.TOTP.generateOneTimePassword(totpKey, timestamp); + final UUID aci = UUID.randomUUID(); + + assertTrue(totpManager.checkTotpMatches(aci, totpKey.totpKey(), timestamp, oneTimePassword)); + assertTrue(totpManager.checkTotpMatches(aci, totpKey.totpKey(), timestamp, oneTimePassword)); + assertFalse(totpManager.checkTotpMatches(aci, totpKey.totpKey(), timestamp, oneTimePassword + 1)); + } + + @Test + void verifyTotpRejectsReuse() throws NoSuchAlgorithmException, InvalidKeyException { + final AnnotatedTotpKey totpKey = generateTotpKey(); + + final Account account = mock(Account.class); + when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); + when(account.getMfaKeys()).thenReturn(Map.of((byte) 1, totpKey)); + + final Instant timestamp = Instant.now(); + final int oneTimePassword = TotpManager.TOTP.generateOneTimePassword(totpKey, timestamp); + + assertTrue(totpManager.verifyTotp(account, timestamp, oneTimePassword)); + + assertFalse(totpManager.verifyTotp(account, timestamp, oneTimePassword), + "One-time password should not be redeemable more than once"); + + // A different ACI / same one-time password should work + when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); + assertTrue(totpManager.verifyTotp(account, timestamp, oneTimePassword)); + } + + @RepeatedTest(value = 10, failureThreshold = 2) + void verifyTotpWithDelay() throws NoSuchAlgorithmException, InvalidKeyException { + final AnnotatedTotpKey totpKey = generateTotpKey(); + + final Account account = mock(Account.class); + when(account.getAccountIdentifier()).thenAnswer(_ -> UUID.randomUUID()); + when(account.getMfaKeys()).thenReturn(Map.of((byte) 1, totpKey)); + + final Instant beginningOfTotpWindow = totpWindowStart(Instant.now()); + final int oneTimePassword = TotpManager.TOTP.generateOneTimePassword(totpKey, beginningOfTotpWindow); + + assertTrue(totpManager.verifyTotp(account, beginningOfTotpWindow, oneTimePassword), + "One-time password should be valid at the start of the window in which it was generated"); + + assertTrue(totpManager.verifyTotp(account, beginningOfTotpWindow.plus(TotpManager.TOTP.getTimeStep()), oneTimePassword), + "One-time password should be valid at the start of the window after which it was generated"); + + assertTrue(totpManager.verifyTotp(account, beginningOfTotpWindow.plus(TotpManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY).minusMillis(1), oneTimePassword), + "One-time password should be valid up until max delay after end of current TOTP window"); + + // With six-digit OTPs, there's a one-in-a-million chance of this returning a false positive, and so we repeat the + // test several allowing for failure + assertFalse(totpManager.verifyTotp(account, beginningOfTotpWindow.plus(TotpManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY), oneTimePassword), + "One-time password should not be valid after max delay past end of current TOTP window"); + } + + @ParameterizedTest + @MethodSource + void verifyTotp(final Map mfaKeys, + final Instant timestamp, + @Nullable final Integer oneTimePassword, + final boolean expectVerified) { + + final Account account = mock(Account.class); + when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); + when(account.getMfaKeys()).thenReturn(mfaKeys); + + assertEquals(expectVerified, totpManager.verifyTotp(account, timestamp, oneTimePassword)); + } + + private static List verifyTotp() throws NoSuchAlgorithmException, InvalidKeyException { + final Instant timestamp = Instant.now(); + + final AnnotatedTotpKey totpKey = generateTotpKey(); + final AnnotatedTotpKey secondTotpKey = generateTotpKey(); + + return List.of( + Arguments.argumentSet("No keys, no password provided", + Collections.emptyMap(), timestamp, null, true), + + Arguments.argumentSet("No keys, password provided", + Collections.emptyMap(), timestamp, 123456, false), + + Arguments.argumentSet("Has key, correct password provided", + Map.of((byte) 1, totpKey), timestamp, TotpManager.TOTP.generateOneTimePassword(totpKey, timestamp), true), + + Arguments.argumentSet("Has key, incorrect password provided", + Map.of((byte) 1, totpKey), timestamp, TotpManager.TOTP.generateOneTimePassword(totpKey, timestamp) + 1, false), + + Arguments.argumentSet("Has key, no password provided", + Map.of((byte) 1, totpKey), timestamp, null, false), + + Arguments.argumentSet("Has multiple keys, correct password provided for one key", + Map.of((byte) 1, totpKey, (byte) 2, secondTotpKey), timestamp, TotpManager.TOTP.generateOneTimePassword(totpKey, timestamp), true) + ); + } +}