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 IdentityKey getOwnPublicKey() {
194 return axolotlStore.getIdentityKeyPair().getPublicKey();
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 private boolean hasAny(Contact contact) {
226 AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
227 return sessions.hasAny(contactAddress);
228 }
229
230 public void regenerateKeys() {
231 axolotlStore.regenerate();
232 sessions.clear();
233 fetchStatusMap.clear();
234 publishBundlesIfNeeded(true);
235 }
236
237 public int getOwnDeviceId() {
238 return axolotlStore.getLocalRegistrationId();
239 }
240
241 public Set<Integer> getOwnDeviceIds() {
242 return this.deviceIds.get(account.getJid().toBareJid());
243 }
244
245 private void setTrustOnSessions(final Jid jid, @NonNull final Set<Integer> deviceIds,
246 final XmppAxolotlSession.Trust from,
247 final XmppAxolotlSession.Trust to) {
248 for (Integer deviceId : deviceIds) {
249 AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
250 XmppAxolotlSession session = sessions.get(address);
251 if (session != null && session.getFingerprint() != null
252 && session.getTrust() == from) {
253 session.setTrust(to);
254 }
255 }
256 }
257
258 public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
259 if (jid.toBareJid().equals(account.getJid().toBareJid())) {
260 if (!deviceIds.isEmpty()) {
261 Log.d(Config.LOGTAG, getLogprefix(account) + "Received non-empty own device list. Resetting publish attemps and pepBroken status.");
262 pepBroken = false;
263 numPublishTriesOnEmptyPep = 0;
264 }
265 if (deviceIds.contains(getOwnDeviceId())) {
266 deviceIds.remove(getOwnDeviceId());
267 } else {
268 publishOwnDeviceId(deviceIds);
269 }
270 for (Integer deviceId : deviceIds) {
271 AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
272 if (sessions.get(ownDeviceAddress) == null) {
273 buildSessionFromPEP(ownDeviceAddress);
274 }
275 }
276 }
277 Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toString()));
278 expiredDevices.removeAll(deviceIds);
279 setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.TRUSTED,
280 XmppAxolotlSession.Trust.INACTIVE_TRUSTED);
281 setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.UNDECIDED,
282 XmppAxolotlSession.Trust.INACTIVE_UNDECIDED);
283 setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.UNTRUSTED,
284 XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED);
285 Set<Integer> newDevices = new HashSet<>(deviceIds);
286 setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_TRUSTED,
287 XmppAxolotlSession.Trust.TRUSTED);
288 setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNDECIDED,
289 XmppAxolotlSession.Trust.UNDECIDED);
290 setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED,
291 XmppAxolotlSession.Trust.UNTRUSTED);
292 this.deviceIds.put(jid, deviceIds);
293 mXmppConnectionService.keyStatusUpdated();
294 }
295
296 public void wipeOtherPepDevices() {
297 if (pepBroken) {
298 Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
299 return;
300 }
301 Set<Integer> deviceIds = new HashSet<>();
302 deviceIds.add(getOwnDeviceId());
303 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
304 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Wiping all other devices from Pep:" + publish);
305 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
306 @Override
307 public void onIqPacketReceived(Account account, IqPacket packet) {
308 // TODO: implement this!
309 }
310 });
311 }
312
313 public void purgeKey(IdentityKey identityKey) {
314 axolotlStore.setFingerprintTrust(identityKey.getFingerprint().replaceAll("\\s", ""), XmppAxolotlSession.Trust.COMPROMISED);
315 }
316
317 public void publishOwnDeviceIdIfNeeded() {
318 if (pepBroken) {
319 Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
320 return;
321 }
322 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
323 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
324 @Override
325 public void onIqPacketReceived(Account account, IqPacket packet) {
326 if (packet.getType() == IqPacket.TYPE.RESULT) {
327 Element item = mXmppConnectionService.getIqParser().getItem(packet);
328 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
329 if (!deviceIds.contains(getOwnDeviceId())) {
330 publishOwnDeviceId(deviceIds);
331 }
332 } else {
333 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while retrieving Device Ids" + packet.findChild("error"));
334 }
335 }
336 });
337 }
338
339 public void publishOwnDeviceId(Set<Integer> deviceIds) {
340 if (!deviceIds.contains(getOwnDeviceId())) {
341 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Own device " + getOwnDeviceId() + " not in PEP devicelist.");
342 if (deviceIds.isEmpty()) {
343 if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
344 Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
345 pepBroken = true;
346 return;
347 } else {
348 numPublishTriesOnEmptyPep++;
349 Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
350 }
351 } else {
352 numPublishTriesOnEmptyPep = 0;
353 }
354 deviceIds.add(getOwnDeviceId());
355 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
356 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
357 @Override
358 public void onIqPacketReceived(Account account, IqPacket packet) {
359 if (packet.getType() != IqPacket.TYPE.RESULT) {
360 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
361 }
362 }
363 });
364 }
365 }
366
367 public void publishBundlesIfNeeded(final boolean announceAfter) {
368 if (pepBroken) {
369 Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
370 return;
371 }
372 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
373 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
374 @Override
375 public void onIqPacketReceived(Account account, IqPacket packet) {
376 PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
377 Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
378 boolean flush = false;
379 if (bundle == null) {
380 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
381 bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
382 flush = true;
383 }
384 if (keys == null) {
385 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
386 }
387 try {
388 boolean changed = false;
389 // Validate IdentityKey
390 IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
391 if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
392 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
393 changed = true;
394 }
395
396 // Validate signedPreKeyRecord + ID
397 SignedPreKeyRecord signedPreKeyRecord;
398 int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
399 try {
400 signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
401 if (flush
402 || !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
403 || !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
404 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
405 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
406 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
407 changed = true;
408 }
409 } catch (InvalidKeyIdException e) {
410 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
411 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
412 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
413 changed = true;
414 }
415
416 // Validate PreKeys
417 Set<PreKeyRecord> preKeyRecords = new HashSet<>();
418 if (keys != null) {
419 for (Integer id : keys.keySet()) {
420 try {
421 PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
422 if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
423 preKeyRecords.add(preKeyRecord);
424 }
425 } catch (InvalidKeyIdException ignored) {
426 }
427 }
428 }
429 int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
430 if (newKeys > 0) {
431 List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
432 axolotlStore.getCurrentPreKeyId() + 1, newKeys);
433 preKeyRecords.addAll(newRecords);
434 for (PreKeyRecord record : newRecords) {
435 axolotlStore.storePreKey(record.getId(), record);
436 }
437 changed = true;
438 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
439 }
440
441
442 if (changed) {
443 IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
444 signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
445 preKeyRecords, getOwnDeviceId());
446 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
447 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
448 @Override
449 public void onIqPacketReceived(Account account, IqPacket packet) {
450 if (packet.getType() == IqPacket.TYPE.RESULT) {
451 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
452 if (announceAfter) {
453 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
454 publishOwnDeviceIdIfNeeded();
455 }
456 } else {
457 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
458 }
459 }
460 });
461 } else {
462 Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
463 if (announceAfter) {
464 Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
465 publishOwnDeviceIdIfNeeded();
466 }
467 }
468 } catch (InvalidKeyException e) {
469 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
470 return;
471 }
472 }
473 });
474 }
475
476 public boolean isContactAxolotlCapable(Contact contact) {
477
478 Jid jid = contact.getJid().toBareJid();
479 AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
480 return sessions.hasAny(address) ||
481 (deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
482 }
483
484 public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
485 return axolotlStore.getFingerprintTrust(fingerprint);
486 }
487
488 public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
489 axolotlStore.setFingerprintTrust(fingerprint, trust);
490 }
491
492 private void buildSessionFromPEP(final AxolotlAddress address) {
493 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.getDeviceId());
494
495 try {
496 IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
497 Jid.fromString(address.getName()), address.getDeviceId());
498 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
499 mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
500 private void finish() {
501 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
502 if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
503 && !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
504 mXmppConnectionService.keyStatusUpdated();
505 }
506 }
507
508 @Override
509 public void onIqPacketReceived(Account account, IqPacket packet) {
510 if (packet.getType() == IqPacket.TYPE.RESULT) {
511 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
512 final IqParser parser = mXmppConnectionService.getIqParser();
513 final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
514 final PreKeyBundle bundle = parser.bundle(packet);
515 if (preKeyBundleList.isEmpty() || bundle == null) {
516 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
517 fetchStatusMap.put(address, FetchStatus.ERROR);
518 finish();
519 return;
520 }
521 Random random = new Random();
522 final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
523 if (preKey == null) {
524 //should never happen
525 fetchStatusMap.put(address, FetchStatus.ERROR);
526 finish();
527 return;
528 }
529
530 final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
531 preKey.getPreKeyId(), preKey.getPreKey(),
532 bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
533 bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
534
535 axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
536
537 try {
538 SessionBuilder builder = new SessionBuilder(axolotlStore, address);
539 builder.process(preKeyBundle);
540 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
541 sessions.put(address, session);
542 fetchStatusMap.put(address, FetchStatus.SUCCESS);
543 } catch (UntrustedIdentityException | InvalidKeyException e) {
544 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
545 + e.getClass().getName() + ", " + e.getMessage());
546 fetchStatusMap.put(address, FetchStatus.ERROR);
547 }
548
549 finish();
550 } else {
551 fetchStatusMap.put(address, FetchStatus.ERROR);
552 Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
553 finish();
554 return;
555 }
556 }
557 });
558 } catch (InvalidJidException e) {
559 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
560 }
561 }
562
563 public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
564 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid());
565 Jid contactJid = conversation.getContact().getJid().toBareJid();
566 Set<AxolotlAddress> addresses = new HashSet<>();
567 if (deviceIds.get(contactJid) != null) {
568 for (Integer foreignId : this.deviceIds.get(contactJid)) {
569 AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
570 if (sessions.get(address) == null) {
571 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
572 if (identityKey != null) {
573 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
574 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
575 sessions.put(address, session);
576 } else {
577 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
578 addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
579 }
580 }
581 }
582 } else {
583 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
584 }
585 if (deviceIds.get(account.getJid().toBareJid()) != null) {
586 for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
587 AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
588 if (sessions.get(address) == null) {
589 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
590 if (identityKey != null) {
591 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
592 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
593 sessions.put(address, session);
594 } else {
595 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
596 addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
597 }
598 }
599 }
600 }
601
602 return addresses;
603 }
604
605 public boolean createSessionsIfNeeded(final Conversation conversation) {
606 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
607 boolean newSessions = false;
608 Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
609 for (AxolotlAddress address : addresses) {
610 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
611 FetchStatus status = fetchStatusMap.get(address);
612 if (status == null || status == FetchStatus.ERROR) {
613 fetchStatusMap.put(address, FetchStatus.PENDING);
614 this.buildSessionFromPEP(address);
615 newSessions = true;
616 } else if (status == FetchStatus.PENDING) {
617 newSessions = true;
618 } else {
619 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
620 }
621 }
622
623 return newSessions;
624 }
625
626 public boolean hasPendingKeyFetches(Conversation conversation) {
627 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
628 AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(), 0);
629 return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
630 || fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
631
632 }
633
634 @Nullable
635 private XmppAxolotlMessage buildHeader(Contact contact) {
636 final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
637 contact.getJid().toBareJid(), getOwnDeviceId());
638
639 Set<XmppAxolotlSession> contactSessions = findSessionsforContact(contact);
640 Set<XmppAxolotlSession> ownSessions = findOwnSessions();
641 if (contactSessions.isEmpty()) {
642 return null;
643 }
644 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl foreign keyElements...");
645 for (XmppAxolotlSession session : contactSessions) {
646 Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
647 axolotlMessage.addDevice(session);
648 }
649 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl own keyElements...");
650 for (XmppAxolotlSession session : ownSessions) {
651 Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
652 axolotlMessage.addDevice(session);
653 }
654
655 return axolotlMessage;
656 }
657
658 @Nullable
659 public XmppAxolotlMessage encrypt(Message message) {
660 XmppAxolotlMessage axolotlMessage = buildHeader(message.getContact());
661
662 if (axolotlMessage != null) {
663 final String content;
664 if (message.hasFileOnRemoteHost()) {
665 content = message.getFileParams().url.toString();
666 } else {
667 content = message.getBody();
668 }
669 try {
670 axolotlMessage.encrypt(content);
671 } catch (CryptoFailedException e) {
672 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
673 return null;
674 }
675 }
676
677 return axolotlMessage;
678 }
679
680 public void preparePayloadMessage(final Message message, final boolean delay) {
681 executor.execute(new Runnable() {
682 @Override
683 public void run() {
684 XmppAxolotlMessage axolotlMessage = encrypt(message);
685 if (axolotlMessage == null) {
686 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
687 //mXmppConnectionService.updateConversationUi();
688 } else {
689 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
690 messageCache.put(message.getUuid(), axolotlMessage);
691 mXmppConnectionService.resendMessage(message, delay);
692 }
693 }
694 });
695 }
696
697 public void prepareKeyTransportMessage(final Contact contact, final OnMessageCreatedCallback onMessageCreatedCallback) {
698 executor.execute(new Runnable() {
699 @Override
700 public void run() {
701 XmppAxolotlMessage axolotlMessage = buildHeader(contact);
702 onMessageCreatedCallback.run(axolotlMessage);
703 }
704 });
705 }
706
707 public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
708 XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
709 if (axolotlMessage != null) {
710 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
711 messageCache.remove(message.getUuid());
712 } else {
713 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
714 }
715 return axolotlMessage;
716 }
717
718 private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
719 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
720 return (identityKey != null)
721 ? new XmppAxolotlSession(account, axolotlStore, address,
722 identityKey.getFingerprint().replaceAll("\\s", ""))
723 : null;
724 }
725
726 private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
727 AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
728 message.getSenderDeviceId());
729 XmppAxolotlSession session = sessions.get(senderAddress);
730 if (session == null) {
731 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
732 session = recreateUncachedSession(senderAddress);
733 if (session == null) {
734 session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
735 }
736 }
737 return session;
738 }
739
740 public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
741 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
742
743 XmppAxolotlSession session = getReceivingSession(message);
744 try {
745 plaintextMessage = message.decrypt(session, getOwnDeviceId());
746 Integer preKeyId = session.getPreKeyId();
747 if (preKeyId != null) {
748 publishBundlesIfNeeded(false);
749 session.resetPreKeyId();
750 }
751 } catch (CryptoFailedException e) {
752 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
753 }
754
755 if (session.isFresh() && plaintextMessage != null) {
756 sessions.put(session);
757 }
758
759 return plaintextMessage;
760 }
761
762 public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
763 XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage = null;
764
765 XmppAxolotlSession session = getReceivingSession(message);
766 keyTransportMessage = message.getParameters(session, getOwnDeviceId());
767
768 if (session.isFresh() && keyTransportMessage != null) {
769 sessions.put(session);
770 }
771
772 return keyTransportMessage;
773 }
774}