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