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
.internal
.SignalDependencies
;
11 import org
.asamk
.signal
.manager
.jobs
.SyncStorageJob
;
12 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
13 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
14 import org
.asamk
.signal
.manager
.util
.NumberVerificationUtils
;
15 import org
.asamk
.signal
.manager
.util
.Utils
;
16 import org
.signal
.core
.util
.Base64
;
17 import org
.signal
.libsignal
.protocol
.IdentityKeyPair
;
18 import org
.signal
.libsignal
.protocol
.InvalidKeyException
;
19 import org
.signal
.libsignal
.protocol
.SignalProtocolAddress
;
20 import org
.signal
.libsignal
.protocol
.state
.KyberPreKeyRecord
;
21 import org
.signal
.libsignal
.protocol
.state
.SignedPreKeyRecord
;
22 import org
.signal
.libsignal
.protocol
.util
.KeyHelper
;
23 import org
.signal
.libsignal
.usernames
.BaseUsernameException
;
24 import org
.signal
.libsignal
.usernames
.Username
;
25 import org
.slf4j
.Logger
;
26 import org
.slf4j
.LoggerFactory
;
27 import org
.whispersystems
.signalservice
.api
.account
.ChangePhoneNumberRequest
;
28 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
29 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
30 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
31 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
32 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
33 import org
.whispersystems
.signalservice
.api
.push
.SignedPreKeyEntity
;
34 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AlreadyVerifiedException
;
35 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
36 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.DeprecatedVersionException
;
37 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UsernameIsNotReservedException
;
38 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UsernameMalformedException
;
39 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UsernameTakenException
;
40 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
41 import org
.whispersystems
.signalservice
.internal
.push
.KyberPreKeyEntity
;
42 import org
.whispersystems
.signalservice
.internal
.push
.OutgoingPushMessage
;
43 import org
.whispersystems
.signalservice
.internal
.push
.SyncMessage
;
44 import org
.whispersystems
.signalservice
.internal
.push
.exceptions
.MismatchedDevicesException
;
46 import java
.io
.IOException
;
47 import java
.util
.ArrayList
;
48 import java
.util
.HashMap
;
49 import java
.util
.List
;
50 import java
.util
.Objects
;
51 import java
.util
.Optional
;
52 import java
.util
.concurrent
.TimeUnit
;
54 import okio
.ByteString
;
56 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.PREKEY_MAXIMUM_ID
;
57 import static org
.whispersystems
.signalservice
.internal
.util
.Util
.isEmpty
;
59 public class AccountHelper
{
61 private static final Logger logger
= LoggerFactory
.getLogger(AccountHelper
.class);
63 private final Context context
;
64 private final SignalAccount account
;
65 private final SignalDependencies dependencies
;
67 private Callable unregisteredListener
;
69 public AccountHelper(final Context context
) {
70 this.account
= context
.getAccount();
71 this.dependencies
= context
.getDependencies();
72 this.context
= context
;
75 public void setUnregisteredListener(final Callable unregisteredListener
) {
76 this.unregisteredListener
= unregisteredListener
;
79 public void checkAccountState() throws IOException
{
80 if (account
.getLastReceiveTimestamp() == 0) {
81 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
83 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
84 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
87 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
92 updateAccountAttributes();
93 context
.getPreKeyHelper().refreshPreKeysIfNecessary();
94 if (account
.getAci() == null || account
.getPni() == null) {
97 if (!account
.isPrimaryDevice() && account
.getPniIdentityKeyPair() == null) {
98 context
.getSyncHelper().requestSyncPniIdentity();
100 if (account
.getPreviousStorageVersion() < 4
101 && account
.isPrimaryDevice()
102 && account
.getRegistrationLockPin() != null) {
103 migrateRegistrationPin();
105 if (account
.getUsername() != null && account
.getUsernameLink() == null) {
107 tryToSetUsernameLink(new Username(account
.getUsername()));
108 } catch (BaseUsernameException e
) {
109 logger
.debug("Invalid local username");
112 } catch (DeprecatedVersionException e
) {
113 logger
.debug("Signal-Server returned deprecated version exception", e
);
115 } catch (AuthorizationFailedException e
) {
116 account
.setRegistered(false);
121 public void checkWhoAmiI() throws IOException
{
122 final var whoAmI
= dependencies
.getAccountManager().getWhoAmI();
123 final var number
= whoAmI
.getNumber();
124 final var aci
= ACI
.parseOrThrow(whoAmI
.getAci());
125 final var pni
= PNI
.parseOrThrow(whoAmI
.getPni());
126 if (number
.equals(account
.getNumber()) && aci
.equals(account
.getAci()) && pni
.equals(account
.getPni())) {
130 updateSelfIdentifiers(number
, aci
, pni
);
133 private void updateSelfIdentifiers(final String number
, final ACI aci
, final PNI pni
) {
134 account
.setNumber(number
);
137 if (account
.isPrimaryDevice() && account
.getPniIdentityKeyPair() == null) {
138 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
140 account
.getRecipientTrustedResolver().resolveSelfRecipientTrusted(account
.getSelfRecipientAddress());
141 context
.getUnidentifiedAccessHelper().rotateSenderCertificates();
142 dependencies
.resetAfterAddressChange();
143 context
.getGroupV2Helper().clearAuthCredentialCache();
144 context
.getAccountFileUpdater().updateAccountIdentifiers(account
.getNumber(), account
.getAci());
145 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
149 final PNI updatedPni
,
150 final IdentityKeyPair pniIdentityKeyPair
,
152 final int localPniRegistrationId
,
153 final SignedPreKeyRecord pniSignedPreKey
,
154 final KyberPreKeyRecord lastResortKyberPreKey
155 ) throws IOException
{
156 updateSelfIdentifiers(number
!= null ? number
: account
.getNumber(), account
.getAci(), updatedPni
);
157 account
.setNewPniIdentity(pniIdentityKeyPair
, pniSignedPreKey
, lastResortKyberPreKey
, localPniRegistrationId
);
158 context
.getPreKeyHelper().refreshPreKeysIfNecessary(ServiceIdType
.PNI
);
161 public void startChangeNumber(
162 String newNumber
, boolean voiceVerification
, String captcha
163 ) throws IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
, RateLimitException
{
164 final var accountManager
= dependencies
.createUnauthenticatedAccountManager(newNumber
, account
.getPassword());
165 String sessionId
= NumberVerificationUtils
.handleVerificationSession(accountManager
,
166 account
.getSessionId(newNumber
),
167 id
-> account
.setSessionId(newNumber
, id
),
170 NumberVerificationUtils
.requestVerificationCode(accountManager
, sessionId
, voiceVerification
);
173 public void finishChangeNumber(
174 String newNumber
, String verificationCode
, String pin
175 ) throws IncorrectPinException
, PinLockedException
, IOException
{
176 for (var attempts
= 0; attempts
< 5; attempts
++) {
178 finishChangeNumberInternal(newNumber
, verificationCode
, pin
);
180 } catch (MismatchedDevicesException e
) {
181 logger
.debug("Change number failed with mismatched devices, retrying.");
183 dependencies
.getMessageSender().handleChangeNumberMismatchDevices(e
.getMismatchedDevices());
184 } catch (UntrustedIdentityException ex
) {
185 throw new AssertionError(ex
);
191 private void finishChangeNumberInternal(
192 String newNumber
, String verificationCode
, String pin
193 ) throws IncorrectPinException
, PinLockedException
, IOException
{
194 final var pniIdentity
= KeyUtils
.generateIdentityKeyPair();
195 final var encryptedDeviceMessages
= new ArrayList
<OutgoingPushMessage
>();
196 final var devicePniSignedPreKeys
= new HashMap
<Integer
, SignedPreKeyEntity
>();
197 final var devicePniLastResortKyberPreKeys
= new HashMap
<Integer
, KyberPreKeyEntity
>();
198 final var pniRegistrationIds
= new HashMap
<Integer
, Integer
>();
200 final var selfDeviceId
= account
.getDeviceId();
201 SyncMessage
.PniChangeNumber selfChangeNumber
= null;
203 final var deviceIds
= new ArrayList
<Integer
>();
204 deviceIds
.add(SignalServiceAddress
.DEFAULT_DEVICE_ID
);
205 final var aci
= account
.getAci();
206 final var accountDataStore
= account
.getSignalServiceDataStore().aci();
207 final var subDeviceSessions
= accountDataStore
.getSubDeviceSessions(aci
.toString())
209 .filter(deviceId
-> accountDataStore
.containsSession(new SignalProtocolAddress(aci
.toString(),
212 deviceIds
.addAll(subDeviceSessions
);
214 final var messageSender
= dependencies
.getMessageSender();
215 for (final var deviceId
: deviceIds
) {
217 final var signedPreKeyRecord
= KeyUtils
.generateSignedPreKeyRecord(KeyUtils
.getRandomInt(PREKEY_MAXIMUM_ID
),
218 pniIdentity
.getPrivateKey());
219 final var signedPreKeyEntity
= new SignedPreKeyEntity(signedPreKeyRecord
.getId(),
220 signedPreKeyRecord
.getKeyPair().getPublicKey(),
221 signedPreKeyRecord
.getSignature());
222 devicePniSignedPreKeys
.put(deviceId
, signedPreKeyEntity
);
224 // Last-resort kyber prekey
225 final var lastResortKyberPreKeyRecord
= KeyUtils
.generateKyberPreKeyRecord(KeyUtils
.getRandomInt(
226 PREKEY_MAXIMUM_ID
), pniIdentity
.getPrivateKey());
227 final var kyberPreKeyEntity
= new KyberPreKeyEntity(lastResortKyberPreKeyRecord
.getId(),
228 lastResortKyberPreKeyRecord
.getKeyPair().getPublicKey(),
229 lastResortKyberPreKeyRecord
.getSignature());
230 devicePniLastResortKyberPreKeys
.put(deviceId
, kyberPreKeyEntity
);
233 var pniRegistrationId
= -1;
234 while (pniRegistrationId
< 0 || pniRegistrationIds
.containsValue(pniRegistrationId
)) {
235 pniRegistrationId
= KeyHelper
.generateRegistrationId(false);
237 pniRegistrationIds
.put(deviceId
, pniRegistrationId
);
240 final var pniChangeNumber
= new SyncMessage
.PniChangeNumber
.Builder().identityKeyPair(ByteString
.of(
241 pniIdentity
.serialize()))
242 .signedPreKey(ByteString
.of(signedPreKeyRecord
.serialize()))
243 .lastResortKyberPreKey(ByteString
.of(lastResortKyberPreKeyRecord
.serialize()))
244 .registrationId(pniRegistrationId
)
248 if (deviceId
== selfDeviceId
) {
249 selfChangeNumber
= pniChangeNumber
;
252 final var message
= messageSender
.getEncryptedSyncPniInitializeDeviceMessage(deviceId
,
254 encryptedDeviceMessages
.add(message
);
255 } catch (UntrustedIdentityException
| IOException
| InvalidKeyException e
) {
256 throw new RuntimeException(e
);
261 final var sessionId
= account
.getSessionId(newNumber
);
262 final var result
= NumberVerificationUtils
.verifyNumber(sessionId
,
265 context
.getPinHelper(),
266 (sessionId1
, verificationCode1
, registrationLock
) -> {
267 final var accountManager
= dependencies
.getAccountManager();
269 Utils
.handleResponseException(accountManager
.verifyAccount(verificationCode1
, sessionId1
));
270 } catch (AlreadyVerifiedException e
) {
271 // Already verified so can continue changing number
273 return Utils
.handleResponseException(accountManager
.changeNumber(new ChangePhoneNumberRequest(
278 pniIdentity
.getPublicKey(),
279 encryptedDeviceMessages
,
280 Utils
.mapKeys(devicePniSignedPreKeys
, Object
::toString
),
281 Utils
.mapKeys(devicePniLastResortKyberPreKeys
, Object
::toString
),
282 Utils
.mapKeys(pniRegistrationIds
, Object
::toString
))));
285 final var updatePni
= PNI
.parseOrThrow(result
.first().getPni());
286 if (updatePni
.equals(account
.getPni())) {
287 logger
.debug("PNI is unchanged after change number");
291 handlePniChangeNumberMessage(selfChangeNumber
, updatePni
);
294 public void handlePniChangeNumberMessage(
295 final SyncMessage
.PniChangeNumber pniChangeNumber
, final PNI updatedPni
297 if (pniChangeNumber
.identityKeyPair
!= null
298 && pniChangeNumber
.registrationId
!= null
299 && pniChangeNumber
.signedPreKey
!= null) {
300 logger
.debug("New PNI: {}", updatedPni
);
303 new IdentityKeyPair(pniChangeNumber
.identityKeyPair
.toByteArray()),
304 pniChangeNumber
.newE164
,
305 pniChangeNumber
.registrationId
,
306 new SignedPreKeyRecord(pniChangeNumber
.signedPreKey
.toByteArray()),
307 pniChangeNumber
.lastResortKyberPreKey
!= null
308 ?
new KyberPreKeyRecord(pniChangeNumber
.lastResortKyberPreKey
.toByteArray())
310 } catch (Exception e
) {
311 logger
.warn("Failed to handle change number message", e
);
316 public static final int USERNAME_MIN_LENGTH
= 3;
317 public static final int USERNAME_MAX_LENGTH
= 32;
319 public void reserveUsername(String nickname
) throws IOException
, BaseUsernameException
{
320 final var currentUsername
= account
.getUsername();
321 if (currentUsername
!= null) {
322 final var currentNickname
= currentUsername
.substring(0, currentUsername
.indexOf('.'));
323 if (currentNickname
.equals(nickname
)) {
325 refreshCurrentUsername();
326 } catch (IOException
| BaseUsernameException e
) {
327 logger
.warn("[reserveUsername] Failed to refresh current username, trying to claim new username");
333 final var candidates
= Username
.candidatesFrom(nickname
, USERNAME_MIN_LENGTH
, USERNAME_MAX_LENGTH
);
334 final var candidateHashes
= new ArrayList
<String
>();
335 for (final var candidate
: candidates
) {
336 candidateHashes
.add(Base64
.encodeUrlSafeWithoutPadding(candidate
.getHash()));
339 final var response
= dependencies
.getAccountManager().reserveUsername(candidateHashes
);
340 final var hashIndex
= candidateHashes
.indexOf(response
.getUsernameHash());
341 if (hashIndex
== -1) {
342 logger
.warn("[reserveUsername] The response hash could not be found in our set of candidateHashes.");
343 throw new IOException("Unexpected username response");
346 logger
.debug("[reserveUsername] Successfully reserved username.");
347 final var username
= candidates
.get(hashIndex
);
349 final var linkComponents
= dependencies
.getAccountManager().confirmUsernameAndCreateNewLink(username
);
350 account
.setUsername(username
.getUsername());
351 account
.setUsernameLink(linkComponents
);
352 account
.getRecipientStore().resolveSelfRecipientTrusted(account
.getSelfRecipientAddress());
353 logger
.debug("[confirmUsername] Successfully confirmed username.");
356 public void refreshCurrentUsername() throws IOException
, BaseUsernameException
{
357 final var localUsername
= account
.getUsername();
358 if (localUsername
== null) {
362 final var whoAmIResponse
= dependencies
.getAccountManager().getWhoAmI();
363 final var serverUsernameHash
= whoAmIResponse
.getUsernameHash();
364 final var hasServerUsername
= !isEmpty(serverUsernameHash
);
365 final var username
= new Username(localUsername
);
366 final var localUsernameHash
= Base64
.encodeUrlSafeWithoutPadding(username
.getHash());
368 if (!hasServerUsername
) {
369 logger
.debug("No remote username is set.");
372 if (!Objects
.equals(localUsernameHash
, serverUsernameHash
)) {
373 logger
.debug("Local username hash does not match server username hash.");
376 if (!hasServerUsername
|| !Objects
.equals(localUsernameHash
, serverUsernameHash
)) {
377 logger
.debug("Attempting to resynchronize username.");
379 tryReserveConfirmUsername(username
);
380 } catch (UsernameMalformedException
| UsernameTakenException
| UsernameIsNotReservedException e
) {
381 logger
.debug("[confirmUsername] Failed to reserve confirm username: {} ({})",
383 e
.getClass().getSimpleName());
384 account
.setUsername(null);
385 account
.setUsernameLink(null);
389 logger
.debug("Username already set, not refreshing.");
393 private void tryReserveConfirmUsername(final Username username
) throws IOException
{
394 final var usernameLink
= account
.getUsernameLink();
396 if (usernameLink
== null) {
397 dependencies
.getAccountManager()
398 .reserveUsername(List
.of(Base64
.encodeUrlSafeWithoutPadding(username
.getHash())));
399 logger
.debug("[reserveUsername] Successfully reserved existing username.");
400 final var linkComponents
= dependencies
.getAccountManager().confirmUsernameAndCreateNewLink(username
);
401 account
.setUsernameLink(linkComponents
);
402 logger
.debug("[confirmUsername] Successfully confirmed existing username.");
404 final var linkComponents
= dependencies
.getAccountManager().reclaimUsernameAndLink(username
, usernameLink
);
405 account
.setUsernameLink(linkComponents
);
406 logger
.debug("[confirmUsername] Successfully reclaimed existing username and link.");
410 private void tryToSetUsernameLink(Username username
) {
411 for (var i
= 1; i
< 4; i
++) {
413 final var linkComponents
= dependencies
.getAccountManager().createUsernameLink(username
);
414 account
.setUsernameLink(linkComponents
);
416 } catch (IOException e
) {
417 logger
.debug("[tryToSetUsernameLink] Failed with IOException on attempt {}/3", i
, e
);
422 public void deleteUsername() throws IOException
{
423 dependencies
.getAccountManager().deleteUsername();
424 account
.setUsername(null);
425 logger
.debug("[deleteUsername] Successfully deleted the username.");
428 public void setDeviceName(String deviceName
) {
429 final var privateKey
= account
.getAciIdentityKeyPair().getPrivateKey();
430 final var encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
431 account
.setEncryptedDeviceName(encryptedDeviceName
);
434 public void updateAccountAttributes() throws IOException
{
435 dependencies
.getAccountManager().setAccountAttributes(account
.getAccountAttributes(null));
438 public void addDevice(DeviceLinkUrl deviceLinkInfo
) throws IOException
, InvalidDeviceLinkException
{
439 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
442 dependencies
.getAccountManager()
443 .addDevice(deviceLinkInfo
.deviceIdentifier(),
444 deviceLinkInfo
.deviceKey(),
445 account
.getAciIdentityKeyPair(),
446 account
.getPniIdentityKeyPair(),
447 account
.getProfileKey(),
448 account
.getOrCreatePinMasterKey(),
450 } catch (InvalidKeyException e
) {
451 throw new InvalidDeviceLinkException("Invalid device link", e
);
453 account
.setMultiDevice(true);
454 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
457 public void removeLinkedDevices(int deviceId
) throws IOException
{
458 dependencies
.getAccountManager().removeDevice(deviceId
);
459 var devices
= dependencies
.getAccountManager().getDevices();
460 account
.setMultiDevice(devices
.size() > 1);
463 public void migrateRegistrationPin() throws IOException
{
464 var masterKey
= account
.getOrCreatePinMasterKey();
466 context
.getPinHelper().migrateRegistrationLockPin(account
.getRegistrationLockPin(), masterKey
);
467 dependencies
.getAccountManager().enableRegistrationLock(masterKey
);
470 public void setRegistrationPin(String pin
) throws IOException
{
471 var masterKey
= account
.getOrCreatePinMasterKey();
473 context
.getPinHelper().setRegistrationLockPin(pin
, masterKey
);
474 dependencies
.getAccountManager().enableRegistrationLock(masterKey
);
476 account
.setRegistrationLockPin(pin
);
479 public void removeRegistrationPin() throws IOException
{
481 context
.getPinHelper().removeRegistrationLockPin();
482 dependencies
.getAccountManager().disableRegistrationLock();
484 account
.setRegistrationLockPin(null);
487 public void unregister() throws IOException
{
488 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
489 // If this is the primary device, other users can't send messages to this number anymore.
490 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
491 dependencies
.getAccountManager().setGcmId(Optional
.empty());
493 account
.setRegistered(false);
494 unregisteredListener
.call();
497 public void deleteAccount() throws IOException
{
499 context
.getPinHelper().removeRegistrationLockPin();
500 } catch (IOException e
) {
501 logger
.warn("Failed to remove registration lock pin");
503 account
.setRegistrationLockPin(null);
505 dependencies
.getAccountManager().deleteAccount();
507 account
.setRegistered(false);
508 unregisteredListener
.call();
511 public interface Callable
{