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		ERROR
183	}
184
185	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
186
187	}
188
189	public static String getLogprefix(Account account) {
190		return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): ";
191	}
192
193	public AxolotlService(Account account, XmppConnectionService connectionService) {
194		if (Security.getProvider("BC") == null) {
195			Security.addProvider(new BouncyCastleProvider());
196		}
197		this.mXmppConnectionService = connectionService;
198		this.account = account;
199		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
200		this.deviceIds = new HashMap<>();
201		this.messageCache = new HashMap<>();
202		this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
203		this.fetchStatusMap = new FetchStatusMap();
204		this.executor = new SerialSingleThreadExecutor();
205	}
206
207	public String getOwnFingerprint() {
208		return axolotlStore.getIdentityKeyPair().getPublicKey().getFingerprint().replaceAll("\\s", "");
209	}
210
211	public Set<IdentityKey> getKeysWithTrust(XmppAxolotlSession.Trust trust) {
212		return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toString(), trust);
213	}
214
215	public Set<IdentityKey> getKeysWithTrust(XmppAxolotlSession.Trust trust, Contact contact) {
216		return axolotlStore.getContactKeysWithTrust(contact.getJid().toBareJid().toString(), trust);
217	}
218
219	public long getNumTrustedKeys(Contact contact) {
220		return axolotlStore.getContactNumTrustedKeys(contact.getJid().toBareJid().toString());
221	}
222
223	private AxolotlAddress getAddressForJid(Jid jid) {
224		return new AxolotlAddress(jid.toString(), 0);
225	}
226
227	private Set<XmppAxolotlSession> findOwnSessions() {
228		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
229		return new HashSet<>(this.sessions.getAll(ownAddress).values());
230	}
231
232	private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
233		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
234		return new HashSet<>(this.sessions.getAll(contactAddress).values());
235	}
236
237	public Set<String> getFingerprintsForOwnSessions() {
238		Set<String> fingerprints = new HashSet<>();
239		for (XmppAxolotlSession session : findOwnSessions()) {
240			fingerprints.add(session.getFingerprint());
241		}
242		return fingerprints;
243	}
244
245	public Set<String> getFingerprintsForContact(final Contact contact) {
246		Set<String> fingerprints = new HashSet<>();
247		for (XmppAxolotlSession session : findSessionsforContact(contact)) {
248			fingerprints.add(session.getFingerprint());
249		}
250		return fingerprints;
251	}
252
253	private boolean hasAny(Contact contact) {
254		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
255		return sessions.hasAny(contactAddress);
256	}
257
258	public boolean isPepBroken() {
259		return this.pepBroken;
260	}
261
262	public void regenerateKeys(boolean wipeOther) {
263		axolotlStore.regenerate();
264		sessions.clear();
265		fetchStatusMap.clear();
266		publishBundlesIfNeeded(true, wipeOther);
267	}
268
269	public int getOwnDeviceId() {
270		return axolotlStore.getLocalRegistrationId();
271	}
272
273	public Set<Integer> getOwnDeviceIds() {
274		return this.deviceIds.get(account.getJid().toBareJid());
275	}
276
277	private void setTrustOnSessions(final Jid jid, @NonNull final Set<Integer> deviceIds,
278	                                final XmppAxolotlSession.Trust from,
279	                                final XmppAxolotlSession.Trust to) {
280		for (Integer deviceId : deviceIds) {
281			AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
282			XmppAxolotlSession session = sessions.get(address);
283			if (session != null && session.getFingerprint() != null
284					&& session.getTrust() == from) {
285				session.setTrust(to);
286			}
287		}
288	}
289
290	public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
291		if (jid.toBareJid().equals(account.getJid().toBareJid())) {
292			if (!deviceIds.isEmpty()) {
293				Log.d(Config.LOGTAG, getLogprefix(account) + "Received non-empty own device list. Resetting publish attemps and pepBroken status.");
294				pepBroken = false;
295				numPublishTriesOnEmptyPep = 0;
296			}
297			if (deviceIds.contains(getOwnDeviceId())) {
298				deviceIds.remove(getOwnDeviceId());
299			} else {
300				publishOwnDeviceId(deviceIds);
301			}
302			for (Integer deviceId : deviceIds) {
303				AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
304				if (sessions.get(ownDeviceAddress) == null) {
305					buildSessionFromPEP(ownDeviceAddress);
306				}
307			}
308		}
309		Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toString()));
310		expiredDevices.removeAll(deviceIds);
311		setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.TRUSTED,
312				XmppAxolotlSession.Trust.INACTIVE_TRUSTED);
313		setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.UNDECIDED,
314				XmppAxolotlSession.Trust.INACTIVE_UNDECIDED);
315		setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.UNTRUSTED,
316				XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED);
317		Set<Integer> newDevices = new HashSet<>(deviceIds);
318		setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_TRUSTED,
319				XmppAxolotlSession.Trust.TRUSTED);
320		setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNDECIDED,
321				XmppAxolotlSession.Trust.UNDECIDED);
322		setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED,
323				XmppAxolotlSession.Trust.UNTRUSTED);
324		this.deviceIds.put(jid, deviceIds);
325		findDevicesWithoutSession(jid);
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							publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
518						} else {
519							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
520						}
521					} else {
522						Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
523						if (wipe) {
524							wipeOtherPepDevices();
525						} else if (announce) {
526							Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
527							publishOwnDeviceIdIfNeeded();
528						}
529					}
530				} catch (InvalidKeyException e) {
531					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
532				}
533			}
534		});
535	}
536
537	private void publishDeviceBundle(SignedPreKeyRecord signedPreKeyRecord,
538									 Set<PreKeyRecord> preKeyRecords,
539									 final boolean announceAfter,
540									 final boolean wipe) {
541		IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
542				signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
543				preKeyRecords, getOwnDeviceId());
544		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
545		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
546			@Override
547			public void onIqPacketReceived(Account account, IqPacket packet) {
548				if (packet.getType() == IqPacket.TYPE.RESULT) {
549					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
550					if (wipe) {
551						wipeOtherPepDevices();
552					} else if (announceAfter) {
553						Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
554						publishOwnDeviceIdIfNeeded();
555					}
556				} else {
557					Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
558				}
559			}
560		});
561	}
562
563	public boolean isContactAxolotlCapable(Contact contact) {
564		Jid jid = contact.getJid().toBareJid();
565		return hasAny(contact) ||
566				(deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
567	}
568
569	public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
570		return axolotlStore.getFingerprintTrust(fingerprint);
571	}
572
573	public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
574		axolotlStore.setFingerprintTrust(fingerprint, trust);
575	}
576
577	private void verifySessionWithPEP(final XmppAxolotlSession session, final IdentityKey identityKey) {
578		final AxolotlAddress address = session.getRemoteAddress();
579		try {
580			IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId());
581			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
582				@Override
583				public void onIqPacketReceived(Account account, IqPacket packet) {
584					Pair<X509Certificate[],byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
585					if (verification != null) {
586						try {
587							Signature verifier = Signature.getInstance("sha256WithRSA");
588							verifier.initVerify(verification.first[0]);
589							verifier.update(identityKey.serialize());
590							if (verifier.verify(verification.second)) {
591								try {
592									mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
593									Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+session.getFingerprint());
594									setFingerprintTrust(session.getFingerprint(), XmppAxolotlSession.Trust.TRUSTED);
595									fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
596									finishBuildingSessionsFromPEP(address);
597									return;
598								} catch (Exception e) {
599									Log.d(Config.LOGTAG,"could not verify certificate");
600								}
601							}
602						} catch (Exception e) {
603							Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
604						}
605					}
606					fetchStatusMap.put(address, FetchStatus.SUCCESS);
607					finishBuildingSessionsFromPEP(address);
608				}
609			});
610		} catch (InvalidJidException e) {
611			fetchStatusMap.put(address, FetchStatus.SUCCESS);
612			finishBuildingSessionsFromPEP(address);
613		}
614	}
615
616	private void finishBuildingSessionsFromPEP(final AxolotlAddress address) {
617		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
618		if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
619				&& !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
620			FetchStatus report = null;
621			if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.SUCCESS_VERIFIED)
622					| fetchStatusMap.getAll(address).containsValue(FetchStatus.SUCCESS_VERIFIED)) {
623				report = FetchStatus.SUCCESS_VERIFIED;
624			} else if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.ERROR)
625					|| fetchStatusMap.getAll(address).containsValue(FetchStatus.ERROR)) {
626				report = FetchStatus.ERROR;
627			}
628			mXmppConnectionService.keyStatusUpdated(report);
629		}
630	}
631
632	private void buildSessionFromPEP(final AxolotlAddress address) {
633		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString());
634		if (address.getDeviceId() == getOwnDeviceId()) {
635			throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
636		}
637
638		try {
639			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
640					Jid.fromString(address.getName()), address.getDeviceId());
641			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
642			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
643
644				@Override
645				public void onIqPacketReceived(Account account, IqPacket packet) {
646					if (packet.getType() == IqPacket.TYPE.RESULT) {
647						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
648						final IqParser parser = mXmppConnectionService.getIqParser();
649						final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
650						final PreKeyBundle bundle = parser.bundle(packet);
651						if (preKeyBundleList.isEmpty() || bundle == null) {
652							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
653							fetchStatusMap.put(address, FetchStatus.ERROR);
654							finishBuildingSessionsFromPEP(address);
655							return;
656						}
657						Random random = new Random();
658						final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
659						if (preKey == null) {
660							//should never happen
661							fetchStatusMap.put(address, FetchStatus.ERROR);
662							finishBuildingSessionsFromPEP(address);
663							return;
664						}
665
666						final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
667								preKey.getPreKeyId(), preKey.getPreKey(),
668								bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
669								bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
670
671						try {
672							SessionBuilder builder = new SessionBuilder(axolotlStore, address);
673							builder.process(preKeyBundle);
674							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
675							sessions.put(address, session);
676							if (Config.X509_VERIFICATION) {
677								verifySessionWithPEP(session, bundle.getIdentityKey());
678							} else {
679								fetchStatusMap.put(address, FetchStatus.SUCCESS);
680								finishBuildingSessionsFromPEP(address);
681							}
682						} catch (UntrustedIdentityException | InvalidKeyException e) {
683							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
684									+ e.getClass().getName() + ", " + e.getMessage());
685							fetchStatusMap.put(address, FetchStatus.ERROR);
686							finishBuildingSessionsFromPEP(address);
687						}
688					} else {
689						fetchStatusMap.put(address, FetchStatus.ERROR);
690						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
691						finishBuildingSessionsFromPEP(address);
692					}
693				}
694			});
695		} catch (InvalidJidException e) {
696			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
697		}
698	}
699
700	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
701		return findDevicesWithoutSession(conversation.getContact().getJid().toBareJid());
702	}
703
704	public Set<AxolotlAddress> findDevicesWithoutSession(final Jid contactJid) {
705		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + contactJid);
706		Set<AxolotlAddress> addresses = new HashSet<>();
707		if (deviceIds.get(contactJid) != null) {
708			for (Integer foreignId : this.deviceIds.get(contactJid)) {
709				AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
710				if (sessions.get(address) == null) {
711					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
712					if (identityKey != null) {
713						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
714						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
715						sessions.put(address, session);
716					} else {
717						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
718						addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
719					}
720				}
721			}
722		} else {
723			Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
724		}
725		if (deviceIds.get(account.getJid().toBareJid()) != null) {
726			for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
727				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
728				if (sessions.get(address) == null) {
729					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
730					if (identityKey != null) {
731						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
732						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
733						sessions.put(address, session);
734					} else {
735						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
736						addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
737					}
738				}
739			}
740		}
741
742		return addresses;
743	}
744
745	public boolean createSessionsIfNeeded(final Conversation conversation) {
746		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
747		boolean newSessions = false;
748		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
749		for (AxolotlAddress address : addresses) {
750			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
751			FetchStatus status = fetchStatusMap.get(address);
752			if (status == null || status == FetchStatus.ERROR) {
753				fetchStatusMap.put(address, FetchStatus.PENDING);
754				this.buildSessionFromPEP(address);
755				newSessions = true;
756			} else if (status == FetchStatus.PENDING) {
757				newSessions = true;
758			} else {
759				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
760			}
761		}
762
763		return newSessions;
764	}
765
766	public boolean hasPendingKeyFetches(Account account, Contact contact) {
767		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
768		AxolotlAddress foreignAddress = new AxolotlAddress(contact.getJid().toBareJid().toString(), 0);
769		return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
770				|| fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
771
772	}
773
774	@Nullable
775	private XmppAxolotlMessage buildHeader(Contact contact) {
776		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
777				contact.getJid().toBareJid(), getOwnDeviceId());
778
779		Set<XmppAxolotlSession> contactSessions = findSessionsforContact(contact);
780		Set<XmppAxolotlSession> ownSessions = findOwnSessions();
781		if (contactSessions.isEmpty()) {
782			return null;
783		}
784		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl foreign keyElements...");
785		for (XmppAxolotlSession session : contactSessions) {
786			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
787			axolotlMessage.addDevice(session);
788		}
789		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl own keyElements...");
790		for (XmppAxolotlSession session : ownSessions) {
791			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
792			axolotlMessage.addDevice(session);
793		}
794
795		return axolotlMessage;
796	}
797
798	@Nullable
799	public XmppAxolotlMessage encrypt(Message message) {
800		XmppAxolotlMessage axolotlMessage = buildHeader(message.getContact());
801
802		if (axolotlMessage != null) {
803			final String content;
804			if (message.hasFileOnRemoteHost()) {
805				content = message.getFileParams().url.toString();
806			} else {
807				content = message.getBody();
808			}
809			try {
810				axolotlMessage.encrypt(content);
811			} catch (CryptoFailedException e) {
812				Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
813				return null;
814			}
815		}
816
817		return axolotlMessage;
818	}
819
820	public void preparePayloadMessage(final Message message, final boolean delay) {
821		executor.execute(new Runnable() {
822			@Override
823			public void run() {
824				XmppAxolotlMessage axolotlMessage = encrypt(message);
825				if (axolotlMessage == null) {
826					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
827					//mXmppConnectionService.updateConversationUi();
828				} else {
829					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
830					messageCache.put(message.getUuid(), axolotlMessage);
831					mXmppConnectionService.resendMessage(message, delay);
832				}
833			}
834		});
835	}
836
837	public void prepareKeyTransportMessage(final Contact contact, final OnMessageCreatedCallback onMessageCreatedCallback) {
838		executor.execute(new Runnable() {
839			@Override
840			public void run() {
841				XmppAxolotlMessage axolotlMessage = buildHeader(contact);
842				onMessageCreatedCallback.run(axolotlMessage);
843			}
844		});
845	}
846
847	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
848		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
849		if (axolotlMessage != null) {
850			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
851			messageCache.remove(message.getUuid());
852		} else {
853			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
854		}
855		return axolotlMessage;
856	}
857
858	private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
859		IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
860		return (identityKey != null)
861				? new XmppAxolotlSession(account, axolotlStore, address,
862						identityKey.getFingerprint().replaceAll("\\s", ""))
863				: null;
864	}
865
866	private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
867		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
868				message.getSenderDeviceId());
869		XmppAxolotlSession session = sessions.get(senderAddress);
870		if (session == null) {
871			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
872			session = recreateUncachedSession(senderAddress);
873			if (session == null) {
874				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
875			}
876		}
877		return session;
878	}
879
880	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
881		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
882
883		XmppAxolotlSession session = getReceivingSession(message);
884		try {
885			plaintextMessage = message.decrypt(session, getOwnDeviceId());
886			Integer preKeyId = session.getPreKeyId();
887			if (preKeyId != null) {
888				publishBundlesIfNeeded(false, false);
889				session.resetPreKeyId();
890			}
891		} catch (CryptoFailedException e) {
892			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
893		}
894
895		if (session.isFresh() && plaintextMessage != null) {
896			sessions.put(session);
897		}
898
899		return plaintextMessage;
900	}
901
902	public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
903		XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
904
905		XmppAxolotlSession session = getReceivingSession(message);
906		keyTransportMessage = message.getParameters(session, getOwnDeviceId());
907
908		if (session.isFresh() && keyTransportMessage != null) {
909			sessions.put(session);
910		}
911
912		return keyTransportMessage;
913	}
914}