]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/internal/RegistrationManagerImpl.java
Improve behavior when pin data doesn't exist on the server
[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.PinLockMissingException;
25 import org.asamk.signal.manager.api.PinLockedException;
26 import org.asamk.signal.manager.api.RateLimitException;
27 import org.asamk.signal.manager.api.UpdateProfile;
28 import org.asamk.signal.manager.api.VerificationMethodNotAvailableException;
29 import org.asamk.signal.manager.config.ServiceConfig;
30 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
31 import org.asamk.signal.manager.helper.AccountFileUpdater;
32 import org.asamk.signal.manager.helper.PinHelper;
33 import org.asamk.signal.manager.storage.SignalAccount;
34 import org.asamk.signal.manager.util.KeyUtils;
35 import org.asamk.signal.manager.util.NumberVerificationUtils;
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.kbs.MasterKey;
42 import org.whispersystems.signalservice.api.push.ServiceId.ACI;
43 import org.whispersystems.signalservice.api.push.ServiceId.PNI;
44 import org.whispersystems.signalservice.api.push.ServiceIdType;
45 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
46 import org.whispersystems.signalservice.api.push.exceptions.AlreadyVerifiedException;
47 import org.whispersystems.signalservice.api.push.exceptions.DeprecatedVersionException;
48 import org.whispersystems.signalservice.api.svr.SecureValueRecovery;
49 import org.whispersystems.signalservice.internal.push.VerifyAccountResponse;
50
51 import java.io.IOException;
52 import java.util.function.Consumer;
53
54 import static org.asamk.signal.manager.util.KeyUtils.generatePreKeysForType;
55 import static org.asamk.signal.manager.util.Utils.handleResponseException;
56
57 public class RegistrationManagerImpl implements RegistrationManager {
58
59 private static final Logger logger = LoggerFactory.getLogger(RegistrationManagerImpl.class);
60
61 private SignalAccount account;
62 private final PathConfig pathConfig;
63 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
64 private final String userAgent;
65 private final Consumer<Manager> newManagerListener;
66
67 private final SignalServiceAccountManager unauthenticatedAccountManager;
68 private final PinHelper pinHelper;
69 private final AccountFileUpdater accountFileUpdater;
70
71 public RegistrationManagerImpl(
72 SignalAccount account,
73 PathConfig pathConfig,
74 ServiceEnvironmentConfig serviceEnvironmentConfig,
75 String userAgent,
76 Consumer<Manager> newManagerListener,
77 AccountFileUpdater accountFileUpdater
78 ) {
79 this.account = account;
80 this.pathConfig = pathConfig;
81 this.accountFileUpdater = accountFileUpdater;
82 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
83 this.userAgent = userAgent;
84 this.newManagerListener = newManagerListener;
85
86 this.unauthenticatedAccountManager = SignalServiceAccountManager.createWithStaticCredentials(
87 serviceEnvironmentConfig.signalServiceConfiguration(),
88 // Using empty UUID, because registering doesn't work otherwise
89 null,
90 null,
91 account.getNumber(),
92 SignalServiceAddress.DEFAULT_DEVICE_ID,
93 account.getPassword(),
94 userAgent,
95 ServiceConfig.AUTOMATIC_NETWORK_RETRY,
96 ServiceConfig.GROUP_MAX_SIZE);
97 final var secureValueRecovery = serviceEnvironmentConfig.svr2Mrenclaves()
98 .stream()
99 .map(mr -> (SecureValueRecovery) this.unauthenticatedAccountManager.getSecureValueRecoveryV2(mr))
100 .toList();
101 this.pinHelper = new PinHelper(secureValueRecovery);
102 }
103
104 @Override
105 public void register(
106 boolean voiceVerification,
107 String captcha,
108 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 final var registrationApi = unauthenticatedAccountManager.getRegistrationApi();
133 logger.trace("Creating verification session");
134 String sessionId = NumberVerificationUtils.handleVerificationSession(registrationApi,
135 account.getSessionId(account.getNumber()),
136 id -> account.setSessionId(account.getNumber(), id),
137 voiceVerification,
138 captcha);
139 logger.trace("Requesting verification code");
140 NumberVerificationUtils.requestVerificationCode(registrationApi, sessionId, voiceVerification);
141 logger.debug("Successfully requested verification code");
142 account.setRegistered(false);
143 } catch (DeprecatedVersionException e) {
144 logger.debug("Signal-Server returned deprecated version exception", e);
145 throw e;
146 }
147 }
148
149 @Override
150 public void verifyAccount(
151 String verificationCode,
152 String pin
153 ) throws IOException, PinLockedException, IncorrectPinException, PinLockMissingException {
154 if (account.isRegistered()) {
155 throw new IOException("Account is already registered");
156 }
157
158 if (account.getPniIdentityKeyPair() == null) {
159 account.setPniIdentityKeyPair(KeyUtils.generateIdentityKeyPair());
160 }
161
162 final var aciPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.ACI));
163 final var pniPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.PNI));
164 final var result = NumberVerificationUtils.verifyNumber(account.getSessionId(account.getNumber()),
165 verificationCode,
166 pin,
167 pinHelper,
168 (sessionId1, verificationCode1, registrationLock) -> verifyAccountWithCode(sessionId1,
169 verificationCode1,
170 registrationLock,
171 aciPreKeys,
172 pniPreKeys));
173 final var response = result.first();
174 final var masterKey = result.second();
175 if (masterKey == null) {
176 pin = null;
177 }
178
179 finishAccountRegistration(response, pin, masterKey, aciPreKeys, pniPreKeys);
180 }
181
182 @Override
183 public void deleteLocalAccountData() throws IOException {
184 account.deleteAccountData();
185 accountFileUpdater.removeAccount();
186 account = null;
187 }
188
189 @Override
190 public boolean isRegistered() {
191 return account.isRegistered();
192 }
193
194 private boolean attemptReregisterAccount(final String recoveryPassword) {
195 try {
196 if (account.getPniIdentityKeyPair() == null) {
197 account.setPniIdentityKeyPair(KeyUtils.generateIdentityKeyPair());
198 }
199
200 final var aciPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.ACI));
201 final var pniPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.PNI));
202 final var registrationApi = unauthenticatedAccountManager.getRegistrationApi();
203 final var response = handleResponseException(registrationApi.registerAccount(null,
204 recoveryPassword,
205 account.getAccountAttributes(null),
206 aciPreKeys,
207 pniPreKeys,
208 null,
209 true));
210 finishAccountRegistration(response,
211 account.getRegistrationLockPin(),
212 account.getPinBackedMasterKey(),
213 aciPreKeys,
214 pniPreKeys);
215 logger.info("Reregistered existing account, verify is not necessary.");
216 return true;
217 } catch (IOException e) {
218 logger.debug("Failed to reregister account with recovery password", e);
219 }
220 return false;
221 }
222
223 private boolean attemptReactivateAccount() {
224 try {
225 final var dependencies = new SignalDependencies(serviceEnvironmentConfig,
226 userAgent,
227 account.getCredentialsProvider(),
228 account.getSignalServiceDataStore(),
229 null,
230 new ReentrantSignalSessionLock());
231 handleResponseException(dependencies.getAccountApi()
232 .setAccountAttributes(account.getAccountAttributes(null)));
233 account.setRegistered(true);
234 logger.info("Reactivated existing account, verify is not necessary.");
235 if (newManagerListener != null) {
236 final var m = new ManagerImpl(account,
237 pathConfig,
238 accountFileUpdater,
239 serviceEnvironmentConfig,
240 userAgent);
241 account = null;
242 newManagerListener.accept(m);
243 }
244 return true;
245 } catch (IOException e) {
246 logger.debug("Failed to reactivate account");
247 }
248 return false;
249 }
250
251 private VerifyAccountResponse verifyAccountWithCode(
252 final String sessionId,
253 final String verificationCode,
254 final String registrationLock,
255 final PreKeyCollection aciPreKeys,
256 final PreKeyCollection pniPreKeys
257 ) throws IOException {
258 final var registrationApi = unauthenticatedAccountManager.getRegistrationApi();
259 try {
260 handleResponseException(registrationApi.verifyAccount(sessionId, verificationCode));
261 } catch (AlreadyVerifiedException e) {
262 // Already verified so can continue registering
263 }
264 return handleResponseException(registrationApi.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 }