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";
39 public static final String OWN = "ownkey";
40 public static final String CERTIFICATE = "certificate";
41
42 public static final String JSONKEY_REGISTRATION_ID = "axolotl_reg_id";
43 public static final String JSONKEY_CURRENT_PREKEY_ID = "axolotl_cur_prekey_id";
44
45 private static final int NUM_TRUSTS_TO_CACHE = 100;
46
47 private final Account account;
48 private final XmppConnectionService mXmppConnectionService;
49
50 private IdentityKeyPair identityKeyPair;
51 private int localRegistrationId;
52 private int currentPreKeyId = 0;
53
54 private final LruCache<String, XmppAxolotlSession.Trust> trustCache =
55 new LruCache<String, XmppAxolotlSession.Trust>(NUM_TRUSTS_TO_CACHE) {
56 @Override
57 protected XmppAxolotlSession.Trust create(String fingerprint) {
58 return mXmppConnectionService.databaseBackend.isIdentityKeyTrusted(account, fingerprint);
59 }
60 };
61
62 private static IdentityKeyPair generateIdentityKeyPair() {
63 Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl IdentityKeyPair...");
64 ECKeyPair identityKeyPairKeys = Curve.generateKeyPair();
65 return new IdentityKeyPair(new IdentityKey(identityKeyPairKeys.getPublicKey()),
66 identityKeyPairKeys.getPrivateKey());
67 }
68
69 private static int generateRegistrationId() {
70 Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl registration ID...");
71 return KeyHelper.generateRegistrationId(true);
72 }
73
74 public SQLiteAxolotlStore(Account account, XmppConnectionService service) {
75 this.account = account;
76 this.mXmppConnectionService = service;
77 this.localRegistrationId = loadRegistrationId();
78 this.currentPreKeyId = loadCurrentPreKeyId();
79 for (SignedPreKeyRecord record : loadSignedPreKeys()) {
80 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got Axolotl signed prekey record:" + record.getId());
81 }
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 mXmppConnectionService.databaseBackend.storeIdentityKey(account, name, identityKey);
189 }
190 }
191
192 /**
193 * Verify a remote client's identity key.
194 * <p/>
195 * Determine whether a remote client's identity is trusted. Convention is
196 * that the TextSecure protocol is 'trust on first use.' This means that
197 * an identity key is considered 'trusted' if there is no entry for the recipient
198 * in the local store, or if it matches the saved key for a recipient in the local
199 * store. Only if it mismatches an entry in the local store is it considered
200 * 'untrusted.'
201 *
202 * @param name The name of the remote client.
203 * @param identityKey The identity key to verify.
204 * @return true if trusted, false if untrusted.
205 */
206 @Override
207 public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
208 return true;
209 }
210
211 public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
212 return (fingerprint == null)? null : trustCache.get(fingerprint);
213 }
214
215 public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
216 mXmppConnectionService.databaseBackend.setIdentityKeyTrust(account, fingerprint, trust);
217 trustCache.remove(fingerprint);
218 }
219
220 public void setFingerprintCertificate(String fingerprint, X509Certificate x509Certificate) {
221 mXmppConnectionService.databaseBackend.setIdentityKeyCertificate(account, fingerprint, x509Certificate);
222 }
223
224 public X509Certificate getFingerprintCertificate(String fingerprint) {
225 return mXmppConnectionService.databaseBackend.getIdentityKeyCertifcate(account, fingerprint);
226 }
227
228 public Set<IdentityKey> getContactKeysWithTrust(String bareJid, XmppAxolotlSession.Trust trust) {
229 return mXmppConnectionService.databaseBackend.loadIdentityKeys(account, bareJid, trust);
230 }
231
232 public long getContactNumTrustedKeys(String bareJid) {
233 return mXmppConnectionService.databaseBackend.numTrustedKeys(account, bareJid);
234 }
235
236 // --------------------------------------
237 // SessionStore
238 // --------------------------------------
239
240 /**
241 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
242 * or a new SessionRecord if one does not currently exist.
243 * <p/>
244 * It is important that implementations return a copy of the current durable information. The
245 * returned SessionRecord may be modified, but those changes should not have an effect on the
246 * durable session state (what is returned by subsequent calls to this method) without the
247 * store method being called here first.
248 *
249 * @param address The name and device ID of the remote client.
250 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
251 * a new SessionRecord if one does not currently exist.
252 */
253 @Override
254 public SessionRecord loadSession(AxolotlAddress address) {
255 SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
256 return (session != null) ? session : new SessionRecord();
257 }
258
259 /**
260 * Returns all known devices with active sessions for a recipient
261 *
262 * @param name the name of the client.
263 * @return all known sub-devices with active sessions.
264 */
265 @Override
266 public List<Integer> getSubDeviceSessions(String name) {
267 return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
268 new AxolotlAddress(name, 0));
269 }
270
271 /**
272 * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
273 *
274 * @param address the address of the remote client.
275 * @param record the current SessionRecord for the remote client.
276 */
277 @Override
278 public void storeSession(AxolotlAddress address, SessionRecord record) {
279 mXmppConnectionService.databaseBackend.storeSession(account, address, record);
280 }
281
282 /**
283 * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
284 *
285 * @param address the address of the remote client.
286 * @return true if a {@link SessionRecord} exists, false otherwise.
287 */
288 @Override
289 public boolean containsSession(AxolotlAddress address) {
290 return mXmppConnectionService.databaseBackend.containsSession(account, address);
291 }
292
293 /**
294 * Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
295 *
296 * @param address the address of the remote client.
297 */
298 @Override
299 public void deleteSession(AxolotlAddress address) {
300 mXmppConnectionService.databaseBackend.deleteSession(account, address);
301 }
302
303 /**
304 * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
305 *
306 * @param name the name of the remote client.
307 */
308 @Override
309 public void deleteAllSessions(String name) {
310 AxolotlAddress address = new AxolotlAddress(name, 0);
311 mXmppConnectionService.databaseBackend.deleteAllSessions(account,
312 address);
313 }
314
315 // --------------------------------------
316 // PreKeyStore
317 // --------------------------------------
318
319 /**
320 * Load a local PreKeyRecord.
321 *
322 * @param preKeyId the ID of the local PreKeyRecord.
323 * @return the corresponding PreKeyRecord.
324 * @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
325 */
326 @Override
327 public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
328 PreKeyRecord record = mXmppConnectionService.databaseBackend.loadPreKey(account, preKeyId);
329 if (record == null) {
330 throw new InvalidKeyIdException("No such PreKeyRecord: " + preKeyId);
331 }
332 return record;
333 }
334
335 /**
336 * Store a local PreKeyRecord.
337 *
338 * @param preKeyId the ID of the PreKeyRecord to store.
339 * @param record the PreKeyRecord.
340 */
341 @Override
342 public void storePreKey(int preKeyId, PreKeyRecord record) {
343 mXmppConnectionService.databaseBackend.storePreKey(account, record);
344 currentPreKeyId = preKeyId;
345 boolean success = this.account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(preKeyId));
346 if (success) {
347 mXmppConnectionService.databaseBackend.updateAccount(account);
348 } else {
349 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to write new prekey id to the database!");
350 }
351 }
352
353 /**
354 * @param preKeyId A PreKeyRecord ID.
355 * @return true if the store has a record for the preKeyId, otherwise false.
356 */
357 @Override
358 public boolean containsPreKey(int preKeyId) {
359 return mXmppConnectionService.databaseBackend.containsPreKey(account, preKeyId);
360 }
361
362 /**
363 * Delete a PreKeyRecord from local storage.
364 *
365 * @param preKeyId The ID of the PreKeyRecord to remove.
366 */
367 @Override
368 public void removePreKey(int preKeyId) {
369 mXmppConnectionService.databaseBackend.deletePreKey(account, preKeyId);
370 }
371
372 // --------------------------------------
373 // SignedPreKeyStore
374 // --------------------------------------
375
376 /**
377 * Load a local SignedPreKeyRecord.
378 *
379 * @param signedPreKeyId the ID of the local SignedPreKeyRecord.
380 * @return the corresponding SignedPreKeyRecord.
381 * @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
382 */
383 @Override
384 public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
385 SignedPreKeyRecord record = mXmppConnectionService.databaseBackend.loadSignedPreKey(account, signedPreKeyId);
386 if (record == null) {
387 throw new InvalidKeyIdException("No such SignedPreKeyRecord: " + signedPreKeyId);
388 }
389 return record;
390 }
391
392 /**
393 * Load all local SignedPreKeyRecords.
394 *
395 * @return All stored SignedPreKeyRecords.
396 */
397 @Override
398 public List<SignedPreKeyRecord> loadSignedPreKeys() {
399 return mXmppConnectionService.databaseBackend.loadSignedPreKeys(account);
400 }
401
402 /**
403 * Store a local SignedPreKeyRecord.
404 *
405 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
406 * @param record the SignedPreKeyRecord.
407 */
408 @Override
409 public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
410 mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
411 }
412
413 /**
414 * @param signedPreKeyId A SignedPreKeyRecord ID.
415 * @return true if the store has a record for the signedPreKeyId, otherwise false.
416 */
417 @Override
418 public boolean containsSignedPreKey(int signedPreKeyId) {
419 return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
420 }
421
422 /**
423 * Delete a SignedPreKeyRecord from local storage.
424 *
425 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
426 */
427 @Override
428 public void removeSignedPreKey(int signedPreKeyId) {
429 mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
430 }
431}