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.libaxolotl.AxolotlAddress;
12import org.whispersystems.libaxolotl.IdentityKey;
13import org.whispersystems.libaxolotl.IdentityKeyPair;
14import org.whispersystems.libaxolotl.InvalidKeyException;
15import org.whispersystems.libaxolotl.InvalidKeyIdException;
16import org.whispersystems.libaxolotl.SessionBuilder;
17import org.whispersystems.libaxolotl.UntrustedIdentityException;
18import org.whispersystems.libaxolotl.ecc.ECPublicKey;
19import org.whispersystems.libaxolotl.state.PreKeyBundle;
20import org.whispersystems.libaxolotl.state.PreKeyRecord;
21import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
22import org.whispersystems.libaxolotl.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.List;
35import java.util.Map;
36import java.util.Random;
37import java.util.Set;
38import java.util.concurrent.atomic.AtomicBoolean;
39
40import eu.siacs.conversations.Config;
41import eu.siacs.conversations.entities.Account;
42import eu.siacs.conversations.entities.Contact;
43import eu.siacs.conversations.entities.Conversation;
44import eu.siacs.conversations.entities.Message;
45import eu.siacs.conversations.parser.IqParser;
46import eu.siacs.conversations.services.XmppConnectionService;
47import eu.siacs.conversations.utils.CryptoHelper;
48import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
49import eu.siacs.conversations.xml.Element;
50import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
51import eu.siacs.conversations.xmpp.OnIqPacketReceived;
52import eu.siacs.conversations.xmpp.jid.InvalidJidException;
53import eu.siacs.conversations.xmpp.jid.Jid;
54import eu.siacs.conversations.xmpp.stanzas.IqPacket;
55
56public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
57
58 public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
59 public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
60 public static final String PEP_DEVICE_LIST_NOTIFY = PEP_DEVICE_LIST + "+notify";
61 public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
62 public static final String PEP_VERIFICATION = PEP_PREFIX + ".verification";
63
64 public static final String LOGPREFIX = "AxolotlService";
65
66 public static final int NUM_KEYS_TO_PUBLISH = 100;
67 public static final int publishTriesThreshold = 3;
68
69 private final Account account;
70 private final XmppConnectionService mXmppConnectionService;
71 private final SQLiteAxolotlStore axolotlStore;
72 private final SessionMap sessions;
73 private final Map<Jid, Set<Integer>> deviceIds;
74 private final Map<String, XmppAxolotlMessage> messageCache;
75 private final FetchStatusMap fetchStatusMap;
76 private final SerialSingleThreadExecutor executor;
77 private int numPublishTriesOnEmptyPep = 0;
78 private boolean pepBroken = false;
79
80 private AtomicBoolean ownPushPending = new AtomicBoolean(false);
81
82 @Override
83 public void onAdvancedStreamFeaturesAvailable(Account account) {
84 if (Config.supportOmemo()
85 && account.getXmppConnection() != null
86 && account.getXmppConnection().getFeatures().pep()) {
87 publishBundlesIfNeeded(true, false);
88 } else {
89 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping OMEMO initialization");
90 }
91 }
92
93 public boolean fetchMapHasErrors(List<Jid> jids) {
94 for(Jid jid : jids) {
95 if (deviceIds.get(jid) != null) {
96 for (Integer foreignId : this.deviceIds.get(jid)) {
97 AxolotlAddress address = new AxolotlAddress(jid.toString(), foreignId);
98 if (fetchStatusMap.getAll(address).containsValue(FetchStatus.ERROR)) {
99 return true;
100 }
101 }
102 }
103 }
104 return false;
105 }
106
107 public void preVerifyFingerprint(Contact contact, String fingerprint) {
108 axolotlStore.preVerifyFingerprint(contact.getAccount(), contact.getJid().toBareJid().toPreppedString(), fingerprint);
109 }
110
111 public void preVerifyFingerprint(Account account, String fingerprint) {
112 axolotlStore.preVerifyFingerprint(account, account.getJid().toBareJid().toPreppedString(), fingerprint);
113 }
114
115 public boolean hasVerifiedKeys(String name) {
116 for(XmppAxolotlSession session : this.sessions.getAll(new AxolotlAddress(name,0)).values()) {
117 if (session.getTrust().isVerified()) {
118 return true;
119 }
120 }
121 return false;
122 }
123
124 private static class AxolotlAddressMap<T> {
125 protected Map<String, Map<Integer, T>> map;
126 protected final Object MAP_LOCK = new Object();
127
128 public AxolotlAddressMap() {
129 this.map = new HashMap<>();
130 }
131
132 public void put(AxolotlAddress address, T value) {
133 synchronized (MAP_LOCK) {
134 Map<Integer, T> devices = map.get(address.getName());
135 if (devices == null) {
136 devices = new HashMap<>();
137 map.put(address.getName(), devices);
138 }
139 devices.put(address.getDeviceId(), value);
140 }
141 }
142
143 public T get(AxolotlAddress address) {
144 synchronized (MAP_LOCK) {
145 Map<Integer, T> devices = map.get(address.getName());
146 if (devices == null) {
147 return null;
148 }
149 return devices.get(address.getDeviceId());
150 }
151 }
152
153 public Map<Integer, T> getAll(AxolotlAddress address) {
154 synchronized (MAP_LOCK) {
155 Map<Integer, T> devices = map.get(address.getName());
156 if (devices == null) {
157 return new HashMap<>();
158 }
159 return devices;
160 }
161 }
162
163 public boolean hasAny(AxolotlAddress address) {
164 synchronized (MAP_LOCK) {
165 Map<Integer, T> devices = map.get(address.getName());
166 return devices != null && !devices.isEmpty();
167 }
168 }
169
170 public void clear() {
171 map.clear();
172 }
173
174 }
175
176 private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
177 private final XmppConnectionService xmppConnectionService;
178 private final Account account;
179
180 public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
181 super();
182 this.xmppConnectionService = service;
183 this.account = account;
184 this.fillMap(store);
185 }
186
187 private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
188 for (Integer deviceId : deviceIds) {
189 AxolotlAddress axolotlAddress = new AxolotlAddress(bareJid, deviceId);
190 IdentityKey identityKey = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey();
191 if(Config.X509_VERIFICATION) {
192 X509Certificate certificate = store.getFingerprintCertificate(identityKey.getFingerprint().replaceAll("\\s", ""));
193 if (certificate != null) {
194 Bundle information = CryptoHelper.extractCertificateInformation(certificate);
195 try {
196 final String cn = information.getString("subject_cn");
197 final Jid jid = Jid.fromString(bareJid);
198 Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
199 account.getRoster().getContact(jid).setCommonName(cn);
200 } catch (final InvalidJidException ignored) {
201 //ignored
202 }
203 }
204 }
205 this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, identityKey));
206 }
207 }
208
209 private void fillMap(SQLiteAxolotlStore store) {
210 List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toPreppedString());
211 putDevicesForJid(account.getJid().toBareJid().toPreppedString(), deviceIds, store);
212 for (Contact contact : account.getRoster().getContacts()) {
213 Jid bareJid = contact.getJid().toBareJid();
214 String address = bareJid.toString();
215 deviceIds = store.getSubDeviceSessions(address);
216 putDevicesForJid(address, deviceIds, store);
217 }
218
219 }
220
221 @Override
222 public void put(AxolotlAddress address, XmppAxolotlSession value) {
223 super.put(address, value);
224 value.setNotFresh();
225 xmppConnectionService.syncRosterToDisk(account); //TODO why?
226 }
227
228 public void put(XmppAxolotlSession session) {
229 this.put(session.getRemoteAddress(), session);
230 }
231 }
232
233 public enum FetchStatus {
234 PENDING,
235 SUCCESS,
236 SUCCESS_VERIFIED,
237 TIMEOUT,
238 SUCCESS_TRUSTED,
239 ERROR
240 }
241
242 private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
243
244 public void clearErrorFor(Jid jid) {
245 synchronized (MAP_LOCK) {
246 Map<Integer, FetchStatus> devices = this.map.get(jid.toBareJid().toPreppedString());
247 if (devices == null) {
248 return;
249 }
250 for(Map.Entry<Integer, FetchStatus> entry : devices.entrySet()) {
251 if (entry.getValue() == FetchStatus.ERROR) {
252 Log.d(Config.LOGTAG,"resetting error for "+jid.toBareJid()+"("+entry.getKey()+")");
253 entry.setValue(FetchStatus.TIMEOUT);
254 }
255 }
256 }
257 }
258 }
259
260 public static String getLogprefix(Account account) {
261 return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): ";
262 }
263
264 public AxolotlService(Account account, XmppConnectionService connectionService) {
265 if (Security.getProvider("BC") == null) {
266 Security.addProvider(new BouncyCastleProvider());
267 }
268 this.mXmppConnectionService = connectionService;
269 this.account = account;
270 this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
271 this.deviceIds = new HashMap<>();
272 this.messageCache = new HashMap<>();
273 this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
274 this.fetchStatusMap = new FetchStatusMap();
275 this.executor = new SerialSingleThreadExecutor();
276 }
277
278 public String getOwnFingerprint() {
279 return axolotlStore.getIdentityKeyPair().getPublicKey().getFingerprint().replaceAll("\\s", "");
280 }
281
282 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status) {
283 return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toPreppedString(), status);
284 }
285
286 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, Jid jid) {
287 return axolotlStore.getContactKeysWithTrust(jid.toBareJid().toPreppedString(), status);
288 }
289
290 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) {
291 Set<IdentityKey> keys = new HashSet<>();
292 for(Jid jid : jids) {
293 keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toPreppedString(), status));
294 }
295 return keys;
296 }
297
298 public long getNumTrustedKeys(Jid jid) {
299 return axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString());
300 }
301
302 public boolean anyTargetHasNoTrustedKeys(List<Jid> jids) {
303 for(Jid jid : jids) {
304 if (axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString()) == 0) {
305 return true;
306 }
307 }
308 return false;
309 }
310
311 private AxolotlAddress getAddressForJid(Jid jid) {
312 return new AxolotlAddress(jid.toPreppedString(), 0);
313 }
314
315 public Collection<XmppAxolotlSession> findOwnSessions() {
316 AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
317 ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(ownAddress).values());
318 Collections.sort(s);
319 return s;
320 }
321
322
323
324 public Collection<XmppAxolotlSession> findSessionsForContact(Contact contact) {
325 AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
326 ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(contactAddress).values());
327 Collections.sort(s);
328 return s;
329 }
330
331 private Set<XmppAxolotlSession> findSessionsForConversation(Conversation conversation) {
332 HashSet<XmppAxolotlSession> sessions = new HashSet<>();
333 for(Jid jid : conversation.getAcceptedCryptoTargets()) {
334 sessions.addAll(this.sessions.getAll(getAddressForJid(jid)).values());
335 }
336 return sessions;
337 }
338
339 private boolean hasAny(Jid jid) {
340 return sessions.hasAny(getAddressForJid(jid));
341 }
342
343 public boolean isPepBroken() {
344 return this.pepBroken;
345 }
346
347 public void resetBrokenness() {
348 this.pepBroken = false;
349 numPublishTriesOnEmptyPep = 0;
350 }
351
352 public void clearErrorsInFetchStatusMap(Jid jid) {
353 fetchStatusMap.clearErrorFor(jid);
354 }
355
356 public void regenerateKeys(boolean wipeOther) {
357 axolotlStore.regenerate();
358 sessions.clear();
359 fetchStatusMap.clear();
360 publishBundlesIfNeeded(true, wipeOther);
361 }
362
363 public int getOwnDeviceId() {
364 return axolotlStore.getLocalRegistrationId();
365 }
366
367 public Set<Integer> getOwnDeviceIds() {
368 return this.deviceIds.get(account.getJid().toBareJid());
369 }
370
371 public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
372 boolean me = jid.toBareJid().equals(account.getJid().toBareJid());
373 if (me && ownPushPending.getAndSet(false)) {
374 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": ignoring own device update because of pending push");
375 return;
376 }
377 boolean needsPublishing = me && !deviceIds.contains(getOwnDeviceId());
378 if (me) {
379 deviceIds.remove(getOwnDeviceId());
380 }
381 Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toPreppedString()));
382 expiredDevices.removeAll(deviceIds);
383 for (Integer deviceId : expiredDevices) {
384 AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
385 XmppAxolotlSession session = sessions.get(address);
386 if (session != null && session.getFingerprint() != null) {
387 if (session.getTrust().isActive()) {
388 session.setTrust(session.getTrust().toInactive());
389 }
390 }
391 }
392 Set<Integer> newDevices = new HashSet<>(deviceIds);
393 for (Integer deviceId : newDevices) {
394 AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
395 XmppAxolotlSession session = sessions.get(address);
396 if (session != null && session.getFingerprint() != null) {
397 if (!session.getTrust().isActive()) {
398 Log.d(Config.LOGTAG,"reactivating device with fingprint "+session.getFingerprint());
399 session.setTrust(session.getTrust().toActive());
400 }
401 }
402 }
403 if (me) {
404 if (Config.OMEMO_AUTO_EXPIRY != 0) {
405 needsPublishing |= deviceIds.removeAll(getExpiredDevices());
406 }
407 for (Integer deviceId : deviceIds) {
408 AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
409 if (sessions.get(ownDeviceAddress) == null) {
410 buildSessionFromPEP(ownDeviceAddress);
411 }
412 }
413 if (needsPublishing) {
414 publishOwnDeviceId(deviceIds);
415 }
416 }
417 this.deviceIds.put(jid, deviceIds);
418 mXmppConnectionService.keyStatusUpdated(null);
419 }
420
421 public void wipeOtherPepDevices() {
422 if (pepBroken) {
423 Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
424 return;
425 }
426 Set<Integer> deviceIds = new HashSet<>();
427 deviceIds.add(getOwnDeviceId());
428 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
429 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Wiping all other devices from Pep:" + publish);
430 mXmppConnectionService.sendIqPacket(account, publish, null);
431 }
432
433 public void purgeKey(final String fingerprint) {
434 axolotlStore.setFingerprintStatus(fingerprint.replaceAll("\\s", ""), FingerprintStatus.createCompromised());
435 }
436
437 public void publishOwnDeviceIdIfNeeded() {
438 if (pepBroken) {
439 Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
440 return;
441 }
442 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
443 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
444 @Override
445 public void onIqPacketReceived(Account account, IqPacket packet) {
446 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
447 Log.d(Config.LOGTAG, getLogprefix(account) + "Timeout received while retrieving own Device Ids.");
448 } else {
449 Element item = mXmppConnectionService.getIqParser().getItem(packet);
450 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
451 registerDevices(account.getJid().toBareJid(),deviceIds);
452 }
453 }
454 });
455 }
456
457 private Set<Integer> getExpiredDevices() {
458 Set<Integer> devices = new HashSet<>();
459 for(XmppAxolotlSession session : findOwnSessions()) {
460 if (session.getTrust().isActive()) {
461 long diff = System.currentTimeMillis() - session.getTrust().getLastActivation();
462 if (diff > Config.OMEMO_AUTO_EXPIRY) {
463 long lastMessageDiff = System.currentTimeMillis() - mXmppConnectionService.databaseBackend.getLastTimeFingerprintUsed(account,session.getFingerprint());
464 if (lastMessageDiff > Config.OMEMO_AUTO_EXPIRY) {
465 devices.add(session.getRemoteAddress().getDeviceId());
466 session.setTrust(session.getTrust().toInactive());
467 Log.d(Config.LOGTAG, "added own device " + session.getFingerprint() + " to list of expired devices. Last message received "+(lastMessageDiff/1000)+"s ago");
468 }
469 }
470 }
471 }
472 return devices;
473 }
474
475 public void publishOwnDeviceId(Set<Integer> deviceIds) {
476 Set<Integer> deviceIdsCopy = new HashSet<>(deviceIds);
477 if (!deviceIdsCopy.contains(getOwnDeviceId())) {
478 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Own device " + getOwnDeviceId() + " not in PEP devicelist.");
479 if (deviceIdsCopy.isEmpty()) {
480 if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
481 Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
482 pepBroken = true;
483 return;
484 } else {
485 numPublishTriesOnEmptyPep++;
486 Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
487 }
488 } else {
489 numPublishTriesOnEmptyPep = 0;
490 }
491 deviceIdsCopy.add(getOwnDeviceId());
492 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIdsCopy);
493 ownPushPending.set(true);
494 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
495 @Override
496 public void onIqPacketReceived(Account account, IqPacket packet) {
497 ownPushPending.set(false);
498 if (packet.getType() == IqPacket.TYPE.ERROR) {
499 pepBroken = true;
500 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
501 }
502 }
503 });
504 }
505 }
506
507 public void publishDeviceVerificationAndBundle(final SignedPreKeyRecord signedPreKeyRecord,
508 final Set<PreKeyRecord> preKeyRecords,
509 final boolean announceAfter,
510 final boolean wipe) {
511 try {
512 IdentityKey axolotlPublicKey = axolotlStore.getIdentityKeyPair().getPublicKey();
513 PrivateKey x509PrivateKey = KeyChain.getPrivateKey(mXmppConnectionService, account.getPrivateKeyAlias());
514 X509Certificate[] chain = KeyChain.getCertificateChain(mXmppConnectionService, account.getPrivateKeyAlias());
515 Signature verifier = Signature.getInstance("sha256WithRSA");
516 verifier.initSign(x509PrivateKey,mXmppConnectionService.getRNG());
517 verifier.update(axolotlPublicKey.serialize());
518 byte[] signature = verifier.sign();
519 IqPacket packet = mXmppConnectionService.getIqGenerator().publishVerification(signature, chain, getOwnDeviceId());
520 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": publish verification for device "+getOwnDeviceId());
521 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
522 @Override
523 public void onIqPacketReceived(Account account, IqPacket packet) {
524 publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
525 }
526 });
527 } catch (Exception e) {
528 e.printStackTrace();
529 }
530 }
531
532 public void publishBundlesIfNeeded(final boolean announce, final boolean wipe) {
533 if (pepBroken) {
534 Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
535 return;
536 }
537 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
538 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
539 @Override
540 public void onIqPacketReceived(Account account, IqPacket packet) {
541
542 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
543 return; //ignore timeout. do nothing
544 }
545
546 if (packet.getType() == IqPacket.TYPE.ERROR) {
547 Element error = packet.findChild("error");
548 if (error == null || !error.hasChild("item-not-found")) {
549 pepBroken = true;
550 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
551 return;
552 }
553 }
554
555 PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
556 Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
557 boolean flush = false;
558 if (bundle == null) {
559 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
560 bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
561 flush = true;
562 }
563 if (keys == null) {
564 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
565 }
566 try {
567 boolean changed = false;
568 // Validate IdentityKey
569 IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
570 if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
571 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
572 changed = true;
573 }
574
575 // Validate signedPreKeyRecord + ID
576 SignedPreKeyRecord signedPreKeyRecord;
577 int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
578 try {
579 signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
580 if (flush
581 || !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
582 || !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
583 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
584 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
585 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
586 changed = true;
587 }
588 } catch (InvalidKeyIdException e) {
589 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
590 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
591 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
592 changed = true;
593 }
594
595 // Validate PreKeys
596 Set<PreKeyRecord> preKeyRecords = new HashSet<>();
597 if (keys != null) {
598 for (Integer id : keys.keySet()) {
599 try {
600 PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
601 if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
602 preKeyRecords.add(preKeyRecord);
603 }
604 } catch (InvalidKeyIdException ignored) {
605 }
606 }
607 }
608 int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
609 if (newKeys > 0) {
610 List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
611 axolotlStore.getCurrentPreKeyId() + 1, newKeys);
612 preKeyRecords.addAll(newRecords);
613 for (PreKeyRecord record : newRecords) {
614 axolotlStore.storePreKey(record.getId(), record);
615 }
616 changed = true;
617 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
618 }
619
620
621 if (changed) {
622 if (account.getPrivateKeyAlias() != null && Config.X509_VERIFICATION) {
623 mXmppConnectionService.publishDisplayName(account);
624 publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
625 } else {
626 publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
627 }
628 } else {
629 Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
630 if (wipe) {
631 wipeOtherPepDevices();
632 } else if (announce) {
633 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
634 publishOwnDeviceIdIfNeeded();
635 }
636 }
637 } catch (InvalidKeyException e) {
638 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
639 }
640 }
641 });
642 }
643
644 private void publishDeviceBundle(SignedPreKeyRecord signedPreKeyRecord,
645 Set<PreKeyRecord> preKeyRecords,
646 final boolean announceAfter,
647 final boolean wipe) {
648 IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
649 signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
650 preKeyRecords, getOwnDeviceId());
651 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
652 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
653 @Override
654 public void onIqPacketReceived(Account account, IqPacket packet) {
655 if (packet.getType() == IqPacket.TYPE.RESULT) {
656 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
657 if (wipe) {
658 wipeOtherPepDevices();
659 } else if (announceAfter) {
660 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
661 publishOwnDeviceIdIfNeeded();
662 }
663 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
664 pepBroken = true;
665 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
666 }
667 }
668 });
669 }
670
671 public enum AxolotlCapability {
672 FULL,
673 MISSING_PRESENCE,
674 MISSING_KEYS,
675 WRONG_CONFIGURATION,
676 NO_MEMBERS
677 }
678
679 public boolean isConversationAxolotlCapable(Conversation conversation) {
680 return isConversationAxolotlCapableDetailed(conversation).first == AxolotlCapability.FULL;
681 }
682
683 public Pair<AxolotlCapability,Jid> isConversationAxolotlCapableDetailed(Conversation conversation) {
684 if (conversation.getMode() == Conversation.MODE_SINGLE
685 || (conversation.getMucOptions().membersOnly() && conversation.getMucOptions().nonanonymous())) {
686 final List<Jid> jids = getCryptoTargets(conversation);
687 for(Jid jid : jids) {
688 if (!hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty())) {
689 if (conversation.getAccount().getRoster().getContact(jid).mutualPresenceSubscription()) {
690 return new Pair<>(AxolotlCapability.MISSING_KEYS,jid);
691 } else {
692 return new Pair<>(AxolotlCapability.MISSING_PRESENCE,jid);
693 }
694 }
695 }
696 if (jids.size() > 0) {
697 return new Pair<>(AxolotlCapability.FULL, null);
698 } else {
699 return new Pair<>(AxolotlCapability.NO_MEMBERS, null);
700 }
701 } else {
702 return new Pair<>(AxolotlCapability.WRONG_CONFIGURATION, null);
703 }
704 }
705
706 public List<Jid> getCryptoTargets(Conversation conversation) {
707 final List<Jid> jids;
708 if (conversation.getMode() == Conversation.MODE_SINGLE) {
709 jids = Arrays.asList(conversation.getJid().toBareJid());
710 } else {
711 jids = conversation.getMucOptions().getMembers();
712 }
713 return jids;
714 }
715
716 public FingerprintStatus getFingerprintTrust(String fingerprint) {
717 return axolotlStore.getFingerprintStatus(fingerprint);
718 }
719
720 public X509Certificate getFingerprintCertificate(String fingerprint) {
721 return axolotlStore.getFingerprintCertificate(fingerprint);
722 }
723
724 public void setFingerprintTrust(String fingerprint, FingerprintStatus status) {
725 axolotlStore.setFingerprintStatus(fingerprint, status);
726 }
727
728 private void verifySessionWithPEP(final XmppAxolotlSession session) {
729 Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
730 final AxolotlAddress address = session.getRemoteAddress();
731 final IdentityKey identityKey = session.getIdentityKey();
732 try {
733 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId());
734 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
735 @Override
736 public void onIqPacketReceived(Account account, IqPacket packet) {
737 Pair<X509Certificate[],byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
738 if (verification != null) {
739 try {
740 Signature verifier = Signature.getInstance("sha256WithRSA");
741 verifier.initVerify(verification.first[0]);
742 verifier.update(identityKey.serialize());
743 if (verifier.verify(verification.second)) {
744 try {
745 mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
746 String fingerprint = session.getFingerprint();
747 Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+fingerprint);
748 setFingerprintTrust(fingerprint, FingerprintStatus.createActiveVerified(true));
749 axolotlStore.setFingerprintCertificate(fingerprint, verification.first[0]);
750 fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
751 Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
752 try {
753 final String cn = information.getString("subject_cn");
754 final Jid jid = Jid.fromString(address.getName());
755 Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
756 account.getRoster().getContact(jid).setCommonName(cn);
757 } catch (final InvalidJidException ignored) {
758 //ignored
759 }
760 finishBuildingSessionsFromPEP(address);
761 return;
762 } catch (Exception e) {
763 Log.d(Config.LOGTAG,"could not verify certificate");
764 }
765 }
766 } catch (Exception e) {
767 Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
768 }
769 } else {
770 Log.d(Config.LOGTAG,"no verification found");
771 }
772 fetchStatusMap.put(address, FetchStatus.SUCCESS);
773 finishBuildingSessionsFromPEP(address);
774 }
775 });
776 } catch (InvalidJidException e) {
777 fetchStatusMap.put(address, FetchStatus.SUCCESS);
778 finishBuildingSessionsFromPEP(address);
779 }
780 }
781
782 private void finishBuildingSessionsFromPEP(final AxolotlAddress address) {
783 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
784 Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress);
785 Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address);
786 if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
787 FetchStatus report = null;
788 if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
789 report = FetchStatus.SUCCESS;
790 } else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
791 report = FetchStatus.SUCCESS_VERIFIED;
792 } else if (own.containsValue(FetchStatus.SUCCESS_TRUSTED) || remote.containsValue(FetchStatus.SUCCESS_TRUSTED)) {
793 report = FetchStatus.SUCCESS_TRUSTED;
794 } else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
795 report = FetchStatus.ERROR;
796 }
797 mXmppConnectionService.keyStatusUpdated(report);
798 }
799 }
800
801 private void buildSessionFromPEP(final AxolotlAddress address) {
802 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString());
803 if (address.getDeviceId() == getOwnDeviceId()) {
804 throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
805 }
806
807 try {
808 IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
809 Jid.fromString(address.getName()), address.getDeviceId());
810 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
811 mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
812
813 @Override
814 public void onIqPacketReceived(Account account, IqPacket packet) {
815 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
816 fetchStatusMap.put(address, FetchStatus.TIMEOUT);
817 } else if (packet.getType() == IqPacket.TYPE.RESULT) {
818 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
819 final IqParser parser = mXmppConnectionService.getIqParser();
820 final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
821 final PreKeyBundle bundle = parser.bundle(packet);
822 if (preKeyBundleList.isEmpty() || bundle == null) {
823 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
824 fetchStatusMap.put(address, FetchStatus.ERROR);
825 finishBuildingSessionsFromPEP(address);
826 return;
827 }
828 Random random = new Random();
829 final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
830 if (preKey == null) {
831 //should never happen
832 fetchStatusMap.put(address, FetchStatus.ERROR);
833 finishBuildingSessionsFromPEP(address);
834 return;
835 }
836
837 final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
838 preKey.getPreKeyId(), preKey.getPreKey(),
839 bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
840 bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
841
842 try {
843 SessionBuilder builder = new SessionBuilder(axolotlStore, address);
844 builder.process(preKeyBundle);
845 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
846 sessions.put(address, session);
847 if (Config.X509_VERIFICATION) {
848 verifySessionWithPEP(session);
849 } else {
850 FingerprintStatus status = getFingerprintTrust(bundle.getIdentityKey().getFingerprint().replaceAll("\\s",""));
851 FetchStatus fetchStatus;
852 if (status != null && status.isVerified()) {
853 fetchStatus = FetchStatus.SUCCESS_VERIFIED;
854 } else if (status != null && status.isTrusted()) {
855 fetchStatus = FetchStatus.SUCCESS_TRUSTED;
856 } else {
857 fetchStatus = FetchStatus.SUCCESS;
858 }
859 fetchStatusMap.put(address, fetchStatus);
860 finishBuildingSessionsFromPEP(address);
861 }
862 } catch (UntrustedIdentityException | InvalidKeyException e) {
863 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
864 + e.getClass().getName() + ", " + e.getMessage());
865 fetchStatusMap.put(address, FetchStatus.ERROR);
866 finishBuildingSessionsFromPEP(address);
867 }
868 } else {
869 fetchStatusMap.put(address, FetchStatus.ERROR);
870 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
871 finishBuildingSessionsFromPEP(address);
872 }
873 }
874 });
875 } catch (InvalidJidException e) {
876 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
877 }
878 }
879
880 public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
881 Set<AxolotlAddress> addresses = new HashSet<>();
882 for(Jid jid : getCryptoTargets(conversation)) {
883 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
884 if (deviceIds.get(jid) != null) {
885 for (Integer foreignId : this.deviceIds.get(jid)) {
886 AxolotlAddress address = new AxolotlAddress(jid.toString(), foreignId);
887 if (sessions.get(address) == null) {
888 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
889 if (identityKey != null) {
890 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
891 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
892 sessions.put(address, session);
893 } else {
894 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + jid + ":" + foreignId);
895 if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
896 addresses.add(address);
897 } else {
898 Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
899 }
900 }
901 }
902 }
903 } else {
904 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
905 }
906 }
907 if (deviceIds.get(account.getJid().toBareJid()) != null) {
908 for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
909 AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), ownId);
910 if (sessions.get(address) == null) {
911 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
912 if (identityKey != null) {
913 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
914 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
915 sessions.put(address, session);
916 } else {
917 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
918 if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
919 addresses.add(address);
920 } else {
921 Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken");
922 }
923 }
924 }
925 }
926 }
927
928 return addresses;
929 }
930
931 public boolean createSessionsIfNeeded(final Conversation conversation) {
932 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
933 boolean newSessions = false;
934 Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
935 for (AxolotlAddress address : addresses) {
936 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
937 FetchStatus status = fetchStatusMap.get(address);
938 if (status == null || status == FetchStatus.TIMEOUT) {
939 fetchStatusMap.put(address, FetchStatus.PENDING);
940 this.buildSessionFromPEP(address);
941 newSessions = true;
942 } else if (status == FetchStatus.PENDING) {
943 newSessions = true;
944 } else {
945 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
946 }
947 }
948
949 return newSessions;
950 }
951
952 public boolean trustedSessionVerified(final Conversation conversation) {
953 Set<XmppAxolotlSession> sessions = findSessionsForConversation(conversation);
954 sessions.addAll(findOwnSessions());
955 boolean verified = false;
956 for(XmppAxolotlSession session : sessions) {
957 if (session.getTrust().isTrustedAndActive()) {
958 if (session.getTrust().getTrust() == FingerprintStatus.Trust.VERIFIED_X509) {
959 verified = true;
960 } else {
961 return false;
962 }
963 }
964 }
965 return verified;
966 }
967
968 public boolean hasPendingKeyFetches(Account account, List<Jid> jids) {
969 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
970 if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)) {
971 return true;
972 }
973 for(Jid jid : jids) {
974 AxolotlAddress foreignAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), 0);
975 if (fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
976 return true;
977 }
978 }
979 return false;
980 }
981
982 @Nullable
983 private XmppAxolotlMessage buildHeader(Conversation conversation) {
984 final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
985 account.getJid().toBareJid(), getOwnDeviceId());
986
987 Set<XmppAxolotlSession> remoteSessions = findSessionsForConversation(conversation);
988 Collection<XmppAxolotlSession> ownSessions = findOwnSessions();
989 if (remoteSessions.isEmpty()) {
990 return null;
991 }
992 for (XmppAxolotlSession session : remoteSessions) {
993 axolotlMessage.addDevice(session);
994 }
995 for (XmppAxolotlSession session : ownSessions) {
996 axolotlMessage.addDevice(session);
997 }
998
999 return axolotlMessage;
1000 }
1001
1002 @Nullable
1003 public XmppAxolotlMessage encrypt(Message message) {
1004 XmppAxolotlMessage axolotlMessage = buildHeader(message.getConversation());
1005
1006 if (axolotlMessage != null) {
1007 final String content;
1008 if (message.hasFileOnRemoteHost()) {
1009 content = message.getFileParams().url.toString();
1010 } else {
1011 content = message.getBody();
1012 }
1013 try {
1014 axolotlMessage.encrypt(content);
1015 } catch (CryptoFailedException e) {
1016 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
1017 return null;
1018 }
1019 }
1020
1021 return axolotlMessage;
1022 }
1023
1024 public void preparePayloadMessage(final Message message, final boolean delay) {
1025 executor.execute(new Runnable() {
1026 @Override
1027 public void run() {
1028 XmppAxolotlMessage axolotlMessage = encrypt(message);
1029 if (axolotlMessage == null) {
1030 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1031 //mXmppConnectionService.updateConversationUi();
1032 } else {
1033 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
1034 messageCache.put(message.getUuid(), axolotlMessage);
1035 mXmppConnectionService.resendMessage(message, delay);
1036 }
1037 }
1038 });
1039 }
1040
1041 public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
1042 executor.execute(new Runnable() {
1043 @Override
1044 public void run() {
1045 XmppAxolotlMessage axolotlMessage = buildHeader(conversation);
1046 onMessageCreatedCallback.run(axolotlMessage);
1047 }
1048 });
1049 }
1050
1051 public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
1052 XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
1053 if (axolotlMessage != null) {
1054 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
1055 messageCache.remove(message.getUuid());
1056 } else {
1057 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
1058 }
1059 return axolotlMessage;
1060 }
1061
1062 private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
1063 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1064 return (identityKey != null)
1065 ? new XmppAxolotlSession(account, axolotlStore, address, identityKey)
1066 : null;
1067 }
1068
1069 private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
1070 AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
1071 message.getSenderDeviceId());
1072 XmppAxolotlSession session = sessions.get(senderAddress);
1073 if (session == null) {
1074 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
1075 session = recreateUncachedSession(senderAddress);
1076 if (session == null) {
1077 session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1078 }
1079 }
1080 return session;
1081 }
1082
1083 public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
1084 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1085
1086 XmppAxolotlSession session = getReceivingSession(message);
1087 try {
1088 plaintextMessage = message.decrypt(session, getOwnDeviceId());
1089 Integer preKeyId = session.getPreKeyId();
1090 if (preKeyId != null) {
1091 publishBundlesIfNeeded(false, false);
1092 session.resetPreKeyId();
1093 }
1094 } catch (CryptoFailedException e) {
1095 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
1096 }
1097
1098 if (session.isFresh() && plaintextMessage != null) {
1099 putFreshSession(session);
1100 }
1101
1102 return plaintextMessage;
1103 }
1104
1105 public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
1106 XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
1107
1108 XmppAxolotlSession session = getReceivingSession(message);
1109 keyTransportMessage = message.getParameters(session, getOwnDeviceId());
1110
1111 if (session.isFresh() && keyTransportMessage != null) {
1112 putFreshSession(session);
1113 }
1114
1115 return keyTransportMessage;
1116 }
1117
1118 private void putFreshSession(XmppAxolotlSession session) {
1119 Log.d(Config.LOGTAG,"put fresh session");
1120 sessions.put(session);
1121 if (Config.X509_VERIFICATION) {
1122 if (session.getIdentityKey() != null) {
1123 verifySessionWithPEP(session);
1124 } else {
1125 Log.e(Config.LOGTAG,account.getJid().toBareJid()+": identity key was empty after reloading for x509 verification");
1126 }
1127 }
1128 }
1129}