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