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
.PinLockMissingException
;
25 import org
.asamk
.signal
.manager
.api
.PinLockedException
;
26 import org
.asamk
.signal
.manager
.api
.RateLimitException
;
27 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
28 import org
.asamk
.signal
.manager
.api
.VerificationMethodNotAvailableException
;
29 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
30 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
31 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
32 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
33 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
34 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
35 import org
.asamk
.signal
.manager
.util
.NumberVerificationUtils
;
36 import org
.signal
.libsignal
.usernames
.BaseUsernameException
;
37 import org
.slf4j
.Logger
;
38 import org
.slf4j
.LoggerFactory
;
39 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
40 import org
.whispersystems
.signalservice
.api
.account
.PreKeyCollection
;
41 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
42 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
43 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
44 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
45 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
46 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AlreadyVerifiedException
;
47 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.DeprecatedVersionException
;
48 import org
.whispersystems
.signalservice
.api
.svr
.SecureValueRecovery
;
49 import org
.whispersystems
.signalservice
.internal
.push
.VerifyAccountResponse
;
51 import java
.io
.IOException
;
52 import java
.util
.function
.Consumer
;
54 import static org
.asamk
.signal
.manager
.util
.KeyUtils
.generatePreKeysForType
;
55 import static org
.asamk
.signal
.manager
.util
.Utils
.handleResponseException
;
57 public class RegistrationManagerImpl
implements RegistrationManager
{
59 private static final Logger logger
= LoggerFactory
.getLogger(RegistrationManagerImpl
.class);
61 private SignalAccount account
;
62 private final PathConfig pathConfig
;
63 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
64 private final String userAgent
;
65 private final Consumer
<Manager
> newManagerListener
;
67 private final SignalServiceAccountManager unauthenticatedAccountManager
;
68 private final PinHelper pinHelper
;
69 private final AccountFileUpdater accountFileUpdater
;
71 public RegistrationManagerImpl(
72 SignalAccount account
,
73 PathConfig pathConfig
,
74 ServiceEnvironmentConfig serviceEnvironmentConfig
,
76 Consumer
<Manager
> newManagerListener
,
77 AccountFileUpdater accountFileUpdater
79 this.account
= account
;
80 this.pathConfig
= pathConfig
;
81 this.accountFileUpdater
= accountFileUpdater
;
82 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
83 this.userAgent
= userAgent
;
84 this.newManagerListener
= newManagerListener
;
86 this.unauthenticatedAccountManager
= SignalServiceAccountManager
.createWithStaticCredentials(
87 serviceEnvironmentConfig
.signalServiceConfiguration(),
88 // Using empty UUID, because registering doesn't work otherwise
92 SignalServiceAddress
.DEFAULT_DEVICE_ID
,
93 account
.getPassword(),
95 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
96 ServiceConfig
.GROUP_MAX_SIZE
);
97 final var secureValueRecovery
= serviceEnvironmentConfig
.svr2Mrenclaves()
99 .map(mr
-> (SecureValueRecovery
) this.unauthenticatedAccountManager
.getSecureValueRecoveryV2(mr
))
101 this.pinHelper
= new PinHelper(secureValueRecovery
);
105 public void register(
106 boolean voiceVerification
,
108 final boolean forceRegister
109 ) throws IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
, RateLimitException
, VerificationMethodNotAvailableException
{
110 if (account
.isRegistered()
111 && account
.getServiceEnvironment() != null
112 && account
.getServiceEnvironment() != serviceEnvironmentConfig
.type()) {
113 throw new IOException("Account is registered in another environment: " + account
.getServiceEnvironment());
117 if (!forceRegister
) {
118 if (account
.isRegistered()) {
119 throw new IOException("Account is already registered");
122 if (account
.getAci() != null && attemptReactivateAccount()) {
127 final var recoveryPassword
= account
.getRecoveryPassword();
128 if (recoveryPassword
!= null && account
.isPrimaryDevice() && attemptReregisterAccount(recoveryPassword
)) {
132 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
133 logger
.trace("Creating verification session");
134 String sessionId
= NumberVerificationUtils
.handleVerificationSession(registrationApi
,
135 account
.getSessionId(account
.getNumber()),
136 id
-> account
.setSessionId(account
.getNumber(), id
),
139 logger
.trace("Requesting verification code");
140 NumberVerificationUtils
.requestVerificationCode(registrationApi
, sessionId
, voiceVerification
);
141 logger
.debug("Successfully requested verification code");
142 account
.setRegistered(false);
143 } catch (DeprecatedVersionException e
) {
144 logger
.debug("Signal-Server returned deprecated version exception", e
);
150 public void verifyAccount(
151 String verificationCode
,
153 ) throws IOException
, PinLockedException
, IncorrectPinException
, PinLockMissingException
{
154 if (account
.isRegistered()) {
155 throw new IOException("Account is already registered");
158 if (account
.getPniIdentityKeyPair() == null) {
159 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
162 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
163 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
164 final var result
= NumberVerificationUtils
.verifyNumber(account
.getSessionId(account
.getNumber()),
168 (sessionId1
, verificationCode1
, registrationLock
) -> verifyAccountWithCode(sessionId1
,
173 final var response
= result
.first();
174 final var masterKey
= result
.second();
175 if (masterKey
== null) {
179 finishAccountRegistration(response
, pin
, masterKey
, aciPreKeys
, pniPreKeys
);
183 public void deleteLocalAccountData() throws IOException
{
184 account
.deleteAccountData();
185 accountFileUpdater
.removeAccount();
190 public boolean isRegistered() {
191 return account
.isRegistered();
194 private boolean attemptReregisterAccount(final String recoveryPassword
) {
196 if (account
.getPniIdentityKeyPair() == null) {
197 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
200 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
201 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
202 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
203 final var response
= handleResponseException(registrationApi
.registerAccount(null,
205 account
.getAccountAttributes(null),
210 finishAccountRegistration(response
,
211 account
.getRegistrationLockPin(),
212 account
.getPinBackedMasterKey(),
215 logger
.info("Reregistered existing account, verify is not necessary.");
217 } catch (IOException e
) {
218 logger
.debug("Failed to reregister account with recovery password", e
);
223 private boolean attemptReactivateAccount() {
225 final var dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
227 account
.getCredentialsProvider(),
228 account
.getSignalServiceDataStore(),
230 new ReentrantSignalSessionLock());
231 handleResponseException(dependencies
.getAccountApi()
232 .setAccountAttributes(account
.getAccountAttributes(null)));
233 account
.setRegistered(true);
234 logger
.info("Reactivated existing account, verify is not necessary.");
235 if (newManagerListener
!= null) {
236 final var m
= new ManagerImpl(account
,
239 serviceEnvironmentConfig
,
242 newManagerListener
.accept(m
);
245 } catch (IOException e
) {
246 logger
.debug("Failed to reactivate account");
251 private VerifyAccountResponse
verifyAccountWithCode(
252 final String sessionId
,
253 final String verificationCode
,
254 final String registrationLock
,
255 final PreKeyCollection aciPreKeys
,
256 final PreKeyCollection pniPreKeys
257 ) throws IOException
{
258 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
260 handleResponseException(registrationApi
.verifyAccount(sessionId
, verificationCode
));
261 } catch (AlreadyVerifiedException e
) {
262 // Already verified so can continue registering
264 return handleResponseException(registrationApi
.registerAccount(sessionId
,
266 account
.getAccountAttributes(registrationLock
),
273 private void finishAccountRegistration(
274 final VerifyAccountResponse response
,
276 final MasterKey masterKey
,
277 final PreKeyCollection aciPreKeys
,
278 final PreKeyCollection pniPreKeys
279 ) throws IOException
{
280 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
281 final var aci
= ACI
.parseOrThrow(response
.getUuid());
282 final var pni
= PNI
.parseOrThrow(response
.getPni());
283 account
.finishRegistration(aci
, pni
, masterKey
, pin
, aciPreKeys
, pniPreKeys
);
284 accountFileUpdater
.updateAccountIdentifiers(account
.getNumber(), aci
);
286 ManagerImpl m
= null;
288 m
= new ManagerImpl(account
, pathConfig
, accountFileUpdater
, serviceEnvironmentConfig
, userAgent
);
292 if (response
.isStorageCapable()) {
293 m
.syncRemoteStorage();
295 // Set an initial empty profile so user can be added to groups
297 m
.updateProfile(UpdateProfile
.newBuilder().build());
298 } catch (NoClassDefFoundError e
) {
299 logger
.warn("Failed to set default profile: {}", e
.getMessage());
303 m
.refreshCurrentUsername();
304 } catch (IOException
| BaseUsernameException e
) {
305 logger
.warn("Failed to refresh current username", e
);
308 if (newManagerListener
!= null) {
309 newManagerListener
.accept(m
);
320 public void close() {
321 if (account
!= null) {