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