]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/RegistrationManagerImpl.java
81602122158f4abe94ea7f8ae2a1ebfab6da7c81
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / RegistrationManagerImpl.java
1 /*
2 Copyright (C) 2015-2022 AsamK and contributors
3
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.
8
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.
13
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/>.
16 */
17 package org.asamk.signal.manager;
18
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.ServiceEnvironmentConfig;
24 import org.asamk.signal.manager.helper.AccountFileUpdater;
25 import org.asamk.signal.manager.helper.PinHelper;
26 import org.asamk.signal.manager.storage.SignalAccount;
27 import org.asamk.signal.manager.util.Utils;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.whispersystems.libsignal.util.guava.Optional;
31 import org.whispersystems.signalservice.api.KbsPinData;
32 import org.whispersystems.signalservice.api.KeyBackupServicePinException;
33 import org.whispersystems.signalservice.api.KeyBackupSystemNoDataException;
34 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
35 import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations;
36 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
37 import org.whispersystems.signalservice.api.kbs.MasterKey;
38 import org.whispersystems.signalservice.api.push.ACI;
39 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
40 import org.whispersystems.signalservice.internal.ServiceResponse;
41 import org.whispersystems.signalservice.internal.push.LockedException;
42 import org.whispersystems.signalservice.internal.push.RequestVerificationCodeResponse;
43 import org.whispersystems.signalservice.internal.push.VerifyAccountResponse;
44 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
45
46 import java.io.IOException;
47 import java.util.function.Consumer;
48
49 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
50
51 class RegistrationManagerImpl implements RegistrationManager {
52
53 private final static Logger logger = LoggerFactory.getLogger(RegistrationManagerImpl.class);
54
55 private SignalAccount account;
56 private final PathConfig pathConfig;
57 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
58 private final String userAgent;
59 private final Consumer<Manager> newManagerListener;
60
61 private final SignalServiceAccountManager accountManager;
62 private final PinHelper pinHelper;
63 private final AccountFileUpdater accountFileUpdater;
64
65 RegistrationManagerImpl(
66 SignalAccount account,
67 PathConfig pathConfig,
68 ServiceEnvironmentConfig serviceEnvironmentConfig,
69 String userAgent,
70 Consumer<Manager> newManagerListener,
71 AccountFileUpdater accountFileUpdater
72 ) {
73 this.account = account;
74 this.pathConfig = pathConfig;
75 this.accountFileUpdater = accountFileUpdater;
76 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
77 this.userAgent = userAgent;
78 this.newManagerListener = newManagerListener;
79
80 GroupsV2Operations groupsV2Operations;
81 try {
82 groupsV2Operations = new GroupsV2Operations(ClientZkOperations.create(serviceEnvironmentConfig.getSignalServiceConfiguration()));
83 } catch (Throwable ignored) {
84 groupsV2Operations = null;
85 }
86 this.accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.getSignalServiceConfiguration(),
87 new DynamicCredentialsProvider(
88 // Using empty UUID, because registering doesn't work otherwise
89 null, account.getNumber(), account.getPassword(), SignalServiceAddress.DEFAULT_DEVICE_ID),
90 userAgent,
91 groupsV2Operations,
92 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
93 final var keyBackupService = accountManager.getKeyBackupService(ServiceConfig.getIasKeyStore(),
94 serviceEnvironmentConfig.getKeyBackupConfig().getEnclaveName(),
95 serviceEnvironmentConfig.getKeyBackupConfig().getServiceId(),
96 serviceEnvironmentConfig.getKeyBackupConfig().getMrenclave(),
97 10);
98 this.pinHelper = new PinHelper(keyBackupService);
99 }
100
101 @Override
102 public void register(boolean voiceVerification, String captcha) throws IOException, CaptchaRequiredException {
103 captcha = captcha == null ? null : captcha.replace("signalcaptcha://", "");
104 if (account.getAci() != null) {
105 try {
106 final var accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.getSignalServiceConfiguration(),
107 new DynamicCredentialsProvider(account.getAci(),
108 account.getNumber(),
109 account.getPassword(),
110 account.getDeviceId()),
111 userAgent,
112 null,
113 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
114 accountManager.setAccountAttributes(account.getEncryptedDeviceName(),
115 null,
116 account.getLocalRegistrationId(),
117 true,
118 null,
119 account.getPinMasterKey() == null ? null : account.getPinMasterKey().deriveRegistrationLock(),
120 account.getSelfUnidentifiedAccessKey(),
121 account.isUnrestrictedUnidentifiedAccess(),
122 capabilities,
123 account.isDiscoverableByPhoneNumber());
124 account.setRegistered(true);
125 logger.info("Reactivated existing account, verify is not necessary.");
126 if (newManagerListener != null) {
127 final var m = new ManagerImpl(account,
128 pathConfig,
129 accountFileUpdater,
130 serviceEnvironmentConfig,
131 userAgent);
132 account = null;
133 newManagerListener.accept(m);
134 }
135 return;
136 } catch (IOException e) {
137 logger.debug("Failed to reactivate account");
138 }
139 }
140 final ServiceResponse<RequestVerificationCodeResponse> response;
141 if (voiceVerification) {
142 response = accountManager.requestVoiceVerificationCode(Utils.getDefaultLocale(null),
143 Optional.fromNullable(captcha),
144 Optional.absent(),
145 Optional.absent());
146 } else {
147 response = accountManager.requestSmsVerificationCode(false,
148 Optional.fromNullable(captcha),
149 Optional.absent(),
150 Optional.absent());
151 }
152 try {
153 handleResponseException(response);
154 } catch (org.whispersystems.signalservice.api.push.exceptions.CaptchaRequiredException e) {
155 throw new CaptchaRequiredException(e.getMessage(), e);
156 }
157 }
158
159 @Override
160 public void verifyAccount(
161 String verificationCode, String pin
162 ) throws IOException, PinLockedException, IncorrectPinException {
163 verificationCode = verificationCode.replace("-", "");
164 VerifyAccountResponse response;
165 MasterKey masterKey;
166 try {
167 response = verifyAccountWithCode(verificationCode, null);
168
169 masterKey = null;
170 pin = null;
171 } catch (LockedException e) {
172 if (pin == null) {
173 throw new PinLockedException(e.getTimeRemaining());
174 }
175
176 KbsPinData registrationLockData;
177 try {
178 registrationLockData = pinHelper.getRegistrationLockData(pin, e);
179 } catch (KeyBackupSystemNoDataException ex) {
180 throw new IOException(e);
181 } catch (KeyBackupServicePinException ex) {
182 throw new IncorrectPinException(ex.getTriesRemaining());
183 }
184 if (registrationLockData == null) {
185 throw e;
186 }
187
188 var registrationLock = registrationLockData.getMasterKey().deriveRegistrationLock();
189 try {
190 response = verifyAccountWithCode(verificationCode, registrationLock);
191 } catch (LockedException _e) {
192 throw new AssertionError("KBS Pin appeared to matched but reg lock still failed!");
193 }
194 masterKey = registrationLockData.getMasterKey();
195 }
196
197 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
198 final var aci = ACI.parseOrNull(response.getUuid());
199 account.finishRegistration(aci, masterKey, pin);
200 accountFileUpdater.updateAccountIdentifiers(account.getNumber(), aci);
201
202 ManagerImpl m = null;
203 try {
204 m = new ManagerImpl(account, pathConfig, accountFileUpdater, serviceEnvironmentConfig, userAgent);
205 account = null;
206
207 m.refreshPreKeys();
208 if (response.isStorageCapable()) {
209 m.retrieveRemoteStorage();
210 }
211 // Set an initial empty profile so user can be added to groups
212 try {
213 m.setProfile(null, null, null, null, null);
214 } catch (NoClassDefFoundError e) {
215 logger.warn("Failed to set default profile: {}", e.getMessage());
216 }
217
218 if (newManagerListener != null) {
219 newManagerListener.accept(m);
220 m = null;
221 }
222 } finally {
223 if (m != null) {
224 m.close();
225 }
226 }
227 }
228
229 private VerifyAccountResponse verifyAccountWithCode(
230 final String verificationCode, final String registrationLock
231 ) throws IOException {
232 final ServiceResponse<VerifyAccountResponse> response;
233 if (registrationLock == null) {
234 response = accountManager.verifyAccount(verificationCode,
235 account.getLocalRegistrationId(),
236 true,
237 account.getSelfUnidentifiedAccessKey(),
238 account.isUnrestrictedUnidentifiedAccess(),
239 ServiceConfig.capabilities,
240 account.isDiscoverableByPhoneNumber());
241 } else {
242 response = accountManager.verifyAccountWithRegistrationLockPin(verificationCode,
243 account.getLocalRegistrationId(),
244 true,
245 registrationLock,
246 account.getSelfUnidentifiedAccessKey(),
247 account.isUnrestrictedUnidentifiedAccess(),
248 ServiceConfig.capabilities,
249 account.isDiscoverableByPhoneNumber());
250 }
251 handleResponseException(response);
252 return response.getResult().get();
253 }
254
255 @Override
256 public void close() {
257 if (account != null) {
258 account.close();
259 account = null;
260 }
261 }
262
263 private void handleResponseException(final ServiceResponse<?> response) throws IOException {
264 final var throwableOptional = response.getExecutionError().or(response.getApplicationError());
265 if (throwableOptional.isPresent()) {
266 if (throwableOptional.get() instanceof IOException) {
267 throw (IOException) throwableOptional.get();
268 } else {
269 throw new IOException(throwableOptional.get());
270 }
271 }
272 }
273 }