AxolotlService.java

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