1package eu.siacs.conversations.crypto.axolotl;
2
3import android.os.Bundle;
4import android.security.KeyChain;
5import android.support.annotation.NonNull;
6import android.support.annotation.Nullable;
7import android.util.Log;
8import android.util.Pair;
9
10import org.bouncycastle.jce.provider.BouncyCastleProvider;
11import org.whispersystems.libsignal.SignalProtocolAddress;
12import org.whispersystems.libsignal.IdentityKey;
13import org.whispersystems.libsignal.IdentityKeyPair;
14import org.whispersystems.libsignal.InvalidKeyException;
15import org.whispersystems.libsignal.InvalidKeyIdException;
16import org.whispersystems.libsignal.SessionBuilder;
17import org.whispersystems.libsignal.UntrustedIdentityException;
18import org.whispersystems.libsignal.ecc.ECPublicKey;
19import org.whispersystems.libsignal.state.PreKeyBundle;
20import org.whispersystems.libsignal.state.PreKeyRecord;
21import org.whispersystems.libsignal.state.SignedPreKeyRecord;
22import org.whispersystems.libsignal.util.KeyHelper;
23
24import java.security.PrivateKey;
25import java.security.Security;
26import java.security.Signature;
27import java.security.cert.X509Certificate;
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.Collection;
31import java.util.Collections;
32import java.util.HashMap;
33import java.util.HashSet;
34import java.util.Iterator;
35import java.util.List;
36import java.util.Map;
37import java.util.Random;
38import java.util.Set;
39import java.util.concurrent.atomic.AtomicBoolean;
40
41import eu.siacs.conversations.Config;
42import eu.siacs.conversations.entities.Account;
43import eu.siacs.conversations.entities.Contact;
44import eu.siacs.conversations.entities.Conversation;
45import eu.siacs.conversations.entities.Message;
46import eu.siacs.conversations.parser.IqParser;
47import eu.siacs.conversations.services.XmppConnectionService;
48import eu.siacs.conversations.utils.CryptoHelper;
49import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
50import eu.siacs.conversations.xml.Element;
51import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
52import eu.siacs.conversations.xmpp.OnIqPacketReceived;
53import eu.siacs.conversations.xmpp.pep.PublishOptions;
54import eu.siacs.conversations.xmpp.stanzas.IqPacket;
55import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
56import rocks.xmpp.addr.Jid;
57
58public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
59
60 public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
61 public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
62 public static final String PEP_DEVICE_LIST_NOTIFY = PEP_DEVICE_LIST + "+notify";
63 public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
64 public static final String PEP_VERIFICATION = PEP_PREFIX + ".verification";
65 public static final String PEP_OMEMO_WHITELISTED = PEP_PREFIX + ".whitelisted";
66
67 public static final String LOGPREFIX = "AxolotlService";
68
69 private static final int NUM_KEYS_TO_PUBLISH = 100;
70 private static final int publishTriesThreshold = 3;
71
72 private final Account account;
73 private final XmppConnectionService mXmppConnectionService;
74 private final SQLiteAxolotlStore axolotlStore;
75 private final SessionMap sessions;
76 private final Map<Jid, Set<Integer>> deviceIds;
77 private final Map<String, XmppAxolotlMessage> messageCache;
78 private final FetchStatusMap fetchStatusMap;
79 private final Map<Jid, Boolean> fetchDeviceListStatus = new HashMap<>();
80 private final HashMap<Jid, List<OnDeviceIdsFetched>> fetchDeviceIdsMap = new HashMap<>();
81 private final SerialSingleThreadExecutor executor;
82 private int numPublishTriesOnEmptyPep = 0;
83 private boolean pepBroken = false;
84 private final Set<SignalProtocolAddress> healingAttempts = new HashSet<>();
85 private int lastDeviceListNotificationHash = 0;
86 private final HashSet<Integer> cleanedOwnDeviceIds = new HashSet<>();
87 private Set<XmppAxolotlSession> postponedSessions = new HashSet<>(); //sessions stored here will receive after mam catchup treatment
88 private Set<SignalProtocolAddress> postponedHealing = new HashSet<>(); //addresses stored here will need a healing notification after mam catchup
89
90 private AtomicBoolean changeAccessMode = new AtomicBoolean(false);
91
92 @Override
93 public void onAdvancedStreamFeaturesAvailable(Account account) {
94 if (Config.supportOmemo()
95 && account.getXmppConnection() != null
96 && account.getXmppConnection().getFeatures().pep()) {
97 publishBundlesIfNeeded(true, false);
98 } else {
99 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping OMEMO initialization");
100 }
101 }
102
103 private boolean hasErrorFetchingDeviceList(Jid jid) {
104 Boolean status = fetchDeviceListStatus.get(jid);
105 return status != null && !status;
106 }
107
108 public boolean hasErrorFetchingDeviceList(List<Jid> jids) {
109 for(Jid jid : jids) {
110 if (hasErrorFetchingDeviceList(jid)) {
111 return true;
112 }
113 }
114 return false;
115 }
116
117 public boolean fetchMapHasErrors(List<Jid> jids) {
118 for (Jid jid : jids) {
119 if (deviceIds.get(jid) != null) {
120 for (Integer foreignId : this.deviceIds.get(jid)) {
121 SignalProtocolAddress address = new SignalProtocolAddress(jid.toString(), foreignId);
122 if (fetchStatusMap.getAll(address.getName()).containsValue(FetchStatus.ERROR)) {
123 return true;
124 }
125 }
126 }
127 }
128 return false;
129 }
130
131 public void preVerifyFingerprint(Contact contact, String fingerprint) {
132 axolotlStore.preVerifyFingerprint(contact.getAccount(), contact.getJid().asBareJid().toString(), fingerprint);
133 }
134
135 public void preVerifyFingerprint(Account account, String fingerprint) {
136 axolotlStore.preVerifyFingerprint(account, account.getJid().asBareJid().toString(), fingerprint);
137 }
138
139 public boolean hasVerifiedKeys(String name) {
140 for (XmppAxolotlSession session : this.sessions.getAll(name).values()) {
141 if (session.getTrust().isVerified()) {
142 return true;
143 }
144 }
145 return false;
146 }
147
148 private static class AxolotlAddressMap<T> {
149 protected Map<String, Map<Integer, T>> map;
150 protected final Object MAP_LOCK = new Object();
151
152 public AxolotlAddressMap() {
153 this.map = new HashMap<>();
154 }
155
156 public void put(SignalProtocolAddress address, T value) {
157 synchronized (MAP_LOCK) {
158 Map<Integer, T> devices = map.get(address.getName());
159 if (devices == null) {
160 devices = new HashMap<>();
161 map.put(address.getName(), devices);
162 }
163 devices.put(address.getDeviceId(), value);
164 }
165 }
166
167 public T get(SignalProtocolAddress address) {
168 synchronized (MAP_LOCK) {
169 Map<Integer, T> devices = map.get(address.getName());
170 if (devices == null) {
171 return null;
172 }
173 return devices.get(address.getDeviceId());
174 }
175 }
176
177 public Map<Integer, T> getAll(String name) {
178 synchronized (MAP_LOCK) {
179 Map<Integer, T> devices = map.get(name);
180 if (devices == null) {
181 return new HashMap<>();
182 }
183 return devices;
184 }
185 }
186
187 public boolean hasAny(SignalProtocolAddress address) {
188 synchronized (MAP_LOCK) {
189 Map<Integer, T> devices = map.get(address.getName());
190 return devices != null && !devices.isEmpty();
191 }
192 }
193
194 public void clear() {
195 map.clear();
196 }
197
198 }
199
200 private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
201 private final XmppConnectionService xmppConnectionService;
202 private final Account account;
203
204 public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
205 super();
206 this.xmppConnectionService = service;
207 this.account = account;
208 this.fillMap(store);
209 }
210
211 public Set<Jid> findCounterpartsForSourceId(Integer sid) {
212 Set<Jid> candidates = new HashSet<>();
213 synchronized (MAP_LOCK) {
214 for(Map.Entry<String,Map<Integer,XmppAxolotlSession>> entry : map.entrySet()) {
215 String key = entry.getKey();
216 if (entry.getValue().containsKey(sid)) {
217 candidates.add(Jid.of(key));
218 }
219 }
220 }
221 return candidates;
222 }
223
224 private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
225 for (Integer deviceId : deviceIds) {
226 SignalProtocolAddress axolotlAddress = new SignalProtocolAddress(bareJid, deviceId);
227 IdentityKey identityKey = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey();
228 if (Config.X509_VERIFICATION) {
229 X509Certificate certificate = store.getFingerprintCertificate(CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()));
230 if (certificate != null) {
231 Bundle information = CryptoHelper.extractCertificateInformation(certificate);
232 try {
233 final String cn = information.getString("subject_cn");
234 final Jid jid = Jid.of(bareJid);
235 Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn);
236 account.getRoster().getContact(jid).setCommonName(cn);
237 } catch (final IllegalArgumentException ignored) {
238 //ignored
239 }
240 }
241 }
242 this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, identityKey));
243 }
244 }
245
246 private void fillMap(SQLiteAxolotlStore store) {
247 List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().asBareJid().toString());
248 putDevicesForJid(account.getJid().asBareJid().toString(), deviceIds, store);
249 for (String address : store.getKnownAddresses()) {
250 deviceIds = store.getSubDeviceSessions(address);
251 putDevicesForJid(address, deviceIds, store);
252 }
253 }
254
255 @Override
256 public void put(SignalProtocolAddress address, XmppAxolotlSession value) {
257 super.put(address, value);
258 value.setNotFresh();
259 }
260
261 public void put(XmppAxolotlSession session) {
262 this.put(session.getRemoteAddress(), session);
263 }
264 }
265
266 public enum FetchStatus {
267 PENDING,
268 SUCCESS,
269 SUCCESS_VERIFIED,
270 TIMEOUT,
271 SUCCESS_TRUSTED,
272 ERROR
273 }
274
275 private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
276
277 public void clearErrorFor(Jid jid) {
278 synchronized (MAP_LOCK) {
279 Map<Integer, FetchStatus> devices = this.map.get(jid.asBareJid().toString());
280 if (devices == null) {
281 return;
282 }
283 for (Map.Entry<Integer, FetchStatus> entry : devices.entrySet()) {
284 if (entry.getValue() == FetchStatus.ERROR) {
285 Log.d(Config.LOGTAG, "resetting error for " + jid.asBareJid() + "(" + entry.getKey() + ")");
286 entry.setValue(FetchStatus.TIMEOUT);
287 }
288 }
289 }
290 }
291 }
292
293 public static String getLogprefix(Account account) {
294 return LOGPREFIX + " (" + account.getJid().asBareJid().toString() + "): ";
295 }
296
297 public AxolotlService(Account account, XmppConnectionService connectionService) {
298 if (account == null || connectionService == null) {
299 throw new IllegalArgumentException("account and service cannot be null");
300 }
301 if (Security.getProvider("BC") == null) {
302 Security.addProvider(new BouncyCastleProvider());
303 }
304 this.mXmppConnectionService = connectionService;
305 this.account = account;
306 this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
307 this.deviceIds = new HashMap<>();
308 this.messageCache = new HashMap<>();
309 this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
310 this.fetchStatusMap = new FetchStatusMap();
311 this.executor = new SerialSingleThreadExecutor("Axolotl");
312 }
313
314 public String getOwnFingerprint() {
315 return CryptoHelper.bytesToHex(axolotlStore.getIdentityKeyPair().getPublicKey().serialize());
316 }
317
318 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status) {
319 return axolotlStore.getContactKeysWithTrust(account.getJid().asBareJid().toString(), status);
320 }
321
322 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, Jid jid) {
323 return axolotlStore.getContactKeysWithTrust(jid.asBareJid().toString(), status);
324 }
325
326 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) {
327 Set<IdentityKey> keys = new HashSet<>();
328 for (Jid jid : jids) {
329 keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toString(), status));
330 }
331 return keys;
332 }
333
334 public Set<Jid> findCounterpartsBySourceId(int sid) {
335 return sessions.findCounterpartsForSourceId(sid);
336 }
337
338 public long getNumTrustedKeys(Jid jid) {
339 return axolotlStore.getContactNumTrustedKeys(jid.asBareJid().toString());
340 }
341
342 public boolean anyTargetHasNoTrustedKeys(List<Jid> jids) {
343 for (Jid jid : jids) {
344 if (axolotlStore.getContactNumTrustedKeys(jid.asBareJid().toString()) == 0) {
345 return true;
346 }
347 }
348 return false;
349 }
350
351 private SignalProtocolAddress getAddressForJid(Jid jid) {
352 return new SignalProtocolAddress(jid.toString(), 0);
353 }
354
355 public Collection<XmppAxolotlSession> findOwnSessions() {
356 SignalProtocolAddress ownAddress = getAddressForJid(account.getJid().asBareJid());
357 ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(ownAddress.getName()).values());
358 Collections.sort(s);
359 return s;
360 }
361
362
363 public Collection<XmppAxolotlSession> findSessionsForContact(Contact contact) {
364 SignalProtocolAddress contactAddress = getAddressForJid(contact.getJid());
365 ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(contactAddress.getName()).values());
366 Collections.sort(s);
367 return s;
368 }
369
370 private Set<XmppAxolotlSession> findSessionsForConversation(Conversation conversation) {
371 if (conversation.getContact().isSelf()) {
372 //will be added in findOwnSessions()
373 return Collections.emptySet();
374 }
375 HashSet<XmppAxolotlSession> sessions = new HashSet<>();
376 for (Jid jid : conversation.getAcceptedCryptoTargets()) {
377 sessions.addAll(this.sessions.getAll(getAddressForJid(jid).getName()).values());
378 }
379 return sessions;
380 }
381
382 private boolean hasAny(Jid jid) {
383 return sessions.hasAny(getAddressForJid(jid));
384 }
385
386 public boolean isPepBroken() {
387 return this.pepBroken;
388 }
389
390 public void resetBrokenness() {
391 this.pepBroken = false;
392 this.numPublishTriesOnEmptyPep = 0;
393 this.lastDeviceListNotificationHash = 0;
394 this.healingAttempts.clear();
395 }
396
397 public void clearErrorsInFetchStatusMap(Jid jid) {
398 fetchStatusMap.clearErrorFor(jid);
399 fetchDeviceListStatus.remove(jid);
400 }
401
402 public void regenerateKeys(boolean wipeOther) {
403 axolotlStore.regenerate();
404 sessions.clear();
405 fetchStatusMap.clear();
406 fetchDeviceIdsMap.clear();
407 fetchDeviceListStatus.clear();
408 publishBundlesIfNeeded(true, wipeOther);
409 }
410
411 public void destroy() {
412 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": destroying old axolotl service. no longer in use");
413 mXmppConnectionService.databaseBackend.wipeAxolotlDb(account);
414 }
415
416 public AxolotlService makeNew() {
417 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": make new axolotl service");
418 return new AxolotlService(this.account, this.mXmppConnectionService);
419 }
420
421 public int getOwnDeviceId() {
422 return axolotlStore.getLocalRegistrationId();
423 }
424
425 public SignalProtocolAddress getOwnAxolotlAddress() {
426 return new SignalProtocolAddress(account.getJid().asBareJid().toString(), getOwnDeviceId());
427 }
428
429 public Set<Integer> getOwnDeviceIds() {
430 return this.deviceIds.get(account.getJid().asBareJid());
431 }
432
433 public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
434 final int hash = deviceIds.hashCode();
435 final boolean me = jid.asBareJid().equals(account.getJid().asBareJid());
436 if (me) {
437 if (hash != 0 && hash == this.lastDeviceListNotificationHash) {
438 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring duplicate own device id list");
439 return;
440 }
441 this.lastDeviceListNotificationHash = hash;
442 }
443 boolean needsPublishing = me && !deviceIds.contains(getOwnDeviceId());
444 if (me) {
445 deviceIds.remove(getOwnDeviceId());
446 }
447 Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.asBareJid().toString()));
448 expiredDevices.removeAll(deviceIds);
449 for (Integer deviceId : expiredDevices) {
450 SignalProtocolAddress address = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
451 XmppAxolotlSession session = sessions.get(address);
452 if (session != null && session.getFingerprint() != null) {
453 if (session.getTrust().isActive()) {
454 session.setTrust(session.getTrust().toInactive());
455 }
456 }
457 }
458 Set<Integer> newDevices = new HashSet<>(deviceIds);
459 for (Integer deviceId : newDevices) {
460 SignalProtocolAddress address = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
461 XmppAxolotlSession session = sessions.get(address);
462 if (session != null && session.getFingerprint() != null) {
463 if (!session.getTrust().isActive()) {
464 Log.d(Config.LOGTAG, "reactivating device with fingerprint " + session.getFingerprint());
465 session.setTrust(session.getTrust().toActive());
466 }
467 }
468 }
469 if (me) {
470 if (Config.OMEMO_AUTO_EXPIRY != 0) {
471 needsPublishing |= deviceIds.removeAll(getExpiredDevices());
472 }
473 needsPublishing |= this.changeAccessMode.get();
474 for (Integer deviceId : deviceIds) {
475 SignalProtocolAddress ownDeviceAddress = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
476 if (sessions.get(ownDeviceAddress) == null) {
477 FetchStatus status = fetchStatusMap.get(ownDeviceAddress);
478 if (status == null || status == FetchStatus.TIMEOUT) {
479 fetchStatusMap.put(ownDeviceAddress, FetchStatus.PENDING);
480 this.buildSessionFromPEP(ownDeviceAddress);
481 }
482 }
483 }
484 if (needsPublishing) {
485 publishOwnDeviceId(deviceIds);
486 }
487 }
488 final Set<Integer> oldSet = this.deviceIds.get(jid);
489 final boolean changed = oldSet == null || oldSet.hashCode() != hash;
490 this.deviceIds.put(jid, deviceIds);
491 if (changed) {
492 mXmppConnectionService.updateConversationUi(); //update the lock icon
493 mXmppConnectionService.keyStatusUpdated(null);
494 if (me) {
495 mXmppConnectionService.updateAccountUi();
496 }
497 } else {
498 Log.d(Config.LOGTAG,"skipped device list update because it hasn't changed");
499 }
500 }
501
502 public void wipeOtherPepDevices() {
503 if (pepBroken) {
504 Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
505 return;
506 }
507 Set<Integer> deviceIds = new HashSet<>();
508 deviceIds.add(getOwnDeviceId());
509 publishDeviceIdsAndRefineAccessModel(deviceIds);
510 }
511
512 public void distrustFingerprint(final String fingerprint) {
513 final String fp = fingerprint.replaceAll("\\s", "");
514 final FingerprintStatus fingerprintStatus = axolotlStore.getFingerprintStatus(fp);
515 axolotlStore.setFingerprintStatus(fp, fingerprintStatus.toUntrusted());
516 }
517
518 private void publishOwnDeviceIdIfNeeded() {
519 if (pepBroken) {
520 Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
521 return;
522 }
523 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().asBareJid());
524 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
525 @Override
526 public void onIqPacketReceived(Account account, IqPacket packet) {
527 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
528 Log.d(Config.LOGTAG, getLogprefix(account) + "Timeout received while retrieving own Device Ids.");
529 } else {
530 //TODO consider calling registerDevices only after item-not-found to account for broken PEPs
531 Element item = mXmppConnectionService.getIqParser().getItem(packet);
532 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
533 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved own device list: " + deviceIds);
534 registerDevices(account.getJid().asBareJid(), deviceIds);
535 }
536 }
537 });
538 }
539
540 private Set<Integer> getExpiredDevices() {
541 Set<Integer> devices = new HashSet<>();
542 for (XmppAxolotlSession session : findOwnSessions()) {
543 if (session.getTrust().isActive()) {
544 long diff = System.currentTimeMillis() - session.getTrust().getLastActivation();
545 if (diff > Config.OMEMO_AUTO_EXPIRY) {
546 long lastMessageDiff = System.currentTimeMillis() - mXmppConnectionService.databaseBackend.getLastTimeFingerprintUsed(account, session.getFingerprint());
547 long hours = Math.round(lastMessageDiff / (1000 * 60.0 * 60.0));
548 if (lastMessageDiff > Config.OMEMO_AUTO_EXPIRY) {
549 devices.add(session.getRemoteAddress().getDeviceId());
550 session.setTrust(session.getTrust().toInactive());
551 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": added own device " + session.getFingerprint() + " to list of expired devices. Last message received " + hours + " hours ago");
552 } else {
553 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": own device " + session.getFingerprint() + " was active " + hours + " hours ago");
554 }
555 } //TODO print last activation diff
556 }
557 }
558 return devices;
559 }
560
561 private void publishOwnDeviceId(Set<Integer> deviceIds) {
562 Set<Integer> deviceIdsCopy = new HashSet<>(deviceIds);
563 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "publishing own device ids");
564 if (deviceIdsCopy.isEmpty()) {
565 if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
566 Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
567 pepBroken = true;
568 return;
569 } else {
570 numPublishTriesOnEmptyPep++;
571 Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
572 }
573 } else {
574 numPublishTriesOnEmptyPep = 0;
575 }
576 deviceIdsCopy.add(getOwnDeviceId());
577 publishDeviceIdsAndRefineAccessModel(deviceIdsCopy);
578 }
579
580 private void publishDeviceIdsAndRefineAccessModel(Set<Integer> ids) {
581 publishDeviceIdsAndRefineAccessModel(ids, true);
582 }
583
584 private void publishDeviceIdsAndRefineAccessModel(final Set<Integer> ids, final boolean firstAttempt) {
585 final Bundle publishOptions = account.getXmppConnection().getFeatures().pepPublishOptions() ? PublishOptions.openAccess() : null;
586 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(ids, publishOptions);
587 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
588 @Override
589 public void onIqPacketReceived(Account account, IqPacket packet) {
590 final Element error = packet.getType() == IqPacket.TYPE.ERROR ? packet.findChild("error") : null;
591 final boolean preConditionNotMet = PublishOptions.preconditionNotMet(packet);
592 if (firstAttempt && preConditionNotMet) {
593 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": precondition wasn't met for device list. pushing node configuration");
594 mXmppConnectionService.pushNodeConfiguration(account, AxolotlService.PEP_DEVICE_LIST, publishOptions, new XmppConnectionService.OnConfigurationPushed() {
595 @Override
596 public void onPushSucceeded() {
597 publishDeviceIdsAndRefineAccessModel(ids, false);
598 }
599
600 @Override
601 public void onPushFailed() {
602 publishDeviceIdsAndRefineAccessModel(ids, false);
603 }
604 });
605 } else {
606 if (AxolotlService.this.changeAccessMode.compareAndSet(true, false)) {
607 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done changing access mode");
608 account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, false);
609 mXmppConnectionService.databaseBackend.updateAccount(account);
610 }
611 if (packet.getType() == IqPacket.TYPE.ERROR) {
612 if (preConditionNotMet) {
613 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": device list pre condition still not met on second attempt");
614 } else if (error != null) {
615 pepBroken = true;
616 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
617 }
618
619 }
620 }
621 }
622 });
623 }
624
625 public void publishDeviceVerificationAndBundle(final SignedPreKeyRecord signedPreKeyRecord,
626 final Set<PreKeyRecord> preKeyRecords,
627 final boolean announceAfter,
628 final boolean wipe) {
629 try {
630 IdentityKey axolotlPublicKey = axolotlStore.getIdentityKeyPair().getPublicKey();
631 PrivateKey x509PrivateKey = KeyChain.getPrivateKey(mXmppConnectionService, account.getPrivateKeyAlias());
632 X509Certificate[] chain = KeyChain.getCertificateChain(mXmppConnectionService, account.getPrivateKeyAlias());
633 Signature verifier = Signature.getInstance("sha256WithRSA");
634 verifier.initSign(x509PrivateKey, mXmppConnectionService.getRNG());
635 verifier.update(axolotlPublicKey.serialize());
636 byte[] signature = verifier.sign();
637 IqPacket packet = mXmppConnectionService.getIqGenerator().publishVerification(signature, chain, getOwnDeviceId());
638 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": publish verification for device " + getOwnDeviceId());
639 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
640 @Override
641 public void onIqPacketReceived(final Account account, IqPacket packet) {
642 String node = AxolotlService.PEP_VERIFICATION + ":" + getOwnDeviceId();
643 mXmppConnectionService.pushNodeConfiguration(account, node, PublishOptions.openAccess(), new XmppConnectionService.OnConfigurationPushed() {
644 @Override
645 public void onPushSucceeded() {
646 Log.d(Config.LOGTAG, getLogprefix(account) + "configured verification node to be world readable");
647 publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
648 }
649
650 @Override
651 public void onPushFailed() {
652 Log.d(Config.LOGTAG, getLogprefix(account) + "unable to set access model on verification node");
653 publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
654 }
655 });
656 }
657 });
658 } catch (Exception e) {
659 e.printStackTrace();
660 }
661 }
662
663 public void publishBundlesIfNeeded(final boolean announce, final boolean wipe) {
664 if (pepBroken) {
665 Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
666 return;
667 }
668
669 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
670 this.changeAccessMode.set(account.isOptionSet(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE));
671 } else {
672 if (account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true)) {
673 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server doesn’t support publish-options. setting for later access mode change");
674 mXmppConnectionService.databaseBackend.updateAccount(account);
675 }
676 }
677 if (this.changeAccessMode.get()) {
678 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server gained publish-options capabilities. changing access model");
679 }
680 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().asBareJid(), getOwnDeviceId());
681 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
682 @Override
683 public void onIqPacketReceived(Account account, IqPacket packet) {
684
685 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
686 return; //ignore timeout. do nothing
687 }
688
689 if (packet.getType() == IqPacket.TYPE.ERROR) {
690 Element error = packet.findChild("error");
691 if (error == null || !error.hasChild("item-not-found")) {
692 pepBroken = true;
693 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
694 return;
695 }
696 }
697
698 PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
699 Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
700 boolean flush = false;
701 if (bundle == null) {
702 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
703 bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
704 flush = true;
705 }
706 if (keys == null) {
707 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
708 }
709 try {
710 boolean changed = false;
711 // Validate IdentityKey
712 IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
713 if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
714 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
715 changed = true;
716 }
717
718 // Validate signedPreKeyRecord + ID
719 SignedPreKeyRecord signedPreKeyRecord;
720 int numSignedPreKeys = axolotlStore.getSignedPreKeysCount();
721 try {
722 signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
723 if (flush
724 || !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
725 || !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
726 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
727 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
728 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
729 changed = true;
730 }
731 } catch (InvalidKeyIdException e) {
732 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
733 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
734 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
735 changed = true;
736 }
737
738 // Validate PreKeys
739 Set<PreKeyRecord> preKeyRecords = new HashSet<>();
740 if (keys != null) {
741 for (Integer id : keys.keySet()) {
742 try {
743 PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
744 if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
745 preKeyRecords.add(preKeyRecord);
746 }
747 } catch (InvalidKeyIdException ignored) {
748 }
749 }
750 }
751 int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
752 if (newKeys > 0) {
753 List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
754 axolotlStore.getCurrentPreKeyId() + 1, newKeys);
755 preKeyRecords.addAll(newRecords);
756 for (PreKeyRecord record : newRecords) {
757 axolotlStore.storePreKey(record.getId(), record);
758 }
759 changed = true;
760 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
761 }
762
763
764 if (changed || changeAccessMode.get()) {
765 if (account.getPrivateKeyAlias() != null && Config.X509_VERIFICATION) {
766 mXmppConnectionService.publishDisplayName(account);
767 publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
768 } else {
769 publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
770 }
771 } else {
772 Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
773 if (wipe) {
774 wipeOtherPepDevices();
775 } else if (announce) {
776 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
777 publishOwnDeviceIdIfNeeded();
778 }
779 }
780 } catch (InvalidKeyException e) {
781 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
782 }
783 }
784 });
785 }
786
787 private void publishDeviceBundle(SignedPreKeyRecord signedPreKeyRecord,
788 Set<PreKeyRecord> preKeyRecords,
789 final boolean announceAfter,
790 final boolean wipe) {
791 publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe, true);
792 }
793
794 private void publishDeviceBundle(final SignedPreKeyRecord signedPreKeyRecord,
795 final Set<PreKeyRecord> preKeyRecords,
796 final boolean announceAfter,
797 final boolean wipe,
798 final boolean firstAttempt) {
799 final Bundle publishOptions = account.getXmppConnection().getFeatures().pepPublishOptions() ? PublishOptions.openAccess() : null;
800 IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
801 signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
802 preKeyRecords, getOwnDeviceId(), publishOptions);
803 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing...");
804 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
805 @Override
806 public void onIqPacketReceived(final Account account, IqPacket packet) {
807 final boolean preconditionNotMet = PublishOptions.preconditionNotMet(packet);
808 if (firstAttempt && preconditionNotMet) {
809 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": precondition wasn't met for bundle. pushing node configuration");
810 final String node = AxolotlService.PEP_BUNDLES + ":" + getOwnDeviceId();
811 mXmppConnectionService.pushNodeConfiguration(account, node, publishOptions, new XmppConnectionService.OnConfigurationPushed() {
812 @Override
813 public void onPushSucceeded() {
814 publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe, false);
815 }
816
817 @Override
818 public void onPushFailed() {
819 publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe, false);
820 }
821 });
822 } else if (packet.getType() == IqPacket.TYPE.RESULT) {
823 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
824 if (wipe) {
825 wipeOtherPepDevices();
826 } else if (announceAfter) {
827 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
828 publishOwnDeviceIdIfNeeded();
829 }
830 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
831 if (preconditionNotMet) {
832 Log.d(Config.LOGTAG,getLogprefix(account) + "bundle precondition still not met after second attempt");
833 } else {
834 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.toString());
835 }
836 pepBroken = true;
837 }
838 }
839 });
840 }
841
842 public void deleteOmemoIdentity() {
843 final String node = AxolotlService.PEP_BUNDLES + ":" + getOwnDeviceId();
844 final IqPacket deleteBundleNode = mXmppConnectionService.getIqGenerator().deleteNode(node);
845 mXmppConnectionService.sendIqPacket(account, deleteBundleNode, null);
846 publishDeviceIdsAndRefineAccessModel(getOwnDeviceIds());
847 }
848
849 public List<Jid> getCryptoTargets(Conversation conversation) {
850 final List<Jid> jids;
851 if (conversation.getMode() == Conversation.MODE_SINGLE) {
852 jids = new ArrayList<>();
853 jids.add(conversation.getJid().asBareJid());
854 } else {
855 jids = conversation.getMucOptions().getMembers(false);
856 }
857 return jids;
858 }
859
860 public FingerprintStatus getFingerprintTrust(String fingerprint) {
861 return axolotlStore.getFingerprintStatus(fingerprint);
862 }
863
864 public X509Certificate getFingerprintCertificate(String fingerprint) {
865 return axolotlStore.getFingerprintCertificate(fingerprint);
866 }
867
868 public void setFingerprintTrust(String fingerprint, FingerprintStatus status) {
869 axolotlStore.setFingerprintStatus(fingerprint, status);
870 }
871
872 private void verifySessionWithPEP(final XmppAxolotlSession session) {
873 Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
874 final SignalProtocolAddress address = session.getRemoteAddress();
875 final IdentityKey identityKey = session.getIdentityKey();
876 try {
877 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.of(address.getName()), address.getDeviceId());
878 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
879 @Override
880 public void onIqPacketReceived(Account account, IqPacket packet) {
881 Pair<X509Certificate[], byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
882 if (verification != null) {
883 try {
884 Signature verifier = Signature.getInstance("sha256WithRSA");
885 verifier.initVerify(verification.first[0]);
886 verifier.update(identityKey.serialize());
887 if (verifier.verify(verification.second)) {
888 try {
889 mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
890 String fingerprint = session.getFingerprint();
891 Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: " + fingerprint);
892 setFingerprintTrust(fingerprint, FingerprintStatus.createActiveVerified(true));
893 axolotlStore.setFingerprintCertificate(fingerprint, verification.first[0]);
894 fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
895 Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
896 try {
897 final String cn = information.getString("subject_cn");
898 final Jid jid = Jid.of(address.getName());
899 Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn);
900 account.getRoster().getContact(jid).setCommonName(cn);
901 } catch (final IllegalArgumentException ignored) {
902 //ignored
903 }
904 finishBuildingSessionsFromPEP(address);
905 return;
906 } catch (Exception e) {
907 Log.d(Config.LOGTAG, "could not verify certificate");
908 }
909 }
910 } catch (Exception e) {
911 Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
912 }
913 } else {
914 Log.d(Config.LOGTAG, "no verification found");
915 }
916 fetchStatusMap.put(address, FetchStatus.SUCCESS);
917 finishBuildingSessionsFromPEP(address);
918 }
919 });
920 } catch (IllegalArgumentException e) {
921 fetchStatusMap.put(address, FetchStatus.SUCCESS);
922 finishBuildingSessionsFromPEP(address);
923 }
924 }
925
926 private final Set<Integer> PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT = new HashSet<>();
927
928 private void finishBuildingSessionsFromPEP(final SignalProtocolAddress address) {
929 SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), 0);
930 Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress.getName());
931 Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address.getName());
932 if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
933 FetchStatus report = null;
934 if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
935 report = FetchStatus.SUCCESS;
936 } else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
937 report = FetchStatus.SUCCESS_VERIFIED;
938 } else if (own.containsValue(FetchStatus.SUCCESS_TRUSTED) || remote.containsValue(FetchStatus.SUCCESS_TRUSTED)) {
939 report = FetchStatus.SUCCESS_TRUSTED;
940 } else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
941 report = FetchStatus.ERROR;
942 }
943 mXmppConnectionService.keyStatusUpdated(report);
944 }
945 if (Config.REMOVE_BROKEN_DEVICES) {
946 Set<Integer> ownDeviceIds = new HashSet<>(getOwnDeviceIds());
947 boolean publish = false;
948 for (Map.Entry<Integer, FetchStatus> entry : own.entrySet()) {
949 int id = entry.getKey();
950 if (entry.getValue() == FetchStatus.ERROR && PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT.add(id) && ownDeviceIds.remove(id)) {
951 publish = true;
952 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error fetching own device with id " + id + ". removing from announcement");
953 }
954 }
955 if (publish) {
956 publishOwnDeviceId(ownDeviceIds);
957 }
958 }
959 }
960
961 public boolean hasEmptyDeviceList(Jid jid) {
962 return !hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty());
963 }
964
965 public interface OnDeviceIdsFetched {
966 void fetched(Jid jid, Set<Integer> deviceIds);
967 }
968
969 public interface OnMultipleDeviceIdFetched {
970 void fetched();
971 }
972
973 public void fetchDeviceIds(final Jid jid) {
974 fetchDeviceIds(jid, null);
975 }
976
977 private void fetchDeviceIds(final Jid jid, OnDeviceIdsFetched callback) {
978 IqPacket packet;
979 synchronized (this.fetchDeviceIdsMap) {
980 List<OnDeviceIdsFetched> callbacks = this.fetchDeviceIdsMap.get(jid);
981 if (callbacks != null) {
982 if (callback != null) {
983 callbacks.add(callback);
984 }
985 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching device ids for " + jid + " already running. adding callback");
986 packet = null;
987 } else {
988 callbacks = new ArrayList<>();
989 if (callback != null) {
990 callbacks.add(callback);
991 }
992 this.fetchDeviceIdsMap.put(jid, callbacks);
993 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching device ids for " + jid);
994 packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(jid);
995 }
996 }
997 if (packet != null) {
998 mXmppConnectionService.sendIqPacket(account, packet, (account, response) -> {
999 if (response.getType() == IqPacket.TYPE.RESULT) {
1000 fetchDeviceListStatus.put(jid, true);
1001 Element item = mXmppConnectionService.getIqParser().getItem(response);
1002 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
1003 registerDevices(jid, deviceIds);
1004 final List<OnDeviceIdsFetched> callbacks;
1005 synchronized (fetchDeviceIdsMap) {
1006 callbacks = fetchDeviceIdsMap.remove(jid);
1007 }
1008 if (callbacks != null) {
1009 for (OnDeviceIdsFetched c : callbacks) {
1010 c.fetched(jid, deviceIds);
1011 }
1012 }
1013 } else {
1014 if (response.getType() == IqPacket.TYPE.TIMEOUT) {
1015 fetchDeviceListStatus.remove(jid);
1016 } else {
1017 fetchDeviceListStatus.put(jid, false);
1018 }
1019 final List<OnDeviceIdsFetched> callbacks;
1020 synchronized (fetchDeviceIdsMap) {
1021 callbacks = fetchDeviceIdsMap.remove(jid);
1022 }
1023 if (callbacks != null) {
1024 for (OnDeviceIdsFetched c : callbacks) {
1025 c.fetched(jid, null);
1026 }
1027 }
1028 }
1029 });
1030 }
1031 }
1032
1033 private void fetchDeviceIds(List<Jid> jids, final OnMultipleDeviceIdFetched callback) {
1034 final ArrayList<Jid> unfinishedJids = new ArrayList<>(jids);
1035 synchronized (unfinishedJids) {
1036 for (Jid jid : unfinishedJids) {
1037 fetchDeviceIds(jid, (j, deviceIds) -> {
1038 synchronized (unfinishedJids) {
1039 unfinishedJids.remove(j);
1040 if (unfinishedJids.size() == 0 && callback != null) {
1041 callback.fetched();
1042 }
1043 }
1044 });
1045 }
1046 }
1047 }
1048
1049 interface OnSessionBuildFromPep {
1050 void onSessionBuildSuccessful();
1051 void onSessionBuildFailed();
1052 }
1053
1054 private void buildSessionFromPEP(final SignalProtocolAddress address) {
1055 buildSessionFromPEP(address, null);
1056 }
1057
1058 private void buildSessionFromPEP(final SignalProtocolAddress address, OnSessionBuildFromPep callback) {
1059 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new session for " + address.toString());
1060 if (address.equals(getOwnAxolotlAddress())) {
1061 throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
1062 }
1063
1064 final Jid jid = Jid.of(address.getName());
1065 final boolean oneOfOurs = jid.asBareJid().equals(account.getJid().asBareJid());
1066 IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(jid, address.getDeviceId());
1067 mXmppConnectionService.sendIqPacket(account, bundlesPacket, (account, packet) -> {
1068 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1069 fetchStatusMap.put(address, FetchStatus.TIMEOUT);
1070 } else if (packet.getType() == IqPacket.TYPE.RESULT) {
1071 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
1072 final IqParser parser = mXmppConnectionService.getIqParser();
1073 final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
1074 final PreKeyBundle bundle = parser.bundle(packet);
1075 if (preKeyBundleList.isEmpty() || bundle == null) {
1076 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
1077 fetchStatusMap.put(address, FetchStatus.ERROR);
1078 finishBuildingSessionsFromPEP(address);
1079 if (callback != null) {
1080 callback.onSessionBuildFailed();
1081 }
1082 return;
1083 }
1084 Random random = new Random();
1085 final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
1086 if (preKey == null) {
1087 //should never happen
1088 fetchStatusMap.put(address, FetchStatus.ERROR);
1089 finishBuildingSessionsFromPEP(address);
1090 if (callback != null) {
1091 callback.onSessionBuildFailed();
1092 }
1093 return;
1094 }
1095
1096 final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
1097 preKey.getPreKeyId(), preKey.getPreKey(),
1098 bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
1099 bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
1100
1101 try {
1102 SessionBuilder builder = new SessionBuilder(axolotlStore, address);
1103 builder.process(preKeyBundle);
1104 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
1105 sessions.put(address, session);
1106 if (Config.X509_VERIFICATION) {
1107 verifySessionWithPEP(session); //TODO; maybe inject callback in here too
1108 } else {
1109 FingerprintStatus status = getFingerprintTrust(CryptoHelper.bytesToHex(bundle.getIdentityKey().getPublicKey().serialize()));
1110 FetchStatus fetchStatus;
1111 if (status != null && status.isVerified()) {
1112 fetchStatus = FetchStatus.SUCCESS_VERIFIED;
1113 } else if (status != null && status.isTrusted()) {
1114 fetchStatus = FetchStatus.SUCCESS_TRUSTED;
1115 } else {
1116 fetchStatus = FetchStatus.SUCCESS;
1117 }
1118 fetchStatusMap.put(address, fetchStatus);
1119 finishBuildingSessionsFromPEP(address);
1120 if (callback != null) {
1121 callback.onSessionBuildSuccessful();
1122 }
1123 }
1124 } catch (UntrustedIdentityException | InvalidKeyException e) {
1125 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
1126 + e.getClass().getName() + ", " + e.getMessage());
1127 fetchStatusMap.put(address, FetchStatus.ERROR);
1128 finishBuildingSessionsFromPEP(address);
1129 if (oneOfOurs && cleanedOwnDeviceIds.add(address.getDeviceId())) {
1130 removeFromDeviceAnnouncement(address.getDeviceId());
1131 }
1132 if (callback != null) {
1133 callback.onSessionBuildFailed();
1134 }
1135 }
1136 } else {
1137 fetchStatusMap.put(address, FetchStatus.ERROR);
1138 Element error = packet.findChild("error");
1139 boolean itemNotFound = error != null && error.hasChild("item-not-found");
1140 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
1141 finishBuildingSessionsFromPEP(address);
1142 if (oneOfOurs && itemNotFound && cleanedOwnDeviceIds.add(address.getDeviceId())) {
1143 removeFromDeviceAnnouncement(address.getDeviceId());
1144 }
1145 if (callback != null) {
1146 callback.onSessionBuildFailed();
1147 }
1148 }
1149 });
1150 }
1151
1152 private void removeFromDeviceAnnouncement(Integer id) {
1153 HashSet<Integer> temp = new HashSet<>(getOwnDeviceIds());
1154 if (temp.remove(id)) {
1155 Log.d(Config.LOGTAG,account.getJid().asBareJid()+" remove own device id "+id+" from announcement. devices left:"+temp);
1156 publishOwnDeviceId(temp);
1157 }
1158 }
1159
1160 public Set<SignalProtocolAddress> findDevicesWithoutSession(final Conversation conversation) {
1161 Set<SignalProtocolAddress> addresses = new HashSet<>();
1162 for (Jid jid : getCryptoTargets(conversation)) {
1163 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
1164 final Set<Integer> ids = deviceIds.get(jid);
1165 if (ids != null && !ids.isEmpty()) {
1166 for (Integer foreignId : ids) {
1167 SignalProtocolAddress address = new SignalProtocolAddress(jid.toString(), foreignId);
1168 if (sessions.get(address) == null) {
1169 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1170 if (identityKey != null) {
1171 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
1172 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
1173 sessions.put(address, session);
1174 } else {
1175 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + jid + ":" + foreignId);
1176 if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
1177 addresses.add(address);
1178 } else {
1179 Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
1180 }
1181 }
1182 }
1183 }
1184 } else {
1185 mXmppConnectionService.keyStatusUpdated(FetchStatus.ERROR);
1186 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
1187 }
1188 }
1189 Set<Integer> ownIds = this.deviceIds.get(account.getJid().asBareJid());
1190 for (Integer ownId : (ownIds != null ? ownIds : new HashSet<Integer>())) {
1191 SignalProtocolAddress address = new SignalProtocolAddress(account.getJid().asBareJid().toString(), ownId);
1192 if (sessions.get(address) == null) {
1193 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1194 if (identityKey != null) {
1195 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
1196 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
1197 sessions.put(address, session);
1198 } else {
1199 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().asBareJid() + ":" + ownId);
1200 if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
1201 addresses.add(address);
1202 } else {
1203 Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
1204 }
1205 }
1206 }
1207 }
1208
1209 return addresses;
1210 }
1211
1212 public boolean createSessionsIfNeeded(final Conversation conversation) {
1213 final List<Jid> jidsWithEmptyDeviceList = getCryptoTargets(conversation);
1214 for (Iterator<Jid> iterator = jidsWithEmptyDeviceList.iterator(); iterator.hasNext(); ) {
1215 final Jid jid = iterator.next();
1216 if (!hasEmptyDeviceList(jid)) {
1217 iterator.remove();
1218 }
1219 }
1220 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": createSessionsIfNeeded() - jids with empty device list: " + jidsWithEmptyDeviceList);
1221 if (jidsWithEmptyDeviceList.size() > 0) {
1222 fetchDeviceIds(jidsWithEmptyDeviceList, () -> createSessionsIfNeededActual(conversation));
1223 return true;
1224 } else {
1225 return createSessionsIfNeededActual(conversation);
1226 }
1227 }
1228
1229 private boolean createSessionsIfNeededActual(final Conversation conversation) {
1230 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
1231 boolean newSessions = false;
1232 Set<SignalProtocolAddress> addresses = findDevicesWithoutSession(conversation);
1233 for (SignalProtocolAddress address : addresses) {
1234 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
1235 FetchStatus status = fetchStatusMap.get(address);
1236 if (status == null || status == FetchStatus.TIMEOUT) {
1237 fetchStatusMap.put(address, FetchStatus.PENDING);
1238 this.buildSessionFromPEP(address);
1239 newSessions = true;
1240 } else if (status == FetchStatus.PENDING) {
1241 newSessions = true;
1242 } else {
1243 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
1244 }
1245 }
1246
1247 return newSessions;
1248 }
1249
1250 public boolean trustedSessionVerified(final Conversation conversation) {
1251 final Set<XmppAxolotlSession> sessions = new HashSet<>();
1252 sessions.addAll(findSessionsForConversation(conversation));
1253 sessions.addAll(findOwnSessions());
1254 boolean verified = false;
1255 for (XmppAxolotlSession session : sessions) {
1256 if (session.getTrust().isTrustedAndActive()) {
1257 if (session.getTrust().getTrust() == FingerprintStatus.Trust.VERIFIED_X509) {
1258 verified = true;
1259 } else {
1260 return false;
1261 }
1262 }
1263 }
1264 return verified;
1265 }
1266
1267 public boolean hasPendingKeyFetches(List<Jid> jids) {
1268 SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), 0);
1269 if (fetchStatusMap.getAll(ownAddress.getName()).containsValue(FetchStatus.PENDING)) {
1270 return true;
1271 }
1272 synchronized (this.fetchDeviceIdsMap) {
1273 for (Jid jid : jids) {
1274 SignalProtocolAddress foreignAddress = new SignalProtocolAddress(jid.asBareJid().toString(), 0);
1275 if (fetchStatusMap.getAll(foreignAddress.getName()).containsValue(FetchStatus.PENDING) || this.fetchDeviceIdsMap.containsKey(jid)) {
1276 return true;
1277 }
1278 }
1279 }
1280 return false;
1281 }
1282
1283 @Nullable
1284 private boolean buildHeader(XmppAxolotlMessage axolotlMessage, Conversation c) {
1285 Set<XmppAxolotlSession> remoteSessions = findSessionsForConversation(c);
1286 final boolean acceptEmpty = (c.getMode() == Conversation.MODE_MULTI && c.getMucOptions().getUserCount() == 0) || c.getContact().isSelf();
1287 Collection<XmppAxolotlSession> ownSessions = findOwnSessions();
1288 if (remoteSessions.isEmpty() && !acceptEmpty) {
1289 return false;
1290 }
1291 for (XmppAxolotlSession session : remoteSessions) {
1292 axolotlMessage.addDevice(session);
1293 }
1294 for (XmppAxolotlSession session : ownSessions) {
1295 axolotlMessage.addDevice(session);
1296 }
1297
1298 return true;
1299 }
1300
1301 //this is being used for private muc messages only
1302 private boolean buildHeader(XmppAxolotlMessage axolotlMessage, Jid jid) {
1303 if (jid == null) {
1304 return false;
1305 }
1306 HashSet<XmppAxolotlSession> sessions = new HashSet<>();
1307 sessions.addAll(this.sessions.getAll(getAddressForJid(jid).getName()).values());
1308 if (sessions.isEmpty()) {
1309 return false;
1310 }
1311 sessions.addAll(findOwnSessions());
1312 for(XmppAxolotlSession session : sessions) {
1313 axolotlMessage.addDevice(session);
1314 }
1315 return true;
1316 }
1317
1318 @Nullable
1319 public XmppAxolotlMessage encrypt(Message message) {
1320 final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
1321 final String content;
1322 if (message.hasFileOnRemoteHost()) {
1323 content = message.getFileParams().url.toString();
1324 } else {
1325 content = message.getBody();
1326 }
1327 try {
1328 axolotlMessage.encrypt(content);
1329 } catch (CryptoFailedException e) {
1330 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
1331 return null;
1332 }
1333
1334 final boolean success;
1335 if (message.isPrivateMessage()) {
1336 success = buildHeader(axolotlMessage, message.getTrueCounterpart());
1337 } else {
1338 success = buildHeader(axolotlMessage, (Conversation) message.getConversation());
1339 }
1340 return success ? axolotlMessage : null;
1341 }
1342
1343 public void preparePayloadMessage(final Message message, final boolean delay) {
1344 executor.execute(new Runnable() {
1345 @Override
1346 public void run() {
1347 XmppAxolotlMessage axolotlMessage = encrypt(message);
1348 if (axolotlMessage == null) {
1349 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1350 //mXmppConnectionService.updateConversationUi();
1351 } else {
1352 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
1353 messageCache.put(message.getUuid(), axolotlMessage);
1354 mXmppConnectionService.resendMessage(message, delay);
1355 }
1356 }
1357 });
1358 }
1359
1360 public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
1361 executor.execute(new Runnable() {
1362 @Override
1363 public void run() {
1364 final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
1365 if (buildHeader(axolotlMessage, conversation)) {
1366 onMessageCreatedCallback.run(axolotlMessage);
1367 } else {
1368 onMessageCreatedCallback.run(null);
1369 }
1370 }
1371 });
1372 }
1373
1374 public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
1375 XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
1376 if (axolotlMessage != null) {
1377 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
1378 messageCache.remove(message.getUuid());
1379 } else {
1380 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
1381 }
1382 return axolotlMessage;
1383 }
1384
1385 private XmppAxolotlSession recreateUncachedSession(SignalProtocolAddress address) {
1386 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1387 return (identityKey != null)
1388 ? new XmppAxolotlSession(account, axolotlStore, address, identityKey)
1389 : null;
1390 }
1391
1392 private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
1393 SignalProtocolAddress senderAddress = new SignalProtocolAddress(message.getFrom().toString(), message.getSenderDeviceId());
1394 return getReceivingSession(senderAddress);
1395
1396 }
1397
1398 private XmppAxolotlSession getReceivingSession(SignalProtocolAddress senderAddress) {
1399 XmppAxolotlSession session = sessions.get(senderAddress);
1400 if (session == null) {
1401 //Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
1402 session = recreateUncachedSession(senderAddress);
1403 if (session == null) {
1404 session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1405 }
1406 }
1407 return session;
1408 }
1409
1410 public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message, boolean postponePreKeyMessageHandling) throws NotEncryptedForThisDeviceException, BrokenSessionException {
1411 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1412
1413 XmppAxolotlSession session = getReceivingSession(message);
1414 int ownDeviceId = getOwnDeviceId();
1415 try {
1416 plaintextMessage = message.decrypt(session, ownDeviceId);
1417 Integer preKeyId = session.getPreKeyIdAndReset();
1418 if (preKeyId != null) {
1419 postPreKeyMessageHandling(session, postponePreKeyMessageHandling);
1420 }
1421 } catch (NotEncryptedForThisDeviceException e) {
1422 if (account.getJid().asBareJid().equals(message.getFrom().asBareJid()) && message.getSenderDeviceId() == ownDeviceId) {
1423 Log.w(Config.LOGTAG, getLogprefix(account) + "Reflected omemo message received");
1424 } else {
1425 throw e;
1426 }
1427 } catch (final BrokenSessionException e) {
1428 throw e;
1429 } catch (CryptoFailedException e) {
1430 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message from " + message.getFrom(), e);
1431 }
1432
1433 if (session.isFresh() && plaintextMessage != null) {
1434 putFreshSession(session);
1435 }
1436
1437 return plaintextMessage;
1438 }
1439
1440 public void reportBrokenSessionException(BrokenSessionException e, boolean postpone) {
1441 Log.e(Config.LOGTAG,account.getJid().asBareJid()+": broken session with "+e.getSignalProtocolAddress().toString()+" detected", e);
1442 if (postpone) {
1443 postponedHealing.add(e.getSignalProtocolAddress());
1444 } else {
1445 notifyRequiresHealing(e.getSignalProtocolAddress());
1446 }
1447 }
1448
1449 private void notifyRequiresHealing(final SignalProtocolAddress signalProtocolAddress) {
1450 if (healingAttempts.add(signalProtocolAddress)) {
1451 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": attempt to heal "+signalProtocolAddress);
1452 buildSessionFromPEP(signalProtocolAddress, new OnSessionBuildFromPep() {
1453 @Override
1454 public void onSessionBuildSuccessful() {
1455 Log.d(Config.LOGTAG, "successfully build new session from pep after detecting broken session");
1456 completeSession(getReceivingSession(signalProtocolAddress));
1457 }
1458
1459 @Override
1460 public void onSessionBuildFailed() {
1461 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to build new session from pep after detecting broken session");
1462 }
1463 });
1464 } else {
1465 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": do not attempt to heal "+signalProtocolAddress+" again");
1466 }
1467 }
1468
1469 private void postPreKeyMessageHandling(final XmppAxolotlSession session, final boolean postpone) {
1470 if (postpone) {
1471 postponedSessions.add(session);
1472 } else {
1473 if (axolotlStore.flushPreKeys()) {
1474 publishBundlesIfNeeded(false, false);
1475 } else {
1476 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": nothing to flush. Not republishing key");
1477 }
1478 if (trustedOrPreviouslyResponded(session)) {
1479 completeSession(session);
1480 }
1481 }
1482 }
1483
1484 public void processPostponed() {
1485 if (postponedSessions.size() > 0) {
1486 if (axolotlStore.flushPreKeys()) {
1487 publishBundlesIfNeeded(false, false);
1488 }
1489 }
1490 final Iterator<XmppAxolotlSession> iterator = postponedSessions.iterator();
1491 while (iterator.hasNext()) {
1492 final XmppAxolotlSession session = iterator.next();
1493 if (trustedOrPreviouslyResponded(session)) {
1494 completeSession(session);
1495 }
1496 iterator.remove();
1497 }
1498 final Iterator<SignalProtocolAddress> postponedHealingAttemptsIterator = postponedHealing.iterator();
1499 while (postponedHealingAttemptsIterator.hasNext()) {
1500 notifyRequiresHealing(postponedHealingAttemptsIterator.next());
1501 postponedHealingAttemptsIterator.remove();
1502 }
1503 }
1504
1505
1506 private boolean trustedOrPreviouslyResponded(XmppAxolotlSession session) {
1507 try {
1508 return trustedOrPreviouslyResponded(Jid.of(session.getRemoteAddress().getName()));
1509 } catch (IllegalArgumentException e) {
1510 return false;
1511 }
1512 }
1513
1514 public boolean trustedOrPreviouslyResponded(Jid jid) {
1515 final Contact contact = account.getRoster().getContact(jid);
1516 if (contact.showInRoster() || contact.isSelf()) {
1517 return true;
1518 }
1519 final Conversation conversation = mXmppConnectionService.find(account, jid);
1520 return conversation != null && conversation.sentMessagesCount() > 0;
1521 }
1522
1523 private void completeSession(XmppAxolotlSession session) {
1524 final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
1525 axolotlMessage.addDevice(session, true);
1526 try {
1527 final Jid jid = Jid.of(session.getRemoteAddress().getName());
1528 MessagePacket packet = mXmppConnectionService.getMessageGenerator().generateKeyTransportMessage(jid, axolotlMessage);
1529 mXmppConnectionService.sendMessagePacket(account, packet);
1530 } catch (IllegalArgumentException e) {
1531 throw new Error("Remote addresses are created from jid and should convert back to jid", e);
1532 }
1533 }
1534
1535
1536 public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message, final boolean postponePreKeyMessageHandling) {
1537 final XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
1538 final XmppAxolotlSession session = getReceivingSession(message);
1539 try {
1540 keyTransportMessage = message.getParameters(session, getOwnDeviceId());
1541 Integer preKeyId = session.getPreKeyIdAndReset();
1542 if (preKeyId != null) {
1543 postPreKeyMessageHandling(session, postponePreKeyMessageHandling);
1544 }
1545 } catch (CryptoFailedException e) {
1546 Log.d(Config.LOGTAG, "could not decrypt keyTransport message " + e.getMessage());
1547 return null;
1548 }
1549
1550 if (session.isFresh() && keyTransportMessage != null) {
1551 putFreshSession(session);
1552 }
1553
1554 return keyTransportMessage;
1555 }
1556
1557 private void putFreshSession(XmppAxolotlSession session) {
1558 sessions.put(session);
1559 if (Config.X509_VERIFICATION) {
1560 if (session.getIdentityKey() != null) {
1561 verifySessionWithPEP(session);
1562 } else {
1563 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": identity key was empty after reloading for x509 verification");
1564 }
1565 }
1566 }
1567}