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