Forbid reuse of TOTPs

This commit is contained in:
Ravi Khadiwala authored and ravi-signal committed 2026-09-23 13:31:22 -05:00
1 parent 7866ad18fa
commit 9b8502bb6e
16 files changed
+364 -194

No files matched your search

@@ -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<WhisperServerConfiguration
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
final TotpManager totpManager = new TotpManager(rateLimitersCluster, config.getRegistrationTotpConfiguration().maxValidationDelay());
final WebAuthnCeremonyManager webAuthnCeremonyManager = new WebAuthnCeremonyManager(
config.getRegistrationWebAuthnConfiguration().relyingPartyId(),
config.getRegistrationWebAuthnConfiguration().origin(),
@@ -825,8 +827,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
config.getRegistrationTotpConfiguration().maxValidationDelay(),
webAuthnCeremonyManager);
webAuthnCeremonyManager, totpManager);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
@@ -432,14 +432,14 @@ public class RegistrationController {
throw new ForbiddenException();
}
existingAccount = checkMfa(existingAccount, registrationRequest.webAuthnResponse(), registrationRequest.totp());
if (!registrationRequest.skipDeviceTransfer() && existingAccount.hasCapability(DeviceCapability.TRANSFER)) {
// If a device transfer is possible, clients must explicitly opt out of a transfer (i.e. after prompting the user)
// before we'll let them recover an account and start "from scratch"
throw new WebApplicationException(Response.status(409, "device transfer available").build());
}
existingAccount = checkMfa(existingAccount, registrationRequest.webAuthnResponse(), registrationRequest.totp());
final Account reclaimedAccount = existingAccount.getNumber().isPresent()
? recoverAccountWithPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent)
: recoverAccountWithoutPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent);
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.storage;
import static java.util.Objects.requireNonNull;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.annotations.VisibleForTesting;
@@ -64,9 +63,7 @@ import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.protocol.IdentityKey;
@@ -153,9 +150,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> implemen
}
public boolean verifyTotp(final Account account, final Instant validationTimestamp, @Nullable final Integer oneTimePassword) {
final List<AnnotatedTotpKey> 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.
@@ -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<AnnotatedTotpKey> 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);
}
}
}
@@ -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);
@@ -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<AccountsGrpcService, Ac
private static final org.whispersystems.textsecuregcm.storage.TotpParameters TOTP_PARAMETERS =
new org.whispersystems.textsecuregcm.storage.TotpParameters(
AccountsManager.TOTP.getAlgorithm(),
AccountsManager.TOTP.getPasswordLength(),
AccountsManager.TOTP.getTimeStep());
TotpManager.TOTP.getAlgorithm(),
TotpManager.TOTP.getPasswordLength(),
TotpManager.TOTP.getTimeStep());
private static final int MFA_KEY_METADATA_SIZE = 160;
@@ -1160,9 +1161,9 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
assertEquals(GenerateTotpKeyResponse.ResponseCase.KEY_GENERATED, response.getResponseCase());
assertArrayEquals(encodedKey, response.getKeyGenerated().getKey().toByteArray());
assertEquals(AccountsManager.TOTP.getAlgorithm(), response.getKeyGenerated().getTotpParameters().getAlgorithm());
assertEquals(AccountsManager.TOTP.getPasswordLength(), response.getKeyGenerated().getTotpParameters().getPasswordLength());
assertEquals(AccountsManager.TOTP.getTimeStep().toSeconds(), response.getKeyGenerated().getTotpParameters().getTimeStepSeconds());
assertEquals(TotpManager.TOTP.getAlgorithm(), response.getKeyGenerated().getTotpParameters().getAlgorithm());
assertEquals(TotpManager.TOTP.getPasswordLength(), response.getKeyGenerated().getTotpParameters().getPasswordLength());
assertEquals(TotpManager.TOTP.getTimeStep().toSeconds(), response.getKeyGenerated().getTotpParameters().getTimeStepSeconds());
}
@Test
@@ -10,11 +10,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import java.util.Base64;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
@@ -175,7 +175,7 @@ public class AccountCreationDeletionIntegrationTest {
executor,
CLOCK,
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null,
null);
}
@@ -155,7 +155,7 @@ class AccountsManagerChangeNumberIntegrationTest {
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null,
null);
}
}
@@ -136,7 +136,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
mock(ScheduledExecutorService.class),
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null,
null
);
}
@@ -71,7 +71,7 @@ public class AccountsManagerDeviceTransferIntegrationTest {
mock(ScheduledExecutorService.class),
Clock.systemUTC(),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null,
null);
accountsManager.start();
@@ -141,7 +141,7 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest {
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null,
null);
}
}
@@ -80,7 +80,6 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.function.Executable;
@@ -138,11 +137,11 @@ class AccountsManagerTest {
private static final byte[] LINK_DEVICE_SECRET = "link-device-secret".getBytes(StandardCharsets.UTF_8);
private static final Duration MAX_TOTP_VALIDATION_DELAY = AccountsManager.TOTP.getTimeStep().dividedBy(2);
private static final Duration MAX_TOTP_VALIDATION_DELAY = TotpManager.TOTP.getTimeStep().dividedBy(2);
private static final TotpParameters TOTP_PARAMETERS = new TotpParameters(AccountsManager.TOTP.getAlgorithm(),
AccountsManager.TOTP.getPasswordLength(),
AccountsManager.TOTP.getTimeStep());
private static final TotpParameters TOTP_PARAMETERS = new TotpParameters(TotpManager.TOTP.getAlgorithm(),
TotpManager.TOTP.getPasswordLength(),
TotpManager.TOTP.getTimeStep());
private static TestClock CLOCK;
@@ -270,8 +269,8 @@ class AccountsManagerTest {
mock(ScheduledExecutorService.class),
CLOCK,
LINK_DEVICE_SECRET,
MAX_TOTP_VALIDATION_DELAY,
webAuthnCeremonyManager);
webAuthnCeremonyManager,
new TotpManager(redisCluster, MAX_TOTP_VALIDATION_DELAY));
}
@ParameterizedTest
@@ -2004,7 +2003,7 @@ class AccountsManagerTest {
final Instant timestamp = Instant.now();
assertEquals(Optional.of(nextTotpKeyId), accountsManager.confirmPendingTotpKey(accountIdentifier,
AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp),
TotpManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp),
timestamp,
TestRandomUtil.nextBytes(16)));
@@ -2028,18 +2027,18 @@ class AccountsManagerTest {
when(account.getNextMfaKeyId()).thenReturn(nextTotpKeyId);
final Instant beginningOfTotpWindow = totpWindowStart(Instant.now());
final int oneTimePassword = AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, beginningOfTotpWindow);
final int oneTimePassword = TotpManager.TOTP.generateOneTimePassword(pendingTotpKey, beginningOfTotpWindow);
// Should be rejected since even after delay allowance, our otp is from the previous window
assertEquals(Optional.empty(), accountsManager.confirmPendingTotpKey(accountIdentifier,
oneTimePassword,
beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY),
beginningOfTotpWindow.plus(TotpManager.TOTP.getTimeStep()).plus(MAX_TOTP_VALIDATION_DELAY),
TestRandomUtil.nextBytes(16)));
// Should still be accepted as MAX_TOTP_VALIDATION_DELAY delay brings us to the otp's window
assertEquals(Optional.of(nextTotpKeyId), accountsManager.confirmPendingTotpKey(accountIdentifier,
oneTimePassword,
beginningOfTotpWindow.plus(AccountsManager.TOTP.getTimeStep())
beginningOfTotpWindow.plus(TotpManager.TOTP.getTimeStep())
.plus(MAX_TOTP_VALIDATION_DELAY)
.minus(Duration.ofMillis(1)),
TestRandomUtil.nextBytes(16)));
@@ -2058,8 +2057,8 @@ class AccountsManagerTest {
final AnnotatedTotpKey confirmedTotpKey;
{
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP.getAlgorithm());
totpKeyGenerator.init(AccountsManager.getTotpKeyLengthBits());
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(TotpManager.TOTP.getAlgorithm());
totpKeyGenerator.init(TotpManager.getTotpKeyLengthBits());
confirmedTotpKey = new AnnotatedTotpKey(
new TotpKey(TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
@@ -2076,7 +2075,7 @@ class AccountsManagerTest {
final Instant timestamp = Instant.now();
assertEquals(Optional.of(keyId), accountsManager.confirmPendingTotpKey(accountIdentifier,
AccountsManager.TOTP.generateOneTimePassword(confirmedTotpKey, timestamp),
TotpManager.TOTP.generateOneTimePassword(confirmedTotpKey, timestamp),
timestamp,
TestRandomUtil.nextBytes(16)));
}
@@ -2099,7 +2098,7 @@ class AccountsManagerTest {
final Instant timestamp = Instant.now();
assertEquals(Optional.empty(), accountsManager.confirmPendingTotpKey(accountIdentifier,
AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp),
TotpManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp),
timestamp,
TestRandomUtil.nextBytes(16)));
}
@@ -2122,7 +2121,7 @@ class AccountsManagerTest {
when(account.getNextMfaKeyId()).thenReturn(nextTotpKeyId);
final Instant timestamp = Instant.now();
final int incorrectPassword = AccountsManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp) + 1;
final int incorrectPassword = TotpManager.TOTP.generateOneTimePassword(pendingTotpKey, timestamp) + 1;
assertEquals(Optional.empty(), accountsManager.confirmPendingTotpKey(accountIdentifier,
incorrectPassword,
@@ -2133,94 +2132,9 @@ class AccountsManagerTest {
}
}
@ParameterizedTest
@MethodSource
void verifyTotp(final Map<Byte, AnnotatedMfaKey> 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<Arguments> 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
@@ -157,7 +157,7 @@ class AccountsManagerUsernameIntegrationTest {
Executors.newSingleThreadScheduledExecutor(),
Clock.systemUTC(),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2),
null,
null);
}
@@ -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();
@@ -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<Byte, AnnotatedMfaKey> 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<Arguments> 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)
);
}
}