Check TOTP at registration time

This commit is contained in:
Jon Chambers authored and GitHub committed 2026-08-20 11:38:09 -04:00
1 parent 2b3a6e1aa5
commit 863057d659
19 files changed
+444 -16

No files matched your search

@@ -112,6 +112,7 @@ public final class Operations {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
null,
receiptCredentialPresentation.serialize(),
null,
user.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
@@ -146,6 +147,7 @@ public final class Operations {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
registrationPassword,
null,
null,
accountAttributes,
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
@@ -63,6 +63,7 @@ import org.whispersystems.textsecuregcm.configuration.SpamFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.TlsKeyStoreConfiguration;
import org.whispersystems.textsecuregcm.configuration.TotpConfiguration;
import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration;
@@ -379,6 +380,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private FoundationDbMessagesConfiguration foundationDbMessages;
@Valid
@NotNull
@JsonProperty
private TotpConfiguration registrationTotp = TotpConfiguration.DEFAULT;
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -633,4 +639,8 @@ public class WhisperServerConfiguration extends Configuration {
public FoundationDbMessagesConfiguration getFoundationDbMessagesConfiguration() {
return foundationDbMessages;
}
public TotpConfiguration getRegistrationTotpConfiguration() {
return registrationTotp;
}
}
@@ -804,7 +804,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
config.getRegistrationTotpConfiguration().maxValidationDelay());
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());
@@ -0,0 +1,20 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
public record TotpConfiguration(@NotNull Duration maxValidationDelay) {
public static TotpConfiguration DEFAULT = new TotpConfiguration(Duration.ofSeconds(15));
public TotpConfiguration {
if (maxValidationDelay == null) {
maxValidationDelay = DEFAULT.maxValidationDelay();
}
}
}
@@ -149,6 +149,7 @@ public class RegistrationController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ApiResponse(responseCode = "441", description = "A valid one-time password (TOTP) is required, but either no password was provided or it was incorrect")
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
public AccountCreationResponse register(
@Parameter(
@@ -272,6 +273,8 @@ public class RegistrationController {
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(),
registrationRequest.accountAttributes().getRegistrationLock(),
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType);
checkTotp(existingAccount.get(), registrationRequest.totp());
}
final Account account = accounts.create(number,
@@ -420,6 +423,8 @@ public class RegistrationController {
throw new ForbiddenException();
}
checkTotp(existingAccount, 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"
@@ -502,4 +507,12 @@ public class RegistrationController {
registrationRequest.deviceActivationRequest().gcmToken()),
userAgent);
}
private void checkTotp(final Account account, @Nullable final Integer totp) throws RateLimitExceededException {
rateLimiters.getCheckTotpLimiter().validate(account.getAccountIdentifier());
if (!accounts.verifyTotp(account, clock.instant(), totp)) {
throw new WebApplicationException(441);
}
}
}
@@ -17,6 +17,7 @@ import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import jakarta.validation.constraints.PositiveOrZero;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
@@ -49,6 +50,13 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@Nullable
byte[] receiptCredentialPresentation,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A TOTP one-time password; required if recovering an account that has TOTP keys.
""")
@PositiveOrZero
@Nullable
Integer totp,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
@@ -65,6 +65,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
CREATE_DONATION_PERMIT("createDonationCredential", new RateLimiterConfig(30, Duration.ofHours(4), true)),
ONE_TIME_DONATION("oneTimeDonation", new RateLimiterConfig(5, Duration.ofMinutes(1), true)),
ADD_SUBSCRIPTION_PAYMENT_METHOD("addSubscriptionPaymentMethod", new RateLimiterConfig(10, Duration.ofMinutes(1), true)),
CHECK_TOTP("checkTotp", new RateLimiterConfig(5, Duration.ofSeconds(6), false))
;
private final String id;
@@ -250,4 +251,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
public RateLimiter getCreateDonationPermitLimiter() {
return forDescriptor(For.CREATE_DONATION_PERMIT);
}
public RateLimiter getCheckTotpLimiter() {
return forDescriptor(For.CHECK_TOTP);
}
}
@@ -61,6 +61,7 @@ import java.util.function.Consumer;
import java.util.function.Function;
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;
@@ -147,6 +148,7 @@ 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 TimeBasedOneTimePasswordGenerator totpGenerator;
@@ -293,15 +295,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final AccountLockManager accountLockManager,
final KeysManager keysManager,
final MessagesManager messagesManager,
final ProfilesManager profilesManager, final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager,
final ProfilesManager profilesManager,
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager,
final SecureStorageClient secureStorageClient,
final SecureValueRecoveryClient secureValueRecovery2Client,
final DisconnectionRequestManager disconnectionRequestManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final Executor accountLockExecutor,
final ScheduledExecutorService messagesPollExecutor, final ScheduledExecutorService retryExecutor,
final ScheduledExecutorService messagesPollExecutor,
final ScheduledExecutorService retryExecutor,
final Clock clock,
final byte[] linkDeviceSecret) {
final byte[] linkDeviceSecret,
final Duration maxTotpValidationDelay) {
this.accounts = accounts;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.cacheCluster = cacheCluster;
@@ -320,6 +325,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.retryExecutor = retryExecutor;
this.clock = requireNonNull(clock);
if (maxTotpValidationDelay.compareTo(TOTP_PARAMETERS.timeStep()) > 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
@@ -2110,4 +2121,29 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
})
.map(Map.Entry::getKey));
}
public boolean verifyTotp(final Account account, final Instant validationTimestamp, @Nullable final Integer oneTimePassword) {
if (account.getTotpKeys().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 Instant timestamp : new Instant[] { validationTimestamp, validationTimestamp.minus(maxTotpValidationDelay) }) {
for (final SecretKey totpKey : account.getTotpKeys().values()) {
try {
if (totpGenerator.validateOneTimePassword(totpKey, timestamp, oneTimePassword)) {
return true;
}
} catch (final InvalidKeyException e) {
ImpossibleEvents.logImpossible(logger, "Invalid TOTP key for account {}", account.getAccountIdentifier(), e);
}
}
}
return false;
}
}
@@ -357,7 +357,8 @@ public record CommandDependencies(
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value());
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value(),
configuration.getRegistrationTotpConfiguration().maxValidationDelay());
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
final BackupsDb backupsDb =
new BackupsDb(dynamoDbAsyncClient, configuration.getDynamoDbTables().getBackups().getTableName(), clock);
@@ -126,6 +126,7 @@ class RegistrationControllerTest {
private final PhoneVerificationTokenManager phoneVerificationTokenManager = mock(PhoneVerificationTokenManager.class);
private final RateLimiter registrationLimiter = mock(RateLimiter.class);
private final RateLimiter totpLimiter = mock(RateLimiter.class);
private static final Clock CLOCK = TestClock.pinned(Instant.now());
@@ -152,6 +153,7 @@ class RegistrationControllerTest {
@BeforeEach
void setUp() throws Exception {
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
when(rateLimiters.getCheckTotpLimiter()).thenReturn(totpLimiter);
when(accountsManager.update(any(UUID.class), any())).thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
@@ -162,6 +164,7 @@ class RegistrationControllerTest {
return invocation.getArgument(0);
});
when(accountsManager.verifyTotp(any(), any(), any())).thenReturn(true);
reset(DYNAMIC_CONFIGURATION_MANAGER, DYNAMIC_CONFIGURATION);
@@ -408,6 +411,50 @@ class RegistrationControllerTest {
}
}
@Test
void totpInvalid() {
final Account existingAccount = mock(Account.class);
when(existingAccount.getNumber()).thenReturn(Optional.of(NUMBER));
when(accountsManager.getByE164(any())).thenReturn(Optional.of(existingAccount));
when(accountsManager.verifyTotp(any(), any(), any())).thenReturn(false);
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJson("sessionId", new byte[0], false, 1, 2)))) {
assertEquals(441, response.getStatus());
}
verify(accountsManager, never()).create(any(), any(), any(), any(), any(), any());
}
@Test
void totpRateLimited() throws RateLimitExceededException {
final Account existingAccount = mock(Account.class);
when(existingAccount.getAccountIdentifier()).thenReturn(UUID.randomUUID());
when(existingAccount.getNumber()).thenReturn(Optional.of(NUMBER));
when(accountsManager.getByE164(any())).thenReturn(Optional.of(existingAccount));
doThrow(new RateLimitExceededException(Duration.ofSeconds(5)))
.when(totpLimiter).validate(any(UUID.class));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(NUMBER, PASSWORD));
try (Response response = request.post(Entity.json(requestJson("sessionId", new byte[0], false, 1, 2)))) {
assertEquals(429, response.getStatus());
}
verify(accountsManager, never()).verifyTotp(any(), any(), any());
verify(accountsManager, never()).create(any(), any(), any(), any(), any(), any());
}
// this is functionally the same as deviceTransferAvailable(existingAccount=false)
@ParameterizedTest
@ValueSource(booleans = {true, false})
@@ -483,7 +530,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
fetchesMessagesAccountAttributes,
null, fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
@@ -498,6 +545,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
@@ -513,6 +561,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
pushAccountAttributes,
true,
aciIdentityKey,
@@ -567,6 +616,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -582,6 +632,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -597,6 +648,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -612,6 +664,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -627,6 +680,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
accountAttributes,
true,
null,
@@ -642,6 +696,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -721,6 +776,7 @@ class RegistrationControllerTest {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
new byte[0],
receiptCredentialPresentation.serialize(),
null,
accountAttributes,
true,
aciIdentityKey,
@@ -797,6 +853,7 @@ class RegistrationControllerTest {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
new byte[0],
receiptCredentialPresentation.serialize(),
null,
accountAttributes,
true,
aciIdentityKey,
@@ -840,6 +897,7 @@ class RegistrationControllerTest {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
new byte[0],
receiptCredentialPresentation,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -897,6 +955,7 @@ class RegistrationControllerTest {
Base64.getEncoder().encodeToString("session-id".getBytes(StandardCharsets.UTF_8)),
new byte[0],
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
null,
accountAttributes,
true,
aciIdentityKey,
@@ -940,6 +999,7 @@ class RegistrationControllerTest {
null,
recoveryPassword,
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
null,
accountAttributes,
true,
aciIdentityKey,
@@ -975,6 +1035,7 @@ class RegistrationControllerTest {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
new byte[0],
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1023,6 +1084,7 @@ class RegistrationControllerTest {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
new byte[0],
receiptCredentialPresentation.serialize(),
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1058,6 +1120,7 @@ class RegistrationControllerTest {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
new byte[0],
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1105,6 +1168,7 @@ class RegistrationControllerTest {
Base64.getEncoder().encodeToString("session-id".getBytes(StandardCharsets.UTF_8)),
new byte[0],
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1182,6 +1246,7 @@ class RegistrationControllerTest {
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
existingRecoveryPassword,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1307,6 +1372,7 @@ class RegistrationControllerTest {
existingAccount,
existingAccount.getAccountIdentifier(),
new RegistrationRequest(null,
null,
null,
null,
accountAttributes,
@@ -1325,6 +1391,7 @@ class RegistrationControllerTest {
existingAccount,
existingAccount.getAccountIdentifier(),
new RegistrationRequest("session-id",
null,
null,
null,
accountAttributes,
@@ -1345,6 +1412,7 @@ class RegistrationControllerTest {
new RegistrationRequest(null,
null,
TestRandomUtil.nextBytes(16),
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1363,6 +1431,7 @@ class RegistrationControllerTest {
new RegistrationRequest(null,
existingRecoveryPassword,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1381,6 +1450,7 @@ class RegistrationControllerTest {
new RegistrationRequest(null,
existingRecoveryPassword,
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1399,6 +1469,7 @@ class RegistrationControllerTest {
new RegistrationRequest(null,
TestRandomUtil.nextBytes(32),
null,
null,
accountAttributes,
true,
aciIdentityKey,
@@ -1417,6 +1488,7 @@ class RegistrationControllerTest {
new RegistrationRequest(null,
existingRecoveryPassword,
null,
null,
accountAttributes,
false,
aciIdentityKey,
@@ -1431,6 +1503,151 @@ class RegistrationControllerTest {
);
}
@Test
void recoverAccountInvalidTotp() {
final IdentityKey aciIdentityKey;
final IdentityKey pniIdentityKey;
final ECSignedPreKey aciSignedPreKey;
final ECSignedPreKey pniSignedPreKey;
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
{
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair);
}
final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8);
final int registrationId = 1;
final int pniRegistrationId = 2;
final byte[] newRecoveryPassword = TestRandomUtil.nextBytes(32);
final Set<DeviceCapability> deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES;
final AccountAttributes accountAttributes =
new AccountAttributes(true, registrationId, pniRegistrationId, deviceName, null, false, deviceCapabilities, newRecoveryPassword)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
final byte[] existingRecoveryPassword = TestRandomUtil.nextBytes(32);
final Account existingAccount = new Account();
existingAccount.setAccountIdentifier(UUID.randomUUID());
existingAccount.setAccountRecoveryPassword(existingRecoveryPassword);
when(accountsManager.getByAccountIdentifier(existingAccount.getAccountIdentifier()))
.thenReturn(Optional.of(existingAccount));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(existingAccount.getAccountIdentifier().toString(), PASSWORD));
when(accountsManager.verifyTotp(any(), any(), any()))
.thenReturn(false);
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
existingRecoveryPassword,
null,
null,
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
Optional.of(pniSignedPreKey),
aciPqLastResortPreKey,
Optional.of(pniPqLastResortPreKey),
Optional.empty(),
Optional.empty()));
try (final Response response = request.post(Entity.json(requestToJson(registrationRequest)))) {
assertEquals(441, response.getStatus());
}
verify(accountsManager, never()).recover(any(), any(), any(), any(), any(), any());
verifyNoInteractions(phoneVerificationTokenManager);
}
@Test
void recoverAccountTotpRateLimited() throws RateLimitExceededException {
final IdentityKey aciIdentityKey;
final IdentityKey pniIdentityKey;
final ECSignedPreKey aciSignedPreKey;
final ECSignedPreKey pniSignedPreKey;
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
{
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair);
}
final byte[] deviceName = "test".getBytes(StandardCharsets.UTF_8);
final int registrationId = 1;
final int pniRegistrationId = 2;
final byte[] newRecoveryPassword = TestRandomUtil.nextBytes(32);
final Set<DeviceCapability> deviceCapabilities = DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES;
final AccountAttributes accountAttributes =
new AccountAttributes(true, registrationId, pniRegistrationId, deviceName, null, false, deviceCapabilities, newRecoveryPassword)
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
final byte[] existingRecoveryPassword = TestRandomUtil.nextBytes(32);
final Account existingAccount = new Account();
existingAccount.setAccountIdentifier(UUID.randomUUID());
existingAccount.setAccountRecoveryPassword(existingRecoveryPassword);
when(accountsManager.getByAccountIdentifier(existingAccount.getAccountIdentifier()))
.thenReturn(Optional.of(existingAccount));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/registration")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getProvisioningAuthHeader(existingAccount.getAccountIdentifier().toString(), PASSWORD));
doThrow(new RateLimitExceededException(Duration.ofSeconds(5)))
.when(totpLimiter).validate(any(UUID.class));
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
existingRecoveryPassword,
null,
null,
accountAttributes,
true,
aciIdentityKey,
pniIdentityKey,
new DeviceActivationRequest(aciSignedPreKey,
Optional.of(pniSignedPreKey),
aciPqLastResortPreKey,
Optional.of(pniPqLastResortPreKey),
Optional.empty(),
Optional.empty()));
try (final Response response = request.post(Entity.json(requestToJson(registrationRequest)))) {
assertEquals(429, response.getStatus());
}
verify(accountsManager, never()).verifyTotp(any(), any(), any());
verify(accountsManager, never()).recover(any(), any(), any(), any(), any(), any());
verifyNoInteractions(phoneVerificationTokenManager);
}
private static boolean accountAttributesEqual(final AccountAttributes a, final AccountAttributes b) {
return a.getFetchesMessages() == b.getFetchesMessages()
&& a.getRegistrationId() == b.getRegistrationId()
@@ -1449,7 +1666,7 @@ class RegistrationControllerTest {
void atomicAccountCreationSuccess(final RegistrationRequest registrationRequest,
final IdentityKey expectedAciIdentityKey,
final IdentityKey expectedPniIdentityKey,
final DeviceSpec expectedDeviceSpec) throws InterruptedException {
final DeviceSpec expectedDeviceSpec) {
final UUID accountIdentifier = UUID.randomUUID();
final UUID phoneNumberIdentifier = UUID.randomUUID();
@@ -1524,6 +1741,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
fetchesMessagesAccountAttributes,
true,
aciIdentityKey,
@@ -1552,6 +1770,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
pushAccountAttributes,
true,
aciIdentityKey,
@@ -1579,6 +1798,7 @@ class RegistrationControllerTest {
new RegistrationRequest("session-id",
new byte[0],
null,
null,
pushAccountAttributes,
true,
aciIdentityKey,
@@ -1626,6 +1846,7 @@ class RegistrationControllerTest {
Base64.getEncoder().encodeToString(sessionId.getBytes(StandardCharsets.UTF_8)),
recoveryPassword,
null,
null,
accountAttributes,
skipDeviceTransfer,
aciIdentityKey,
@@ -90,6 +90,7 @@ class RegistrationRequestTest {
null,
null,
null,
null,
true,
aciIdentityKey,
pniIdentityKey,
@@ -131,6 +132,7 @@ class RegistrationRequestTest {
@Nullable final String fcmToken) {
return new RegistrationRequest(null,
null,
null,
null,
new AccountAttributes(fetchesMessages, 1, 2, null, null, false, Collections.emptySet(), null),
@@ -157,6 +159,7 @@ class RegistrationRequestTest {
final KEMSignedPreKey pniKemSignedPreKey = KeysHelper.signedKEMPreKey(4, pniKeyPair);
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
null,
null,
null,
new AccountAttributes(true, 1, pniRegistrationIdPresent ? 2 : null, null, null, false, Collections.emptySet(), null),
@@ -175,7 +175,8 @@ public class AccountCreationDeletionIntegrationTest {
executor,
executor,
CLOCK,
"link-device-secret".getBytes(StandardCharsets.UTF_8));
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
}
@AfterEach
@@ -155,7 +155,8 @@ class AccountsManagerChangeNumberIntegrationTest {
executor,
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8));
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
}
}
@@ -136,7 +136,8 @@ class AccountsManagerConcurrentModificationIntegrationTest {
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8)
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2)
);
}
}
@@ -31,7 +31,6 @@ import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.TransferArchiveResult;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -73,7 +72,8 @@ public class AccountsManagerDeviceTransferIntegrationTest {
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
Clock.systemUTC(),
"link-device-secret".getBytes(StandardCharsets.UTF_8));
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
accountsManager.start();
}
@@ -141,7 +141,8 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest {
executor,
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8));
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
}
}
@@ -73,6 +73,7 @@ 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;
@@ -126,6 +127,8 @@ 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_PARAMETERS.timeStep().dividedBy(2);
private static TestClock CLOCK;
private Accounts accounts;
@@ -249,7 +252,8 @@ class AccountsManagerTest {
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
CLOCK,
LINK_DEVICE_SECRET);
LINK_DEVICE_SECRET,
MAX_TOTP_VALIDATION_DELAY);
}
@ParameterizedTest
@@ -2096,4 +2100,102 @@ class AccountsManagerTest {
verify(account, never()).setPendingTotpKey(null);
}
}
@ParameterizedTest
@MethodSource
void verifyTotp(final Map<Integer, AnnotatedTotpKey> totpKeys,
final Instant timestamp,
@Nullable final Integer oneTimePassword,
final boolean expectVerified) {
final Account account = mock(Account.class);
when(account.getTotpKeys()).thenReturn(totpKeys);
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_PARAMETERS.algorithm());
totpKeyGenerator.init(AccountsManager.TOTP_KEY_LENGTH_BITS);
totpKey = new AnnotatedTotpKey(
new TotpKey(AccountsManager.TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
TestRandomUtil.nextBytes(16));
secondTotpKey = new AnnotatedTotpKey(
new TotpKey(AccountsManager.TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
TestRandomUtil.nextBytes(16));
}
final TimeBasedOneTimePasswordGenerator totpGenerator =
new TimeBasedOneTimePasswordGenerator(AccountsManager.TOTP_PARAMETERS.timeStep(),
AccountsManager.TOTP_PARAMETERS.passwordLength(),
AccountsManager.TOTP_PARAMETERS.algorithm());
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(1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true),
Arguments.argumentSet("Has key, incorrect password provided",
Map.of(1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp) + 1, false),
Arguments.argumentSet("Has key, no password provided",
Map.of(1, totpKey), timestamp, null, false),
Arguments.argumentSet("Has multiple keys, correct password provided for one key",
Map.of(1, totpKey, 2, secondTotpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true)
);
}
@RepeatedTest(value = 10, failureThreshold = 2)
void verifyTotpWithDelay() throws NoSuchAlgorithmException, InvalidKeyException {
final AnnotatedTotpKey totpKey;
{
final KeyGenerator totpKeyGenerator = KeyGenerator.getInstance(AccountsManager.TOTP_PARAMETERS.algorithm());
totpKeyGenerator.init(AccountsManager.TOTP_KEY_LENGTH_BITS);
totpKey = new AnnotatedTotpKey(
new TotpKey(AccountsManager.TOTP_PARAMETERS, totpKeyGenerator.generateKey().getEncoded()),
TestRandomUtil.nextBytes(16));
}
final TimeBasedOneTimePasswordGenerator totpGenerator =
new TimeBasedOneTimePasswordGenerator(AccountsManager.TOTP_PARAMETERS.timeStep(),
AccountsManager.TOTP_PARAMETERS.passwordLength(),
AccountsManager.TOTP_PARAMETERS.algorithm());
final Account account = mock(Account.class);
when(account.getTotpKeys()).thenReturn(Map.of(1, totpKey));
final Instant beginningOfTotpWindow =
Instant.ofEpochMilli((Instant.now().toEpochMilli() / AccountsManager.TOTP_PARAMETERS.timeStep().toMillis()) *
AccountsManager.TOTP_PARAMETERS.timeStep().toMillis());
final int oneTimePassword = totpGenerator.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_PARAMETERS.timeStep()), 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_PARAMETERS.timeStep()).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_PARAMETERS.timeStep()).plus(MAX_TOTP_VALIDATION_DELAY), oneTimePassword),
"One-time password should not be valid after max delay past end of current TOTP window");
}
}
@@ -157,7 +157,8 @@ class AccountsManagerUsernameIntegrationTest {
Executors.newSingleThreadScheduledExecutor(),
Executors.newSingleThreadScheduledExecutor(),
Clock.systemUTC(),
"link-device-secret".getBytes(StandardCharsets.UTF_8));
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
}
@Test
@@ -161,7 +161,8 @@ public class AddRemoveDeviceIntegrationTest {
scheduledExecutorService,
scheduledExecutorService,
clock,
"link-device-secret".getBytes(StandardCharsets.UTF_8));
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP_PARAMETERS.timeStep().dividedBy(2));
accountsManager.start();
}