SQLiteAxolotlStore.java

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