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.entities.Contact;
25import eu.siacs.conversations.services.XmppConnectionService;
26import eu.siacs.conversations.xmpp.jid.InvalidJidException;
27import eu.siacs.conversations.xmpp.jid.Jid;
28
29public class SQLiteAxolotlStore implements AxolotlStore {
30
31 public static final String PREKEY_TABLENAME = "prekeys";
32 public static final String SIGNED_PREKEY_TABLENAME = "signed_prekeys";
33 public static final String SESSION_TABLENAME = "sessions";
34 public static final String IDENTITIES_TABLENAME = "identities";
35 public static final String ACCOUNT = "account";
36 public static final String DEVICE_ID = "device_id";
37 public static final String ID = "id";
38 public static final String KEY = "key";
39 public static final String FINGERPRINT = "fingerprint";
40 public static final String NAME = "name";
41 public static final String TRUSTED = "trusted"; //no longer used
42 public static final String TRUST = "trust";
43 public static final String ACTIVE = "active";
44 public static final String LAST_ACTIVATION = "last_activation";
45 public static final String OWN = "ownkey";
46 public static final String CERTIFICATE = "certificate";
47
48 public static final String JSONKEY_REGISTRATION_ID = "axolotl_reg_id";
49 public static final String JSONKEY_CURRENT_PREKEY_ID = "axolotl_cur_prekey_id";
50
51 private static final int NUM_TRUSTS_TO_CACHE = 100;
52
53 private final Account account;
54 private final XmppConnectionService mXmppConnectionService;
55
56 private IdentityKeyPair identityKeyPair;
57 private int localRegistrationId;
58 private int currentPreKeyId = 0;
59
60 private final LruCache<String, FingerprintStatus> trustCache =
61 new LruCache<String, FingerprintStatus>(NUM_TRUSTS_TO_CACHE) {
62 @Override
63 protected FingerprintStatus create(String fingerprint) {
64 return mXmppConnectionService.databaseBackend.getFingerprintStatus(account, fingerprint);
65 }
66 };
67
68 private static IdentityKeyPair generateIdentityKeyPair() {
69 Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl IdentityKeyPair...");
70 ECKeyPair identityKeyPairKeys = Curve.generateKeyPair();
71 return new IdentityKeyPair(new IdentityKey(identityKeyPairKeys.getPublicKey()),
72 identityKeyPairKeys.getPrivateKey());
73 }
74
75 private static int generateRegistrationId() {
76 Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl registration ID...");
77 return KeyHelper.generateRegistrationId(true);
78 }
79
80 public SQLiteAxolotlStore(Account account, XmppConnectionService service) {
81 this.account = account;
82 this.mXmppConnectionService = service;
83 this.localRegistrationId = loadRegistrationId();
84 this.currentPreKeyId = loadCurrentPreKeyId();
85 for (SignedPreKeyRecord record : loadSignedPreKeys()) {
86 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got Axolotl signed prekey record:" + record.getId());
87 }
88 }
89
90 public int getCurrentPreKeyId() {
91 return currentPreKeyId;
92 }
93
94 // --------------------------------------
95 // IdentityKeyStore
96 // --------------------------------------
97
98 private IdentityKeyPair loadIdentityKeyPair() {
99 synchronized (mXmppConnectionService) {
100 IdentityKeyPair ownKey = mXmppConnectionService.databaseBackend.loadOwnIdentityKeyPair(account);
101
102 if (ownKey != null) {
103 return ownKey;
104 } else {
105 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve own IdentityKeyPair");
106 ownKey = generateIdentityKeyPair();
107 mXmppConnectionService.databaseBackend.storeOwnIdentityKeyPair(account, ownKey);
108 }
109 return ownKey;
110 }
111 }
112
113 private int loadRegistrationId() {
114 return loadRegistrationId(false);
115 }
116
117 private int loadRegistrationId(boolean regenerate) {
118 String regIdString = this.account.getKey(JSONKEY_REGISTRATION_ID);
119 int reg_id;
120 if (!regenerate && regIdString != null) {
121 reg_id = Integer.valueOf(regIdString);
122 } else {
123 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve axolotl registration id for account " + account.getJid());
124 reg_id = generateRegistrationId();
125 boolean success = this.account.setKey(JSONKEY_REGISTRATION_ID, Integer.toString(reg_id));
126 if (success) {
127 mXmppConnectionService.databaseBackend.updateAccount(account);
128 } else {
129 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to write new key to the database!");
130 }
131 }
132 return reg_id;
133 }
134
135 private int loadCurrentPreKeyId() {
136 String prekeyIdString = this.account.getKey(JSONKEY_CURRENT_PREKEY_ID);
137 int prekey_id;
138 if (prekeyIdString != null) {
139 prekey_id = Integer.valueOf(prekeyIdString);
140 } else {
141 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve current prekey id for account " + account.getJid());
142 prekey_id = 0;
143 }
144 return prekey_id;
145 }
146
147 public void regenerate() {
148 mXmppConnectionService.databaseBackend.wipeAxolotlDb(account);
149 trustCache.evictAll();
150 account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(0));
151 identityKeyPair = loadIdentityKeyPair();
152 localRegistrationId = loadRegistrationId(true);
153 currentPreKeyId = 0;
154 mXmppConnectionService.updateAccountUi();
155 }
156
157 /**
158 * Get the local client's identity key pair.
159 *
160 * @return The local client's persistent identity key pair.
161 */
162 @Override
163 public IdentityKeyPair getIdentityKeyPair() {
164 if (identityKeyPair == null) {
165 identityKeyPair = loadIdentityKeyPair();
166 }
167 return identityKeyPair;
168 }
169
170 /**
171 * Return the local client's registration ID.
172 * <p/>
173 * Clients should maintain a registration ID, a random number
174 * between 1 and 16380 that's generated once at install time.
175 *
176 * @return the local client's registration ID.
177 */
178 @Override
179 public int getLocalRegistrationId() {
180 return localRegistrationId;
181 }
182
183 /**
184 * Save a remote client's identity key
185 * <p/>
186 * Store a remote client's identity key as trusted.
187 *
188 * @param name The name of the remote client.
189 * @param identityKey The remote client's identity key.
190 */
191 @Override
192 public void saveIdentity(String name, IdentityKey identityKey) {
193 if (!mXmppConnectionService.databaseBackend.loadIdentityKeys(account, name).contains(identityKey)) {
194 String fingerprint = identityKey.getFingerprint().replaceAll("\\s", "");
195 FingerprintStatus status = getFingerprintStatus(fingerprint);
196 if (status == null) {
197 if (mXmppConnectionService.blindTrustBeforeVerification() && !account.getAxolotlService().hasVerifiedKeys(name)) {
198 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": blindly trusted "+fingerprint+" of "+name);
199 status = FingerprintStatus.createActiveTrusted();
200 } else {
201 status = FingerprintStatus.createActiveUndecided();
202 }
203 } else {
204 status = status.toActive();
205 }
206 mXmppConnectionService.databaseBackend.storeIdentityKey(account, name, identityKey, status);
207 trustCache.remove(fingerprint);
208 }
209 }
210
211 /**
212 * Verify a remote client's identity key.
213 * <p/>
214 * Determine whether a remote client's identity is trusted. Convention is
215 * that the TextSecure protocol is 'trust on first use.' This means that
216 * an identity key is considered 'trusted' if there is no entry for the recipient
217 * in the local store, or if it matches the saved key for a recipient in the local
218 * store. Only if it mismatches an entry in the local store is it considered
219 * 'untrusted.'
220 *
221 * @param name The name of the remote client.
222 * @param identityKey The identity key to verify.
223 * @return true if trusted, false if untrusted.
224 */
225 @Override
226 public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
227 return true;
228 }
229
230 public FingerprintStatus getFingerprintStatus(String fingerprint) {
231 return (fingerprint == null)? null : trustCache.get(fingerprint);
232 }
233
234 public void setFingerprintStatus(String fingerprint, FingerprintStatus status) {
235 mXmppConnectionService.databaseBackend.setIdentityKeyTrust(account, fingerprint, status);
236 trustCache.remove(fingerprint);
237 }
238
239 public void setFingerprintCertificate(String fingerprint, X509Certificate x509Certificate) {
240 mXmppConnectionService.databaseBackend.setIdentityKeyCertificate(account, fingerprint, x509Certificate);
241 }
242
243 public X509Certificate getFingerprintCertificate(String fingerprint) {
244 return mXmppConnectionService.databaseBackend.getIdentityKeyCertifcate(account, fingerprint);
245 }
246
247 public Set<IdentityKey> getContactKeysWithTrust(String bareJid, FingerprintStatus status) {
248 return mXmppConnectionService.databaseBackend.loadIdentityKeys(account, bareJid, status);
249 }
250
251 public long getContactNumTrustedKeys(String bareJid) {
252 return mXmppConnectionService.databaseBackend.numTrustedKeys(account, bareJid);
253 }
254
255 // --------------------------------------
256 // SessionStore
257 // --------------------------------------
258
259 /**
260 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
261 * or a new SessionRecord if one does not currently exist.
262 * <p/>
263 * It is important that implementations return a copy of the current durable information. The
264 * returned SessionRecord may be modified, but those changes should not have an effect on the
265 * durable session state (what is returned by subsequent calls to this method) without the
266 * store method being called here first.
267 *
268 * @param address The name and device ID of the remote client.
269 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
270 * a new SessionRecord if one does not currently exist.
271 */
272 @Override
273 public SessionRecord loadSession(AxolotlAddress address) {
274 SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
275 return (session != null) ? session : new SessionRecord();
276 }
277
278 /**
279 * Returns all known devices with active sessions for a recipient
280 *
281 * @param name the name of the client.
282 * @return all known sub-devices with active sessions.
283 */
284 @Override
285 public List<Integer> getSubDeviceSessions(String name) {
286 return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
287 new AxolotlAddress(name, 0));
288 }
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(AxolotlAddress 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(AxolotlAddress 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(AxolotlAddress 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 AxolotlAddress address = new AxolotlAddress(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 /**
422 * Store a local SignedPreKeyRecord.
423 *
424 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
425 * @param record the SignedPreKeyRecord.
426 */
427 @Override
428 public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
429 mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
430 }
431
432 /**
433 * @param signedPreKeyId A SignedPreKeyRecord ID.
434 * @return true if the store has a record for the signedPreKeyId, otherwise false.
435 */
436 @Override
437 public boolean containsSignedPreKey(int signedPreKeyId) {
438 return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
439 }
440
441 /**
442 * Delete a SignedPreKeyRecord from local storage.
443 *
444 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
445 */
446 @Override
447 public void removeSignedPreKey(int signedPreKeyId) {
448 mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
449 }
450
451 public void preVerifyFingerprint(Account account, String name, String fingerprint) {
452 mXmppConnectionService.databaseBackend.storePreVerification(account,name,fingerprint,FingerprintStatus.createInactiveVerified());
453 }
454}