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