]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/RegistrationManager.java
789173af6d495073464584c5a9865aea4e913cc9
[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
53 public class RegistrationManager implements Closeable {
54
55 private final static Logger logger = LoggerFactory.getLogger(RegistrationManager.class);
56
57 private SignalAccount account;
58 private final PathConfig pathConfig;
59 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
60 private final String userAgent;
61
62 private final SignalServiceAccountManager accountManager;
63 private final PinHelper pinHelper;
64
65 private RegistrationManager(
66 SignalAccount account,
67 PathConfig pathConfig,
68 ServiceEnvironmentConfig serviceEnvironmentConfig,
69 String userAgent
70 ) {
71 this.account = account;
72 this.pathConfig = pathConfig;
73 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
74 this.userAgent = userAgent;
75
76 GroupsV2Operations groupsV2Operations;
77 try {
78 groupsV2Operations = new GroupsV2Operations(ClientZkOperations.create(serviceEnvironmentConfig.getSignalServiceConfiguration()));
79 } catch (Throwable ignored) {
80 groupsV2Operations = null;
81 }
82 this.accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.getSignalServiceConfiguration(),
83 new DynamicCredentialsProvider(
84 // Using empty UUID, because registering doesn't work otherwise
85 null, account.getUsername(), account.getPassword(), SignalServiceAddress.DEFAULT_DEVICE_ID),
86 userAgent,
87 groupsV2Operations,
88 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
89 final var keyBackupService = accountManager.getKeyBackupService(ServiceConfig.getIasKeyStore(),
90 serviceEnvironmentConfig.getKeyBackupConfig().getEnclaveName(),
91 serviceEnvironmentConfig.getKeyBackupConfig().getServiceId(),
92 serviceEnvironmentConfig.getKeyBackupConfig().getMrenclave(),
93 10);
94 this.pinHelper = new PinHelper(keyBackupService);
95 }
96
97 public static RegistrationManager init(
98 String number, File settingsPath, ServiceEnvironment serviceEnvironment, String userAgent
99 ) throws IOException {
100 var pathConfig = PathConfig.createDefault(settingsPath);
101
102 final var serviceConfiguration = ServiceConfig.getServiceEnvironmentConfig(serviceEnvironment, userAgent);
103 if (!SignalAccount.userExists(pathConfig.dataPath(), number)) {
104 var identityKey = KeyUtils.generateIdentityKeyPair();
105 var registrationId = KeyHelper.generateRegistrationId(false);
106
107 var profileKey = KeyUtils.createProfileKey();
108 var account = SignalAccount.create(pathConfig.dataPath(),
109 number,
110 identityKey,
111 registrationId,
112 profileKey,
113 TrustNewIdentity.ON_FIRST_USE);
114
115 return new RegistrationManager(account, pathConfig, serviceConfiguration, userAgent);
116 }
117
118 var account = SignalAccount.load(pathConfig.dataPath(), number, true, TrustNewIdentity.ON_FIRST_USE);
119
120 return new RegistrationManager(account, pathConfig, serviceConfiguration, userAgent);
121 }
122
123 public void register(boolean voiceVerification, String captcha) throws IOException, CaptchaRequiredException {
124 final ServiceResponse<RequestVerificationCodeResponse> response;
125 if (voiceVerification) {
126 response = accountManager.requestVoiceVerificationCode(Utils.getDefaultLocale(),
127 Optional.fromNullable(captcha),
128 Optional.absent(),
129 Optional.absent());
130 } else {
131 response = accountManager.requestSmsVerificationCode(false,
132 Optional.fromNullable(captcha),
133 Optional.absent(),
134 Optional.absent());
135 }
136 try {
137 handleResponseException(response);
138 } catch (org.whispersystems.signalservice.api.push.exceptions.CaptchaRequiredException e) {
139 throw new CaptchaRequiredException(e.getMessage(), e);
140 }
141 }
142
143 public Manager verifyAccount(
144 String verificationCode, String pin
145 ) throws IOException, PinLockedException, IncorrectPinException {
146 verificationCode = verificationCode.replace("-", "");
147 VerifyAccountResponse response;
148 MasterKey masterKey;
149 try {
150 response = verifyAccountWithCode(verificationCode, null);
151
152 masterKey = null;
153 pin = null;
154 } catch (LockedException e) {
155 if (pin == null) {
156 throw new PinLockedException(e.getTimeRemaining());
157 }
158
159 KbsPinData registrationLockData;
160 try {
161 registrationLockData = pinHelper.getRegistrationLockData(pin, e);
162 } catch (KeyBackupSystemNoDataException ex) {
163 throw new IOException(e);
164 } catch (KeyBackupServicePinException ex) {
165 throw new IncorrectPinException(ex.getTriesRemaining());
166 }
167 if (registrationLockData == null) {
168 throw e;
169 }
170
171 var registrationLock = registrationLockData.getMasterKey().deriveRegistrationLock();
172 try {
173 response = verifyAccountWithCode(verificationCode, registrationLock);
174 } catch (LockedException _e) {
175 throw new AssertionError("KBS Pin appeared to matched but reg lock still failed!");
176 }
177 masterKey = registrationLockData.getMasterKey();
178 }
179
180 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
181 account.finishRegistration(ACI.parseOrNull(response.getUuid()), masterKey, pin);
182
183 ManagerImpl m = null;
184 try {
185 m = new ManagerImpl(account, pathConfig, serviceEnvironmentConfig, userAgent);
186 account = null;
187
188 m.refreshPreKeys();
189 if (response.isStorageCapable()) {
190 m.retrieveRemoteStorage();
191 }
192 // Set an initial empty profile so user can be added to groups
193 try {
194 m.setProfile(null, null, null, null, null);
195 } catch (NoClassDefFoundError e) {
196 logger.warn("Failed to set default profile: {}", e.getMessage());
197 }
198
199 final var result = m;
200 m = null;
201
202 return result;
203 } finally {
204 if (m != null) {
205 m.close();
206 }
207 }
208 }
209
210 private VerifyAccountResponse verifyAccountWithCode(
211 final String verificationCode, final String registrationLock
212 ) throws IOException {
213 final ServiceResponse<VerifyAccountResponse> response;
214 if (registrationLock == null) {
215 response = accountManager.verifyAccount(verificationCode,
216 account.getLocalRegistrationId(),
217 true,
218 account.getSelfUnidentifiedAccessKey(),
219 account.isUnrestrictedUnidentifiedAccess(),
220 ServiceConfig.capabilities,
221 account.isDiscoverableByPhoneNumber());
222 } else {
223 response = accountManager.verifyAccountWithRegistrationLockPin(verificationCode,
224 account.getLocalRegistrationId(),
225 true,
226 registrationLock,
227 account.getSelfUnidentifiedAccessKey(),
228 account.isUnrestrictedUnidentifiedAccess(),
229 ServiceConfig.capabilities,
230 account.isDiscoverableByPhoneNumber());
231 }
232 handleResponseException(response);
233 return response.getResult().get();
234 }
235
236 @Override
237 public void close() throws IOException {
238 if (account != null) {
239 account.close();
240 account = null;
241 }
242 }
243
244 private void handleResponseException(final ServiceResponse<?> response) throws IOException {
245 final var throwableOptional = response.getExecutionError().or(response.getApplicationError());
246 if (throwableOptional.isPresent()) {
247 if (throwableOptional.get() instanceof IOException) {
248 throw (IOException) throwableOptional.get();
249 } else {
250 throw new IOException(throwableOptional.get());
251 }
252 }
253 }
254 }