]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/internal/RegistrationManagerImpl.java
Remove v2 suffix from secure value recovery
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / internal / RegistrationManagerImpl.java
1 /*
2 Copyright (C) 2015-2022 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.internal;
18
19 import org.asamk.signal.manager.Manager;
20 import org.asamk.signal.manager.RegistrationManager;
21 import org.asamk.signal.manager.api.CaptchaRequiredException;
22 import org.asamk.signal.manager.api.IncorrectPinException;
23 import org.asamk.signal.manager.api.NonNormalizedPhoneNumberException;
24 import org.asamk.signal.manager.api.PinLockedException;
25 import org.asamk.signal.manager.api.RateLimitException;
26 import org.asamk.signal.manager.api.UpdateProfile;
27 import org.asamk.signal.manager.api.VerificationMethodNotAvailableException;
28 import org.asamk.signal.manager.config.ServiceConfig;
29 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
30 import org.asamk.signal.manager.helper.AccountFileUpdater;
31 import org.asamk.signal.manager.helper.PinHelper;
32 import org.asamk.signal.manager.storage.SignalAccount;
33 import org.asamk.signal.manager.util.KeyUtils;
34 import org.asamk.signal.manager.util.NumberVerificationUtils;
35 import org.asamk.signal.manager.util.Utils;
36 import org.signal.libsignal.usernames.BaseUsernameException;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
40 import org.whispersystems.signalservice.api.account.PreKeyCollection;
41 import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations;
42 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
43 import org.whispersystems.signalservice.api.kbs.MasterKey;
44 import org.whispersystems.signalservice.api.push.ServiceId.ACI;
45 import org.whispersystems.signalservice.api.push.ServiceId.PNI;
46 import org.whispersystems.signalservice.api.push.ServiceIdType;
47 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
48 import org.whispersystems.signalservice.api.push.exceptions.AlreadyVerifiedException;
49 import org.whispersystems.signalservice.api.push.exceptions.DeprecatedVersionException;
50 import org.whispersystems.signalservice.api.svr.SecureValueRecovery;
51 import org.whispersystems.signalservice.internal.push.PushServiceSocket;
52 import org.whispersystems.signalservice.internal.push.VerifyAccountResponse;
53
54 import java.io.IOException;
55 import java.util.function.Consumer;
56
57 import static org.asamk.signal.manager.util.KeyUtils.generatePreKeysForType;
58
59 public class RegistrationManagerImpl implements RegistrationManager {
60
61 private static final Logger logger = LoggerFactory.getLogger(RegistrationManagerImpl.class);
62
63 private SignalAccount account;
64 private final PathConfig pathConfig;
65 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
66 private final String userAgent;
67 private final Consumer<Manager> newManagerListener;
68
69 private final SignalServiceAccountManager unauthenticatedAccountManager;
70 private final PinHelper pinHelper;
71 private final AccountFileUpdater accountFileUpdater;
72
73 public RegistrationManagerImpl(
74 SignalAccount account,
75 PathConfig pathConfig,
76 ServiceEnvironmentConfig serviceEnvironmentConfig,
77 String userAgent,
78 Consumer<Manager> newManagerListener,
79 AccountFileUpdater accountFileUpdater
80 ) {
81 this.account = account;
82 this.pathConfig = pathConfig;
83 this.accountFileUpdater = accountFileUpdater;
84 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
85 this.userAgent = userAgent;
86 this.newManagerListener = newManagerListener;
87
88 this.unauthenticatedAccountManager = SignalServiceAccountManager.createWithStaticCredentials(
89 serviceEnvironmentConfig.signalServiceConfiguration(),
90 // Using empty UUID, because registering doesn't work otherwise
91 null,
92 null,
93 account.getNumber(),
94 SignalServiceAddress.DEFAULT_DEVICE_ID,
95 account.getPassword(),
96 userAgent,
97 ServiceConfig.AUTOMATIC_NETWORK_RETRY,
98 ServiceConfig.GROUP_MAX_SIZE);
99 final var secureValueRecovery = serviceEnvironmentConfig.svr2Mrenclaves()
100 .stream()
101 .map(mr -> (SecureValueRecovery) this.unauthenticatedAccountManager.getSecureValueRecoveryV2(mr))
102 .toList();
103 this.pinHelper = new PinHelper(secureValueRecovery);
104 }
105
106 @Override
107 public void register(
108 boolean voiceVerification, String captcha, final boolean forceRegister
109 ) throws IOException, CaptchaRequiredException, NonNormalizedPhoneNumberException, RateLimitException, VerificationMethodNotAvailableException {
110 if (account.isRegistered()
111 && account.getServiceEnvironment() != null
112 && account.getServiceEnvironment() != serviceEnvironmentConfig.type()) {
113 throw new IOException("Account is registered in another environment: " + account.getServiceEnvironment());
114 }
115
116 try {
117 if (!forceRegister) {
118 if (account.isRegistered()) {
119 throw new IOException("Account is already registered");
120 }
121
122 if (account.getAci() != null && attemptReactivateAccount()) {
123 return;
124 }
125 }
126
127 final var recoveryPassword = account.getRecoveryPassword();
128 if (recoveryPassword != null && account.isPrimaryDevice() && attemptReregisterAccount(recoveryPassword)) {
129 return;
130 }
131
132 String sessionId = NumberVerificationUtils.handleVerificationSession(unauthenticatedAccountManager,
133 account.getSessionId(account.getNumber()),
134 id -> account.setSessionId(account.getNumber(), id),
135 voiceVerification,
136 captcha);
137 NumberVerificationUtils.requestVerificationCode(unauthenticatedAccountManager,
138 sessionId,
139 voiceVerification);
140 account.setRegistered(false);
141 } catch (DeprecatedVersionException e) {
142 logger.debug("Signal-Server returned deprecated version exception", e);
143 throw e;
144 }
145 }
146
147 @Override
148 public void verifyAccount(
149 String verificationCode, String pin
150 ) throws IOException, PinLockedException, IncorrectPinException {
151 if (account.isRegistered()) {
152 throw new IOException("Account is already registered");
153 }
154
155 if (account.getPniIdentityKeyPair() == null) {
156 account.setPniIdentityKeyPair(KeyUtils.generateIdentityKeyPair());
157 }
158
159 final var aciPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.ACI));
160 final var pniPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.PNI));
161 final var result = NumberVerificationUtils.verifyNumber(account.getSessionId(account.getNumber()),
162 verificationCode,
163 pin,
164 pinHelper,
165 (sessionId1, verificationCode1, registrationLock) -> verifyAccountWithCode(sessionId1,
166 verificationCode1,
167 registrationLock,
168 aciPreKeys,
169 pniPreKeys));
170 final var response = result.first();
171 final var masterKey = result.second();
172 if (masterKey == null) {
173 pin = null;
174 }
175
176 finishAccountRegistration(response, pin, masterKey, aciPreKeys, pniPreKeys);
177 }
178
179 @Override
180 public void deleteLocalAccountData() throws IOException {
181 account.deleteAccountData();
182 accountFileUpdater.removeAccount();
183 account = null;
184 }
185
186 @Override
187 public boolean isRegistered() {
188 return account.isRegistered();
189 }
190
191 private boolean attemptReregisterAccount(final String recoveryPassword) {
192 try {
193 if (account.getPniIdentityKeyPair() == null) {
194 account.setPniIdentityKeyPair(KeyUtils.generateIdentityKeyPair());
195 }
196
197 final var aciPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.ACI));
198 final var pniPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.PNI));
199 final var response = Utils.handleResponseException(unauthenticatedAccountManager.registerAccount(null,
200 recoveryPassword,
201 account.getAccountAttributes(null),
202 aciPreKeys,
203 pniPreKeys,
204 null,
205 true));
206 finishAccountRegistration(response,
207 account.getRegistrationLockPin(),
208 account.getPinBackedMasterKey(),
209 aciPreKeys,
210 pniPreKeys);
211 logger.info("Reregistered existing account, verify is not necessary.");
212 return true;
213 } catch (IOException e) {
214 logger.debug("Failed to reregister account with recovery password", e);
215 }
216 return false;
217 }
218
219 private boolean attemptReactivateAccount() {
220 try {
221 final var accountManager = createAuthenticatedSignalServiceAccountManager();
222 accountManager.setAccountAttributes(account.getAccountAttributes(null));
223 account.setRegistered(true);
224 logger.info("Reactivated existing account, verify is not necessary.");
225 if (newManagerListener != null) {
226 final var m = new ManagerImpl(account,
227 pathConfig,
228 accountFileUpdater,
229 serviceEnvironmentConfig,
230 userAgent);
231 account = null;
232 newManagerListener.accept(m);
233 }
234 return true;
235 } catch (IOException e) {
236 logger.debug("Failed to reactivate account");
237 }
238 return false;
239 }
240
241 private SignalServiceAccountManager createAuthenticatedSignalServiceAccountManager() {
242 final var clientZkOperations = ClientZkOperations.create(serviceEnvironmentConfig.signalServiceConfiguration());
243 final var pushServiceSocket = new PushServiceSocket(serviceEnvironmentConfig.signalServiceConfiguration(),
244 account.getCredentialsProvider(),
245 userAgent,
246 clientZkOperations.getProfileOperations(),
247 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
248 final var groupsV2Operations = new GroupsV2Operations(clientZkOperations, ServiceConfig.GROUP_MAX_SIZE);
249 return new SignalServiceAccountManager(pushServiceSocket, null, groupsV2Operations);
250 }
251
252 private VerifyAccountResponse verifyAccountWithCode(
253 final String sessionId,
254 final String verificationCode,
255 final String registrationLock,
256 final PreKeyCollection aciPreKeys,
257 final PreKeyCollection pniPreKeys
258 ) throws IOException {
259 try {
260 Utils.handleResponseException(unauthenticatedAccountManager.verifyAccount(verificationCode, sessionId));
261 } catch (AlreadyVerifiedException e) {
262 // Already verified so can continue registering
263 }
264 return Utils.handleResponseException(unauthenticatedAccountManager.registerAccount(sessionId,
265 null,
266 account.getAccountAttributes(registrationLock),
267 aciPreKeys,
268 pniPreKeys,
269 null,
270 true));
271 }
272
273 private void finishAccountRegistration(
274 final VerifyAccountResponse response,
275 final String pin,
276 final MasterKey masterKey,
277 final PreKeyCollection aciPreKeys,
278 final PreKeyCollection pniPreKeys
279 ) throws IOException {
280 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
281 final var aci = ACI.parseOrThrow(response.getUuid());
282 final var pni = PNI.parseOrThrow(response.getPni());
283 account.finishRegistration(aci, pni, masterKey, pin, aciPreKeys, pniPreKeys);
284 accountFileUpdater.updateAccountIdentifiers(account.getNumber(), aci);
285
286 ManagerImpl m = null;
287 try {
288 m = new ManagerImpl(account, pathConfig, accountFileUpdater, serviceEnvironmentConfig, userAgent);
289 account = null;
290
291 m.refreshPreKeys();
292 if (response.isStorageCapable()) {
293 m.syncRemoteStorage();
294 }
295 // Set an initial empty profile so user can be added to groups
296 try {
297 m.updateProfile(UpdateProfile.newBuilder().build());
298 } catch (NoClassDefFoundError e) {
299 logger.warn("Failed to set default profile: {}", e.getMessage());
300 }
301
302 try {
303 m.refreshCurrentUsername();
304 } catch (IOException | BaseUsernameException e) {
305 logger.warn("Failed to refresh current username", e);
306 }
307
308 if (newManagerListener != null) {
309 newManagerListener.accept(m);
310 m = null;
311 }
312 } finally {
313 if (m != null) {
314 m.close();
315 }
316 }
317 }
318
319 @Override
320 public void close() {
321 if (account != null) {
322 account.close();
323 account = null;
324 }
325 }
326 }