blob: 57ea4523a9a0af16f421df261ab5f9fb9168866e [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
Eric Biggers673d34a2023-10-18 01:54:18 +000083/// The user's AfterFirstUnlock super key. This super key is loaded into memory when the user first
84/// unlocks the device, and it remains in memory until the device reboots. This is used to encrypt
85/// keys that require user authentication but not an unlocked device.
86pub const USER_AFTER_FIRST_UNLOCK_SUPER_KEY: SuperKeyType =
Paul Crowley8d5b2532021-03-19 10:53:07 -070087 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070088/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
89/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070090/// Symmetric.
91pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
92 alias: "USER_SCREEN_LOCK_BOUND_KEY",
93 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
94};
95/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
96/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
97/// Asymmetric, so keys can be encrypted when the device is locked.
Paul Crowley52f017f2021-06-22 08:16:01 -070098pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
99 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
100 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700101};
Paul Crowley7a658392021-03-18 17:08:20 -0700102
103/// Superencryption to apply to a new key.
104#[derive(Debug, Clone, Copy)]
105pub enum SuperEncryptionType {
106 /// Do not superencrypt this key.
107 None,
Eric Biggers673d34a2023-10-18 01:54:18 +0000108 /// Superencrypt with the AfterFirstUnlock super key.
109 AfterFirstUnlock,
Paul Crowley7a658392021-03-18 17:08:20 -0700110 /// Superencrypt with a key cleared from memory when the device is locked.
111 ScreenLockBound,
Paul Crowley44c02da2021-04-08 17:04:43 +0000112 /// Superencrypt with a key based on the desired boot level
113 BootLevel(i32),
114}
115
116#[derive(Debug, Clone, Copy)]
117pub enum SuperKeyIdentifier {
118 /// id of the super key in the database.
119 DatabaseId(i64),
120 /// Boot level of the encrypting boot level key
121 BootLevel(i32),
122}
123
124impl SuperKeyIdentifier {
125 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
126 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
127 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000128 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700129 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000130 }
131 }
132
133 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
134 match self {
135 SuperKeyIdentifier::DatabaseId(id) => {
136 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
137 }
138 SuperKeyIdentifier::BootLevel(level) => {
139 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
140 }
141 }
142 }
Paul Crowley7a658392021-03-18 17:08:20 -0700143}
144
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000145pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700146 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700147 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000148 /// Identifier of the encrypting key, used to write an encrypted blob
149 /// back to the database after re-encryption eg on a key update.
150 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700151 /// ECDH is more expensive than AES. So on ECDH private keys we set the
152 /// reencrypt_with field to point at the corresponding AES key, and the
153 /// keys will be re-encrypted with AES on first use.
154 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000155}
156
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800157impl AesGcm for SuperKey {
158 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700159 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000160 aes_gcm_decrypt(data, iv, tag, &self.key).context(ks_err!("Decryption failed."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700161 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000162 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800163 }
164 }
165
166 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
167 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000168 aes_gcm_encrypt(plaintext, &self.key).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800169 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000170 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700171 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000172 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700173}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000174
Paul Crowley618869e2021-04-08 20:30:54 -0700175/// A SuperKey that has been encrypted with an AES-GCM key. For
176/// encryption the key is in memory, and for decryption it is in KM.
177struct LockedKey {
178 algorithm: SuperEncryptionAlgorithm,
179 id: SuperKeyIdentifier,
180 nonce: Vec<u8>,
181 ciphertext: Vec<u8>, // with tag appended
182}
183
184impl LockedKey {
185 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
186 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
187 ciphertext.append(&mut tag);
188 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
189 }
190
191 fn decrypt(
192 &self,
193 db: &mut KeystoreDB,
194 km_dev: &KeyMintDevice,
195 key_id_guard: &KeyIdGuard,
196 key_entry: &KeyEntry,
197 auth_token: &HardwareAuthToken,
198 reencrypt_with: Option<Arc<SuperKey>>,
199 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700200 let key_blob = key_entry
201 .key_blob_info()
202 .as_ref()
203 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
204 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000205 .context(ks_err!("Missing key blob info."))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700206 let key_params = vec![
207 KeyParameterValue::Algorithm(Algorithm::AES),
208 KeyParameterValue::KeySize(256),
209 KeyParameterValue::BlockMode(BlockMode::GCM),
210 KeyParameterValue::PaddingMode(PaddingMode::NONE),
211 KeyParameterValue::Nonce(self.nonce.clone()),
212 KeyParameterValue::MacLength(128),
213 ];
214 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
215 let key = ZVec::try_from(km_dev.use_key_in_one_step(
216 db,
217 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700218 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700219 KeyPurpose::DECRYPT,
220 &key_params,
221 Some(auth_token),
222 &self.ciphertext,
223 )?)?;
224 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
225 }
226}
227
228/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
229/// a database descriptor for the encrypting key and the sids for the auth tokens
230/// that can be used to decrypt it.
231struct BiometricUnlock {
232 /// List of auth token SIDs that can be used to unlock these keys.
233 sids: Vec<i64>,
234 /// Database descriptor of key to use to unlock.
235 key_desc: KeyDescriptor,
236 /// Locked versions of the matching UserSuperKeys fields
237 screen_lock_bound: LockedKey,
238 screen_lock_bound_private: LockedKey,
239}
240
Paul Crowleye8826e52021-03-31 08:33:53 -0700241#[derive(Default)]
242struct UserSuperKeys {
Eric Biggers673d34a2023-10-18 01:54:18 +0000243 /// The AfterFirstUnlock super key is used for LSKF binding of authentication bound keys. There
244 /// is one key per android user. The key is stored on flash encrypted with a key derived from a
245 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF). When the
246 /// user unlocks the device for the first time, this key is unlocked, i.e., decrypted, and stays
247 /// memory resident until the device reboots.
248 after_first_unlock: Option<Arc<SuperKey>>,
Paul Crowleye8826e52021-03-31 08:33:53 -0700249 /// The screen lock key works like the per boot key with the distinction that it is cleared
250 /// from memory when the screen lock is engaged.
251 screen_lock_bound: Option<Arc<SuperKey>>,
252 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
253 /// ECDH public-key encryption. This field holds the decryption private key.
254 screen_lock_bound_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700255 /// Versions of the above two keys, locked behind a biometric.
256 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000257}
258
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800259#[derive(Default)]
260struct SkmState {
261 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700262 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800263 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700264}
265
266impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000267 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
268 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
269 self.key_index.insert(id, Arc::downgrade(super_key));
270 Ok(())
271 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000272 Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000273 }
Paul Crowley7a658392021-03-18 17:08:20 -0700274 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800275}
276
277#[derive(Default)]
278pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800279 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800280}
281
282impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800283 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
284 let mut skm_guard = skm.write().unwrap();
285 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000286 log::info!("In set_up_boot_level_cache: called for a second time");
287 return Ok(());
288 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000289 let level_zero_key =
290 get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800291 skm_guard.data.boot_level_key_cache =
292 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000293 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800294 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000295 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800296 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000297 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
298 });
299 Ok(())
300 }
301
302 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
303 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800304 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000305 let mut w = PropertyWatcher::new("keystore.boot_level")
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000306 .context(ks_err!("PropertyWatcher::new failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000307 loop {
308 let level = w
309 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000310 .context(ks_err!("read of property failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800311
312 // This scope limits the skm_guard life, so we don't hold the skm_guard while
313 // waiting.
314 {
315 let mut skm_guard = skm.write().unwrap();
316 let boot_level_key_cache = skm_guard
317 .data
318 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000319 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800320 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000321 .context(ks_err!("Boot level cache not initialized"))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800322 .get_mut()
323 .unwrap();
324 if level < MAX_MAX_BOOT_LEVEL {
325 log::info!("Read keystore.boot_level value {}", level);
326 boot_level_key_cache
327 .advance_boot_level(level)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000328 .context(ks_err!("advance_boot_level failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800329 } else {
330 log::info!(
331 "keystore.boot_level {} hits maximum {}, finishing.",
332 level,
333 MAX_MAX_BOOT_LEVEL
334 );
335 boot_level_key_cache.finish();
336 break;
337 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000338 }
Andrew Walbran48fa9702023-05-10 15:19:30 +0000339 w.wait(None).context(ks_err!("property wait failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000340 }
341 Ok(())
342 }
343
344 pub fn level_accessible(&self, boot_level: i32) -> bool {
345 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000346 .boot_level_key_cache
347 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800348 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000349 }
350
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800351 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
352 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800353 }
354
Eric Biggers673d34a2023-10-18 01:54:18 +0000355 fn install_after_first_unlock_key_for_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800356 &mut self,
357 user: UserId,
358 super_key: Arc<SuperKey>,
359 ) -> Result<()> {
360 self.data
361 .add_key_to_key_index(&super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000362 .context(ks_err!("add_key_to_key_index failed"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000363 self.data.user_keys.entry(user).or_default().after_first_unlock = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000364 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800365 }
366
Paul Crowley44c02da2021-04-08 17:04:43 +0000367 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000368 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800369 SuperKeyIdentifier::DatabaseId(id) => {
370 self.data.key_index.get(id).and_then(|k| k.upgrade())
371 }
372 SuperKeyIdentifier::BootLevel(level) => self
373 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000374 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800375 .as_ref()
376 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000377 .transpose()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000378 .context(ks_err!("aes_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000379 .flatten()
380 .map(|key| {
381 Arc::new(SuperKey {
382 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
383 key,
384 id: *key_id,
385 reencrypt_with: None,
386 })
387 }),
388 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800389 }
390
Eric Biggers673d34a2023-10-18 01:54:18 +0000391 /// Returns the AfterFirstUnlock superencryption key for the given user ID, or None if the user
392 /// has not yet unlocked the device since boot.
393 pub fn get_after_first_unlock_key_by_user_id(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800394 &self,
395 user_id: UserId,
396 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
Eric Biggers673d34a2023-10-18 01:54:18 +0000397 self.get_after_first_unlock_key_by_user_id_internal(user_id)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800398 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
399 }
400
Eric Biggers673d34a2023-10-18 01:54:18 +0000401 fn get_after_first_unlock_key_by_user_id_internal(
402 &self,
403 user_id: UserId,
404 ) -> Option<Arc<SuperKey>> {
405 self.data.user_keys.get(&user_id).and_then(|e| e.after_first_unlock.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800406 }
407
Paul Crowley44c02da2021-04-08 17:04:43 +0000408 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
409 /// the relevant super key.
410 pub fn unwrap_key_if_required<'a>(
411 &self,
412 metadata: &BlobMetaData,
413 blob: &'a [u8],
414 ) -> Result<KeyBlob<'a>> {
415 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
416 let super_key = self
417 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000418 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000419 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000420 .context(ks_err!("Required super decryption key is not in memory."))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000421 KeyBlob::Sensitive {
422 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000423 .context(ks_err!("unwrap_key_with_key failed"))?,
Paul Crowley44c02da2021-04-08 17:04:43 +0000424 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
425 force_reencrypt: super_key.reencrypt_with.is_some(),
426 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700427 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000428 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700429 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800430 }
431
432 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700433 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700434 match key.algorithm {
435 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000436 (Some(iv), Some(tag)) => {
437 key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
438 }
439 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
440 "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700441 iv.is_some(),
442 tag.is_some(),
443 )),
444 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700445 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700446 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
447 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
448 ECDHPrivateKey::from_private_key(&key.key)
449 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000450 .context(ks_err!("Failed to decrypt the key blob with ECDH."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700451 }
452 (public_key, salt, iv, aead_tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000453 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700454 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000455 "Key has incomplete metadata. ",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700456 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
457 ),
458 public_key.is_some(),
459 salt.is_some(),
460 iv.is_some(),
461 aead_tag.is_some(),
462 ))
463 }
464 }
465 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800466 }
467 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000468
469 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800470 /// The reference to self is unused but it is required to prevent calling this function
471 /// concurrently with skm state database changes.
472 fn super_key_exists_in_db_for_user(
473 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000474 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800475 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700476 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000477 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000478 let key_in_db = db
Eric Biggers673d34a2023-10-18 01:54:18 +0000479 .key_exists(
480 Domain::APP,
481 user_id as u64 as i64,
482 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
483 KeyType::Super,
484 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000485 .context(ks_err!())?;
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000486
487 if key_in_db {
488 Ok(key_in_db)
489 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000490 legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000491 }
492 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000493
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800494 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000495 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800496 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700497 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700498 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000499 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700500 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700501 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700502 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000503 .context(ks_err!("Failed to extract super key from key entry"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000504 self.install_after_first_unlock_key_for_user(user_id, super_key.clone())
505 .context(ks_err!("Failed to install AfterFirstUnlock super key for user!"))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000506 Ok(super_key)
507 }
508
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800509 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700510 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700511 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700512 entry: KeyEntry,
513 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700514 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700515 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000516 if let Some((blob, metadata)) = entry.key_blob_info() {
517 let key = match (
518 metadata.encrypted_by(),
519 metadata.salt(),
520 metadata.iv(),
521 metadata.aead_tag(),
522 ) {
523 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800524 // Note that password encryption is AES no matter the value of algorithm.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000525 let key = pw
526 .derive_key(salt, AES_256_KEY_LENGTH)
527 .context(ks_err!("Failed to generate key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000528
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000529 aes_gcm_decrypt(blob, iv, tag, &key)
530 .context(ks_err!("Failed to decrypt key blob."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +0000531 }
532 (enc_by, salt, iv, tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000533 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Hasini Gunasingheda895552021-01-27 19:34:37 +0000534 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000535 "Super key has incomplete metadata.",
536 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
537 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700538 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000539 salt.is_some(),
540 iv.is_some(),
541 tag.is_some()
542 ));
543 }
544 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000545 Ok(Arc::new(SuperKey {
546 algorithm,
547 key,
548 id: SuperKeyIdentifier::DatabaseId(entry.id()),
549 reencrypt_with,
550 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000551 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000552 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000553 }
554 }
555
556 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700557 pub fn encrypt_with_password(
558 super_key: &[u8],
559 pw: &Password,
560 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000561 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700562 let derived_key = pw
David Drysdale6a0ec2c2022-04-19 08:11:18 +0100563 .derive_key(&salt, AES_256_KEY_LENGTH)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000564 .context(ks_err!("Failed to derive password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000565 let mut metadata = BlobMetaData::new();
566 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
567 metadata.add(BlobMetaEntry::Salt(salt));
568 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000569 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000570 metadata.add(BlobMetaEntry::Iv(iv));
571 metadata.add(BlobMetaEntry::AeadTag(tag));
572 Ok((encrypted_key, metadata))
573 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000574
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800575 // Helper function to encrypt a key with the given super key. Callers should select which super
576 // key to be used. This is called when a key is super encrypted at its creation as well as at
577 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700578 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000579 key_blob: &[u8],
580 super_key: &SuperKey,
581 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700582 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000583 return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
Paul Crowley8d5b2532021-03-19 10:53:07 -0700584 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000585 let mut metadata = BlobMetaData::new();
586 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000587 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000588 metadata.add(BlobMetaEntry::Iv(iv));
589 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000590 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000591 Ok((encrypted_key, metadata))
592 }
593
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000594 // Encrypts a given key_blob using a hybrid approach, which can either use the symmetric super
595 // key or the public super key depending on which is available.
596 //
597 // If the symmetric_key is available, the key_blob is encrypted using symmetric encryption with
598 // the provided symmetric super key. Otherwise, the function loads the public super key from
599 // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be
600 // re-encrypted with the symmetric super key on the first use.
601 //
602 // This hybrid scheme allows lock-screen-bound keys to be added when the screen is locked.
603 fn encrypt_with_hybrid_super_key(
604 key_blob: &[u8],
605 symmetric_key: Option<&SuperKey>,
606 public_key_type: &SuperKeyType,
607 db: &mut KeystoreDB,
608 user_id: UserId,
609 ) -> Result<(Vec<u8>, BlobMetaData)> {
610 if let Some(super_key) = symmetric_key {
611 Self::encrypt_with_aes_super_key(key_blob, super_key)
612 .context(ks_err!("Failed to encrypt with ScreenLockBound super key."))
613 } else {
614 // Symmetric key is not available, use public key encryption
615 let loaded = db
616 .load_super_key(public_key_type, user_id)
617 .context(ks_err!("load_super_key failed."))?;
618 let (key_id_guard, key_entry) =
619 loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH super key missing."))?;
620 let public_key = key_entry
621 .metadata()
622 .sec1_public_key()
623 .ok_or_else(Error::sys)
624 .context(ks_err!("sec1_public_key missing."))?;
625 let mut metadata = BlobMetaData::new();
626 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
627 ECDHPrivateKey::encrypt_message(public_key, key_blob)
628 .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
629 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
630 metadata.add(BlobMetaEntry::Salt(salt));
631 metadata.add(BlobMetaEntry::Iv(iv));
632 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
633 SuperKeyIdentifier::DatabaseId(key_id_guard.id()).add_to_metadata(&mut metadata);
634 Ok((encrypted_key, metadata))
635 }
636 }
637
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000638 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
639 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700640 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000641 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000642 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000643 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800644 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000645 domain: &Domain,
646 key_parameters: &[KeyParameter],
647 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700648 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000649 key_blob: &[u8],
650 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700651 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
652 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Eric Biggers673d34a2023-10-18 01:54:18 +0000653 SuperEncryptionType::AfterFirstUnlock => {
654 // Encrypt the given key blob with the user's AfterFirstUnlock super key. If the
655 // user has not unlocked the device since boot or has no LSKF, an error is returned.
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000656 match self
657 .get_user_state(db, legacy_importer, user_id)
David Drysdalee85523f2023-06-19 12:28:53 +0100658 .context(ks_err!("Failed to get user state for user {user_id}"))?
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000659 {
Eric Biggers673d34a2023-10-18 01:54:18 +0000660 UserState::AfterFirstUnlock(super_key) => {
661 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(ks_err!(
662 "Failed to encrypt with AfterFirstUnlock super key for user {user_id}"
663 ))
664 }
Eric Biggers13869372023-10-18 01:54:18 +0000665 UserState::BeforeFirstUnlock => {
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000666 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
667 }
668 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
David Drysdalee85523f2023-06-19 12:28:53 +0100669 .context(ks_err!("LSKF is not setup for user {user_id}")),
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000670 }
671 }
Paul Crowley7a658392021-03-18 17:08:20 -0700672 SuperEncryptionType::ScreenLockBound => {
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000673 let screen_lock_bound_symmetric_key = self
674 .data
675 .user_keys
676 .get(&user_id)
677 .and_then(|e| e.screen_lock_bound.as_ref())
678 .map(|arc| arc.as_ref());
679 Self::encrypt_with_hybrid_super_key(
680 key_blob,
681 screen_lock_bound_symmetric_key,
682 &USER_SCREEN_LOCK_BOUND_P521_KEY,
683 db,
684 user_id,
685 )
686 .context(ks_err!("Failed to encrypt with ScreenLockBound hybrid scheme."))
Paul Crowley7a658392021-03-18 17:08:20 -0700687 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000688 SuperEncryptionType::BootLevel(level) => {
689 let key_id = SuperKeyIdentifier::BootLevel(level);
690 let super_key = self
691 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000692 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000693 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000694 .context(ks_err!("Boot stage key absent"))?;
695 Self::encrypt_with_aes_super_key(key_blob, &super_key)
696 .context(ks_err!("Failed to encrypt with BootLevel key."))
Paul Crowley44c02da2021-04-08 17:04:43 +0000697 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000698 }
699 }
700
701 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
702 /// If so, re-super-encrypt the key and return a new set of metadata,
703 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700704 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000705 key_blob_before_upgrade: &KeyBlob,
706 key_after_upgrade: &'a [u8],
707 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
708 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700709 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700710 let (key, metadata) =
711 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000712 .context(ks_err!("Failed to re-super-encrypt key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000713 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
714 }
715 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
716 }
717 }
718
Paul Crowley7a658392021-03-18 17:08:20 -0700719 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
720 /// When this is called, the caller must hold the lock on the SuperKeyManager.
721 /// So it's OK that the check and creation are different DB transactions.
722 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800723 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700724 db: &mut KeystoreDB,
725 user_id: UserId,
726 key_type: &SuperKeyType,
727 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700728 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700729 ) -> Result<Arc<SuperKey>> {
730 let loaded_key = db.load_super_key(key_type, user_id)?;
731 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700732 Ok(Self::extract_super_key_from_key_entry(
733 key_type.algorithm,
734 key_entry,
735 password,
736 reencrypt_with,
737 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700738 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700739 let (super_key, public_key) = match key_type.algorithm {
740 SuperEncryptionAlgorithm::Aes256Gcm => (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000741 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700742 None,
743 ),
Paul Crowley52f017f2021-06-22 08:16:01 -0700744 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700745 let key = ECDHPrivateKey::generate()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000746 .context(ks_err!("Failed to generate ECDH key"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700747 (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000748 key.private_key().context(ks_err!("private_key failed"))?,
749 Some(key.public_key().context(ks_err!("public_key failed"))?),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700750 )
751 }
752 };
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800753 // Derive an AES256 key from the password and re-encrypt the super key
754 // before we insert it in the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700755 let (encrypted_super_key, blob_metadata) =
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000756 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700757 let mut key_metadata = KeyMetaData::new();
758 if let Some(pk) = public_key {
759 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
760 }
Paul Crowley7a658392021-03-18 17:08:20 -0700761 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700762 .store_super_key(
763 user_id,
764 key_type,
765 &encrypted_super_key,
766 &blob_metadata,
767 &key_metadata,
768 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000769 .context(ks_err!("Failed to store super key."))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700770 Ok(Arc::new(SuperKey {
771 algorithm: key_type.algorithm,
772 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000773 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700774 reencrypt_with,
775 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700776 }
777 }
778
Paul Crowley8d5b2532021-03-19 10:53:07 -0700779 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700780 pub fn unlock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800781 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700782 db: &mut KeystoreDB,
783 user_id: UserId,
784 password: &Password,
785 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800786 let (screen_lock_bound, screen_lock_bound_private) = self
787 .data
788 .user_keys
789 .get(&user_id)
790 .map(|e| (e.screen_lock_bound.clone(), e.screen_lock_bound_private.clone()))
791 .unwrap_or((None, None));
792
793 if screen_lock_bound.is_some() && screen_lock_bound_private.is_some() {
794 // Already unlocked.
795 return Ok(());
796 }
797
798 let aes = if let Some(screen_lock_bound) = screen_lock_bound {
799 // This is weird. If this point is reached only one of the screen locked keys was
800 // initialized. This should never happen.
801 screen_lock_bound
802 } else {
803 self.get_or_create_super_key(db, user_id, &USER_SCREEN_LOCK_BOUND_KEY, password, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000804 .context(ks_err!("Trying to get or create symmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800805 };
806
807 let ecdh = if let Some(screen_lock_bound_private) = screen_lock_bound_private {
808 // This is weird. If this point is reached only one of the screen locked keys was
809 // initialized. This should never happen.
810 screen_lock_bound_private
811 } else {
812 self.get_or_create_super_key(
813 db,
814 user_id,
815 &USER_SCREEN_LOCK_BOUND_P521_KEY,
816 password,
817 Some(aes.clone()),
818 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000819 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800820 };
821
822 self.data.add_key_to_key_index(&aes)?;
823 self.data.add_key_to_key_index(&ecdh)?;
824 let entry = self.data.user_keys.entry(user_id).or_default();
825 entry.screen_lock_bound = Some(aes);
826 entry.screen_lock_bound_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700827 Ok(())
828 }
829
Paul Crowley8d5b2532021-03-19 10:53:07 -0700830 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley618869e2021-04-08 20:30:54 -0700831 pub fn lock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800832 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700833 db: &mut KeystoreDB,
834 user_id: UserId,
835 unlocking_sids: &[i64],
836 ) {
837 log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
Chris Wailes53a22af2023-07-12 17:02:47 -0700838 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700839 if !unlocking_sids.is_empty() {
840 if let (Some(aes), Some(ecdh)) = (
841 entry.screen_lock_bound.as_ref().cloned(),
842 entry.screen_lock_bound_private.as_ref().cloned(),
843 ) {
844 let res = (|| -> Result<()> {
845 let key_desc = KeyMintDevice::internal_descriptor(format!(
846 "biometric_unlock_key_{}",
847 user_id
848 ));
849 let encrypting_key = generate_aes256_key()?;
850 let km_dev: KeyMintDevice =
851 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000852 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700853 let mut key_params = vec![
854 KeyParameterValue::Algorithm(Algorithm::AES),
855 KeyParameterValue::KeySize(256),
856 KeyParameterValue::BlockMode(BlockMode::GCM),
857 KeyParameterValue::PaddingMode(PaddingMode::NONE),
858 KeyParameterValue::CallerNonce,
859 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
860 KeyParameterValue::MinMacLength(128),
861 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
862 KeyParameterValue::HardwareAuthenticatorType(
863 HardwareAuthenticatorType::FINGERPRINT,
864 ),
865 ];
866 for sid in unlocking_sids {
867 key_params.push(KeyParameterValue::UserSecureID(*sid));
868 }
869 let key_params: Vec<KmKeyParameter> =
870 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700871 km_dev.create_and_store_key(
872 db,
873 &key_desc,
874 KeyType::Client, /* TODO Should be Super b/189470584 */
875 |dev| {
876 let _wp = wd::watch_millis(
877 "In lock_screen_lock_bound_key: calling importKey.",
878 500,
879 );
880 dev.importKey(
881 key_params.as_slice(),
882 KeyFormat::RAW,
883 &encrypting_key,
884 None,
885 )
886 },
887 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700888 entry.biometric_unlock = Some(BiometricUnlock {
889 sids: unlocking_sids.into(),
890 key_desc,
891 screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
892 screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
893 });
894 Ok(())
895 })();
896 // There is no reason to propagate an error here upwards. We must discard
897 // entry.screen_lock_bound* in any case.
898 if let Err(e) = res {
899 log::error!("Error setting up biometric unlock: {:#?}", e);
900 }
901 }
902 }
Paul Crowley7a658392021-03-18 17:08:20 -0700903 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700904 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700905 }
Paul Crowley618869e2021-04-08 20:30:54 -0700906
907 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
908 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
909 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800910 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700911 db: &mut KeystoreDB,
912 user_id: UserId,
913 ) -> Result<()> {
Chris Wailes53a22af2023-07-12 17:02:47 -0700914 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700915 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700916 let (key_id_guard, key_entry) = db
917 .load_key_entry(
918 &biometric.key_desc,
919 KeyType::Client, // This should not be a Client key.
920 KeyEntryLoadBits::KM,
921 AID_KEYSTORE,
922 |_, _| Ok(()),
923 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000924 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700925 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000926 .context(ks_err!("KeyMintDevice::get failed"))?;
David Drysdalee85523f2023-06-19 12:28:53 +0100927 let mut errs = vec![];
Paul Crowley618869e2021-04-08 20:30:54 -0700928 for sid in &biometric.sids {
David Drysdalee85523f2023-06-19 12:28:53 +0100929 let sid = *sid;
Paul Crowley618869e2021-04-08 20:30:54 -0700930 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
David Drysdalee85523f2023-06-19 12:28:53 +0100931 entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700932 }) {
Paul Crowley618869e2021-04-08 20:30:54 -0700933 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
934 let slb = biometric.screen_lock_bound.decrypt(
935 db,
936 &km_dev,
937 &key_id_guard,
938 &key_entry,
939 auth_token_entry.auth_token(),
940 None,
941 )?;
942 let slbp = biometric.screen_lock_bound_private.decrypt(
943 db,
944 &km_dev,
945 &key_id_guard,
946 &key_entry,
947 auth_token_entry.auth_token(),
948 Some(slb.clone()),
949 )?;
950 Ok((slb, slbp))
951 })();
952 match res {
953 Ok((slb, slbp)) => {
954 entry.screen_lock_bound = Some(slb.clone());
955 entry.screen_lock_bound_private = Some(slbp.clone());
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800956 self.data.add_key_to_key_index(&slb)?;
957 self.data.add_key_to_key_index(&slbp)?;
David Drysdalee85523f2023-06-19 12:28:53 +0100958 log::info!("Successfully unlocked user {user_id} with biometric {sid}",);
Paul Crowley618869e2021-04-08 20:30:54 -0700959 return Ok(());
960 }
961 Err(e) => {
David Drysdalee85523f2023-06-19 12:28:53 +0100962 // Don't log an error yet, as some other biometric SID might work.
963 errs.push((sid, e));
Paul Crowley618869e2021-04-08 20:30:54 -0700964 }
965 }
966 }
967 }
David Drysdalee85523f2023-06-19 12:28:53 +0100968 if !errs.is_empty() {
969 log::warn!("biometric unlock failed for all SIDs, with errors:");
970 for (sid, err) in errs {
971 log::warn!(" biometric {sid}: {err}");
972 }
973 }
Paul Crowley618869e2021-04-08 20:30:54 -0700974 }
975 Ok(())
976 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800977
978 /// Returns the keystore locked state of the given user. It requires the thread local
979 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800980 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800981 pub fn get_user_state(
982 &self,
983 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800984 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800985 user_id: UserId,
986 ) -> Result<UserState> {
Eric Biggers673d34a2023-10-18 01:54:18 +0000987 match self.get_after_first_unlock_key_by_user_id_internal(user_id) {
Eric Biggers13869372023-10-18 01:54:18 +0000988 Some(super_key) => Ok(UserState::AfterFirstUnlock(super_key)),
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800989 None => {
990 // Check if a super key exists in the database or legacy database.
991 // If so, return locked user state.
992 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800993 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000994 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800995 {
Eric Biggers13869372023-10-18 01:54:18 +0000996 Ok(UserState::BeforeFirstUnlock)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800997 } else {
998 Ok(UserState::Uninitialized)
999 }
1000 }
1001 }
1002 }
1003
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001004 /// Deletes all keys and super keys for the given user.
1005 /// This is called when a user is deleted.
1006 pub fn remove_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001007 &mut self,
1008 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001009 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001010 user_id: UserId,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001011 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001012 log::info!("remove_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001013 // Mark keys created on behalf of the user as unreferenced.
1014 legacy_importer
1015 .bulk_delete_user(user_id, false)
1016 .context(ks_err!("Trying to delete legacy keys."))?;
1017 db.unbind_keys_for_user(user_id, false).context(ks_err!("Error in unbinding keys."))?;
1018
1019 // Delete super key in cache, if exists.
1020 self.forget_all_keys_for_user(user_id);
1021 Ok(())
1022 }
1023
1024 /// Deletes all authentication bound keys and super keys for the given user. The user must be
1025 /// unlocked before this function is called. This function is used to transition a user to
1026 /// swipe.
1027 pub fn reset_user(
1028 &mut self,
1029 db: &mut KeystoreDB,
1030 legacy_importer: &LegacyImporter,
1031 user_id: UserId,
1032 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001033 log::info!("reset_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001034 match self.get_user_state(db, legacy_importer, user_id)? {
1035 UserState::Uninitialized => {
1036 Err(Error::sys()).context(ks_err!("Tried to reset an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001037 }
Eric Biggers13869372023-10-18 01:54:18 +00001038 UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001039 Err(Error::sys()).context(ks_err!("Tried to reset a locked user's password!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001040 }
Eric Biggers13869372023-10-18 01:54:18 +00001041 UserState::AfterFirstUnlock(_) => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001042 // Mark keys created on behalf of the user as unreferenced.
1043 legacy_importer
1044 .bulk_delete_user(user_id, true)
1045 .context(ks_err!("Trying to delete legacy keys."))?;
1046 db.unbind_keys_for_user(user_id, true)
1047 .context(ks_err!("Error in unbinding keys."))?;
1048
1049 // Delete super key in cache, if exists.
1050 self.forget_all_keys_for_user(user_id);
1051 Ok(())
1052 }
1053 }
1054 }
1055
Eric Biggers673d34a2023-10-18 01:54:18 +00001056 /// If the user hasn't been initialized yet, then this function generates the user's
1057 /// AfterFirstUnlock super key and sets the user's state to AfterFirstUnlock. Otherwise this
1058 /// function returns an error.
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001059 pub fn init_user(
1060 &mut self,
1061 db: &mut KeystoreDB,
1062 legacy_importer: &LegacyImporter,
1063 user_id: UserId,
1064 password: &Password,
1065 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001066 log::info!("init_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001067 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001068 UserState::AfterFirstUnlock(_) | UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001069 Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"))
1070 }
1071 UserState::Uninitialized => {
1072 // Generate a new super key.
1073 let super_key =
1074 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
1075 // Derive an AES256 key from the password and re-encrypt the super key
1076 // before we insert it in the database.
1077 let (encrypted_super_key, blob_metadata) =
1078 Self::encrypt_with_password(&super_key, password)
1079 .context(ks_err!("Failed to encrypt super key with password!"))?;
1080
1081 let key_entry = db
1082 .store_super_key(
1083 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001084 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001085 &encrypted_super_key,
1086 &blob_metadata,
1087 &KeyMetaData::new(),
1088 )
1089 .context(ks_err!("Failed to store super key."))?;
1090
1091 self.populate_cache_from_super_key_blob(
1092 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001093 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001094 key_entry,
1095 password,
1096 )
1097 .context(ks_err!("Failed to initialize user!"))?;
1098 Ok(())
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001099 }
1100 }
1101 }
1102
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001103 /// Unlocks the given user with the given password.
1104 ///
Eric Biggers13869372023-10-18 01:54:18 +00001105 /// If the user state is BeforeFirstUnlock:
Eric Biggers673d34a2023-10-18 01:54:18 +00001106 /// - Unlock the user's AfterFirstUnlock super key
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001107 /// - Unlock the screen_lock_bound super key
1108 ///
Eric Biggers13869372023-10-18 01:54:18 +00001109 /// If the user state is AfterFirstUnlock:
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001110 /// - Unlock the screen_lock_bound super key only
1111 ///
1112 pub fn unlock_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001113 &mut self,
1114 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001115 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001116 user_id: UserId,
1117 password: &Password,
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001118 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001119 log::info!("unlock_user(user={user_id})");
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001120 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001121 UserState::AfterFirstUnlock(_) => {
1122 self.unlock_screen_lock_bound_key(db, user_id, password)
1123 }
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001124 UserState::Uninitialized => {
1125 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001126 }
Eric Biggers13869372023-10-18 01:54:18 +00001127 UserState::BeforeFirstUnlock => {
Eric Biggers673d34a2023-10-18 01:54:18 +00001128 let alias = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001129 let result = legacy_importer
1130 .with_try_import_super_key(user_id, password, || {
1131 db.load_super_key(alias, user_id)
1132 })
1133 .context(ks_err!("Failed to load super key"))?;
1134
1135 match result {
1136 Some((_, entry)) => {
1137 self.populate_cache_from_super_key_blob(
1138 user_id,
1139 alias.algorithm,
1140 entry,
1141 password,
1142 )
1143 .context(ks_err!("Failed when unlocking user."))?;
1144 self.unlock_screen_lock_bound_key(db, user_id, password)
1145 }
1146 None => {
1147 Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))
1148 }
1149 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001150 }
1151 }
1152 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001153}
1154
1155/// This enum represents different states of the user's life cycle in the device.
1156/// For now, only three states are defined. More states may be added later.
1157pub enum UserState {
1158 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
Eric Biggers673d34a2023-10-18 01:54:18 +00001159 // and hence the AfterFirstUnlock super key is available in the cache.
Eric Biggers13869372023-10-18 01:54:18 +00001160 AfterFirstUnlock(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001161 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
Eric Biggers673d34a2023-10-18 01:54:18 +00001162 // Hence the AfterFirstUnlock and UnlockedDeviceRequired super keys are not available in the
1163 // cache. However, they exist in the database in encrypted form.
Eric Biggers13869372023-10-18 01:54:18 +00001164 BeforeFirstUnlock,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001165 // There's no user in the device for the given user id, or the user with the user id has not
1166 // setup LSKF.
1167 Uninitialized,
1168}
1169
Janis Danisevskiseed69842021-02-18 20:04:10 -08001170/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1171/// `Sensitive` holds the non encrypted key and a reference to its super key.
1172/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1173/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1174/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001175pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001176 Sensitive {
1177 key: ZVec,
1178 /// If KeyMint reports that the key must be upgraded, we must
1179 /// re-encrypt the key before writing to the database; we use
1180 /// this key.
1181 reencrypt_with: Arc<SuperKey>,
1182 /// If this key was decrypted with an ECDH key, we want to
1183 /// re-encrypt it on first use whether it was upgraded or not;
1184 /// this field indicates that that's necessary.
1185 force_reencrypt: bool,
1186 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001187 NonSensitive(Vec<u8>),
1188 Ref(&'a [u8]),
1189}
1190
Paul Crowley8d5b2532021-03-19 10:53:07 -07001191impl<'a> KeyBlob<'a> {
1192 pub fn force_reencrypt(&self) -> bool {
1193 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1194 *force_reencrypt
1195 } else {
1196 false
1197 }
1198 }
1199}
1200
Janis Danisevskiseed69842021-02-18 20:04:10 -08001201/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001202impl<'a> Deref for KeyBlob<'a> {
1203 type Target = [u8];
1204
1205 fn deref(&self) -> &Self::Target {
1206 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001207 Self::Sensitive { key, .. } => key,
1208 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001209 Self::Ref(key) => key,
1210 }
1211 }
1212}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001213
1214#[cfg(test)]
1215mod tests {
1216 use super::*;
1217 use crate::database::tests::make_bootlevel_key_entry;
1218 use crate::database::tests::make_test_key_entry;
1219 use crate::database::tests::new_test_db;
1220 use rand::prelude::*;
1221 const USER_ID: u32 = 0;
1222 const TEST_KEY_ALIAS: &str = "TEST_KEY";
1223 const TEST_BOOT_KEY_ALIAS: &str = "TEST_BOOT_KEY";
1224
1225 pub fn generate_password_blob() -> Password<'static> {
1226 let mut rng = rand::thread_rng();
1227 let mut password = vec![0u8; 64];
1228 rng.fill_bytes(&mut password);
1229
1230 let mut zvec = ZVec::new(64).expect("Failed to create ZVec");
1231 zvec[..].copy_from_slice(&password[..]);
1232
1233 Password::Owned(zvec)
1234 }
1235
1236 fn setup_test(pw: &Password) -> (Arc<RwLock<SuperKeyManager>>, KeystoreDB, LegacyImporter) {
1237 let mut keystore_db = new_test_db().unwrap();
1238 let mut legacy_importer = LegacyImporter::new(Arc::new(Default::default()));
1239 legacy_importer.set_empty();
1240 let skm: Arc<RwLock<SuperKeyManager>> = Default::default();
1241 assert!(skm
1242 .write()
1243 .unwrap()
1244 .init_user(&mut keystore_db, &legacy_importer, USER_ID, pw)
1245 .is_ok());
1246 (skm, keystore_db, legacy_importer)
1247 }
1248
1249 fn assert_unlocked(
1250 skm: &Arc<RwLock<SuperKeyManager>>,
1251 keystore_db: &mut KeystoreDB,
1252 legacy_importer: &LegacyImporter,
1253 user_id: u32,
1254 err_msg: &str,
1255 ) {
1256 let user_state =
1257 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1258 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001259 UserState::AfterFirstUnlock(_) => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001260 _ => panic!("{}", err_msg),
1261 }
1262 }
1263
1264 fn assert_locked(
1265 skm: &Arc<RwLock<SuperKeyManager>>,
1266 keystore_db: &mut KeystoreDB,
1267 legacy_importer: &LegacyImporter,
1268 user_id: u32,
1269 err_msg: &str,
1270 ) {
1271 let user_state =
1272 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1273 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001274 UserState::BeforeFirstUnlock => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001275 _ => panic!("{}", err_msg),
1276 }
1277 }
1278
1279 fn assert_uninitialized(
1280 skm: &Arc<RwLock<SuperKeyManager>>,
1281 keystore_db: &mut KeystoreDB,
1282 legacy_importer: &LegacyImporter,
1283 user_id: u32,
1284 err_msg: &str,
1285 ) {
1286 let user_state =
1287 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1288 match user_state {
1289 UserState::Uninitialized => {}
1290 _ => panic!("{}", err_msg),
1291 }
1292 }
1293
1294 #[test]
1295 fn test_init_user() {
1296 let pw: Password = generate_password_blob();
1297 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1298 assert_unlocked(
1299 &skm,
1300 &mut keystore_db,
1301 &legacy_importer,
1302 USER_ID,
1303 "The user was not unlocked after initialization!",
1304 );
1305 }
1306
1307 #[test]
1308 fn test_unlock_user() {
1309 let pw: Password = generate_password_blob();
1310 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1311 assert_unlocked(
1312 &skm,
1313 &mut keystore_db,
1314 &legacy_importer,
1315 USER_ID,
1316 "The user was not unlocked after initialization!",
1317 );
1318
1319 skm.write().unwrap().data.user_keys.clear();
1320 assert_locked(
1321 &skm,
1322 &mut keystore_db,
1323 &legacy_importer,
1324 USER_ID,
1325 "Clearing the cache did not lock the user!",
1326 );
1327
1328 assert!(skm
1329 .write()
1330 .unwrap()
1331 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1332 .is_ok());
1333 assert_unlocked(
1334 &skm,
1335 &mut keystore_db,
1336 &legacy_importer,
1337 USER_ID,
1338 "The user did not unlock!",
1339 );
1340 }
1341
1342 #[test]
1343 fn test_unlock_wrong_password() {
1344 let pw: Password = generate_password_blob();
1345 let wrong_pw: Password = generate_password_blob();
1346 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1347 assert_unlocked(
1348 &skm,
1349 &mut keystore_db,
1350 &legacy_importer,
1351 USER_ID,
1352 "The user was not unlocked after initialization!",
1353 );
1354
1355 skm.write().unwrap().data.user_keys.clear();
1356 assert_locked(
1357 &skm,
1358 &mut keystore_db,
1359 &legacy_importer,
1360 USER_ID,
1361 "Clearing the cache did not lock the user!",
1362 );
1363
1364 assert!(skm
1365 .write()
1366 .unwrap()
1367 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &wrong_pw)
1368 .is_err());
1369 assert_locked(
1370 &skm,
1371 &mut keystore_db,
1372 &legacy_importer,
1373 USER_ID,
1374 "The user was unlocked with an incorrect password!",
1375 );
1376 }
1377
1378 #[test]
1379 fn test_unlock_user_idempotent() {
1380 let pw: Password = generate_password_blob();
1381 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1382 assert_unlocked(
1383 &skm,
1384 &mut keystore_db,
1385 &legacy_importer,
1386 USER_ID,
1387 "The user was not unlocked after initialization!",
1388 );
1389
1390 skm.write().unwrap().data.user_keys.clear();
1391 assert_locked(
1392 &skm,
1393 &mut keystore_db,
1394 &legacy_importer,
1395 USER_ID,
1396 "Clearing the cache did not lock the user!",
1397 );
1398
1399 for _ in 0..5 {
1400 assert!(skm
1401 .write()
1402 .unwrap()
1403 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1404 .is_ok());
1405 assert_unlocked(
1406 &skm,
1407 &mut keystore_db,
1408 &legacy_importer,
1409 USER_ID,
1410 "The user did not unlock!",
1411 );
1412 }
1413 }
1414
1415 fn test_user_removal(locked: bool) {
1416 let pw: Password = generate_password_blob();
1417 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1418 assert_unlocked(
1419 &skm,
1420 &mut keystore_db,
1421 &legacy_importer,
1422 USER_ID,
1423 "The user was not unlocked after initialization!",
1424 );
1425
1426 assert!(make_test_key_entry(
1427 &mut keystore_db,
1428 Domain::APP,
1429 USER_ID.into(),
1430 TEST_KEY_ALIAS,
1431 None
1432 )
1433 .is_ok());
1434 assert!(make_bootlevel_key_entry(
1435 &mut keystore_db,
1436 Domain::APP,
1437 USER_ID.into(),
1438 TEST_BOOT_KEY_ALIAS,
1439 false
1440 )
1441 .is_ok());
1442
1443 assert!(keystore_db
1444 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1445 .unwrap());
1446 assert!(keystore_db
1447 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1448 .unwrap());
1449
1450 if locked {
1451 skm.write().unwrap().data.user_keys.clear();
1452 assert_locked(
1453 &skm,
1454 &mut keystore_db,
1455 &legacy_importer,
1456 USER_ID,
1457 "Clearing the cache did not lock the user!",
1458 );
1459 }
1460
1461 assert!(skm
1462 .write()
1463 .unwrap()
1464 .remove_user(&mut keystore_db, &legacy_importer, USER_ID)
1465 .is_ok());
1466 assert_uninitialized(
1467 &skm,
1468 &mut keystore_db,
1469 &legacy_importer,
1470 USER_ID,
1471 "The user was not removed!",
1472 );
1473
1474 assert!(!skm
1475 .write()
1476 .unwrap()
1477 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1478 .unwrap());
1479
1480 assert!(!keystore_db
1481 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1482 .unwrap());
1483 assert!(!keystore_db
1484 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1485 .unwrap());
1486 }
1487
1488 fn test_user_reset(locked: bool) {
1489 let pw: Password = generate_password_blob();
1490 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1491 assert_unlocked(
1492 &skm,
1493 &mut keystore_db,
1494 &legacy_importer,
1495 USER_ID,
1496 "The user was not unlocked after initialization!",
1497 );
1498
1499 assert!(make_test_key_entry(
1500 &mut keystore_db,
1501 Domain::APP,
1502 USER_ID.into(),
1503 TEST_KEY_ALIAS,
1504 None
1505 )
1506 .is_ok());
1507 assert!(make_bootlevel_key_entry(
1508 &mut keystore_db,
1509 Domain::APP,
1510 USER_ID.into(),
1511 TEST_BOOT_KEY_ALIAS,
1512 false
1513 )
1514 .is_ok());
1515 assert!(keystore_db
1516 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1517 .unwrap());
1518 assert!(keystore_db
1519 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1520 .unwrap());
1521
1522 if locked {
1523 skm.write().unwrap().data.user_keys.clear();
1524 assert_locked(
1525 &skm,
1526 &mut keystore_db,
1527 &legacy_importer,
1528 USER_ID,
1529 "Clearing the cache did not lock the user!",
1530 );
1531 assert!(skm
1532 .write()
1533 .unwrap()
1534 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1535 .is_err());
1536 assert_locked(
1537 &skm,
1538 &mut keystore_db,
1539 &legacy_importer,
1540 USER_ID,
1541 "User state should not have changed!",
1542 );
1543
1544 // Keys should still exist.
1545 assert!(keystore_db
1546 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1547 .unwrap());
1548 assert!(keystore_db
1549 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1550 .unwrap());
1551 } else {
1552 assert!(skm
1553 .write()
1554 .unwrap()
1555 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1556 .is_ok());
1557 assert_uninitialized(
1558 &skm,
1559 &mut keystore_db,
1560 &legacy_importer,
1561 USER_ID,
1562 "The user was not reset!",
1563 );
1564 assert!(!skm
1565 .write()
1566 .unwrap()
1567 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1568 .unwrap());
1569
1570 // Auth bound key should no longer exist.
1571 assert!(!keystore_db
1572 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1573 .unwrap());
1574 assert!(keystore_db
1575 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1576 .unwrap());
1577 }
1578 }
1579
1580 #[test]
1581 fn test_remove_unlocked_user() {
1582 test_user_removal(false);
1583 }
1584
1585 #[test]
1586 fn test_remove_locked_user() {
1587 test_user_removal(true);
1588 }
1589
1590 #[test]
1591 fn test_reset_unlocked_user() {
1592 test_user_reset(false);
1593 }
1594
1595 #[test]
1596 fn test_reset_locked_user() {
1597 test_user_reset(true);
1598 }
1599}