]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/RegistrationManager.java
Remove libsignal-service from manager lib API
[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.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.whispersystems.libsignal.util.KeyHelper;
32 import org.whispersystems.libsignal.util.guava.Optional;
33 import org.whispersystems.signalservice.api.KbsPinData;
34 import org.whispersystems.signalservice.api.KeyBackupServicePinException;
35 import org.whispersystems.signalservice.api.KeyBackupSystemNoDataException;
36 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
37 import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations;
38 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
39 import org.whispersystems.signalservice.api.kbs.MasterKey;
40 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
41 import org.whispersystems.signalservice.api.util.UuidUtil;
42 import org.whispersystems.signalservice.internal.ServiceResponse;
43 import org.whispersystems.signalservice.internal.push.LockedException;
44 import org.whispersystems.signalservice.internal.push.RequestVerificationCodeResponse;
45 import org.whispersystems.signalservice.internal.push.VerifyAccountResponse;
46 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
47
48 import java.io.Closeable;
49 import java.io.File;
50 import java.io.IOException;
51 import java.util.Locale;
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(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 private Locale getDefaultLocale() {
144 final var locale = Locale.getDefault();
145 try {
146 Locale.LanguageRange.parse(locale.getLanguage() + "-" + locale.getCountry());
147 } catch (IllegalArgumentException e) {
148 logger.debug("Invalid locale, ignoring: {}", locale);
149 return null;
150 }
151
152 return locale;
153 }
154
155 public Manager verifyAccount(
156 String verificationCode, String pin
157 ) throws IOException, PinLockedException, IncorrectPinException {
158 verificationCode = verificationCode.replace("-", "");
159 VerifyAccountResponse response;
160 MasterKey masterKey;
161 try {
162 response = verifyAccountWithCode(verificationCode, null);
163
164 masterKey = null;
165 pin = null;
166 } catch (LockedException e) {
167 if (pin == null) {
168 throw new PinLockedException(e.getTimeRemaining());
169 }
170
171 KbsPinData registrationLockData;
172 try {
173 registrationLockData = pinHelper.getRegistrationLockData(pin, e);
174 } catch (KeyBackupSystemNoDataException ex) {
175 throw new IOException(e);
176 } catch (KeyBackupServicePinException ex) {
177 throw new IncorrectPinException(ex.getTriesRemaining());
178 }
179 if (registrationLockData == null) {
180 throw e;
181 }
182
183 var registrationLock = registrationLockData.getMasterKey().deriveRegistrationLock();
184 try {
185 response = verifyAccountWithCode(verificationCode, registrationLock);
186 } catch (LockedException _e) {
187 throw new AssertionError("KBS Pin appeared to matched but reg lock still failed!");
188 }
189 masterKey = registrationLockData.getMasterKey();
190 }
191
192 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
193 account.finishRegistration(UuidUtil.parseOrNull(response.getUuid()), masterKey, pin);
194
195 ManagerImpl m = null;
196 try {
197 m = new ManagerImpl(account, pathConfig, serviceEnvironmentConfig, userAgent);
198 account = null;
199
200 m.refreshPreKeys();
201 if (response.isStorageCapable()) {
202 m.retrieveRemoteStorage();
203 }
204 // Set an initial empty profile so user can be added to groups
205 try {
206 m.setProfile(null, null, null, null, null);
207 } catch (NoClassDefFoundError e) {
208 logger.warn("Failed to set default profile: {}", e.getMessage());
209 }
210
211 final var result = m;
212 m = null;
213
214 return result;
215 } finally {
216 if (m != null) {
217 m.close();
218 }
219 }
220 }
221
222 private VerifyAccountResponse verifyAccountWithCode(
223 final String verificationCode, final String registrationLock
224 ) throws IOException {
225 final ServiceResponse<VerifyAccountResponse> response;
226 if (registrationLock == null) {
227 response = accountManager.verifyAccount(verificationCode,
228 account.getLocalRegistrationId(),
229 true,
230 account.getSelfUnidentifiedAccessKey(),
231 account.isUnrestrictedUnidentifiedAccess(),
232 ServiceConfig.capabilities,
233 account.isDiscoverableByPhoneNumber());
234 } else {
235 response = accountManager.verifyAccountWithRegistrationLockPin(verificationCode,
236 account.getLocalRegistrationId(),
237 true,
238 registrationLock,
239 account.getSelfUnidentifiedAccessKey(),
240 account.isUnrestrictedUnidentifiedAccess(),
241 ServiceConfig.capabilities,
242 account.isDiscoverableByPhoneNumber());
243 }
244 handleResponseException(response);
245 return response.getResult().get();
246 }
247
248 @Override
249 public void close() throws IOException {
250 if (account != null) {
251 account.close();
252 account = null;
253 }
254 }
255
256 private void handleResponseException(final ServiceResponse<?> response) throws IOException {
257 final var throwableOptional = response.getExecutionError().or(response.getApplicationError());
258 if (throwableOptional.isPresent()) {
259 if (throwableOptional.get() instanceof IOException) {
260 throw (IOException) throwableOptional.get();
261 } else {
262 throw new IOException(throwableOptional.get());
263 }
264 }
265 }
266 }