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