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		findDevicesWithoutSession(jid);
327		mXmppConnectionService.keyStatusUpdated(null);
328	}
329
330	public void wipeOtherPepDevices() {
331		if (pepBroken) {
332			Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
333			return;
334		}
335		Set<Integer> deviceIds = new HashSet<>();
336		deviceIds.add(getOwnDeviceId());
337		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
338		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Wiping all other devices from Pep:" + publish);
339		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
340			@Override
341			public void onIqPacketReceived(Account account, IqPacket packet) {
342				// TODO: implement this!
343			}
344		});
345	}
346
347	public void purgeKey(final String fingerprint) {
348		axolotlStore.setFingerprintTrust(fingerprint.replaceAll("\\s", ""), XmppAxolotlSession.Trust.COMPROMISED);
349	}
350
351	public void publishOwnDeviceIdIfNeeded() {
352		if (pepBroken) {
353			Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
354			return;
355		}
356		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
357		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
358			@Override
359			public void onIqPacketReceived(Account account, IqPacket packet) {
360				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
361					Log.d(Config.LOGTAG, getLogprefix(account) + "Timeout received while retrieving own Device Ids.");
362				} else {
363					Element item = mXmppConnectionService.getIqParser().getItem(packet);
364					Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
365					if (!deviceIds.contains(getOwnDeviceId())) {
366						publishOwnDeviceId(deviceIds);
367					}
368				}
369			}
370		});
371	}
372
373	public void publishOwnDeviceId(Set<Integer> deviceIds) {
374		Set<Integer> deviceIdsCopy = new HashSet<>(deviceIds);
375		if (!deviceIdsCopy.contains(getOwnDeviceId())) {
376			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Own device " + getOwnDeviceId() + " not in PEP devicelist.");
377			if (deviceIdsCopy.isEmpty()) {
378				if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
379					Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
380					pepBroken = true;
381					return;
382				} else {
383					numPublishTriesOnEmptyPep++;
384					Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
385				}
386			} else {
387				numPublishTriesOnEmptyPep = 0;
388			}
389			deviceIdsCopy.add(getOwnDeviceId());
390			IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIdsCopy);
391			mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
392				@Override
393				public void onIqPacketReceived(Account account, IqPacket packet) {
394					if (packet.getType() != IqPacket.TYPE.RESULT) {
395						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
396					}
397				}
398			});
399		}
400	}
401
402	public void publishDeviceVerificationAndBundle(final SignedPreKeyRecord signedPreKeyRecord,
403												   final Set<PreKeyRecord> preKeyRecords,
404												   final boolean announceAfter,
405												   final boolean wipe) {
406		try {
407			IdentityKey axolotlPublicKey = axolotlStore.getIdentityKeyPair().getPublicKey();
408			PrivateKey x509PrivateKey = KeyChain.getPrivateKey(mXmppConnectionService, account.getPrivateKeyAlias());
409			X509Certificate[] chain = KeyChain.getCertificateChain(mXmppConnectionService, account.getPrivateKeyAlias());
410			Signature verifier = Signature.getInstance("sha256WithRSA");
411			verifier.initSign(x509PrivateKey,mXmppConnectionService.getRNG());
412			verifier.update(axolotlPublicKey.serialize());
413			byte[] signature = verifier.sign();
414			IqPacket packet = mXmppConnectionService.getIqGenerator().publishVerification(signature, chain, getOwnDeviceId());
415			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": publish verification for device "+getOwnDeviceId());
416			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
417				@Override
418				public void onIqPacketReceived(Account account, IqPacket packet) {
419					publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
420				}
421			});
422		} catch (Exception  e) {
423			e.printStackTrace();
424		}
425	}
426
427	public void publishBundlesIfNeeded(final boolean announce, final boolean wipe) {
428		if (pepBroken) {
429			Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
430			return;
431		}
432		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
433		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
434			@Override
435			public void onIqPacketReceived(Account account, IqPacket packet) {
436
437				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
438					return; //ignore timeout. do nothing
439				}
440
441				if (packet.getType() == IqPacket.TYPE.ERROR) {
442					Element error = packet.findChild("error");
443					if (error == null || !error.hasChild("item-not-found")) {
444						pepBroken = true;
445						Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
446						return;
447					}
448				}
449
450				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
451				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
452				boolean flush = false;
453				if (bundle == null) {
454					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
455					bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
456					flush = true;
457				}
458				if (keys == null) {
459					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
460				}
461				try {
462					boolean changed = false;
463					// Validate IdentityKey
464					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
465					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
466						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
467						changed = true;
468					}
469
470					// Validate signedPreKeyRecord + ID
471					SignedPreKeyRecord signedPreKeyRecord;
472					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
473					try {
474						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
475						if (flush
476								|| !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
477								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
478							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
479							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
480							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
481							changed = true;
482						}
483					} catch (InvalidKeyIdException e) {
484						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
485						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
486						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
487						changed = true;
488					}
489
490					// Validate PreKeys
491					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
492					if (keys != null) {
493						for (Integer id : keys.keySet()) {
494							try {
495								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
496								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
497									preKeyRecords.add(preKeyRecord);
498								}
499							} catch (InvalidKeyIdException ignored) {
500							}
501						}
502					}
503					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
504					if (newKeys > 0) {
505						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
506								axolotlStore.getCurrentPreKeyId() + 1, newKeys);
507						preKeyRecords.addAll(newRecords);
508						for (PreKeyRecord record : newRecords) {
509							axolotlStore.storePreKey(record.getId(), record);
510						}
511						changed = true;
512						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
513					}
514
515
516					if (changed) {
517						if (account.getPrivateKeyAlias() != null && Config.X509_VERIFICATION) {
518							mXmppConnectionService.publishDisplayName(account);
519							publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
520						} else {
521							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
522						}
523					} else {
524						Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
525						if (wipe) {
526							wipeOtherPepDevices();
527						} else if (announce) {
528							Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
529							publishOwnDeviceIdIfNeeded();
530						}
531					}
532				} catch (InvalidKeyException e) {
533					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
534				}
535			}
536		});
537	}
538
539	private void publishDeviceBundle(SignedPreKeyRecord signedPreKeyRecord,
540									 Set<PreKeyRecord> preKeyRecords,
541									 final boolean announceAfter,
542									 final boolean wipe) {
543		IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
544				signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
545				preKeyRecords, getOwnDeviceId());
546		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
547		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
548			@Override
549			public void onIqPacketReceived(Account account, IqPacket packet) {
550				if (packet.getType() == IqPacket.TYPE.RESULT) {
551					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
552					if (wipe) {
553						wipeOtherPepDevices();
554					} else if (announceAfter) {
555						Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
556						publishOwnDeviceIdIfNeeded();
557					}
558				} else {
559					Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
560				}
561			}
562		});
563	}
564
565	public boolean isContactAxolotlCapable(Contact contact) {
566		Jid jid = contact.getJid().toBareJid();
567		return hasAny(contact) ||
568				(deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
569	}
570
571	public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
572		return axolotlStore.getFingerprintTrust(fingerprint);
573	}
574
575	public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
576		axolotlStore.setFingerprintTrust(fingerprint, trust);
577	}
578
579	private void verifySessionWithPEP(final XmppAxolotlSession session, final IdentityKey identityKey) {
580		final AxolotlAddress address = session.getRemoteAddress();
581		try {
582			IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId());
583			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
584				@Override
585				public void onIqPacketReceived(Account account, IqPacket packet) {
586					Pair<X509Certificate[],byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
587					if (verification != null) {
588						try {
589							Signature verifier = Signature.getInstance("sha256WithRSA");
590							verifier.initVerify(verification.first[0]);
591							verifier.update(identityKey.serialize());
592							if (verifier.verify(verification.second)) {
593								try {
594									mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
595									Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+session.getFingerprint());
596									setFingerprintTrust(session.getFingerprint(), XmppAxolotlSession.Trust.TRUSTED);
597									fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
598									finishBuildingSessionsFromPEP(address);
599									return;
600								} catch (Exception e) {
601									Log.d(Config.LOGTAG,"could not verify certificate");
602								}
603							}
604						} catch (Exception e) {
605							Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
606						}
607					}
608					fetchStatusMap.put(address, FetchStatus.SUCCESS);
609					finishBuildingSessionsFromPEP(address);
610				}
611			});
612		} catch (InvalidJidException e) {
613			fetchStatusMap.put(address, FetchStatus.SUCCESS);
614			finishBuildingSessionsFromPEP(address);
615		}
616	}
617
618	private void finishBuildingSessionsFromPEP(final AxolotlAddress address) {
619		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
620		if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
621				&& !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
622			FetchStatus report = null;
623			if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.SUCCESS_VERIFIED)
624					| fetchStatusMap.getAll(address).containsValue(FetchStatus.SUCCESS_VERIFIED)) {
625				report = FetchStatus.SUCCESS_VERIFIED;
626			} else if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.ERROR)
627					|| fetchStatusMap.getAll(address).containsValue(FetchStatus.ERROR)) {
628				report = FetchStatus.ERROR;
629			}
630			mXmppConnectionService.keyStatusUpdated(report);
631		}
632	}
633
634	private void buildSessionFromPEP(final AxolotlAddress address) {
635		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString());
636		if (address.getDeviceId() == getOwnDeviceId()) {
637			throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
638		}
639
640		try {
641			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
642					Jid.fromString(address.getName()), address.getDeviceId());
643			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
644			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
645
646				@Override
647				public void onIqPacketReceived(Account account, IqPacket packet) {
648					if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
649						fetchStatusMap.put(address, FetchStatus.TIMEOUT);
650					} else if (packet.getType() == IqPacket.TYPE.RESULT) {
651						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
652						final IqParser parser = mXmppConnectionService.getIqParser();
653						final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
654						final PreKeyBundle bundle = parser.bundle(packet);
655						if (preKeyBundleList.isEmpty() || bundle == null) {
656							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
657							fetchStatusMap.put(address, FetchStatus.ERROR);
658							finishBuildingSessionsFromPEP(address);
659							return;
660						}
661						Random random = new Random();
662						final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
663						if (preKey == null) {
664							//should never happen
665							fetchStatusMap.put(address, FetchStatus.ERROR);
666							finishBuildingSessionsFromPEP(address);
667							return;
668						}
669
670						final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
671								preKey.getPreKeyId(), preKey.getPreKey(),
672								bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
673								bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
674
675						try {
676							SessionBuilder builder = new SessionBuilder(axolotlStore, address);
677							builder.process(preKeyBundle);
678							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
679							sessions.put(address, session);
680							if (Config.X509_VERIFICATION) {
681								verifySessionWithPEP(session, bundle.getIdentityKey());
682							} else {
683								fetchStatusMap.put(address, FetchStatus.SUCCESS);
684								finishBuildingSessionsFromPEP(address);
685							}
686						} catch (UntrustedIdentityException | InvalidKeyException e) {
687							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
688									+ e.getClass().getName() + ", " + e.getMessage());
689							fetchStatusMap.put(address, FetchStatus.ERROR);
690							finishBuildingSessionsFromPEP(address);
691						}
692					} else {
693						fetchStatusMap.put(address, FetchStatus.ERROR);
694						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
695						finishBuildingSessionsFromPEP(address);
696					}
697				}
698			});
699		} catch (InvalidJidException e) {
700			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
701		}
702	}
703
704	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
705		return findDevicesWithoutSession(conversation.getContact().getJid().toBareJid());
706	}
707
708	public Set<AxolotlAddress> findDevicesWithoutSession(final Jid contactJid) {
709		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + contactJid);
710		Set<AxolotlAddress> addresses = new HashSet<>();
711		if (deviceIds.get(contactJid) != null) {
712			for (Integer foreignId : this.deviceIds.get(contactJid)) {
713				AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
714				if (sessions.get(address) == null) {
715					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
716					if (identityKey != null) {
717						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
718						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
719						sessions.put(address, session);
720					} else {
721						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
722						if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
723							addresses.add(address);
724						} else {
725							Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken");
726						}
727					}
728				}
729			}
730		} else {
731			Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
732		}
733		if (deviceIds.get(account.getJid().toBareJid()) != null) {
734			for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
735				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
736				if (sessions.get(address) == null) {
737					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
738					if (identityKey != null) {
739						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
740						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
741						sessions.put(address, session);
742					} else {
743						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
744						if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
745							addresses.add(address);
746						} else {
747							Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken");
748						}
749					}
750				}
751			}
752		}
753
754		return addresses;
755	}
756
757	public boolean createSessionsIfNeeded(final Conversation conversation) {
758		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
759		boolean newSessions = false;
760		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
761		for (AxolotlAddress address : addresses) {
762			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
763			FetchStatus status = fetchStatusMap.get(address);
764			if (status == null || status == FetchStatus.TIMEOUT) {
765				fetchStatusMap.put(address, FetchStatus.PENDING);
766				this.buildSessionFromPEP(address);
767				newSessions = true;
768			} else if (status == FetchStatus.PENDING) {
769				newSessions = true;
770			} else {
771				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
772			}
773		}
774
775		return newSessions;
776	}
777
778	public boolean hasPendingKeyFetches(Account account, Contact contact) {
779		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
780		AxolotlAddress foreignAddress = new AxolotlAddress(contact.getJid().toBareJid().toString(), 0);
781		return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
782				|| fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
783
784	}
785
786	@Nullable
787	private XmppAxolotlMessage buildHeader(Contact contact) {
788		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
789				contact.getJid().toBareJid(), getOwnDeviceId());
790
791		Set<XmppAxolotlSession> contactSessions = findSessionsforContact(contact);
792		Set<XmppAxolotlSession> ownSessions = findOwnSessions();
793		if (contactSessions.isEmpty()) {
794			return null;
795		}
796		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl foreign keyElements...");
797		for (XmppAxolotlSession session : contactSessions) {
798			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
799			axolotlMessage.addDevice(session);
800		}
801		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl own keyElements...");
802		for (XmppAxolotlSession session : ownSessions) {
803			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
804			axolotlMessage.addDevice(session);
805		}
806
807		return axolotlMessage;
808	}
809
810	@Nullable
811	public XmppAxolotlMessage encrypt(Message message) {
812		XmppAxolotlMessage axolotlMessage = buildHeader(message.getContact());
813
814		if (axolotlMessage != null) {
815			final String content;
816			if (message.hasFileOnRemoteHost()) {
817				content = message.getFileParams().url.toString();
818			} else {
819				content = message.getBody();
820			}
821			try {
822				axolotlMessage.encrypt(content);
823			} catch (CryptoFailedException e) {
824				Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
825				return null;
826			}
827		}
828
829		return axolotlMessage;
830	}
831
832	public void preparePayloadMessage(final Message message, final boolean delay) {
833		executor.execute(new Runnable() {
834			@Override
835			public void run() {
836				XmppAxolotlMessage axolotlMessage = encrypt(message);
837				if (axolotlMessage == null) {
838					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
839					//mXmppConnectionService.updateConversationUi();
840				} else {
841					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
842					messageCache.put(message.getUuid(), axolotlMessage);
843					mXmppConnectionService.resendMessage(message, delay);
844				}
845			}
846		});
847	}
848
849	public void prepareKeyTransportMessage(final Contact contact, final OnMessageCreatedCallback onMessageCreatedCallback) {
850		executor.execute(new Runnable() {
851			@Override
852			public void run() {
853				XmppAxolotlMessage axolotlMessage = buildHeader(contact);
854				onMessageCreatedCallback.run(axolotlMessage);
855			}
856		});
857	}
858
859	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
860		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
861		if (axolotlMessage != null) {
862			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
863			messageCache.remove(message.getUuid());
864		} else {
865			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
866		}
867		return axolotlMessage;
868	}
869
870	private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
871		IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
872		return (identityKey != null)
873				? new XmppAxolotlSession(account, axolotlStore, address,
874						identityKey.getFingerprint().replaceAll("\\s", ""))
875				: null;
876	}
877
878	private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
879		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
880				message.getSenderDeviceId());
881		XmppAxolotlSession session = sessions.get(senderAddress);
882		if (session == null) {
883			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
884			session = recreateUncachedSession(senderAddress);
885			if (session == null) {
886				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
887			}
888		}
889		return session;
890	}
891
892	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
893		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
894
895		XmppAxolotlSession session = getReceivingSession(message);
896		try {
897			plaintextMessage = message.decrypt(session, getOwnDeviceId());
898			Integer preKeyId = session.getPreKeyId();
899			if (preKeyId != null) {
900				publishBundlesIfNeeded(false, false);
901				session.resetPreKeyId();
902			}
903		} catch (CryptoFailedException e) {
904			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
905		}
906
907		if (session.isFresh() && plaintextMessage != null) {
908			sessions.put(session);
909		}
910
911		return plaintextMessage;
912	}
913
914	public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
915		XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
916
917		XmppAxolotlSession session = getReceivingSession(message);
918		keyTransportMessage = message.getParameters(session, getOwnDeviceId());
919
920		if (session.isFresh() && keyTransportMessage != null) {
921			sessions.put(session);
922		}
923
924		return keyTransportMessage;
925	}
926}