2 Copyright (C) 2015-2022 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
.internal
;
19 import org
.asamk
.signal
.manager
.Manager
;
20 import org
.asamk
.signal
.manager
.RegistrationManager
;
21 import org
.asamk
.signal
.manager
.api
.CaptchaRequiredException
;
22 import org
.asamk
.signal
.manager
.api
.IncorrectPinException
;
23 import org
.asamk
.signal
.manager
.api
.NonNormalizedPhoneNumberException
;
24 import org
.asamk
.signal
.manager
.api
.PinLockedException
;
25 import org
.asamk
.signal
.manager
.api
.RateLimitException
;
26 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
27 import org
.asamk
.signal
.manager
.api
.VerificationMethodNotAvailableException
;
28 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
29 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
30 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
31 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
32 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
33 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
34 import org
.asamk
.signal
.manager
.util
.NumberVerificationUtils
;
35 import org
.signal
.libsignal
.usernames
.BaseUsernameException
;
36 import org
.slf4j
.Logger
;
37 import org
.slf4j
.LoggerFactory
;
38 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
39 import org
.whispersystems
.signalservice
.api
.account
.PreKeyCollection
;
40 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
41 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
42 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
43 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
44 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
45 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AlreadyVerifiedException
;
46 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.DeprecatedVersionException
;
47 import org
.whispersystems
.signalservice
.api
.svr
.SecureValueRecovery
;
48 import org
.whispersystems
.signalservice
.internal
.push
.VerifyAccountResponse
;
50 import java
.io
.IOException
;
51 import java
.util
.function
.Consumer
;
53 import static org
.asamk
.signal
.manager
.util
.KeyUtils
.generatePreKeysForType
;
54 import static org
.asamk
.signal
.manager
.util
.Utils
.handleResponseException
;
56 public class RegistrationManagerImpl
implements RegistrationManager
{
58 private static final Logger logger
= LoggerFactory
.getLogger(RegistrationManagerImpl
.class);
60 private SignalAccount account
;
61 private final PathConfig pathConfig
;
62 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
63 private final String userAgent
;
64 private final Consumer
<Manager
> newManagerListener
;
66 private final SignalServiceAccountManager unauthenticatedAccountManager
;
67 private final PinHelper pinHelper
;
68 private final AccountFileUpdater accountFileUpdater
;
70 public RegistrationManagerImpl(
71 SignalAccount account
,
72 PathConfig pathConfig
,
73 ServiceEnvironmentConfig serviceEnvironmentConfig
,
75 Consumer
<Manager
> newManagerListener
,
76 AccountFileUpdater accountFileUpdater
78 this.account
= account
;
79 this.pathConfig
= pathConfig
;
80 this.accountFileUpdater
= accountFileUpdater
;
81 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
82 this.userAgent
= userAgent
;
83 this.newManagerListener
= newManagerListener
;
85 this.unauthenticatedAccountManager
= SignalServiceAccountManager
.createWithStaticCredentials(
86 serviceEnvironmentConfig
.signalServiceConfiguration(),
87 // Using empty UUID, because registering doesn't work otherwise
91 SignalServiceAddress
.DEFAULT_DEVICE_ID
,
92 account
.getPassword(),
94 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
95 ServiceConfig
.GROUP_MAX_SIZE
);
96 final var secureValueRecovery
= serviceEnvironmentConfig
.svr2Mrenclaves()
98 .map(mr
-> (SecureValueRecovery
) this.unauthenticatedAccountManager
.getSecureValueRecoveryV2(mr
))
100 this.pinHelper
= new PinHelper(secureValueRecovery
);
104 public void register(
105 boolean voiceVerification
,
107 final boolean forceRegister
108 ) throws IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
, RateLimitException
, VerificationMethodNotAvailableException
{
109 if (account
.isRegistered()
110 && account
.getServiceEnvironment() != null
111 && account
.getServiceEnvironment() != serviceEnvironmentConfig
.type()) {
112 throw new IOException("Account is registered in another environment: " + account
.getServiceEnvironment());
116 if (!forceRegister
) {
117 if (account
.isRegistered()) {
118 throw new IOException("Account is already registered");
121 if (account
.getAci() != null && attemptReactivateAccount()) {
126 final var recoveryPassword
= account
.getRecoveryPassword();
127 if (recoveryPassword
!= null && account
.isPrimaryDevice() && attemptReregisterAccount(recoveryPassword
)) {
131 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
132 logger
.trace("Creating verification session");
133 String sessionId
= NumberVerificationUtils
.handleVerificationSession(registrationApi
,
134 account
.getSessionId(account
.getNumber()),
135 id
-> account
.setSessionId(account
.getNumber(), id
),
138 logger
.trace("Requesting verification code");
139 NumberVerificationUtils
.requestVerificationCode(registrationApi
, sessionId
, voiceVerification
);
140 logger
.debug("Successfully requested verification code");
141 account
.setRegistered(false);
142 } catch (DeprecatedVersionException e
) {
143 logger
.debug("Signal-Server returned deprecated version exception", e
);
149 public void verifyAccount(
150 String verificationCode
,
152 ) throws IOException
, PinLockedException
, IncorrectPinException
{
153 if (account
.isRegistered()) {
154 throw new IOException("Account is already registered");
157 if (account
.getPniIdentityKeyPair() == null) {
158 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
161 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
162 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
163 final var result
= NumberVerificationUtils
.verifyNumber(account
.getSessionId(account
.getNumber()),
167 (sessionId1
, verificationCode1
, registrationLock
) -> verifyAccountWithCode(sessionId1
,
172 final var response
= result
.first();
173 final var masterKey
= result
.second();
174 if (masterKey
== null) {
178 finishAccountRegistration(response
, pin
, masterKey
, aciPreKeys
, pniPreKeys
);
182 public void deleteLocalAccountData() throws IOException
{
183 account
.deleteAccountData();
184 accountFileUpdater
.removeAccount();
189 public boolean isRegistered() {
190 return account
.isRegistered();
193 private boolean attemptReregisterAccount(final String recoveryPassword
) {
195 if (account
.getPniIdentityKeyPair() == null) {
196 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
199 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
200 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
201 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
202 final var response
= handleResponseException(registrationApi
.registerAccount(null,
204 account
.getAccountAttributes(null),
209 finishAccountRegistration(response
,
210 account
.getRegistrationLockPin(),
211 account
.getPinBackedMasterKey(),
214 logger
.info("Reregistered existing account, verify is not necessary.");
216 } catch (IOException e
) {
217 logger
.debug("Failed to reregister account with recovery password", e
);
222 private boolean attemptReactivateAccount() {
224 final var dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
226 account
.getCredentialsProvider(),
227 account
.getSignalServiceDataStore(),
229 new ReentrantSignalSessionLock());
230 handleResponseException(dependencies
.getAccountApi()
231 .setAccountAttributes(account
.getAccountAttributes(null)));
232 account
.setRegistered(true);
233 logger
.info("Reactivated existing account, verify is not necessary.");
234 if (newManagerListener
!= null) {
235 final var m
= new ManagerImpl(account
,
238 serviceEnvironmentConfig
,
241 newManagerListener
.accept(m
);
244 } catch (IOException e
) {
245 logger
.debug("Failed to reactivate account");
250 private VerifyAccountResponse
verifyAccountWithCode(
251 final String sessionId
,
252 final String verificationCode
,
253 final String registrationLock
,
254 final PreKeyCollection aciPreKeys
,
255 final PreKeyCollection pniPreKeys
256 ) throws IOException
{
257 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
259 handleResponseException(registrationApi
.verifyAccount(sessionId
, verificationCode
));
260 } catch (AlreadyVerifiedException e
) {
261 // Already verified so can continue registering
263 return handleResponseException(registrationApi
.registerAccount(sessionId
,
265 account
.getAccountAttributes(registrationLock
),
272 private void finishAccountRegistration(
273 final VerifyAccountResponse response
,
275 final MasterKey masterKey
,
276 final PreKeyCollection aciPreKeys
,
277 final PreKeyCollection pniPreKeys
278 ) throws IOException
{
279 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
280 final var aci
= ACI
.parseOrThrow(response
.getUuid());
281 final var pni
= PNI
.parseOrThrow(response
.getPni());
282 account
.finishRegistration(aci
, pni
, masterKey
, pin
, aciPreKeys
, pniPreKeys
);
283 accountFileUpdater
.updateAccountIdentifiers(account
.getNumber(), aci
);
285 ManagerImpl m
= null;
287 m
= new ManagerImpl(account
, pathConfig
, accountFileUpdater
, serviceEnvironmentConfig
, userAgent
);
291 if (response
.isStorageCapable()) {
292 m
.syncRemoteStorage();
294 // Set an initial empty profile so user can be added to groups
296 m
.updateProfile(UpdateProfile
.newBuilder().build());
297 } catch (NoClassDefFoundError e
) {
298 logger
.warn("Failed to set default profile: {}", e
.getMessage());
302 m
.refreshCurrentUsername();
303 } catch (IOException
| BaseUsernameException e
) {
304 logger
.warn("Failed to refresh current username", e
);
307 if (newManagerListener
!= null) {
308 newManagerListener
.accept(m
);
319 public void close() {
320 if (account
!= null) {