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 PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
398 Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
399 boolean flush = false;
400 if (bundle == null) {
401 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
402 bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
403 flush = true;
404 }
405 if (keys == null) {
406 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
407 }
408 try {
409 boolean changed = false;
410 // Validate IdentityKey
411 IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
412 if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
413 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
414 changed = true;
415 }
416
417 // Validate signedPreKeyRecord + ID
418 SignedPreKeyRecord signedPreKeyRecord;
419 int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
420 try {
421 signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
422 if (flush
423 || !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
424 || !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
425 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
426 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
427 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
428 changed = true;
429 }
430 } catch (InvalidKeyIdException e) {
431 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
432 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
433 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
434 changed = true;
435 }
436
437 // Validate PreKeys
438 Set<PreKeyRecord> preKeyRecords = new HashSet<>();
439 if (keys != null) {
440 for (Integer id : keys.keySet()) {
441 try {
442 PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
443 if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
444 preKeyRecords.add(preKeyRecord);
445 }
446 } catch (InvalidKeyIdException ignored) {
447 }
448 }
449 }
450 int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
451 if (newKeys > 0) {
452 List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
453 axolotlStore.getCurrentPreKeyId() + 1, newKeys);
454 preKeyRecords.addAll(newRecords);
455 for (PreKeyRecord record : newRecords) {
456 axolotlStore.storePreKey(record.getId(), record);
457 }
458 changed = true;
459 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
460 }
461
462
463 if (changed) {
464 IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
465 signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
466 preKeyRecords, getOwnDeviceId());
467 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
468 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
469 @Override
470 public void onIqPacketReceived(Account account, IqPacket packet) {
471 if (packet.getType() == IqPacket.TYPE.RESULT) {
472 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
473 if (announceAfter) {
474 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
475 publishOwnDeviceIdIfNeeded();
476 }
477 } else {
478 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
479 }
480 }
481 });
482 } else {
483 Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
484 if (announceAfter) {
485 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
486 publishOwnDeviceIdIfNeeded();
487 }
488 }
489 } catch (InvalidKeyException e) {
490 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
491 return;
492 }
493 }
494 });
495 }
496
497 public boolean isContactAxolotlCapable(Contact contact) {
498
499 Jid jid = contact.getJid().toBareJid();
500 AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
501 return sessions.hasAny(address) ||
502 (deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
503 }
504
505 public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
506 return axolotlStore.getFingerprintTrust(fingerprint);
507 }
508
509 public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
510 axolotlStore.setFingerprintTrust(fingerprint, trust);
511 }
512
513 private void buildSessionFromPEP(final AxolotlAddress address) {
514 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString());
515 if (address.getDeviceId() == getOwnDeviceId()) {
516 throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
517 }
518
519 try {
520 IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
521 Jid.fromString(address.getName()), address.getDeviceId());
522 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
523 mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
524 private void finish() {
525 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
526 if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
527 && !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
528 mXmppConnectionService.keyStatusUpdated();
529 }
530 }
531
532 @Override
533 public void onIqPacketReceived(Account account, IqPacket packet) {
534 if (packet.getType() == IqPacket.TYPE.RESULT) {
535 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
536 final IqParser parser = mXmppConnectionService.getIqParser();
537 final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
538 final PreKeyBundle bundle = parser.bundle(packet);
539 if (preKeyBundleList.isEmpty() || bundle == null) {
540 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
541 fetchStatusMap.put(address, FetchStatus.ERROR);
542 finish();
543 return;
544 }
545 Random random = new Random();
546 final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
547 if (preKey == null) {
548 //should never happen
549 fetchStatusMap.put(address, FetchStatus.ERROR);
550 finish();
551 return;
552 }
553
554 final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
555 preKey.getPreKeyId(), preKey.getPreKey(),
556 bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
557 bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
558
559 try {
560 SessionBuilder builder = new SessionBuilder(axolotlStore, address);
561 builder.process(preKeyBundle);
562 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
563 sessions.put(address, session);
564 fetchStatusMap.put(address, FetchStatus.SUCCESS);
565 } catch (UntrustedIdentityException | InvalidKeyException e) {
566 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
567 + e.getClass().getName() + ", " + e.getMessage());
568 fetchStatusMap.put(address, FetchStatus.ERROR);
569 }
570
571 finish();
572 } else {
573 fetchStatusMap.put(address, FetchStatus.ERROR);
574 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
575 finish();
576 return;
577 }
578 }
579 });
580 } catch (InvalidJidException e) {
581 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
582 }
583 }
584
585 public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
586 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid());
587 Jid contactJid = conversation.getContact().getJid().toBareJid();
588 Set<AxolotlAddress> addresses = new HashSet<>();
589 if (deviceIds.get(contactJid) != null) {
590 for (Integer foreignId : this.deviceIds.get(contactJid)) {
591 AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
592 if (sessions.get(address) == null) {
593 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
594 if (identityKey != null) {
595 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
596 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
597 sessions.put(address, session);
598 } else {
599 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
600 addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
601 }
602 }
603 }
604 } else {
605 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
606 }
607 if (deviceIds.get(account.getJid().toBareJid()) != null) {
608 for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
609 AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
610 if (sessions.get(address) == null) {
611 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
612 if (identityKey != null) {
613 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
614 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
615 sessions.put(address, session);
616 } else {
617 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
618 addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
619 }
620 }
621 }
622 }
623
624 return addresses;
625 }
626
627 public boolean createSessionsIfNeeded(final Conversation conversation) {
628 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
629 boolean newSessions = false;
630 Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
631 for (AxolotlAddress address : addresses) {
632 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
633 FetchStatus status = fetchStatusMap.get(address);
634 if (status == null || status == FetchStatus.ERROR) {
635 fetchStatusMap.put(address, FetchStatus.PENDING);
636 this.buildSessionFromPEP(address);
637 newSessions = true;
638 } else if (status == FetchStatus.PENDING) {
639 newSessions = true;
640 } else {
641 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
642 }
643 }
644
645 return newSessions;
646 }
647
648 public boolean hasPendingKeyFetches(Conversation conversation) {
649 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
650 AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(), 0);
651 return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
652 || fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
653
654 }
655
656 @Nullable
657 private XmppAxolotlMessage buildHeader(Contact contact) {
658 final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
659 contact.getJid().toBareJid(), getOwnDeviceId());
660
661 Set<XmppAxolotlSession> contactSessions = findSessionsforContact(contact);
662 Set<XmppAxolotlSession> ownSessions = findOwnSessions();
663 if (contactSessions.isEmpty()) {
664 return null;
665 }
666 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl foreign keyElements...");
667 for (XmppAxolotlSession session : contactSessions) {
668 Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
669 axolotlMessage.addDevice(session);
670 }
671 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl own keyElements...");
672 for (XmppAxolotlSession session : ownSessions) {
673 Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
674 axolotlMessage.addDevice(session);
675 }
676
677 return axolotlMessage;
678 }
679
680 @Nullable
681 public XmppAxolotlMessage encrypt(Message message) {
682 XmppAxolotlMessage axolotlMessage = buildHeader(message.getContact());
683
684 if (axolotlMessage != null) {
685 final String content;
686 if (message.hasFileOnRemoteHost()) {
687 content = message.getFileParams().url.toString();
688 } else {
689 content = message.getBody();
690 }
691 try {
692 axolotlMessage.encrypt(content);
693 } catch (CryptoFailedException e) {
694 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
695 return null;
696 }
697 }
698
699 return axolotlMessage;
700 }
701
702 public void preparePayloadMessage(final Message message, final boolean delay) {
703 executor.execute(new Runnable() {
704 @Override
705 public void run() {
706 XmppAxolotlMessage axolotlMessage = encrypt(message);
707 if (axolotlMessage == null) {
708 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
709 //mXmppConnectionService.updateConversationUi();
710 } else {
711 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
712 messageCache.put(message.getUuid(), axolotlMessage);
713 mXmppConnectionService.resendMessage(message, delay);
714 }
715 }
716 });
717 }
718
719 public void prepareKeyTransportMessage(final Contact contact, final OnMessageCreatedCallback onMessageCreatedCallback) {
720 executor.execute(new Runnable() {
721 @Override
722 public void run() {
723 XmppAxolotlMessage axolotlMessage = buildHeader(contact);
724 onMessageCreatedCallback.run(axolotlMessage);
725 }
726 });
727 }
728
729 public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
730 XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
731 if (axolotlMessage != null) {
732 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
733 messageCache.remove(message.getUuid());
734 } else {
735 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
736 }
737 return axolotlMessage;
738 }
739
740 private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
741 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
742 return (identityKey != null)
743 ? new XmppAxolotlSession(account, axolotlStore, address,
744 identityKey.getFingerprint().replaceAll("\\s", ""))
745 : null;
746 }
747
748 private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
749 AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
750 message.getSenderDeviceId());
751 XmppAxolotlSession session = sessions.get(senderAddress);
752 if (session == null) {
753 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
754 session = recreateUncachedSession(senderAddress);
755 if (session == null) {
756 session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
757 }
758 }
759 return session;
760 }
761
762 public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
763 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
764
765 XmppAxolotlSession session = getReceivingSession(message);
766 try {
767 plaintextMessage = message.decrypt(session, getOwnDeviceId());
768 Integer preKeyId = session.getPreKeyId();
769 if (preKeyId != null) {
770 publishBundlesIfNeeded(false);
771 session.resetPreKeyId();
772 }
773 } catch (CryptoFailedException e) {
774 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
775 }
776
777 if (session.isFresh() && plaintextMessage != null) {
778 sessions.put(session);
779 }
780
781 return plaintextMessage;
782 }
783
784 public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
785 XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage = null;
786
787 XmppAxolotlSession session = getReceivingSession(message);
788 keyTransportMessage = message.getParameters(session, getOwnDeviceId());
789
790 if (session.isFresh() && keyTransportMessage != null) {
791 sessions.put(session);
792 }
793
794 return keyTransportMessage;
795 }
796}