blob: 3fa4cf021856bae64196f76df7b31289dee7b0c1 [file] [log] [blame]
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskisb42fc182020-12-15 08:41:27 -080015use crate::{
Paul Crowley8d5b2532021-03-19 10:53:07 -070016 database::BlobMetaData,
17 database::BlobMetaEntry,
18 database::EncryptedBy,
19 database::KeyEntry,
20 database::KeyType,
21 database::{KeyMetaData, KeyMetaEntry, KeystoreDB},
22 ec_crypto::ECDHPrivateKey,
23 enforcements::Enforcements,
24 error::Error,
25 error::ResponseCode,
26 key_parameter::KeyParameter,
27 legacy_blob::LegacyBlobLoader,
28 legacy_migrator::LegacyMigrator,
29 try_insert::TryInsert,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080030};
31use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
32use anyhow::{Context, Result};
33use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070034 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
35 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080036};
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000037use std::ops::Deref;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080038use std::{
39 collections::HashMap,
40 sync::Arc,
41 sync::{Mutex, Weak},
42};
43
44type UserId = u32;
45
Paul Crowley8d5b2532021-03-19 10:53:07 -070046/// Encryption algorithm used by a particular type of superencryption key
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum SuperEncryptionAlgorithm {
49 /// Symmetric encryption with AES-256-GCM
50 Aes256Gcm,
51 /// Public-key encryption with ECDH P-256
52 EcdhP256,
53}
54
Paul Crowley7a658392021-03-18 17:08:20 -070055/// A particular user may have several superencryption keys in the database, each for a
56/// different purpose, distinguished by alias. Each is associated with a static
57/// constant of this type.
58pub struct SuperKeyType {
59 /// Alias used to look the key up in the `persistent.keyentry` table.
60 pub alias: &'static str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070061 /// Encryption algorithm
62 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070063}
64
65/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
66/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070067pub const USER_SUPER_KEY: SuperKeyType =
68 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070069/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
70/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070071/// Symmetric.
72pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
73 alias: "USER_SCREEN_LOCK_BOUND_KEY",
74 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
75};
76/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
77/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
78/// Asymmetric, so keys can be encrypted when the device is locked.
79pub const USER_SCREEN_LOCK_BOUND_ECDH_KEY: SuperKeyType = SuperKeyType {
80 alias: "USER_SCREEN_LOCK_BOUND_ECDH_KEY",
81 algorithm: SuperEncryptionAlgorithm::EcdhP256,
82};
Paul Crowley7a658392021-03-18 17:08:20 -070083
84/// Superencryption to apply to a new key.
85#[derive(Debug, Clone, Copy)]
86pub enum SuperEncryptionType {
87 /// Do not superencrypt this key.
88 None,
89 /// Superencrypt with a key that remains in memory from first unlock to reboot.
90 LskfBound,
91 /// Superencrypt with a key cleared from memory when the device is locked.
92 ScreenLockBound,
93}
94
Hasini Gunasinghe0e161452021-01-27 19:34:37 +000095pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -070096 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070097 key: ZVec,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +000098 // id of the super key in the database.
99 id: i64,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700100 /// ECDH is more expensive than AES. So on ECDH private keys we set the
101 /// reencrypt_with field to point at the corresponding AES key, and the
102 /// keys will be re-encrypted with AES on first use.
103 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000104}
105
106impl SuperKey {
Paul Crowley7a658392021-03-18 17:08:20 -0700107 /// For most purposes `unwrap_key` handles decryption,
108 /// but legacy handling and some tests need to assume AES and decrypt directly.
109 pub fn aes_gcm_decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700110 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
111 aes_gcm_decrypt(data, iv, tag, &self.key)
112 .context("In aes_gcm_decrypt: decryption failed")
113 } else {
114 Err(Error::sys()).context("In aes_gcm_decrypt: Key is not an AES key")
115 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000116 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700117}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000118
Paul Crowleye8826e52021-03-31 08:33:53 -0700119#[derive(Default)]
120struct UserSuperKeys {
121 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
122 /// key per android user. The key is stored on flash encrypted with a key derived from a
123 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
124 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
125 /// and stays memory resident until the device reboots.
126 per_boot: Option<Arc<SuperKey>>,
127 /// The screen lock key works like the per boot key with the distinction that it is cleared
128 /// from memory when the screen lock is engaged.
129 screen_lock_bound: Option<Arc<SuperKey>>,
130 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
131 /// ECDH public-key encryption. This field holds the decryption private key.
132 screen_lock_bound_private: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000133}
134
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800135#[derive(Default)]
136struct SkmState {
137 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700138 key_index: HashMap<i64, Weak<SuperKey>>,
139}
140
141impl SkmState {
142 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) {
143 self.key_index.insert(super_key.id, Arc::downgrade(super_key));
144 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800145}
146
147#[derive(Default)]
148pub struct SuperKeyManager {
149 data: Mutex<SkmState>,
150}
151
152impl SuperKeyManager {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800153 pub fn forget_all_keys_for_user(&self, user: UserId) {
154 let mut data = self.data.lock().unwrap();
155 data.user_keys.remove(&user);
156 }
157
Paul Crowley7a658392021-03-18 17:08:20 -0700158 fn install_per_boot_key_for_user(&self, user: UserId, super_key: Arc<SuperKey>) {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800159 let mut data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700160 data.add_key_to_key_index(&super_key);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000161 data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800162 }
163
Paul Crowleye8826e52021-03-31 08:33:53 -0700164 fn lookup_key(&self, key_id: &i64) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800165 self.data.lock().unwrap().key_index.get(key_id).and_then(|k| k.upgrade())
166 }
167
Paul Crowley7a658392021-03-18 17:08:20 -0700168 pub fn get_per_boot_key_by_user_id(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800169 let data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700170 data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800171 }
172
173 /// This function unlocks the super keys for a given user.
174 /// This means the key is loaded from the database, decrypted and placed in the
175 /// super key cache. If there is no such key a new key is created, encrypted with
176 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800177 pub fn unlock_user_key(
178 &self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000179 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800180 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700181 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800182 legacy_blob_loader: &LegacyBlobLoader,
183 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800184 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800185 .get_or_create_key_with(
186 Domain::APP,
187 user as u64 as i64,
Paul Crowley7a658392021-03-18 17:08:20 -0700188 &USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800189 crate::database::KEYSTORE_UUID,
190 || {
191 // For backward compatibility we need to check if there is a super key present.
192 let super_key = legacy_blob_loader
193 .load_super_key(user, pw)
194 .context("In create_new_key: Failed to load legacy key blob.")?;
195 let super_key = match super_key {
196 None => {
197 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000198 generate_aes256_key()
Max Bires8e93d2b2021-01-14 13:17:59 -0800199 .context("In create_new_key: Failed to generate AES 256 key.")?
200 }
201 Some(key) => key,
202 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000203 // Regardless of whether we loaded an old AES128 key or generated a new AES256
204 // key as the super key, we derive a AES256 key from the password and re-encrypt
205 // the super key before we insert it in the database. The length of the key is
206 // preserved by the encryption so we don't need any extra flags to inform us
207 // which algorithm to use it with.
208 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800209 },
210 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800211 .context("In unlock_user_key: Failed to get key id.")?;
212
Paul Crowley8d5b2532021-03-19 10:53:07 -0700213 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
214 .context("In unlock_user_key.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800215 Ok(())
216 }
217
218 /// Unwraps an encrypted key blob given metadata identifying the encryption key.
219 /// The function queries `metadata.encrypted_by()` to determine the encryption key.
Paul Crowleye8826e52021-03-31 08:33:53 -0700220 /// It then checks if the required key is memory resident, and if so decrypts the
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800221 /// blob.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000222 pub fn unwrap_key<'a>(&self, blob: &'a [u8], metadata: &BlobMetaData) -> Result<KeyBlob<'a>> {
Paul Crowleye8826e52021-03-31 08:33:53 -0700223 let key_id = if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
224 key_id
225 } else {
226 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
227 .context("In unwrap_key: Cannot determine wrapping key.");
228 };
229 let super_key = self
230 .lookup_key(&key_id)
231 .ok_or(Error::Rc(ResponseCode::LOCKED))
232 .context("In unwrap_key: Required super decryption key is not in memory.")?;
233 Ok(KeyBlob::Sensitive {
234 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
235 .context("In unwrap_key: unwrap_key_with_key failed")?,
236 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
237 force_reencrypt: super_key.reencrypt_with.is_some(),
238 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800239 }
240
241 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700242 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700243 match key.algorithm {
244 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
245 (Some(iv), Some(tag)) => key
246 .aes_gcm_decrypt(blob, iv, tag)
247 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
248 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
249 concat!(
250 "In unwrap_key_with_key: Key has incomplete metadata.",
251 "Present: iv: {}, aead_tag: {}."
252 ),
253 iv.is_some(),
254 tag.is_some(),
255 )),
256 },
257 SuperEncryptionAlgorithm::EcdhP256 => {
258 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
259 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
260 ECDHPrivateKey::from_private_key(&key.key)
261 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
262 .context(
263 "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.",
264 )
265 }
266 (public_key, salt, iv, aead_tag) => {
267 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
268 concat!(
269 "In unwrap_key_with_key: Key has incomplete metadata.",
270 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
271 ),
272 public_key.is_some(),
273 salt.is_some(),
274 iv.is_some(),
275 aead_tag.is_some(),
276 ))
277 }
278 }
279 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800280 }
281 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000282
283 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000284 pub fn super_key_exists_in_db_for_user(
285 db: &mut KeystoreDB,
286 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700287 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000288 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000289 let key_in_db = db
Paul Crowley7a658392021-03-18 17:08:20 -0700290 .key_exists(Domain::APP, user_id as u64 as i64, &USER_SUPER_KEY.alias, KeyType::Super)
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000291 .context("In super_key_exists_in_db_for_user.")?;
292
293 if key_in_db {
294 Ok(key_in_db)
295 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000296 legacy_migrator
297 .has_super_key(user_id)
298 .context("In super_key_exists_in_db_for_user: Trying to query legacy db.")
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000299 }
300 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000301
302 /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000303 /// legacy database). If not, return Uninitialized state.
304 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
305 pub fn check_and_unlock_super_key(
306 &self,
307 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000308 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700309 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700310 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000311 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700312 let alias = &USER_SUPER_KEY;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000313 let result = legacy_migrator
Paul Crowley8d5b2532021-03-19 10:53:07 -0700314 .with_try_migrate_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000315 .context("In check_and_unlock_super_key. Failed to load super key")?;
316
317 match result {
318 Some((_, entry)) => {
319 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700320 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000321 .context("In check_and_unlock_super_key.")?;
322 Ok(UserState::LskfUnlocked(super_key))
323 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000324 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000325 }
326 }
327
328 /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the
Hasini Gunasingheda895552021-01-27 19:34:37 +0000329 /// legacy database). If so, return LskfLocked state.
330 /// If the password is provided, generate a new super key, encrypt with the password,
331 /// store in the database and populate the super key cache for the new user
332 /// and return LskfUnlocked state.
333 /// If the password is not provided, return Uninitialized state.
334 pub fn check_and_initialize_super_key(
335 &self,
336 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000337 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700338 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700339 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000340 ) -> Result<UserState> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000341 let super_key_exists_in_db =
342 Self::super_key_exists_in_db_for_user(db, legacy_migrator, user_id).context(
343 "In check_and_initialize_super_key. Failed to check if super key exists.",
344 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000345 if super_key_exists_in_db {
346 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000347 } else if let Some(pw) = pw {
348 //generate a new super key.
349 let super_key = generate_aes256_key()
350 .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?;
351 //derive an AES256 key from the password and re-encrypt the super key
352 //before we insert it in the database.
353 let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw)
354 .context("In check_and_initialize_super_key.")?;
355
356 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700357 .store_super_key(
358 user_id,
359 &USER_SUPER_KEY,
360 &encrypted_super_key,
361 &blob_metadata,
362 &KeyMetaData::new(),
363 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000364 .context("In check_and_initialize_super_key. Failed to store super key.")?;
365
366 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700367 .populate_cache_from_super_key_blob(
368 user_id,
369 USER_SUPER_KEY.algorithm,
370 key_entry,
371 pw,
372 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000373 .context("In check_and_initialize_super_key.")?;
374 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000375 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000376 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000377 }
378 }
379
380 //helper function to populate super key cache from the super key blob loaded from the database
381 fn populate_cache_from_super_key_blob(
382 &self,
Paul Crowley7a658392021-03-18 17:08:20 -0700383 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700384 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000385 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700386 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700387 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700388 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
389 .context(
390 "In populate_cache_from_super_key_blob. Failed to extract super key from key entry",
391 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000392 self.install_per_boot_key_for_user(user_id, super_key.clone());
393 Ok(super_key)
394 }
395
396 /// Extracts super key from the entry loaded from the database
Paul Crowley7a658392021-03-18 17:08:20 -0700397 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700398 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700399 entry: KeyEntry,
400 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700401 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700402 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000403 if let Some((blob, metadata)) = entry.key_blob_info() {
404 let key = match (
405 metadata.encrypted_by(),
406 metadata.salt(),
407 metadata.iv(),
408 metadata.aead_tag(),
409 ) {
410 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700411 // Note that password encryption is AES no matter the value of algorithm
Paul Crowleyf61fee72021-03-17 14:38:44 -0700412 let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context(
413 "In extract_super_key_from_key_entry: Failed to generate key from password.",
414 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000415
416 aes_gcm_decrypt(blob, iv, tag, &key).context(
417 "In extract_super_key_from_key_entry: Failed to decrypt key blob.",
418 )?
419 }
420 (enc_by, salt, iv, tag) => {
421 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
422 concat!(
423 "In extract_super_key_from_key_entry: Super key has incomplete metadata.",
Paul Crowleye8826e52021-03-31 08:33:53 -0700424 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
Hasini Gunasingheda895552021-01-27 19:34:37 +0000425 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700426 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000427 salt.is_some(),
428 iv.is_some(),
429 tag.is_some()
430 ));
431 }
432 };
Paul Crowley8d5b2532021-03-19 10:53:07 -0700433 Ok(Arc::new(SuperKey { algorithm, key, id: entry.id(), reencrypt_with }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000434 } else {
435 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
436 .context("In extract_super_key_from_key_entry: No key blob info.")
437 }
438 }
439
440 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700441 pub fn encrypt_with_password(
442 super_key: &[u8],
443 pw: &Password,
444 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000445 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700446 let derived_key = pw
447 .derive_key(Some(&salt), AES_256_KEY_LENGTH)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000448 .context("In encrypt_with_password: Failed to derive password.")?;
449 let mut metadata = BlobMetaData::new();
450 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
451 metadata.add(BlobMetaEntry::Salt(salt));
452 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
453 .context("In encrypt_with_password: Failed to encrypt new super key.")?;
454 metadata.add(BlobMetaEntry::Iv(iv));
455 metadata.add(BlobMetaEntry::AeadTag(tag));
456 Ok((encrypted_key, metadata))
457 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000458
459 // Encrypt the given key blob with the user's super key, if the super key exists and the device
460 // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
461 // return error. Note that it is out of the scope of this function to check if super encryption
462 // is required. Such check should be performed before calling this function.
463 fn super_encrypt_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000464 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000465 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000466 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700467 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000468 key_blob: &[u8],
469 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000470 match UserState::get(db, legacy_migrator, self, user_id)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000471 .context("In super_encrypt. Failed to get user state.")?
472 {
473 UserState::LskfUnlocked(super_key) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700474 Self::encrypt_with_aes_super_key(key_blob, &super_key)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000475 .context("In super_encrypt_on_key_init. Failed to encrypt the key.")
476 }
477 UserState::LskfLocked => {
478 Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.")
479 }
480 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
481 .context("In super_encrypt. LSKF is not setup for the user."),
482 }
483 }
484
485 //Helper function to encrypt a key with the given super key. Callers should select which super
486 //key to be used. This is called when a key is super encrypted at its creation as well as at its
487 //upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700488 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000489 key_blob: &[u8],
490 super_key: &SuperKey,
491 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700492 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
493 return Err(Error::sys())
494 .context("In encrypt_with_aes_super_key: unexpected algorithm");
495 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000496 let mut metadata = BlobMetaData::new();
497 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700498 .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000499 metadata.add(BlobMetaEntry::Iv(iv));
500 metadata.add(BlobMetaEntry::AeadTag(tag));
501 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key.id)));
502 Ok((encrypted_key, metadata))
503 }
504
505 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
506 /// the database.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000507 #[allow(clippy::clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000508 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000509 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000510 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000511 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000512 domain: &Domain,
513 key_parameters: &[KeyParameter],
514 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700515 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000516 key_blob: &[u8],
517 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700518 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
519 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Paul Crowleye8826e52021-03-31 08:33:53 -0700520 SuperEncryptionType::LskfBound => self
521 .super_encrypt_on_key_init(db, legacy_migrator, user_id, &key_blob)
522 .context(concat!(
523 "In handle_super_encryption_on_key_init. ",
524 "Failed to super encrypt with LskfBound key."
525 )),
Paul Crowley7a658392021-03-18 17:08:20 -0700526 SuperEncryptionType::ScreenLockBound => {
527 let mut data = self.data.lock().unwrap();
528 let entry = data.user_keys.entry(user_id).or_default();
529 if let Some(super_key) = entry.screen_lock_bound.as_ref() {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700530 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
Paul Crowley7a658392021-03-18 17:08:20 -0700531 "In handle_super_encryption_on_key_init. ",
Paul Crowleye8826e52021-03-31 08:33:53 -0700532 "Failed to encrypt with ScreenLockBound key."
Paul Crowley7a658392021-03-18 17:08:20 -0700533 ))
534 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700535 // Symmetric key is not available, use public key encryption
536 let loaded =
537 db.load_super_key(&USER_SCREEN_LOCK_BOUND_ECDH_KEY, user_id).context(
538 "In handle_super_encryption_on_key_init: load_super_key failed.",
539 )?;
540 let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context(
541 "In handle_super_encryption_on_key_init: User ECDH key missing.",
542 )?;
543 let public_key =
544 key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context(
545 "In handle_super_encryption_on_key_init: sec1_public_key missing.",
546 )?;
547 let mut metadata = BlobMetaData::new();
548 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
549 ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!(
550 "In handle_super_encryption_on_key_init: ",
551 "ECDHPrivateKey::encrypt_message failed."
552 ))?;
553 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
554 metadata.add(BlobMetaEntry::Salt(salt));
555 metadata.add(BlobMetaEntry::Iv(iv));
556 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
557 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(key_id_guard.id())));
558 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700559 }
560 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000561 }
562 }
563
564 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
565 /// the relevant super key.
566 pub fn unwrap_key_if_required<'a>(
567 &self,
568 metadata: &BlobMetaData,
569 key_blob: &'a [u8],
570 ) -> Result<KeyBlob<'a>> {
571 if Self::key_super_encrypted(&metadata) {
572 let unwrapped_key = self
573 .unwrap_key(key_blob, metadata)
574 .context("In unwrap_key_if_required. Error in unwrapping the key.")?;
575 Ok(unwrapped_key)
576 } else {
577 Ok(KeyBlob::Ref(key_blob))
578 }
579 }
580
581 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
582 /// If so, re-super-encrypt the key and return a new set of metadata,
583 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700584 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000585 key_blob_before_upgrade: &KeyBlob,
586 key_after_upgrade: &'a [u8],
587 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
588 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700589 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700590 let (key, metadata) =
591 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
592 .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000593 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
594 }
595 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
596 }
597 }
598
599 // Helper function to decide if a key is super encrypted, given metadata.
600 fn key_super_encrypted(metadata: &BlobMetaData) -> bool {
601 if let Some(&EncryptedBy::KeyId(_)) = metadata.encrypted_by() {
602 return true;
603 }
604 false
605 }
Paul Crowley7a658392021-03-18 17:08:20 -0700606
607 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
608 /// When this is called, the caller must hold the lock on the SuperKeyManager.
609 /// So it's OK that the check and creation are different DB transactions.
610 fn get_or_create_super_key(
611 db: &mut KeystoreDB,
612 user_id: UserId,
613 key_type: &SuperKeyType,
614 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700615 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700616 ) -> Result<Arc<SuperKey>> {
617 let loaded_key = db.load_super_key(key_type, user_id)?;
618 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700619 Ok(Self::extract_super_key_from_key_entry(
620 key_type.algorithm,
621 key_entry,
622 password,
623 reencrypt_with,
624 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700625 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700626 let (super_key, public_key) = match key_type.algorithm {
627 SuperEncryptionAlgorithm::Aes256Gcm => (
628 generate_aes256_key()
629 .context("In get_or_create_super_key: Failed to generate AES 256 key.")?,
630 None,
631 ),
632 SuperEncryptionAlgorithm::EcdhP256 => {
633 let key = ECDHPrivateKey::generate()
634 .context("In get_or_create_super_key: Failed to generate ECDH key")?;
635 (
636 key.private_key()
637 .context("In get_or_create_super_key: private_key failed")?,
638 Some(
639 key.public_key()
640 .context("In get_or_create_super_key: public_key failed")?,
641 ),
642 )
643 }
644 };
Paul Crowley7a658392021-03-18 17:08:20 -0700645 //derive an AES256 key from the password and re-encrypt the super key
646 //before we insert it in the database.
647 let (encrypted_super_key, blob_metadata) =
648 Self::encrypt_with_password(&super_key, password)
649 .context("In get_or_create_super_key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700650 let mut key_metadata = KeyMetaData::new();
651 if let Some(pk) = public_key {
652 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
653 }
Paul Crowley7a658392021-03-18 17:08:20 -0700654 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700655 .store_super_key(
656 user_id,
657 key_type,
658 &encrypted_super_key,
659 &blob_metadata,
660 &key_metadata,
661 )
Paul Crowley7a658392021-03-18 17:08:20 -0700662 .context("In get_or_create_super_key. Failed to store super key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700663 Ok(Arc::new(SuperKey {
664 algorithm: key_type.algorithm,
665 key: super_key,
666 id: key_entry.id(),
667 reencrypt_with,
668 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700669 }
670 }
671
Paul Crowley8d5b2532021-03-19 10:53:07 -0700672 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700673 pub fn unlock_screen_lock_bound_key(
674 &self,
675 db: &mut KeystoreDB,
676 user_id: UserId,
677 password: &Password,
678 ) -> Result<()> {
679 let mut data = self.data.lock().unwrap();
680 let entry = data.user_keys.entry(user_id).or_default();
681 let aes = entry
682 .screen_lock_bound
683 .get_or_try_to_insert_with(|| {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700684 Self::get_or_create_super_key(
685 db,
686 user_id,
687 &USER_SCREEN_LOCK_BOUND_KEY,
688 password,
689 None,
690 )
691 })?
692 .clone();
693 let ecdh = entry
694 .screen_lock_bound_private
695 .get_or_try_to_insert_with(|| {
696 Self::get_or_create_super_key(
697 db,
698 user_id,
699 &USER_SCREEN_LOCK_BOUND_ECDH_KEY,
700 password,
701 Some(aes.clone()),
702 )
Paul Crowley7a658392021-03-18 17:08:20 -0700703 })?
704 .clone();
705 data.add_key_to_key_index(&aes);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700706 data.add_key_to_key_index(&ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700707 Ok(())
708 }
709
Paul Crowley8d5b2532021-03-19 10:53:07 -0700710 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700711 pub fn lock_screen_lock_bound_key(&self, user_id: UserId) {
712 let mut data = self.data.lock().unwrap();
713 let mut entry = data.user_keys.entry(user_id).or_default();
714 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700715 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700716 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000717}
718
719/// This enum represents different states of the user's life cycle in the device.
720/// For now, only three states are defined. More states may be added later.
721pub enum UserState {
722 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
723 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -0700724 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000725 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
726 // Hence the per-boot super-key(s) is not available in the cache.
727 // However, the encrypted super key is available in the database.
728 LskfLocked,
729 // There's no user in the device for the given user id, or the user with the user id has not
730 // setup LSKF.
731 Uninitialized,
732}
733
734impl UserState {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000735 pub fn get(
736 db: &mut KeystoreDB,
737 legacy_migrator: &LegacyMigrator,
738 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700739 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000740 ) -> Result<UserState> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000741 match skm.get_per_boot_key_by_user_id(user_id) {
742 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
743 None => {
744 //Check if a super key exists in the database or legacy database.
745 //If so, return locked user state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000746 if SuperKeyManager::super_key_exists_in_db_for_user(db, legacy_migrator, user_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000747 .context("In get.")?
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000748 {
749 Ok(UserState::LskfLocked)
750 } else {
751 Ok(UserState::Uninitialized)
752 }
753 }
754 }
755 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000756
757 /// Queries user state when serving password change requests.
758 pub fn get_with_password_changed(
759 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000760 legacy_migrator: &LegacyMigrator,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000761 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700762 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700763 password: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000764 ) -> Result<UserState> {
765 match skm.get_per_boot_key_by_user_id(user_id) {
766 Some(super_key) => {
767 if password.is_none() {
768 //transitioning to swiping, delete only the super key in database and cache, and
769 //super-encrypted keys in database (and in KM)
Janis Danisevskiseed69842021-02-18 20:04:10 -0800770 Self::reset_user(db, skm, legacy_migrator, user_id, true).context(
771 "In get_with_password_changed: Trying to delete keys from the db.",
772 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000773 //Lskf is now removed in Keystore
774 Ok(UserState::Uninitialized)
775 } else {
776 //Keystore won't be notified when changing to a new password when LSKF is
777 //already setup. Therefore, ideally this path wouldn't be reached.
778 Ok(UserState::LskfUnlocked(super_key))
779 }
780 }
781 None => {
782 //Check if a super key exists in the database or legacy database.
783 //If so, return LskfLocked state.
784 //Otherwise, i) if the password is provided, initialize the super key and return
785 //LskfUnlocked state ii) if password is not provided, return Uninitialized state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000786 skm.check_and_initialize_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000787 }
788 }
789 }
790
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000791 /// Queries user state when serving password unlock requests.
792 pub fn get_with_password_unlock(
793 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000794 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000795 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700796 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700797 password: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000798 ) -> Result<UserState> {
799 match skm.get_per_boot_key_by_user_id(user_id) {
800 Some(super_key) => {
801 log::info!("In get_with_password_unlock. Trying to unlock when already unlocked.");
802 Ok(UserState::LskfUnlocked(super_key))
803 }
804 None => {
805 //Check if a super key exists in the database or legacy database.
806 //If not, return Uninitialized state.
807 //Otherwise, try to unlock the super key and if successful,
808 //return LskfUnlocked state
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000809 skm.check_and_unlock_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000810 .context("In get_with_password_unlock. Failed to unlock super key.")
811 }
812 }
813 }
814
Hasini Gunasingheda895552021-01-27 19:34:37 +0000815 /// Delete all the keys created on behalf of the user.
816 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
817 /// encrypted keys.
818 pub fn reset_user(
819 db: &mut KeystoreDB,
820 skm: &SuperKeyManager,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800821 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700822 user_id: UserId,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000823 keep_non_super_encrypted_keys: bool,
824 ) -> Result<()> {
825 // mark keys created on behalf of the user as unreferenced.
Janis Danisevskiseed69842021-02-18 20:04:10 -0800826 legacy_migrator
827 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
828 .context("In reset_user: Trying to delete legacy keys.")?;
Paul Crowley7a658392021-03-18 17:08:20 -0700829 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000830 .context("In reset user. Error in unbinding keys.")?;
831
832 //delete super key in cache, if exists
Paul Crowley7a658392021-03-18 17:08:20 -0700833 skm.forget_all_keys_for_user(user_id);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000834 Ok(())
835 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800836}
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000837
Janis Danisevskiseed69842021-02-18 20:04:10 -0800838/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
839/// `Sensitive` holds the non encrypted key and a reference to its super key.
840/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
841/// `Ref` holds a reference to a key blob when it does not need to be modified if its
842/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000843pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700844 Sensitive {
845 key: ZVec,
846 /// If KeyMint reports that the key must be upgraded, we must
847 /// re-encrypt the key before writing to the database; we use
848 /// this key.
849 reencrypt_with: Arc<SuperKey>,
850 /// If this key was decrypted with an ECDH key, we want to
851 /// re-encrypt it on first use whether it was upgraded or not;
852 /// this field indicates that that's necessary.
853 force_reencrypt: bool,
854 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000855 NonSensitive(Vec<u8>),
856 Ref(&'a [u8]),
857}
858
Paul Crowley8d5b2532021-03-19 10:53:07 -0700859impl<'a> KeyBlob<'a> {
860 pub fn force_reencrypt(&self) -> bool {
861 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
862 *force_reencrypt
863 } else {
864 false
865 }
866 }
867}
868
Janis Danisevskiseed69842021-02-18 20:04:10 -0800869/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000870impl<'a> Deref for KeyBlob<'a> {
871 type Target = [u8];
872
873 fn deref(&self) -> &Self::Target {
874 match self {
Paul Crowley7a658392021-03-18 17:08:20 -0700875 Self::Sensitive { key, .. } => &key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000876 Self::NonSensitive(key) => &key,
877 Self::Ref(key) => key,
878 }
879 }
880}