1 package org
.asamk
.signal
.manager
.helper
;
3 import org
.asamk
.signal
.manager
.api
.CaptchaRequiredException
;
4 import org
.asamk
.signal
.manager
.api
.DeviceLinkUrl
;
5 import org
.asamk
.signal
.manager
.api
.IncorrectPinException
;
6 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
7 import org
.asamk
.signal
.manager
.api
.NonNormalizedPhoneNumberException
;
8 import org
.asamk
.signal
.manager
.api
.PinLockedException
;
9 import org
.asamk
.signal
.manager
.api
.RateLimitException
;
10 import org
.asamk
.signal
.manager
.api
.VerificationMethoNotAvailableException
;
11 import org
.asamk
.signal
.manager
.internal
.SignalDependencies
;
12 import org
.asamk
.signal
.manager
.jobs
.SyncStorageJob
;
13 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
14 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
15 import org
.asamk
.signal
.manager
.util
.NumberVerificationUtils
;
16 import org
.asamk
.signal
.manager
.util
.Utils
;
17 import org
.signal
.core
.util
.Base64
;
18 import org
.signal
.libsignal
.protocol
.IdentityKeyPair
;
19 import org
.signal
.libsignal
.protocol
.InvalidKeyException
;
20 import org
.signal
.libsignal
.protocol
.SignalProtocolAddress
;
21 import org
.signal
.libsignal
.protocol
.state
.KyberPreKeyRecord
;
22 import org
.signal
.libsignal
.protocol
.state
.SignedPreKeyRecord
;
23 import org
.signal
.libsignal
.protocol
.util
.KeyHelper
;
24 import org
.signal
.libsignal
.usernames
.BaseUsernameException
;
25 import org
.signal
.libsignal
.usernames
.Username
;
26 import org
.slf4j
.Logger
;
27 import org
.slf4j
.LoggerFactory
;
28 import org
.whispersystems
.signalservice
.api
.account
.ChangePhoneNumberRequest
;
29 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
30 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
31 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
32 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
33 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
34 import org
.whispersystems
.signalservice
.api
.push
.SignedPreKeyEntity
;
35 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AlreadyVerifiedException
;
36 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
37 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.DeprecatedVersionException
;
38 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UsernameIsNotReservedException
;
39 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UsernameMalformedException
;
40 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UsernameTakenException
;
41 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
42 import org
.whispersystems
.signalservice
.internal
.push
.KyberPreKeyEntity
;
43 import org
.whispersystems
.signalservice
.internal
.push
.OutgoingPushMessage
;
44 import org
.whispersystems
.signalservice
.internal
.push
.SyncMessage
;
45 import org
.whispersystems
.signalservice
.internal
.push
.exceptions
.MismatchedDevicesException
;
47 import java
.io
.IOException
;
48 import java
.util
.ArrayList
;
49 import java
.util
.HashMap
;
50 import java
.util
.List
;
51 import java
.util
.Objects
;
52 import java
.util
.Optional
;
53 import java
.util
.concurrent
.TimeUnit
;
55 import okio
.ByteString
;
57 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.PREKEY_MAXIMUM_ID
;
58 import static org
.whispersystems
.signalservice
.internal
.util
.Util
.isEmpty
;
60 public class AccountHelper
{
62 private static final Logger logger
= LoggerFactory
.getLogger(AccountHelper
.class);
64 private final Context context
;
65 private final SignalAccount account
;
66 private final SignalDependencies dependencies
;
68 private Callable unregisteredListener
;
70 public AccountHelper(final Context context
) {
71 this.account
= context
.getAccount();
72 this.dependencies
= context
.getDependencies();
73 this.context
= context
;
76 public void setUnregisteredListener(final Callable unregisteredListener
) {
77 this.unregisteredListener
= unregisteredListener
;
80 public void checkAccountState() throws IOException
{
81 if (account
.getLastReceiveTimestamp() == 0) {
82 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
84 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
85 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
88 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
93 updateAccountAttributes();
94 if (account
.getPreviousStorageVersion() < 9) {
95 context
.getPreKeyHelper().forceRefreshPreKeys();
97 context
.getPreKeyHelper().refreshPreKeysIfNecessary();
99 if (account
.getAci() == null || account
.getPni() == null) {
102 if (!account
.isPrimaryDevice() && account
.getPniIdentityKeyPair() == null) {
103 context
.getSyncHelper().requestSyncPniIdentity();
105 if (account
.getPreviousStorageVersion() < 4
106 && account
.isPrimaryDevice()
107 && account
.getRegistrationLockPin() != null) {
108 migrateRegistrationPin();
110 if (account
.getUsername() != null && account
.getUsernameLink() == null) {
112 tryToSetUsernameLink(new Username(account
.getUsername()));
113 } catch (BaseUsernameException e
) {
114 logger
.debug("Invalid local username");
117 } catch (DeprecatedVersionException e
) {
118 logger
.debug("Signal-Server returned deprecated version exception", e
);
120 } catch (AuthorizationFailedException e
) {
121 account
.setRegistered(false);
126 public void checkWhoAmiI() throws IOException
{
127 final var whoAmI
= dependencies
.getAccountManager().getWhoAmI();
128 final var number
= whoAmI
.getNumber();
129 final var aci
= ACI
.parseOrThrow(whoAmI
.getAci());
130 final var pni
= PNI
.parseOrThrow(whoAmI
.getPni());
131 if (number
.equals(account
.getNumber()) && aci
.equals(account
.getAci()) && pni
.equals(account
.getPni())) {
135 updateSelfIdentifiers(number
, aci
, pni
);
138 private void updateSelfIdentifiers(final String number
, final ACI aci
, final PNI pni
) {
139 account
.setNumber(number
);
142 if (account
.isPrimaryDevice() && account
.getPniIdentityKeyPair() == null) {
143 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
145 account
.getRecipientTrustedResolver().resolveSelfRecipientTrusted(account
.getSelfRecipientAddress());
146 context
.getUnidentifiedAccessHelper().rotateSenderCertificates();
147 dependencies
.resetAfterAddressChange();
148 context
.getGroupV2Helper().clearAuthCredentialCache();
149 context
.getAccountFileUpdater().updateAccountIdentifiers(account
.getNumber(), account
.getAci());
150 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
154 final PNI updatedPni
,
155 final IdentityKeyPair pniIdentityKeyPair
,
157 final int localPniRegistrationId
,
158 final SignedPreKeyRecord pniSignedPreKey
,
159 final KyberPreKeyRecord lastResortKyberPreKey
160 ) throws IOException
{
161 updateSelfIdentifiers(number
!= null ? number
: account
.getNumber(), account
.getAci(), updatedPni
);
162 account
.setNewPniIdentity(pniIdentityKeyPair
, pniSignedPreKey
, lastResortKyberPreKey
, localPniRegistrationId
);
163 context
.getPreKeyHelper().refreshPreKeysIfNecessary(ServiceIdType
.PNI
);
166 public void startChangeNumber(
167 String newNumber
, boolean voiceVerification
, String captcha
168 ) throws IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
, RateLimitException
, VerificationMethoNotAvailableException
{
169 final var accountManager
= dependencies
.createUnauthenticatedAccountManager(newNumber
, account
.getPassword());
170 String sessionId
= NumberVerificationUtils
.handleVerificationSession(accountManager
,
171 account
.getSessionId(newNumber
),
172 id
-> account
.setSessionId(newNumber
, id
),
175 NumberVerificationUtils
.requestVerificationCode(accountManager
, sessionId
, voiceVerification
);
178 public void finishChangeNumber(
179 String newNumber
, String verificationCode
, String pin
180 ) throws IncorrectPinException
, PinLockedException
, IOException
{
181 for (var attempts
= 0; attempts
< 5; attempts
++) {
183 finishChangeNumberInternal(newNumber
, verificationCode
, pin
);
185 } catch (MismatchedDevicesException e
) {
186 logger
.debug("Change number failed with mismatched devices, retrying.");
188 dependencies
.getMessageSender().handleChangeNumberMismatchDevices(e
.getMismatchedDevices());
189 } catch (UntrustedIdentityException ex
) {
190 throw new AssertionError(ex
);
196 private void finishChangeNumberInternal(
197 String newNumber
, String verificationCode
, String pin
198 ) throws IncorrectPinException
, PinLockedException
, IOException
{
199 final var pniIdentity
= KeyUtils
.generateIdentityKeyPair();
200 final var encryptedDeviceMessages
= new ArrayList
<OutgoingPushMessage
>();
201 final var devicePniSignedPreKeys
= new HashMap
<Integer
, SignedPreKeyEntity
>();
202 final var devicePniLastResortKyberPreKeys
= new HashMap
<Integer
, KyberPreKeyEntity
>();
203 final var pniRegistrationIds
= new HashMap
<Integer
, Integer
>();
205 final var selfDeviceId
= account
.getDeviceId();
206 SyncMessage
.PniChangeNumber selfChangeNumber
= null;
208 final var deviceIds
= new ArrayList
<Integer
>();
209 deviceIds
.add(SignalServiceAddress
.DEFAULT_DEVICE_ID
);
210 final var aci
= account
.getAci();
211 final var accountDataStore
= account
.getSignalServiceDataStore().aci();
212 final var subDeviceSessions
= accountDataStore
.getSubDeviceSessions(aci
.toString())
214 .filter(deviceId
-> accountDataStore
.containsSession(new SignalProtocolAddress(aci
.toString(),
217 deviceIds
.addAll(subDeviceSessions
);
219 final var messageSender
= dependencies
.getMessageSender();
220 for (final var deviceId
: deviceIds
) {
222 final var signedPreKeyRecord
= KeyUtils
.generateSignedPreKeyRecord(KeyUtils
.getRandomInt(PREKEY_MAXIMUM_ID
),
223 pniIdentity
.getPrivateKey());
224 final var signedPreKeyEntity
= new SignedPreKeyEntity(signedPreKeyRecord
.getId(),
225 signedPreKeyRecord
.getKeyPair().getPublicKey(),
226 signedPreKeyRecord
.getSignature());
227 devicePniSignedPreKeys
.put(deviceId
, signedPreKeyEntity
);
229 // Last-resort kyber prekey
230 final var lastResortKyberPreKeyRecord
= KeyUtils
.generateKyberPreKeyRecord(KeyUtils
.getRandomInt(
231 PREKEY_MAXIMUM_ID
), pniIdentity
.getPrivateKey());
232 final var kyberPreKeyEntity
= new KyberPreKeyEntity(lastResortKyberPreKeyRecord
.getId(),
233 lastResortKyberPreKeyRecord
.getKeyPair().getPublicKey(),
234 lastResortKyberPreKeyRecord
.getSignature());
235 devicePniLastResortKyberPreKeys
.put(deviceId
, kyberPreKeyEntity
);
238 var pniRegistrationId
= -1;
239 while (pniRegistrationId
< 0 || pniRegistrationIds
.containsValue(pniRegistrationId
)) {
240 pniRegistrationId
= KeyHelper
.generateRegistrationId(false);
242 pniRegistrationIds
.put(deviceId
, pniRegistrationId
);
245 final var pniChangeNumber
= new SyncMessage
.PniChangeNumber
.Builder().identityKeyPair(ByteString
.of(
246 pniIdentity
.serialize()))
247 .signedPreKey(ByteString
.of(signedPreKeyRecord
.serialize()))
248 .lastResortKyberPreKey(ByteString
.of(lastResortKyberPreKeyRecord
.serialize()))
249 .registrationId(pniRegistrationId
)
253 if (deviceId
== selfDeviceId
) {
254 selfChangeNumber
= pniChangeNumber
;
257 final var message
= messageSender
.getEncryptedSyncPniInitializeDeviceMessage(deviceId
,
259 encryptedDeviceMessages
.add(message
);
260 } catch (UntrustedIdentityException
| IOException
| InvalidKeyException e
) {
261 throw new RuntimeException(e
);
266 final var sessionId
= account
.getSessionId(newNumber
);
267 final var result
= NumberVerificationUtils
.verifyNumber(sessionId
,
270 context
.getPinHelper(),
271 (sessionId1
, verificationCode1
, registrationLock
) -> {
272 final var accountManager
= dependencies
.getAccountManager();
274 Utils
.handleResponseException(accountManager
.verifyAccount(verificationCode1
, sessionId1
));
275 } catch (AlreadyVerifiedException e
) {
276 // Already verified so can continue changing number
278 return Utils
.handleResponseException(accountManager
.changeNumber(new ChangePhoneNumberRequest(
283 pniIdentity
.getPublicKey(),
284 encryptedDeviceMessages
,
285 Utils
.mapKeys(devicePniSignedPreKeys
, Object
::toString
),
286 Utils
.mapKeys(devicePniLastResortKyberPreKeys
, Object
::toString
),
287 Utils
.mapKeys(pniRegistrationIds
, Object
::toString
))));
290 final var updatePni
= PNI
.parseOrThrow(result
.first().getPni());
291 if (updatePni
.equals(account
.getPni())) {
292 logger
.debug("PNI is unchanged after change number");
296 handlePniChangeNumberMessage(selfChangeNumber
, updatePni
);
299 public void handlePniChangeNumberMessage(
300 final SyncMessage
.PniChangeNumber pniChangeNumber
, final PNI updatedPni
302 if (pniChangeNumber
.identityKeyPair
!= null
303 && pniChangeNumber
.registrationId
!= null
304 && pniChangeNumber
.signedPreKey
!= null) {
305 logger
.debug("New PNI: {}", updatedPni
);
308 new IdentityKeyPair(pniChangeNumber
.identityKeyPair
.toByteArray()),
309 pniChangeNumber
.newE164
,
310 pniChangeNumber
.registrationId
,
311 new SignedPreKeyRecord(pniChangeNumber
.signedPreKey
.toByteArray()),
312 pniChangeNumber
.lastResortKyberPreKey
!= null
313 ?
new KyberPreKeyRecord(pniChangeNumber
.lastResortKyberPreKey
.toByteArray())
315 } catch (Exception e
) {
316 logger
.warn("Failed to handle change number message", e
);
321 public static final int USERNAME_MIN_LENGTH
= 3;
322 public static final int USERNAME_MAX_LENGTH
= 32;
324 public void reserveUsername(String nickname
) throws IOException
, BaseUsernameException
{
325 final var currentUsername
= account
.getUsername();
326 if (currentUsername
!= null) {
327 final var currentNickname
= currentUsername
.substring(0, currentUsername
.indexOf('.'));
328 if (currentNickname
.equals(nickname
)) {
330 refreshCurrentUsername();
331 } catch (IOException
| BaseUsernameException e
) {
332 logger
.warn("[reserveUsername] Failed to refresh current username, trying to claim new username");
338 final var candidates
= Username
.candidatesFrom(nickname
, USERNAME_MIN_LENGTH
, USERNAME_MAX_LENGTH
);
339 final var candidateHashes
= new ArrayList
<String
>();
340 for (final var candidate
: candidates
) {
341 candidateHashes
.add(Base64
.encodeUrlSafeWithoutPadding(candidate
.getHash()));
344 final var response
= dependencies
.getAccountManager().reserveUsername(candidateHashes
);
345 final var hashIndex
= candidateHashes
.indexOf(response
.getUsernameHash());
346 if (hashIndex
== -1) {
347 logger
.warn("[reserveUsername] The response hash could not be found in our set of candidateHashes.");
348 throw new IOException("Unexpected username response");
351 logger
.debug("[reserveUsername] Successfully reserved username.");
352 final var username
= candidates
.get(hashIndex
);
354 final var linkComponents
= dependencies
.getAccountManager().confirmUsernameAndCreateNewLink(username
);
355 account
.setUsername(username
.getUsername());
356 account
.setUsernameLink(linkComponents
);
357 account
.getRecipientStore().resolveSelfRecipientTrusted(account
.getSelfRecipientAddress());
358 logger
.debug("[confirmUsername] Successfully confirmed username.");
361 public void refreshCurrentUsername() throws IOException
, BaseUsernameException
{
362 final var localUsername
= account
.getUsername();
363 if (localUsername
== null) {
367 final var whoAmIResponse
= dependencies
.getAccountManager().getWhoAmI();
368 final var serverUsernameHash
= whoAmIResponse
.getUsernameHash();
369 final var hasServerUsername
= !isEmpty(serverUsernameHash
);
370 final var username
= new Username(localUsername
);
371 final var localUsernameHash
= Base64
.encodeUrlSafeWithoutPadding(username
.getHash());
373 if (!hasServerUsername
) {
374 logger
.debug("No remote username is set.");
377 if (!Objects
.equals(localUsernameHash
, serverUsernameHash
)) {
378 logger
.debug("Local username hash does not match server username hash.");
381 if (!hasServerUsername
|| !Objects
.equals(localUsernameHash
, serverUsernameHash
)) {
382 logger
.debug("Attempting to resynchronize username.");
384 tryReserveConfirmUsername(username
);
385 } catch (UsernameMalformedException
| UsernameTakenException
| UsernameIsNotReservedException e
) {
386 logger
.debug("[confirmUsername] Failed to reserve confirm username: {} ({})",
388 e
.getClass().getSimpleName());
389 account
.setUsername(null);
390 account
.setUsernameLink(null);
394 logger
.debug("Username already set, not refreshing.");
398 private void tryReserveConfirmUsername(final Username username
) throws IOException
{
399 final var usernameLink
= account
.getUsernameLink();
401 if (usernameLink
== null) {
402 dependencies
.getAccountManager()
403 .reserveUsername(List
.of(Base64
.encodeUrlSafeWithoutPadding(username
.getHash())));
404 logger
.debug("[reserveUsername] Successfully reserved existing username.");
405 final var linkComponents
= dependencies
.getAccountManager().confirmUsernameAndCreateNewLink(username
);
406 account
.setUsernameLink(linkComponents
);
407 logger
.debug("[confirmUsername] Successfully confirmed existing username.");
409 final var linkComponents
= dependencies
.getAccountManager().reclaimUsernameAndLink(username
, usernameLink
);
410 account
.setUsernameLink(linkComponents
);
411 logger
.debug("[confirmUsername] Successfully reclaimed existing username and link.");
415 private void tryToSetUsernameLink(Username username
) {
416 for (var i
= 1; i
< 4; i
++) {
418 final var linkComponents
= dependencies
.getAccountManager().createUsernameLink(username
);
419 account
.setUsernameLink(linkComponents
);
421 } catch (IOException e
) {
422 logger
.debug("[tryToSetUsernameLink] Failed with IOException on attempt {}/3", i
, e
);
427 public void deleteUsername() throws IOException
{
428 dependencies
.getAccountManager().deleteUsername();
429 account
.setUsername(null);
430 logger
.debug("[deleteUsername] Successfully deleted the username.");
433 public void setDeviceName(String deviceName
) {
434 final var privateKey
= account
.getAciIdentityKeyPair().getPrivateKey();
435 final var encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
436 account
.setEncryptedDeviceName(encryptedDeviceName
);
439 public void updateAccountAttributes() throws IOException
{
440 dependencies
.getAccountManager().setAccountAttributes(account
.getAccountAttributes(null));
443 public void addDevice(DeviceLinkUrl deviceLinkInfo
) throws IOException
, InvalidDeviceLinkException
{
444 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
447 dependencies
.getAccountManager()
448 .addDevice(deviceLinkInfo
.deviceIdentifier(),
449 deviceLinkInfo
.deviceKey(),
450 account
.getAciIdentityKeyPair(),
451 account
.getPniIdentityKeyPair(),
452 account
.getProfileKey(),
453 account
.getOrCreatePinMasterKey(),
455 } catch (InvalidKeyException e
) {
456 throw new InvalidDeviceLinkException("Invalid device link", e
);
458 account
.setMultiDevice(true);
459 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
462 public void removeLinkedDevices(int deviceId
) throws IOException
{
463 dependencies
.getAccountManager().removeDevice(deviceId
);
464 var devices
= dependencies
.getAccountManager().getDevices();
465 account
.setMultiDevice(devices
.size() > 1);
468 public void migrateRegistrationPin() throws IOException
{
469 var masterKey
= account
.getOrCreatePinMasterKey();
471 context
.getPinHelper().migrateRegistrationLockPin(account
.getRegistrationLockPin(), masterKey
);
472 dependencies
.getAccountManager().enableRegistrationLock(masterKey
);
475 public void setRegistrationPin(String pin
) throws IOException
{
476 var masterKey
= account
.getOrCreatePinMasterKey();
478 context
.getPinHelper().setRegistrationLockPin(pin
, masterKey
);
479 dependencies
.getAccountManager().enableRegistrationLock(masterKey
);
481 account
.setRegistrationLockPin(pin
);
484 public void removeRegistrationPin() throws IOException
{
486 context
.getPinHelper().removeRegistrationLockPin();
487 dependencies
.getAccountManager().disableRegistrationLock();
489 account
.setRegistrationLockPin(null);
492 public void unregister() throws IOException
{
493 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
494 // If this is the primary device, other users can't send messages to this number anymore.
495 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
496 dependencies
.getAccountManager().setGcmId(Optional
.empty());
498 account
.setRegistered(false);
499 unregisteredListener
.call();
502 public void deleteAccount() throws IOException
{
504 context
.getPinHelper().removeRegistrationLockPin();
505 } catch (IOException e
) {
506 logger
.warn("Failed to remove registration lock pin");
508 account
.setRegistrationLockPin(null);
510 dependencies
.getAccountManager().deleteAccount();
512 account
.setRegistered(false);
513 unregisteredListener
.call();
516 public interface Callable
{