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 }
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 name The name of the remote client.
183 * @param identityKey The remote client's identity key.
184 */
185 @Override
186 public void saveIdentity(String name, IdentityKey identityKey) {
187 if (!mXmppConnectionService.databaseBackend.loadIdentityKeys(account, name).contains(identityKey)) {
188 String fingerprint = identityKey.getFingerprint().replaceAll("\\s", "");
189 FingerprintStatus status = getFingerprintStatus(fingerprint);
190 if (status == null) {
191 if (mXmppConnectionService.blindTrustBeforeVerification() && !account.getAxolotlService().hasVerifiedKeys(name)) {
192 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": blindly trusted "+fingerprint+" of "+name);
193 status = FingerprintStatus.createActiveTrusted();
194 } else {
195 status = FingerprintStatus.createActiveUndecided();
196 }
197 } else {
198 status = status.toActive();
199 }
200 mXmppConnectionService.databaseBackend.storeIdentityKey(account, name, identityKey, status);
201 trustCache.remove(fingerprint);
202 }
203 }
204
205 /**
206 * Verify a remote client's identity key.
207 * <p/>
208 * Determine whether a remote client's identity is trusted. Convention is
209 * that the TextSecure protocol is 'trust on first use.' This means that
210 * an identity key is considered 'trusted' if there is no entry for the recipient
211 * in the local store, or if it matches the saved key for a recipient in the local
212 * store. Only if it mismatches an entry in the local store is it considered
213 * 'untrusted.'
214 *
215 * @param name The name of the remote client.
216 * @param identityKey The identity key to verify.
217 * @return true if trusted, false if untrusted.
218 */
219 @Override
220 public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
221 return true;
222 }
223
224 public FingerprintStatus getFingerprintStatus(String fingerprint) {
225 return (fingerprint == null)? null : trustCache.get(fingerprint);
226 }
227
228 public void setFingerprintStatus(String fingerprint, FingerprintStatus status) {
229 mXmppConnectionService.databaseBackend.setIdentityKeyTrust(account, fingerprint, status);
230 trustCache.remove(fingerprint);
231 }
232
233 public void setFingerprintCertificate(String fingerprint, X509Certificate x509Certificate) {
234 mXmppConnectionService.databaseBackend.setIdentityKeyCertificate(account, fingerprint, x509Certificate);
235 }
236
237 public X509Certificate getFingerprintCertificate(String fingerprint) {
238 return mXmppConnectionService.databaseBackend.getIdentityKeyCertifcate(account, fingerprint);
239 }
240
241 public Set<IdentityKey> getContactKeysWithTrust(String bareJid, FingerprintStatus status) {
242 return mXmppConnectionService.databaseBackend.loadIdentityKeys(account, bareJid, status);
243 }
244
245 public long getContactNumTrustedKeys(String bareJid) {
246 return mXmppConnectionService.databaseBackend.numTrustedKeys(account, bareJid);
247 }
248
249 // --------------------------------------
250 // SessionStore
251 // --------------------------------------
252
253 /**
254 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
255 * or a new SessionRecord if one does not currently exist.
256 * <p/>
257 * It is important that implementations return a copy of the current durable information. The
258 * returned SessionRecord may be modified, but those changes should not have an effect on the
259 * durable session state (what is returned by subsequent calls to this method) without the
260 * store method being called here first.
261 *
262 * @param address The name and device ID of the remote client.
263 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
264 * a new SessionRecord if one does not currently exist.
265 */
266 @Override
267 public SessionRecord loadSession(AxolotlAddress address) {
268 SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
269 return (session != null) ? session : new SessionRecord();
270 }
271
272 /**
273 * Returns all known devices with active sessions for a recipient
274 *
275 * @param name the name of the client.
276 * @return all known sub-devices with active sessions.
277 */
278 @Override
279 public List<Integer> getSubDeviceSessions(String name) {
280 return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
281 new AxolotlAddress(name, 0));
282 }
283
284 /**
285 * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
286 *
287 * @param address the address of the remote client.
288 * @param record the current SessionRecord for the remote client.
289 */
290 @Override
291 public void storeSession(AxolotlAddress address, SessionRecord record) {
292 mXmppConnectionService.databaseBackend.storeSession(account, address, record);
293 }
294
295 /**
296 * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
297 *
298 * @param address the address of the remote client.
299 * @return true if a {@link SessionRecord} exists, false otherwise.
300 */
301 @Override
302 public boolean containsSession(AxolotlAddress address) {
303 return mXmppConnectionService.databaseBackend.containsSession(account, address);
304 }
305
306 /**
307 * Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
308 *
309 * @param address the address of the remote client.
310 */
311 @Override
312 public void deleteSession(AxolotlAddress address) {
313 mXmppConnectionService.databaseBackend.deleteSession(account, address);
314 }
315
316 /**
317 * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
318 *
319 * @param name the name of the remote client.
320 */
321 @Override
322 public void deleteAllSessions(String name) {
323 AxolotlAddress address = new AxolotlAddress(name, 0);
324 mXmppConnectionService.databaseBackend.deleteAllSessions(account,
325 address);
326 }
327
328 // --------------------------------------
329 // PreKeyStore
330 // --------------------------------------
331
332 /**
333 * Load a local PreKeyRecord.
334 *
335 * @param preKeyId the ID of the local PreKeyRecord.
336 * @return the corresponding PreKeyRecord.
337 * @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
338 */
339 @Override
340 public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
341 PreKeyRecord record = mXmppConnectionService.databaseBackend.loadPreKey(account, preKeyId);
342 if (record == null) {
343 throw new InvalidKeyIdException("No such PreKeyRecord: " + preKeyId);
344 }
345 return record;
346 }
347
348 /**
349 * Store a local PreKeyRecord.
350 *
351 * @param preKeyId the ID of the PreKeyRecord to store.
352 * @param record the PreKeyRecord.
353 */
354 @Override
355 public void storePreKey(int preKeyId, PreKeyRecord record) {
356 mXmppConnectionService.databaseBackend.storePreKey(account, record);
357 currentPreKeyId = preKeyId;
358 boolean success = this.account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(preKeyId));
359 if (success) {
360 mXmppConnectionService.databaseBackend.updateAccount(account);
361 } else {
362 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to write new prekey id to the database!");
363 }
364 }
365
366 /**
367 * @param preKeyId A PreKeyRecord ID.
368 * @return true if the store has a record for the preKeyId, otherwise false.
369 */
370 @Override
371 public boolean containsPreKey(int preKeyId) {
372 return mXmppConnectionService.databaseBackend.containsPreKey(account, preKeyId);
373 }
374
375 /**
376 * Delete a PreKeyRecord from local storage.
377 *
378 * @param preKeyId The ID of the PreKeyRecord to remove.
379 */
380 @Override
381 public void removePreKey(int preKeyId) {
382 mXmppConnectionService.databaseBackend.deletePreKey(account, preKeyId);
383 }
384
385 // --------------------------------------
386 // SignedPreKeyStore
387 // --------------------------------------
388
389 /**
390 * Load a local SignedPreKeyRecord.
391 *
392 * @param signedPreKeyId the ID of the local SignedPreKeyRecord.
393 * @return the corresponding SignedPreKeyRecord.
394 * @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
395 */
396 @Override
397 public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
398 SignedPreKeyRecord record = mXmppConnectionService.databaseBackend.loadSignedPreKey(account, signedPreKeyId);
399 if (record == null) {
400 throw new InvalidKeyIdException("No such SignedPreKeyRecord: " + signedPreKeyId);
401 }
402 return record;
403 }
404
405 /**
406 * Load all local SignedPreKeyRecords.
407 *
408 * @return All stored SignedPreKeyRecords.
409 */
410 @Override
411 public List<SignedPreKeyRecord> loadSignedPreKeys() {
412 return mXmppConnectionService.databaseBackend.loadSignedPreKeys(account);
413 }
414
415 public int getSignedPreKeysCount() {
416 return mXmppConnectionService.databaseBackend.getSignedPreKeysCount(account);
417 }
418
419 /**
420 * Store a local SignedPreKeyRecord.
421 *
422 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
423 * @param record the SignedPreKeyRecord.
424 */
425 @Override
426 public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
427 mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
428 }
429
430 /**
431 * @param signedPreKeyId A SignedPreKeyRecord ID.
432 * @return true if the store has a record for the signedPreKeyId, otherwise false.
433 */
434 @Override
435 public boolean containsSignedPreKey(int signedPreKeyId) {
436 return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
437 }
438
439 /**
440 * Delete a SignedPreKeyRecord from local storage.
441 *
442 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
443 */
444 @Override
445 public void removeSignedPreKey(int signedPreKeyId) {
446 mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
447 }
448
449 public void preVerifyFingerprint(Account account, String name, String fingerprint) {
450 mXmppConnectionService.databaseBackend.storePreVerification(account,name,fingerprint,FingerprintStatus.createInactiveVerified());
451 }
452}