• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // 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 
15 use crate::{
16     boot_level_keys::{get_level_zero_key, BootLevelKeyCache},
17     database::BlobMetaData,
18     database::BlobMetaEntry,
19     database::EncryptedBy,
20     database::KeyEntry,
21     database::KeyType,
22     database::{KeyEntryLoadBits, KeyIdGuard, KeyMetaData, KeyMetaEntry, KeystoreDB},
23     ec_crypto::ECDHPrivateKey,
24     enforcements::Enforcements,
25     error::Error,
26     error::ResponseCode,
27     key_parameter::{KeyParameter, KeyParameterValue},
28     ks_err,
29     legacy_blob::LegacyBlobLoader,
30     legacy_importer::LegacyImporter,
31     raw_device::KeyMintDevice,
32     utils::{watchdog as wd, AesGcm, AID_KEYSTORE},
33 };
34 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
35     Algorithm::Algorithm, BlockMode::BlockMode, HardwareAuthToken::HardwareAuthToken,
36     HardwareAuthenticatorType::HardwareAuthenticatorType, KeyFormat::KeyFormat,
37     KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
38     SecurityLevel::SecurityLevel,
39 };
40 use android_system_keystore2::aidl::android::system::keystore2::{
41     Domain::Domain, KeyDescriptor::KeyDescriptor,
42 };
43 use anyhow::{Context, Result};
44 use keystore2_crypto::{
45     aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
46     AES_256_KEY_LENGTH,
47 };
48 use rustutils::system_properties::PropertyWatcher;
49 use std::{
50     collections::HashMap,
51     sync::Arc,
52     sync::{Mutex, RwLock, Weak},
53 };
54 use std::{convert::TryFrom, ops::Deref};
55 
56 const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
57 /// Allow up to 15 seconds between the user unlocking using a biometric, and the auth
58 /// token being used to unlock in [`SuperKeyManager::try_unlock_user_with_biometric`].
59 /// This seems short enough for security purposes, while long enough that even the
60 /// very slowest device will present the auth token in time.
61 const BIOMETRIC_AUTH_TIMEOUT_S: i32 = 15; // seconds
62 
63 type UserId = u32;
64 
65 /// Encryption algorithm used by a particular type of superencryption key
66 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
67 pub enum SuperEncryptionAlgorithm {
68     /// Symmetric encryption with AES-256-GCM
69     Aes256Gcm,
70     /// Public-key encryption with ECDH P-521
71     EcdhP521,
72 }
73 
74 /// A particular user may have several superencryption keys in the database, each for a
75 /// different purpose, distinguished by alias. Each is associated with a static
76 /// constant of this type.
77 pub struct SuperKeyType<'a> {
78     /// Alias used to look up the key in the `persistent.keyentry` table.
79     pub alias: &'a str,
80     /// Encryption algorithm
81     pub algorithm: SuperEncryptionAlgorithm,
82 }
83 
84 /// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
85 /// when the user first unlocks, and remains in memory until the device reboots.
86 pub const USER_SUPER_KEY: SuperKeyType =
87     SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
88 /// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
89 /// each time the user enters their LSKF, and cleared from memory each time the device is locked.
90 /// Symmetric.
91 pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
92     alias: "USER_SCREEN_LOCK_BOUND_KEY",
93     algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
94 };
95 /// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
96 /// each time the user enters their LSKF, and cleared from memory each time the device is locked.
97 /// Asymmetric, so keys can be encrypted when the device is locked.
98 pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
99     alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
100     algorithm: SuperEncryptionAlgorithm::EcdhP521,
101 };
102 
103 /// Superencryption to apply to a new key.
104 #[derive(Debug, Clone, Copy)]
105 pub enum SuperEncryptionType {
106     /// Do not superencrypt this key.
107     None,
108     /// Superencrypt with a key that remains in memory from first unlock to reboot.
109     LskfBound,
110     /// Superencrypt with a key cleared from memory when the device is locked.
111     ScreenLockBound,
112     /// Superencrypt with a key based on the desired boot level
113     BootLevel(i32),
114 }
115 
116 #[derive(Debug, Clone, Copy)]
117 pub enum SuperKeyIdentifier {
118     /// id of the super key in the database.
119     DatabaseId(i64),
120     /// Boot level of the encrypting boot level key
121     BootLevel(i32),
122 }
123 
124 impl SuperKeyIdentifier {
from_metadata(metadata: &BlobMetaData) -> Option<Self>125     fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
126         if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
127             Some(SuperKeyIdentifier::DatabaseId(*key_id))
128         } else {
129             metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
130         }
131     }
132 
add_to_metadata(&self, metadata: &mut BlobMetaData)133     fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
134         match self {
135             SuperKeyIdentifier::DatabaseId(id) => {
136                 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
137             }
138             SuperKeyIdentifier::BootLevel(level) => {
139                 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
140             }
141         }
142     }
143 }
144 
145 pub struct SuperKey {
146     algorithm: SuperEncryptionAlgorithm,
147     key: ZVec,
148     /// Identifier of the encrypting key, used to write an encrypted blob
149     /// back to the database after re-encryption eg on a key update.
150     id: SuperKeyIdentifier,
151     /// ECDH is more expensive than AES. So on ECDH private keys we set the
152     /// reencrypt_with field to point at the corresponding AES key, and the
153     /// keys will be re-encrypted with AES on first use.
154     reencrypt_with: Option<Arc<SuperKey>>,
155 }
156 
157 impl AesGcm for SuperKey {
decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>158     fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
159         if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
160             aes_gcm_decrypt(data, iv, tag, &self.key).context(ks_err!("Decryption failed."))
161         } else {
162             Err(Error::sys()).context(ks_err!("Key is not an AES key."))
163         }
164     }
165 
encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>166     fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
167         if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
168             aes_gcm_encrypt(plaintext, &self.key).context(ks_err!("Encryption failed."))
169         } else {
170             Err(Error::sys()).context(ks_err!("Key is not an AES key."))
171         }
172     }
173 }
174 
175 /// A SuperKey that has been encrypted with an AES-GCM key. For
176 /// encryption the key is in memory, and for decryption it is in KM.
177 struct LockedKey {
178     algorithm: SuperEncryptionAlgorithm,
179     id: SuperKeyIdentifier,
180     nonce: Vec<u8>,
181     ciphertext: Vec<u8>, // with tag appended
182 }
183 
184 impl LockedKey {
new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self>185     fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
186         let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
187         ciphertext.append(&mut tag);
188         Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
189     }
190 
decrypt( &self, db: &mut KeystoreDB, km_dev: &KeyMintDevice, key_id_guard: &KeyIdGuard, key_entry: &KeyEntry, auth_token: &HardwareAuthToken, reencrypt_with: Option<Arc<SuperKey>>, ) -> Result<Arc<SuperKey>>191     fn decrypt(
192         &self,
193         db: &mut KeystoreDB,
194         km_dev: &KeyMintDevice,
195         key_id_guard: &KeyIdGuard,
196         key_entry: &KeyEntry,
197         auth_token: &HardwareAuthToken,
198         reencrypt_with: Option<Arc<SuperKey>>,
199     ) -> Result<Arc<SuperKey>> {
200         let key_blob = key_entry
201             .key_blob_info()
202             .as_ref()
203             .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
204             .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
205             .context(ks_err!("Missing key blob info."))?;
206         let key_params = vec![
207             KeyParameterValue::Algorithm(Algorithm::AES),
208             KeyParameterValue::KeySize(256),
209             KeyParameterValue::BlockMode(BlockMode::GCM),
210             KeyParameterValue::PaddingMode(PaddingMode::NONE),
211             KeyParameterValue::Nonce(self.nonce.clone()),
212             KeyParameterValue::MacLength(128),
213         ];
214         let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
215         let key = ZVec::try_from(km_dev.use_key_in_one_step(
216             db,
217             key_id_guard,
218             &key_blob,
219             KeyPurpose::DECRYPT,
220             &key_params,
221             Some(auth_token),
222             &self.ciphertext,
223         )?)?;
224         Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
225     }
226 }
227 
228 /// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
229 /// a database descriptor for the encrypting key and the sids for the auth tokens
230 /// that can be used to decrypt it.
231 struct BiometricUnlock {
232     /// List of auth token SIDs that can be used to unlock these keys.
233     sids: Vec<i64>,
234     /// Database descriptor of key to use to unlock.
235     key_desc: KeyDescriptor,
236     /// Locked versions of the matching UserSuperKeys fields
237     screen_lock_bound: LockedKey,
238     screen_lock_bound_private: LockedKey,
239 }
240 
241 #[derive(Default)]
242 struct UserSuperKeys {
243     /// The per boot key is used for LSKF binding of authentication bound keys. There is one
244     /// key per android user. The key is stored on flash encrypted with a key derived from a
245     /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
246     /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
247     /// and stays memory resident until the device reboots.
248     per_boot: Option<Arc<SuperKey>>,
249     /// The screen lock key works like the per boot key with the distinction that it is cleared
250     /// from memory when the screen lock is engaged.
251     screen_lock_bound: Option<Arc<SuperKey>>,
252     /// When the device is locked, screen-lock-bound keys can still be encrypted, using
253     /// ECDH public-key encryption. This field holds the decryption private key.
254     screen_lock_bound_private: Option<Arc<SuperKey>>,
255     /// Versions of the above two keys, locked behind a biometric.
256     biometric_unlock: Option<BiometricUnlock>,
257 }
258 
259 #[derive(Default)]
260 struct SkmState {
261     user_keys: HashMap<UserId, UserSuperKeys>,
262     key_index: HashMap<i64, Weak<SuperKey>>,
263     boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
264 }
265 
266 impl SkmState {
add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()>267     fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
268         if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
269             self.key_index.insert(id, Arc::downgrade(super_key));
270             Ok(())
271         } else {
272             Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id))
273         }
274     }
275 }
276 
277 #[derive(Default)]
278 pub struct SuperKeyManager {
279     data: SkmState,
280 }
281 
282 impl SuperKeyManager {
set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()>283     pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
284         let mut skm_guard = skm.write().unwrap();
285         if skm_guard.data.boot_level_key_cache.is_some() {
286             log::info!("In set_up_boot_level_cache: called for a second time");
287             return Ok(());
288         }
289         let level_zero_key =
290             get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?;
291         skm_guard.data.boot_level_key_cache =
292             Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
293         log::info!("Starting boot level watcher.");
294         let clone = skm.clone();
295         std::thread::spawn(move || {
296             Self::watch_boot_level(clone)
297                 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
298         });
299         Ok(())
300     }
301 
302     /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
303     /// Blocks waiting for system property changes, so must be run in its own thread.
watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()>304     fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
305         let mut w = PropertyWatcher::new("keystore.boot_level")
306             .context(ks_err!("PropertyWatcher::new failed"))?;
307         loop {
308             let level = w
309                 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
310                 .context(ks_err!("read of property failed"))?;
311 
312             // This scope limits the skm_guard life, so we don't hold the skm_guard while
313             // waiting.
314             {
315                 let mut skm_guard = skm.write().unwrap();
316                 let boot_level_key_cache = skm_guard
317                     .data
318                     .boot_level_key_cache
319                     .as_mut()
320                     .ok_or_else(Error::sys)
321                     .context(ks_err!("Boot level cache not initialized"))?
322                     .get_mut()
323                     .unwrap();
324                 if level < MAX_MAX_BOOT_LEVEL {
325                     log::info!("Read keystore.boot_level value {}", level);
326                     boot_level_key_cache
327                         .advance_boot_level(level)
328                         .context(ks_err!("advance_boot_level failed"))?;
329                 } else {
330                     log::info!(
331                         "keystore.boot_level {} hits maximum {}, finishing.",
332                         level,
333                         MAX_MAX_BOOT_LEVEL
334                     );
335                     boot_level_key_cache.finish();
336                     break;
337                 }
338             }
339             w.wait().context(ks_err!("property wait failed"))?;
340         }
341         Ok(())
342     }
343 
level_accessible(&self, boot_level: i32) -> bool344     pub fn level_accessible(&self, boot_level: i32) -> bool {
345         self.data
346             .boot_level_key_cache
347             .as_ref()
348             .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
349     }
350 
forget_all_keys_for_user(&mut self, user: UserId)351     pub fn forget_all_keys_for_user(&mut self, user: UserId) {
352         self.data.user_keys.remove(&user);
353     }
354 
install_per_boot_key_for_user( &mut self, user: UserId, super_key: Arc<SuperKey>, ) -> Result<()>355     fn install_per_boot_key_for_user(
356         &mut self,
357         user: UserId,
358         super_key: Arc<SuperKey>,
359     ) -> Result<()> {
360         self.data
361             .add_key_to_key_index(&super_key)
362             .context(ks_err!("add_key_to_key_index failed"))?;
363         self.data.user_keys.entry(user).or_default().per_boot = Some(super_key);
364         Ok(())
365     }
366 
lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>>367     fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
368         Ok(match key_id {
369             SuperKeyIdentifier::DatabaseId(id) => {
370                 self.data.key_index.get(id).and_then(|k| k.upgrade())
371             }
372             SuperKeyIdentifier::BootLevel(level) => self
373                 .data
374                 .boot_level_key_cache
375                 .as_ref()
376                 .map(|b| b.lock().unwrap().aes_key(*level as usize))
377                 .transpose()
378                 .context(ks_err!("aes_key failed"))?
379                 .flatten()
380                 .map(|key| {
381                     Arc::new(SuperKey {
382                         algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
383                         key,
384                         id: *key_id,
385                         reencrypt_with: None,
386                     })
387                 }),
388         })
389     }
390 
get_per_boot_key_by_user_id( &self, user_id: UserId, ) -> Option<Arc<dyn AesGcm + Send + Sync>>391     pub fn get_per_boot_key_by_user_id(
392         &self,
393         user_id: UserId,
394     ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
395         self.get_per_boot_key_by_user_id_internal(user_id)
396             .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
397     }
398 
get_per_boot_key_by_user_id_internal(&self, user_id: UserId) -> Option<Arc<SuperKey>>399     fn get_per_boot_key_by_user_id_internal(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
400         self.data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
401     }
402 
403     /// This function unlocks the super keys for a given user.
404     /// This means the key is loaded from the database, decrypted and placed in the
405     /// super key cache. If there is no such key a new key is created, encrypted with
406     /// a key derived from the given password and stored in the database.
unlock_user_key( &mut self, db: &mut KeystoreDB, user: UserId, pw: &Password, legacy_blob_loader: &LegacyBlobLoader, ) -> Result<()>407     pub fn unlock_user_key(
408         &mut self,
409         db: &mut KeystoreDB,
410         user: UserId,
411         pw: &Password,
412         legacy_blob_loader: &LegacyBlobLoader,
413     ) -> Result<()> {
414         let (_, entry) = db
415             .get_or_create_key_with(
416                 Domain::APP,
417                 user as u64 as i64,
418                 USER_SUPER_KEY.alias,
419                 crate::database::KEYSTORE_UUID,
420                 || {
421                     // For backward compatibility we need to check if there is a super key present.
422                     let super_key = legacy_blob_loader
423                         .load_super_key(user, pw)
424                         .context(ks_err!("Failed to load legacy key blob."))?;
425                     let super_key = match super_key {
426                         None => {
427                             // No legacy file was found. So we generate a new key.
428                             generate_aes256_key()
429                                 .context(ks_err!("Failed to generate AES 256 key."))?
430                         }
431                         Some(key) => key,
432                     };
433                     // Regardless of whether we loaded an old AES128 key or generated a new AES256
434                     // key as the super key, we derive a AES256 key from the password and re-encrypt
435                     // the super key before we insert it in the database. The length of the key is
436                     // preserved by the encryption so we don't need any extra flags to inform us
437                     // which algorithm to use it with.
438                     Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
439                 },
440             )
441             .context(ks_err!("Failed to get key id."))?;
442 
443         self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
444             .context(ks_err!())?;
445         Ok(())
446     }
447 
448     /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
449     /// the relevant super key.
unwrap_key_if_required<'a>( &self, metadata: &BlobMetaData, blob: &'a [u8], ) -> Result<KeyBlob<'a>>450     pub fn unwrap_key_if_required<'a>(
451         &self,
452         metadata: &BlobMetaData,
453         blob: &'a [u8],
454     ) -> Result<KeyBlob<'a>> {
455         Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
456             let super_key = self
457                 .lookup_key(&key_id)
458                 .context(ks_err!("lookup_key failed"))?
459                 .ok_or(Error::Rc(ResponseCode::LOCKED))
460                 .context(ks_err!("Required super decryption key is not in memory."))?;
461             KeyBlob::Sensitive {
462                 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
463                     .context(ks_err!("unwrap_key_with_key failed"))?,
464                 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
465                 force_reencrypt: super_key.reencrypt_with.is_some(),
466             }
467         } else {
468             KeyBlob::Ref(blob)
469         })
470     }
471 
472     /// Unwraps an encrypted key blob given an encryption key.
unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec>473     fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
474         match key.algorithm {
475             SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
476                 (Some(iv), Some(tag)) => {
477                     key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
478                 }
479                 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
480                     "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
481                     iv.is_some(),
482                     tag.is_some(),
483                 )),
484             },
485             SuperEncryptionAlgorithm::EcdhP521 => {
486                 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
487                     (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
488                         ECDHPrivateKey::from_private_key(&key.key)
489                             .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
490                             .context(ks_err!("Failed to decrypt the key blob with ECDH."))
491                     }
492                     (public_key, salt, iv, aead_tag) => {
493                         Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
494                             concat!(
495                                 "Key has incomplete metadata. ",
496                                 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
497                             ),
498                             public_key.is_some(),
499                             salt.is_some(),
500                             iv.is_some(),
501                             aead_tag.is_some(),
502                         ))
503                     }
504                 }
505             }
506         }
507     }
508 
509     /// Checks if user has setup LSKF, even when super key cache is empty for the user.
510     /// The reference to self is unused but it is required to prevent calling this function
511     /// concurrently with skm state database changes.
super_key_exists_in_db_for_user( &self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, user_id: UserId, ) -> Result<bool>512     fn super_key_exists_in_db_for_user(
513         &self,
514         db: &mut KeystoreDB,
515         legacy_importer: &LegacyImporter,
516         user_id: UserId,
517     ) -> Result<bool> {
518         let key_in_db = db
519             .key_exists(Domain::APP, user_id as u64 as i64, USER_SUPER_KEY.alias, KeyType::Super)
520             .context(ks_err!())?;
521 
522         if key_in_db {
523             Ok(key_in_db)
524         } else {
525             legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
526         }
527     }
528 
529     /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the
530     /// legacy database). If not, return Uninitialized state.
531     /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
check_and_unlock_super_key( &mut self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, user_id: UserId, pw: &Password, ) -> Result<UserState>532     pub fn check_and_unlock_super_key(
533         &mut self,
534         db: &mut KeystoreDB,
535         legacy_importer: &LegacyImporter,
536         user_id: UserId,
537         pw: &Password,
538     ) -> Result<UserState> {
539         let alias = &USER_SUPER_KEY;
540         let result = legacy_importer
541             .with_try_import_super_key(user_id, pw, || db.load_super_key(alias, user_id))
542             .context(ks_err!("Failed to load super key"))?;
543 
544         match result {
545             Some((_, entry)) => {
546                 let super_key = self
547                     .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
548                     .context(ks_err!())?;
549                 Ok(UserState::LskfUnlocked(super_key))
550             }
551             None => Ok(UserState::Uninitialized),
552         }
553     }
554 
555     /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the
556     /// legacy database). If so, return LskfLocked state.
557     /// If the password is provided, generate a new super key, encrypt with the password,
558     /// store in the database and populate the super key cache for the new user
559     /// and return LskfUnlocked state.
560     /// If the password is not provided, return Uninitialized state.
check_and_initialize_super_key( &mut self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, user_id: UserId, pw: Option<&Password>, ) -> Result<UserState>561     pub fn check_and_initialize_super_key(
562         &mut self,
563         db: &mut KeystoreDB,
564         legacy_importer: &LegacyImporter,
565         user_id: UserId,
566         pw: Option<&Password>,
567     ) -> Result<UserState> {
568         let super_key_exists_in_db = self
569             .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
570             .context(ks_err!("Failed to check if super key exists."))?;
571         if super_key_exists_in_db {
572             Ok(UserState::LskfLocked)
573         } else if let Some(pw) = pw {
574             // Generate a new super key.
575             let super_key =
576                 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
577             // Derive an AES256 key from the password and re-encrypt the super key
578             // before we insert it in the database.
579             let (encrypted_super_key, blob_metadata) =
580                 Self::encrypt_with_password(&super_key, pw).context(ks_err!())?;
581 
582             let key_entry = db
583                 .store_super_key(
584                     user_id,
585                     &USER_SUPER_KEY,
586                     &encrypted_super_key,
587                     &blob_metadata,
588                     &KeyMetaData::new(),
589                 )
590                 .context(ks_err!("Failed to store super key."))?;
591 
592             let super_key = self
593                 .populate_cache_from_super_key_blob(
594                     user_id,
595                     USER_SUPER_KEY.algorithm,
596                     key_entry,
597                     pw,
598                 )
599                 .context(ks_err!())?;
600             Ok(UserState::LskfUnlocked(super_key))
601         } else {
602             Ok(UserState::Uninitialized)
603         }
604     }
605 
606     // Helper function to populate super key cache from the super key blob loaded from the database.
populate_cache_from_super_key_blob( &mut self, user_id: UserId, algorithm: SuperEncryptionAlgorithm, entry: KeyEntry, pw: &Password, ) -> Result<Arc<SuperKey>>607     fn populate_cache_from_super_key_blob(
608         &mut self,
609         user_id: UserId,
610         algorithm: SuperEncryptionAlgorithm,
611         entry: KeyEntry,
612         pw: &Password,
613     ) -> Result<Arc<SuperKey>> {
614         let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
615             .context(ks_err!("Failed to extract super key from key entry"))?;
616         self.install_per_boot_key_for_user(user_id, super_key.clone())?;
617         Ok(super_key)
618     }
619 
620     /// Extracts super key from the entry loaded from the database.
extract_super_key_from_key_entry( algorithm: SuperEncryptionAlgorithm, entry: KeyEntry, pw: &Password, reencrypt_with: Option<Arc<SuperKey>>, ) -> Result<Arc<SuperKey>>621     pub fn extract_super_key_from_key_entry(
622         algorithm: SuperEncryptionAlgorithm,
623         entry: KeyEntry,
624         pw: &Password,
625         reencrypt_with: Option<Arc<SuperKey>>,
626     ) -> Result<Arc<SuperKey>> {
627         if let Some((blob, metadata)) = entry.key_blob_info() {
628             let key = match (
629                 metadata.encrypted_by(),
630                 metadata.salt(),
631                 metadata.iv(),
632                 metadata.aead_tag(),
633             ) {
634                 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
635                     // Note that password encryption is AES no matter the value of algorithm.
636                     let key = pw
637                         .derive_key(salt, AES_256_KEY_LENGTH)
638                         .context(ks_err!("Failed to generate key from password."))?;
639 
640                     aes_gcm_decrypt(blob, iv, tag, &key)
641                         .context(ks_err!("Failed to decrypt key blob."))?
642                 }
643                 (enc_by, salt, iv, tag) => {
644                     return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
645                         concat!(
646                             "Super key has incomplete metadata.",
647                             "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
648                         ),
649                         enc_by,
650                         salt.is_some(),
651                         iv.is_some(),
652                         tag.is_some()
653                     ));
654                 }
655             };
656             Ok(Arc::new(SuperKey {
657                 algorithm,
658                 key,
659                 id: SuperKeyIdentifier::DatabaseId(entry.id()),
660                 reencrypt_with,
661             }))
662         } else {
663             Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
664         }
665     }
666 
667     /// Encrypts the super key from a key derived from the password, before storing in the database.
encrypt_with_password( super_key: &[u8], pw: &Password, ) -> Result<(Vec<u8>, BlobMetaData)>668     pub fn encrypt_with_password(
669         super_key: &[u8],
670         pw: &Password,
671     ) -> Result<(Vec<u8>, BlobMetaData)> {
672         let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
673         let derived_key = pw
674             .derive_key(&salt, AES_256_KEY_LENGTH)
675             .context(ks_err!("Failed to derive password."))?;
676         let mut metadata = BlobMetaData::new();
677         metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
678         metadata.add(BlobMetaEntry::Salt(salt));
679         let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
680             .context(ks_err!("Failed to encrypt new super key."))?;
681         metadata.add(BlobMetaEntry::Iv(iv));
682         metadata.add(BlobMetaEntry::AeadTag(tag));
683         Ok((encrypted_key, metadata))
684     }
685 
686     // Encrypt the given key blob with the user's super key, if the super key exists and the device
687     // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
688     // return error. Note that it is out of the scope of this function to check if super encryption
689     // is required. Such check should be performed before calling this function.
super_encrypt_on_key_init( &self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, user_id: UserId, key_blob: &[u8], ) -> Result<(Vec<u8>, BlobMetaData)>690     fn super_encrypt_on_key_init(
691         &self,
692         db: &mut KeystoreDB,
693         legacy_importer: &LegacyImporter,
694         user_id: UserId,
695         key_blob: &[u8],
696     ) -> Result<(Vec<u8>, BlobMetaData)> {
697         match self
698             .get_user_state(db, legacy_importer, user_id)
699             .context(ks_err!("Failed to get user state."))?
700         {
701             UserState::LskfUnlocked(super_key) => {
702                 Self::encrypt_with_aes_super_key(key_blob, &super_key)
703                     .context(ks_err!("Failed to encrypt the key."))
704             }
705             UserState::LskfLocked => {
706                 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
707             }
708             UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
709                 .context(ks_err!("LSKF is not setup for the user.")),
710         }
711     }
712 
713     // Helper function to encrypt a key with the given super key. Callers should select which super
714     // key to be used. This is called when a key is super encrypted at its creation as well as at
715     // its upgrade.
encrypt_with_aes_super_key( key_blob: &[u8], super_key: &SuperKey, ) -> Result<(Vec<u8>, BlobMetaData)>716     fn encrypt_with_aes_super_key(
717         key_blob: &[u8],
718         super_key: &SuperKey,
719     ) -> Result<(Vec<u8>, BlobMetaData)> {
720         if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
721             return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
722         }
723         let mut metadata = BlobMetaData::new();
724         let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
725             .context(ks_err!("Failed to encrypt new super key."))?;
726         metadata.add(BlobMetaEntry::Iv(iv));
727         metadata.add(BlobMetaEntry::AeadTag(tag));
728         super_key.id.add_to_metadata(&mut metadata);
729         Ok((encrypted_key, metadata))
730     }
731 
732     /// Check if super encryption is required and if so, super-encrypt the key to be stored in
733     /// the database.
734     #[allow(clippy::too_many_arguments)]
handle_super_encryption_on_key_init( &self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, domain: &Domain, key_parameters: &[KeyParameter], flags: Option<i32>, user_id: UserId, key_blob: &[u8], ) -> Result<(Vec<u8>, BlobMetaData)>735     pub fn handle_super_encryption_on_key_init(
736         &self,
737         db: &mut KeystoreDB,
738         legacy_importer: &LegacyImporter,
739         domain: &Domain,
740         key_parameters: &[KeyParameter],
741         flags: Option<i32>,
742         user_id: UserId,
743         key_blob: &[u8],
744     ) -> Result<(Vec<u8>, BlobMetaData)> {
745         match Enforcements::super_encryption_required(domain, key_parameters, flags) {
746             SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
747             SuperEncryptionType::LskfBound => self
748                 .super_encrypt_on_key_init(db, legacy_importer, user_id, key_blob)
749                 .context(ks_err!("Failed to super encrypt with LskfBound key.")),
750             SuperEncryptionType::ScreenLockBound => {
751                 let entry =
752                     self.data.user_keys.get(&user_id).and_then(|e| e.screen_lock_bound.as_ref());
753                 if let Some(super_key) = entry {
754                     Self::encrypt_with_aes_super_key(key_blob, super_key)
755                         .context(ks_err!("Failed to encrypt with ScreenLockBound key."))
756                 } else {
757                     // Symmetric key is not available, use public key encryption
758                     let loaded = db
759                         .load_super_key(&USER_SCREEN_LOCK_BOUND_P521_KEY, user_id)
760                         .context(ks_err!("load_super_key failed."))?;
761                     let (key_id_guard, key_entry) =
762                         loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH key missing."))?;
763                     let public_key = key_entry
764                         .metadata()
765                         .sec1_public_key()
766                         .ok_or_else(Error::sys)
767                         .context(ks_err!("sec1_public_key missing."))?;
768                     let mut metadata = BlobMetaData::new();
769                     let (ephem_key, salt, iv, encrypted_key, aead_tag) =
770                         ECDHPrivateKey::encrypt_message(public_key, key_blob)
771                             .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
772                     metadata.add(BlobMetaEntry::PublicKey(ephem_key));
773                     metadata.add(BlobMetaEntry::Salt(salt));
774                     metadata.add(BlobMetaEntry::Iv(iv));
775                     metadata.add(BlobMetaEntry::AeadTag(aead_tag));
776                     SuperKeyIdentifier::DatabaseId(key_id_guard.id())
777                         .add_to_metadata(&mut metadata);
778                     Ok((encrypted_key, metadata))
779                 }
780             }
781             SuperEncryptionType::BootLevel(level) => {
782                 let key_id = SuperKeyIdentifier::BootLevel(level);
783                 let super_key = self
784                     .lookup_key(&key_id)
785                     .context(ks_err!("lookup_key failed"))?
786                     .ok_or(Error::Rc(ResponseCode::LOCKED))
787                     .context(ks_err!("Boot stage key absent"))?;
788                 Self::encrypt_with_aes_super_key(key_blob, &super_key)
789                     .context(ks_err!("Failed to encrypt with BootLevel key."))
790             }
791         }
792     }
793 
794     /// Check if a given key needs re-super-encryption, from its KeyBlob type.
795     /// If so, re-super-encrypt the key and return a new set of metadata,
796     /// containing the new super encryption information.
reencrypt_if_required<'a>( key_blob_before_upgrade: &KeyBlob, key_after_upgrade: &'a [u8], ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)>797     pub fn reencrypt_if_required<'a>(
798         key_blob_before_upgrade: &KeyBlob,
799         key_after_upgrade: &'a [u8],
800     ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
801         match key_blob_before_upgrade {
802             KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
803                 let (key, metadata) =
804                     Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
805                         .context(ks_err!("Failed to re-super-encrypt key."))?;
806                 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
807             }
808             _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
809         }
810     }
811 
812     /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
813     /// When this is called, the caller must hold the lock on the SuperKeyManager.
814     /// So it's OK that the check and creation are different DB transactions.
get_or_create_super_key( &mut self, db: &mut KeystoreDB, user_id: UserId, key_type: &SuperKeyType, password: &Password, reencrypt_with: Option<Arc<SuperKey>>, ) -> Result<Arc<SuperKey>>815     fn get_or_create_super_key(
816         &mut self,
817         db: &mut KeystoreDB,
818         user_id: UserId,
819         key_type: &SuperKeyType,
820         password: &Password,
821         reencrypt_with: Option<Arc<SuperKey>>,
822     ) -> Result<Arc<SuperKey>> {
823         let loaded_key = db.load_super_key(key_type, user_id)?;
824         if let Some((_, key_entry)) = loaded_key {
825             Ok(Self::extract_super_key_from_key_entry(
826                 key_type.algorithm,
827                 key_entry,
828                 password,
829                 reencrypt_with,
830             )?)
831         } else {
832             let (super_key, public_key) = match key_type.algorithm {
833                 SuperEncryptionAlgorithm::Aes256Gcm => (
834                     generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?,
835                     None,
836                 ),
837                 SuperEncryptionAlgorithm::EcdhP521 => {
838                     let key = ECDHPrivateKey::generate()
839                         .context(ks_err!("Failed to generate ECDH key"))?;
840                     (
841                         key.private_key().context(ks_err!("private_key failed"))?,
842                         Some(key.public_key().context(ks_err!("public_key failed"))?),
843                     )
844                 }
845             };
846             // Derive an AES256 key from the password and re-encrypt the super key
847             // before we insert it in the database.
848             let (encrypted_super_key, blob_metadata) =
849                 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
850             let mut key_metadata = KeyMetaData::new();
851             if let Some(pk) = public_key {
852                 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
853             }
854             let key_entry = db
855                 .store_super_key(
856                     user_id,
857                     key_type,
858                     &encrypted_super_key,
859                     &blob_metadata,
860                     &key_metadata,
861                 )
862                 .context(ks_err!("Failed to store super key."))?;
863             Ok(Arc::new(SuperKey {
864                 algorithm: key_type.algorithm,
865                 key: super_key,
866                 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
867                 reencrypt_with,
868             }))
869         }
870     }
871 
872     /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
unlock_screen_lock_bound_key( &mut self, db: &mut KeystoreDB, user_id: UserId, password: &Password, ) -> Result<()>873     pub fn unlock_screen_lock_bound_key(
874         &mut self,
875         db: &mut KeystoreDB,
876         user_id: UserId,
877         password: &Password,
878     ) -> Result<()> {
879         let (screen_lock_bound, screen_lock_bound_private) = self
880             .data
881             .user_keys
882             .get(&user_id)
883             .map(|e| (e.screen_lock_bound.clone(), e.screen_lock_bound_private.clone()))
884             .unwrap_or((None, None));
885 
886         if screen_lock_bound.is_some() && screen_lock_bound_private.is_some() {
887             // Already unlocked.
888             return Ok(());
889         }
890 
891         let aes = if let Some(screen_lock_bound) = screen_lock_bound {
892             // This is weird. If this point is reached only one of the screen locked keys was
893             // initialized. This should never happen.
894             screen_lock_bound
895         } else {
896             self.get_or_create_super_key(db, user_id, &USER_SCREEN_LOCK_BOUND_KEY, password, None)
897                 .context(ks_err!("Trying to get or create symmetric key."))?
898         };
899 
900         let ecdh = if let Some(screen_lock_bound_private) = screen_lock_bound_private {
901             // This is weird. If this point is reached only one of the screen locked keys was
902             // initialized. This should never happen.
903             screen_lock_bound_private
904         } else {
905             self.get_or_create_super_key(
906                 db,
907                 user_id,
908                 &USER_SCREEN_LOCK_BOUND_P521_KEY,
909                 password,
910                 Some(aes.clone()),
911             )
912             .context(ks_err!("Trying to get or create asymmetric key."))?
913         };
914 
915         self.data.add_key_to_key_index(&aes)?;
916         self.data.add_key_to_key_index(&ecdh)?;
917         let entry = self.data.user_keys.entry(user_id).or_default();
918         entry.screen_lock_bound = Some(aes);
919         entry.screen_lock_bound_private = Some(ecdh);
920         Ok(())
921     }
922 
923     /// Wipe the screen-lock bound keys for this user from memory.
lock_screen_lock_bound_key( &mut self, db: &mut KeystoreDB, user_id: UserId, unlocking_sids: &[i64], )924     pub fn lock_screen_lock_bound_key(
925         &mut self,
926         db: &mut KeystoreDB,
927         user_id: UserId,
928         unlocking_sids: &[i64],
929     ) {
930         log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
931         let mut entry = self.data.user_keys.entry(user_id).or_default();
932         if !unlocking_sids.is_empty() {
933             if let (Some(aes), Some(ecdh)) = (
934                 entry.screen_lock_bound.as_ref().cloned(),
935                 entry.screen_lock_bound_private.as_ref().cloned(),
936             ) {
937                 let res = (|| -> Result<()> {
938                     let key_desc = KeyMintDevice::internal_descriptor(format!(
939                         "biometric_unlock_key_{}",
940                         user_id
941                     ));
942                     let encrypting_key = generate_aes256_key()?;
943                     let km_dev: KeyMintDevice =
944                         KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
945                             .context(ks_err!("KeyMintDevice::get failed"))?;
946                     let mut key_params = vec![
947                         KeyParameterValue::Algorithm(Algorithm::AES),
948                         KeyParameterValue::KeySize(256),
949                         KeyParameterValue::BlockMode(BlockMode::GCM),
950                         KeyParameterValue::PaddingMode(PaddingMode::NONE),
951                         KeyParameterValue::CallerNonce,
952                         KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
953                         KeyParameterValue::MinMacLength(128),
954                         KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
955                         KeyParameterValue::HardwareAuthenticatorType(
956                             HardwareAuthenticatorType::FINGERPRINT,
957                         ),
958                     ];
959                     for sid in unlocking_sids {
960                         key_params.push(KeyParameterValue::UserSecureID(*sid));
961                     }
962                     let key_params: Vec<KmKeyParameter> =
963                         key_params.into_iter().map(|x| x.into()).collect();
964                     km_dev.create_and_store_key(
965                         db,
966                         &key_desc,
967                         KeyType::Client, /* TODO Should be Super b/189470584 */
968                         |dev| {
969                             let _wp = wd::watch_millis(
970                                 "In lock_screen_lock_bound_key: calling importKey.",
971                                 500,
972                             );
973                             dev.importKey(
974                                 key_params.as_slice(),
975                                 KeyFormat::RAW,
976                                 &encrypting_key,
977                                 None,
978                             )
979                         },
980                     )?;
981                     entry.biometric_unlock = Some(BiometricUnlock {
982                         sids: unlocking_sids.into(),
983                         key_desc,
984                         screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
985                         screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
986                     });
987                     Ok(())
988                 })();
989                 // There is no reason to propagate an error here upwards. We must discard
990                 // entry.screen_lock_bound* in any case.
991                 if let Err(e) = res {
992                     log::error!("Error setting up biometric unlock: {:#?}", e);
993                 }
994             }
995         }
996         entry.screen_lock_bound = None;
997         entry.screen_lock_bound_private = None;
998     }
999 
1000     /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
1001     /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
try_unlock_user_with_biometric( &mut self, db: &mut KeystoreDB, user_id: UserId, ) -> Result<()>1002     pub fn try_unlock_user_with_biometric(
1003         &mut self,
1004         db: &mut KeystoreDB,
1005         user_id: UserId,
1006     ) -> Result<()> {
1007         let mut entry = self.data.user_keys.entry(user_id).or_default();
1008         if let Some(biometric) = entry.biometric_unlock.as_ref() {
1009             let (key_id_guard, key_entry) = db
1010                 .load_key_entry(
1011                     &biometric.key_desc,
1012                     KeyType::Client, // This should not be a Client key.
1013                     KeyEntryLoadBits::KM,
1014                     AID_KEYSTORE,
1015                     |_, _| Ok(()),
1016                 )
1017                 .context(ks_err!("load_key_entry failed"))?;
1018             let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
1019                 .context(ks_err!("KeyMintDevice::get failed"))?;
1020             for sid in &biometric.sids {
1021                 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
1022                     entry.auth_token().userId == *sid || entry.auth_token().authenticatorId == *sid
1023                 }) {
1024                     let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
1025                         let slb = biometric.screen_lock_bound.decrypt(
1026                             db,
1027                             &km_dev,
1028                             &key_id_guard,
1029                             &key_entry,
1030                             auth_token_entry.auth_token(),
1031                             None,
1032                         )?;
1033                         let slbp = biometric.screen_lock_bound_private.decrypt(
1034                             db,
1035                             &km_dev,
1036                             &key_id_guard,
1037                             &key_entry,
1038                             auth_token_entry.auth_token(),
1039                             Some(slb.clone()),
1040                         )?;
1041                         Ok((slb, slbp))
1042                     })();
1043                     match res {
1044                         Ok((slb, slbp)) => {
1045                             entry.screen_lock_bound = Some(slb.clone());
1046                             entry.screen_lock_bound_private = Some(slbp.clone());
1047                             self.data.add_key_to_key_index(&slb)?;
1048                             self.data.add_key_to_key_index(&slbp)?;
1049                             log::info!("Successfully unlocked with biometric");
1050                             return Ok(());
1051                         }
1052                         Err(e) => {
1053                             log::warn!("attempt failed: {:?}", e)
1054                         }
1055                     }
1056                 }
1057             }
1058         }
1059         Ok(())
1060     }
1061 
1062     /// Returns the keystore locked state of the given user. It requires the thread local
1063     /// keystore database and a reference to the legacy migrator because it may need to
1064     /// import the super key from the legacy blob database to the keystore database.
get_user_state( &self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, user_id: UserId, ) -> Result<UserState>1065     pub fn get_user_state(
1066         &self,
1067         db: &mut KeystoreDB,
1068         legacy_importer: &LegacyImporter,
1069         user_id: UserId,
1070     ) -> Result<UserState> {
1071         match self.get_per_boot_key_by_user_id_internal(user_id) {
1072             Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
1073             None => {
1074                 // Check if a super key exists in the database or legacy database.
1075                 // If so, return locked user state.
1076                 if self
1077                     .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
1078                     .context(ks_err!())?
1079                 {
1080                     Ok(UserState::LskfLocked)
1081                 } else {
1082                     Ok(UserState::Uninitialized)
1083                 }
1084             }
1085         }
1086     }
1087 
1088     /// If the given user is unlocked:
1089     /// * and `password` is None, the user is reset, all authentication bound keys are deleted and
1090     ///   `Ok(UserState::Uninitialized)` is returned.
1091     /// * and `password` is Some, `Ok(UserState::LskfUnlocked)` is returned.
1092     /// If the given user is locked:
1093     /// * and the user was initialized before, `Ok(UserState::Locked)` is returned.
1094     /// * and the user was not initialized before:
1095     ///   * and `password` is None, `Ok(Uninitialized)` is returned.
1096     ///   * and `password` is Some, super keys are generated and `Ok(UserState::LskfUnlocked)` is
1097     ///     returned.
reset_or_init_user_and_get_user_state( &mut self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, user_id: UserId, password: Option<&Password>, ) -> Result<UserState>1098     pub fn reset_or_init_user_and_get_user_state(
1099         &mut self,
1100         db: &mut KeystoreDB,
1101         legacy_importer: &LegacyImporter,
1102         user_id: UserId,
1103         password: Option<&Password>,
1104     ) -> Result<UserState> {
1105         match self.get_per_boot_key_by_user_id_internal(user_id) {
1106             Some(_) if password.is_none() => {
1107                 // Transitioning to swiping, delete only the super key in database and cache,
1108                 // and super-encrypted keys in database (and in KM).
1109                 self.reset_user(db, legacy_importer, user_id, true)
1110                     .context(ks_err!("Trying to delete keys from the db."))?;
1111                 // Lskf is now removed in Keystore.
1112                 Ok(UserState::Uninitialized)
1113             }
1114             Some(super_key) => {
1115                 // Keystore won't be notified when changing to a new password when LSKF is
1116                 // already setup. Therefore, ideally this path wouldn't be reached.
1117                 Ok(UserState::LskfUnlocked(super_key))
1118             }
1119             None => {
1120                 // Check if a super key exists in the database or legacy database.
1121                 // If so, return LskfLocked state.
1122                 // Otherwise, i) if the password is provided, initialize the super key and return
1123                 // LskfUnlocked state ii) if password is not provided, return Uninitialized state.
1124                 self.check_and_initialize_super_key(db, legacy_importer, user_id, password)
1125             }
1126         }
1127     }
1128 
1129     /// Unlocks the given user with the given password. If the key was already unlocked or unlocking
1130     /// was successful, `Ok(UserState::LskfUnlocked)` is returned.
1131     /// If the user was never initialized `Ok(UserState::Uninitialized)` is returned.
unlock_and_get_user_state( &mut self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, user_id: UserId, password: &Password, ) -> Result<UserState>1132     pub fn unlock_and_get_user_state(
1133         &mut self,
1134         db: &mut KeystoreDB,
1135         legacy_importer: &LegacyImporter,
1136         user_id: UserId,
1137         password: &Password,
1138     ) -> Result<UserState> {
1139         match self.get_per_boot_key_by_user_id_internal(user_id) {
1140             Some(super_key) => {
1141                 log::info!("Trying to unlock when already unlocked.");
1142                 Ok(UserState::LskfUnlocked(super_key))
1143             }
1144             None => {
1145                 // Check if a super key exists in the database or legacy database.
1146                 // If not, return Uninitialized state.
1147                 // Otherwise, try to unlock the super key and if successful,
1148                 // return LskfUnlocked.
1149                 self.check_and_unlock_super_key(db, legacy_importer, user_id, password)
1150                     .context(ks_err!("Failed to unlock super key."))
1151             }
1152         }
1153     }
1154 
1155     /// Delete all the keys created on behalf of the user.
1156     /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
1157     /// encrypted keys.
reset_user( &mut self, db: &mut KeystoreDB, legacy_importer: &LegacyImporter, user_id: UserId, keep_non_super_encrypted_keys: bool, ) -> Result<()>1158     pub fn reset_user(
1159         &mut self,
1160         db: &mut KeystoreDB,
1161         legacy_importer: &LegacyImporter,
1162         user_id: UserId,
1163         keep_non_super_encrypted_keys: bool,
1164     ) -> Result<()> {
1165         // Mark keys created on behalf of the user as unreferenced.
1166         legacy_importer
1167             .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
1168             .context(ks_err!("Trying to delete legacy keys."))?;
1169         db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
1170             .context(ks_err!("Error in unbinding keys."))?;
1171 
1172         // Delete super key in cache, if exists.
1173         self.forget_all_keys_for_user(user_id);
1174         Ok(())
1175     }
1176 }
1177 
1178 /// This enum represents different states of the user's life cycle in the device.
1179 /// For now, only three states are defined. More states may be added later.
1180 pub enum UserState {
1181     // The user has registered LSKF and has unlocked the device by entering PIN/Password,
1182     // and hence the per-boot super key is available in the cache.
1183     LskfUnlocked(Arc<SuperKey>),
1184     // The user has registered LSKF, but has not unlocked the device using password, after reboot.
1185     // Hence the per-boot super-key(s) is not available in the cache.
1186     // However, the encrypted super key is available in the database.
1187     LskfLocked,
1188     // There's no user in the device for the given user id, or the user with the user id has not
1189     // setup LSKF.
1190     Uninitialized,
1191 }
1192 
1193 /// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1194 /// `Sensitive` holds the non encrypted key and a reference to its super key.
1195 /// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1196 /// `Ref` holds a reference to a key blob when it does not need to be modified if its
1197 /// life time allows it.
1198 pub enum KeyBlob<'a> {
1199     Sensitive {
1200         key: ZVec,
1201         /// If KeyMint reports that the key must be upgraded, we must
1202         /// re-encrypt the key before writing to the database; we use
1203         /// this key.
1204         reencrypt_with: Arc<SuperKey>,
1205         /// If this key was decrypted with an ECDH key, we want to
1206         /// re-encrypt it on first use whether it was upgraded or not;
1207         /// this field indicates that that's necessary.
1208         force_reencrypt: bool,
1209     },
1210     NonSensitive(Vec<u8>),
1211     Ref(&'a [u8]),
1212 }
1213 
1214 impl<'a> KeyBlob<'a> {
force_reencrypt(&self) -> bool1215     pub fn force_reencrypt(&self) -> bool {
1216         if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1217             *force_reencrypt
1218         } else {
1219             false
1220         }
1221     }
1222 }
1223 
1224 /// Deref returns a reference to the key material in any variant.
1225 impl<'a> Deref for KeyBlob<'a> {
1226     type Target = [u8];
1227 
deref(&self) -> &Self::Target1228     fn deref(&self) -> &Self::Target {
1229         match self {
1230             Self::Sensitive { key, .. } => key,
1231             Self::NonSensitive(key) => key,
1232             Self::Ref(key) => key,
1233         }
1234     }
1235 }
1236