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