blob: 898a8c2c62f9766bf453f6055998592945491d35 [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,
Eric Biggers6745f532023-10-27 03:55:28 +000081 /// What to call this key in log messages. Not used for anything else.
82 pub name: &'a str,
Paul Crowley7a658392021-03-18 17:08:20 -070083}
84
Eric Biggers673d34a2023-10-18 01:54:18 +000085/// The user's AfterFirstUnlock super key. This super key is loaded into memory when the user first
86/// unlocks the device, and it remains in memory until the device reboots. This is used to encrypt
87/// keys that require user authentication but not an unlocked device.
Eric Biggers6745f532023-10-27 03:55:28 +000088pub const USER_AFTER_FIRST_UNLOCK_SUPER_KEY: SuperKeyType = SuperKeyType {
89 alias: "USER_SUPER_KEY",
90 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
91 name: "AfterFirstUnlock super key",
92};
93
Eric Biggersb1f641d2023-10-18 01:54:18 +000094/// The user's UnlockedDeviceRequired symmetric super key. This super key is loaded into memory each
95/// time the user unlocks the device, and it is cleared from memory each time the user locks the
96/// device. This is used to encrypt keys that use the UnlockedDeviceRequired key parameter.
97pub const USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY: SuperKeyType = SuperKeyType {
Paul Crowley8d5b2532021-03-19 10:53:07 -070098 alias: "USER_SCREEN_LOCK_BOUND_KEY",
99 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +0000100 name: "UnlockedDeviceRequired symmetric super key",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700101};
Eric Biggers6745f532023-10-27 03:55:28 +0000102
Eric Biggersb1f641d2023-10-18 01:54:18 +0000103/// The user's UnlockedDeviceRequired asymmetric super key. This is used to allow, while the device
104/// is locked, the creation of keys that use the UnlockedDeviceRequired key parameter. The private
105/// part of this key is loaded and cleared when the symmetric key is loaded and cleared.
106pub const USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY: SuperKeyType = SuperKeyType {
Paul Crowley52f017f2021-06-22 08:16:01 -0700107 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
108 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Eric Biggers6745f532023-10-27 03:55:28 +0000109 name: "UnlockedDeviceRequired asymmetric super key",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700110};
Paul Crowley7a658392021-03-18 17:08:20 -0700111
112/// Superencryption to apply to a new key.
113#[derive(Debug, Clone, Copy)]
114pub enum SuperEncryptionType {
115 /// Do not superencrypt this key.
116 None,
Eric Biggers673d34a2023-10-18 01:54:18 +0000117 /// Superencrypt with the AfterFirstUnlock super key.
118 AfterFirstUnlock,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000119 /// Superencrypt with an UnlockedDeviceRequired super key.
120 UnlockedDeviceRequired,
Paul Crowley44c02da2021-04-08 17:04:43 +0000121 /// Superencrypt with a key based on the desired boot level
122 BootLevel(i32),
123}
124
125#[derive(Debug, Clone, Copy)]
126pub enum SuperKeyIdentifier {
127 /// id of the super key in the database.
128 DatabaseId(i64),
129 /// Boot level of the encrypting boot level key
130 BootLevel(i32),
131}
132
133impl SuperKeyIdentifier {
134 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
135 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
136 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000137 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700138 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000139 }
140 }
141
142 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
143 match self {
144 SuperKeyIdentifier::DatabaseId(id) => {
145 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
146 }
147 SuperKeyIdentifier::BootLevel(level) => {
148 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
149 }
150 }
151 }
Paul Crowley7a658392021-03-18 17:08:20 -0700152}
153
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000154pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700155 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700156 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000157 /// Identifier of the encrypting key, used to write an encrypted blob
158 /// back to the database after re-encryption eg on a key update.
159 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700160 /// ECDH is more expensive than AES. So on ECDH private keys we set the
161 /// reencrypt_with field to point at the corresponding AES key, and the
162 /// keys will be re-encrypted with AES on first use.
163 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000164}
165
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800166impl AesGcm for SuperKey {
167 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700168 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000169 aes_gcm_decrypt(data, iv, tag, &self.key).context(ks_err!("Decryption failed."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700170 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000171 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800172 }
173 }
174
175 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
176 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000177 aes_gcm_encrypt(plaintext, &self.key).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800178 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000179 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700180 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000181 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700182}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000183
Paul Crowley618869e2021-04-08 20:30:54 -0700184/// A SuperKey that has been encrypted with an AES-GCM key. For
185/// encryption the key is in memory, and for decryption it is in KM.
186struct LockedKey {
187 algorithm: SuperEncryptionAlgorithm,
188 id: SuperKeyIdentifier,
189 nonce: Vec<u8>,
190 ciphertext: Vec<u8>, // with tag appended
191}
192
193impl LockedKey {
194 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
195 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
196 ciphertext.append(&mut tag);
197 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
198 }
199
200 fn decrypt(
201 &self,
202 db: &mut KeystoreDB,
203 km_dev: &KeyMintDevice,
204 key_id_guard: &KeyIdGuard,
205 key_entry: &KeyEntry,
206 auth_token: &HardwareAuthToken,
207 reencrypt_with: Option<Arc<SuperKey>>,
208 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700209 let key_blob = key_entry
210 .key_blob_info()
211 .as_ref()
212 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
213 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000214 .context(ks_err!("Missing key blob info."))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700215 let key_params = vec![
216 KeyParameterValue::Algorithm(Algorithm::AES),
217 KeyParameterValue::KeySize(256),
218 KeyParameterValue::BlockMode(BlockMode::GCM),
219 KeyParameterValue::PaddingMode(PaddingMode::NONE),
220 KeyParameterValue::Nonce(self.nonce.clone()),
221 KeyParameterValue::MacLength(128),
222 ];
223 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
224 let key = ZVec::try_from(km_dev.use_key_in_one_step(
225 db,
226 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700227 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700228 KeyPurpose::DECRYPT,
229 &key_params,
230 Some(auth_token),
231 &self.ciphertext,
232 )?)?;
233 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
234 }
235}
236
Eric Biggersb1f641d2023-10-18 01:54:18 +0000237/// A user's UnlockedDeviceRequired super keys, encrypted with a biometric-bound key, and
238/// information about that biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700239struct BiometricUnlock {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000240 /// List of auth token SIDs that are accepted by the encrypting biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700241 sids: Vec<i64>,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000242 /// Key descriptor of the encrypting biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700243 key_desc: KeyDescriptor,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000244 /// The UnlockedDeviceRequired super keys, encrypted with a biometric-bound key.
245 symmetric: LockedKey,
246 private: LockedKey,
Paul Crowley618869e2021-04-08 20:30:54 -0700247}
248
Paul Crowleye8826e52021-03-31 08:33:53 -0700249#[derive(Default)]
250struct UserSuperKeys {
Eric Biggers673d34a2023-10-18 01:54:18 +0000251 /// The AfterFirstUnlock super key is used for LSKF binding of authentication bound keys. There
252 /// is one key per android user. The key is stored on flash encrypted with a key derived from a
253 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF). When the
254 /// user unlocks the device for the first time, this key is unlocked, i.e., decrypted, and stays
255 /// memory resident until the device reboots.
256 after_first_unlock: Option<Arc<SuperKey>>,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000257 /// The UnlockedDeviceRequired symmetric super key works like the AfterFirstUnlock super key
258 /// with the distinction that it is cleared from memory when the device is locked.
259 unlocked_device_required_symmetric: Option<Arc<SuperKey>>,
260 /// When the device is locked, keys that use the UnlockedDeviceRequired key parameter can still
261 /// be created, using ECDH public-key encryption. This field holds the decryption private key.
262 unlocked_device_required_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700263 /// Versions of the above two keys, locked behind a biometric.
264 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000265}
266
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800267#[derive(Default)]
268struct SkmState {
269 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700270 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800271 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700272}
273
274impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000275 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
276 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
277 self.key_index.insert(id, Arc::downgrade(super_key));
278 Ok(())
279 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000280 Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000281 }
Paul Crowley7a658392021-03-18 17:08:20 -0700282 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800283}
284
285#[derive(Default)]
286pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800287 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800288}
289
290impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800291 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
292 let mut skm_guard = skm.write().unwrap();
293 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000294 log::info!("In set_up_boot_level_cache: called for a second time");
295 return Ok(());
296 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000297 let level_zero_key =
298 get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800299 skm_guard.data.boot_level_key_cache =
300 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000301 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800302 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000303 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800304 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000305 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
306 });
307 Ok(())
308 }
309
310 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
311 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800312 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000313 let mut w = PropertyWatcher::new("keystore.boot_level")
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000314 .context(ks_err!("PropertyWatcher::new failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000315 loop {
316 let level = w
317 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000318 .context(ks_err!("read of property failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800319
320 // This scope limits the skm_guard life, so we don't hold the skm_guard while
321 // waiting.
322 {
323 let mut skm_guard = skm.write().unwrap();
324 let boot_level_key_cache = skm_guard
325 .data
326 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000327 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800328 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000329 .context(ks_err!("Boot level cache not initialized"))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800330 .get_mut()
331 .unwrap();
332 if level < MAX_MAX_BOOT_LEVEL {
333 log::info!("Read keystore.boot_level value {}", level);
334 boot_level_key_cache
335 .advance_boot_level(level)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000336 .context(ks_err!("advance_boot_level failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800337 } else {
338 log::info!(
339 "keystore.boot_level {} hits maximum {}, finishing.",
340 level,
341 MAX_MAX_BOOT_LEVEL
342 );
343 boot_level_key_cache.finish();
344 break;
345 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000346 }
Andrew Walbran48fa9702023-05-10 15:19:30 +0000347 w.wait(None).context(ks_err!("property wait failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000348 }
349 Ok(())
350 }
351
352 pub fn level_accessible(&self, boot_level: i32) -> bool {
353 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000354 .boot_level_key_cache
355 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800356 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000357 }
358
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800359 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
360 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800361 }
362
Eric Biggers673d34a2023-10-18 01:54:18 +0000363 fn install_after_first_unlock_key_for_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800364 &mut self,
365 user: UserId,
366 super_key: Arc<SuperKey>,
367 ) -> Result<()> {
368 self.data
369 .add_key_to_key_index(&super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000370 .context(ks_err!("add_key_to_key_index failed"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000371 self.data.user_keys.entry(user).or_default().after_first_unlock = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000372 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800373 }
374
Paul Crowley44c02da2021-04-08 17:04:43 +0000375 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000376 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800377 SuperKeyIdentifier::DatabaseId(id) => {
378 self.data.key_index.get(id).and_then(|k| k.upgrade())
379 }
380 SuperKeyIdentifier::BootLevel(level) => self
381 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000382 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800383 .as_ref()
384 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000385 .transpose()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000386 .context(ks_err!("aes_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000387 .flatten()
388 .map(|key| {
389 Arc::new(SuperKey {
390 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
391 key,
392 id: *key_id,
393 reencrypt_with: None,
394 })
395 }),
396 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800397 }
398
Eric Biggers673d34a2023-10-18 01:54:18 +0000399 /// Returns the AfterFirstUnlock superencryption key for the given user ID, or None if the user
400 /// has not yet unlocked the device since boot.
401 pub fn get_after_first_unlock_key_by_user_id(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800402 &self,
403 user_id: UserId,
404 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
Eric Biggers673d34a2023-10-18 01:54:18 +0000405 self.get_after_first_unlock_key_by_user_id_internal(user_id)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800406 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
407 }
408
Eric Biggers673d34a2023-10-18 01:54:18 +0000409 fn get_after_first_unlock_key_by_user_id_internal(
410 &self,
411 user_id: UserId,
412 ) -> Option<Arc<SuperKey>> {
413 self.data.user_keys.get(&user_id).and_then(|e| e.after_first_unlock.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800414 }
415
Paul Crowley44c02da2021-04-08 17:04:43 +0000416 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
417 /// the relevant super key.
418 pub fn unwrap_key_if_required<'a>(
419 &self,
420 metadata: &BlobMetaData,
421 blob: &'a [u8],
422 ) -> Result<KeyBlob<'a>> {
423 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
424 let super_key = self
425 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000426 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000427 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000428 .context(ks_err!("Required super decryption key is not in memory."))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000429 KeyBlob::Sensitive {
430 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000431 .context(ks_err!("unwrap_key_with_key failed"))?,
Paul Crowley44c02da2021-04-08 17:04:43 +0000432 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
433 force_reencrypt: super_key.reencrypt_with.is_some(),
434 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700435 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000436 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700437 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800438 }
439
440 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700441 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700442 match key.algorithm {
443 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000444 (Some(iv), Some(tag)) => {
445 key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
446 }
447 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
448 "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700449 iv.is_some(),
450 tag.is_some(),
451 )),
452 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700453 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700454 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
455 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
456 ECDHPrivateKey::from_private_key(&key.key)
457 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000458 .context(ks_err!("Failed to decrypt the key blob with ECDH."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700459 }
460 (public_key, salt, iv, aead_tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000461 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700462 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000463 "Key has incomplete metadata. ",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700464 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
465 ),
466 public_key.is_some(),
467 salt.is_some(),
468 iv.is_some(),
469 aead_tag.is_some(),
470 ))
471 }
472 }
473 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800474 }
475 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000476
477 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800478 /// The reference to self is unused but it is required to prevent calling this function
479 /// concurrently with skm state database changes.
480 fn super_key_exists_in_db_for_user(
481 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000482 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800483 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700484 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000485 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000486 let key_in_db = db
Eric Biggers673d34a2023-10-18 01:54:18 +0000487 .key_exists(
488 Domain::APP,
489 user_id as u64 as i64,
490 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
491 KeyType::Super,
492 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000493 .context(ks_err!())?;
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000494
495 if key_in_db {
496 Ok(key_in_db)
497 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000498 legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000499 }
500 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000501
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800502 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000503 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800504 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700505 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700506 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000507 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700508 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700509 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700510 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000511 .context(ks_err!("Failed to extract super key from key entry"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000512 self.install_after_first_unlock_key_for_user(user_id, super_key.clone())
513 .context(ks_err!("Failed to install AfterFirstUnlock super key for user!"))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000514 Ok(super_key)
515 }
516
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800517 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700518 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700519 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700520 entry: KeyEntry,
521 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700522 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700523 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000524 if let Some((blob, metadata)) = entry.key_blob_info() {
525 let key = match (
526 metadata.encrypted_by(),
527 metadata.salt(),
528 metadata.iv(),
529 metadata.aead_tag(),
530 ) {
531 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800532 // Note that password encryption is AES no matter the value of algorithm.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000533 let key = pw
534 .derive_key(salt, AES_256_KEY_LENGTH)
535 .context(ks_err!("Failed to generate key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000536
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000537 aes_gcm_decrypt(blob, iv, tag, &key)
538 .context(ks_err!("Failed to decrypt key blob."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +0000539 }
540 (enc_by, salt, iv, tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000541 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Hasini Gunasingheda895552021-01-27 19:34:37 +0000542 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000543 "Super key has incomplete metadata.",
544 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
545 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700546 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000547 salt.is_some(),
548 iv.is_some(),
549 tag.is_some()
550 ));
551 }
552 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000553 Ok(Arc::new(SuperKey {
554 algorithm,
555 key,
556 id: SuperKeyIdentifier::DatabaseId(entry.id()),
557 reencrypt_with,
558 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000559 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000560 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000561 }
562 }
563
564 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700565 pub fn encrypt_with_password(
566 super_key: &[u8],
567 pw: &Password,
568 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000569 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700570 let derived_key = pw
David Drysdale6a0ec2c2022-04-19 08:11:18 +0100571 .derive_key(&salt, AES_256_KEY_LENGTH)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000572 .context(ks_err!("Failed to derive password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000573 let mut metadata = BlobMetaData::new();
574 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
575 metadata.add(BlobMetaEntry::Salt(salt));
576 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000577 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000578 metadata.add(BlobMetaEntry::Iv(iv));
579 metadata.add(BlobMetaEntry::AeadTag(tag));
580 Ok((encrypted_key, metadata))
581 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000582
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800583 // Helper function to encrypt a key with the given super key. Callers should select which super
584 // key to be used. This is called when a key is super encrypted at its creation as well as at
585 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700586 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000587 key_blob: &[u8],
588 super_key: &SuperKey,
589 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700590 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000591 return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
Paul Crowley8d5b2532021-03-19 10:53:07 -0700592 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000593 let mut metadata = BlobMetaData::new();
594 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000595 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000596 metadata.add(BlobMetaEntry::Iv(iv));
597 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000598 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000599 Ok((encrypted_key, metadata))
600 }
601
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000602 // Encrypts a given key_blob using a hybrid approach, which can either use the symmetric super
603 // key or the public super key depending on which is available.
604 //
605 // If the symmetric_key is available, the key_blob is encrypted using symmetric encryption with
606 // the provided symmetric super key. Otherwise, the function loads the public super key from
607 // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be
608 // re-encrypted with the symmetric super key on the first use.
609 //
Eric Biggersb1f641d2023-10-18 01:54:18 +0000610 // This hybrid scheme allows keys that use the UnlockedDeviceRequired key parameter to be
611 // created while the device is locked.
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000612 fn encrypt_with_hybrid_super_key(
613 key_blob: &[u8],
614 symmetric_key: Option<&SuperKey>,
615 public_key_type: &SuperKeyType,
616 db: &mut KeystoreDB,
617 user_id: UserId,
618 ) -> Result<(Vec<u8>, BlobMetaData)> {
619 if let Some(super_key) = symmetric_key {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000620 Self::encrypt_with_aes_super_key(key_blob, super_key).context(ks_err!(
621 "Failed to encrypt with UnlockedDeviceRequired symmetric super key."
622 ))
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000623 } else {
624 // Symmetric key is not available, use public key encryption
625 let loaded = db
626 .load_super_key(public_key_type, user_id)
627 .context(ks_err!("load_super_key failed."))?;
628 let (key_id_guard, key_entry) =
629 loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH super key missing."))?;
630 let public_key = key_entry
631 .metadata()
632 .sec1_public_key()
633 .ok_or_else(Error::sys)
634 .context(ks_err!("sec1_public_key missing."))?;
635 let mut metadata = BlobMetaData::new();
636 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
637 ECDHPrivateKey::encrypt_message(public_key, key_blob)
638 .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
639 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
640 metadata.add(BlobMetaEntry::Salt(salt));
641 metadata.add(BlobMetaEntry::Iv(iv));
642 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
643 SuperKeyIdentifier::DatabaseId(key_id_guard.id()).add_to_metadata(&mut metadata);
644 Ok((encrypted_key, metadata))
645 }
646 }
647
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000648 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
649 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700650 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000651 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000652 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000653 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800654 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000655 domain: &Domain,
656 key_parameters: &[KeyParameter],
657 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700658 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000659 key_blob: &[u8],
660 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700661 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
662 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Eric Biggers673d34a2023-10-18 01:54:18 +0000663 SuperEncryptionType::AfterFirstUnlock => {
664 // Encrypt the given key blob with the user's AfterFirstUnlock super key. If the
665 // user has not unlocked the device since boot or has no LSKF, an error is returned.
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000666 match self
667 .get_user_state(db, legacy_importer, user_id)
David Drysdalee85523f2023-06-19 12:28:53 +0100668 .context(ks_err!("Failed to get user state for user {user_id}"))?
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000669 {
Eric Biggers673d34a2023-10-18 01:54:18 +0000670 UserState::AfterFirstUnlock(super_key) => {
671 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(ks_err!(
672 "Failed to encrypt with AfterFirstUnlock super key for user {user_id}"
673 ))
674 }
Eric Biggers13869372023-10-18 01:54:18 +0000675 UserState::BeforeFirstUnlock => {
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000676 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
677 }
678 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
David Drysdalee85523f2023-06-19 12:28:53 +0100679 .context(ks_err!("LSKF is not setup for user {user_id}")),
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000680 }
681 }
Eric Biggersb1f641d2023-10-18 01:54:18 +0000682 SuperEncryptionType::UnlockedDeviceRequired => {
683 let symmetric_key = self
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000684 .data
685 .user_keys
686 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000687 .and_then(|e| e.unlocked_device_required_symmetric.as_ref())
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000688 .map(|arc| arc.as_ref());
689 Self::encrypt_with_hybrid_super_key(
690 key_blob,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000691 symmetric_key,
692 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000693 db,
694 user_id,
695 )
Eric Biggersb1f641d2023-10-18 01:54:18 +0000696 .context(ks_err!("Failed to encrypt with UnlockedDeviceRequired hybrid scheme."))
Paul Crowley7a658392021-03-18 17:08:20 -0700697 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000698 SuperEncryptionType::BootLevel(level) => {
699 let key_id = SuperKeyIdentifier::BootLevel(level);
700 let super_key = self
701 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000702 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000703 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000704 .context(ks_err!("Boot stage key absent"))?;
705 Self::encrypt_with_aes_super_key(key_blob, &super_key)
706 .context(ks_err!("Failed to encrypt with BootLevel key."))
Paul Crowley44c02da2021-04-08 17:04:43 +0000707 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000708 }
709 }
710
711 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
712 /// If so, re-super-encrypt the key and return a new set of metadata,
713 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700714 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000715 key_blob_before_upgrade: &KeyBlob,
716 key_after_upgrade: &'a [u8],
717 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
718 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700719 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700720 let (key, metadata) =
721 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000722 .context(ks_err!("Failed to re-super-encrypt key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000723 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
724 }
725 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
726 }
727 }
728
Eric Biggers456a3a62023-10-27 03:55:28 +0000729 fn create_super_key(
730 &mut self,
731 db: &mut KeystoreDB,
732 user_id: UserId,
733 key_type: &SuperKeyType,
734 password: &Password,
735 reencrypt_with: Option<Arc<SuperKey>>,
736 ) -> Result<Arc<SuperKey>> {
Eric Biggers6745f532023-10-27 03:55:28 +0000737 log::info!("Creating {} for user {}", key_type.name, user_id);
Eric Biggers456a3a62023-10-27 03:55:28 +0000738 let (super_key, public_key) = match key_type.algorithm {
739 SuperEncryptionAlgorithm::Aes256Gcm => {
740 (generate_aes256_key().context(ks_err!("Failed to generate AES-256 key."))?, None)
741 }
742 SuperEncryptionAlgorithm::EcdhP521 => {
743 let key =
744 ECDHPrivateKey::generate().context(ks_err!("Failed to generate ECDH key"))?;
745 (
746 key.private_key().context(ks_err!("private_key failed"))?,
747 Some(key.public_key().context(ks_err!("public_key failed"))?),
748 )
749 }
750 };
751 // Derive an AES-256 key from the password and re-encrypt the super key before we insert it
752 // in the database.
753 let (encrypted_super_key, blob_metadata) =
754 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
755 let mut key_metadata = KeyMetaData::new();
756 if let Some(pk) = public_key {
757 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
758 }
759 let key_entry = db
760 .store_super_key(user_id, key_type, &encrypted_super_key, &blob_metadata, &key_metadata)
761 .context(ks_err!("Failed to store super key."))?;
762 Ok(Arc::new(SuperKey {
763 algorithm: key_type.algorithm,
764 key: super_key,
765 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
766 reencrypt_with,
767 }))
768 }
769
Paul Crowley7a658392021-03-18 17:08:20 -0700770 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
771 /// When this is called, the caller must hold the lock on the SuperKeyManager.
772 /// So it's OK that the check and creation are different DB transactions.
773 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800774 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700775 db: &mut KeystoreDB,
776 user_id: UserId,
777 key_type: &SuperKeyType,
778 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700779 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700780 ) -> Result<Arc<SuperKey>> {
781 let loaded_key = db.load_super_key(key_type, user_id)?;
782 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700783 Ok(Self::extract_super_key_from_key_entry(
784 key_type.algorithm,
785 key_entry,
786 password,
787 reencrypt_with,
788 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700789 } else {
Eric Biggers456a3a62023-10-27 03:55:28 +0000790 self.create_super_key(db, user_id, key_type, password, reencrypt_with)
Paul Crowley7a658392021-03-18 17:08:20 -0700791 }
792 }
793
Eric Biggersb1f641d2023-10-18 01:54:18 +0000794 /// Decrypt the UnlockedDeviceRequired super keys for this user using the password and store
795 /// them in memory. If these keys don't exist yet, create them.
796 pub fn unlock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800797 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700798 db: &mut KeystoreDB,
799 user_id: UserId,
800 password: &Password,
801 ) -> Result<()> {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000802 let (symmetric, private) = self
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800803 .data
804 .user_keys
805 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000806 .map(|e| {
807 (
808 e.unlocked_device_required_symmetric.clone(),
809 e.unlocked_device_required_private.clone(),
810 )
811 })
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800812 .unwrap_or((None, None));
813
Eric Biggersb1f641d2023-10-18 01:54:18 +0000814 if symmetric.is_some() && private.is_some() {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800815 // Already unlocked.
816 return Ok(());
817 }
818
Eric Biggersb1f641d2023-10-18 01:54:18 +0000819 let aes = if let Some(symmetric) = symmetric {
820 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
821 // keys was initialized. This should never happen.
822 symmetric
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800823 } else {
824 self.get_or_create_super_key(
825 db,
826 user_id,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000827 &USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY,
828 password,
829 None,
830 )
831 .context(ks_err!("Trying to get or create symmetric key."))?
832 };
833
834 let ecdh = if let Some(private) = private {
835 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
836 // keys was initialized. This should never happen.
837 private
838 } else {
839 self.get_or_create_super_key(
840 db,
841 user_id,
842 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800843 password,
844 Some(aes.clone()),
845 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000846 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800847 };
848
849 self.data.add_key_to_key_index(&aes)?;
850 self.data.add_key_to_key_index(&ecdh)?;
851 let entry = self.data.user_keys.entry(user_id).or_default();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000852 entry.unlocked_device_required_symmetric = Some(aes);
853 entry.unlocked_device_required_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700854 Ok(())
855 }
856
Eric Biggersb1f641d2023-10-18 01:54:18 +0000857 /// Wipe the user's UnlockedDeviceRequired super keys from memory.
858 pub fn lock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800859 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700860 db: &mut KeystoreDB,
861 user_id: UserId,
862 unlocking_sids: &[i64],
863 ) {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000864 log::info!(
865 "Locking UnlockedDeviceRequired super keys for user {}; unlocking_sids={:?}",
866 user_id,
867 unlocking_sids
868 );
Chris Wailes53a22af2023-07-12 17:02:47 -0700869 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700870 if !unlocking_sids.is_empty() {
871 if let (Some(aes), Some(ecdh)) = (
Eric Biggersb1f641d2023-10-18 01:54:18 +0000872 entry.unlocked_device_required_symmetric.as_ref().cloned(),
873 entry.unlocked_device_required_private.as_ref().cloned(),
Paul Crowley618869e2021-04-08 20:30:54 -0700874 ) {
875 let res = (|| -> Result<()> {
876 let key_desc = KeyMintDevice::internal_descriptor(format!(
877 "biometric_unlock_key_{}",
878 user_id
879 ));
880 let encrypting_key = generate_aes256_key()?;
881 let km_dev: KeyMintDevice =
882 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000883 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700884 let mut key_params = vec![
885 KeyParameterValue::Algorithm(Algorithm::AES),
886 KeyParameterValue::KeySize(256),
887 KeyParameterValue::BlockMode(BlockMode::GCM),
888 KeyParameterValue::PaddingMode(PaddingMode::NONE),
889 KeyParameterValue::CallerNonce,
890 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
891 KeyParameterValue::MinMacLength(128),
892 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
893 KeyParameterValue::HardwareAuthenticatorType(
894 HardwareAuthenticatorType::FINGERPRINT,
895 ),
896 ];
897 for sid in unlocking_sids {
898 key_params.push(KeyParameterValue::UserSecureID(*sid));
899 }
900 let key_params: Vec<KmKeyParameter> =
901 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700902 km_dev.create_and_store_key(
903 db,
904 &key_desc,
905 KeyType::Client, /* TODO Should be Super b/189470584 */
906 |dev| {
907 let _wp = wd::watch_millis(
Eric Biggersb1f641d2023-10-18 01:54:18 +0000908 "In lock_unlocked_device_required_keys: calling importKey.",
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700909 500,
910 );
911 dev.importKey(
912 key_params.as_slice(),
913 KeyFormat::RAW,
914 &encrypting_key,
915 None,
916 )
917 },
918 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700919 entry.biometric_unlock = Some(BiometricUnlock {
920 sids: unlocking_sids.into(),
921 key_desc,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000922 symmetric: LockedKey::new(&encrypting_key, &aes)?,
923 private: LockedKey::new(&encrypting_key, &ecdh)?,
Paul Crowley618869e2021-04-08 20:30:54 -0700924 });
925 Ok(())
926 })();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000927 // There is no reason to propagate an error here upwards. We must clear the keys
928 // from memory in any case.
Paul Crowley618869e2021-04-08 20:30:54 -0700929 if let Err(e) = res {
930 log::error!("Error setting up biometric unlock: {:#?}", e);
931 }
932 }
933 }
Eric Biggersb1f641d2023-10-18 01:54:18 +0000934 entry.unlocked_device_required_symmetric = None;
935 entry.unlocked_device_required_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700936 }
Paul Crowley618869e2021-04-08 20:30:54 -0700937
938 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
939 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
940 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800941 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700942 db: &mut KeystoreDB,
943 user_id: UserId,
944 ) -> Result<()> {
Chris Wailes53a22af2023-07-12 17:02:47 -0700945 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700946 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700947 let (key_id_guard, key_entry) = db
948 .load_key_entry(
949 &biometric.key_desc,
950 KeyType::Client, // This should not be a Client key.
951 KeyEntryLoadBits::KM,
952 AID_KEYSTORE,
953 |_, _| Ok(()),
954 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000955 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700956 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000957 .context(ks_err!("KeyMintDevice::get failed"))?;
David Drysdalee85523f2023-06-19 12:28:53 +0100958 let mut errs = vec![];
Paul Crowley618869e2021-04-08 20:30:54 -0700959 for sid in &biometric.sids {
David Drysdalee85523f2023-06-19 12:28:53 +0100960 let sid = *sid;
Paul Crowley618869e2021-04-08 20:30:54 -0700961 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
David Drysdalee85523f2023-06-19 12:28:53 +0100962 entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700963 }) {
Paul Crowley618869e2021-04-08 20:30:54 -0700964 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000965 let symmetric = biometric.symmetric.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -0700966 db,
967 &km_dev,
968 &key_id_guard,
969 &key_entry,
970 auth_token_entry.auth_token(),
971 None,
972 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +0000973 let private = biometric.private.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -0700974 db,
975 &km_dev,
976 &key_id_guard,
977 &key_entry,
978 auth_token_entry.auth_token(),
Eric Biggersb1f641d2023-10-18 01:54:18 +0000979 Some(symmetric.clone()),
Paul Crowley618869e2021-04-08 20:30:54 -0700980 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +0000981 Ok((symmetric, private))
Paul Crowley618869e2021-04-08 20:30:54 -0700982 })();
983 match res {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000984 Ok((symmetric, private)) => {
985 entry.unlocked_device_required_symmetric = Some(symmetric.clone());
986 entry.unlocked_device_required_private = Some(private.clone());
987 self.data.add_key_to_key_index(&symmetric)?;
988 self.data.add_key_to_key_index(&private)?;
David Drysdalee85523f2023-06-19 12:28:53 +0100989 log::info!("Successfully unlocked user {user_id} with biometric {sid}",);
Paul Crowley618869e2021-04-08 20:30:54 -0700990 return Ok(());
991 }
992 Err(e) => {
David Drysdalee85523f2023-06-19 12:28:53 +0100993 // Don't log an error yet, as some other biometric SID might work.
994 errs.push((sid, e));
Paul Crowley618869e2021-04-08 20:30:54 -0700995 }
996 }
997 }
998 }
David Drysdalee85523f2023-06-19 12:28:53 +0100999 if !errs.is_empty() {
1000 log::warn!("biometric unlock failed for all SIDs, with errors:");
1001 for (sid, err) in errs {
1002 log::warn!(" biometric {sid}: {err}");
1003 }
1004 }
Paul Crowley618869e2021-04-08 20:30:54 -07001005 }
1006 Ok(())
1007 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001008
1009 /// Returns the keystore locked state of the given user. It requires the thread local
1010 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001011 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001012 pub fn get_user_state(
1013 &self,
1014 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001015 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001016 user_id: UserId,
1017 ) -> Result<UserState> {
Eric Biggers673d34a2023-10-18 01:54:18 +00001018 match self.get_after_first_unlock_key_by_user_id_internal(user_id) {
Eric Biggers13869372023-10-18 01:54:18 +00001019 Some(super_key) => Ok(UserState::AfterFirstUnlock(super_key)),
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001020 None => {
1021 // Check if a super key exists in the database or legacy database.
1022 // If so, return locked user state.
1023 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001024 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001025 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001026 {
Eric Biggers13869372023-10-18 01:54:18 +00001027 Ok(UserState::BeforeFirstUnlock)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001028 } else {
1029 Ok(UserState::Uninitialized)
1030 }
1031 }
1032 }
1033 }
1034
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001035 /// Deletes all keys and super keys for the given user.
1036 /// This is called when a user is deleted.
1037 pub fn remove_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001038 &mut self,
1039 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001040 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001041 user_id: UserId,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001042 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001043 log::info!("remove_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001044 // Mark keys created on behalf of the user as unreferenced.
1045 legacy_importer
1046 .bulk_delete_user(user_id, false)
1047 .context(ks_err!("Trying to delete legacy keys."))?;
1048 db.unbind_keys_for_user(user_id, false).context(ks_err!("Error in unbinding keys."))?;
1049
1050 // Delete super key in cache, if exists.
1051 self.forget_all_keys_for_user(user_id);
1052 Ok(())
1053 }
1054
1055 /// Deletes all authentication bound keys and super keys for the given user. The user must be
1056 /// unlocked before this function is called. This function is used to transition a user to
1057 /// swipe.
1058 pub fn reset_user(
1059 &mut self,
1060 db: &mut KeystoreDB,
1061 legacy_importer: &LegacyImporter,
1062 user_id: UserId,
1063 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001064 log::info!("reset_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001065 match self.get_user_state(db, legacy_importer, user_id)? {
1066 UserState::Uninitialized => {
1067 Err(Error::sys()).context(ks_err!("Tried to reset an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001068 }
Eric Biggers13869372023-10-18 01:54:18 +00001069 UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001070 Err(Error::sys()).context(ks_err!("Tried to reset a locked user's password!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001071 }
Eric Biggers13869372023-10-18 01:54:18 +00001072 UserState::AfterFirstUnlock(_) => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001073 // Mark keys created on behalf of the user as unreferenced.
1074 legacy_importer
1075 .bulk_delete_user(user_id, true)
1076 .context(ks_err!("Trying to delete legacy keys."))?;
1077 db.unbind_keys_for_user(user_id, true)
1078 .context(ks_err!("Error in unbinding keys."))?;
1079
1080 // Delete super key in cache, if exists.
1081 self.forget_all_keys_for_user(user_id);
1082 Ok(())
1083 }
1084 }
1085 }
1086
Eric Biggers673d34a2023-10-18 01:54:18 +00001087 /// If the user hasn't been initialized yet, then this function generates the user's
1088 /// AfterFirstUnlock super key and sets the user's state to AfterFirstUnlock. Otherwise this
1089 /// function returns an error.
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001090 pub fn init_user(
1091 &mut self,
1092 db: &mut KeystoreDB,
1093 legacy_importer: &LegacyImporter,
1094 user_id: UserId,
1095 password: &Password,
1096 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001097 log::info!("init_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001098 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001099 UserState::AfterFirstUnlock(_) | UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001100 Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"))
1101 }
1102 UserState::Uninitialized => {
1103 // Generate a new super key.
1104 let super_key =
1105 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
1106 // Derive an AES256 key from the password and re-encrypt the super key
1107 // before we insert it in the database.
1108 let (encrypted_super_key, blob_metadata) =
1109 Self::encrypt_with_password(&super_key, password)
1110 .context(ks_err!("Failed to encrypt super key with password!"))?;
1111
1112 let key_entry = db
1113 .store_super_key(
1114 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001115 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001116 &encrypted_super_key,
1117 &blob_metadata,
1118 &KeyMetaData::new(),
1119 )
1120 .context(ks_err!("Failed to store super key."))?;
1121
1122 self.populate_cache_from_super_key_blob(
1123 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001124 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001125 key_entry,
1126 password,
1127 )
1128 .context(ks_err!("Failed to initialize user!"))?;
1129 Ok(())
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001130 }
1131 }
1132 }
1133
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001134 /// Unlocks the given user with the given password.
1135 ///
Eric Biggers13869372023-10-18 01:54:18 +00001136 /// If the user state is BeforeFirstUnlock:
Eric Biggers673d34a2023-10-18 01:54:18 +00001137 /// - Unlock the user's AfterFirstUnlock super key
Eric Biggersb1f641d2023-10-18 01:54:18 +00001138 /// - Unlock the user's UnlockedDeviceRequired super keys
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001139 ///
Eric Biggers13869372023-10-18 01:54:18 +00001140 /// If the user state is AfterFirstUnlock:
Eric Biggersb1f641d2023-10-18 01:54:18 +00001141 /// - Unlock the user's UnlockedDeviceRequired super keys only
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001142 ///
1143 pub fn unlock_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001144 &mut self,
1145 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001146 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001147 user_id: UserId,
1148 password: &Password,
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001149 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001150 log::info!("unlock_user(user={user_id})");
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001151 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001152 UserState::AfterFirstUnlock(_) => {
Eric Biggersb1f641d2023-10-18 01:54:18 +00001153 self.unlock_unlocked_device_required_keys(db, user_id, password)
Eric Biggers13869372023-10-18 01:54:18 +00001154 }
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001155 UserState::Uninitialized => {
1156 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001157 }
Eric Biggers13869372023-10-18 01:54:18 +00001158 UserState::BeforeFirstUnlock => {
Eric Biggers673d34a2023-10-18 01:54:18 +00001159 let alias = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001160 let result = legacy_importer
1161 .with_try_import_super_key(user_id, password, || {
1162 db.load_super_key(alias, user_id)
1163 })
1164 .context(ks_err!("Failed to load super key"))?;
1165
1166 match result {
1167 Some((_, entry)) => {
1168 self.populate_cache_from_super_key_blob(
1169 user_id,
1170 alias.algorithm,
1171 entry,
1172 password,
1173 )
1174 .context(ks_err!("Failed when unlocking user."))?;
Eric Biggersb1f641d2023-10-18 01:54:18 +00001175 self.unlock_unlocked_device_required_keys(db, user_id, password)
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001176 }
1177 None => {
1178 Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))
1179 }
1180 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001181 }
1182 }
1183 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001184}
1185
1186/// This enum represents different states of the user's life cycle in the device.
1187/// For now, only three states are defined. More states may be added later.
1188pub enum UserState {
1189 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
Eric Biggers673d34a2023-10-18 01:54:18 +00001190 // and hence the AfterFirstUnlock super key is available in the cache.
Eric Biggers13869372023-10-18 01:54:18 +00001191 AfterFirstUnlock(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001192 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
Eric Biggers673d34a2023-10-18 01:54:18 +00001193 // Hence the AfterFirstUnlock and UnlockedDeviceRequired super keys are not available in the
1194 // cache. However, they exist in the database in encrypted form.
Eric Biggers13869372023-10-18 01:54:18 +00001195 BeforeFirstUnlock,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001196 // There's no user in the device for the given user id, or the user with the user id has not
1197 // setup LSKF.
1198 Uninitialized,
1199}
1200
Janis Danisevskiseed69842021-02-18 20:04:10 -08001201/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1202/// `Sensitive` holds the non encrypted key and a reference to its super key.
1203/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1204/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1205/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001206pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001207 Sensitive {
1208 key: ZVec,
1209 /// If KeyMint reports that the key must be upgraded, we must
1210 /// re-encrypt the key before writing to the database; we use
1211 /// this key.
1212 reencrypt_with: Arc<SuperKey>,
1213 /// If this key was decrypted with an ECDH key, we want to
1214 /// re-encrypt it on first use whether it was upgraded or not;
1215 /// this field indicates that that's necessary.
1216 force_reencrypt: bool,
1217 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001218 NonSensitive(Vec<u8>),
1219 Ref(&'a [u8]),
1220}
1221
Paul Crowley8d5b2532021-03-19 10:53:07 -07001222impl<'a> KeyBlob<'a> {
1223 pub fn force_reencrypt(&self) -> bool {
1224 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1225 *force_reencrypt
1226 } else {
1227 false
1228 }
1229 }
1230}
1231
Janis Danisevskiseed69842021-02-18 20:04:10 -08001232/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001233impl<'a> Deref for KeyBlob<'a> {
1234 type Target = [u8];
1235
1236 fn deref(&self) -> &Self::Target {
1237 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001238 Self::Sensitive { key, .. } => key,
1239 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001240 Self::Ref(key) => key,
1241 }
1242 }
1243}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001244
1245#[cfg(test)]
1246mod tests {
1247 use super::*;
1248 use crate::database::tests::make_bootlevel_key_entry;
1249 use crate::database::tests::make_test_key_entry;
1250 use crate::database::tests::new_test_db;
1251 use rand::prelude::*;
1252 const USER_ID: u32 = 0;
1253 const TEST_KEY_ALIAS: &str = "TEST_KEY";
1254 const TEST_BOOT_KEY_ALIAS: &str = "TEST_BOOT_KEY";
1255
1256 pub fn generate_password_blob() -> Password<'static> {
1257 let mut rng = rand::thread_rng();
1258 let mut password = vec![0u8; 64];
1259 rng.fill_bytes(&mut password);
1260
1261 let mut zvec = ZVec::new(64).expect("Failed to create ZVec");
1262 zvec[..].copy_from_slice(&password[..]);
1263
1264 Password::Owned(zvec)
1265 }
1266
1267 fn setup_test(pw: &Password) -> (Arc<RwLock<SuperKeyManager>>, KeystoreDB, LegacyImporter) {
1268 let mut keystore_db = new_test_db().unwrap();
1269 let mut legacy_importer = LegacyImporter::new(Arc::new(Default::default()));
1270 legacy_importer.set_empty();
1271 let skm: Arc<RwLock<SuperKeyManager>> = Default::default();
1272 assert!(skm
1273 .write()
1274 .unwrap()
1275 .init_user(&mut keystore_db, &legacy_importer, USER_ID, pw)
1276 .is_ok());
1277 (skm, keystore_db, legacy_importer)
1278 }
1279
1280 fn assert_unlocked(
1281 skm: &Arc<RwLock<SuperKeyManager>>,
1282 keystore_db: &mut KeystoreDB,
1283 legacy_importer: &LegacyImporter,
1284 user_id: u32,
1285 err_msg: &str,
1286 ) {
1287 let user_state =
1288 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1289 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001290 UserState::AfterFirstUnlock(_) => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001291 _ => panic!("{}", err_msg),
1292 }
1293 }
1294
1295 fn assert_locked(
1296 skm: &Arc<RwLock<SuperKeyManager>>,
1297 keystore_db: &mut KeystoreDB,
1298 legacy_importer: &LegacyImporter,
1299 user_id: u32,
1300 err_msg: &str,
1301 ) {
1302 let user_state =
1303 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1304 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001305 UserState::BeforeFirstUnlock => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001306 _ => panic!("{}", err_msg),
1307 }
1308 }
1309
1310 fn assert_uninitialized(
1311 skm: &Arc<RwLock<SuperKeyManager>>,
1312 keystore_db: &mut KeystoreDB,
1313 legacy_importer: &LegacyImporter,
1314 user_id: u32,
1315 err_msg: &str,
1316 ) {
1317 let user_state =
1318 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1319 match user_state {
1320 UserState::Uninitialized => {}
1321 _ => panic!("{}", err_msg),
1322 }
1323 }
1324
1325 #[test]
1326 fn test_init_user() {
1327 let pw: Password = generate_password_blob();
1328 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1329 assert_unlocked(
1330 &skm,
1331 &mut keystore_db,
1332 &legacy_importer,
1333 USER_ID,
1334 "The user was not unlocked after initialization!",
1335 );
1336 }
1337
1338 #[test]
1339 fn test_unlock_user() {
1340 let pw: Password = generate_password_blob();
1341 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1342 assert_unlocked(
1343 &skm,
1344 &mut keystore_db,
1345 &legacy_importer,
1346 USER_ID,
1347 "The user was not unlocked after initialization!",
1348 );
1349
1350 skm.write().unwrap().data.user_keys.clear();
1351 assert_locked(
1352 &skm,
1353 &mut keystore_db,
1354 &legacy_importer,
1355 USER_ID,
1356 "Clearing the cache did not lock the user!",
1357 );
1358
1359 assert!(skm
1360 .write()
1361 .unwrap()
1362 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1363 .is_ok());
1364 assert_unlocked(
1365 &skm,
1366 &mut keystore_db,
1367 &legacy_importer,
1368 USER_ID,
1369 "The user did not unlock!",
1370 );
1371 }
1372
1373 #[test]
1374 fn test_unlock_wrong_password() {
1375 let pw: Password = generate_password_blob();
1376 let wrong_pw: Password = generate_password_blob();
1377 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1378 assert_unlocked(
1379 &skm,
1380 &mut keystore_db,
1381 &legacy_importer,
1382 USER_ID,
1383 "The user was not unlocked after initialization!",
1384 );
1385
1386 skm.write().unwrap().data.user_keys.clear();
1387 assert_locked(
1388 &skm,
1389 &mut keystore_db,
1390 &legacy_importer,
1391 USER_ID,
1392 "Clearing the cache did not lock the user!",
1393 );
1394
1395 assert!(skm
1396 .write()
1397 .unwrap()
1398 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &wrong_pw)
1399 .is_err());
1400 assert_locked(
1401 &skm,
1402 &mut keystore_db,
1403 &legacy_importer,
1404 USER_ID,
1405 "The user was unlocked with an incorrect password!",
1406 );
1407 }
1408
1409 #[test]
1410 fn test_unlock_user_idempotent() {
1411 let pw: Password = generate_password_blob();
1412 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1413 assert_unlocked(
1414 &skm,
1415 &mut keystore_db,
1416 &legacy_importer,
1417 USER_ID,
1418 "The user was not unlocked after initialization!",
1419 );
1420
1421 skm.write().unwrap().data.user_keys.clear();
1422 assert_locked(
1423 &skm,
1424 &mut keystore_db,
1425 &legacy_importer,
1426 USER_ID,
1427 "Clearing the cache did not lock the user!",
1428 );
1429
1430 for _ in 0..5 {
1431 assert!(skm
1432 .write()
1433 .unwrap()
1434 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1435 .is_ok());
1436 assert_unlocked(
1437 &skm,
1438 &mut keystore_db,
1439 &legacy_importer,
1440 USER_ID,
1441 "The user did not unlock!",
1442 );
1443 }
1444 }
1445
1446 fn test_user_removal(locked: bool) {
1447 let pw: Password = generate_password_blob();
1448 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1449 assert_unlocked(
1450 &skm,
1451 &mut keystore_db,
1452 &legacy_importer,
1453 USER_ID,
1454 "The user was not unlocked after initialization!",
1455 );
1456
1457 assert!(make_test_key_entry(
1458 &mut keystore_db,
1459 Domain::APP,
1460 USER_ID.into(),
1461 TEST_KEY_ALIAS,
1462 None
1463 )
1464 .is_ok());
1465 assert!(make_bootlevel_key_entry(
1466 &mut keystore_db,
1467 Domain::APP,
1468 USER_ID.into(),
1469 TEST_BOOT_KEY_ALIAS,
1470 false
1471 )
1472 .is_ok());
1473
1474 assert!(keystore_db
1475 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1476 .unwrap());
1477 assert!(keystore_db
1478 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1479 .unwrap());
1480
1481 if locked {
1482 skm.write().unwrap().data.user_keys.clear();
1483 assert_locked(
1484 &skm,
1485 &mut keystore_db,
1486 &legacy_importer,
1487 USER_ID,
1488 "Clearing the cache did not lock the user!",
1489 );
1490 }
1491
1492 assert!(skm
1493 .write()
1494 .unwrap()
1495 .remove_user(&mut keystore_db, &legacy_importer, USER_ID)
1496 .is_ok());
1497 assert_uninitialized(
1498 &skm,
1499 &mut keystore_db,
1500 &legacy_importer,
1501 USER_ID,
1502 "The user was not removed!",
1503 );
1504
1505 assert!(!skm
1506 .write()
1507 .unwrap()
1508 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1509 .unwrap());
1510
1511 assert!(!keystore_db
1512 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1513 .unwrap());
1514 assert!(!keystore_db
1515 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1516 .unwrap());
1517 }
1518
1519 fn test_user_reset(locked: bool) {
1520 let pw: Password = generate_password_blob();
1521 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1522 assert_unlocked(
1523 &skm,
1524 &mut keystore_db,
1525 &legacy_importer,
1526 USER_ID,
1527 "The user was not unlocked after initialization!",
1528 );
1529
1530 assert!(make_test_key_entry(
1531 &mut keystore_db,
1532 Domain::APP,
1533 USER_ID.into(),
1534 TEST_KEY_ALIAS,
1535 None
1536 )
1537 .is_ok());
1538 assert!(make_bootlevel_key_entry(
1539 &mut keystore_db,
1540 Domain::APP,
1541 USER_ID.into(),
1542 TEST_BOOT_KEY_ALIAS,
1543 false
1544 )
1545 .is_ok());
1546 assert!(keystore_db
1547 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1548 .unwrap());
1549 assert!(keystore_db
1550 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1551 .unwrap());
1552
1553 if locked {
1554 skm.write().unwrap().data.user_keys.clear();
1555 assert_locked(
1556 &skm,
1557 &mut keystore_db,
1558 &legacy_importer,
1559 USER_ID,
1560 "Clearing the cache did not lock the user!",
1561 );
1562 assert!(skm
1563 .write()
1564 .unwrap()
1565 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1566 .is_err());
1567 assert_locked(
1568 &skm,
1569 &mut keystore_db,
1570 &legacy_importer,
1571 USER_ID,
1572 "User state should not have changed!",
1573 );
1574
1575 // Keys should still exist.
1576 assert!(keystore_db
1577 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1578 .unwrap());
1579 assert!(keystore_db
1580 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1581 .unwrap());
1582 } else {
1583 assert!(skm
1584 .write()
1585 .unwrap()
1586 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1587 .is_ok());
1588 assert_uninitialized(
1589 &skm,
1590 &mut keystore_db,
1591 &legacy_importer,
1592 USER_ID,
1593 "The user was not reset!",
1594 );
1595 assert!(!skm
1596 .write()
1597 .unwrap()
1598 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1599 .unwrap());
1600
1601 // Auth bound key should no longer exist.
1602 assert!(!keystore_db
1603 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1604 .unwrap());
1605 assert!(keystore_db
1606 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1607 .unwrap());
1608 }
1609 }
1610
1611 #[test]
1612 fn test_remove_unlocked_user() {
1613 test_user_removal(false);
1614 }
1615
1616 #[test]
1617 fn test_remove_locked_user() {
1618 test_user_removal(true);
1619 }
1620
1621 #[test]
1622 fn test_reset_unlocked_user() {
1623 test_user_reset(false);
1624 }
1625
1626 #[test]
1627 fn test_reset_locked_user() {
1628 test_user_reset(true);
1629 }
1630}