2 Copyright (C) 2015-2021 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
;
19 import org
.asamk
.signal
.manager
.api
.CaptchaRequiredException
;
20 import org
.asamk
.signal
.manager
.api
.IncorrectPinException
;
21 import org
.asamk
.signal
.manager
.api
.PinLockedException
;
22 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
23 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
24 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
25 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
26 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
27 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
28 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
29 import org
.asamk
.signal
.manager
.util
.Utils
;
30 import org
.slf4j
.Logger
;
31 import org
.slf4j
.LoggerFactory
;
32 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
33 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
34 import org
.whispersystems
.signalservice
.api
.KbsPinData
;
35 import org
.whispersystems
.signalservice
.api
.KeyBackupServicePinException
;
36 import org
.whispersystems
.signalservice
.api
.KeyBackupSystemNoDataException
;
37 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
38 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
39 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
40 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
41 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
42 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
43 import org
.whispersystems
.signalservice
.internal
.ServiceResponse
;
44 import org
.whispersystems
.signalservice
.internal
.push
.LockedException
;
45 import org
.whispersystems
.signalservice
.internal
.push
.RequestVerificationCodeResponse
;
46 import org
.whispersystems
.signalservice
.internal
.push
.VerifyAccountResponse
;
47 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
49 import java
.io
.Closeable
;
51 import java
.io
.IOException
;
52 import java
.util
.function
.Consumer
;
54 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
56 public class RegistrationManager
implements Closeable
{
58 private final static Logger logger
= LoggerFactory
.getLogger(RegistrationManager
.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 accountManager
;
67 private final PinHelper pinHelper
;
69 private RegistrationManager(
70 SignalAccount account
,
71 PathConfig pathConfig
,
72 ServiceEnvironmentConfig serviceEnvironmentConfig
,
74 Consumer
<Manager
> newManagerListener
76 this.account
= account
;
77 this.pathConfig
= pathConfig
;
78 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
79 this.userAgent
= userAgent
;
80 this.newManagerListener
= newManagerListener
;
82 GroupsV2Operations groupsV2Operations
;
84 groupsV2Operations
= new GroupsV2Operations(ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration()));
85 } catch (Throwable ignored
) {
86 groupsV2Operations
= null;
88 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
89 new DynamicCredentialsProvider(
90 // Using empty UUID, because registering doesn't work otherwise
91 null, account
.getUsername(), account
.getPassword(), SignalServiceAddress
.DEFAULT_DEVICE_ID
),
94 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
95 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
96 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
97 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
98 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
100 this.pinHelper
= new PinHelper(keyBackupService
);
103 public static RegistrationManager
init(
104 String number
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
105 ) throws IOException
{
106 return init(number
, settingsPath
, serviceEnvironment
, userAgent
, null);
109 public static RegistrationManager
init(
112 ServiceEnvironment serviceEnvironment
,
114 Consumer
<Manager
> newManagerListener
115 ) throws IOException
{
116 var pathConfig
= PathConfig
.createDefault(settingsPath
);
118 final var serviceConfiguration
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
119 if (!SignalAccount
.userExists(pathConfig
.dataPath(), number
)) {
120 var identityKey
= KeyUtils
.generateIdentityKeyPair();
121 var registrationId
= KeyHelper
.generateRegistrationId(false);
123 var profileKey
= KeyUtils
.createProfileKey();
124 var account
= SignalAccount
.create(pathConfig
.dataPath(),
129 TrustNewIdentity
.ON_FIRST_USE
);
131 return new RegistrationManager(account
, pathConfig
, serviceConfiguration
, userAgent
, newManagerListener
);
134 var account
= SignalAccount
.load(pathConfig
.dataPath(), number
, true, TrustNewIdentity
.ON_FIRST_USE
);
136 return new RegistrationManager(account
, pathConfig
, serviceConfiguration
, userAgent
, newManagerListener
);
139 public void register(boolean voiceVerification
, String captcha
) throws IOException
, CaptchaRequiredException
{
140 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
141 if (account
.getAci() != null) {
143 final var accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
144 new DynamicCredentialsProvider(account
.getAci(),
145 account
.getUsername(),
146 account
.getPassword(),
147 account
.getDeviceId()),
150 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
151 accountManager
.setAccountAttributes(account
.getEncryptedDeviceName(),
153 account
.getLocalRegistrationId(),
156 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
157 account
.getSelfUnidentifiedAccessKey(),
158 account
.isUnrestrictedUnidentifiedAccess(),
160 account
.isDiscoverableByPhoneNumber());
161 account
.setRegistered(true);
162 logger
.info("Reactivated existing account, verify is not necessary.");
163 if (newManagerListener
!= null) {
164 final var m
= new ManagerImpl(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
166 newManagerListener
.accept(m
);
169 } catch (IOException e
) {
170 logger
.debug("Failed to reactivate account");
173 final ServiceResponse
<RequestVerificationCodeResponse
> response
;
174 if (voiceVerification
) {
175 response
= accountManager
.requestVoiceVerificationCode(Utils
.getDefaultLocale(),
176 Optional
.fromNullable(captcha
),
180 response
= accountManager
.requestSmsVerificationCode(false,
181 Optional
.fromNullable(captcha
),
186 handleResponseException(response
);
187 } catch (org
.whispersystems
.signalservice
.api
.push
.exceptions
.CaptchaRequiredException e
) {
188 throw new CaptchaRequiredException(e
.getMessage(), e
);
192 public void verifyAccount(
193 String verificationCode
, String pin
194 ) throws IOException
, PinLockedException
, IncorrectPinException
{
195 verificationCode
= verificationCode
.replace("-", "");
196 VerifyAccountResponse response
;
199 response
= verifyAccountWithCode(verificationCode
, null);
203 } catch (LockedException e
) {
205 throw new PinLockedException(e
.getTimeRemaining());
208 KbsPinData registrationLockData
;
210 registrationLockData
= pinHelper
.getRegistrationLockData(pin
, e
);
211 } catch (KeyBackupSystemNoDataException ex
) {
212 throw new IOException(e
);
213 } catch (KeyBackupServicePinException ex
) {
214 throw new IncorrectPinException(ex
.getTriesRemaining());
216 if (registrationLockData
== null) {
220 var registrationLock
= registrationLockData
.getMasterKey().deriveRegistrationLock();
222 response
= verifyAccountWithCode(verificationCode
, registrationLock
);
223 } catch (LockedException _e
) {
224 throw new AssertionError("KBS Pin appeared to matched but reg lock still failed!");
226 masterKey
= registrationLockData
.getMasterKey();
229 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
230 account
.finishRegistration(ACI
.parseOrNull(response
.getUuid()), masterKey
, pin
);
232 ManagerImpl m
= null;
234 m
= new ManagerImpl(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
238 if (response
.isStorageCapable()) {
239 m
.retrieveRemoteStorage();
241 // Set an initial empty profile so user can be added to groups
243 m
.setProfile(null, null, null, null, null);
244 } catch (NoClassDefFoundError e
) {
245 logger
.warn("Failed to set default profile: {}", e
.getMessage());
248 if (newManagerListener
!= null) {
249 newManagerListener
.accept(m
);
259 private VerifyAccountResponse
verifyAccountWithCode(
260 final String verificationCode
, final String registrationLock
261 ) throws IOException
{
262 final ServiceResponse
<VerifyAccountResponse
> response
;
263 if (registrationLock
== null) {
264 response
= accountManager
.verifyAccount(verificationCode
,
265 account
.getLocalRegistrationId(),
267 account
.getSelfUnidentifiedAccessKey(),
268 account
.isUnrestrictedUnidentifiedAccess(),
269 ServiceConfig
.capabilities
,
270 account
.isDiscoverableByPhoneNumber());
272 response
= accountManager
.verifyAccountWithRegistrationLockPin(verificationCode
,
273 account
.getLocalRegistrationId(),
276 account
.getSelfUnidentifiedAccessKey(),
277 account
.isUnrestrictedUnidentifiedAccess(),
278 ServiceConfig
.capabilities
,
279 account
.isDiscoverableByPhoneNumber());
281 handleResponseException(response
);
282 return response
.getResult().get();
286 public void close() throws IOException
{
287 if (account
!= null) {
293 private void handleResponseException(final ServiceResponse
<?
> response
) throws IOException
{
294 final var throwableOptional
= response
.getExecutionError().or(response
.getApplicationError());
295 if (throwableOptional
.isPresent()) {
296 if (throwableOptional
.get() instanceof IOException
) {
297 throw (IOException
) throwableOptional
.get();
299 throw new IOException(throwableOptional
.get());