diff --git a/integration-tests/src/main/java/org/signal/integration/Operations.java b/integration-tests/src/main/java/org/signal/integration/Operations.java index bc77a63f5..0d19d9dec 100644 --- a/integration-tests/src/main/java/org/signal/integration/Operations.java +++ b/integration-tests/src/main/java/org/signal/integration/Operations.java @@ -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()), diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java index 84b202bd1..f15d07e60 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java @@ -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; + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index a2769afdc..050a2f330 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -804,7 +804,8 @@ public class WhisperServerService extends Application { 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 { public RateLimiter getCreateDonationPermitLimiter() { return forDescriptor(For.CREATE_DONATION_PERMIT); } + + public RateLimiter getCheckTotpLimiter() { + return forDescriptor(For.CHECK_TOTP); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java index 3d22b6237..11d0667e8 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -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 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 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 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 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; + } } 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 7d44c7e3c..77ce8808a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -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); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java index e7c1dca5d..d1df90b15 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/RegistrationControllerTest.java @@ -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 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 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, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/entities/RegistrationRequestTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/entities/RegistrationRequestTest.java index a6a9a1129..5105ede87 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/entities/RegistrationRequestTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/entities/RegistrationRequestTest.java @@ -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), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java index 18652c096..b0f7a3637 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountCreationDeletionIntegrationTest.java @@ -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 diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java index 2219420b3..bed46bb15 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerChangeNumberIntegrationTest.java @@ -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)); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java index 7f9fb182f..1b9f2f38b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerConcurrentModificationIntegrationTest.java @@ -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) ); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerDeviceTransferIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerDeviceTransferIntegrationTest.java index 986caa13d..595d2a376 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerDeviceTransferIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerDeviceTransferIntegrationTest.java @@ -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(); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java index 7b5fa061d..781c6c7af 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerMigrateRecoveryPasswordIntegrationTest.java @@ -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)); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java index e16b0eef4..cde89c93a 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java @@ -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 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 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"); + } } 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 6374adfe6..120c7b053 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,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 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 84c0d8060..7f459319f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AddRemoveDeviceIntegrationTest.java @@ -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(); }