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