]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/RegistrationManager.java
1a124021bc7df02b5640eeae93eea169b3f3bfef
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / RegistrationManager.java
1 /*
2 Copyright (C) 2015-2021 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.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;
48
49 import java.io.Closeable;
50 import java.io.File;
51 import java.io.IOException;
52 import java.util.function.Consumer;
53
54 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
55
56 public class RegistrationManager implements Closeable {
57
58 private final static Logger logger = LoggerFactory.getLogger(RegistrationManager.class);
59
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;
65
66 private final SignalServiceAccountManager accountManager;
67 private final PinHelper pinHelper;
68
69 private RegistrationManager(
70 SignalAccount account,
71 PathConfig pathConfig,
72 ServiceEnvironmentConfig serviceEnvironmentConfig,
73 String userAgent,
74 Consumer<Manager> newManagerListener
75 ) {
76 this.account = account;
77 this.pathConfig = pathConfig;
78 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
79 this.userAgent = userAgent;
80 this.newManagerListener = newManagerListener;
81
82 GroupsV2Operations groupsV2Operations;
83 try {
84 groupsV2Operations = new GroupsV2Operations(ClientZkOperations.create(serviceEnvironmentConfig.getSignalServiceConfiguration()));
85 } catch (Throwable ignored) {
86 groupsV2Operations = null;
87 }
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),
92 userAgent,
93 groupsV2Operations,
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(),
99 10);
100 this.pinHelper = new PinHelper(keyBackupService);
101 }
102
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);
107 }
108
109 public static RegistrationManager init(
110 String number,
111 File settingsPath,
112 ServiceEnvironment serviceEnvironment,
113 String userAgent,
114 Consumer<Manager> newManagerListener
115 ) throws IOException {
116 var pathConfig = PathConfig.createDefault(settingsPath);
117
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);
122
123 var profileKey = KeyUtils.createProfileKey();
124 var account = SignalAccount.create(pathConfig.dataPath(),
125 number,
126 identityKey,
127 registrationId,
128 profileKey,
129 TrustNewIdentity.ON_FIRST_USE);
130
131 return new RegistrationManager(account, pathConfig, serviceConfiguration, userAgent, newManagerListener);
132 }
133
134 var account = SignalAccount.load(pathConfig.dataPath(), number, true, TrustNewIdentity.ON_FIRST_USE);
135
136 return new RegistrationManager(account, pathConfig, serviceConfiguration, userAgent, newManagerListener);
137 }
138
139 public void register(boolean voiceVerification, String captcha) throws IOException, CaptchaRequiredException {
140 captcha = captcha == null ? null : captcha.replace("signalcaptcha://", "");
141 if (account.getAci() != null) {
142 try {
143 final var accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.getSignalServiceConfiguration(),
144 new DynamicCredentialsProvider(account.getAci(),
145 account.getUsername(),
146 account.getPassword(),
147 account.getDeviceId()),
148 userAgent,
149 null,
150 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
151 accountManager.setAccountAttributes(account.getEncryptedDeviceName(),
152 null,
153 account.getLocalRegistrationId(),
154 true,
155 null,
156 account.getPinMasterKey() == null ? null : account.getPinMasterKey().deriveRegistrationLock(),
157 account.getSelfUnidentifiedAccessKey(),
158 account.isUnrestrictedUnidentifiedAccess(),
159 capabilities,
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);
165 account = null;
166 newManagerListener.accept(m);
167 }
168 return;
169 } catch (IOException e) {
170 logger.debug("Failed to reactivate account");
171 }
172 }
173 final ServiceResponse<RequestVerificationCodeResponse> response;
174 if (voiceVerification) {
175 response = accountManager.requestVoiceVerificationCode(Utils.getDefaultLocale(),
176 Optional.fromNullable(captcha),
177 Optional.absent(),
178 Optional.absent());
179 } else {
180 response = accountManager.requestSmsVerificationCode(false,
181 Optional.fromNullable(captcha),
182 Optional.absent(),
183 Optional.absent());
184 }
185 try {
186 handleResponseException(response);
187 } catch (org.whispersystems.signalservice.api.push.exceptions.CaptchaRequiredException e) {
188 throw new CaptchaRequiredException(e.getMessage(), e);
189 }
190 }
191
192 public void verifyAccount(
193 String verificationCode, String pin
194 ) throws IOException, PinLockedException, IncorrectPinException {
195 verificationCode = verificationCode.replace("-", "");
196 VerifyAccountResponse response;
197 MasterKey masterKey;
198 try {
199 response = verifyAccountWithCode(verificationCode, null);
200
201 masterKey = null;
202 pin = null;
203 } catch (LockedException e) {
204 if (pin == null) {
205 throw new PinLockedException(e.getTimeRemaining());
206 }
207
208 KbsPinData registrationLockData;
209 try {
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());
215 }
216 if (registrationLockData == null) {
217 throw e;
218 }
219
220 var registrationLock = registrationLockData.getMasterKey().deriveRegistrationLock();
221 try {
222 response = verifyAccountWithCode(verificationCode, registrationLock);
223 } catch (LockedException _e) {
224 throw new AssertionError("KBS Pin appeared to matched but reg lock still failed!");
225 }
226 masterKey = registrationLockData.getMasterKey();
227 }
228
229 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
230 account.finishRegistration(ACI.parseOrNull(response.getUuid()), masterKey, pin);
231
232 ManagerImpl m = null;
233 try {
234 m = new ManagerImpl(account, pathConfig, serviceEnvironmentConfig, userAgent);
235 account = null;
236
237 m.refreshPreKeys();
238 if (response.isStorageCapable()) {
239 m.retrieveRemoteStorage();
240 }
241 // Set an initial empty profile so user can be added to groups
242 try {
243 m.setProfile(null, null, null, null, null);
244 } catch (NoClassDefFoundError e) {
245 logger.warn("Failed to set default profile: {}", e.getMessage());
246 }
247
248 if (newManagerListener != null) {
249 newManagerListener.accept(m);
250 m = null;
251 }
252 } finally {
253 if (m != null) {
254 m.close();
255 }
256 }
257 }
258
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(),
266 true,
267 account.getSelfUnidentifiedAccessKey(),
268 account.isUnrestrictedUnidentifiedAccess(),
269 ServiceConfig.capabilities,
270 account.isDiscoverableByPhoneNumber());
271 } else {
272 response = accountManager.verifyAccountWithRegistrationLockPin(verificationCode,
273 account.getLocalRegistrationId(),
274 true,
275 registrationLock,
276 account.getSelfUnidentifiedAccessKey(),
277 account.isUnrestrictedUnidentifiedAccess(),
278 ServiceConfig.capabilities,
279 account.isDiscoverableByPhoneNumber());
280 }
281 handleResponseException(response);
282 return response.getResult().get();
283 }
284
285 @Override
286 public void close() throws IOException {
287 if (account != null) {
288 account.close();
289 account = null;
290 }
291 }
292
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();
298 } else {
299 throw new IOException(throwableOptional.get());
300 }
301 }
302 }
303 }