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