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