SQLiteAxolotlStore.java

  1package eu.siacs.conversations.crypto.axolotl;
  2
  3import android.util.Log;
  4import android.util.LruCache;
  5
  6import org.whispersystems.libsignal.SignalProtocolAddress;
  7import org.whispersystems.libsignal.IdentityKey;
  8import org.whispersystems.libsignal.IdentityKeyPair;
  9import org.whispersystems.libsignal.InvalidKeyIdException;
 10import org.whispersystems.libsignal.ecc.Curve;
 11import org.whispersystems.libsignal.ecc.ECKeyPair;
 12import org.whispersystems.libsignal.state.SignalProtocolStore;
 13import org.whispersystems.libsignal.state.PreKeyRecord;
 14import org.whispersystems.libsignal.state.SessionRecord;
 15import org.whispersystems.libsignal.state.SignedPreKeyRecord;
 16import org.whispersystems.libsignal.util.KeyHelper;
 17
 18import java.security.cert.X509Certificate;
 19import java.util.List;
 20import java.util.Set;
 21
 22import eu.siacs.conversations.Config;
 23import eu.siacs.conversations.entities.Account;
 24import eu.siacs.conversations.services.XmppConnectionService;
 25
 26public class SQLiteAxolotlStore implements SignalProtocolStore {
 27
 28	public static final String PREKEY_TABLENAME = "prekeys";
 29	public static final String SIGNED_PREKEY_TABLENAME = "signed_prekeys";
 30	public static final String SESSION_TABLENAME = "sessions";
 31	public static final String IDENTITIES_TABLENAME = "identities";
 32	public static final String ACCOUNT = "account";
 33	public static final String DEVICE_ID = "device_id";
 34	public static final String ID = "id";
 35	public static final String KEY = "key";
 36	public static final String FINGERPRINT = "fingerprint";
 37	public static final String NAME = "name";
 38	public static final String TRUSTED = "trusted"; //no longer used
 39	public static final String TRUST = "trust";
 40	public static final String ACTIVE = "active";
 41	public static final String LAST_ACTIVATION = "last_activation";
 42	public static final String OWN = "ownkey";
 43	public static final String CERTIFICATE = "certificate";
 44
 45	public static final String JSONKEY_REGISTRATION_ID = "axolotl_reg_id";
 46	public static final String JSONKEY_CURRENT_PREKEY_ID = "axolotl_cur_prekey_id";
 47
 48	private static final int NUM_TRUSTS_TO_CACHE = 100;
 49
 50	private final Account account;
 51	private final XmppConnectionService mXmppConnectionService;
 52
 53	private IdentityKeyPair identityKeyPair;
 54	private int localRegistrationId;
 55	private int currentPreKeyId = 0;
 56
 57	private final LruCache<String, FingerprintStatus> trustCache =
 58			new LruCache<String, FingerprintStatus>(NUM_TRUSTS_TO_CACHE) {
 59				@Override
 60				protected FingerprintStatus create(String fingerprint) {
 61					return mXmppConnectionService.databaseBackend.getFingerprintStatus(account, fingerprint);
 62				}
 63			};
 64
 65	private static IdentityKeyPair generateIdentityKeyPair() {
 66		Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl IdentityKeyPair...");
 67		ECKeyPair identityKeyPairKeys = Curve.generateKeyPair();
 68		return new IdentityKeyPair(new IdentityKey(identityKeyPairKeys.getPublicKey()),
 69				identityKeyPairKeys.getPrivateKey());
 70	}
 71
 72	private static int generateRegistrationId() {
 73		Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl registration ID...");
 74		return KeyHelper.generateRegistrationId(true);
 75	}
 76
 77	public SQLiteAxolotlStore(Account account, XmppConnectionService service) {
 78		this.account = account;
 79		this.mXmppConnectionService = service;
 80		this.localRegistrationId = loadRegistrationId();
 81		this.currentPreKeyId = loadCurrentPreKeyId();
 82	}
 83
 84	public int getCurrentPreKeyId() {
 85		return currentPreKeyId;
 86	}
 87
 88	// --------------------------------------
 89	// IdentityKeyStore
 90	// --------------------------------------
 91
 92	private IdentityKeyPair loadIdentityKeyPair() {
 93		synchronized (mXmppConnectionService) {
 94			IdentityKeyPair ownKey = mXmppConnectionService.databaseBackend.loadOwnIdentityKeyPair(account);
 95
 96			if (ownKey != null) {
 97				return ownKey;
 98			} else {
 99				Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve own IdentityKeyPair");
100				ownKey = generateIdentityKeyPair();
101				mXmppConnectionService.databaseBackend.storeOwnIdentityKeyPair(account, ownKey);
102			}
103			return ownKey;
104		}
105	}
106
107	private int loadRegistrationId() {
108		return loadRegistrationId(false);
109	}
110
111	private int loadRegistrationId(boolean regenerate) {
112		String regIdString = this.account.getKey(JSONKEY_REGISTRATION_ID);
113		int reg_id;
114		if (!regenerate && regIdString != null) {
115			reg_id = Integer.valueOf(regIdString);
116		} else {
117			Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve axolotl registration id for account " + account.getJid());
118			reg_id = generateRegistrationId();
119			boolean success = this.account.setKey(JSONKEY_REGISTRATION_ID, Integer.toString(reg_id));
120			if (success) {
121				mXmppConnectionService.databaseBackend.updateAccount(account);
122			} else {
123				Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to write new key to the database!");
124			}
125		}
126		return reg_id;
127	}
128
129	private int loadCurrentPreKeyId() {
130		String prekeyIdString = this.account.getKey(JSONKEY_CURRENT_PREKEY_ID);
131		int prekey_id;
132		if (prekeyIdString != null) {
133			prekey_id = Integer.valueOf(prekeyIdString);
134		} else {
135			Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve current prekey id for account " + account.getJid());
136			prekey_id = 0;
137		}
138		return prekey_id;
139	}
140
141	public void regenerate() {
142		mXmppConnectionService.databaseBackend.wipeAxolotlDb(account);
143		trustCache.evictAll();
144		account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(0));
145		identityKeyPair = loadIdentityKeyPair();
146		localRegistrationId = loadRegistrationId(true);
147		currentPreKeyId = 0;
148		mXmppConnectionService.updateAccountUi();
149	}
150
151	/**
152	 * Get the local client's identity key pair.
153	 *
154	 * @return The local client's persistent identity key pair.
155	 */
156	@Override
157	public IdentityKeyPair getIdentityKeyPair() {
158		if (identityKeyPair == null) {
159			identityKeyPair = loadIdentityKeyPair();
160		}
161		return identityKeyPair;
162	}
163
164	/**
165	 * Return the local client's registration ID.
166	 * <p/>
167	 * Clients should maintain a registration ID, a random number
168	 * between 1 and 16380 that's generated once at install time.
169	 *
170	 * @return the local client's registration ID.
171	 */
172	@Override
173	public int getLocalRegistrationId() {
174		return localRegistrationId;
175	}
176
177	/**
178	 * Save a remote client's identity key
179	 * <p/>
180	 * Store a remote client's identity key as trusted.
181	 *
182	 * @param address     The address of the remote client.
183	 * @param identityKey The remote client's identity key.
184	 * @return true on success
185	 */
186	@Override
187	public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey) {
188		if (!mXmppConnectionService.databaseBackend.loadIdentityKeys(account, address.getName()).contains(identityKey)) {
189			String fingerprint = identityKey.getFingerprint().replaceAll("\\s", "");
190			FingerprintStatus status = getFingerprintStatus(fingerprint);
191			if (status == null) {
192				if (mXmppConnectionService.blindTrustBeforeVerification() && !account.getAxolotlService().hasVerifiedKeys(address.getName())) {
193					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": blindly trusted "+fingerprint+" of "+address.getName());
194					status = FingerprintStatus.createActiveTrusted();
195				} else {
196					status = FingerprintStatus.createActiveUndecided();
197				}
198			} else {
199				status = status.toActive();
200			}
201			mXmppConnectionService.databaseBackend.storeIdentityKey(account, address.getName(), identityKey, status);
202			trustCache.remove(fingerprint);
203		}
204		return true;
205	}
206
207	/**
208	 * Verify a remote client's identity key.
209	 * <p/>
210	 * Determine whether a remote client's identity is trusted.  Convention is
211	 * that the TextSecure protocol is 'trust on first use.'  This means that
212	 * an identity key is considered 'trusted' if there is no entry for the recipient
213	 * in the local store, or if it matches the saved key for a recipient in the local
214	 * store.  Only if it mismatches an entry in the local store is it considered
215	 * 'untrusted.'
216	 *
217	 * @param identityKey The identity key to verify.
218	 * @return true if trusted, false if untrusted.
219	 */
220	@Override
221	public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) {
222		return true;
223	}
224
225	public FingerprintStatus getFingerprintStatus(String fingerprint) {
226		return (fingerprint == null)? null : trustCache.get(fingerprint);
227	}
228
229	public void setFingerprintStatus(String fingerprint, FingerprintStatus status) {
230		mXmppConnectionService.databaseBackend.setIdentityKeyTrust(account, fingerprint, status);
231		trustCache.remove(fingerprint);
232	}
233
234	public void setFingerprintCertificate(String fingerprint, X509Certificate x509Certificate) {
235		mXmppConnectionService.databaseBackend.setIdentityKeyCertificate(account, fingerprint, x509Certificate);
236	}
237
238	public X509Certificate getFingerprintCertificate(String fingerprint) {
239		return mXmppConnectionService.databaseBackend.getIdentityKeyCertifcate(account, fingerprint);
240	}
241
242	public Set<IdentityKey> getContactKeysWithTrust(String bareJid, FingerprintStatus status) {
243		return mXmppConnectionService.databaseBackend.loadIdentityKeys(account, bareJid, status);
244	}
245
246	public long getContactNumTrustedKeys(String bareJid) {
247		return mXmppConnectionService.databaseBackend.numTrustedKeys(account, bareJid);
248	}
249
250	// --------------------------------------
251	// SessionStore
252	// --------------------------------------
253
254	/**
255	 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
256	 * or a new SessionRecord if one does not currently exist.
257	 * <p/>
258	 * It is important that implementations return a copy of the current durable information.  The
259	 * returned SessionRecord may be modified, but those changes should not have an effect on the
260	 * durable session state (what is returned by subsequent calls to this method) without the
261	 * store method being called here first.
262	 *
263	 * @param address The name and device ID of the remote client.
264	 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
265	 * a new SessionRecord if one does not currently exist.
266	 */
267	@Override
268	public SessionRecord loadSession(SignalProtocolAddress address) {
269		SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
270		return (session != null) ? session : new SessionRecord();
271	}
272
273	/**
274	 * Returns all known devices with active sessions for a recipient
275	 *
276	 * @param name the name of the client.
277	 * @return all known sub-devices with active sessions.
278	 */
279	@Override
280	public List<Integer> getSubDeviceSessions(String name) {
281		return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
282				new SignalProtocolAddress(name, 0));
283	}
284
285	/**
286	 * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
287	 *
288	 * @param address the address of the remote client.
289	 * @param record  the current SessionRecord for the remote client.
290	 */
291	@Override
292	public void storeSession(SignalProtocolAddress address, SessionRecord record) {
293		mXmppConnectionService.databaseBackend.storeSession(account, address, record);
294	}
295
296	/**
297	 * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
298	 *
299	 * @param address the address of the remote client.
300	 * @return true if a {@link SessionRecord} exists, false otherwise.
301	 */
302	@Override
303	public boolean containsSession(SignalProtocolAddress address) {
304		return mXmppConnectionService.databaseBackend.containsSession(account, address);
305	}
306
307	/**
308	 * Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
309	 *
310	 * @param address the address of the remote client.
311	 */
312	@Override
313	public void deleteSession(SignalProtocolAddress address) {
314		mXmppConnectionService.databaseBackend.deleteSession(account, address);
315	}
316
317	/**
318	 * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
319	 *
320	 * @param name the name of the remote client.
321	 */
322	@Override
323	public void deleteAllSessions(String name) {
324		SignalProtocolAddress address = new SignalProtocolAddress(name, 0);
325		mXmppConnectionService.databaseBackend.deleteAllSessions(account,
326				address);
327	}
328
329	// --------------------------------------
330	// PreKeyStore
331	// --------------------------------------
332
333	/**
334	 * Load a local PreKeyRecord.
335	 *
336	 * @param preKeyId the ID of the local PreKeyRecord.
337	 * @return the corresponding PreKeyRecord.
338	 * @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
339	 */
340	@Override
341	public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
342		PreKeyRecord record = mXmppConnectionService.databaseBackend.loadPreKey(account, preKeyId);
343		if (record == null) {
344			throw new InvalidKeyIdException("No such PreKeyRecord: " + preKeyId);
345		}
346		return record;
347	}
348
349	/**
350	 * Store a local PreKeyRecord.
351	 *
352	 * @param preKeyId the ID of the PreKeyRecord to store.
353	 * @param record   the PreKeyRecord.
354	 */
355	@Override
356	public void storePreKey(int preKeyId, PreKeyRecord record) {
357		mXmppConnectionService.databaseBackend.storePreKey(account, record);
358		currentPreKeyId = preKeyId;
359		boolean success = this.account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(preKeyId));
360		if (success) {
361			mXmppConnectionService.databaseBackend.updateAccount(account);
362		} else {
363			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to write new prekey id to the database!");
364		}
365	}
366
367	/**
368	 * @param preKeyId A PreKeyRecord ID.
369	 * @return true if the store has a record for the preKeyId, otherwise false.
370	 */
371	@Override
372	public boolean containsPreKey(int preKeyId) {
373		return mXmppConnectionService.databaseBackend.containsPreKey(account, preKeyId);
374	}
375
376	/**
377	 * Delete a PreKeyRecord from local storage.
378	 *
379	 * @param preKeyId The ID of the PreKeyRecord to remove.
380	 */
381	@Override
382	public void removePreKey(int preKeyId) {
383		mXmppConnectionService.databaseBackend.deletePreKey(account, preKeyId);
384	}
385
386	// --------------------------------------
387	// SignedPreKeyStore
388	// --------------------------------------
389
390	/**
391	 * Load a local SignedPreKeyRecord.
392	 *
393	 * @param signedPreKeyId the ID of the local SignedPreKeyRecord.
394	 * @return the corresponding SignedPreKeyRecord.
395	 * @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
396	 */
397	@Override
398	public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
399		SignedPreKeyRecord record = mXmppConnectionService.databaseBackend.loadSignedPreKey(account, signedPreKeyId);
400		if (record == null) {
401			throw new InvalidKeyIdException("No such SignedPreKeyRecord: " + signedPreKeyId);
402		}
403		return record;
404	}
405
406	/**
407	 * Load all local SignedPreKeyRecords.
408	 *
409	 * @return All stored SignedPreKeyRecords.
410	 */
411	@Override
412	public List<SignedPreKeyRecord> loadSignedPreKeys() {
413		return mXmppConnectionService.databaseBackend.loadSignedPreKeys(account);
414	}
415
416	public int getSignedPreKeysCount() {
417		return mXmppConnectionService.databaseBackend.getSignedPreKeysCount(account);
418	}
419
420	/**
421	 * Store a local SignedPreKeyRecord.
422	 *
423	 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
424	 * @param record         the SignedPreKeyRecord.
425	 */
426	@Override
427	public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
428		mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
429	}
430
431	/**
432	 * @param signedPreKeyId A SignedPreKeyRecord ID.
433	 * @return true if the store has a record for the signedPreKeyId, otherwise false.
434	 */
435	@Override
436	public boolean containsSignedPreKey(int signedPreKeyId) {
437		return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
438	}
439
440	/**
441	 * Delete a SignedPreKeyRecord from local storage.
442	 *
443	 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
444	 */
445	@Override
446	public void removeSignedPreKey(int signedPreKeyId) {
447		mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
448	}
449
450	public void preVerifyFingerprint(Account account, String name, String fingerprint) {
451		mXmppConnectionService.databaseBackend.storePreVerification(account,name,fingerprint,FingerprintStatus.createInactiveVerified());
452	}
453}