AxolotlService.java

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