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