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