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 IdentityKeyPair ownKey = mXmppConnectionService.databaseBackend.loadOwnIdentityKeyPair(account);
94
95 if (ownKey != null) {
96 return ownKey;
97 } else {
98 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve own IdentityKeyPair");
99 ownKey = generateIdentityKeyPair();
100 mXmppConnectionService.databaseBackend.storeOwnIdentityKeyPair(account, ownKey);
101 }
102 return ownKey;
103 }
104
105 private int loadRegistrationId() {
106 return loadRegistrationId(false);
107 }
108
109 private int loadRegistrationId(boolean regenerate) {
110 String regIdString = this.account.getKey(JSONKEY_REGISTRATION_ID);
111 int reg_id;
112 if (!regenerate && regIdString != null) {
113 reg_id = Integer.valueOf(regIdString);
114 } else {
115 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve axolotl registration id for account " + account.getJid());
116 reg_id = generateRegistrationId();
117 boolean success = this.account.setKey(JSONKEY_REGISTRATION_ID, Integer.toString(reg_id));
118 if (success) {
119 mXmppConnectionService.databaseBackend.updateAccount(account);
120 } else {
121 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to write new key to the database!");
122 }
123 }
124 return reg_id;
125 }
126
127 private int loadCurrentPreKeyId() {
128 String prekeyIdString = this.account.getKey(JSONKEY_CURRENT_PREKEY_ID);
129 int prekey_id;
130 if (prekeyIdString != null) {
131 prekey_id = Integer.valueOf(prekeyIdString);
132 } else {
133 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Could not retrieve current prekey id for account " + account.getJid());
134 prekey_id = 0;
135 }
136 return prekey_id;
137 }
138
139 public void regenerate() {
140 mXmppConnectionService.databaseBackend.wipeAxolotlDb(account);
141 trustCache.evictAll();
142 account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(0));
143 identityKeyPair = loadIdentityKeyPair();
144 localRegistrationId = loadRegistrationId(true);
145 currentPreKeyId = 0;
146 mXmppConnectionService.updateAccountUi();
147 }
148
149 /**
150 * Get the local client's identity key pair.
151 *
152 * @return The local client's persistent identity key pair.
153 */
154 @Override
155 public IdentityKeyPair getIdentityKeyPair() {
156 if (identityKeyPair == null) {
157 identityKeyPair = loadIdentityKeyPair();
158 }
159 return identityKeyPair;
160 }
161
162 /**
163 * Return the local client's registration ID.
164 * <p/>
165 * Clients should maintain a registration ID, a random number
166 * between 1 and 16380 that's generated once at install time.
167 *
168 * @return the local client's registration ID.
169 */
170 @Override
171 public int getLocalRegistrationId() {
172 return localRegistrationId;
173 }
174
175 /**
176 * Save a remote client's identity key
177 * <p/>
178 * Store a remote client's identity key as trusted.
179 *
180 * @param name The name of the remote client.
181 * @param identityKey The remote client's identity key.
182 */
183 @Override
184 public void saveIdentity(String name, IdentityKey identityKey) {
185 if (!mXmppConnectionService.databaseBackend.loadIdentityKeys(account, name).contains(identityKey)) {
186 mXmppConnectionService.databaseBackend.storeIdentityKey(account, name, identityKey);
187 }
188 }
189
190 /**
191 * Verify a remote client's identity key.
192 * <p/>
193 * Determine whether a remote client's identity is trusted. Convention is
194 * that the TextSecure protocol is 'trust on first use.' This means that
195 * an identity key is considered 'trusted' if there is no entry for the recipient
196 * in the local store, or if it matches the saved key for a recipient in the local
197 * store. Only if it mismatches an entry in the local store is it considered
198 * 'untrusted.'
199 *
200 * @param name The name of the remote client.
201 * @param identityKey The identity key to verify.
202 * @return true if trusted, false if untrusted.
203 */
204 @Override
205 public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
206 return true;
207 }
208
209 public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
210 return (fingerprint == null)? null : trustCache.get(fingerprint);
211 }
212
213 public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
214 mXmppConnectionService.databaseBackend.setIdentityKeyTrust(account, fingerprint, trust);
215 trustCache.remove(fingerprint);
216 }
217
218 public void setFingerprintCertificate(String fingerprint, X509Certificate x509Certificate) {
219 mXmppConnectionService.databaseBackend.setIdentityKeyCertificate(account, fingerprint, x509Certificate);
220 }
221
222 public X509Certificate getFingerprintCertificate(String fingerprint) {
223 return mXmppConnectionService.databaseBackend.getIdentityKeyCertifcate(account, fingerprint);
224 }
225
226 public Set<IdentityKey> getContactKeysWithTrust(String bareJid, XmppAxolotlSession.Trust trust) {
227 return mXmppConnectionService.databaseBackend.loadIdentityKeys(account, bareJid, trust);
228 }
229
230 public long getContactNumTrustedKeys(String bareJid) {
231 return mXmppConnectionService.databaseBackend.numTrustedKeys(account, bareJid);
232 }
233
234 // --------------------------------------
235 // SessionStore
236 // --------------------------------------
237
238 /**
239 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
240 * or a new SessionRecord if one does not currently exist.
241 * <p/>
242 * It is important that implementations return a copy of the current durable information. The
243 * returned SessionRecord may be modified, but those changes should not have an effect on the
244 * durable session state (what is returned by subsequent calls to this method) without the
245 * store method being called here first.
246 *
247 * @param address The name and device ID of the remote client.
248 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
249 * a new SessionRecord if one does not currently exist.
250 */
251 @Override
252 public SessionRecord loadSession(AxolotlAddress address) {
253 SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
254 return (session != null) ? session : new SessionRecord();
255 }
256
257 /**
258 * Returns all known devices with active sessions for a recipient
259 *
260 * @param name the name of the client.
261 * @return all known sub-devices with active sessions.
262 */
263 @Override
264 public List<Integer> getSubDeviceSessions(String name) {
265 return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
266 new AxolotlAddress(name, 0));
267 }
268
269 /**
270 * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
271 *
272 * @param address the address of the remote client.
273 * @param record the current SessionRecord for the remote client.
274 */
275 @Override
276 public void storeSession(AxolotlAddress address, SessionRecord record) {
277 mXmppConnectionService.databaseBackend.storeSession(account, address, record);
278 }
279
280 /**
281 * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
282 *
283 * @param address the address of the remote client.
284 * @return true if a {@link SessionRecord} exists, false otherwise.
285 */
286 @Override
287 public boolean containsSession(AxolotlAddress address) {
288 return mXmppConnectionService.databaseBackend.containsSession(account, address);
289 }
290
291 /**
292 * Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
293 *
294 * @param address the address of the remote client.
295 */
296 @Override
297 public void deleteSession(AxolotlAddress address) {
298 mXmppConnectionService.databaseBackend.deleteSession(account, address);
299 }
300
301 /**
302 * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
303 *
304 * @param name the name of the remote client.
305 */
306 @Override
307 public void deleteAllSessions(String name) {
308 AxolotlAddress address = new AxolotlAddress(name, 0);
309 mXmppConnectionService.databaseBackend.deleteAllSessions(account,
310 address);
311 }
312
313 // --------------------------------------
314 // PreKeyStore
315 // --------------------------------------
316
317 /**
318 * Load a local PreKeyRecord.
319 *
320 * @param preKeyId the ID of the local PreKeyRecord.
321 * @return the corresponding PreKeyRecord.
322 * @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
323 */
324 @Override
325 public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
326 PreKeyRecord record = mXmppConnectionService.databaseBackend.loadPreKey(account, preKeyId);
327 if (record == null) {
328 throw new InvalidKeyIdException("No such PreKeyRecord: " + preKeyId);
329 }
330 return record;
331 }
332
333 /**
334 * Store a local PreKeyRecord.
335 *
336 * @param preKeyId the ID of the PreKeyRecord to store.
337 * @param record the PreKeyRecord.
338 */
339 @Override
340 public void storePreKey(int preKeyId, PreKeyRecord record) {
341 mXmppConnectionService.databaseBackend.storePreKey(account, record);
342 currentPreKeyId = preKeyId;
343 boolean success = this.account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(preKeyId));
344 if (success) {
345 mXmppConnectionService.databaseBackend.updateAccount(account);
346 } else {
347 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to write new prekey id to the database!");
348 }
349 }
350
351 /**
352 * @param preKeyId A PreKeyRecord ID.
353 * @return true if the store has a record for the preKeyId, otherwise false.
354 */
355 @Override
356 public boolean containsPreKey(int preKeyId) {
357 return mXmppConnectionService.databaseBackend.containsPreKey(account, preKeyId);
358 }
359
360 /**
361 * Delete a PreKeyRecord from local storage.
362 *
363 * @param preKeyId The ID of the PreKeyRecord to remove.
364 */
365 @Override
366 public void removePreKey(int preKeyId) {
367 mXmppConnectionService.databaseBackend.deletePreKey(account, preKeyId);
368 }
369
370 // --------------------------------------
371 // SignedPreKeyStore
372 // --------------------------------------
373
374 /**
375 * Load a local SignedPreKeyRecord.
376 *
377 * @param signedPreKeyId the ID of the local SignedPreKeyRecord.
378 * @return the corresponding SignedPreKeyRecord.
379 * @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
380 */
381 @Override
382 public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
383 SignedPreKeyRecord record = mXmppConnectionService.databaseBackend.loadSignedPreKey(account, signedPreKeyId);
384 if (record == null) {
385 throw new InvalidKeyIdException("No such SignedPreKeyRecord: " + signedPreKeyId);
386 }
387 return record;
388 }
389
390 /**
391 * Load all local SignedPreKeyRecords.
392 *
393 * @return All stored SignedPreKeyRecords.
394 */
395 @Override
396 public List<SignedPreKeyRecord> loadSignedPreKeys() {
397 return mXmppConnectionService.databaseBackend.loadSignedPreKeys(account);
398 }
399
400 /**
401 * Store a local SignedPreKeyRecord.
402 *
403 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
404 * @param record the SignedPreKeyRecord.
405 */
406 @Override
407 public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
408 mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
409 }
410
411 /**
412 * @param signedPreKeyId A SignedPreKeyRecord ID.
413 * @return true if the store has a record for the signedPreKeyId, otherwise false.
414 */
415 @Override
416 public boolean containsSignedPreKey(int signedPreKeyId) {
417 return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
418 }
419
420 /**
421 * Delete a SignedPreKeyRecord from local storage.
422 *
423 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
424 */
425 @Override
426 public void removeSignedPreKey(int signedPreKeyId) {
427 mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
428 }
429}