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 (Config.supportOmemo()
79 && account.getXmppConnection() != null
80 && account.getXmppConnection().getFeatures().pep()) {
81 publishBundlesIfNeeded(true, false);
82 } else {
83 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping OMEMO initialization");
84 }
85 }
86
87 public boolean fetchMapHasErrors(List<Jid> jids) {
88 for(Jid jid : jids) {
89 if (deviceIds.get(jid) != null) {
90 for (Integer foreignId : this.deviceIds.get(jid)) {
91 AxolotlAddress address = new AxolotlAddress(jid.toString(), foreignId);
92 if (fetchStatusMap.getAll(address).containsValue(FetchStatus.ERROR)) {
93 return true;
94 }
95 }
96 }
97 }
98 return false;
99 }
100
101 public void preVerifyFingerprint(Contact contact, String fingerprint) {
102 axolotlStore.preVerifyFingerprint(contact.getAccount(), contact.getJid().toBareJid().toPreppedString(), fingerprint);
103 }
104
105 public void preVerifyFingerprint(Account account, String fingerprint) {
106 axolotlStore.preVerifyFingerprint(account, account.getJid().toBareJid().toPreppedString(), fingerprint);
107 }
108
109 private static class AxolotlAddressMap<T> {
110 protected Map<String, Map<Integer, T>> map;
111 protected final Object MAP_LOCK = new Object();
112
113 public AxolotlAddressMap() {
114 this.map = new HashMap<>();
115 }
116
117 public void put(AxolotlAddress address, T value) {
118 synchronized (MAP_LOCK) {
119 Map<Integer, T> devices = map.get(address.getName());
120 if (devices == null) {
121 devices = new HashMap<>();
122 map.put(address.getName(), devices);
123 }
124 devices.put(address.getDeviceId(), value);
125 }
126 }
127
128 public T get(AxolotlAddress address) {
129 synchronized (MAP_LOCK) {
130 Map<Integer, T> devices = map.get(address.getName());
131 if (devices == null) {
132 return null;
133 }
134 return devices.get(address.getDeviceId());
135 }
136 }
137
138 public Map<Integer, T> getAll(AxolotlAddress address) {
139 synchronized (MAP_LOCK) {
140 Map<Integer, T> devices = map.get(address.getName());
141 if (devices == null) {
142 return new HashMap<>();
143 }
144 return devices;
145 }
146 }
147
148 public boolean hasAny(AxolotlAddress address) {
149 synchronized (MAP_LOCK) {
150 Map<Integer, T> devices = map.get(address.getName());
151 return devices != null && !devices.isEmpty();
152 }
153 }
154
155 public void clear() {
156 map.clear();
157 }
158
159 }
160
161 private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
162 private final XmppConnectionService xmppConnectionService;
163 private final Account account;
164
165 public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
166 super();
167 this.xmppConnectionService = service;
168 this.account = account;
169 this.fillMap(store);
170 }
171
172 private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
173 for (Integer deviceId : deviceIds) {
174 AxolotlAddress axolotlAddress = new AxolotlAddress(bareJid, deviceId);
175 IdentityKey identityKey = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey();
176 if(Config.X509_VERIFICATION) {
177 X509Certificate certificate = store.getFingerprintCertificate(identityKey.getFingerprint().replaceAll("\\s", ""));
178 if (certificate != null) {
179 Bundle information = CryptoHelper.extractCertificateInformation(certificate);
180 try {
181 final String cn = information.getString("subject_cn");
182 final Jid jid = Jid.fromString(bareJid);
183 Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
184 account.getRoster().getContact(jid).setCommonName(cn);
185 } catch (final InvalidJidException ignored) {
186 //ignored
187 }
188 }
189 }
190 this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, identityKey));
191 }
192 }
193
194 private void fillMap(SQLiteAxolotlStore store) {
195 List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toPreppedString());
196 putDevicesForJid(account.getJid().toBareJid().toPreppedString(), deviceIds, store);
197 for (Contact contact : account.getRoster().getContacts()) {
198 Jid bareJid = contact.getJid().toBareJid();
199 String address = bareJid.toString();
200 deviceIds = store.getSubDeviceSessions(address);
201 putDevicesForJid(address, deviceIds, store);
202 }
203
204 }
205
206 @Override
207 public void put(AxolotlAddress address, XmppAxolotlSession value) {
208 super.put(address, value);
209 value.setNotFresh();
210 xmppConnectionService.syncRosterToDisk(account); //TODO why?
211 }
212
213 public void put(XmppAxolotlSession session) {
214 this.put(session.getRemoteAddress(), session);
215 }
216 }
217
218 public enum FetchStatus {
219 PENDING,
220 SUCCESS,
221 SUCCESS_VERIFIED,
222 TIMEOUT,
223 ERROR
224 }
225
226 private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
227
228 public void clearErrorFor(Jid jid) {
229 synchronized (MAP_LOCK) {
230 Map<Integer, FetchStatus> devices = this.map.get(jid.toBareJid().toPreppedString());
231 if (devices == null) {
232 return;
233 }
234 for(Map.Entry<Integer, FetchStatus> entry : devices.entrySet()) {
235 if (entry.getValue() == FetchStatus.ERROR) {
236 Log.d(Config.LOGTAG,"resetting error for "+jid.toBareJid()+"("+entry.getKey()+")");
237 entry.setValue(FetchStatus.TIMEOUT);
238 }
239 }
240 }
241 }
242 }
243
244 public static String getLogprefix(Account account) {
245 return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): ";
246 }
247
248 public AxolotlService(Account account, XmppConnectionService connectionService) {
249 if (Security.getProvider("BC") == null) {
250 Security.addProvider(new BouncyCastleProvider());
251 }
252 this.mXmppConnectionService = connectionService;
253 this.account = account;
254 this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
255 this.deviceIds = new HashMap<>();
256 this.messageCache = new HashMap<>();
257 this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
258 this.fetchStatusMap = new FetchStatusMap();
259 this.executor = new SerialSingleThreadExecutor();
260 }
261
262 public String getOwnFingerprint() {
263 return axolotlStore.getIdentityKeyPair().getPublicKey().getFingerprint().replaceAll("\\s", "");
264 }
265
266 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status) {
267 return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toPreppedString(), status);
268 }
269
270 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, Jid jid) {
271 return axolotlStore.getContactKeysWithTrust(jid.toBareJid().toPreppedString(), status);
272 }
273
274 public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) {
275 Set<IdentityKey> keys = new HashSet<>();
276 for(Jid jid : jids) {
277 keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toPreppedString(), status));
278 }
279 return keys;
280 }
281
282 public long getNumTrustedKeys(Jid jid) {
283 return axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString());
284 }
285
286 public boolean anyTargetHasNoTrustedKeys(List<Jid> jids) {
287 for(Jid jid : jids) {
288 if (axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString()) == 0) {
289 return true;
290 }
291 }
292 return false;
293 }
294
295 private AxolotlAddress getAddressForJid(Jid jid) {
296 return new AxolotlAddress(jid.toPreppedString(), 0);
297 }
298
299 public Set<XmppAxolotlSession> findOwnSessions() {
300 AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
301 return new HashSet<>(this.sessions.getAll(ownAddress).values());
302 }
303
304
305
306 private Set<XmppAxolotlSession> findSessionsForContact(Contact contact) {
307 AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
308 return new HashSet<>(this.sessions.getAll(contactAddress).values());
309 }
310
311 private Set<XmppAxolotlSession> findSessionsForConversation(Conversation conversation) {
312 HashSet<XmppAxolotlSession> sessions = new HashSet<>();
313 for(Jid jid : conversation.getAcceptedCryptoTargets()) {
314 sessions.addAll(this.sessions.getAll(getAddressForJid(jid)).values());
315 }
316 return sessions;
317 }
318
319 public Set<String> getFingerprintsForOwnSessions() {
320 Set<String> fingerprints = new HashSet<>();
321 for (XmppAxolotlSession session : findOwnSessions()) {
322 fingerprints.add(session.getFingerprint());
323 }
324 return fingerprints;
325 }
326
327 public Set<String> getFingerprintsForContact(final Contact contact) {
328 Set<String> fingerprints = new HashSet<>();
329 for (XmppAxolotlSession session : findSessionsForContact(contact)) {
330 fingerprints.add(session.getFingerprint());
331 }
332 return fingerprints;
333 }
334
335 private boolean hasAny(Jid jid) {
336 return sessions.hasAny(getAddressForJid(jid));
337 }
338
339 public boolean isPepBroken() {
340 return this.pepBroken;
341 }
342
343 public void resetBrokenness() {
344 this.pepBroken = false;
345 numPublishTriesOnEmptyPep = 0;
346 }
347
348 public void clearErrorsInFetchStatusMap(Jid jid) {
349 fetchStatusMap.clearErrorFor(jid);
350 }
351
352 public void regenerateKeys(boolean wipeOther) {
353 axolotlStore.regenerate();
354 sessions.clear();
355 fetchStatusMap.clear();
356 publishBundlesIfNeeded(true, wipeOther);
357 }
358
359 public int getOwnDeviceId() {
360 return axolotlStore.getLocalRegistrationId();
361 }
362
363 public Set<Integer> getOwnDeviceIds() {
364 return this.deviceIds.get(account.getJid().toBareJid());
365 }
366
367 public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
368 if (jid.toBareJid().equals(account.getJid().toBareJid())) {
369 if (!deviceIds.isEmpty()) {
370 Log.d(Config.LOGTAG, getLogprefix(account) + "Received non-empty own device list. Resetting publish attempts and pepBroken status.");
371 pepBroken = false;
372 numPublishTriesOnEmptyPep = 0;
373 }
374 if (deviceIds.contains(getOwnDeviceId())) {
375 deviceIds.remove(getOwnDeviceId());
376 } else {
377 publishOwnDeviceId(deviceIds);
378 }
379 for (Integer deviceId : deviceIds) {
380 AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
381 if (sessions.get(ownDeviceAddress) == null) {
382 buildSessionFromPEP(ownDeviceAddress);
383 }
384 }
385 }
386 Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toPreppedString()));
387 expiredDevices.removeAll(deviceIds);
388 for (Integer deviceId : expiredDevices) {
389 AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
390 XmppAxolotlSession session = sessions.get(address);
391 if (session != null && session.getFingerprint() != null) {
392 if (session.getTrust().isActive()) {
393 session.setTrust(session.getTrust().toInactive());
394 }
395 }
396 }
397 Set<Integer> newDevices = new HashSet<>(deviceIds);
398 for (Integer deviceId : newDevices) {
399 AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
400 XmppAxolotlSession session = sessions.get(address);
401 if (session != null && session.getFingerprint() != null) {
402 if (!session.getTrust().isActive()) {
403 session.setTrust(session.getTrust().toActive());
404 }
405 }
406 }
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.setFingerprintStatus(fingerprint.replaceAll("\\s", ""), FingerprintStatus.createCompromised());
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 enum AxolotlCapability {
649 FULL,
650 MISSING_PRESENCE,
651 MISSING_KEYS,
652 WRONG_CONFIGURATION,
653 NO_MEMBERS
654 }
655
656 public boolean isConversationAxolotlCapable(Conversation conversation) {
657 return isConversationAxolotlCapableDetailed(conversation).first == AxolotlCapability.FULL;
658 }
659
660 public Pair<AxolotlCapability,Jid> isConversationAxolotlCapableDetailed(Conversation conversation) {
661 if (conversation.getMode() == Conversation.MODE_SINGLE
662 || (conversation.getMucOptions().membersOnly() && conversation.getMucOptions().nonanonymous())) {
663 final List<Jid> jids = getCryptoTargets(conversation);
664 for(Jid jid : jids) {
665 if (!hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty())) {
666 if (conversation.getAccount().getRoster().getContact(jid).mutualPresenceSubscription()) {
667 return new Pair<>(AxolotlCapability.MISSING_KEYS,jid);
668 } else {
669 return new Pair<>(AxolotlCapability.MISSING_PRESENCE,jid);
670 }
671 }
672 }
673 if (jids.size() > 0) {
674 return new Pair<>(AxolotlCapability.FULL, null);
675 } else {
676 return new Pair<>(AxolotlCapability.NO_MEMBERS, null);
677 }
678 } else {
679 return new Pair<>(AxolotlCapability.WRONG_CONFIGURATION, null);
680 }
681 }
682
683 public List<Jid> getCryptoTargets(Conversation conversation) {
684 final List<Jid> jids;
685 if (conversation.getMode() == Conversation.MODE_SINGLE) {
686 jids = Arrays.asList(conversation.getJid().toBareJid());
687 } else {
688 jids = conversation.getMucOptions().getMembers();
689 }
690 return jids;
691 }
692
693 public FingerprintStatus getFingerprintTrust(String fingerprint) {
694 return axolotlStore.getFingerprintStatus(fingerprint);
695 }
696
697 public X509Certificate getFingerprintCertificate(String fingerprint) {
698 return axolotlStore.getFingerprintCertificate(fingerprint);
699 }
700
701 public void setFingerprintTrust(String fingerprint, FingerprintStatus status) {
702 axolotlStore.setFingerprintStatus(fingerprint, status);
703 }
704
705 private void verifySessionWithPEP(final XmppAxolotlSession session) {
706 Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
707 final AxolotlAddress address = session.getRemoteAddress();
708 final IdentityKey identityKey = session.getIdentityKey();
709 try {
710 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId());
711 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
712 @Override
713 public void onIqPacketReceived(Account account, IqPacket packet) {
714 Pair<X509Certificate[],byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
715 if (verification != null) {
716 try {
717 Signature verifier = Signature.getInstance("sha256WithRSA");
718 verifier.initVerify(verification.first[0]);
719 verifier.update(identityKey.serialize());
720 if (verifier.verify(verification.second)) {
721 try {
722 mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
723 String fingerprint = session.getFingerprint();
724 Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+fingerprint);
725 setFingerprintTrust(fingerprint, FingerprintStatus.createActiveVerified(true));
726 axolotlStore.setFingerprintCertificate(fingerprint, verification.first[0]);
727 fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
728 Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
729 try {
730 final String cn = information.getString("subject_cn");
731 final Jid jid = Jid.fromString(address.getName());
732 Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
733 account.getRoster().getContact(jid).setCommonName(cn);
734 } catch (final InvalidJidException ignored) {
735 //ignored
736 }
737 finishBuildingSessionsFromPEP(address);
738 return;
739 } catch (Exception e) {
740 Log.d(Config.LOGTAG,"could not verify certificate");
741 }
742 }
743 } catch (Exception e) {
744 Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
745 }
746 } else {
747 Log.d(Config.LOGTAG,"no verification found");
748 }
749 fetchStatusMap.put(address, FetchStatus.SUCCESS);
750 finishBuildingSessionsFromPEP(address);
751 }
752 });
753 } catch (InvalidJidException e) {
754 fetchStatusMap.put(address, FetchStatus.SUCCESS);
755 finishBuildingSessionsFromPEP(address);
756 }
757 }
758
759 private void finishBuildingSessionsFromPEP(final AxolotlAddress address) {
760 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
761 Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress);
762 Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address);
763 if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
764 FetchStatus report = null;
765 if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
766 report = FetchStatus.SUCCESS;
767 } else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
768 report = FetchStatus.SUCCESS_VERIFIED;
769 } else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
770 report = FetchStatus.ERROR;
771 }
772 mXmppConnectionService.keyStatusUpdated(report);
773 }
774 }
775
776 private void buildSessionFromPEP(final AxolotlAddress address) {
777 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString());
778 if (address.getDeviceId() == getOwnDeviceId()) {
779 throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
780 }
781
782 try {
783 IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
784 Jid.fromString(address.getName()), address.getDeviceId());
785 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
786 mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
787
788 @Override
789 public void onIqPacketReceived(Account account, IqPacket packet) {
790 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
791 fetchStatusMap.put(address, FetchStatus.TIMEOUT);
792 } else if (packet.getType() == IqPacket.TYPE.RESULT) {
793 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
794 final IqParser parser = mXmppConnectionService.getIqParser();
795 final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
796 final PreKeyBundle bundle = parser.bundle(packet);
797 if (preKeyBundleList.isEmpty() || bundle == null) {
798 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
799 fetchStatusMap.put(address, FetchStatus.ERROR);
800 finishBuildingSessionsFromPEP(address);
801 return;
802 }
803 Random random = new Random();
804 final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
805 if (preKey == null) {
806 //should never happen
807 fetchStatusMap.put(address, FetchStatus.ERROR);
808 finishBuildingSessionsFromPEP(address);
809 return;
810 }
811
812 final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
813 preKey.getPreKeyId(), preKey.getPreKey(),
814 bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
815 bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
816
817 try {
818 SessionBuilder builder = new SessionBuilder(axolotlStore, address);
819 builder.process(preKeyBundle);
820 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
821 sessions.put(address, session);
822 if (Config.X509_VERIFICATION) {
823 verifySessionWithPEP(session);
824 } else {
825 FingerprintStatus status = getFingerprintTrust(bundle.getIdentityKey().getFingerprint().replaceAll("\\s",""));
826 boolean verified = status != null && status.isVerified();
827 fetchStatusMap.put(address, verified ? FetchStatus.SUCCESS_VERIFIED : FetchStatus.SUCCESS);
828 finishBuildingSessionsFromPEP(address);
829 }
830 } catch (UntrustedIdentityException | InvalidKeyException e) {
831 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
832 + e.getClass().getName() + ", " + e.getMessage());
833 fetchStatusMap.put(address, FetchStatus.ERROR);
834 finishBuildingSessionsFromPEP(address);
835 }
836 } else {
837 fetchStatusMap.put(address, FetchStatus.ERROR);
838 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
839 finishBuildingSessionsFromPEP(address);
840 }
841 }
842 });
843 } catch (InvalidJidException e) {
844 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
845 }
846 }
847
848 public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
849 Set<AxolotlAddress> addresses = new HashSet<>();
850 for(Jid jid : getCryptoTargets(conversation)) {
851 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
852 if (deviceIds.get(jid) != null) {
853 for (Integer foreignId : this.deviceIds.get(jid)) {
854 AxolotlAddress address = new AxolotlAddress(jid.toString(), foreignId);
855 if (sessions.get(address) == null) {
856 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
857 if (identityKey != null) {
858 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
859 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
860 sessions.put(address, session);
861 } else {
862 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + jid + ":" + foreignId);
863 if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
864 addresses.add(address);
865 } else {
866 Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
867 }
868 }
869 }
870 }
871 } else {
872 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
873 }
874 }
875 if (deviceIds.get(account.getJid().toBareJid()) != null) {
876 for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
877 AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), ownId);
878 if (sessions.get(address) == null) {
879 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
880 if (identityKey != null) {
881 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
882 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
883 sessions.put(address, session);
884 } else {
885 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
886 if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
887 addresses.add(address);
888 } else {
889 Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken");
890 }
891 }
892 }
893 }
894 }
895
896 return addresses;
897 }
898
899 public boolean createSessionsIfNeeded(final Conversation conversation) {
900 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
901 boolean newSessions = false;
902 Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
903 for (AxolotlAddress address : addresses) {
904 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
905 FetchStatus status = fetchStatusMap.get(address);
906 if (status == null || status == FetchStatus.TIMEOUT) {
907 fetchStatusMap.put(address, FetchStatus.PENDING);
908 this.buildSessionFromPEP(address);
909 newSessions = true;
910 } else if (status == FetchStatus.PENDING) {
911 newSessions = true;
912 } else {
913 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
914 }
915 }
916
917 return newSessions;
918 }
919
920 public boolean trustedSessionVerified(final Conversation conversation) {
921 Set<XmppAxolotlSession> sessions = findSessionsForConversation(conversation);
922 sessions.addAll(findOwnSessions());
923 boolean verified = false;
924 for(XmppAxolotlSession session : sessions) {
925 if (session.getTrust().isTrustedAndActive()) {
926 if (session.getTrust().getTrust() == FingerprintStatus.Trust.VERIFIED_X509) {
927 verified = true;
928 } else {
929 return false;
930 }
931 }
932 }
933 return verified;
934 }
935
936 public boolean hasPendingKeyFetches(Account account, List<Jid> jids) {
937 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
938 if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)) {
939 return true;
940 }
941 for(Jid jid : jids) {
942 AxolotlAddress foreignAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), 0);
943 if (fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
944 return true;
945 }
946 }
947 return false;
948 }
949
950 @Nullable
951 private XmppAxolotlMessage buildHeader(Conversation conversation) {
952 final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
953 account.getJid().toBareJid(), getOwnDeviceId());
954
955 Set<XmppAxolotlSession> remoteSessions = findSessionsForConversation(conversation);
956 Set<XmppAxolotlSession> ownSessions = findOwnSessions();
957 if (remoteSessions.isEmpty()) {
958 return null;
959 }
960 for (XmppAxolotlSession session : remoteSessions) {
961 axolotlMessage.addDevice(session);
962 }
963 for (XmppAxolotlSession session : ownSessions) {
964 axolotlMessage.addDevice(session);
965 }
966
967 return axolotlMessage;
968 }
969
970 @Nullable
971 public XmppAxolotlMessage encrypt(Message message) {
972 XmppAxolotlMessage axolotlMessage = buildHeader(message.getConversation());
973
974 if (axolotlMessage != null) {
975 final String content;
976 if (message.hasFileOnRemoteHost()) {
977 content = message.getFileParams().url.toString();
978 } else {
979 content = message.getBody();
980 }
981 try {
982 axolotlMessage.encrypt(content);
983 } catch (CryptoFailedException e) {
984 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
985 return null;
986 }
987 }
988
989 return axolotlMessage;
990 }
991
992 public void preparePayloadMessage(final Message message, final boolean delay) {
993 executor.execute(new Runnable() {
994 @Override
995 public void run() {
996 XmppAxolotlMessage axolotlMessage = encrypt(message);
997 if (axolotlMessage == null) {
998 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
999 //mXmppConnectionService.updateConversationUi();
1000 } else {
1001 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
1002 messageCache.put(message.getUuid(), axolotlMessage);
1003 mXmppConnectionService.resendMessage(message, delay);
1004 }
1005 }
1006 });
1007 }
1008
1009 public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
1010 executor.execute(new Runnable() {
1011 @Override
1012 public void run() {
1013 XmppAxolotlMessage axolotlMessage = buildHeader(conversation);
1014 onMessageCreatedCallback.run(axolotlMessage);
1015 }
1016 });
1017 }
1018
1019 public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
1020 XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
1021 if (axolotlMessage != null) {
1022 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
1023 messageCache.remove(message.getUuid());
1024 } else {
1025 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
1026 }
1027 return axolotlMessage;
1028 }
1029
1030 private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
1031 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1032 return (identityKey != null)
1033 ? new XmppAxolotlSession(account, axolotlStore, address, identityKey)
1034 : null;
1035 }
1036
1037 private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
1038 AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
1039 message.getSenderDeviceId());
1040 XmppAxolotlSession session = sessions.get(senderAddress);
1041 if (session == null) {
1042 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
1043 session = recreateUncachedSession(senderAddress);
1044 if (session == null) {
1045 session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1046 }
1047 }
1048 return session;
1049 }
1050
1051 public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
1052 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1053
1054 XmppAxolotlSession session = getReceivingSession(message);
1055 try {
1056 plaintextMessage = message.decrypt(session, getOwnDeviceId());
1057 Integer preKeyId = session.getPreKeyId();
1058 if (preKeyId != null) {
1059 publishBundlesIfNeeded(false, false);
1060 session.resetPreKeyId();
1061 }
1062 } catch (CryptoFailedException e) {
1063 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
1064 }
1065
1066 if (session.isFresh() && plaintextMessage != null) {
1067 putFreshSession(session);
1068 }
1069
1070 return plaintextMessage;
1071 }
1072
1073 public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
1074 XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
1075
1076 XmppAxolotlSession session = getReceivingSession(message);
1077 keyTransportMessage = message.getParameters(session, getOwnDeviceId());
1078
1079 if (session.isFresh() && keyTransportMessage != null) {
1080 putFreshSession(session);
1081 }
1082
1083 return keyTransportMessage;
1084 }
1085
1086 private void putFreshSession(XmppAxolotlSession session) {
1087 Log.d(Config.LOGTAG,"put fresh session");
1088 sessions.put(session);
1089 if (Config.X509_VERIFICATION) {
1090 if (session.getIdentityKey() != null) {
1091 verifySessionWithPEP(session);
1092 } else {
1093 Log.e(Config.LOGTAG,account.getJid().toBareJid()+": identity key was empty after reloading for x509 verification");
1094 }
1095 }
1096 }
1097}