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