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
.config
.ServiceConfig
;
28 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
29 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
30 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
31 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
32 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
33 import org
.asamk
.signal
.manager
.util
.NumberVerificationUtils
;
34 import org
.asamk
.signal
.manager
.util
.Utils
;
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
.groupsv2
.ClientZkOperations
;
41 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
42 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
43 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
44 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
45 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
46 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
47 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AlreadyVerifiedException
;
48 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.DeprecatedVersionException
;
49 import org
.whispersystems
.signalservice
.api
.svr
.SecureValueRecovery
;
50 import org
.whispersystems
.signalservice
.internal
.push
.VerifyAccountResponse
;
51 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
53 import java
.io
.IOException
;
54 import java
.util
.function
.Consumer
;
56 import static org
.asamk
.signal
.manager
.util
.KeyUtils
.generatePreKeysForType
;
58 public class RegistrationManagerImpl
implements RegistrationManager
{
60 private static final Logger logger
= LoggerFactory
.getLogger(RegistrationManagerImpl
.class);
62 private SignalAccount account
;
63 private final PathConfig pathConfig
;
64 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
65 private final String userAgent
;
66 private final Consumer
<Manager
> newManagerListener
;
67 private final GroupsV2Operations groupsV2Operations
;
69 private final SignalServiceAccountManager accountManager
;
70 private final PinHelper pinHelper
;
71 private final AccountFileUpdater accountFileUpdater
;
73 public RegistrationManagerImpl(
74 SignalAccount account
,
75 PathConfig pathConfig
,
76 ServiceEnvironmentConfig serviceEnvironmentConfig
,
78 Consumer
<Manager
> newManagerListener
,
79 AccountFileUpdater accountFileUpdater
81 this.account
= account
;
82 this.pathConfig
= pathConfig
;
83 this.accountFileUpdater
= accountFileUpdater
;
84 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
85 this.userAgent
= userAgent
;
86 this.newManagerListener
= newManagerListener
;
88 groupsV2Operations
= new GroupsV2Operations(ClientZkOperations
.create(serviceEnvironmentConfig
.signalServiceConfiguration()),
89 ServiceConfig
.GROUP_MAX_SIZE
);
90 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.signalServiceConfiguration(),
91 new DynamicCredentialsProvider(
92 // Using empty UUID, because registering doesn't work otherwise
93 null, null, account
.getNumber(), account
.getPassword(), SignalServiceAddress
.DEFAULT_DEVICE_ID
),
96 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
97 final var secureValueRecoveryV2
= serviceEnvironmentConfig
.svr2Mrenclaves()
99 .map(mr
-> (SecureValueRecovery
) accountManager
.getSecureValueRecoveryV2(mr
))
101 this.pinHelper
= new PinHelper(secureValueRecoveryV2
);
105 public void register(
106 boolean voiceVerification
, String captcha
107 ) throws IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
, RateLimitException
{
108 if (account
.isRegistered()
109 && account
.getServiceEnvironment() != null
110 && account
.getServiceEnvironment() != serviceEnvironmentConfig
.type()) {
111 throw new IOException("Account is registered in another environment: " + account
.getServiceEnvironment());
115 final var recoveryPassword
= account
.getRecoveryPassword();
116 if (recoveryPassword
!= null && account
.isPrimaryDevice() && attemptReregisterAccount(recoveryPassword
)) {
120 if (account
.getAci() != null && attemptReactivateAccount()) {
124 String sessionId
= NumberVerificationUtils
.handleVerificationSession(accountManager
,
125 account
.getSessionId(account
.getNumber()),
126 id
-> account
.setSessionId(account
.getNumber(), id
),
129 NumberVerificationUtils
.requestVerificationCode(accountManager
, sessionId
, voiceVerification
);
130 } catch (DeprecatedVersionException e
) {
131 logger
.debug("Signal-Server returned deprecated version exception", e
);
137 public void verifyAccount(
138 String verificationCode
, String pin
139 ) throws IOException
, PinLockedException
, IncorrectPinException
{
140 if (account
.isRegistered()) {
141 throw new IOException("Account is already registered");
144 if (account
.getPniIdentityKeyPair() == null) {
145 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
148 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
149 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
150 final var result
= NumberVerificationUtils
.verifyNumber(account
.getSessionId(account
.getNumber()),
154 (sessionId1
, verificationCode1
, registrationLock
) -> verifyAccountWithCode(sessionId1
,
159 final var response
= result
.first();
160 final var masterKey
= result
.second();
161 if (masterKey
== null) {
165 finishAccountRegistration(response
, pin
, masterKey
, aciPreKeys
, pniPreKeys
);
169 public void deleteLocalAccountData() throws IOException
{
170 account
.deleteAccountData();
171 accountFileUpdater
.removeAccount();
176 public boolean isRegistered() {
177 return account
.isRegistered();
180 private boolean attemptReregisterAccount(final String recoveryPassword
) {
182 if (account
.getPniIdentityKeyPair() == null) {
183 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
186 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
187 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
188 final var response
= Utils
.handleResponseException(accountManager
.registerAccount(null,
190 account
.getAccountAttributes(null),
195 finishAccountRegistration(response
,
196 account
.getRegistrationLockPin(),
197 account
.getPinBackedMasterKey(),
200 logger
.info("Reregistered existing account, verify is not necessary.");
202 } catch (IOException e
) {
203 logger
.debug("Failed to reregister account with recovery password", e
);
208 private boolean attemptReactivateAccount() {
210 final var accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.signalServiceConfiguration(),
211 account
.getCredentialsProvider(),
214 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
215 accountManager
.setAccountAttributes(account
.getAccountAttributes(null));
216 account
.setRegistered(true);
217 logger
.info("Reactivated existing account, verify is not necessary.");
218 if (newManagerListener
!= null) {
219 final var m
= new ManagerImpl(account
,
222 serviceEnvironmentConfig
,
225 newManagerListener
.accept(m
);
228 } catch (IOException e
) {
229 logger
.debug("Failed to reactivate account");
234 private VerifyAccountResponse
verifyAccountWithCode(
235 final String sessionId
,
236 final String verificationCode
,
237 final String registrationLock
,
238 final PreKeyCollection aciPreKeys
,
239 final PreKeyCollection pniPreKeys
240 ) throws IOException
{
242 Utils
.handleResponseException(accountManager
.verifyAccount(verificationCode
, sessionId
));
243 } catch (AlreadyVerifiedException e
) {
244 // Already verified so can continue registering
246 return Utils
.handleResponseException(accountManager
.registerAccount(sessionId
,
248 account
.getAccountAttributes(registrationLock
),
255 private void finishAccountRegistration(
256 final VerifyAccountResponse response
,
258 final MasterKey masterKey
,
259 final PreKeyCollection aciPreKeys
,
260 final PreKeyCollection pniPreKeys
261 ) throws IOException
{
262 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
263 final var aci
= ACI
.parseOrThrow(response
.getUuid());
264 final var pni
= PNI
.parseOrThrow(response
.getPni());
265 account
.finishRegistration(aci
, pni
, masterKey
, pin
, aciPreKeys
, pniPreKeys
);
266 accountFileUpdater
.updateAccountIdentifiers(account
.getNumber(), aci
);
268 ManagerImpl m
= null;
270 m
= new ManagerImpl(account
, pathConfig
, accountFileUpdater
, serviceEnvironmentConfig
, userAgent
);
274 if (response
.isStorageCapable()) {
275 m
.syncRemoteStorage();
277 // Set an initial empty profile so user can be added to groups
279 m
.updateProfile(UpdateProfile
.newBuilder().build());
280 } catch (NoClassDefFoundError e
) {
281 logger
.warn("Failed to set default profile: {}", e
.getMessage());
285 m
.refreshCurrentUsername();
286 } catch (IOException
| BaseUsernameException e
) {
287 logger
.warn("Failed to refresh current username", e
);
290 if (newManagerListener
!= null) {
291 newManagerListener
.accept(m
);
302 public void close() {
303 if (account
!= null) {