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