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
.VerificationMethoNotAvailableException
;
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
.asamk
.signal
.manager
.util
.Utils
;
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
.groupsv2
.ClientZkOperations
;
42 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
43 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
44 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
45 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
46 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
47 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
48 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AlreadyVerifiedException
;
49 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.DeprecatedVersionException
;
50 import org
.whispersystems
.signalservice
.api
.svr
.SecureValueRecovery
;
51 import org
.whispersystems
.signalservice
.internal
.push
.VerifyAccountResponse
;
52 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
54 import java
.io
.IOException
;
55 import java
.util
.function
.Consumer
;
57 import static org
.asamk
.signal
.manager
.util
.KeyUtils
.generatePreKeysForType
;
59 public class RegistrationManagerImpl
implements RegistrationManager
{
61 private static final Logger logger
= LoggerFactory
.getLogger(RegistrationManagerImpl
.class);
63 private SignalAccount account
;
64 private final PathConfig pathConfig
;
65 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
66 private final String userAgent
;
67 private final Consumer
<Manager
> newManagerListener
;
68 private final GroupsV2Operations groupsV2Operations
;
70 private final SignalServiceAccountManager accountManager
;
71 private final PinHelper pinHelper
;
72 private final AccountFileUpdater accountFileUpdater
;
74 public RegistrationManagerImpl(
75 SignalAccount account
,
76 PathConfig pathConfig
,
77 ServiceEnvironmentConfig serviceEnvironmentConfig
,
79 Consumer
<Manager
> newManagerListener
,
80 AccountFileUpdater accountFileUpdater
82 this.account
= account
;
83 this.pathConfig
= pathConfig
;
84 this.accountFileUpdater
= accountFileUpdater
;
85 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
86 this.userAgent
= userAgent
;
87 this.newManagerListener
= newManagerListener
;
89 groupsV2Operations
= new GroupsV2Operations(ClientZkOperations
.create(serviceEnvironmentConfig
.signalServiceConfiguration()),
90 ServiceConfig
.GROUP_MAX_SIZE
);
91 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.signalServiceConfiguration(),
92 new DynamicCredentialsProvider(
93 // Using empty UUID, because registering doesn't work otherwise
94 null, null, account
.getNumber(), account
.getPassword(), SignalServiceAddress
.DEFAULT_DEVICE_ID
),
97 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
98 final var secureValueRecoveryV2
= serviceEnvironmentConfig
.svr2Mrenclaves()
100 .map(mr
-> (SecureValueRecovery
) accountManager
.getSecureValueRecoveryV2(mr
))
102 this.pinHelper
= new PinHelper(secureValueRecoveryV2
);
106 public void register(
107 boolean voiceVerification
, String captcha
, final boolean forceRegister
108 ) throws IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
, RateLimitException
, VerificationMethoNotAvailableException
{
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 String sessionId
= NumberVerificationUtils
.handleVerificationSession(accountManager
,
132 account
.getSessionId(account
.getNumber()),
133 id
-> account
.setSessionId(account
.getNumber(), id
),
136 NumberVerificationUtils
.requestVerificationCode(accountManager
, sessionId
, voiceVerification
);
137 account
.setRegistered(false);
138 } catch (DeprecatedVersionException e
) {
139 logger
.debug("Signal-Server returned deprecated version exception", e
);
145 public void verifyAccount(
146 String verificationCode
, String pin
147 ) throws IOException
, PinLockedException
, IncorrectPinException
{
148 if (account
.isRegistered()) {
149 throw new IOException("Account is already registered");
152 if (account
.getPniIdentityKeyPair() == null) {
153 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
156 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
157 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
158 final var result
= NumberVerificationUtils
.verifyNumber(account
.getSessionId(account
.getNumber()),
162 (sessionId1
, verificationCode1
, registrationLock
) -> verifyAccountWithCode(sessionId1
,
167 final var response
= result
.first();
168 final var masterKey
= result
.second();
169 if (masterKey
== null) {
173 finishAccountRegistration(response
, pin
, masterKey
, aciPreKeys
, pniPreKeys
);
177 public void deleteLocalAccountData() throws IOException
{
178 account
.deleteAccountData();
179 accountFileUpdater
.removeAccount();
184 public boolean isRegistered() {
185 return account
.isRegistered();
188 private boolean attemptReregisterAccount(final String recoveryPassword
) {
190 if (account
.getPniIdentityKeyPair() == null) {
191 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
194 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
195 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
196 final var response
= Utils
.handleResponseException(accountManager
.registerAccount(null,
198 account
.getAccountAttributes(null),
203 finishAccountRegistration(response
,
204 account
.getRegistrationLockPin(),
205 account
.getPinBackedMasterKey(),
208 logger
.info("Reregistered existing account, verify is not necessary.");
210 } catch (IOException e
) {
211 logger
.debug("Failed to reregister account with recovery password", e
);
216 private boolean attemptReactivateAccount() {
218 final var accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.signalServiceConfiguration(),
219 account
.getCredentialsProvider(),
222 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
223 accountManager
.setAccountAttributes(account
.getAccountAttributes(null));
224 account
.setRegistered(true);
225 logger
.info("Reactivated existing account, verify is not necessary.");
226 if (newManagerListener
!= null) {
227 final var m
= new ManagerImpl(account
,
230 serviceEnvironmentConfig
,
233 newManagerListener
.accept(m
);
236 } catch (IOException e
) {
237 logger
.debug("Failed to reactivate account");
242 private VerifyAccountResponse
verifyAccountWithCode(
243 final String sessionId
,
244 final String verificationCode
,
245 final String registrationLock
,
246 final PreKeyCollection aciPreKeys
,
247 final PreKeyCollection pniPreKeys
248 ) throws IOException
{
250 Utils
.handleResponseException(accountManager
.verifyAccount(verificationCode
, sessionId
));
251 } catch (AlreadyVerifiedException e
) {
252 // Already verified so can continue registering
254 return Utils
.handleResponseException(accountManager
.registerAccount(sessionId
,
256 account
.getAccountAttributes(registrationLock
),
263 private void finishAccountRegistration(
264 final VerifyAccountResponse response
,
266 final MasterKey masterKey
,
267 final PreKeyCollection aciPreKeys
,
268 final PreKeyCollection pniPreKeys
269 ) throws IOException
{
270 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
271 final var aci
= ACI
.parseOrThrow(response
.getUuid());
272 final var pni
= PNI
.parseOrThrow(response
.getPni());
273 account
.finishRegistration(aci
, pni
, masterKey
, pin
, aciPreKeys
, pniPreKeys
);
274 accountFileUpdater
.updateAccountIdentifiers(account
.getNumber(), aci
);
276 ManagerImpl m
= null;
278 m
= new ManagerImpl(account
, pathConfig
, accountFileUpdater
, serviceEnvironmentConfig
, userAgent
);
282 if (response
.isStorageCapable()) {
283 m
.syncRemoteStorage();
285 // Set an initial empty profile so user can be added to groups
287 m
.updateProfile(UpdateProfile
.newBuilder().build());
288 } catch (NoClassDefFoundError e
) {
289 logger
.warn("Failed to set default profile: {}", e
.getMessage());
293 m
.refreshCurrentUsername();
294 } catch (IOException
| BaseUsernameException e
) {
295 logger
.warn("Failed to refresh current username", e
);
298 if (newManagerListener
!= null) {
299 newManagerListener
.accept(m
);
310 public void close() {
311 if (account
!= null) {