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
.VerificationMethodNotAvailableException
;
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
.DeviceLimitExceededException
;
43 import org
.whispersystems
.signalservice
.internal
.push
.KyberPreKeyEntity
;
44 import org
.whispersystems
.signalservice
.internal
.push
.OutgoingPushMessage
;
45 import org
.whispersystems
.signalservice
.internal
.push
.SyncMessage
;
46 import org
.whispersystems
.signalservice
.internal
.push
.exceptions
.MismatchedDevicesException
;
48 import java
.io
.IOException
;
49 import java
.util
.ArrayList
;
50 import java
.util
.HashMap
;
51 import java
.util
.List
;
52 import java
.util
.Objects
;
53 import java
.util
.Optional
;
54 import java
.util
.concurrent
.TimeUnit
;
56 import okio
.ByteString
;
58 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.PREKEY_MAXIMUM_ID
;
59 import static org
.whispersystems
.signalservice
.internal
.util
.Util
.isEmpty
;
61 public class AccountHelper
{
63 private static final Logger logger
= LoggerFactory
.getLogger(AccountHelper
.class);
65 private final Context context
;
66 private final SignalAccount account
;
67 private final SignalDependencies dependencies
;
69 private Callable unregisteredListener
;
71 public AccountHelper(final Context context
) {
72 this.account
= context
.getAccount();
73 this.dependencies
= context
.getDependencies();
74 this.context
= context
;
77 public void setUnregisteredListener(final Callable unregisteredListener
) {
78 this.unregisteredListener
= unregisteredListener
;
81 public void checkAccountState() throws IOException
{
82 if (account
.getLastReceiveTimestamp() == 0) {
83 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
85 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
86 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
89 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
94 updateAccountAttributes();
95 if (account
.getPreviousStorageVersion() < 9) {
96 context
.getPreKeyHelper().forceRefreshPreKeys();
98 context
.getPreKeyHelper().refreshPreKeysIfNecessary();
100 if (account
.getAci() == null || account
.getPni() == null) {
103 if (!account
.isPrimaryDevice() && account
.getPniIdentityKeyPair() == null) {
104 context
.getSyncHelper().requestSyncPniIdentity();
106 if (account
.getPreviousStorageVersion() < 4
107 && account
.isPrimaryDevice()
108 && account
.getRegistrationLockPin() != null) {
109 migrateRegistrationPin();
111 if (account
.getUsername() != null && account
.getUsernameLink() == null) {
113 tryToSetUsernameLink(new Username(account
.getUsername()));
114 } catch (BaseUsernameException e
) {
115 logger
.debug("Invalid local username");
118 } catch (DeprecatedVersionException e
) {
119 logger
.debug("Signal-Server returned deprecated version exception", e
);
121 } catch (AuthorizationFailedException e
) {
122 account
.setRegistered(false);
127 public void checkWhoAmiI() throws IOException
{
128 final var whoAmI
= dependencies
.getAccountManager().getWhoAmI();
129 final var number
= whoAmI
.getNumber();
130 final var aci
= ACI
.parseOrThrow(whoAmI
.getAci());
131 final var pni
= PNI
.parseOrThrow(whoAmI
.getPni());
132 if (number
.equals(account
.getNumber()) && aci
.equals(account
.getAci()) && pni
.equals(account
.getPni())) {
136 updateSelfIdentifiers(number
, aci
, pni
);
139 private void updateSelfIdentifiers(final String number
, final ACI aci
, final PNI pni
) {
140 account
.setNumber(number
);
143 if (account
.isPrimaryDevice() && account
.getPniIdentityKeyPair() == null) {
144 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
146 account
.getRecipientTrustedResolver().resolveSelfRecipientTrusted(account
.getSelfRecipientAddress());
147 context
.getUnidentifiedAccessHelper().rotateSenderCertificates();
148 dependencies
.resetAfterAddressChange();
149 context
.getGroupV2Helper().clearAuthCredentialCache();
150 context
.getAccountFileUpdater().updateAccountIdentifiers(account
.getNumber(), account
.getAci());
151 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
155 final PNI updatedPni
,
156 final IdentityKeyPair pniIdentityKeyPair
,
158 final int localPniRegistrationId
,
159 final SignedPreKeyRecord pniSignedPreKey
,
160 final KyberPreKeyRecord lastResortKyberPreKey
161 ) throws IOException
{
162 updateSelfIdentifiers(number
!= null ? number
: account
.getNumber(), account
.getAci(), updatedPni
);
163 account
.setNewPniIdentity(pniIdentityKeyPair
, pniSignedPreKey
, lastResortKyberPreKey
, localPniRegistrationId
);
164 context
.getPreKeyHelper().refreshPreKeysIfNecessary(ServiceIdType
.PNI
);
167 public void startChangeNumber(
168 String newNumber
, boolean voiceVerification
, String captcha
169 ) throws IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
, RateLimitException
, VerificationMethodNotAvailableException
{
170 final var accountManager
= dependencies
.createUnauthenticatedAccountManager(newNumber
, account
.getPassword());
171 String sessionId
= NumberVerificationUtils
.handleVerificationSession(accountManager
,
172 account
.getSessionId(newNumber
),
173 id
-> account
.setSessionId(newNumber
, id
),
176 NumberVerificationUtils
.requestVerificationCode(accountManager
, sessionId
, voiceVerification
);
179 public void finishChangeNumber(
180 String newNumber
, String verificationCode
, String pin
181 ) throws IncorrectPinException
, PinLockedException
, IOException
{
182 for (var attempts
= 0; attempts
< 5; attempts
++) {
184 finishChangeNumberInternal(newNumber
, verificationCode
, pin
);
186 } catch (MismatchedDevicesException e
) {
187 logger
.debug("Change number failed with mismatched devices, retrying.");
189 dependencies
.getMessageSender().handleChangeNumberMismatchDevices(e
.getMismatchedDevices());
190 } catch (UntrustedIdentityException ex
) {
191 throw new AssertionError(ex
);
197 private void finishChangeNumberInternal(
198 String newNumber
, String verificationCode
, String pin
199 ) throws IncorrectPinException
, PinLockedException
, IOException
{
200 final var pniIdentity
= KeyUtils
.generateIdentityKeyPair();
201 final var encryptedDeviceMessages
= new ArrayList
<OutgoingPushMessage
>();
202 final var devicePniSignedPreKeys
= new HashMap
<Integer
, SignedPreKeyEntity
>();
203 final var devicePniLastResortKyberPreKeys
= new HashMap
<Integer
, KyberPreKeyEntity
>();
204 final var pniRegistrationIds
= new HashMap
<Integer
, Integer
>();
206 final var selfDeviceId
= account
.getDeviceId();
207 SyncMessage
.PniChangeNumber selfChangeNumber
= null;
209 final var deviceIds
= new ArrayList
<Integer
>();
210 deviceIds
.add(SignalServiceAddress
.DEFAULT_DEVICE_ID
);
211 final var aci
= account
.getAci();
212 final var accountDataStore
= account
.getSignalServiceDataStore().aci();
213 final var subDeviceSessions
= accountDataStore
.getSubDeviceSessions(aci
.toString())
215 .filter(deviceId
-> accountDataStore
.containsSession(new SignalProtocolAddress(aci
.toString(),
218 deviceIds
.addAll(subDeviceSessions
);
220 final var messageSender
= dependencies
.getMessageSender();
221 for (final var deviceId
: deviceIds
) {
223 final var signedPreKeyRecord
= KeyUtils
.generateSignedPreKeyRecord(KeyUtils
.getRandomInt(PREKEY_MAXIMUM_ID
),
224 pniIdentity
.getPrivateKey());
225 final var signedPreKeyEntity
= new SignedPreKeyEntity(signedPreKeyRecord
.getId(),
226 signedPreKeyRecord
.getKeyPair().getPublicKey(),
227 signedPreKeyRecord
.getSignature());
228 devicePniSignedPreKeys
.put(deviceId
, signedPreKeyEntity
);
230 // Last-resort kyber prekey
231 final var lastResortKyberPreKeyRecord
= KeyUtils
.generateKyberPreKeyRecord(KeyUtils
.getRandomInt(
232 PREKEY_MAXIMUM_ID
), pniIdentity
.getPrivateKey());
233 final var kyberPreKeyEntity
= new KyberPreKeyEntity(lastResortKyberPreKeyRecord
.getId(),
234 lastResortKyberPreKeyRecord
.getKeyPair().getPublicKey(),
235 lastResortKyberPreKeyRecord
.getSignature());
236 devicePniLastResortKyberPreKeys
.put(deviceId
, kyberPreKeyEntity
);
239 var pniRegistrationId
= -1;
240 while (pniRegistrationId
< 0 || pniRegistrationIds
.containsValue(pniRegistrationId
)) {
241 pniRegistrationId
= KeyHelper
.generateRegistrationId(false);
243 pniRegistrationIds
.put(deviceId
, pniRegistrationId
);
246 final var pniChangeNumber
= new SyncMessage
.PniChangeNumber
.Builder().identityKeyPair(ByteString
.of(
247 pniIdentity
.serialize()))
248 .signedPreKey(ByteString
.of(signedPreKeyRecord
.serialize()))
249 .lastResortKyberPreKey(ByteString
.of(lastResortKyberPreKeyRecord
.serialize()))
250 .registrationId(pniRegistrationId
)
254 if (deviceId
== selfDeviceId
) {
255 selfChangeNumber
= pniChangeNumber
;
258 final var message
= messageSender
.getEncryptedSyncPniInitializeDeviceMessage(deviceId
,
260 encryptedDeviceMessages
.add(message
);
261 } catch (UntrustedIdentityException
| IOException
| InvalidKeyException e
) {
262 throw new RuntimeException(e
);
267 final var sessionId
= account
.getSessionId(newNumber
);
268 final var result
= NumberVerificationUtils
.verifyNumber(sessionId
,
271 context
.getPinHelper(),
272 (sessionId1
, verificationCode1
, registrationLock
) -> {
273 final var accountManager
= dependencies
.getAccountManager();
275 Utils
.handleResponseException(accountManager
.verifyAccount(verificationCode1
, sessionId1
));
276 } catch (AlreadyVerifiedException e
) {
277 // Already verified so can continue changing number
279 return Utils
.handleResponseException(accountManager
.changeNumber(new ChangePhoneNumberRequest(
284 pniIdentity
.getPublicKey(),
285 encryptedDeviceMessages
,
286 Utils
.mapKeys(devicePniSignedPreKeys
, Object
::toString
),
287 Utils
.mapKeys(devicePniLastResortKyberPreKeys
, Object
::toString
),
288 Utils
.mapKeys(pniRegistrationIds
, Object
::toString
))));
291 final var updatePni
= PNI
.parseOrThrow(result
.first().getPni());
292 if (updatePni
.equals(account
.getPni())) {
293 logger
.debug("PNI is unchanged after change number");
297 handlePniChangeNumberMessage(selfChangeNumber
, updatePni
);
300 public void handlePniChangeNumberMessage(
301 final SyncMessage
.PniChangeNumber pniChangeNumber
, final PNI updatedPni
303 if (pniChangeNumber
.identityKeyPair
!= null
304 && pniChangeNumber
.registrationId
!= null
305 && pniChangeNumber
.signedPreKey
!= null) {
306 logger
.debug("New PNI: {}", updatedPni
);
309 new IdentityKeyPair(pniChangeNumber
.identityKeyPair
.toByteArray()),
310 pniChangeNumber
.newE164
,
311 pniChangeNumber
.registrationId
,
312 new SignedPreKeyRecord(pniChangeNumber
.signedPreKey
.toByteArray()),
313 pniChangeNumber
.lastResortKyberPreKey
!= null
314 ?
new KyberPreKeyRecord(pniChangeNumber
.lastResortKyberPreKey
.toByteArray())
316 } catch (Exception e
) {
317 logger
.warn("Failed to handle change number message", e
);
322 public static final int USERNAME_MIN_LENGTH
= 3;
323 public static final int USERNAME_MAX_LENGTH
= 32;
325 public void reserveUsernameFromNickname(String nickname
) throws IOException
, BaseUsernameException
{
326 final var currentUsername
= account
.getUsername();
327 if (currentUsername
!= null) {
328 final var currentNickname
= currentUsername
.substring(0, currentUsername
.indexOf('.'));
329 if (currentNickname
.equals(nickname
)) {
331 refreshCurrentUsername();
333 } catch (IOException
| BaseUsernameException e
) {
334 logger
.warn("[reserveUsername] Failed to refresh current username, trying to claim new username");
339 final var candidates
= Username
.candidatesFrom(nickname
, USERNAME_MIN_LENGTH
, USERNAME_MAX_LENGTH
);
340 reserveUsername(candidates
);
343 public void reserveExactUsername(String username
) throws IOException
, BaseUsernameException
{
344 final var currentUsername
= account
.getUsername();
345 if (currentUsername
!= null) {
346 if (currentUsername
.equals(username
)) {
348 refreshCurrentUsername();
350 } catch (IOException
| BaseUsernameException e
) {
351 logger
.warn("[reserveUsername] Failed to refresh current username, trying to claim new username");
356 final var candidates
= List
.of(new Username(username
));
357 reserveUsername(candidates
);
360 private void reserveUsername(final List
<Username
> candidates
) throws IOException
{
361 final var candidateHashes
= new ArrayList
<String
>();
362 for (final var candidate
: candidates
) {
363 candidateHashes
.add(Base64
.encodeUrlSafeWithoutPadding(candidate
.getHash()));
366 final var response
= dependencies
.getAccountManager().reserveUsername(candidateHashes
);
367 final var hashIndex
= candidateHashes
.indexOf(response
.getUsernameHash());
368 if (hashIndex
== -1) {
369 logger
.warn("[reserveUsername] The response hash could not be found in our set of candidateHashes.");
370 throw new IOException("Unexpected username response");
373 logger
.debug("[reserveUsername] Successfully reserved username.");
374 final var username
= candidates
.get(hashIndex
);
376 final var linkComponents
= dependencies
.getAccountManager().confirmUsernameAndCreateNewLink(username
);
377 account
.setUsername(username
.getUsername());
378 account
.setUsernameLink(linkComponents
);
379 account
.getRecipientStore().resolveSelfRecipientTrusted(account
.getSelfRecipientAddress());
380 account
.getRecipientStore().rotateSelfStorageId();
381 logger
.debug("[confirmUsername] Successfully confirmed username.");
384 public void refreshCurrentUsername() throws IOException
, BaseUsernameException
{
385 final var localUsername
= account
.getUsername();
386 if (localUsername
== null) {
390 final var whoAmIResponse
= dependencies
.getAccountManager().getWhoAmI();
391 final var serverUsernameHash
= whoAmIResponse
.getUsernameHash();
392 final var hasServerUsername
= !isEmpty(serverUsernameHash
);
393 final var username
= new Username(localUsername
);
394 final var localUsernameHash
= Base64
.encodeUrlSafeWithoutPadding(username
.getHash());
396 if (!hasServerUsername
) {
397 logger
.debug("No remote username is set.");
400 if (!Objects
.equals(localUsernameHash
, serverUsernameHash
)) {
401 logger
.debug("Local username hash does not match server username hash.");
404 if (!hasServerUsername
|| !Objects
.equals(localUsernameHash
, serverUsernameHash
)) {
405 logger
.debug("Attempting to resynchronize username.");
407 tryReserveConfirmUsername(username
);
408 } catch (UsernameMalformedException
| UsernameTakenException
| UsernameIsNotReservedException e
) {
409 logger
.debug("[confirmUsername] Failed to reserve confirm username: {} ({})",
411 e
.getClass().getSimpleName());
412 account
.setUsername(null);
413 account
.setUsernameLink(null);
414 account
.getRecipientStore().rotateSelfStorageId();
418 logger
.debug("Username already set, not refreshing.");
422 private void tryReserveConfirmUsername(final Username username
) throws IOException
{
423 final var usernameLink
= account
.getUsernameLink();
425 if (usernameLink
== null) {
426 dependencies
.getAccountManager()
427 .reserveUsername(List
.of(Base64
.encodeUrlSafeWithoutPadding(username
.getHash())));
428 logger
.debug("[reserveUsername] Successfully reserved existing username.");
429 final var linkComponents
= dependencies
.getAccountManager().confirmUsernameAndCreateNewLink(username
);
430 account
.setUsernameLink(linkComponents
);
431 logger
.debug("[confirmUsername] Successfully confirmed existing username.");
433 final var linkComponents
= dependencies
.getAccountManager().reclaimUsernameAndLink(username
, usernameLink
);
434 account
.setUsernameLink(linkComponents
);
435 logger
.debug("[confirmUsername] Successfully reclaimed existing username and link.");
437 account
.getRecipientStore().rotateSelfStorageId();
440 private void tryToSetUsernameLink(Username username
) {
441 for (var i
= 1; i
< 4; i
++) {
443 final var linkComponents
= dependencies
.getAccountManager().createUsernameLink(username
);
444 account
.setUsernameLink(linkComponents
);
446 } catch (IOException e
) {
447 logger
.debug("[tryToSetUsernameLink] Failed with IOException on attempt {}/3", i
, e
);
452 public void deleteUsername() throws IOException
{
453 dependencies
.getAccountManager().deleteUsernameLink();
454 account
.setUsernameLink(null);
455 dependencies
.getAccountManager().deleteUsername();
456 account
.setUsername(null);
457 logger
.debug("[deleteUsername] Successfully deleted the username.");
460 public void setDeviceName(String deviceName
) {
461 final var privateKey
= account
.getAciIdentityKeyPair().getPrivateKey();
462 final var encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
463 account
.setEncryptedDeviceName(encryptedDeviceName
);
466 public void updateAccountAttributes() throws IOException
{
467 dependencies
.getAccountManager().setAccountAttributes(account
.getAccountAttributes(null));
470 public void addDevice(DeviceLinkUrl deviceLinkInfo
) throws IOException
, InvalidDeviceLinkException
, org
.asamk
.signal
.manager
.api
.DeviceLimitExceededException
{
471 String verificationCode
;
473 verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
474 } catch (DeviceLimitExceededException e
) {
475 throw new org
.asamk
.signal
.manager
.api
.DeviceLimitExceededException("Too many linked devices", e
);
479 dependencies
.getAccountManager()
480 .addDevice(deviceLinkInfo
.deviceIdentifier(),
481 deviceLinkInfo
.deviceKey(),
482 account
.getAciIdentityKeyPair(),
483 account
.getPniIdentityKeyPair(),
484 account
.getProfileKey(),
485 account
.getOrCreatePinMasterKey(),
487 } catch (InvalidKeyException e
) {
488 throw new InvalidDeviceLinkException("Invalid device link", e
);
490 account
.setMultiDevice(true);
491 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
494 public void removeLinkedDevices(int deviceId
) throws IOException
{
495 dependencies
.getAccountManager().removeDevice(deviceId
);
496 var devices
= dependencies
.getAccountManager().getDevices();
497 account
.setMultiDevice(devices
.size() > 1);
500 public void migrateRegistrationPin() throws IOException
{
501 var masterKey
= account
.getOrCreatePinMasterKey();
503 context
.getPinHelper().migrateRegistrationLockPin(account
.getRegistrationLockPin(), masterKey
);
504 dependencies
.getAccountManager().enableRegistrationLock(masterKey
);
507 public void setRegistrationPin(String pin
) throws IOException
{
508 var masterKey
= account
.getOrCreatePinMasterKey();
510 context
.getPinHelper().setRegistrationLockPin(pin
, masterKey
);
511 dependencies
.getAccountManager().enableRegistrationLock(masterKey
);
513 account
.setRegistrationLockPin(pin
);
514 updateAccountAttributes();
517 public void removeRegistrationPin() throws IOException
{
519 context
.getPinHelper().removeRegistrationLockPin();
520 dependencies
.getAccountManager().disableRegistrationLock();
522 account
.setRegistrationLockPin(null);
525 public void unregister() throws IOException
{
526 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
527 // If this is the primary device, other users can't send messages to this number anymore.
528 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
529 dependencies
.getAccountManager().setGcmId(Optional
.empty());
531 account
.setRegistered(false);
532 unregisteredListener
.call();
535 public void deleteAccount() throws IOException
{
537 context
.getPinHelper().removeRegistrationLockPin();
538 } catch (IOException e
) {
539 logger
.warn("Failed to remove registration lock pin");
541 account
.setRegistrationLockPin(null);
543 dependencies
.getAccountManager().deleteAccount();
545 account
.setRegistered(false);
546 unregisteredListener
.call();
549 public interface Callable
{