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