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
.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
, VerificationMethodNotAvailableException
{
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 reserveUsernameFromNickname(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();
332 } catch (IOException
| BaseUsernameException e
) {
333 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 reserveUsername(candidates
);
342 public void reserveExactUsername(String username
) throws IOException
, BaseUsernameException
{
343 final var currentUsername
= account
.getUsername();
344 if (currentUsername
!= null) {
345 if (currentUsername
.equals(username
)) {
347 refreshCurrentUsername();
349 } catch (IOException
| BaseUsernameException e
) {
350 logger
.warn("[reserveUsername] Failed to refresh current username, trying to claim new username");
355 final var candidates
= List
.of(new Username(username
));
356 reserveUsername(candidates
);
359 private void reserveUsername(final List
<Username
> candidates
) throws IOException
{
360 final var candidateHashes
= new ArrayList
<String
>();
361 for (final var candidate
: candidates
) {
362 candidateHashes
.add(Base64
.encodeUrlSafeWithoutPadding(candidate
.getHash()));
365 final var response
= dependencies
.getAccountManager().reserveUsername(candidateHashes
);
366 final var hashIndex
= candidateHashes
.indexOf(response
.getUsernameHash());
367 if (hashIndex
== -1) {
368 logger
.warn("[reserveUsername] The response hash could not be found in our set of candidateHashes.");
369 throw new IOException("Unexpected username response");
372 logger
.debug("[reserveUsername] Successfully reserved username.");
373 final var username
= candidates
.get(hashIndex
);
375 final var linkComponents
= dependencies
.getAccountManager().confirmUsernameAndCreateNewLink(username
);
376 account
.setUsername(username
.getUsername());
377 account
.setUsernameLink(linkComponents
);
378 account
.getRecipientStore().resolveSelfRecipientTrusted(account
.getSelfRecipientAddress());
379 logger
.debug("[confirmUsername] Successfully confirmed username.");
382 public void refreshCurrentUsername() throws IOException
, BaseUsernameException
{
383 final var localUsername
= account
.getUsername();
384 if (localUsername
== null) {
388 final var whoAmIResponse
= dependencies
.getAccountManager().getWhoAmI();
389 final var serverUsernameHash
= whoAmIResponse
.getUsernameHash();
390 final var hasServerUsername
= !isEmpty(serverUsernameHash
);
391 final var username
= new Username(localUsername
);
392 final var localUsernameHash
= Base64
.encodeUrlSafeWithoutPadding(username
.getHash());
394 if (!hasServerUsername
) {
395 logger
.debug("No remote username is set.");
398 if (!Objects
.equals(localUsernameHash
, serverUsernameHash
)) {
399 logger
.debug("Local username hash does not match server username hash.");
402 if (!hasServerUsername
|| !Objects
.equals(localUsernameHash
, serverUsernameHash
)) {
403 logger
.debug("Attempting to resynchronize username.");
405 tryReserveConfirmUsername(username
);
406 } catch (UsernameMalformedException
| UsernameTakenException
| UsernameIsNotReservedException e
) {
407 logger
.debug("[confirmUsername] Failed to reserve confirm username: {} ({})",
409 e
.getClass().getSimpleName());
410 account
.setUsername(null);
411 account
.setUsernameLink(null);
415 logger
.debug("Username already set, not refreshing.");
419 private void tryReserveConfirmUsername(final Username username
) throws IOException
{
420 final var usernameLink
= account
.getUsernameLink();
422 if (usernameLink
== null) {
423 dependencies
.getAccountManager()
424 .reserveUsername(List
.of(Base64
.encodeUrlSafeWithoutPadding(username
.getHash())));
425 logger
.debug("[reserveUsername] Successfully reserved existing username.");
426 final var linkComponents
= dependencies
.getAccountManager().confirmUsernameAndCreateNewLink(username
);
427 account
.setUsernameLink(linkComponents
);
428 logger
.debug("[confirmUsername] Successfully confirmed existing username.");
430 final var linkComponents
= dependencies
.getAccountManager().reclaimUsernameAndLink(username
, usernameLink
);
431 account
.setUsernameLink(linkComponents
);
432 logger
.debug("[confirmUsername] Successfully reclaimed existing username and link.");
436 private void tryToSetUsernameLink(Username username
) {
437 for (var i
= 1; i
< 4; i
++) {
439 final var linkComponents
= dependencies
.getAccountManager().createUsernameLink(username
);
440 account
.setUsernameLink(linkComponents
);
442 } catch (IOException e
) {
443 logger
.debug("[tryToSetUsernameLink] Failed with IOException on attempt {}/3", i
, e
);
448 public void deleteUsername() throws IOException
{
449 dependencies
.getAccountManager().deleteUsernameLink();
450 account
.setUsernameLink(null);
451 dependencies
.getAccountManager().deleteUsername();
452 account
.setUsername(null);
453 logger
.debug("[deleteUsername] Successfully deleted the username.");
456 public void setDeviceName(String deviceName
) {
457 final var privateKey
= account
.getAciIdentityKeyPair().getPrivateKey();
458 final var encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
459 account
.setEncryptedDeviceName(encryptedDeviceName
);
462 public void updateAccountAttributes() throws IOException
{
463 dependencies
.getAccountManager().setAccountAttributes(account
.getAccountAttributes(null));
466 public void addDevice(DeviceLinkUrl deviceLinkInfo
) throws IOException
, InvalidDeviceLinkException
{
467 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
470 dependencies
.getAccountManager()
471 .addDevice(deviceLinkInfo
.deviceIdentifier(),
472 deviceLinkInfo
.deviceKey(),
473 account
.getAciIdentityKeyPair(),
474 account
.getPniIdentityKeyPair(),
475 account
.getProfileKey(),
476 account
.getOrCreatePinMasterKey(),
478 } catch (InvalidKeyException e
) {
479 throw new InvalidDeviceLinkException("Invalid device link", e
);
481 account
.setMultiDevice(true);
482 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
485 public void removeLinkedDevices(int deviceId
) throws IOException
{
486 dependencies
.getAccountManager().removeDevice(deviceId
);
487 var devices
= dependencies
.getAccountManager().getDevices();
488 account
.setMultiDevice(devices
.size() > 1);
491 public void migrateRegistrationPin() throws IOException
{
492 var masterKey
= account
.getOrCreatePinMasterKey();
494 context
.getPinHelper().migrateRegistrationLockPin(account
.getRegistrationLockPin(), masterKey
);
495 dependencies
.getAccountManager().enableRegistrationLock(masterKey
);
498 public void setRegistrationPin(String pin
) throws IOException
{
499 var masterKey
= account
.getOrCreatePinMasterKey();
501 context
.getPinHelper().setRegistrationLockPin(pin
, masterKey
);
502 dependencies
.getAccountManager().enableRegistrationLock(masterKey
);
504 account
.setRegistrationLockPin(pin
);
505 updateAccountAttributes();
508 public void removeRegistrationPin() throws IOException
{
510 context
.getPinHelper().removeRegistrationLockPin();
511 dependencies
.getAccountManager().disableRegistrationLock();
513 account
.setRegistrationLockPin(null);
516 public void unregister() throws IOException
{
517 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
518 // If this is the primary device, other users can't send messages to this number anymore.
519 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
520 dependencies
.getAccountManager().setGcmId(Optional
.empty());
522 account
.setRegistered(false);
523 unregisteredListener
.call();
526 public void deleteAccount() throws IOException
{
528 context
.getPinHelper().removeRegistrationLockPin();
529 } catch (IOException e
) {
530 logger
.warn("Failed to remove registration lock pin");
532 account
.setRegistrationLockPin(null);
534 dependencies
.getAccountManager().deleteAccount();
536 account
.setRegistered(false);
537 unregisteredListener
.call();
540 public interface Callable
{