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