]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/RegistrationManager.java
2be3f7193113b8612e59fca96ebfda7c93506cdd
[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 public 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 // TODO response.isStorageCapable()
178 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
179 account.finishRegistration(UuidUtil.parseOrNull(response.getUuid()), masterKey, pin);
180
181 Manager m = null;
182 try {
183 m = new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent);
184 account = null;
185
186 m.refreshPreKeys();
187 // Set an initial empty profile so user can be added to groups
188 m.setProfile(null, null, null, null, null);
189
190 final var result = m;
191 m = null;
192
193 return result;
194 } finally {
195 if (m != null) {
196 m.close();
197 }
198 }
199 }
200
201 private VerifyAccountResponse verifyAccountWithCode(
202 final String verificationCode, final String registrationLock
203 ) throws IOException {
204 final ServiceResponse<VerifyAccountResponse> response;
205 if (registrationLock == null) {
206 response = accountManager.verifyAccount(verificationCode,
207 account.getLocalRegistrationId(),
208 true,
209 account.getSelfUnidentifiedAccessKey(),
210 account.isUnrestrictedUnidentifiedAccess(),
211 ServiceConfig.capabilities,
212 account.isDiscoverableByPhoneNumber());
213 } else {
214 response = accountManager.verifyAccountWithRegistrationLockPin(verificationCode,
215 account.getLocalRegistrationId(),
216 true,
217 registrationLock,
218 account.getSelfUnidentifiedAccessKey(),
219 account.isUnrestrictedUnidentifiedAccess(),
220 ServiceConfig.capabilities,
221 account.isDiscoverableByPhoneNumber());
222 }
223 handleResponseException(response);
224 return response.getResult().get();
225 }
226
227 @Override
228 public void close() throws IOException {
229 if (account != null) {
230 account.close();
231 account = null;
232 }
233 }
234
235 private void handleResponseException(final ServiceResponse<?> response) throws IOException {
236 final var throwableOptional = response.getExecutionError().or(response.getApplicationError());
237 if (throwableOptional.isPresent()) {
238 if (throwableOptional.get() instanceof IOException) {
239 throw (IOException) throwableOptional.get();
240 } else {
241 throw new IOException(throwableOptional.get());
242 }
243 }
244 }
245 }