1package eu.siacs.conversations.crypto.axolotl;
2
3import android.support.annotation.NonNull;
4import android.support.annotation.Nullable;
5import android.util.Log;
6
7import org.bouncycastle.jce.provider.BouncyCastleProvider;
8import org.whispersystems.libaxolotl.AxolotlAddress;
9import org.whispersystems.libaxolotl.IdentityKey;
10import org.whispersystems.libaxolotl.IdentityKeyPair;
11import org.whispersystems.libaxolotl.InvalidKeyException;
12import org.whispersystems.libaxolotl.InvalidKeyIdException;
13import org.whispersystems.libaxolotl.SessionBuilder;
14import org.whispersystems.libaxolotl.UntrustedIdentityException;
15import org.whispersystems.libaxolotl.ecc.ECPublicKey;
16import org.whispersystems.libaxolotl.state.PreKeyBundle;
17import org.whispersystems.libaxolotl.state.PreKeyRecord;
18import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
19import org.whispersystems.libaxolotl.util.KeyHelper;
20
21import java.security.Security;
22import java.util.Arrays;
23import java.util.HashMap;
24import java.util.HashSet;
25import java.util.List;
26import java.util.Map;
27import java.util.Random;
28import java.util.Set;
29
30import eu.siacs.conversations.Config;
31import eu.siacs.conversations.entities.Account;
32import eu.siacs.conversations.entities.Contact;
33import eu.siacs.conversations.entities.Conversation;
34import eu.siacs.conversations.entities.Message;
35import eu.siacs.conversations.parser.IqParser;
36import eu.siacs.conversations.services.XmppConnectionService;
37import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
38import eu.siacs.conversations.xml.Element;
39import eu.siacs.conversations.xmpp.OnIqPacketReceived;
40import eu.siacs.conversations.xmpp.jid.InvalidJidException;
41import eu.siacs.conversations.xmpp.jid.Jid;
42import eu.siacs.conversations.xmpp.stanzas.IqPacket;
43
44public class AxolotlService {
45
46 public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
47 public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
48 public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
49
50 public static final String LOGPREFIX = "AxolotlService";
51
52 public static final int NUM_KEYS_TO_PUBLISH = 100;
53 public static final int publishTriesThreshold = 3;
54
55 private final Account account;
56 private final XmppConnectionService mXmppConnectionService;
57 private final SQLiteAxolotlStore axolotlStore;
58 private final SessionMap sessions;
59 private final Map<Jid, Set<Integer>> deviceIds;
60 private final Map<String, XmppAxolotlMessage> messageCache;
61 private final FetchStatusMap fetchStatusMap;
62 private final SerialSingleThreadExecutor executor;
63 private int numPublishTriesOnEmptyPep = 0;
64 private boolean pepBroken = false;
65
66 private static class AxolotlAddressMap<T> {
67 protected Map<String, Map<Integer, T>> map;
68 protected final Object MAP_LOCK = new Object();
69
70 public AxolotlAddressMap() {
71 this.map = new HashMap<>();
72 }
73
74 public void put(AxolotlAddress address, T value) {
75 synchronized (MAP_LOCK) {
76 Map<Integer, T> devices = map.get(address.getName());
77 if (devices == null) {
78 devices = new HashMap<>();
79 map.put(address.getName(), devices);
80 }
81 devices.put(address.getDeviceId(), value);
82 }
83 }
84
85 public T get(AxolotlAddress address) {
86 synchronized (MAP_LOCK) {
87 Map<Integer, T> devices = map.get(address.getName());
88 if (devices == null) {
89 return null;
90 }
91 return devices.get(address.getDeviceId());
92 }
93 }
94
95 public Map<Integer, T> getAll(AxolotlAddress address) {
96 synchronized (MAP_LOCK) {
97 Map<Integer, T> devices = map.get(address.getName());
98 if (devices == null) {
99 return new HashMap<>();
100 }
101 return devices;
102 }
103 }
104
105 public boolean hasAny(AxolotlAddress address) {
106 synchronized (MAP_LOCK) {
107 Map<Integer, T> devices = map.get(address.getName());
108 return devices != null && !devices.isEmpty();
109 }
110 }
111
112 public void clear() {
113 map.clear();
114 }
115
116 }
117
118 private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
119 private final XmppConnectionService xmppConnectionService;
120 private final Account account;
121
122 public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
123 super();
124 this.xmppConnectionService = service;
125 this.account = account;
126 this.fillMap(store);
127 }
128
129 private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
130 for (Integer deviceId : deviceIds) {
131 AxolotlAddress axolotlAddress = new AxolotlAddress(bareJid, deviceId);
132 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building session for remote address: " + axolotlAddress.toString());
133 String fingerprint = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey().getFingerprint().replaceAll("\\s", "");
134 this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, fingerprint));
135 }
136 }
137
138 private void fillMap(SQLiteAxolotlStore store) {
139 List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toString());
140 putDevicesForJid(account.getJid().toBareJid().toString(), deviceIds, store);
141 for (Contact contact : account.getRoster().getContacts()) {
142 Jid bareJid = contact.getJid().toBareJid();
143 if (bareJid == null) {
144 continue; // FIXME: handle this?
145 }
146 String address = bareJid.toString();
147 deviceIds = store.getSubDeviceSessions(address);
148 putDevicesForJid(address, deviceIds, store);
149 }
150
151 }
152
153 @Override
154 public void put(AxolotlAddress address, XmppAxolotlSession value) {
155 super.put(address, value);
156 value.setNotFresh();
157 xmppConnectionService.syncRosterToDisk(account);
158 }
159
160 public void put(XmppAxolotlSession session) {
161 this.put(session.getRemoteAddress(), session);
162 }
163 }
164
165 private static enum FetchStatus {
166 PENDING,
167 SUCCESS,
168 ERROR
169 }
170
171 private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
172
173 }
174
175 public static String getLogprefix(Account account) {
176 return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): ";
177 }
178
179 public AxolotlService(Account account, XmppConnectionService connectionService) {
180 if (Security.getProvider("BC") == null) {
181 Security.addProvider(new BouncyCastleProvider());
182 }
183 this.mXmppConnectionService = connectionService;
184 this.account = account;
185 this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
186 this.deviceIds = new HashMap<>();
187 this.messageCache = new HashMap<>();
188 this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
189 this.fetchStatusMap = new FetchStatusMap();
190 this.executor = new SerialSingleThreadExecutor();
191 }
192
193 public String getOwnFingerprint() {
194 return axolotlStore.getIdentityKeyPair().getPublicKey().getFingerprint().replaceAll("\\s", "");
195 }
196
197 public Set<IdentityKey> getKeysWithTrust(XmppAxolotlSession.Trust trust) {
198 return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toString(), trust);
199 }
200
201 public Set<IdentityKey> getKeysWithTrust(XmppAxolotlSession.Trust trust, Contact contact) {
202 return axolotlStore.getContactKeysWithTrust(contact.getJid().toBareJid().toString(), trust);
203 }
204
205 public long getNumTrustedKeys(Contact contact) {
206 return axolotlStore.getContactNumTrustedKeys(contact.getJid().toBareJid().toString());
207 }
208
209 private AxolotlAddress getAddressForJid(Jid jid) {
210 return new AxolotlAddress(jid.toString(), 0);
211 }
212
213 private Set<XmppAxolotlSession> findOwnSessions() {
214 AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
215 Set<XmppAxolotlSession> ownDeviceSessions = new HashSet<>(this.sessions.getAll(ownAddress).values());
216 return ownDeviceSessions;
217 }
218
219 private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
220 AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
221 Set<XmppAxolotlSession> sessions = new HashSet<>(this.sessions.getAll(contactAddress).values());
222 return sessions;
223 }
224
225 public Set<String> getFingerprintsForOwnSessions() {
226 Set<String> fingerprints = new HashSet<>();
227 for (XmppAxolotlSession session : findOwnSessions()) {
228 fingerprints.add(session.getFingerprint());
229 }
230 return fingerprints;
231 }
232
233 public Set<String> getFingerprintsForContact(final Contact contact) {
234 Set<String> fingerprints = new HashSet<>();
235 for (XmppAxolotlSession session : findSessionsforContact(contact)) {
236 fingerprints.add(session.getFingerprint());
237 }
238 return fingerprints;
239 }
240
241 private boolean hasAny(Contact contact) {
242 AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
243 return sessions.hasAny(contactAddress);
244 }
245
246 public boolean isPepBroken() {
247 return this.pepBroken;
248 }
249
250 public void regenerateKeys() {
251 axolotlStore.regenerate();
252 sessions.clear();
253 fetchStatusMap.clear();
254 publishBundlesIfNeeded(true);
255 }
256
257 public int getOwnDeviceId() {
258 return axolotlStore.getLocalRegistrationId();
259 }
260
261 public Set<Integer> getOwnDeviceIds() {
262 return this.deviceIds.get(account.getJid().toBareJid());
263 }
264
265 private void setTrustOnSessions(final Jid jid, @NonNull final Set<Integer> deviceIds,
266 final XmppAxolotlSession.Trust from,
267 final XmppAxolotlSession.Trust to) {
268 for (Integer deviceId : deviceIds) {
269 AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
270 XmppAxolotlSession session = sessions.get(address);
271 if (session != null && session.getFingerprint() != null
272 && session.getTrust() == from) {
273 session.setTrust(to);
274 }
275 }
276 }
277
278 public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
279 if (jid.toBareJid().equals(account.getJid().toBareJid())) {
280 if (!deviceIds.isEmpty()) {
281 Log.d(Config.LOGTAG, getLogprefix(account) + "Received non-empty own device list. Resetting publish attemps and pepBroken status.");
282 pepBroken = false;
283 numPublishTriesOnEmptyPep = 0;
284 }
285 if (deviceIds.contains(getOwnDeviceId())) {
286 deviceIds.remove(getOwnDeviceId());
287 } else {
288 publishOwnDeviceId(deviceIds);
289 }
290 for (Integer deviceId : deviceIds) {
291 AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
292 if (sessions.get(ownDeviceAddress) == null) {
293 buildSessionFromPEP(ownDeviceAddress);
294 }
295 }
296 }
297 Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toString()));
298 expiredDevices.removeAll(deviceIds);
299 setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.TRUSTED,
300 XmppAxolotlSession.Trust.INACTIVE_TRUSTED);
301 setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.UNDECIDED,
302 XmppAxolotlSession.Trust.INACTIVE_UNDECIDED);
303 setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.UNTRUSTED,
304 XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED);
305 Set<Integer> newDevices = new HashSet<>(deviceIds);
306 setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_TRUSTED,
307 XmppAxolotlSession.Trust.TRUSTED);
308 setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNDECIDED,
309 XmppAxolotlSession.Trust.UNDECIDED);
310 setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED,
311 XmppAxolotlSession.Trust.UNTRUSTED);
312 this.deviceIds.put(jid, deviceIds);
313 mXmppConnectionService.keyStatusUpdated();
314 }
315
316 public void wipeOtherPepDevices() {
317 if (pepBroken) {
318 Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
319 return;
320 }
321 Set<Integer> deviceIds = new HashSet<>();
322 deviceIds.add(getOwnDeviceId());
323 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
324 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Wiping all other devices from Pep:" + publish);
325 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
326 @Override
327 public void onIqPacketReceived(Account account, IqPacket packet) {
328 // TODO: implement this!
329 }
330 });
331 }
332
333 public void purgeKey(final String fingerprint) {
334 axolotlStore.setFingerprintTrust(fingerprint.replaceAll("\\s", ""), XmppAxolotlSession.Trust.COMPROMISED);
335 }
336
337 public void publishOwnDeviceIdIfNeeded() {
338 if (pepBroken) {
339 Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
340 return;
341 }
342 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
343 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
344 @Override
345 public void onIqPacketReceived(Account account, IqPacket packet) {
346 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
347 Log.d(Config.LOGTAG, getLogprefix(account) + "Timeout received while retrieving own Device Ids.");
348 } else {
349 Element item = mXmppConnectionService.getIqParser().getItem(packet);
350 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
351 if (!deviceIds.contains(getOwnDeviceId())) {
352 publishOwnDeviceId(deviceIds);
353 }
354 }
355 }
356 });
357 }
358
359 public void publishOwnDeviceId(Set<Integer> deviceIds) {
360 Set<Integer> deviceIdsCopy = new HashSet<>(deviceIds);
361 if (!deviceIdsCopy.contains(getOwnDeviceId())) {
362 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Own device " + getOwnDeviceId() + " not in PEP devicelist.");
363 if (deviceIdsCopy.isEmpty()) {
364 if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
365 Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
366 pepBroken = true;
367 return;
368 } else {
369 numPublishTriesOnEmptyPep++;
370 Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
371 }
372 } else {
373 numPublishTriesOnEmptyPep = 0;
374 }
375 deviceIdsCopy.add(getOwnDeviceId());
376 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIdsCopy);
377 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
378 @Override
379 public void onIqPacketReceived(Account account, IqPacket packet) {
380 if (packet.getType() != IqPacket.TYPE.RESULT) {
381 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
382 }
383 }
384 });
385 }
386 }
387
388 public void publishBundlesIfNeeded(final boolean announceAfter) {
389 if (pepBroken) {
390 Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
391 return;
392 }
393 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
394 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
395 @Override
396 public void onIqPacketReceived(Account account, IqPacket packet) {
397
398 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
399 return; //ignore timeout. do nothing
400 }
401
402 if (packet.getType() == IqPacket.TYPE.ERROR) {
403 Element error = packet.findChild("error");
404 if (error == null || !error.hasChild("item-not-found")) {
405 pepBroken = true;
406 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
407 return;
408 }
409 }
410
411 PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
412 Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
413 boolean flush = false;
414 if (bundle == null) {
415 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
416 bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
417 flush = true;
418 }
419 if (keys == null) {
420 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
421 }
422 try {
423 boolean changed = false;
424 // Validate IdentityKey
425 IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
426 if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
427 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
428 changed = true;
429 }
430
431 // Validate signedPreKeyRecord + ID
432 SignedPreKeyRecord signedPreKeyRecord;
433 int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
434 try {
435 signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
436 if (flush
437 || !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
438 || !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
439 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
440 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
441 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
442 changed = true;
443 }
444 } catch (InvalidKeyIdException e) {
445 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
446 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
447 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
448 changed = true;
449 }
450
451 // Validate PreKeys
452 Set<PreKeyRecord> preKeyRecords = new HashSet<>();
453 if (keys != null) {
454 for (Integer id : keys.keySet()) {
455 try {
456 PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
457 if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
458 preKeyRecords.add(preKeyRecord);
459 }
460 } catch (InvalidKeyIdException ignored) {
461 }
462 }
463 }
464 int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
465 if (newKeys > 0) {
466 List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
467 axolotlStore.getCurrentPreKeyId() + 1, newKeys);
468 preKeyRecords.addAll(newRecords);
469 for (PreKeyRecord record : newRecords) {
470 axolotlStore.storePreKey(record.getId(), record);
471 }
472 changed = true;
473 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
474 }
475
476
477 if (changed) {
478 IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
479 signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
480 preKeyRecords, getOwnDeviceId());
481 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
482 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
483 @Override
484 public void onIqPacketReceived(Account account, IqPacket packet) {
485 if (packet.getType() == IqPacket.TYPE.RESULT) {
486 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
487 if (announceAfter) {
488 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
489 publishOwnDeviceIdIfNeeded();
490 }
491 } else {
492 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
493 }
494 }
495 });
496 } else {
497 Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
498 if (announceAfter) {
499 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
500 publishOwnDeviceIdIfNeeded();
501 }
502 }
503 } catch (InvalidKeyException e) {
504 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
505 return;
506 }
507 }
508 });
509 }
510
511 public boolean isContactAxolotlCapable(Contact contact) {
512
513 Jid jid = contact.getJid().toBareJid();
514 AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
515 return sessions.hasAny(address) ||
516 (deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
517 }
518
519 public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
520 return axolotlStore.getFingerprintTrust(fingerprint);
521 }
522
523 public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
524 axolotlStore.setFingerprintTrust(fingerprint, trust);
525 }
526
527 private void buildSessionFromPEP(final AxolotlAddress address) {
528 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString());
529 if (address.getDeviceId() == getOwnDeviceId()) {
530 throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
531 }
532
533 try {
534 IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
535 Jid.fromString(address.getName()), address.getDeviceId());
536 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
537 mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
538 private void finish() {
539 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
540 if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
541 && !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
542 mXmppConnectionService.keyStatusUpdated();
543 }
544 }
545
546 @Override
547 public void onIqPacketReceived(Account account, IqPacket packet) {
548 if (packet.getType() == IqPacket.TYPE.RESULT) {
549 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
550 final IqParser parser = mXmppConnectionService.getIqParser();
551 final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
552 final PreKeyBundle bundle = parser.bundle(packet);
553 if (preKeyBundleList.isEmpty() || bundle == null) {
554 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
555 fetchStatusMap.put(address, FetchStatus.ERROR);
556 finish();
557 return;
558 }
559 Random random = new Random();
560 final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
561 if (preKey == null) {
562 //should never happen
563 fetchStatusMap.put(address, FetchStatus.ERROR);
564 finish();
565 return;
566 }
567
568 final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
569 preKey.getPreKeyId(), preKey.getPreKey(),
570 bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
571 bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
572
573 try {
574 SessionBuilder builder = new SessionBuilder(axolotlStore, address);
575 builder.process(preKeyBundle);
576 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
577 sessions.put(address, session);
578 fetchStatusMap.put(address, FetchStatus.SUCCESS);
579 } catch (UntrustedIdentityException | InvalidKeyException e) {
580 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
581 + e.getClass().getName() + ", " + e.getMessage());
582 fetchStatusMap.put(address, FetchStatus.ERROR);
583 }
584
585 finish();
586 } else {
587 fetchStatusMap.put(address, FetchStatus.ERROR);
588 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
589 finish();
590 return;
591 }
592 }
593 });
594 } catch (InvalidJidException e) {
595 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
596 }
597 }
598
599 public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
600 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid());
601 Jid contactJid = conversation.getContact().getJid().toBareJid();
602 Set<AxolotlAddress> addresses = new HashSet<>();
603 if (deviceIds.get(contactJid) != null) {
604 for (Integer foreignId : this.deviceIds.get(contactJid)) {
605 AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
606 if (sessions.get(address) == null) {
607 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
608 if (identityKey != null) {
609 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
610 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
611 sessions.put(address, session);
612 } else {
613 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
614 addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
615 }
616 }
617 }
618 } else {
619 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
620 }
621 if (deviceIds.get(account.getJid().toBareJid()) != null) {
622 for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
623 AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
624 if (sessions.get(address) == null) {
625 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
626 if (identityKey != null) {
627 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
628 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
629 sessions.put(address, session);
630 } else {
631 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
632 addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
633 }
634 }
635 }
636 }
637
638 return addresses;
639 }
640
641 public boolean createSessionsIfNeeded(final Conversation conversation) {
642 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
643 boolean newSessions = false;
644 Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
645 for (AxolotlAddress address : addresses) {
646 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
647 FetchStatus status = fetchStatusMap.get(address);
648 if (status == null || status == FetchStatus.ERROR) {
649 fetchStatusMap.put(address, FetchStatus.PENDING);
650 this.buildSessionFromPEP(address);
651 newSessions = true;
652 } else if (status == FetchStatus.PENDING) {
653 newSessions = true;
654 } else {
655 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
656 }
657 }
658
659 return newSessions;
660 }
661
662 public boolean hasPendingKeyFetches(Conversation conversation) {
663 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
664 AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(), 0);
665 return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
666 || fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
667
668 }
669
670 @Nullable
671 private XmppAxolotlMessage buildHeader(Contact contact) {
672 final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
673 contact.getJid().toBareJid(), getOwnDeviceId());
674
675 Set<XmppAxolotlSession> contactSessions = findSessionsforContact(contact);
676 Set<XmppAxolotlSession> ownSessions = findOwnSessions();
677 if (contactSessions.isEmpty()) {
678 return null;
679 }
680 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl foreign keyElements...");
681 for (XmppAxolotlSession session : contactSessions) {
682 Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
683 axolotlMessage.addDevice(session);
684 }
685 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl own keyElements...");
686 for (XmppAxolotlSession session : ownSessions) {
687 Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
688 axolotlMessage.addDevice(session);
689 }
690
691 return axolotlMessage;
692 }
693
694 @Nullable
695 public XmppAxolotlMessage encrypt(Message message) {
696 XmppAxolotlMessage axolotlMessage = buildHeader(message.getContact());
697
698 if (axolotlMessage != null) {
699 final String content;
700 if (message.hasFileOnRemoteHost()) {
701 content = message.getFileParams().url.toString();
702 } else {
703 content = message.getBody();
704 }
705 try {
706 axolotlMessage.encrypt(content);
707 } catch (CryptoFailedException e) {
708 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
709 return null;
710 }
711 }
712
713 return axolotlMessage;
714 }
715
716 public void preparePayloadMessage(final Message message, final boolean delay) {
717 executor.execute(new Runnable() {
718 @Override
719 public void run() {
720 XmppAxolotlMessage axolotlMessage = encrypt(message);
721 if (axolotlMessage == null) {
722 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
723 //mXmppConnectionService.updateConversationUi();
724 } else {
725 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
726 messageCache.put(message.getUuid(), axolotlMessage);
727 mXmppConnectionService.resendMessage(message, delay);
728 }
729 }
730 });
731 }
732
733 public void prepareKeyTransportMessage(final Contact contact, final OnMessageCreatedCallback onMessageCreatedCallback) {
734 executor.execute(new Runnable() {
735 @Override
736 public void run() {
737 XmppAxolotlMessage axolotlMessage = buildHeader(contact);
738 onMessageCreatedCallback.run(axolotlMessage);
739 }
740 });
741 }
742
743 public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
744 XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
745 if (axolotlMessage != null) {
746 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
747 messageCache.remove(message.getUuid());
748 } else {
749 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
750 }
751 return axolotlMessage;
752 }
753
754 private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
755 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
756 return (identityKey != null)
757 ? new XmppAxolotlSession(account, axolotlStore, address,
758 identityKey.getFingerprint().replaceAll("\\s", ""))
759 : null;
760 }
761
762 private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
763 AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
764 message.getSenderDeviceId());
765 XmppAxolotlSession session = sessions.get(senderAddress);
766 if (session == null) {
767 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
768 session = recreateUncachedSession(senderAddress);
769 if (session == null) {
770 session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
771 }
772 }
773 return session;
774 }
775
776 public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
777 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
778
779 XmppAxolotlSession session = getReceivingSession(message);
780 try {
781 plaintextMessage = message.decrypt(session, getOwnDeviceId());
782 Integer preKeyId = session.getPreKeyId();
783 if (preKeyId != null) {
784 publishBundlesIfNeeded(false);
785 session.resetPreKeyId();
786 }
787 } catch (CryptoFailedException e) {
788 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
789 }
790
791 if (session.isFresh() && plaintextMessage != null) {
792 sessions.put(session);
793 }
794
795 return plaintextMessage;
796 }
797
798 public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
799 XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage = null;
800
801 XmppAxolotlSession session = getReceivingSession(message);
802 keyTransportMessage = message.getParameters(session, getOwnDeviceId());
803
804 if (session.isFresh() && keyTransportMessage != null) {
805 sessions.put(session);
806 }
807
808 return keyTransportMessage;
809 }
810}