blob: 128cf4cae9c9ebda1135b02e2527209338cc2abd [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
Paul Crowley7a658392021-03-18 17:08:20 -0700720 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
721 /// When this is called, the caller must hold the lock on the SuperKeyManager.
722 /// So it's OK that the check and creation are different DB transactions.
723 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800724 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700725 db: &mut KeystoreDB,
726 user_id: UserId,
727 key_type: &SuperKeyType,
728 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700729 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700730 ) -> Result<Arc<SuperKey>> {
731 let loaded_key = db.load_super_key(key_type, user_id)?;
732 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700733 Ok(Self::extract_super_key_from_key_entry(
734 key_type.algorithm,
735 key_entry,
736 password,
737 reencrypt_with,
738 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700739 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700740 let (super_key, public_key) = match key_type.algorithm {
741 SuperEncryptionAlgorithm::Aes256Gcm => (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000742 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700743 None,
744 ),
Paul Crowley52f017f2021-06-22 08:16:01 -0700745 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700746 let key = ECDHPrivateKey::generate()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000747 .context(ks_err!("Failed to generate ECDH key"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700748 (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000749 key.private_key().context(ks_err!("private_key failed"))?,
750 Some(key.public_key().context(ks_err!("public_key failed"))?),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700751 )
752 }
753 };
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800754 // Derive an AES256 key from the password and re-encrypt the super key
755 // before we insert it in the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700756 let (encrypted_super_key, blob_metadata) =
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000757 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700758 let mut key_metadata = KeyMetaData::new();
759 if let Some(pk) = public_key {
760 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
761 }
Paul Crowley7a658392021-03-18 17:08:20 -0700762 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700763 .store_super_key(
764 user_id,
765 key_type,
766 &encrypted_super_key,
767 &blob_metadata,
768 &key_metadata,
769 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000770 .context(ks_err!("Failed to store super key."))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700771 Ok(Arc::new(SuperKey {
772 algorithm: key_type.algorithm,
773 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000774 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700775 reencrypt_with,
776 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700777 }
778 }
779
Eric Biggersb1f641d2023-10-18 01:54:18 +0000780 /// Decrypt the UnlockedDeviceRequired super keys for this user using the password and store
781 /// them in memory. If these keys don't exist yet, create them.
782 pub fn unlock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800783 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700784 db: &mut KeystoreDB,
785 user_id: UserId,
786 password: &Password,
787 ) -> Result<()> {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000788 let (symmetric, private) = self
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800789 .data
790 .user_keys
791 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000792 .map(|e| {
793 (
794 e.unlocked_device_required_symmetric.clone(),
795 e.unlocked_device_required_private.clone(),
796 )
797 })
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800798 .unwrap_or((None, None));
799
Eric Biggersb1f641d2023-10-18 01:54:18 +0000800 if symmetric.is_some() && private.is_some() {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800801 // Already unlocked.
802 return Ok(());
803 }
804
Eric Biggersb1f641d2023-10-18 01:54:18 +0000805 let aes = if let Some(symmetric) = symmetric {
806 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
807 // keys was initialized. This should never happen.
808 symmetric
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800809 } else {
810 self.get_or_create_super_key(
811 db,
812 user_id,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000813 &USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY,
814 password,
815 None,
816 )
817 .context(ks_err!("Trying to get or create symmetric key."))?
818 };
819
820 let ecdh = if let Some(private) = private {
821 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
822 // keys was initialized. This should never happen.
823 private
824 } else {
825 self.get_or_create_super_key(
826 db,
827 user_id,
828 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800829 password,
830 Some(aes.clone()),
831 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000832 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800833 };
834
835 self.data.add_key_to_key_index(&aes)?;
836 self.data.add_key_to_key_index(&ecdh)?;
837 let entry = self.data.user_keys.entry(user_id).or_default();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000838 entry.unlocked_device_required_symmetric = Some(aes);
839 entry.unlocked_device_required_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700840 Ok(())
841 }
842
Eric Biggersb1f641d2023-10-18 01:54:18 +0000843 /// Wipe the user's UnlockedDeviceRequired super keys from memory.
844 pub fn lock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800845 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700846 db: &mut KeystoreDB,
847 user_id: UserId,
848 unlocking_sids: &[i64],
849 ) {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000850 log::info!(
851 "Locking UnlockedDeviceRequired super keys for user {}; unlocking_sids={:?}",
852 user_id,
853 unlocking_sids
854 );
Chris Wailes53a22af2023-07-12 17:02:47 -0700855 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700856 if !unlocking_sids.is_empty() {
857 if let (Some(aes), Some(ecdh)) = (
Eric Biggersb1f641d2023-10-18 01:54:18 +0000858 entry.unlocked_device_required_symmetric.as_ref().cloned(),
859 entry.unlocked_device_required_private.as_ref().cloned(),
Paul Crowley618869e2021-04-08 20:30:54 -0700860 ) {
861 let res = (|| -> Result<()> {
862 let key_desc = KeyMintDevice::internal_descriptor(format!(
863 "biometric_unlock_key_{}",
864 user_id
865 ));
866 let encrypting_key = generate_aes256_key()?;
867 let km_dev: KeyMintDevice =
868 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000869 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700870 let mut key_params = vec![
871 KeyParameterValue::Algorithm(Algorithm::AES),
872 KeyParameterValue::KeySize(256),
873 KeyParameterValue::BlockMode(BlockMode::GCM),
874 KeyParameterValue::PaddingMode(PaddingMode::NONE),
875 KeyParameterValue::CallerNonce,
876 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
877 KeyParameterValue::MinMacLength(128),
878 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
879 KeyParameterValue::HardwareAuthenticatorType(
880 HardwareAuthenticatorType::FINGERPRINT,
881 ),
882 ];
883 for sid in unlocking_sids {
884 key_params.push(KeyParameterValue::UserSecureID(*sid));
885 }
886 let key_params: Vec<KmKeyParameter> =
887 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700888 km_dev.create_and_store_key(
889 db,
890 &key_desc,
891 KeyType::Client, /* TODO Should be Super b/189470584 */
892 |dev| {
893 let _wp = wd::watch_millis(
Eric Biggersb1f641d2023-10-18 01:54:18 +0000894 "In lock_unlocked_device_required_keys: calling importKey.",
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700895 500,
896 );
897 dev.importKey(
898 key_params.as_slice(),
899 KeyFormat::RAW,
900 &encrypting_key,
901 None,
902 )
903 },
904 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700905 entry.biometric_unlock = Some(BiometricUnlock {
906 sids: unlocking_sids.into(),
907 key_desc,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000908 symmetric: LockedKey::new(&encrypting_key, &aes)?,
909 private: LockedKey::new(&encrypting_key, &ecdh)?,
Paul Crowley618869e2021-04-08 20:30:54 -0700910 });
911 Ok(())
912 })();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000913 // There is no reason to propagate an error here upwards. We must clear the keys
914 // from memory in any case.
Paul Crowley618869e2021-04-08 20:30:54 -0700915 if let Err(e) = res {
916 log::error!("Error setting up biometric unlock: {:#?}", e);
917 }
918 }
919 }
Eric Biggersb1f641d2023-10-18 01:54:18 +0000920 entry.unlocked_device_required_symmetric = None;
921 entry.unlocked_device_required_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700922 }
Paul Crowley618869e2021-04-08 20:30:54 -0700923
924 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
925 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
926 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800927 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700928 db: &mut KeystoreDB,
929 user_id: UserId,
930 ) -> Result<()> {
Chris Wailes53a22af2023-07-12 17:02:47 -0700931 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700932 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700933 let (key_id_guard, key_entry) = db
934 .load_key_entry(
935 &biometric.key_desc,
936 KeyType::Client, // This should not be a Client key.
937 KeyEntryLoadBits::KM,
938 AID_KEYSTORE,
939 |_, _| Ok(()),
940 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000941 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700942 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000943 .context(ks_err!("KeyMintDevice::get failed"))?;
David Drysdalee85523f2023-06-19 12:28:53 +0100944 let mut errs = vec![];
Paul Crowley618869e2021-04-08 20:30:54 -0700945 for sid in &biometric.sids {
David Drysdalee85523f2023-06-19 12:28:53 +0100946 let sid = *sid;
Paul Crowley618869e2021-04-08 20:30:54 -0700947 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
David Drysdalee85523f2023-06-19 12:28:53 +0100948 entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700949 }) {
Paul Crowley618869e2021-04-08 20:30:54 -0700950 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000951 let symmetric = biometric.symmetric.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -0700952 db,
953 &km_dev,
954 &key_id_guard,
955 &key_entry,
956 auth_token_entry.auth_token(),
957 None,
958 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +0000959 let private = biometric.private.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -0700960 db,
961 &km_dev,
962 &key_id_guard,
963 &key_entry,
964 auth_token_entry.auth_token(),
Eric Biggersb1f641d2023-10-18 01:54:18 +0000965 Some(symmetric.clone()),
Paul Crowley618869e2021-04-08 20:30:54 -0700966 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +0000967 Ok((symmetric, private))
Paul Crowley618869e2021-04-08 20:30:54 -0700968 })();
969 match res {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000970 Ok((symmetric, private)) => {
971 entry.unlocked_device_required_symmetric = Some(symmetric.clone());
972 entry.unlocked_device_required_private = Some(private.clone());
973 self.data.add_key_to_key_index(&symmetric)?;
974 self.data.add_key_to_key_index(&private)?;
David Drysdalee85523f2023-06-19 12:28:53 +0100975 log::info!("Successfully unlocked user {user_id} with biometric {sid}",);
Paul Crowley618869e2021-04-08 20:30:54 -0700976 return Ok(());
977 }
978 Err(e) => {
David Drysdalee85523f2023-06-19 12:28:53 +0100979 // Don't log an error yet, as some other biometric SID might work.
980 errs.push((sid, e));
Paul Crowley618869e2021-04-08 20:30:54 -0700981 }
982 }
983 }
984 }
David Drysdalee85523f2023-06-19 12:28:53 +0100985 if !errs.is_empty() {
986 log::warn!("biometric unlock failed for all SIDs, with errors:");
987 for (sid, err) in errs {
988 log::warn!(" biometric {sid}: {err}");
989 }
990 }
Paul Crowley618869e2021-04-08 20:30:54 -0700991 }
992 Ok(())
993 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800994
995 /// Returns the keystore locked state of the given user. It requires the thread local
996 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800997 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800998 pub fn get_user_state(
999 &self,
1000 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001001 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001002 user_id: UserId,
1003 ) -> Result<UserState> {
Eric Biggers673d34a2023-10-18 01:54:18 +00001004 match self.get_after_first_unlock_key_by_user_id_internal(user_id) {
Eric Biggers13869372023-10-18 01:54:18 +00001005 Some(super_key) => Ok(UserState::AfterFirstUnlock(super_key)),
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001006 None => {
1007 // Check if a super key exists in the database or legacy database.
1008 // If so, return locked user state.
1009 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001010 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001011 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001012 {
Eric Biggers13869372023-10-18 01:54:18 +00001013 Ok(UserState::BeforeFirstUnlock)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001014 } else {
1015 Ok(UserState::Uninitialized)
1016 }
1017 }
1018 }
1019 }
1020
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001021 /// Deletes all keys and super keys for the given user.
1022 /// This is called when a user is deleted.
1023 pub fn remove_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001024 &mut self,
1025 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001026 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001027 user_id: UserId,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001028 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001029 log::info!("remove_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001030 // Mark keys created on behalf of the user as unreferenced.
1031 legacy_importer
1032 .bulk_delete_user(user_id, false)
1033 .context(ks_err!("Trying to delete legacy keys."))?;
1034 db.unbind_keys_for_user(user_id, false).context(ks_err!("Error in unbinding keys."))?;
1035
1036 // Delete super key in cache, if exists.
1037 self.forget_all_keys_for_user(user_id);
1038 Ok(())
1039 }
1040
1041 /// Deletes all authentication bound keys and super keys for the given user. The user must be
1042 /// unlocked before this function is called. This function is used to transition a user to
1043 /// swipe.
1044 pub fn reset_user(
1045 &mut self,
1046 db: &mut KeystoreDB,
1047 legacy_importer: &LegacyImporter,
1048 user_id: UserId,
1049 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001050 log::info!("reset_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001051 match self.get_user_state(db, legacy_importer, user_id)? {
1052 UserState::Uninitialized => {
1053 Err(Error::sys()).context(ks_err!("Tried to reset an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001054 }
Eric Biggers13869372023-10-18 01:54:18 +00001055 UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001056 Err(Error::sys()).context(ks_err!("Tried to reset a locked user's password!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001057 }
Eric Biggers13869372023-10-18 01:54:18 +00001058 UserState::AfterFirstUnlock(_) => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001059 // Mark keys created on behalf of the user as unreferenced.
1060 legacy_importer
1061 .bulk_delete_user(user_id, true)
1062 .context(ks_err!("Trying to delete legacy keys."))?;
1063 db.unbind_keys_for_user(user_id, true)
1064 .context(ks_err!("Error in unbinding keys."))?;
1065
1066 // Delete super key in cache, if exists.
1067 self.forget_all_keys_for_user(user_id);
1068 Ok(())
1069 }
1070 }
1071 }
1072
Eric Biggers673d34a2023-10-18 01:54:18 +00001073 /// If the user hasn't been initialized yet, then this function generates the user's
1074 /// AfterFirstUnlock super key and sets the user's state to AfterFirstUnlock. Otherwise this
1075 /// function returns an error.
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001076 pub fn init_user(
1077 &mut self,
1078 db: &mut KeystoreDB,
1079 legacy_importer: &LegacyImporter,
1080 user_id: UserId,
1081 password: &Password,
1082 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001083 log::info!("init_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001084 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001085 UserState::AfterFirstUnlock(_) | UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001086 Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"))
1087 }
1088 UserState::Uninitialized => {
1089 // Generate a new super key.
1090 let super_key =
1091 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
1092 // Derive an AES256 key from the password and re-encrypt the super key
1093 // before we insert it in the database.
1094 let (encrypted_super_key, blob_metadata) =
1095 Self::encrypt_with_password(&super_key, password)
1096 .context(ks_err!("Failed to encrypt super key with password!"))?;
1097
1098 let key_entry = db
1099 .store_super_key(
1100 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001101 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001102 &encrypted_super_key,
1103 &blob_metadata,
1104 &KeyMetaData::new(),
1105 )
1106 .context(ks_err!("Failed to store super key."))?;
1107
1108 self.populate_cache_from_super_key_blob(
1109 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001110 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001111 key_entry,
1112 password,
1113 )
1114 .context(ks_err!("Failed to initialize user!"))?;
1115 Ok(())
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001116 }
1117 }
1118 }
1119
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001120 /// Unlocks the given user with the given password.
1121 ///
Eric Biggers13869372023-10-18 01:54:18 +00001122 /// If the user state is BeforeFirstUnlock:
Eric Biggers673d34a2023-10-18 01:54:18 +00001123 /// - Unlock the user's AfterFirstUnlock super key
Eric Biggersb1f641d2023-10-18 01:54:18 +00001124 /// - Unlock the user's UnlockedDeviceRequired super keys
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001125 ///
Eric Biggers13869372023-10-18 01:54:18 +00001126 /// If the user state is AfterFirstUnlock:
Eric Biggersb1f641d2023-10-18 01:54:18 +00001127 /// - Unlock the user's UnlockedDeviceRequired super keys only
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001128 ///
1129 pub fn unlock_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001130 &mut self,
1131 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001132 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001133 user_id: UserId,
1134 password: &Password,
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001135 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001136 log::info!("unlock_user(user={user_id})");
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001137 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001138 UserState::AfterFirstUnlock(_) => {
Eric Biggersb1f641d2023-10-18 01:54:18 +00001139 self.unlock_unlocked_device_required_keys(db, user_id, password)
Eric Biggers13869372023-10-18 01:54:18 +00001140 }
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001141 UserState::Uninitialized => {
1142 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001143 }
Eric Biggers13869372023-10-18 01:54:18 +00001144 UserState::BeforeFirstUnlock => {
Eric Biggers673d34a2023-10-18 01:54:18 +00001145 let alias = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001146 let result = legacy_importer
1147 .with_try_import_super_key(user_id, password, || {
1148 db.load_super_key(alias, user_id)
1149 })
1150 .context(ks_err!("Failed to load super key"))?;
1151
1152 match result {
1153 Some((_, entry)) => {
1154 self.populate_cache_from_super_key_blob(
1155 user_id,
1156 alias.algorithm,
1157 entry,
1158 password,
1159 )
1160 .context(ks_err!("Failed when unlocking user."))?;
Eric Biggersb1f641d2023-10-18 01:54:18 +00001161 self.unlock_unlocked_device_required_keys(db, user_id, password)
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001162 }
1163 None => {
1164 Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))
1165 }
1166 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001167 }
1168 }
1169 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001170}
1171
1172/// This enum represents different states of the user's life cycle in the device.
1173/// For now, only three states are defined. More states may be added later.
1174pub enum UserState {
1175 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
Eric Biggers673d34a2023-10-18 01:54:18 +00001176 // and hence the AfterFirstUnlock super key is available in the cache.
Eric Biggers13869372023-10-18 01:54:18 +00001177 AfterFirstUnlock(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001178 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
Eric Biggers673d34a2023-10-18 01:54:18 +00001179 // Hence the AfterFirstUnlock and UnlockedDeviceRequired super keys are not available in the
1180 // cache. However, they exist in the database in encrypted form.
Eric Biggers13869372023-10-18 01:54:18 +00001181 BeforeFirstUnlock,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001182 // There's no user in the device for the given user id, or the user with the user id has not
1183 // setup LSKF.
1184 Uninitialized,
1185}
1186
Janis Danisevskiseed69842021-02-18 20:04:10 -08001187/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1188/// `Sensitive` holds the non encrypted key and a reference to its super key.
1189/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1190/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1191/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001192pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001193 Sensitive {
1194 key: ZVec,
1195 /// If KeyMint reports that the key must be upgraded, we must
1196 /// re-encrypt the key before writing to the database; we use
1197 /// this key.
1198 reencrypt_with: Arc<SuperKey>,
1199 /// If this key was decrypted with an ECDH key, we want to
1200 /// re-encrypt it on first use whether it was upgraded or not;
1201 /// this field indicates that that's necessary.
1202 force_reencrypt: bool,
1203 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001204 NonSensitive(Vec<u8>),
1205 Ref(&'a [u8]),
1206}
1207
Paul Crowley8d5b2532021-03-19 10:53:07 -07001208impl<'a> KeyBlob<'a> {
1209 pub fn force_reencrypt(&self) -> bool {
1210 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1211 *force_reencrypt
1212 } else {
1213 false
1214 }
1215 }
1216}
1217
Janis Danisevskiseed69842021-02-18 20:04:10 -08001218/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001219impl<'a> Deref for KeyBlob<'a> {
1220 type Target = [u8];
1221
1222 fn deref(&self) -> &Self::Target {
1223 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001224 Self::Sensitive { key, .. } => key,
1225 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001226 Self::Ref(key) => key,
1227 }
1228 }
1229}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001230
1231#[cfg(test)]
1232mod tests {
1233 use super::*;
1234 use crate::database::tests::make_bootlevel_key_entry;
1235 use crate::database::tests::make_test_key_entry;
1236 use crate::database::tests::new_test_db;
1237 use rand::prelude::*;
1238 const USER_ID: u32 = 0;
1239 const TEST_KEY_ALIAS: &str = "TEST_KEY";
1240 const TEST_BOOT_KEY_ALIAS: &str = "TEST_BOOT_KEY";
1241
1242 pub fn generate_password_blob() -> Password<'static> {
1243 let mut rng = rand::thread_rng();
1244 let mut password = vec![0u8; 64];
1245 rng.fill_bytes(&mut password);
1246
1247 let mut zvec = ZVec::new(64).expect("Failed to create ZVec");
1248 zvec[..].copy_from_slice(&password[..]);
1249
1250 Password::Owned(zvec)
1251 }
1252
1253 fn setup_test(pw: &Password) -> (Arc<RwLock<SuperKeyManager>>, KeystoreDB, LegacyImporter) {
1254 let mut keystore_db = new_test_db().unwrap();
1255 let mut legacy_importer = LegacyImporter::new(Arc::new(Default::default()));
1256 legacy_importer.set_empty();
1257 let skm: Arc<RwLock<SuperKeyManager>> = Default::default();
1258 assert!(skm
1259 .write()
1260 .unwrap()
1261 .init_user(&mut keystore_db, &legacy_importer, USER_ID, pw)
1262 .is_ok());
1263 (skm, keystore_db, legacy_importer)
1264 }
1265
1266 fn assert_unlocked(
1267 skm: &Arc<RwLock<SuperKeyManager>>,
1268 keystore_db: &mut KeystoreDB,
1269 legacy_importer: &LegacyImporter,
1270 user_id: u32,
1271 err_msg: &str,
1272 ) {
1273 let user_state =
1274 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1275 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001276 UserState::AfterFirstUnlock(_) => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001277 _ => panic!("{}", err_msg),
1278 }
1279 }
1280
1281 fn assert_locked(
1282 skm: &Arc<RwLock<SuperKeyManager>>,
1283 keystore_db: &mut KeystoreDB,
1284 legacy_importer: &LegacyImporter,
1285 user_id: u32,
1286 err_msg: &str,
1287 ) {
1288 let user_state =
1289 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1290 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001291 UserState::BeforeFirstUnlock => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001292 _ => panic!("{}", err_msg),
1293 }
1294 }
1295
1296 fn assert_uninitialized(
1297 skm: &Arc<RwLock<SuperKeyManager>>,
1298 keystore_db: &mut KeystoreDB,
1299 legacy_importer: &LegacyImporter,
1300 user_id: u32,
1301 err_msg: &str,
1302 ) {
1303 let user_state =
1304 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1305 match user_state {
1306 UserState::Uninitialized => {}
1307 _ => panic!("{}", err_msg),
1308 }
1309 }
1310
1311 #[test]
1312 fn test_init_user() {
1313 let pw: Password = generate_password_blob();
1314 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1315 assert_unlocked(
1316 &skm,
1317 &mut keystore_db,
1318 &legacy_importer,
1319 USER_ID,
1320 "The user was not unlocked after initialization!",
1321 );
1322 }
1323
1324 #[test]
1325 fn test_unlock_user() {
1326 let pw: Password = generate_password_blob();
1327 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1328 assert_unlocked(
1329 &skm,
1330 &mut keystore_db,
1331 &legacy_importer,
1332 USER_ID,
1333 "The user was not unlocked after initialization!",
1334 );
1335
1336 skm.write().unwrap().data.user_keys.clear();
1337 assert_locked(
1338 &skm,
1339 &mut keystore_db,
1340 &legacy_importer,
1341 USER_ID,
1342 "Clearing the cache did not lock the user!",
1343 );
1344
1345 assert!(skm
1346 .write()
1347 .unwrap()
1348 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1349 .is_ok());
1350 assert_unlocked(
1351 &skm,
1352 &mut keystore_db,
1353 &legacy_importer,
1354 USER_ID,
1355 "The user did not unlock!",
1356 );
1357 }
1358
1359 #[test]
1360 fn test_unlock_wrong_password() {
1361 let pw: Password = generate_password_blob();
1362 let wrong_pw: Password = generate_password_blob();
1363 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1364 assert_unlocked(
1365 &skm,
1366 &mut keystore_db,
1367 &legacy_importer,
1368 USER_ID,
1369 "The user was not unlocked after initialization!",
1370 );
1371
1372 skm.write().unwrap().data.user_keys.clear();
1373 assert_locked(
1374 &skm,
1375 &mut keystore_db,
1376 &legacy_importer,
1377 USER_ID,
1378 "Clearing the cache did not lock the user!",
1379 );
1380
1381 assert!(skm
1382 .write()
1383 .unwrap()
1384 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &wrong_pw)
1385 .is_err());
1386 assert_locked(
1387 &skm,
1388 &mut keystore_db,
1389 &legacy_importer,
1390 USER_ID,
1391 "The user was unlocked with an incorrect password!",
1392 );
1393 }
1394
1395 #[test]
1396 fn test_unlock_user_idempotent() {
1397 let pw: Password = generate_password_blob();
1398 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1399 assert_unlocked(
1400 &skm,
1401 &mut keystore_db,
1402 &legacy_importer,
1403 USER_ID,
1404 "The user was not unlocked after initialization!",
1405 );
1406
1407 skm.write().unwrap().data.user_keys.clear();
1408 assert_locked(
1409 &skm,
1410 &mut keystore_db,
1411 &legacy_importer,
1412 USER_ID,
1413 "Clearing the cache did not lock the user!",
1414 );
1415
1416 for _ in 0..5 {
1417 assert!(skm
1418 .write()
1419 .unwrap()
1420 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1421 .is_ok());
1422 assert_unlocked(
1423 &skm,
1424 &mut keystore_db,
1425 &legacy_importer,
1426 USER_ID,
1427 "The user did not unlock!",
1428 );
1429 }
1430 }
1431
1432 fn test_user_removal(locked: bool) {
1433 let pw: Password = generate_password_blob();
1434 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1435 assert_unlocked(
1436 &skm,
1437 &mut keystore_db,
1438 &legacy_importer,
1439 USER_ID,
1440 "The user was not unlocked after initialization!",
1441 );
1442
1443 assert!(make_test_key_entry(
1444 &mut keystore_db,
1445 Domain::APP,
1446 USER_ID.into(),
1447 TEST_KEY_ALIAS,
1448 None
1449 )
1450 .is_ok());
1451 assert!(make_bootlevel_key_entry(
1452 &mut keystore_db,
1453 Domain::APP,
1454 USER_ID.into(),
1455 TEST_BOOT_KEY_ALIAS,
1456 false
1457 )
1458 .is_ok());
1459
1460 assert!(keystore_db
1461 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1462 .unwrap());
1463 assert!(keystore_db
1464 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1465 .unwrap());
1466
1467 if locked {
1468 skm.write().unwrap().data.user_keys.clear();
1469 assert_locked(
1470 &skm,
1471 &mut keystore_db,
1472 &legacy_importer,
1473 USER_ID,
1474 "Clearing the cache did not lock the user!",
1475 );
1476 }
1477
1478 assert!(skm
1479 .write()
1480 .unwrap()
1481 .remove_user(&mut keystore_db, &legacy_importer, USER_ID)
1482 .is_ok());
1483 assert_uninitialized(
1484 &skm,
1485 &mut keystore_db,
1486 &legacy_importer,
1487 USER_ID,
1488 "The user was not removed!",
1489 );
1490
1491 assert!(!skm
1492 .write()
1493 .unwrap()
1494 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1495 .unwrap());
1496
1497 assert!(!keystore_db
1498 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1499 .unwrap());
1500 assert!(!keystore_db
1501 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1502 .unwrap());
1503 }
1504
1505 fn test_user_reset(locked: bool) {
1506 let pw: Password = generate_password_blob();
1507 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1508 assert_unlocked(
1509 &skm,
1510 &mut keystore_db,
1511 &legacy_importer,
1512 USER_ID,
1513 "The user was not unlocked after initialization!",
1514 );
1515
1516 assert!(make_test_key_entry(
1517 &mut keystore_db,
1518 Domain::APP,
1519 USER_ID.into(),
1520 TEST_KEY_ALIAS,
1521 None
1522 )
1523 .is_ok());
1524 assert!(make_bootlevel_key_entry(
1525 &mut keystore_db,
1526 Domain::APP,
1527 USER_ID.into(),
1528 TEST_BOOT_KEY_ALIAS,
1529 false
1530 )
1531 .is_ok());
1532 assert!(keystore_db
1533 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1534 .unwrap());
1535 assert!(keystore_db
1536 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1537 .unwrap());
1538
1539 if locked {
1540 skm.write().unwrap().data.user_keys.clear();
1541 assert_locked(
1542 &skm,
1543 &mut keystore_db,
1544 &legacy_importer,
1545 USER_ID,
1546 "Clearing the cache did not lock the user!",
1547 );
1548 assert!(skm
1549 .write()
1550 .unwrap()
1551 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1552 .is_err());
1553 assert_locked(
1554 &skm,
1555 &mut keystore_db,
1556 &legacy_importer,
1557 USER_ID,
1558 "User state should not have changed!",
1559 );
1560
1561 // Keys should still exist.
1562 assert!(keystore_db
1563 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1564 .unwrap());
1565 assert!(keystore_db
1566 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1567 .unwrap());
1568 } else {
1569 assert!(skm
1570 .write()
1571 .unwrap()
1572 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1573 .is_ok());
1574 assert_uninitialized(
1575 &skm,
1576 &mut keystore_db,
1577 &legacy_importer,
1578 USER_ID,
1579 "The user was not reset!",
1580 );
1581 assert!(!skm
1582 .write()
1583 .unwrap()
1584 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1585 .unwrap());
1586
1587 // Auth bound key should no longer exist.
1588 assert!(!keystore_db
1589 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1590 .unwrap());
1591 assert!(keystore_db
1592 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1593 .unwrap());
1594 }
1595 }
1596
1597 #[test]
1598 fn test_remove_unlocked_user() {
1599 test_user_removal(false);
1600 }
1601
1602 #[test]
1603 fn test_remove_locked_user() {
1604 test_user_removal(true);
1605 }
1606
1607 #[test]
1608 fn test_reset_unlocked_user() {
1609 test_user_reset(false);
1610 }
1611
1612 #[test]
1613 fn test_reset_locked_user() {
1614 test_user_reset(true);
1615 }
1616}