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