blob: 25dc25bfcc886edc439f5386d6e74fa06c40fc35 [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 };
Eric Biggersb1f641d2023-10-18 01:54:18 +000088/// The user's UnlockedDeviceRequired symmetric super key. This super key is loaded into memory each
89/// time the user unlocks the device, and it is cleared from memory each time the user locks the
90/// device. This is used to encrypt keys that use the UnlockedDeviceRequired key parameter.
91pub const USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY: SuperKeyType = SuperKeyType {
Paul Crowley8d5b2532021-03-19 10:53:07 -070092 alias: "USER_SCREEN_LOCK_BOUND_KEY",
93 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
94};
Eric Biggersb1f641d2023-10-18 01:54:18 +000095/// The user's UnlockedDeviceRequired asymmetric super key. This is used to allow, while the device
96/// is locked, the creation of keys that use the UnlockedDeviceRequired key parameter. The private
97/// part of this key is loaded and cleared when the symmetric key is loaded and cleared.
98pub const USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY: SuperKeyType = SuperKeyType {
Paul Crowley52f017f2021-06-22 08:16:01 -070099 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,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000110 /// Superencrypt with an UnlockedDeviceRequired super key.
111 UnlockedDeviceRequired,
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
Eric Biggersb1f641d2023-10-18 01:54:18 +0000228/// A user's UnlockedDeviceRequired super keys, encrypted with a biometric-bound key, and
229/// information about that biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700230struct BiometricUnlock {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000231 /// List of auth token SIDs that are accepted by the encrypting biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700232 sids: Vec<i64>,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000233 /// Key descriptor of the encrypting biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700234 key_desc: KeyDescriptor,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000235 /// The UnlockedDeviceRequired super keys, encrypted with a biometric-bound key.
236 symmetric: LockedKey,
237 private: LockedKey,
Paul Crowley618869e2021-04-08 20:30:54 -0700238}
239
Paul Crowleye8826e52021-03-31 08:33:53 -0700240#[derive(Default)]
241struct UserSuperKeys {
Eric Biggers673d34a2023-10-18 01:54:18 +0000242 /// The AfterFirstUnlock super key is used for LSKF binding of authentication bound keys. There
243 /// is one 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). When the
245 /// user unlocks the device for the first time, this key is unlocked, i.e., decrypted, and stays
246 /// memory resident until the device reboots.
247 after_first_unlock: Option<Arc<SuperKey>>,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000248 /// The UnlockedDeviceRequired symmetric super key works like the AfterFirstUnlock super key
249 /// with the distinction that it is cleared from memory when the device is locked.
250 unlocked_device_required_symmetric: Option<Arc<SuperKey>>,
251 /// When the device is locked, keys that use the UnlockedDeviceRequired key parameter can still
252 /// be created, using ECDH public-key encryption. This field holds the decryption private key.
253 unlocked_device_required_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
Eric Biggers673d34a2023-10-18 01:54:18 +0000354 fn install_after_first_unlock_key_for_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800355 &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"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000362 self.data.user_keys.entry(user).or_default().after_first_unlock = 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
Eric Biggers673d34a2023-10-18 01:54:18 +0000390 /// Returns the AfterFirstUnlock superencryption key for the given user ID, or None if the user
391 /// has not yet unlocked the device since boot.
392 pub fn get_after_first_unlock_key_by_user_id(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800393 &self,
394 user_id: UserId,
395 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
Eric Biggers673d34a2023-10-18 01:54:18 +0000396 self.get_after_first_unlock_key_by_user_id_internal(user_id)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800397 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
398 }
399
Eric Biggers673d34a2023-10-18 01:54:18 +0000400 fn get_after_first_unlock_key_by_user_id_internal(
401 &self,
402 user_id: UserId,
403 ) -> Option<Arc<SuperKey>> {
404 self.data.user_keys.get(&user_id).and_then(|e| e.after_first_unlock.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800405 }
406
Paul Crowley44c02da2021-04-08 17:04:43 +0000407 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
408 /// the relevant super key.
409 pub fn unwrap_key_if_required<'a>(
410 &self,
411 metadata: &BlobMetaData,
412 blob: &'a [u8],
413 ) -> Result<KeyBlob<'a>> {
414 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
415 let super_key = self
416 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000417 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000418 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000419 .context(ks_err!("Required super decryption key is not in memory."))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000420 KeyBlob::Sensitive {
421 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000422 .context(ks_err!("unwrap_key_with_key failed"))?,
Paul Crowley44c02da2021-04-08 17:04:43 +0000423 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
424 force_reencrypt: super_key.reencrypt_with.is_some(),
425 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700426 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000427 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700428 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800429 }
430
431 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700432 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700433 match key.algorithm {
434 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000435 (Some(iv), Some(tag)) => {
436 key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
437 }
438 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
439 "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700440 iv.is_some(),
441 tag.is_some(),
442 )),
443 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700444 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700445 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
446 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
447 ECDHPrivateKey::from_private_key(&key.key)
448 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000449 .context(ks_err!("Failed to decrypt the key blob with ECDH."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700450 }
451 (public_key, salt, iv, aead_tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000452 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700453 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000454 "Key has incomplete metadata. ",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700455 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
456 ),
457 public_key.is_some(),
458 salt.is_some(),
459 iv.is_some(),
460 aead_tag.is_some(),
461 ))
462 }
463 }
464 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800465 }
466 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000467
468 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800469 /// The reference to self is unused but it is required to prevent calling this function
470 /// concurrently with skm state database changes.
471 fn super_key_exists_in_db_for_user(
472 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000473 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800474 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700475 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000476 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000477 let key_in_db = db
Eric Biggers673d34a2023-10-18 01:54:18 +0000478 .key_exists(
479 Domain::APP,
480 user_id as u64 as i64,
481 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
482 KeyType::Super,
483 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000484 .context(ks_err!())?;
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000485
486 if key_in_db {
487 Ok(key_in_db)
488 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000489 legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000490 }
491 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000492
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800493 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000494 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800495 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700496 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700497 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000498 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700499 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700500 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700501 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000502 .context(ks_err!("Failed to extract super key from key entry"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000503 self.install_after_first_unlock_key_for_user(user_id, super_key.clone())
504 .context(ks_err!("Failed to install AfterFirstUnlock super key for user!"))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000505 Ok(super_key)
506 }
507
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800508 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700509 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700510 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700511 entry: KeyEntry,
512 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700513 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700514 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000515 if let Some((blob, metadata)) = entry.key_blob_info() {
516 let key = match (
517 metadata.encrypted_by(),
518 metadata.salt(),
519 metadata.iv(),
520 metadata.aead_tag(),
521 ) {
522 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800523 // Note that password encryption is AES no matter the value of algorithm.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000524 let key = pw
525 .derive_key(salt, AES_256_KEY_LENGTH)
526 .context(ks_err!("Failed to generate key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000527
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000528 aes_gcm_decrypt(blob, iv, tag, &key)
529 .context(ks_err!("Failed to decrypt key blob."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +0000530 }
531 (enc_by, salt, iv, tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000532 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Hasini Gunasingheda895552021-01-27 19:34:37 +0000533 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000534 "Super key has incomplete metadata.",
535 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
536 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700537 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000538 salt.is_some(),
539 iv.is_some(),
540 tag.is_some()
541 ));
542 }
543 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000544 Ok(Arc::new(SuperKey {
545 algorithm,
546 key,
547 id: SuperKeyIdentifier::DatabaseId(entry.id()),
548 reencrypt_with,
549 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000550 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000551 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000552 }
553 }
554
555 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700556 pub fn encrypt_with_password(
557 super_key: &[u8],
558 pw: &Password,
559 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000560 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700561 let derived_key = pw
David Drysdale6a0ec2c2022-04-19 08:11:18 +0100562 .derive_key(&salt, AES_256_KEY_LENGTH)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000563 .context(ks_err!("Failed to derive password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000564 let mut metadata = BlobMetaData::new();
565 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
566 metadata.add(BlobMetaEntry::Salt(salt));
567 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000568 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000569 metadata.add(BlobMetaEntry::Iv(iv));
570 metadata.add(BlobMetaEntry::AeadTag(tag));
571 Ok((encrypted_key, metadata))
572 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000573
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800574 // Helper function to encrypt a key with the given super key. Callers should select which super
575 // key to be used. This is called when a key is super encrypted at its creation as well as at
576 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700577 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000578 key_blob: &[u8],
579 super_key: &SuperKey,
580 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700581 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000582 return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
Paul Crowley8d5b2532021-03-19 10:53:07 -0700583 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000584 let mut metadata = BlobMetaData::new();
585 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000586 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000587 metadata.add(BlobMetaEntry::Iv(iv));
588 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000589 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000590 Ok((encrypted_key, metadata))
591 }
592
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000593 // Encrypts a given key_blob using a hybrid approach, which can either use the symmetric super
594 // key or the public super key depending on which is available.
595 //
596 // If the symmetric_key is available, the key_blob is encrypted using symmetric encryption with
597 // the provided symmetric super key. Otherwise, the function loads the public super key from
598 // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be
599 // re-encrypted with the symmetric super key on the first use.
600 //
Eric Biggersb1f641d2023-10-18 01:54:18 +0000601 // This hybrid scheme allows keys that use the UnlockedDeviceRequired key parameter to be
602 // created while the device is locked.
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000603 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 {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000611 Self::encrypt_with_aes_super_key(key_blob, super_key).context(ks_err!(
612 "Failed to encrypt with UnlockedDeviceRequired symmetric super key."
613 ))
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000614 } else {
615 // Symmetric key is not available, use public key encryption
616 let loaded = db
617 .load_super_key(public_key_type, user_id)
618 .context(ks_err!("load_super_key failed."))?;
619 let (key_id_guard, key_entry) =
620 loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH super key missing."))?;
621 let public_key = key_entry
622 .metadata()
623 .sec1_public_key()
624 .ok_or_else(Error::sys)
625 .context(ks_err!("sec1_public_key missing."))?;
626 let mut metadata = BlobMetaData::new();
627 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
628 ECDHPrivateKey::encrypt_message(public_key, key_blob)
629 .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
630 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
631 metadata.add(BlobMetaEntry::Salt(salt));
632 metadata.add(BlobMetaEntry::Iv(iv));
633 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
634 SuperKeyIdentifier::DatabaseId(key_id_guard.id()).add_to_metadata(&mut metadata);
635 Ok((encrypted_key, metadata))
636 }
637 }
638
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000639 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
640 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700641 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000642 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000643 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000644 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800645 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000646 domain: &Domain,
647 key_parameters: &[KeyParameter],
648 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700649 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000650 key_blob: &[u8],
651 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700652 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
653 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Eric Biggers673d34a2023-10-18 01:54:18 +0000654 SuperEncryptionType::AfterFirstUnlock => {
655 // Encrypt the given key blob with the user's AfterFirstUnlock super key. If the
656 // user has not unlocked the device since boot or has no LSKF, an error is returned.
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000657 match self
658 .get_user_state(db, legacy_importer, user_id)
David Drysdalee85523f2023-06-19 12:28:53 +0100659 .context(ks_err!("Failed to get user state for user {user_id}"))?
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000660 {
Eric Biggers673d34a2023-10-18 01:54:18 +0000661 UserState::AfterFirstUnlock(super_key) => {
662 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(ks_err!(
663 "Failed to encrypt with AfterFirstUnlock super key for user {user_id}"
664 ))
665 }
Eric Biggers13869372023-10-18 01:54:18 +0000666 UserState::BeforeFirstUnlock => {
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000667 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
668 }
669 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
David Drysdalee85523f2023-06-19 12:28:53 +0100670 .context(ks_err!("LSKF is not setup for user {user_id}")),
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000671 }
672 }
Eric Biggersb1f641d2023-10-18 01:54:18 +0000673 SuperEncryptionType::UnlockedDeviceRequired => {
674 let symmetric_key = self
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000675 .data
676 .user_keys
677 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000678 .and_then(|e| e.unlocked_device_required_symmetric.as_ref())
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000679 .map(|arc| arc.as_ref());
680 Self::encrypt_with_hybrid_super_key(
681 key_blob,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000682 symmetric_key,
683 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000684 db,
685 user_id,
686 )
Eric Biggersb1f641d2023-10-18 01:54:18 +0000687 .context(ks_err!("Failed to encrypt with UnlockedDeviceRequired hybrid scheme."))
Paul Crowley7a658392021-03-18 17:08:20 -0700688 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000689 SuperEncryptionType::BootLevel(level) => {
690 let key_id = SuperKeyIdentifier::BootLevel(level);
691 let super_key = self
692 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000693 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000694 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000695 .context(ks_err!("Boot stage key absent"))?;
696 Self::encrypt_with_aes_super_key(key_blob, &super_key)
697 .context(ks_err!("Failed to encrypt with BootLevel key."))
Paul Crowley44c02da2021-04-08 17:04:43 +0000698 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000699 }
700 }
701
702 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
703 /// If so, re-super-encrypt the key and return a new set of metadata,
704 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700705 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000706 key_blob_before_upgrade: &KeyBlob,
707 key_after_upgrade: &'a [u8],
708 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
709 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700710 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700711 let (key, metadata) =
712 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000713 .context(ks_err!("Failed to re-super-encrypt key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000714 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
715 }
716 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
717 }
718 }
719
Eric Biggers456a3a62023-10-27 03:55:28 +0000720 fn create_super_key(
721 &mut self,
722 db: &mut KeystoreDB,
723 user_id: UserId,
724 key_type: &SuperKeyType,
725 password: &Password,
726 reencrypt_with: Option<Arc<SuperKey>>,
727 ) -> Result<Arc<SuperKey>> {
728 let (super_key, public_key) = match key_type.algorithm {
729 SuperEncryptionAlgorithm::Aes256Gcm => {
730 (generate_aes256_key().context(ks_err!("Failed to generate AES-256 key."))?, None)
731 }
732 SuperEncryptionAlgorithm::EcdhP521 => {
733 let key =
734 ECDHPrivateKey::generate().context(ks_err!("Failed to generate ECDH key"))?;
735 (
736 key.private_key().context(ks_err!("private_key failed"))?,
737 Some(key.public_key().context(ks_err!("public_key failed"))?),
738 )
739 }
740 };
741 // Derive an AES-256 key from the password and re-encrypt the super key before we insert it
742 // in the database.
743 let (encrypted_super_key, blob_metadata) =
744 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
745 let mut key_metadata = KeyMetaData::new();
746 if let Some(pk) = public_key {
747 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
748 }
749 let key_entry = db
750 .store_super_key(user_id, key_type, &encrypted_super_key, &blob_metadata, &key_metadata)
751 .context(ks_err!("Failed to store super key."))?;
752 Ok(Arc::new(SuperKey {
753 algorithm: key_type.algorithm,
754 key: super_key,
755 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
756 reencrypt_with,
757 }))
758 }
759
Paul Crowley7a658392021-03-18 17:08:20 -0700760 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
761 /// When this is called, the caller must hold the lock on the SuperKeyManager.
762 /// So it's OK that the check and creation are different DB transactions.
763 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800764 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700765 db: &mut KeystoreDB,
766 user_id: UserId,
767 key_type: &SuperKeyType,
768 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700769 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700770 ) -> Result<Arc<SuperKey>> {
771 let loaded_key = db.load_super_key(key_type, user_id)?;
772 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700773 Ok(Self::extract_super_key_from_key_entry(
774 key_type.algorithm,
775 key_entry,
776 password,
777 reencrypt_with,
778 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700779 } else {
Eric Biggers456a3a62023-10-27 03:55:28 +0000780 self.create_super_key(db, user_id, key_type, password, reencrypt_with)
Paul Crowley7a658392021-03-18 17:08:20 -0700781 }
782 }
783
Eric Biggersb1f641d2023-10-18 01:54:18 +0000784 /// Decrypt the UnlockedDeviceRequired super keys for this user using the password and store
785 /// them in memory. If these keys don't exist yet, create them.
786 pub fn unlock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800787 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700788 db: &mut KeystoreDB,
789 user_id: UserId,
790 password: &Password,
791 ) -> Result<()> {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000792 let (symmetric, private) = self
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800793 .data
794 .user_keys
795 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000796 .map(|e| {
797 (
798 e.unlocked_device_required_symmetric.clone(),
799 e.unlocked_device_required_private.clone(),
800 )
801 })
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800802 .unwrap_or((None, None));
803
Eric Biggersb1f641d2023-10-18 01:54:18 +0000804 if symmetric.is_some() && private.is_some() {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800805 // Already unlocked.
806 return Ok(());
807 }
808
Eric Biggersb1f641d2023-10-18 01:54:18 +0000809 let aes = if let Some(symmetric) = symmetric {
810 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
811 // keys was initialized. This should never happen.
812 symmetric
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800813 } else {
814 self.get_or_create_super_key(
815 db,
816 user_id,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000817 &USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY,
818 password,
819 None,
820 )
821 .context(ks_err!("Trying to get or create symmetric key."))?
822 };
823
824 let ecdh = if let Some(private) = private {
825 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
826 // keys was initialized. This should never happen.
827 private
828 } else {
829 self.get_or_create_super_key(
830 db,
831 user_id,
832 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800833 password,
834 Some(aes.clone()),
835 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000836 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800837 };
838
839 self.data.add_key_to_key_index(&aes)?;
840 self.data.add_key_to_key_index(&ecdh)?;
841 let entry = self.data.user_keys.entry(user_id).or_default();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000842 entry.unlocked_device_required_symmetric = Some(aes);
843 entry.unlocked_device_required_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700844 Ok(())
845 }
846
Eric Biggersb1f641d2023-10-18 01:54:18 +0000847 /// Wipe the user's UnlockedDeviceRequired super keys from memory.
848 pub fn lock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800849 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700850 db: &mut KeystoreDB,
851 user_id: UserId,
852 unlocking_sids: &[i64],
853 ) {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000854 log::info!(
855 "Locking UnlockedDeviceRequired super keys for user {}; unlocking_sids={:?}",
856 user_id,
857 unlocking_sids
858 );
Chris Wailes53a22af2023-07-12 17:02:47 -0700859 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700860 if !unlocking_sids.is_empty() {
861 if let (Some(aes), Some(ecdh)) = (
Eric Biggersb1f641d2023-10-18 01:54:18 +0000862 entry.unlocked_device_required_symmetric.as_ref().cloned(),
863 entry.unlocked_device_required_private.as_ref().cloned(),
Paul Crowley618869e2021-04-08 20:30:54 -0700864 ) {
865 let res = (|| -> Result<()> {
866 let key_desc = KeyMintDevice::internal_descriptor(format!(
867 "biometric_unlock_key_{}",
868 user_id
869 ));
870 let encrypting_key = generate_aes256_key()?;
871 let km_dev: KeyMintDevice =
872 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000873 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700874 let mut key_params = vec![
875 KeyParameterValue::Algorithm(Algorithm::AES),
876 KeyParameterValue::KeySize(256),
877 KeyParameterValue::BlockMode(BlockMode::GCM),
878 KeyParameterValue::PaddingMode(PaddingMode::NONE),
879 KeyParameterValue::CallerNonce,
880 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
881 KeyParameterValue::MinMacLength(128),
882 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
883 KeyParameterValue::HardwareAuthenticatorType(
884 HardwareAuthenticatorType::FINGERPRINT,
885 ),
886 ];
887 for sid in unlocking_sids {
888 key_params.push(KeyParameterValue::UserSecureID(*sid));
889 }
890 let key_params: Vec<KmKeyParameter> =
891 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700892 km_dev.create_and_store_key(
893 db,
894 &key_desc,
895 KeyType::Client, /* TODO Should be Super b/189470584 */
896 |dev| {
897 let _wp = wd::watch_millis(
Eric Biggersb1f641d2023-10-18 01:54:18 +0000898 "In lock_unlocked_device_required_keys: calling importKey.",
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700899 500,
900 );
901 dev.importKey(
902 key_params.as_slice(),
903 KeyFormat::RAW,
904 &encrypting_key,
905 None,
906 )
907 },
908 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700909 entry.biometric_unlock = Some(BiometricUnlock {
910 sids: unlocking_sids.into(),
911 key_desc,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000912 symmetric: LockedKey::new(&encrypting_key, &aes)?,
913 private: LockedKey::new(&encrypting_key, &ecdh)?,
Paul Crowley618869e2021-04-08 20:30:54 -0700914 });
915 Ok(())
916 })();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000917 // There is no reason to propagate an error here upwards. We must clear the keys
918 // from memory in any case.
Paul Crowley618869e2021-04-08 20:30:54 -0700919 if let Err(e) = res {
920 log::error!("Error setting up biometric unlock: {:#?}", e);
921 }
922 }
923 }
Eric Biggersb1f641d2023-10-18 01:54:18 +0000924 entry.unlocked_device_required_symmetric = None;
925 entry.unlocked_device_required_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700926 }
Paul Crowley618869e2021-04-08 20:30:54 -0700927
928 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
929 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
930 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800931 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700932 db: &mut KeystoreDB,
933 user_id: UserId,
934 ) -> Result<()> {
Chris Wailes53a22af2023-07-12 17:02:47 -0700935 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700936 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700937 let (key_id_guard, key_entry) = db
938 .load_key_entry(
939 &biometric.key_desc,
940 KeyType::Client, // This should not be a Client key.
941 KeyEntryLoadBits::KM,
942 AID_KEYSTORE,
943 |_, _| Ok(()),
944 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000945 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700946 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000947 .context(ks_err!("KeyMintDevice::get failed"))?;
David Drysdalee85523f2023-06-19 12:28:53 +0100948 let mut errs = vec![];
Paul Crowley618869e2021-04-08 20:30:54 -0700949 for sid in &biometric.sids {
David Drysdalee85523f2023-06-19 12:28:53 +0100950 let sid = *sid;
Paul Crowley618869e2021-04-08 20:30:54 -0700951 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
David Drysdalee85523f2023-06-19 12:28:53 +0100952 entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700953 }) {
Paul Crowley618869e2021-04-08 20:30:54 -0700954 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000955 let symmetric = biometric.symmetric.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -0700956 db,
957 &km_dev,
958 &key_id_guard,
959 &key_entry,
960 auth_token_entry.auth_token(),
961 None,
962 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +0000963 let private = biometric.private.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -0700964 db,
965 &km_dev,
966 &key_id_guard,
967 &key_entry,
968 auth_token_entry.auth_token(),
Eric Biggersb1f641d2023-10-18 01:54:18 +0000969 Some(symmetric.clone()),
Paul Crowley618869e2021-04-08 20:30:54 -0700970 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +0000971 Ok((symmetric, private))
Paul Crowley618869e2021-04-08 20:30:54 -0700972 })();
973 match res {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000974 Ok((symmetric, private)) => {
975 entry.unlocked_device_required_symmetric = Some(symmetric.clone());
976 entry.unlocked_device_required_private = Some(private.clone());
977 self.data.add_key_to_key_index(&symmetric)?;
978 self.data.add_key_to_key_index(&private)?;
David Drysdalee85523f2023-06-19 12:28:53 +0100979 log::info!("Successfully unlocked user {user_id} with biometric {sid}",);
Paul Crowley618869e2021-04-08 20:30:54 -0700980 return Ok(());
981 }
982 Err(e) => {
David Drysdalee85523f2023-06-19 12:28:53 +0100983 // Don't log an error yet, as some other biometric SID might work.
984 errs.push((sid, e));
Paul Crowley618869e2021-04-08 20:30:54 -0700985 }
986 }
987 }
988 }
David Drysdalee85523f2023-06-19 12:28:53 +0100989 if !errs.is_empty() {
990 log::warn!("biometric unlock failed for all SIDs, with errors:");
991 for (sid, err) in errs {
992 log::warn!(" biometric {sid}: {err}");
993 }
994 }
Paul Crowley618869e2021-04-08 20:30:54 -0700995 }
996 Ok(())
997 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800998
999 /// Returns the keystore locked state of the given user. It requires the thread local
1000 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001001 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001002 pub fn get_user_state(
1003 &self,
1004 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001005 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001006 user_id: UserId,
1007 ) -> Result<UserState> {
Eric Biggers673d34a2023-10-18 01:54:18 +00001008 match self.get_after_first_unlock_key_by_user_id_internal(user_id) {
Eric Biggers13869372023-10-18 01:54:18 +00001009 Some(super_key) => Ok(UserState::AfterFirstUnlock(super_key)),
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001010 None => {
1011 // Check if a super key exists in the database or legacy database.
1012 // If so, return locked user state.
1013 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001014 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001015 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001016 {
Eric Biggers13869372023-10-18 01:54:18 +00001017 Ok(UserState::BeforeFirstUnlock)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001018 } else {
1019 Ok(UserState::Uninitialized)
1020 }
1021 }
1022 }
1023 }
1024
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001025 /// Deletes all keys and super keys for the given user.
1026 /// This is called when a user is deleted.
1027 pub fn remove_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001028 &mut self,
1029 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001030 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001031 user_id: UserId,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001032 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001033 log::info!("remove_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001034 // Mark keys created on behalf of the user as unreferenced.
1035 legacy_importer
1036 .bulk_delete_user(user_id, false)
1037 .context(ks_err!("Trying to delete legacy keys."))?;
1038 db.unbind_keys_for_user(user_id, false).context(ks_err!("Error in unbinding keys."))?;
1039
1040 // Delete super key in cache, if exists.
1041 self.forget_all_keys_for_user(user_id);
1042 Ok(())
1043 }
1044
1045 /// Deletes all authentication bound keys and super keys for the given user. The user must be
1046 /// unlocked before this function is called. This function is used to transition a user to
1047 /// swipe.
1048 pub fn reset_user(
1049 &mut self,
1050 db: &mut KeystoreDB,
1051 legacy_importer: &LegacyImporter,
1052 user_id: UserId,
1053 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001054 log::info!("reset_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001055 match self.get_user_state(db, legacy_importer, user_id)? {
1056 UserState::Uninitialized => {
1057 Err(Error::sys()).context(ks_err!("Tried to reset an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001058 }
Eric Biggers13869372023-10-18 01:54:18 +00001059 UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001060 Err(Error::sys()).context(ks_err!("Tried to reset a locked user's password!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001061 }
Eric Biggers13869372023-10-18 01:54:18 +00001062 UserState::AfterFirstUnlock(_) => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001063 // Mark keys created on behalf of the user as unreferenced.
1064 legacy_importer
1065 .bulk_delete_user(user_id, true)
1066 .context(ks_err!("Trying to delete legacy keys."))?;
1067 db.unbind_keys_for_user(user_id, true)
1068 .context(ks_err!("Error in unbinding keys."))?;
1069
1070 // Delete super key in cache, if exists.
1071 self.forget_all_keys_for_user(user_id);
1072 Ok(())
1073 }
1074 }
1075 }
1076
Eric Biggers673d34a2023-10-18 01:54:18 +00001077 /// If the user hasn't been initialized yet, then this function generates the user's
1078 /// AfterFirstUnlock super key and sets the user's state to AfterFirstUnlock. Otherwise this
1079 /// function returns an error.
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001080 pub fn init_user(
1081 &mut self,
1082 db: &mut KeystoreDB,
1083 legacy_importer: &LegacyImporter,
1084 user_id: UserId,
1085 password: &Password,
1086 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001087 log::info!("init_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001088 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001089 UserState::AfterFirstUnlock(_) | UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001090 Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"))
1091 }
1092 UserState::Uninitialized => {
1093 // Generate a new super key.
1094 let super_key =
1095 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
1096 // Derive an AES256 key from the password and re-encrypt the super key
1097 // before we insert it in the database.
1098 let (encrypted_super_key, blob_metadata) =
1099 Self::encrypt_with_password(&super_key, password)
1100 .context(ks_err!("Failed to encrypt super key with password!"))?;
1101
1102 let key_entry = db
1103 .store_super_key(
1104 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001105 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001106 &encrypted_super_key,
1107 &blob_metadata,
1108 &KeyMetaData::new(),
1109 )
1110 .context(ks_err!("Failed to store super key."))?;
1111
1112 self.populate_cache_from_super_key_blob(
1113 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001114 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001115 key_entry,
1116 password,
1117 )
1118 .context(ks_err!("Failed to initialize user!"))?;
1119 Ok(())
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001120 }
1121 }
1122 }
1123
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001124 /// Unlocks the given user with the given password.
1125 ///
Eric Biggers13869372023-10-18 01:54:18 +00001126 /// If the user state is BeforeFirstUnlock:
Eric Biggers673d34a2023-10-18 01:54:18 +00001127 /// - Unlock the user's AfterFirstUnlock super key
Eric Biggersb1f641d2023-10-18 01:54:18 +00001128 /// - Unlock the user's UnlockedDeviceRequired super keys
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001129 ///
Eric Biggers13869372023-10-18 01:54:18 +00001130 /// If the user state is AfterFirstUnlock:
Eric Biggersb1f641d2023-10-18 01:54:18 +00001131 /// - Unlock the user's UnlockedDeviceRequired super keys only
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001132 ///
1133 pub fn unlock_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001134 &mut self,
1135 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001136 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001137 user_id: UserId,
1138 password: &Password,
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001139 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001140 log::info!("unlock_user(user={user_id})");
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001141 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001142 UserState::AfterFirstUnlock(_) => {
Eric Biggersb1f641d2023-10-18 01:54:18 +00001143 self.unlock_unlocked_device_required_keys(db, user_id, password)
Eric Biggers13869372023-10-18 01:54:18 +00001144 }
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001145 UserState::Uninitialized => {
1146 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001147 }
Eric Biggers13869372023-10-18 01:54:18 +00001148 UserState::BeforeFirstUnlock => {
Eric Biggers673d34a2023-10-18 01:54:18 +00001149 let alias = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001150 let result = legacy_importer
1151 .with_try_import_super_key(user_id, password, || {
1152 db.load_super_key(alias, user_id)
1153 })
1154 .context(ks_err!("Failed to load super key"))?;
1155
1156 match result {
1157 Some((_, entry)) => {
1158 self.populate_cache_from_super_key_blob(
1159 user_id,
1160 alias.algorithm,
1161 entry,
1162 password,
1163 )
1164 .context(ks_err!("Failed when unlocking user."))?;
Eric Biggersb1f641d2023-10-18 01:54:18 +00001165 self.unlock_unlocked_device_required_keys(db, user_id, password)
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001166 }
1167 None => {
1168 Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))
1169 }
1170 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001171 }
1172 }
1173 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001174}
1175
1176/// This enum represents different states of the user's life cycle in the device.
1177/// For now, only three states are defined. More states may be added later.
1178pub enum UserState {
1179 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
Eric Biggers673d34a2023-10-18 01:54:18 +00001180 // and hence the AfterFirstUnlock super key is available in the cache.
Eric Biggers13869372023-10-18 01:54:18 +00001181 AfterFirstUnlock(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001182 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
Eric Biggers673d34a2023-10-18 01:54:18 +00001183 // Hence the AfterFirstUnlock and UnlockedDeviceRequired super keys are not available in the
1184 // cache. However, they exist in the database in encrypted form.
Eric Biggers13869372023-10-18 01:54:18 +00001185 BeforeFirstUnlock,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001186 // There's no user in the device for the given user id, or the user with the user id has not
1187 // setup LSKF.
1188 Uninitialized,
1189}
1190
Janis Danisevskiseed69842021-02-18 20:04:10 -08001191/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1192/// `Sensitive` holds the non encrypted key and a reference to its super key.
1193/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1194/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1195/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001196pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001197 Sensitive {
1198 key: ZVec,
1199 /// If KeyMint reports that the key must be upgraded, we must
1200 /// re-encrypt the key before writing to the database; we use
1201 /// this key.
1202 reencrypt_with: Arc<SuperKey>,
1203 /// If this key was decrypted with an ECDH key, we want to
1204 /// re-encrypt it on first use whether it was upgraded or not;
1205 /// this field indicates that that's necessary.
1206 force_reencrypt: bool,
1207 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001208 NonSensitive(Vec<u8>),
1209 Ref(&'a [u8]),
1210}
1211
Paul Crowley8d5b2532021-03-19 10:53:07 -07001212impl<'a> KeyBlob<'a> {
1213 pub fn force_reencrypt(&self) -> bool {
1214 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1215 *force_reencrypt
1216 } else {
1217 false
1218 }
1219 }
1220}
1221
Janis Danisevskiseed69842021-02-18 20:04:10 -08001222/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001223impl<'a> Deref for KeyBlob<'a> {
1224 type Target = [u8];
1225
1226 fn deref(&self) -> &Self::Target {
1227 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001228 Self::Sensitive { key, .. } => key,
1229 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001230 Self::Ref(key) => key,
1231 }
1232 }
1233}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001234
1235#[cfg(test)]
1236mod tests {
1237 use super::*;
1238 use crate::database::tests::make_bootlevel_key_entry;
1239 use crate::database::tests::make_test_key_entry;
1240 use crate::database::tests::new_test_db;
1241 use rand::prelude::*;
1242 const USER_ID: u32 = 0;
1243 const TEST_KEY_ALIAS: &str = "TEST_KEY";
1244 const TEST_BOOT_KEY_ALIAS: &str = "TEST_BOOT_KEY";
1245
1246 pub fn generate_password_blob() -> Password<'static> {
1247 let mut rng = rand::thread_rng();
1248 let mut password = vec![0u8; 64];
1249 rng.fill_bytes(&mut password);
1250
1251 let mut zvec = ZVec::new(64).expect("Failed to create ZVec");
1252 zvec[..].copy_from_slice(&password[..]);
1253
1254 Password::Owned(zvec)
1255 }
1256
1257 fn setup_test(pw: &Password) -> (Arc<RwLock<SuperKeyManager>>, KeystoreDB, LegacyImporter) {
1258 let mut keystore_db = new_test_db().unwrap();
1259 let mut legacy_importer = LegacyImporter::new(Arc::new(Default::default()));
1260 legacy_importer.set_empty();
1261 let skm: Arc<RwLock<SuperKeyManager>> = Default::default();
1262 assert!(skm
1263 .write()
1264 .unwrap()
1265 .init_user(&mut keystore_db, &legacy_importer, USER_ID, pw)
1266 .is_ok());
1267 (skm, keystore_db, legacy_importer)
1268 }
1269
1270 fn assert_unlocked(
1271 skm: &Arc<RwLock<SuperKeyManager>>,
1272 keystore_db: &mut KeystoreDB,
1273 legacy_importer: &LegacyImporter,
1274 user_id: u32,
1275 err_msg: &str,
1276 ) {
1277 let user_state =
1278 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1279 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001280 UserState::AfterFirstUnlock(_) => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001281 _ => panic!("{}", err_msg),
1282 }
1283 }
1284
1285 fn assert_locked(
1286 skm: &Arc<RwLock<SuperKeyManager>>,
1287 keystore_db: &mut KeystoreDB,
1288 legacy_importer: &LegacyImporter,
1289 user_id: u32,
1290 err_msg: &str,
1291 ) {
1292 let user_state =
1293 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1294 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001295 UserState::BeforeFirstUnlock => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001296 _ => panic!("{}", err_msg),
1297 }
1298 }
1299
1300 fn assert_uninitialized(
1301 skm: &Arc<RwLock<SuperKeyManager>>,
1302 keystore_db: &mut KeystoreDB,
1303 legacy_importer: &LegacyImporter,
1304 user_id: u32,
1305 err_msg: &str,
1306 ) {
1307 let user_state =
1308 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1309 match user_state {
1310 UserState::Uninitialized => {}
1311 _ => panic!("{}", err_msg),
1312 }
1313 }
1314
1315 #[test]
1316 fn test_init_user() {
1317 let 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
1328 #[test]
1329 fn test_unlock_user() {
1330 let pw: Password = generate_password_blob();
1331 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1332 assert_unlocked(
1333 &skm,
1334 &mut keystore_db,
1335 &legacy_importer,
1336 USER_ID,
1337 "The user was not unlocked after initialization!",
1338 );
1339
1340 skm.write().unwrap().data.user_keys.clear();
1341 assert_locked(
1342 &skm,
1343 &mut keystore_db,
1344 &legacy_importer,
1345 USER_ID,
1346 "Clearing the cache did not lock the user!",
1347 );
1348
1349 assert!(skm
1350 .write()
1351 .unwrap()
1352 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1353 .is_ok());
1354 assert_unlocked(
1355 &skm,
1356 &mut keystore_db,
1357 &legacy_importer,
1358 USER_ID,
1359 "The user did not unlock!",
1360 );
1361 }
1362
1363 #[test]
1364 fn test_unlock_wrong_password() {
1365 let pw: Password = generate_password_blob();
1366 let wrong_pw: Password = generate_password_blob();
1367 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1368 assert_unlocked(
1369 &skm,
1370 &mut keystore_db,
1371 &legacy_importer,
1372 USER_ID,
1373 "The user was not unlocked after initialization!",
1374 );
1375
1376 skm.write().unwrap().data.user_keys.clear();
1377 assert_locked(
1378 &skm,
1379 &mut keystore_db,
1380 &legacy_importer,
1381 USER_ID,
1382 "Clearing the cache did not lock the user!",
1383 );
1384
1385 assert!(skm
1386 .write()
1387 .unwrap()
1388 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &wrong_pw)
1389 .is_err());
1390 assert_locked(
1391 &skm,
1392 &mut keystore_db,
1393 &legacy_importer,
1394 USER_ID,
1395 "The user was unlocked with an incorrect password!",
1396 );
1397 }
1398
1399 #[test]
1400 fn test_unlock_user_idempotent() {
1401 let pw: Password = generate_password_blob();
1402 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1403 assert_unlocked(
1404 &skm,
1405 &mut keystore_db,
1406 &legacy_importer,
1407 USER_ID,
1408 "The user was not unlocked after initialization!",
1409 );
1410
1411 skm.write().unwrap().data.user_keys.clear();
1412 assert_locked(
1413 &skm,
1414 &mut keystore_db,
1415 &legacy_importer,
1416 USER_ID,
1417 "Clearing the cache did not lock the user!",
1418 );
1419
1420 for _ in 0..5 {
1421 assert!(skm
1422 .write()
1423 .unwrap()
1424 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1425 .is_ok());
1426 assert_unlocked(
1427 &skm,
1428 &mut keystore_db,
1429 &legacy_importer,
1430 USER_ID,
1431 "The user did not unlock!",
1432 );
1433 }
1434 }
1435
1436 fn test_user_removal(locked: bool) {
1437 let pw: Password = generate_password_blob();
1438 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1439 assert_unlocked(
1440 &skm,
1441 &mut keystore_db,
1442 &legacy_importer,
1443 USER_ID,
1444 "The user was not unlocked after initialization!",
1445 );
1446
1447 assert!(make_test_key_entry(
1448 &mut keystore_db,
1449 Domain::APP,
1450 USER_ID.into(),
1451 TEST_KEY_ALIAS,
1452 None
1453 )
1454 .is_ok());
1455 assert!(make_bootlevel_key_entry(
1456 &mut keystore_db,
1457 Domain::APP,
1458 USER_ID.into(),
1459 TEST_BOOT_KEY_ALIAS,
1460 false
1461 )
1462 .is_ok());
1463
1464 assert!(keystore_db
1465 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1466 .unwrap());
1467 assert!(keystore_db
1468 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1469 .unwrap());
1470
1471 if locked {
1472 skm.write().unwrap().data.user_keys.clear();
1473 assert_locked(
1474 &skm,
1475 &mut keystore_db,
1476 &legacy_importer,
1477 USER_ID,
1478 "Clearing the cache did not lock the user!",
1479 );
1480 }
1481
1482 assert!(skm
1483 .write()
1484 .unwrap()
1485 .remove_user(&mut keystore_db, &legacy_importer, USER_ID)
1486 .is_ok());
1487 assert_uninitialized(
1488 &skm,
1489 &mut keystore_db,
1490 &legacy_importer,
1491 USER_ID,
1492 "The user was not removed!",
1493 );
1494
1495 assert!(!skm
1496 .write()
1497 .unwrap()
1498 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1499 .unwrap());
1500
1501 assert!(!keystore_db
1502 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1503 .unwrap());
1504 assert!(!keystore_db
1505 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1506 .unwrap());
1507 }
1508
1509 fn test_user_reset(locked: bool) {
1510 let pw: Password = generate_password_blob();
1511 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1512 assert_unlocked(
1513 &skm,
1514 &mut keystore_db,
1515 &legacy_importer,
1516 USER_ID,
1517 "The user was not unlocked after initialization!",
1518 );
1519
1520 assert!(make_test_key_entry(
1521 &mut keystore_db,
1522 Domain::APP,
1523 USER_ID.into(),
1524 TEST_KEY_ALIAS,
1525 None
1526 )
1527 .is_ok());
1528 assert!(make_bootlevel_key_entry(
1529 &mut keystore_db,
1530 Domain::APP,
1531 USER_ID.into(),
1532 TEST_BOOT_KEY_ALIAS,
1533 false
1534 )
1535 .is_ok());
1536 assert!(keystore_db
1537 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1538 .unwrap());
1539 assert!(keystore_db
1540 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1541 .unwrap());
1542
1543 if locked {
1544 skm.write().unwrap().data.user_keys.clear();
1545 assert_locked(
1546 &skm,
1547 &mut keystore_db,
1548 &legacy_importer,
1549 USER_ID,
1550 "Clearing the cache did not lock the user!",
1551 );
1552 assert!(skm
1553 .write()
1554 .unwrap()
1555 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1556 .is_err());
1557 assert_locked(
1558 &skm,
1559 &mut keystore_db,
1560 &legacy_importer,
1561 USER_ID,
1562 "User state should not have changed!",
1563 );
1564
1565 // Keys should still exist.
1566 assert!(keystore_db
1567 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1568 .unwrap());
1569 assert!(keystore_db
1570 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1571 .unwrap());
1572 } else {
1573 assert!(skm
1574 .write()
1575 .unwrap()
1576 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1577 .is_ok());
1578 assert_uninitialized(
1579 &skm,
1580 &mut keystore_db,
1581 &legacy_importer,
1582 USER_ID,
1583 "The user was not reset!",
1584 );
1585 assert!(!skm
1586 .write()
1587 .unwrap()
1588 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1589 .unwrap());
1590
1591 // Auth bound key should no longer exist.
1592 assert!(!keystore_db
1593 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1594 .unwrap());
1595 assert!(keystore_db
1596 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1597 .unwrap());
1598 }
1599 }
1600
1601 #[test]
1602 fn test_remove_unlocked_user() {
1603 test_user_removal(false);
1604 }
1605
1606 #[test]
1607 fn test_remove_locked_user() {
1608 test_user_removal(true);
1609 }
1610
1611 #[test]
1612 fn test_reset_unlocked_user() {
1613 test_user_reset(false);
1614 }
1615
1616 #[test]
1617 fn test_reset_locked_user() {
1618 test_user_reset(true);
1619 }
1620}