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