blob: 7fc3ed48bde43611a0698f67347da7cf5fe5613d [file] [log] [blame]
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskisb42fc182020-12-15 08:41:27 -080015use crate::{
Paul Crowley44c02da2021-04-08 17:04:43 +000016 boot_level_keys::{get_level_zero_key, BootLevelKeyCache},
Paul Crowley8d5b2532021-03-19 10:53:07 -070017 database::BlobMetaData,
18 database::BlobMetaEntry,
19 database::EncryptedBy,
20 database::KeyEntry,
21 database::KeyType,
Janis Danisevskisacebfa22021-05-25 10:56:10 -070022 database::{KeyEntryLoadBits, KeyIdGuard, KeyMetaData, KeyMetaEntry, KeystoreDB},
Paul Crowley8d5b2532021-03-19 10:53:07 -070023 ec_crypto::ECDHPrivateKey,
24 enforcements::Enforcements,
25 error::Error,
26 error::ResponseCode,
Paul Crowley618869e2021-04-08 20:30:54 -070027 key_parameter::{KeyParameter, KeyParameterValue},
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000028 ks_err,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080029 legacy_importer::LegacyImporter,
Paul Crowley618869e2021-04-08 20:30:54 -070030 raw_device::KeyMintDevice,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080031 utils::{watchdog as wd, AesGcm, AID_KEYSTORE},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080032};
Paul Crowley618869e2021-04-08 20:30:54 -070033use 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};
39use android_system_keystore2::aidl::android::system::keystore2::{
40 Domain::Domain, KeyDescriptor::KeyDescriptor,
41};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080042use anyhow::{Context, Result};
43use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070044 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
45 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046};
Joel Galenson7ead3a22021-07-29 15:27:34 -070047use rustutils::system_properties::PropertyWatcher;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080048use std::{
49 collections::HashMap,
50 sync::Arc,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080051 sync::{Mutex, RwLock, Weak},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080052};
Paul Crowley618869e2021-04-08 20:30:54 -070053use std::{convert::TryFrom, ops::Deref};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080054
Paul Crowley44c02da2021-04-08 17:04:43 +000055const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
Paul Crowley618869e2021-04-08 20:30:54 -070056/// Allow up to 15 seconds between the user unlocking using a biometric, and the auth
57/// token being used to unlock in [`SuperKeyManager::try_unlock_user_with_biometric`].
58/// This seems short enough for security purposes, while long enough that even the
59/// very slowest device will present the auth token in time.
60const BIOMETRIC_AUTH_TIMEOUT_S: i32 = 15; // seconds
Paul Crowley44c02da2021-04-08 17:04:43 +000061
Janis Danisevskisb42fc182020-12-15 08:41:27 -080062type UserId = u32;
63
Paul Crowley8d5b2532021-03-19 10:53:07 -070064/// Encryption algorithm used by a particular type of superencryption key
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum SuperEncryptionAlgorithm {
67 /// Symmetric encryption with AES-256-GCM
68 Aes256Gcm,
Paul Crowley52f017f2021-06-22 08:16:01 -070069 /// Public-key encryption with ECDH P-521
70 EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -070071}
72
Paul Crowley7a658392021-03-18 17:08:20 -070073/// A particular user may have several superencryption keys in the database, each for a
74/// different purpose, distinguished by alias. Each is associated with a static
75/// constant of this type.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080076pub struct SuperKeyType<'a> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080077 /// Alias used to look up the key in the `persistent.keyentry` table.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080078 pub alias: &'a str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070079 /// Encryption algorithm
80 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070081}
82
83/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
84/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070085pub const USER_SUPER_KEY: SuperKeyType =
86 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070087/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
88/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070089/// Symmetric.
90pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
91 alias: "USER_SCREEN_LOCK_BOUND_KEY",
92 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
93};
94/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
95/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
96/// Asymmetric, so keys can be encrypted when the device is locked.
Paul Crowley52f017f2021-06-22 08:16:01 -070097pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
98 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
99 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700100};
Paul Crowley7a658392021-03-18 17:08:20 -0700101
102/// Superencryption to apply to a new key.
103#[derive(Debug, Clone, Copy)]
104pub enum SuperEncryptionType {
105 /// Do not superencrypt this key.
106 None,
107 /// Superencrypt with a key that remains in memory from first unlock to reboot.
108 LskfBound,
109 /// Superencrypt with a key cleared from memory when the device is locked.
110 ScreenLockBound,
Paul Crowley44c02da2021-04-08 17:04:43 +0000111 /// Superencrypt with a key based on the desired boot level
112 BootLevel(i32),
113}
114
115#[derive(Debug, Clone, Copy)]
116pub enum SuperKeyIdentifier {
117 /// id of the super key in the database.
118 DatabaseId(i64),
119 /// Boot level of the encrypting boot level key
120 BootLevel(i32),
121}
122
123impl SuperKeyIdentifier {
124 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
125 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
126 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000127 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700128 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000129 }
130 }
131
132 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
133 match self {
134 SuperKeyIdentifier::DatabaseId(id) => {
135 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
136 }
137 SuperKeyIdentifier::BootLevel(level) => {
138 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
139 }
140 }
141 }
Paul Crowley7a658392021-03-18 17:08:20 -0700142}
143
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000144pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700145 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700146 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000147 /// Identifier of the encrypting key, used to write an encrypted blob
148 /// back to the database after re-encryption eg on a key update.
149 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700150 /// ECDH is more expensive than AES. So on ECDH private keys we set the
151 /// reencrypt_with field to point at the corresponding AES key, and the
152 /// keys will be re-encrypted with AES on first use.
153 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000154}
155
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800156impl AesGcm for SuperKey {
157 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700158 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000159 aes_gcm_decrypt(data, iv, tag, &self.key).context(ks_err!("Decryption failed."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700160 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000161 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800162 }
163 }
164
165 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
166 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000167 aes_gcm_encrypt(plaintext, &self.key).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800168 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000169 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700170 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000171 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700172}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000173
Paul Crowley618869e2021-04-08 20:30:54 -0700174/// A SuperKey that has been encrypted with an AES-GCM key. For
175/// encryption the key is in memory, and for decryption it is in KM.
176struct LockedKey {
177 algorithm: SuperEncryptionAlgorithm,
178 id: SuperKeyIdentifier,
179 nonce: Vec<u8>,
180 ciphertext: Vec<u8>, // with tag appended
181}
182
183impl LockedKey {
184 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
185 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
186 ciphertext.append(&mut tag);
187 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
188 }
189
190 fn decrypt(
191 &self,
192 db: &mut KeystoreDB,
193 km_dev: &KeyMintDevice,
194 key_id_guard: &KeyIdGuard,
195 key_entry: &KeyEntry,
196 auth_token: &HardwareAuthToken,
197 reencrypt_with: Option<Arc<SuperKey>>,
198 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700199 let key_blob = key_entry
200 .key_blob_info()
201 .as_ref()
202 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
203 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000204 .context(ks_err!("Missing key blob info."))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700205 let key_params = vec![
206 KeyParameterValue::Algorithm(Algorithm::AES),
207 KeyParameterValue::KeySize(256),
208 KeyParameterValue::BlockMode(BlockMode::GCM),
209 KeyParameterValue::PaddingMode(PaddingMode::NONE),
210 KeyParameterValue::Nonce(self.nonce.clone()),
211 KeyParameterValue::MacLength(128),
212 ];
213 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
214 let key = ZVec::try_from(km_dev.use_key_in_one_step(
215 db,
216 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700217 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700218 KeyPurpose::DECRYPT,
219 &key_params,
220 Some(auth_token),
221 &self.ciphertext,
222 )?)?;
223 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
224 }
225}
226
227/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
228/// a database descriptor for the encrypting key and the sids for the auth tokens
229/// that can be used to decrypt it.
230struct BiometricUnlock {
231 /// List of auth token SIDs that can be used to unlock these keys.
232 sids: Vec<i64>,
233 /// Database descriptor of key to use to unlock.
234 key_desc: KeyDescriptor,
235 /// Locked versions of the matching UserSuperKeys fields
236 screen_lock_bound: LockedKey,
237 screen_lock_bound_private: LockedKey,
238}
239
Paul Crowleye8826e52021-03-31 08:33:53 -0700240#[derive(Default)]
241struct UserSuperKeys {
242 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
243 /// key per android user. The key is stored on flash encrypted with a key derived from a
244 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
245 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
246 /// and stays memory resident until the device reboots.
247 per_boot: Option<Arc<SuperKey>>,
248 /// The screen lock key works like the per boot key with the distinction that it is cleared
249 /// from memory when the screen lock is engaged.
250 screen_lock_bound: Option<Arc<SuperKey>>,
251 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
252 /// ECDH public-key encryption. This field holds the decryption private key.
253 screen_lock_bound_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700254 /// Versions of the above two keys, locked behind a biometric.
255 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000256}
257
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800258#[derive(Default)]
259struct SkmState {
260 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700261 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800262 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700263}
264
265impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000266 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
267 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
268 self.key_index.insert(id, Arc::downgrade(super_key));
269 Ok(())
270 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000271 Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000272 }
Paul Crowley7a658392021-03-18 17:08:20 -0700273 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800274}
275
276#[derive(Default)]
277pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800278 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800279}
280
281impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800282 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
283 let mut skm_guard = skm.write().unwrap();
284 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000285 log::info!("In set_up_boot_level_cache: called for a second time");
286 return Ok(());
287 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000288 let level_zero_key =
289 get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800290 skm_guard.data.boot_level_key_cache =
291 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000292 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800293 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000294 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800295 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000296 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
297 });
298 Ok(())
299 }
300
301 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
302 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800303 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000304 let mut w = PropertyWatcher::new("keystore.boot_level")
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000305 .context(ks_err!("PropertyWatcher::new failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000306 loop {
307 let level = w
308 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000309 .context(ks_err!("read of property failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800310
311 // This scope limits the skm_guard life, so we don't hold the skm_guard while
312 // waiting.
313 {
314 let mut skm_guard = skm.write().unwrap();
315 let boot_level_key_cache = skm_guard
316 .data
317 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000318 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800319 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000320 .context(ks_err!("Boot level cache not initialized"))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800321 .get_mut()
322 .unwrap();
323 if level < MAX_MAX_BOOT_LEVEL {
324 log::info!("Read keystore.boot_level value {}", level);
325 boot_level_key_cache
326 .advance_boot_level(level)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000327 .context(ks_err!("advance_boot_level failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800328 } else {
329 log::info!(
330 "keystore.boot_level {} hits maximum {}, finishing.",
331 level,
332 MAX_MAX_BOOT_LEVEL
333 );
334 boot_level_key_cache.finish();
335 break;
336 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000337 }
Andrew Walbran48fa9702023-05-10 15:19:30 +0000338 w.wait(None).context(ks_err!("property wait failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000339 }
340 Ok(())
341 }
342
343 pub fn level_accessible(&self, boot_level: i32) -> bool {
344 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000345 .boot_level_key_cache
346 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800347 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000348 }
349
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800350 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
351 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800352 }
353
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800354 fn install_per_boot_key_for_user(
355 &mut self,
356 user: UserId,
357 super_key: Arc<SuperKey>,
358 ) -> Result<()> {
359 self.data
360 .add_key_to_key_index(&super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000361 .context(ks_err!("add_key_to_key_index failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800362 self.data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000363 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800364 }
365
Paul Crowley44c02da2021-04-08 17:04:43 +0000366 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000367 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800368 SuperKeyIdentifier::DatabaseId(id) => {
369 self.data.key_index.get(id).and_then(|k| k.upgrade())
370 }
371 SuperKeyIdentifier::BootLevel(level) => self
372 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000373 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800374 .as_ref()
375 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000376 .transpose()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000377 .context(ks_err!("aes_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000378 .flatten()
379 .map(|key| {
380 Arc::new(SuperKey {
381 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
382 key,
383 id: *key_id,
384 reencrypt_with: None,
385 })
386 }),
387 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800388 }
389
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800390 pub fn get_per_boot_key_by_user_id(
391 &self,
392 user_id: UserId,
393 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
394 self.get_per_boot_key_by_user_id_internal(user_id)
395 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
396 }
397
398 fn get_per_boot_key_by_user_id_internal(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800399 self.data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800400 }
401
Paul Crowley44c02da2021-04-08 17:04:43 +0000402 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
403 /// the relevant super key.
404 pub fn unwrap_key_if_required<'a>(
405 &self,
406 metadata: &BlobMetaData,
407 blob: &'a [u8],
408 ) -> Result<KeyBlob<'a>> {
409 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
410 let super_key = self
411 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000412 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000413 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000414 .context(ks_err!("Required super decryption key is not in memory."))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000415 KeyBlob::Sensitive {
416 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000417 .context(ks_err!("unwrap_key_with_key failed"))?,
Paul Crowley44c02da2021-04-08 17:04:43 +0000418 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
419 force_reencrypt: super_key.reencrypt_with.is_some(),
420 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700421 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000422 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700423 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800424 }
425
426 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700427 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700428 match key.algorithm {
429 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000430 (Some(iv), Some(tag)) => {
431 key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
432 }
433 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
434 "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700435 iv.is_some(),
436 tag.is_some(),
437 )),
438 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700439 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700440 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
441 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
442 ECDHPrivateKey::from_private_key(&key.key)
443 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000444 .context(ks_err!("Failed to decrypt the key blob with ECDH."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700445 }
446 (public_key, salt, iv, aead_tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000447 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700448 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000449 "Key has incomplete metadata. ",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700450 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
451 ),
452 public_key.is_some(),
453 salt.is_some(),
454 iv.is_some(),
455 aead_tag.is_some(),
456 ))
457 }
458 }
459 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800460 }
461 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000462
463 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800464 /// The reference to self is unused but it is required to prevent calling this function
465 /// concurrently with skm state database changes.
466 fn super_key_exists_in_db_for_user(
467 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000468 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800469 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700470 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000471 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000472 let key_in_db = db
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700473 .key_exists(Domain::APP, user_id as u64 as i64, USER_SUPER_KEY.alias, KeyType::Super)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000474 .context(ks_err!())?;
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000475
476 if key_in_db {
477 Ok(key_in_db)
478 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000479 legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000480 }
481 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000482
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800483 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000484 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800485 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700486 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700487 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000488 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700489 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700490 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700491 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000492 .context(ks_err!("Failed to extract super key from key entry"))?;
Nathan Huckleberry95dca012023-05-10 18:02:11 +0000493 self.install_per_boot_key_for_user(user_id, super_key.clone())
494 .context(ks_err!("Failed to install per boot key for user!"))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000495 Ok(super_key)
496 }
497
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800498 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700499 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700500 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700501 entry: KeyEntry,
502 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700503 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700504 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000505 if let Some((blob, metadata)) = entry.key_blob_info() {
506 let key = match (
507 metadata.encrypted_by(),
508 metadata.salt(),
509 metadata.iv(),
510 metadata.aead_tag(),
511 ) {
512 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800513 // Note that password encryption is AES no matter the value of algorithm.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000514 let key = pw
515 .derive_key(salt, AES_256_KEY_LENGTH)
516 .context(ks_err!("Failed to generate key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000517
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000518 aes_gcm_decrypt(blob, iv, tag, &key)
519 .context(ks_err!("Failed to decrypt key blob."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +0000520 }
521 (enc_by, salt, iv, tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000522 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Hasini Gunasingheda895552021-01-27 19:34:37 +0000523 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000524 "Super key has incomplete metadata.",
525 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
526 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700527 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000528 salt.is_some(),
529 iv.is_some(),
530 tag.is_some()
531 ));
532 }
533 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000534 Ok(Arc::new(SuperKey {
535 algorithm,
536 key,
537 id: SuperKeyIdentifier::DatabaseId(entry.id()),
538 reencrypt_with,
539 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000540 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000541 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000542 }
543 }
544
545 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700546 pub fn encrypt_with_password(
547 super_key: &[u8],
548 pw: &Password,
549 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000550 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700551 let derived_key = pw
David Drysdale6a0ec2c2022-04-19 08:11:18 +0100552 .derive_key(&salt, AES_256_KEY_LENGTH)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000553 .context(ks_err!("Failed to derive password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000554 let mut metadata = BlobMetaData::new();
555 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
556 metadata.add(BlobMetaEntry::Salt(salt));
557 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000558 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000559 metadata.add(BlobMetaEntry::Iv(iv));
560 metadata.add(BlobMetaEntry::AeadTag(tag));
561 Ok((encrypted_key, metadata))
562 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000563
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800564 // Helper function to encrypt a key with the given super key. Callers should select which super
565 // key to be used. This is called when a key is super encrypted at its creation as well as at
566 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700567 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000568 key_blob: &[u8],
569 super_key: &SuperKey,
570 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700571 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000572 return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
Paul Crowley8d5b2532021-03-19 10:53:07 -0700573 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000574 let mut metadata = BlobMetaData::new();
575 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000576 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000577 metadata.add(BlobMetaEntry::Iv(iv));
578 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000579 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000580 Ok((encrypted_key, metadata))
581 }
582
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000583 // Encrypts a given key_blob using a hybrid approach, which can either use the symmetric super
584 // key or the public super key depending on which is available.
585 //
586 // If the symmetric_key is available, the key_blob is encrypted using symmetric encryption with
587 // the provided symmetric super key. Otherwise, the function loads the public super key from
588 // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be
589 // re-encrypted with the symmetric super key on the first use.
590 //
591 // This hybrid scheme allows lock-screen-bound keys to be added when the screen is locked.
592 fn encrypt_with_hybrid_super_key(
593 key_blob: &[u8],
594 symmetric_key: Option<&SuperKey>,
595 public_key_type: &SuperKeyType,
596 db: &mut KeystoreDB,
597 user_id: UserId,
598 ) -> Result<(Vec<u8>, BlobMetaData)> {
599 if let Some(super_key) = symmetric_key {
600 Self::encrypt_with_aes_super_key(key_blob, super_key)
601 .context(ks_err!("Failed to encrypt with ScreenLockBound super key."))
602 } else {
603 // Symmetric key is not available, use public key encryption
604 let loaded = db
605 .load_super_key(public_key_type, user_id)
606 .context(ks_err!("load_super_key failed."))?;
607 let (key_id_guard, key_entry) =
608 loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH super key missing."))?;
609 let public_key = key_entry
610 .metadata()
611 .sec1_public_key()
612 .ok_or_else(Error::sys)
613 .context(ks_err!("sec1_public_key missing."))?;
614 let mut metadata = BlobMetaData::new();
615 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
616 ECDHPrivateKey::encrypt_message(public_key, key_blob)
617 .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
618 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
619 metadata.add(BlobMetaEntry::Salt(salt));
620 metadata.add(BlobMetaEntry::Iv(iv));
621 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
622 SuperKeyIdentifier::DatabaseId(key_id_guard.id()).add_to_metadata(&mut metadata);
623 Ok((encrypted_key, metadata))
624 }
625 }
626
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000627 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
628 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700629 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000630 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000631 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000632 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800633 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000634 domain: &Domain,
635 key_parameters: &[KeyParameter],
636 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700637 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000638 key_blob: &[u8],
639 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700640 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
641 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000642 SuperEncryptionType::LskfBound => {
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +0000643 // Encrypt the given key blob with the user's per-boot super key. If the per-boot
644 // super key is not unlocked or the LSKF is not setup, an error is returned.
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000645 match self
646 .get_user_state(db, legacy_importer, user_id)
647 .context(ks_err!("Failed to get user state."))?
648 {
649 UserState::LskfUnlocked(super_key) => {
650 Self::encrypt_with_aes_super_key(key_blob, &super_key)
651 .context(ks_err!("Failed to encrypt with LskfBound key."))
652 }
653 UserState::LskfLocked => {
654 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
655 }
656 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
657 .context(ks_err!("LSKF is not setup for the user.")),
658 }
659 }
Paul Crowley7a658392021-03-18 17:08:20 -0700660 SuperEncryptionType::ScreenLockBound => {
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000661 let screen_lock_bound_symmetric_key = self
662 .data
663 .user_keys
664 .get(&user_id)
665 .and_then(|e| e.screen_lock_bound.as_ref())
666 .map(|arc| arc.as_ref());
667 Self::encrypt_with_hybrid_super_key(
668 key_blob,
669 screen_lock_bound_symmetric_key,
670 &USER_SCREEN_LOCK_BOUND_P521_KEY,
671 db,
672 user_id,
673 )
674 .context(ks_err!("Failed to encrypt with ScreenLockBound hybrid scheme."))
Paul Crowley7a658392021-03-18 17:08:20 -0700675 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000676 SuperEncryptionType::BootLevel(level) => {
677 let key_id = SuperKeyIdentifier::BootLevel(level);
678 let super_key = self
679 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000680 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000681 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000682 .context(ks_err!("Boot stage key absent"))?;
683 Self::encrypt_with_aes_super_key(key_blob, &super_key)
684 .context(ks_err!("Failed to encrypt with BootLevel key."))
Paul Crowley44c02da2021-04-08 17:04:43 +0000685 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000686 }
687 }
688
689 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
690 /// If so, re-super-encrypt the key and return a new set of metadata,
691 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700692 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000693 key_blob_before_upgrade: &KeyBlob,
694 key_after_upgrade: &'a [u8],
695 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
696 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700697 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700698 let (key, metadata) =
699 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000700 .context(ks_err!("Failed to re-super-encrypt key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000701 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
702 }
703 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
704 }
705 }
706
Paul Crowley7a658392021-03-18 17:08:20 -0700707 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
708 /// When this is called, the caller must hold the lock on the SuperKeyManager.
709 /// So it's OK that the check and creation are different DB transactions.
710 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800711 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700712 db: &mut KeystoreDB,
713 user_id: UserId,
714 key_type: &SuperKeyType,
715 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700716 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700717 ) -> Result<Arc<SuperKey>> {
718 let loaded_key = db.load_super_key(key_type, user_id)?;
719 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700720 Ok(Self::extract_super_key_from_key_entry(
721 key_type.algorithm,
722 key_entry,
723 password,
724 reencrypt_with,
725 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700726 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700727 let (super_key, public_key) = match key_type.algorithm {
728 SuperEncryptionAlgorithm::Aes256Gcm => (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000729 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700730 None,
731 ),
Paul Crowley52f017f2021-06-22 08:16:01 -0700732 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700733 let key = ECDHPrivateKey::generate()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000734 .context(ks_err!("Failed to generate ECDH key"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700735 (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000736 key.private_key().context(ks_err!("private_key failed"))?,
737 Some(key.public_key().context(ks_err!("public_key failed"))?),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700738 )
739 }
740 };
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800741 // Derive an AES256 key from the password and re-encrypt the super key
742 // before we insert it in the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700743 let (encrypted_super_key, blob_metadata) =
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000744 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700745 let mut key_metadata = KeyMetaData::new();
746 if let Some(pk) = public_key {
747 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
748 }
Paul Crowley7a658392021-03-18 17:08:20 -0700749 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700750 .store_super_key(
751 user_id,
752 key_type,
753 &encrypted_super_key,
754 &blob_metadata,
755 &key_metadata,
756 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000757 .context(ks_err!("Failed to store super key."))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700758 Ok(Arc::new(SuperKey {
759 algorithm: key_type.algorithm,
760 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000761 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700762 reencrypt_with,
763 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700764 }
765 }
766
Paul Crowley8d5b2532021-03-19 10:53:07 -0700767 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700768 pub fn unlock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800769 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700770 db: &mut KeystoreDB,
771 user_id: UserId,
772 password: &Password,
773 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800774 let (screen_lock_bound, screen_lock_bound_private) = self
775 .data
776 .user_keys
777 .get(&user_id)
778 .map(|e| (e.screen_lock_bound.clone(), e.screen_lock_bound_private.clone()))
779 .unwrap_or((None, None));
780
781 if screen_lock_bound.is_some() && screen_lock_bound_private.is_some() {
782 // Already unlocked.
783 return Ok(());
784 }
785
786 let aes = if let Some(screen_lock_bound) = screen_lock_bound {
787 // This is weird. If this point is reached only one of the screen locked keys was
788 // initialized. This should never happen.
789 screen_lock_bound
790 } else {
791 self.get_or_create_super_key(db, user_id, &USER_SCREEN_LOCK_BOUND_KEY, password, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000792 .context(ks_err!("Trying to get or create symmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800793 };
794
795 let ecdh = if let Some(screen_lock_bound_private) = screen_lock_bound_private {
796 // This is weird. If this point is reached only one of the screen locked keys was
797 // initialized. This should never happen.
798 screen_lock_bound_private
799 } else {
800 self.get_or_create_super_key(
801 db,
802 user_id,
803 &USER_SCREEN_LOCK_BOUND_P521_KEY,
804 password,
805 Some(aes.clone()),
806 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000807 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800808 };
809
810 self.data.add_key_to_key_index(&aes)?;
811 self.data.add_key_to_key_index(&ecdh)?;
812 let entry = self.data.user_keys.entry(user_id).or_default();
813 entry.screen_lock_bound = Some(aes);
814 entry.screen_lock_bound_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700815 Ok(())
816 }
817
Paul Crowley8d5b2532021-03-19 10:53:07 -0700818 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley618869e2021-04-08 20:30:54 -0700819 pub fn lock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800820 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700821 db: &mut KeystoreDB,
822 user_id: UserId,
823 unlocking_sids: &[i64],
824 ) {
825 log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
Chris Wailes53a22af2023-07-12 17:02:47 -0700826 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700827 if !unlocking_sids.is_empty() {
828 if let (Some(aes), Some(ecdh)) = (
829 entry.screen_lock_bound.as_ref().cloned(),
830 entry.screen_lock_bound_private.as_ref().cloned(),
831 ) {
832 let res = (|| -> Result<()> {
833 let key_desc = KeyMintDevice::internal_descriptor(format!(
834 "biometric_unlock_key_{}",
835 user_id
836 ));
837 let encrypting_key = generate_aes256_key()?;
838 let km_dev: KeyMintDevice =
839 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000840 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700841 let mut key_params = vec![
842 KeyParameterValue::Algorithm(Algorithm::AES),
843 KeyParameterValue::KeySize(256),
844 KeyParameterValue::BlockMode(BlockMode::GCM),
845 KeyParameterValue::PaddingMode(PaddingMode::NONE),
846 KeyParameterValue::CallerNonce,
847 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
848 KeyParameterValue::MinMacLength(128),
849 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
850 KeyParameterValue::HardwareAuthenticatorType(
851 HardwareAuthenticatorType::FINGERPRINT,
852 ),
853 ];
854 for sid in unlocking_sids {
855 key_params.push(KeyParameterValue::UserSecureID(*sid));
856 }
857 let key_params: Vec<KmKeyParameter> =
858 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700859 km_dev.create_and_store_key(
860 db,
861 &key_desc,
862 KeyType::Client, /* TODO Should be Super b/189470584 */
863 |dev| {
864 let _wp = wd::watch_millis(
865 "In lock_screen_lock_bound_key: calling importKey.",
866 500,
867 );
868 dev.importKey(
869 key_params.as_slice(),
870 KeyFormat::RAW,
871 &encrypting_key,
872 None,
873 )
874 },
875 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700876 entry.biometric_unlock = Some(BiometricUnlock {
877 sids: unlocking_sids.into(),
878 key_desc,
879 screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
880 screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
881 });
882 Ok(())
883 })();
884 // There is no reason to propagate an error here upwards. We must discard
885 // entry.screen_lock_bound* in any case.
886 if let Err(e) = res {
887 log::error!("Error setting up biometric unlock: {:#?}", e);
888 }
889 }
890 }
Paul Crowley7a658392021-03-18 17:08:20 -0700891 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700892 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700893 }
Paul Crowley618869e2021-04-08 20:30:54 -0700894
895 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
896 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
897 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800898 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700899 db: &mut KeystoreDB,
900 user_id: UserId,
901 ) -> Result<()> {
Chris Wailes53a22af2023-07-12 17:02:47 -0700902 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700903 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700904 let (key_id_guard, key_entry) = db
905 .load_key_entry(
906 &biometric.key_desc,
907 KeyType::Client, // This should not be a Client key.
908 KeyEntryLoadBits::KM,
909 AID_KEYSTORE,
910 |_, _| Ok(()),
911 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000912 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700913 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000914 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700915 for sid in &biometric.sids {
916 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
917 entry.auth_token().userId == *sid || entry.auth_token().authenticatorId == *sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700918 }) {
Paul Crowley618869e2021-04-08 20:30:54 -0700919 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
920 let slb = biometric.screen_lock_bound.decrypt(
921 db,
922 &km_dev,
923 &key_id_guard,
924 &key_entry,
925 auth_token_entry.auth_token(),
926 None,
927 )?;
928 let slbp = biometric.screen_lock_bound_private.decrypt(
929 db,
930 &km_dev,
931 &key_id_guard,
932 &key_entry,
933 auth_token_entry.auth_token(),
934 Some(slb.clone()),
935 )?;
936 Ok((slb, slbp))
937 })();
938 match res {
939 Ok((slb, slbp)) => {
940 entry.screen_lock_bound = Some(slb.clone());
941 entry.screen_lock_bound_private = Some(slbp.clone());
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800942 self.data.add_key_to_key_index(&slb)?;
943 self.data.add_key_to_key_index(&slbp)?;
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000944 log::info!("Successfully unlocked with biometric");
Paul Crowley618869e2021-04-08 20:30:54 -0700945 return Ok(());
946 }
947 Err(e) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000948 log::warn!("attempt failed: {:?}", e)
Paul Crowley618869e2021-04-08 20:30:54 -0700949 }
950 }
951 }
952 }
953 }
954 Ok(())
955 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800956
957 /// Returns the keystore locked state of the given user. It requires the thread local
958 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800959 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800960 pub fn get_user_state(
961 &self,
962 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800963 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800964 user_id: UserId,
965 ) -> Result<UserState> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800966 match self.get_per_boot_key_by_user_id_internal(user_id) {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800967 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
968 None => {
969 // Check if a super key exists in the database or legacy database.
970 // If so, return locked user state.
971 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800972 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000973 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800974 {
975 Ok(UserState::LskfLocked)
976 } else {
977 Ok(UserState::Uninitialized)
978 }
979 }
980 }
981 }
982
Nathan Huckleberry204a0442023-03-30 17:27:47 +0000983 /// Deletes all keys and super keys for the given user.
984 /// This is called when a user is deleted.
985 pub fn remove_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800986 &mut self,
987 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800988 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800989 user_id: UserId,
Nathan Huckleberry204a0442023-03-30 17:27:47 +0000990 ) -> Result<()> {
991 // Mark keys created on behalf of the user as unreferenced.
992 legacy_importer
993 .bulk_delete_user(user_id, false)
994 .context(ks_err!("Trying to delete legacy keys."))?;
995 db.unbind_keys_for_user(user_id, false).context(ks_err!("Error in unbinding keys."))?;
996
997 // Delete super key in cache, if exists.
998 self.forget_all_keys_for_user(user_id);
999 Ok(())
1000 }
1001
1002 /// Deletes all authentication bound keys and super keys for the given user. The user must be
1003 /// unlocked before this function is called. This function is used to transition a user to
1004 /// swipe.
1005 pub fn reset_user(
1006 &mut self,
1007 db: &mut KeystoreDB,
1008 legacy_importer: &LegacyImporter,
1009 user_id: UserId,
1010 ) -> Result<()> {
1011 match self.get_user_state(db, legacy_importer, user_id)? {
1012 UserState::Uninitialized => {
1013 Err(Error::sys()).context(ks_err!("Tried to reset an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001014 }
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001015 UserState::LskfLocked => {
1016 Err(Error::sys()).context(ks_err!("Tried to reset a locked user's password!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001017 }
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001018 UserState::LskfUnlocked(_) => {
1019 // Mark keys created on behalf of the user as unreferenced.
1020 legacy_importer
1021 .bulk_delete_user(user_id, true)
1022 .context(ks_err!("Trying to delete legacy keys."))?;
1023 db.unbind_keys_for_user(user_id, true)
1024 .context(ks_err!("Error in unbinding keys."))?;
1025
1026 // Delete super key in cache, if exists.
1027 self.forget_all_keys_for_user(user_id);
1028 Ok(())
1029 }
1030 }
1031 }
1032
1033 /// If the user hasn't been initialized yet, then this function generates the user's super keys
1034 /// and sets the user's state to LskfUnlocked. Otherwise this function returns an error.
1035 pub fn init_user(
1036 &mut self,
1037 db: &mut KeystoreDB,
1038 legacy_importer: &LegacyImporter,
1039 user_id: UserId,
1040 password: &Password,
1041 ) -> Result<()> {
1042 match self.get_user_state(db, legacy_importer, user_id)? {
1043 UserState::LskfUnlocked(_) | UserState::LskfLocked => {
1044 Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"))
1045 }
1046 UserState::Uninitialized => {
1047 // Generate a new super key.
1048 let super_key =
1049 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
1050 // Derive an AES256 key from the password and re-encrypt the super key
1051 // before we insert it in the database.
1052 let (encrypted_super_key, blob_metadata) =
1053 Self::encrypt_with_password(&super_key, password)
1054 .context(ks_err!("Failed to encrypt super key with password!"))?;
1055
1056 let key_entry = db
1057 .store_super_key(
1058 user_id,
1059 &USER_SUPER_KEY,
1060 &encrypted_super_key,
1061 &blob_metadata,
1062 &KeyMetaData::new(),
1063 )
1064 .context(ks_err!("Failed to store super key."))?;
1065
1066 self.populate_cache_from_super_key_blob(
1067 user_id,
1068 USER_SUPER_KEY.algorithm,
1069 key_entry,
1070 password,
1071 )
1072 .context(ks_err!("Failed to initialize user!"))?;
1073 Ok(())
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001074 }
1075 }
1076 }
1077
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001078 /// Unlocks the given user with the given password.
1079 ///
1080 /// If the user is LskfLocked:
1081 /// - Unlock the per_boot super key
1082 /// - Unlock the screen_lock_bound super key
1083 ///
1084 /// If the user is LskfUnlocked:
1085 /// - Unlock the screen_lock_bound super key only
1086 ///
1087 pub fn unlock_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001088 &mut self,
1089 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001090 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001091 user_id: UserId,
1092 password: &Password,
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001093 ) -> Result<()> {
1094 match self.get_user_state(db, legacy_importer, user_id)? {
1095 UserState::LskfUnlocked(_) => self.unlock_screen_lock_bound_key(db, user_id, password),
1096 UserState::Uninitialized => {
1097 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001098 }
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001099 UserState::LskfLocked => {
1100 let alias = &USER_SUPER_KEY;
1101 let result = legacy_importer
1102 .with_try_import_super_key(user_id, password, || {
1103 db.load_super_key(alias, user_id)
1104 })
1105 .context(ks_err!("Failed to load super key"))?;
1106
1107 match result {
1108 Some((_, entry)) => {
1109 self.populate_cache_from_super_key_blob(
1110 user_id,
1111 alias.algorithm,
1112 entry,
1113 password,
1114 )
1115 .context(ks_err!("Failed when unlocking user."))?;
1116 self.unlock_screen_lock_bound_key(db, user_id, password)
1117 }
1118 None => {
1119 Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))
1120 }
1121 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001122 }
1123 }
1124 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001125}
1126
1127/// This enum represents different states of the user's life cycle in the device.
1128/// For now, only three states are defined. More states may be added later.
1129pub enum UserState {
1130 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
1131 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -07001132 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001133 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
1134 // Hence the per-boot super-key(s) is not available in the cache.
1135 // However, the encrypted super key is available in the database.
1136 LskfLocked,
1137 // There's no user in the device for the given user id, or the user with the user id has not
1138 // setup LSKF.
1139 Uninitialized,
1140}
1141
Janis Danisevskiseed69842021-02-18 20:04:10 -08001142/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1143/// `Sensitive` holds the non encrypted key and a reference to its super key.
1144/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1145/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1146/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001147pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001148 Sensitive {
1149 key: ZVec,
1150 /// If KeyMint reports that the key must be upgraded, we must
1151 /// re-encrypt the key before writing to the database; we use
1152 /// this key.
1153 reencrypt_with: Arc<SuperKey>,
1154 /// If this key was decrypted with an ECDH key, we want to
1155 /// re-encrypt it on first use whether it was upgraded or not;
1156 /// this field indicates that that's necessary.
1157 force_reencrypt: bool,
1158 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001159 NonSensitive(Vec<u8>),
1160 Ref(&'a [u8]),
1161}
1162
Paul Crowley8d5b2532021-03-19 10:53:07 -07001163impl<'a> KeyBlob<'a> {
1164 pub fn force_reencrypt(&self) -> bool {
1165 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1166 *force_reencrypt
1167 } else {
1168 false
1169 }
1170 }
1171}
1172
Janis Danisevskiseed69842021-02-18 20:04:10 -08001173/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001174impl<'a> Deref for KeyBlob<'a> {
1175 type Target = [u8];
1176
1177 fn deref(&self) -> &Self::Target {
1178 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001179 Self::Sensitive { key, .. } => key,
1180 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001181 Self::Ref(key) => key,
1182 }
1183 }
1184}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001185
1186#[cfg(test)]
1187mod tests {
1188 use super::*;
1189 use crate::database::tests::make_bootlevel_key_entry;
1190 use crate::database::tests::make_test_key_entry;
1191 use crate::database::tests::new_test_db;
1192 use rand::prelude::*;
1193 const USER_ID: u32 = 0;
1194 const TEST_KEY_ALIAS: &str = "TEST_KEY";
1195 const TEST_BOOT_KEY_ALIAS: &str = "TEST_BOOT_KEY";
1196
1197 pub fn generate_password_blob() -> Password<'static> {
1198 let mut rng = rand::thread_rng();
1199 let mut password = vec![0u8; 64];
1200 rng.fill_bytes(&mut password);
1201
1202 let mut zvec = ZVec::new(64).expect("Failed to create ZVec");
1203 zvec[..].copy_from_slice(&password[..]);
1204
1205 Password::Owned(zvec)
1206 }
1207
1208 fn setup_test(pw: &Password) -> (Arc<RwLock<SuperKeyManager>>, KeystoreDB, LegacyImporter) {
1209 let mut keystore_db = new_test_db().unwrap();
1210 let mut legacy_importer = LegacyImporter::new(Arc::new(Default::default()));
1211 legacy_importer.set_empty();
1212 let skm: Arc<RwLock<SuperKeyManager>> = Default::default();
1213 assert!(skm
1214 .write()
1215 .unwrap()
1216 .init_user(&mut keystore_db, &legacy_importer, USER_ID, pw)
1217 .is_ok());
1218 (skm, keystore_db, legacy_importer)
1219 }
1220
1221 fn assert_unlocked(
1222 skm: &Arc<RwLock<SuperKeyManager>>,
1223 keystore_db: &mut KeystoreDB,
1224 legacy_importer: &LegacyImporter,
1225 user_id: u32,
1226 err_msg: &str,
1227 ) {
1228 let user_state =
1229 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1230 match user_state {
1231 UserState::LskfUnlocked(_) => {}
1232 _ => panic!("{}", err_msg),
1233 }
1234 }
1235
1236 fn assert_locked(
1237 skm: &Arc<RwLock<SuperKeyManager>>,
1238 keystore_db: &mut KeystoreDB,
1239 legacy_importer: &LegacyImporter,
1240 user_id: u32,
1241 err_msg: &str,
1242 ) {
1243 let user_state =
1244 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1245 match user_state {
1246 UserState::LskfLocked => {}
1247 _ => panic!("{}", err_msg),
1248 }
1249 }
1250
1251 fn assert_uninitialized(
1252 skm: &Arc<RwLock<SuperKeyManager>>,
1253 keystore_db: &mut KeystoreDB,
1254 legacy_importer: &LegacyImporter,
1255 user_id: u32,
1256 err_msg: &str,
1257 ) {
1258 let user_state =
1259 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1260 match user_state {
1261 UserState::Uninitialized => {}
1262 _ => panic!("{}", err_msg),
1263 }
1264 }
1265
1266 #[test]
1267 fn test_init_user() {
1268 let pw: Password = generate_password_blob();
1269 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1270 assert_unlocked(
1271 &skm,
1272 &mut keystore_db,
1273 &legacy_importer,
1274 USER_ID,
1275 "The user was not unlocked after initialization!",
1276 );
1277 }
1278
1279 #[test]
1280 fn test_unlock_user() {
1281 let pw: Password = generate_password_blob();
1282 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1283 assert_unlocked(
1284 &skm,
1285 &mut keystore_db,
1286 &legacy_importer,
1287 USER_ID,
1288 "The user was not unlocked after initialization!",
1289 );
1290
1291 skm.write().unwrap().data.user_keys.clear();
1292 assert_locked(
1293 &skm,
1294 &mut keystore_db,
1295 &legacy_importer,
1296 USER_ID,
1297 "Clearing the cache did not lock the user!",
1298 );
1299
1300 assert!(skm
1301 .write()
1302 .unwrap()
1303 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1304 .is_ok());
1305 assert_unlocked(
1306 &skm,
1307 &mut keystore_db,
1308 &legacy_importer,
1309 USER_ID,
1310 "The user did not unlock!",
1311 );
1312 }
1313
1314 #[test]
1315 fn test_unlock_wrong_password() {
1316 let pw: Password = generate_password_blob();
1317 let wrong_pw: Password = generate_password_blob();
1318 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1319 assert_unlocked(
1320 &skm,
1321 &mut keystore_db,
1322 &legacy_importer,
1323 USER_ID,
1324 "The user was not unlocked after initialization!",
1325 );
1326
1327 skm.write().unwrap().data.user_keys.clear();
1328 assert_locked(
1329 &skm,
1330 &mut keystore_db,
1331 &legacy_importer,
1332 USER_ID,
1333 "Clearing the cache did not lock the user!",
1334 );
1335
1336 assert!(skm
1337 .write()
1338 .unwrap()
1339 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &wrong_pw)
1340 .is_err());
1341 assert_locked(
1342 &skm,
1343 &mut keystore_db,
1344 &legacy_importer,
1345 USER_ID,
1346 "The user was unlocked with an incorrect password!",
1347 );
1348 }
1349
1350 #[test]
1351 fn test_unlock_user_idempotent() {
1352 let pw: Password = generate_password_blob();
1353 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1354 assert_unlocked(
1355 &skm,
1356 &mut keystore_db,
1357 &legacy_importer,
1358 USER_ID,
1359 "The user was not unlocked after initialization!",
1360 );
1361
1362 skm.write().unwrap().data.user_keys.clear();
1363 assert_locked(
1364 &skm,
1365 &mut keystore_db,
1366 &legacy_importer,
1367 USER_ID,
1368 "Clearing the cache did not lock the user!",
1369 );
1370
1371 for _ in 0..5 {
1372 assert!(skm
1373 .write()
1374 .unwrap()
1375 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1376 .is_ok());
1377 assert_unlocked(
1378 &skm,
1379 &mut keystore_db,
1380 &legacy_importer,
1381 USER_ID,
1382 "The user did not unlock!",
1383 );
1384 }
1385 }
1386
1387 fn test_user_removal(locked: bool) {
1388 let pw: Password = generate_password_blob();
1389 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1390 assert_unlocked(
1391 &skm,
1392 &mut keystore_db,
1393 &legacy_importer,
1394 USER_ID,
1395 "The user was not unlocked after initialization!",
1396 );
1397
1398 assert!(make_test_key_entry(
1399 &mut keystore_db,
1400 Domain::APP,
1401 USER_ID.into(),
1402 TEST_KEY_ALIAS,
1403 None
1404 )
1405 .is_ok());
1406 assert!(make_bootlevel_key_entry(
1407 &mut keystore_db,
1408 Domain::APP,
1409 USER_ID.into(),
1410 TEST_BOOT_KEY_ALIAS,
1411 false
1412 )
1413 .is_ok());
1414
1415 assert!(keystore_db
1416 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1417 .unwrap());
1418 assert!(keystore_db
1419 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1420 .unwrap());
1421
1422 if locked {
1423 skm.write().unwrap().data.user_keys.clear();
1424 assert_locked(
1425 &skm,
1426 &mut keystore_db,
1427 &legacy_importer,
1428 USER_ID,
1429 "Clearing the cache did not lock the user!",
1430 );
1431 }
1432
1433 assert!(skm
1434 .write()
1435 .unwrap()
1436 .remove_user(&mut keystore_db, &legacy_importer, USER_ID)
1437 .is_ok());
1438 assert_uninitialized(
1439 &skm,
1440 &mut keystore_db,
1441 &legacy_importer,
1442 USER_ID,
1443 "The user was not removed!",
1444 );
1445
1446 assert!(!skm
1447 .write()
1448 .unwrap()
1449 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1450 .unwrap());
1451
1452 assert!(!keystore_db
1453 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1454 .unwrap());
1455 assert!(!keystore_db
1456 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1457 .unwrap());
1458 }
1459
1460 fn test_user_reset(locked: bool) {
1461 let pw: Password = generate_password_blob();
1462 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1463 assert_unlocked(
1464 &skm,
1465 &mut keystore_db,
1466 &legacy_importer,
1467 USER_ID,
1468 "The user was not unlocked after initialization!",
1469 );
1470
1471 assert!(make_test_key_entry(
1472 &mut keystore_db,
1473 Domain::APP,
1474 USER_ID.into(),
1475 TEST_KEY_ALIAS,
1476 None
1477 )
1478 .is_ok());
1479 assert!(make_bootlevel_key_entry(
1480 &mut keystore_db,
1481 Domain::APP,
1482 USER_ID.into(),
1483 TEST_BOOT_KEY_ALIAS,
1484 false
1485 )
1486 .is_ok());
1487 assert!(keystore_db
1488 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1489 .unwrap());
1490 assert!(keystore_db
1491 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1492 .unwrap());
1493
1494 if locked {
1495 skm.write().unwrap().data.user_keys.clear();
1496 assert_locked(
1497 &skm,
1498 &mut keystore_db,
1499 &legacy_importer,
1500 USER_ID,
1501 "Clearing the cache did not lock the user!",
1502 );
1503 assert!(skm
1504 .write()
1505 .unwrap()
1506 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1507 .is_err());
1508 assert_locked(
1509 &skm,
1510 &mut keystore_db,
1511 &legacy_importer,
1512 USER_ID,
1513 "User state should not have changed!",
1514 );
1515
1516 // Keys should still exist.
1517 assert!(keystore_db
1518 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1519 .unwrap());
1520 assert!(keystore_db
1521 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1522 .unwrap());
1523 } else {
1524 assert!(skm
1525 .write()
1526 .unwrap()
1527 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1528 .is_ok());
1529 assert_uninitialized(
1530 &skm,
1531 &mut keystore_db,
1532 &legacy_importer,
1533 USER_ID,
1534 "The user was not reset!",
1535 );
1536 assert!(!skm
1537 .write()
1538 .unwrap()
1539 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1540 .unwrap());
1541
1542 // Auth bound key should no longer exist.
1543 assert!(!keystore_db
1544 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1545 .unwrap());
1546 assert!(keystore_db
1547 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1548 .unwrap());
1549 }
1550 }
1551
1552 #[test]
1553 fn test_remove_unlocked_user() {
1554 test_user_removal(false);
1555 }
1556
1557 #[test]
1558 fn test_remove_locked_user() {
1559 test_user_removal(true);
1560 }
1561
1562 #[test]
1563 fn test_reset_unlocked_user() {
1564 test_user_reset(false);
1565 }
1566
1567 #[test]
1568 fn test_reset_locked_user() {
1569 test_user_reset(true);
1570 }
1571}