blob: 42fd7645c8bbc8b83adc11d41046a5b7409a3205 [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
David Drysdale2566fb32024-07-09 14:46:37 +010055#[cfg(test)]
56mod tests;
57
Paul Crowley44c02da2021-04-08 17:04:43 +000058const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
Paul Crowley618869e2021-04-08 20:30:54 -070059/// Allow up to 15 seconds between the user unlocking using a biometric, and the auth
60/// token being used to unlock in [`SuperKeyManager::try_unlock_user_with_biometric`].
61/// This seems short enough for security purposes, while long enough that even the
62/// very slowest device will present the auth token in time.
63const BIOMETRIC_AUTH_TIMEOUT_S: i32 = 15; // seconds
Paul Crowley44c02da2021-04-08 17:04:43 +000064
Janis Danisevskisb42fc182020-12-15 08:41:27 -080065type UserId = u32;
66
Paul Crowley8d5b2532021-03-19 10:53:07 -070067/// Encryption algorithm used by a particular type of superencryption key
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum SuperEncryptionAlgorithm {
70 /// Symmetric encryption with AES-256-GCM
71 Aes256Gcm,
Paul Crowley52f017f2021-06-22 08:16:01 -070072 /// Public-key encryption with ECDH P-521
73 EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -070074}
75
Paul Crowley7a658392021-03-18 17:08:20 -070076/// A particular user may have several superencryption keys in the database, each for a
77/// different purpose, distinguished by alias. Each is associated with a static
78/// constant of this type.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080079pub struct SuperKeyType<'a> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080080 /// Alias used to look up the key in the `persistent.keyentry` table.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080081 pub alias: &'a str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070082 /// Encryption algorithm
83 pub algorithm: SuperEncryptionAlgorithm,
Eric Biggers6745f532023-10-27 03:55:28 +000084 /// What to call this key in log messages. Not used for anything else.
85 pub name: &'a str,
Paul Crowley7a658392021-03-18 17:08:20 -070086}
87
Eric Biggers673d34a2023-10-18 01:54:18 +000088/// The user's AfterFirstUnlock super key. This super key is loaded into memory when the user first
89/// unlocks the device, and it remains in memory until the device reboots. This is used to encrypt
90/// keys that require user authentication but not an unlocked device.
Eric Biggers6745f532023-10-27 03:55:28 +000091pub const USER_AFTER_FIRST_UNLOCK_SUPER_KEY: SuperKeyType = SuperKeyType {
92 alias: "USER_SUPER_KEY",
93 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
94 name: "AfterFirstUnlock super key",
95};
96
Eric Biggersb1f641d2023-10-18 01:54:18 +000097/// The user's UnlockedDeviceRequired symmetric super key. This super key is loaded into memory each
98/// time the user unlocks the device, and it is cleared from memory each time the user locks the
99/// device. This is used to encrypt keys that use the UnlockedDeviceRequired key parameter.
100pub const USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY: SuperKeyType = SuperKeyType {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700101 alias: "USER_SCREEN_LOCK_BOUND_KEY",
102 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +0000103 name: "UnlockedDeviceRequired symmetric super key",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700104};
Eric Biggers6745f532023-10-27 03:55:28 +0000105
Eric Biggersb1f641d2023-10-18 01:54:18 +0000106/// The user's UnlockedDeviceRequired asymmetric super key. This is used to allow, while the device
107/// is locked, the creation of keys that use the UnlockedDeviceRequired key parameter. The private
108/// part of this key is loaded and cleared when the symmetric key is loaded and cleared.
109pub const USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY: SuperKeyType = SuperKeyType {
Paul Crowley52f017f2021-06-22 08:16:01 -0700110 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
111 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Eric Biggers6745f532023-10-27 03:55:28 +0000112 name: "UnlockedDeviceRequired asymmetric super key",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700113};
Paul Crowley7a658392021-03-18 17:08:20 -0700114
115/// Superencryption to apply to a new key.
116#[derive(Debug, Clone, Copy)]
117pub enum SuperEncryptionType {
118 /// Do not superencrypt this key.
119 None,
Eric Biggers673d34a2023-10-18 01:54:18 +0000120 /// Superencrypt with the AfterFirstUnlock super key.
121 AfterFirstUnlock,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000122 /// Superencrypt with an UnlockedDeviceRequired super key.
123 UnlockedDeviceRequired,
Paul Crowley44c02da2021-04-08 17:04:43 +0000124 /// Superencrypt with a key based on the desired boot level
125 BootLevel(i32),
126}
127
128#[derive(Debug, Clone, Copy)]
129pub enum SuperKeyIdentifier {
130 /// id of the super key in the database.
131 DatabaseId(i64),
132 /// Boot level of the encrypting boot level key
133 BootLevel(i32),
134}
135
136impl SuperKeyIdentifier {
137 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
138 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
139 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000140 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700141 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000142 }
143 }
144
145 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
146 match self {
147 SuperKeyIdentifier::DatabaseId(id) => {
148 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
149 }
150 SuperKeyIdentifier::BootLevel(level) => {
151 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
152 }
153 }
154 }
Paul Crowley7a658392021-03-18 17:08:20 -0700155}
156
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000157pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700158 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700159 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000160 /// Identifier of the encrypting key, used to write an encrypted blob
161 /// back to the database after re-encryption eg on a key update.
162 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700163 /// ECDH is more expensive than AES. So on ECDH private keys we set the
164 /// reencrypt_with field to point at the corresponding AES key, and the
165 /// keys will be re-encrypted with AES on first use.
166 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000167}
168
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800169impl AesGcm for SuperKey {
170 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700171 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000172 aes_gcm_decrypt(data, iv, tag, &self.key).context(ks_err!("Decryption failed."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700173 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000174 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800175 }
176 }
177
178 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
179 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000180 aes_gcm_encrypt(plaintext, &self.key).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800181 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000182 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700183 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000184 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700185}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000186
Paul Crowley618869e2021-04-08 20:30:54 -0700187/// A SuperKey that has been encrypted with an AES-GCM key. For
188/// encryption the key is in memory, and for decryption it is in KM.
189struct LockedKey {
190 algorithm: SuperEncryptionAlgorithm,
191 id: SuperKeyIdentifier,
192 nonce: Vec<u8>,
193 ciphertext: Vec<u8>, // with tag appended
194}
195
196impl LockedKey {
197 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
198 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
199 ciphertext.append(&mut tag);
200 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
201 }
202
203 fn decrypt(
204 &self,
205 db: &mut KeystoreDB,
206 km_dev: &KeyMintDevice,
207 key_id_guard: &KeyIdGuard,
208 key_entry: &KeyEntry,
209 auth_token: &HardwareAuthToken,
210 reencrypt_with: Option<Arc<SuperKey>>,
211 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700212 let key_blob = key_entry
213 .key_blob_info()
214 .as_ref()
215 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
216 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000217 .context(ks_err!("Missing key blob info."))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700218 let key_params = vec![
219 KeyParameterValue::Algorithm(Algorithm::AES),
220 KeyParameterValue::KeySize(256),
221 KeyParameterValue::BlockMode(BlockMode::GCM),
222 KeyParameterValue::PaddingMode(PaddingMode::NONE),
223 KeyParameterValue::Nonce(self.nonce.clone()),
224 KeyParameterValue::MacLength(128),
225 ];
226 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
227 let key = ZVec::try_from(km_dev.use_key_in_one_step(
228 db,
229 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700230 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700231 KeyPurpose::DECRYPT,
232 &key_params,
233 Some(auth_token),
234 &self.ciphertext,
235 )?)?;
236 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
237 }
238}
239
Eric Biggersb1f641d2023-10-18 01:54:18 +0000240/// A user's UnlockedDeviceRequired super keys, encrypted with a biometric-bound key, and
241/// information about that biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700242struct BiometricUnlock {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000243 /// List of auth token SIDs that are accepted by the encrypting biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700244 sids: Vec<i64>,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000245 /// Key descriptor of the encrypting biometric-bound key.
Paul Crowley618869e2021-04-08 20:30:54 -0700246 key_desc: KeyDescriptor,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000247 /// The UnlockedDeviceRequired super keys, encrypted with a biometric-bound key.
248 symmetric: LockedKey,
249 private: LockedKey,
Paul Crowley618869e2021-04-08 20:30:54 -0700250}
251
Paul Crowleye8826e52021-03-31 08:33:53 -0700252#[derive(Default)]
253struct UserSuperKeys {
Eric Biggersb0478cf2023-10-27 03:55:29 +0000254 /// The AfterFirstUnlock super key is used for synthetic password binding of authentication
255 /// bound keys. There is one key per android user. The key is stored on flash encrypted with a
256 /// key derived from a secret, that is itself derived from the user's synthetic password. (In
257 /// most cases, the user's synthetic password can, in turn, only be decrypted using the user's
258 /// Lock Screen Knowledge Factor or LSKF.) When the user unlocks the device for the first time,
259 /// this key is unlocked, i.e., decrypted, and stays memory resident until the device reboots.
Eric Biggers673d34a2023-10-18 01:54:18 +0000260 after_first_unlock: Option<Arc<SuperKey>>,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000261 /// The UnlockedDeviceRequired symmetric super key works like the AfterFirstUnlock super key
262 /// with the distinction that it is cleared from memory when the device is locked.
263 unlocked_device_required_symmetric: Option<Arc<SuperKey>>,
264 /// When the device is locked, keys that use the UnlockedDeviceRequired key parameter can still
265 /// be created, using ECDH public-key encryption. This field holds the decryption private key.
266 unlocked_device_required_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700267 /// Versions of the above two keys, locked behind a biometric.
268 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000269}
270
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800271#[derive(Default)]
272struct SkmState {
273 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700274 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800275 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700276}
277
278impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000279 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
280 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
281 self.key_index.insert(id, Arc::downgrade(super_key));
282 Ok(())
283 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000284 Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000285 }
Paul Crowley7a658392021-03-18 17:08:20 -0700286 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800287}
288
289#[derive(Default)]
290pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800291 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800292}
293
294impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800295 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
296 let mut skm_guard = skm.write().unwrap();
297 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000298 log::info!("In set_up_boot_level_cache: called for a second time");
299 return Ok(());
300 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000301 let level_zero_key =
302 get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800303 skm_guard.data.boot_level_key_cache =
304 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000305 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800306 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000307 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800308 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000309 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
310 });
311 Ok(())
312 }
313
314 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
315 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800316 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000317 let mut w = PropertyWatcher::new("keystore.boot_level")
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000318 .context(ks_err!("PropertyWatcher::new failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000319 loop {
320 let level = w
321 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000322 .context(ks_err!("read of property failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800323
324 // This scope limits the skm_guard life, so we don't hold the skm_guard while
325 // waiting.
326 {
327 let mut skm_guard = skm.write().unwrap();
328 let boot_level_key_cache = skm_guard
329 .data
330 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000331 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800332 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000333 .context(ks_err!("Boot level cache not initialized"))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800334 .get_mut()
335 .unwrap();
336 if level < MAX_MAX_BOOT_LEVEL {
337 log::info!("Read keystore.boot_level value {}", level);
338 boot_level_key_cache
339 .advance_boot_level(level)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000340 .context(ks_err!("advance_boot_level failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800341 } else {
342 log::info!(
343 "keystore.boot_level {} hits maximum {}, finishing.",
344 level,
345 MAX_MAX_BOOT_LEVEL
346 );
347 boot_level_key_cache.finish();
348 break;
349 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000350 }
Andrew Walbran48fa9702023-05-10 15:19:30 +0000351 w.wait(None).context(ks_err!("property wait failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000352 }
353 Ok(())
354 }
355
356 pub fn level_accessible(&self, boot_level: i32) -> bool {
357 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000358 .boot_level_key_cache
359 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800360 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000361 }
362
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800363 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
364 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800365 }
366
Eric Biggers673d34a2023-10-18 01:54:18 +0000367 fn install_after_first_unlock_key_for_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800368 &mut self,
369 user: UserId,
370 super_key: Arc<SuperKey>,
371 ) -> Result<()> {
372 self.data
373 .add_key_to_key_index(&super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000374 .context(ks_err!("add_key_to_key_index failed"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000375 self.data.user_keys.entry(user).or_default().after_first_unlock = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000376 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800377 }
378
Paul Crowley44c02da2021-04-08 17:04:43 +0000379 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000380 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800381 SuperKeyIdentifier::DatabaseId(id) => {
382 self.data.key_index.get(id).and_then(|k| k.upgrade())
383 }
384 SuperKeyIdentifier::BootLevel(level) => self
385 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000386 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800387 .as_ref()
388 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000389 .transpose()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000390 .context(ks_err!("aes_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000391 .flatten()
392 .map(|key| {
393 Arc::new(SuperKey {
394 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
395 key,
396 id: *key_id,
397 reencrypt_with: None,
398 })
399 }),
400 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800401 }
402
Eric Biggers673d34a2023-10-18 01:54:18 +0000403 /// Returns the AfterFirstUnlock superencryption key for the given user ID, or None if the user
404 /// has not yet unlocked the device since boot.
405 pub fn get_after_first_unlock_key_by_user_id(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800406 &self,
407 user_id: UserId,
408 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
Eric Biggers673d34a2023-10-18 01:54:18 +0000409 self.get_after_first_unlock_key_by_user_id_internal(user_id)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800410 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
411 }
412
Eric Biggers673d34a2023-10-18 01:54:18 +0000413 fn get_after_first_unlock_key_by_user_id_internal(
414 &self,
415 user_id: UserId,
416 ) -> Option<Arc<SuperKey>> {
417 self.data.user_keys.get(&user_id).and_then(|e| e.after_first_unlock.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800418 }
419
Paul Crowley44c02da2021-04-08 17:04:43 +0000420 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
421 /// the relevant super key.
422 pub fn unwrap_key_if_required<'a>(
423 &self,
424 metadata: &BlobMetaData,
425 blob: &'a [u8],
426 ) -> Result<KeyBlob<'a>> {
427 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
428 let super_key = self
429 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000430 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000431 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000432 .context(ks_err!("Required super decryption key is not in memory."))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000433 KeyBlob::Sensitive {
434 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000435 .context(ks_err!("unwrap_key_with_key failed"))?,
Paul Crowley44c02da2021-04-08 17:04:43 +0000436 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
437 force_reencrypt: super_key.reencrypt_with.is_some(),
438 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700439 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000440 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700441 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800442 }
443
444 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700445 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700446 match key.algorithm {
447 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000448 (Some(iv), Some(tag)) => {
449 key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
450 }
451 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
452 "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700453 iv.is_some(),
454 tag.is_some(),
455 )),
456 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700457 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700458 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
459 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
460 ECDHPrivateKey::from_private_key(&key.key)
461 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000462 .context(ks_err!("Failed to decrypt the key blob with ECDH."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700463 }
464 (public_key, salt, iv, aead_tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000465 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700466 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000467 "Key has incomplete metadata. ",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700468 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
469 ),
470 public_key.is_some(),
471 salt.is_some(),
472 iv.is_some(),
473 aead_tag.is_some(),
474 ))
475 }
476 }
477 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800478 }
479 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000480
Eric Biggersb0478cf2023-10-27 03:55:29 +0000481 /// Checks if the user's AfterFirstUnlock super key exists in the database (or legacy database).
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800482 /// The reference to self is unused but it is required to prevent calling this function
483 /// concurrently with skm state database changes.
484 fn super_key_exists_in_db_for_user(
485 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000486 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800487 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700488 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000489 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000490 let key_in_db = db
Eric Biggers673d34a2023-10-18 01:54:18 +0000491 .key_exists(
492 Domain::APP,
493 user_id as u64 as i64,
494 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
495 KeyType::Super,
496 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000497 .context(ks_err!())?;
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000498
499 if key_in_db {
500 Ok(key_in_db)
501 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000502 legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000503 }
504 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000505
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800506 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000507 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800508 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700509 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700510 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000511 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700512 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700513 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700514 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000515 .context(ks_err!("Failed to extract super key from key entry"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000516 self.install_after_first_unlock_key_for_user(user_id, super_key.clone())
517 .context(ks_err!("Failed to install AfterFirstUnlock super key for user!"))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000518 Ok(super_key)
519 }
520
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800521 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700522 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700523 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700524 entry: KeyEntry,
525 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700526 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700527 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000528 if let Some((blob, metadata)) = entry.key_blob_info() {
529 let key = match (
530 metadata.encrypted_by(),
531 metadata.salt(),
532 metadata.iv(),
533 metadata.aead_tag(),
534 ) {
535 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800536 // Note that password encryption is AES no matter the value of algorithm.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000537 let key = pw
Eric Biggers6e5ccd72024-01-17 03:54:11 +0000538 .derive_key_hkdf(salt, AES_256_KEY_LENGTH)
539 .context(ks_err!("Failed to derive key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000540
Eric Biggers6e5ccd72024-01-17 03:54:11 +0000541 aes_gcm_decrypt(blob, iv, tag, &key).or_else(|_e| {
542 // Handle old key stored before the switch to HKDF.
543 let key = pw
544 .derive_key_pbkdf2(salt, AES_256_KEY_LENGTH)
545 .context(ks_err!("Failed to derive key from password (PBKDF2)."))?;
546 aes_gcm_decrypt(blob, iv, tag, &key)
547 .context(ks_err!("Failed to decrypt key blob."))
548 })?
Hasini Gunasingheda895552021-01-27 19:34:37 +0000549 }
550 (enc_by, salt, iv, tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000551 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Hasini Gunasingheda895552021-01-27 19:34:37 +0000552 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000553 "Super key has incomplete metadata.",
554 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
555 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700556 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000557 salt.is_some(),
558 iv.is_some(),
559 tag.is_some()
560 ));
561 }
562 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000563 Ok(Arc::new(SuperKey {
564 algorithm,
565 key,
566 id: SuperKeyIdentifier::DatabaseId(entry.id()),
567 reencrypt_with,
568 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000569 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000570 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000571 }
572 }
573
574 /// Encrypts the super key from a key derived from the password, before storing in the database.
Eric Biggers6e5ccd72024-01-17 03:54:11 +0000575 /// This does not stretch the password; i.e., it assumes that the password is a high-entropy
576 /// synthetic password, not a low-entropy user provided password.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700577 pub fn encrypt_with_password(
578 super_key: &[u8],
579 pw: &Password,
580 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000581 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Eric Biggers9f7ebeb2024-06-20 14:59:32 +0000582 let derived_key = pw
583 .derive_key_hkdf(&salt, AES_256_KEY_LENGTH)
584 .context(ks_err!("Failed to derive key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000585 let mut metadata = BlobMetaData::new();
586 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
587 metadata.add(BlobMetaEntry::Salt(salt));
588 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000589 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000590 metadata.add(BlobMetaEntry::Iv(iv));
591 metadata.add(BlobMetaEntry::AeadTag(tag));
592 Ok((encrypted_key, metadata))
593 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000594
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800595 // Helper function to encrypt a key with the given super key. Callers should select which super
596 // key to be used. This is called when a key is super encrypted at its creation as well as at
597 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700598 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000599 key_blob: &[u8],
600 super_key: &SuperKey,
601 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700602 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000603 return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
Paul Crowley8d5b2532021-03-19 10:53:07 -0700604 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000605 let mut metadata = BlobMetaData::new();
606 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000607 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000608 metadata.add(BlobMetaEntry::Iv(iv));
609 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000610 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000611 Ok((encrypted_key, metadata))
612 }
613
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000614 // Encrypts a given key_blob using a hybrid approach, which can either use the symmetric super
615 // key or the public super key depending on which is available.
616 //
617 // If the symmetric_key is available, the key_blob is encrypted using symmetric encryption with
618 // the provided symmetric super key. Otherwise, the function loads the public super key from
619 // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be
620 // re-encrypted with the symmetric super key on the first use.
621 //
Eric Biggersb1f641d2023-10-18 01:54:18 +0000622 // This hybrid scheme allows keys that use the UnlockedDeviceRequired key parameter to be
623 // created while the device is locked.
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000624 fn encrypt_with_hybrid_super_key(
625 key_blob: &[u8],
626 symmetric_key: Option<&SuperKey>,
627 public_key_type: &SuperKeyType,
628 db: &mut KeystoreDB,
629 user_id: UserId,
630 ) -> Result<(Vec<u8>, BlobMetaData)> {
631 if let Some(super_key) = symmetric_key {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000632 Self::encrypt_with_aes_super_key(key_blob, super_key).context(ks_err!(
633 "Failed to encrypt with UnlockedDeviceRequired symmetric super key."
634 ))
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000635 } else {
636 // Symmetric key is not available, use public key encryption
637 let loaded = db
638 .load_super_key(public_key_type, user_id)
639 .context(ks_err!("load_super_key failed."))?;
640 let (key_id_guard, key_entry) =
641 loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH super key missing."))?;
642 let public_key = key_entry
643 .metadata()
644 .sec1_public_key()
645 .ok_or_else(Error::sys)
646 .context(ks_err!("sec1_public_key missing."))?;
647 let mut metadata = BlobMetaData::new();
648 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
649 ECDHPrivateKey::encrypt_message(public_key, key_blob)
650 .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
651 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
652 metadata.add(BlobMetaEntry::Salt(salt));
653 metadata.add(BlobMetaEntry::Iv(iv));
654 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
655 SuperKeyIdentifier::DatabaseId(key_id_guard.id()).add_to_metadata(&mut metadata);
656 Ok((encrypted_key, metadata))
657 }
658 }
659
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000660 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
661 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700662 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000663 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000664 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000665 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800666 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000667 domain: &Domain,
668 key_parameters: &[KeyParameter],
669 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700670 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000671 key_blob: &[u8],
672 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700673 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
674 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Eric Biggers673d34a2023-10-18 01:54:18 +0000675 SuperEncryptionType::AfterFirstUnlock => {
676 // Encrypt the given key blob with the user's AfterFirstUnlock super key. If the
Eric Biggersb0478cf2023-10-27 03:55:29 +0000677 // user has not unlocked the device since boot or the super keys were never
678 // initialized for the user for some reason, an error is returned.
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000679 match self
680 .get_user_state(db, legacy_importer, user_id)
David Drysdalee85523f2023-06-19 12:28:53 +0100681 .context(ks_err!("Failed to get user state for user {user_id}"))?
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000682 {
Eric Biggers673d34a2023-10-18 01:54:18 +0000683 UserState::AfterFirstUnlock(super_key) => {
684 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(ks_err!(
685 "Failed to encrypt with AfterFirstUnlock super key for user {user_id}"
686 ))
687 }
Eric Biggers13869372023-10-18 01:54:18 +0000688 UserState::BeforeFirstUnlock => {
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000689 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
690 }
691 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
Eric Biggersb0478cf2023-10-27 03:55:29 +0000692 .context(ks_err!("User {user_id} does not have super keys")),
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000693 }
694 }
Eric Biggersb1f641d2023-10-18 01:54:18 +0000695 SuperEncryptionType::UnlockedDeviceRequired => {
696 let symmetric_key = self
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000697 .data
698 .user_keys
699 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000700 .and_then(|e| e.unlocked_device_required_symmetric.as_ref())
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000701 .map(|arc| arc.as_ref());
702 Self::encrypt_with_hybrid_super_key(
703 key_blob,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000704 symmetric_key,
705 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000706 db,
707 user_id,
708 )
Eric Biggersb1f641d2023-10-18 01:54:18 +0000709 .context(ks_err!("Failed to encrypt with UnlockedDeviceRequired hybrid scheme."))
Paul Crowley7a658392021-03-18 17:08:20 -0700710 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000711 SuperEncryptionType::BootLevel(level) => {
712 let key_id = SuperKeyIdentifier::BootLevel(level);
713 let super_key = self
714 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000715 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000716 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000717 .context(ks_err!("Boot stage key absent"))?;
718 Self::encrypt_with_aes_super_key(key_blob, &super_key)
719 .context(ks_err!("Failed to encrypt with BootLevel key."))
Paul Crowley44c02da2021-04-08 17:04:43 +0000720 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000721 }
722 }
723
724 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
725 /// If so, re-super-encrypt the key and return a new set of metadata,
726 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700727 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000728 key_blob_before_upgrade: &KeyBlob,
729 key_after_upgrade: &'a [u8],
730 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
731 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700732 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700733 let (key, metadata) =
734 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000735 .context(ks_err!("Failed to re-super-encrypt key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000736 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
737 }
738 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
739 }
740 }
741
Eric Biggers456a3a62023-10-27 03:55:28 +0000742 fn create_super_key(
743 &mut self,
744 db: &mut KeystoreDB,
745 user_id: UserId,
746 key_type: &SuperKeyType,
747 password: &Password,
748 reencrypt_with: Option<Arc<SuperKey>>,
749 ) -> Result<Arc<SuperKey>> {
Eric Biggers6745f532023-10-27 03:55:28 +0000750 log::info!("Creating {} for user {}", key_type.name, user_id);
Eric Biggers456a3a62023-10-27 03:55:28 +0000751 let (super_key, public_key) = match key_type.algorithm {
752 SuperEncryptionAlgorithm::Aes256Gcm => {
753 (generate_aes256_key().context(ks_err!("Failed to generate AES-256 key."))?, None)
754 }
755 SuperEncryptionAlgorithm::EcdhP521 => {
756 let key =
757 ECDHPrivateKey::generate().context(ks_err!("Failed to generate ECDH key"))?;
758 (
759 key.private_key().context(ks_err!("private_key failed"))?,
760 Some(key.public_key().context(ks_err!("public_key failed"))?),
761 )
762 }
763 };
764 // Derive an AES-256 key from the password and re-encrypt the super key before we insert it
765 // in the database.
766 let (encrypted_super_key, blob_metadata) =
767 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
768 let mut key_metadata = KeyMetaData::new();
769 if let Some(pk) = public_key {
770 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
771 }
772 let key_entry = db
773 .store_super_key(user_id, key_type, &encrypted_super_key, &blob_metadata, &key_metadata)
774 .context(ks_err!("Failed to store super key."))?;
775 Ok(Arc::new(SuperKey {
776 algorithm: key_type.algorithm,
777 key: super_key,
778 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
779 reencrypt_with,
780 }))
781 }
782
Paul Crowley7a658392021-03-18 17:08:20 -0700783 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
784 /// When this is called, the caller must hold the lock on the SuperKeyManager.
785 /// So it's OK that the check and creation are different DB transactions.
786 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800787 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700788 db: &mut KeystoreDB,
789 user_id: UserId,
790 key_type: &SuperKeyType,
791 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700792 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700793 ) -> Result<Arc<SuperKey>> {
794 let loaded_key = db.load_super_key(key_type, user_id)?;
795 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700796 Ok(Self::extract_super_key_from_key_entry(
797 key_type.algorithm,
798 key_entry,
799 password,
800 reencrypt_with,
801 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700802 } else {
Eric Biggers456a3a62023-10-27 03:55:28 +0000803 self.create_super_key(db, user_id, key_type, password, reencrypt_with)
Paul Crowley7a658392021-03-18 17:08:20 -0700804 }
805 }
806
Eric Biggersb1f641d2023-10-18 01:54:18 +0000807 /// Decrypt the UnlockedDeviceRequired super keys for this user using the password and store
808 /// them in memory. If these keys don't exist yet, create them.
809 pub fn unlock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800810 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700811 db: &mut KeystoreDB,
812 user_id: UserId,
813 password: &Password,
814 ) -> Result<()> {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000815 let (symmetric, private) = self
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800816 .data
817 .user_keys
818 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000819 .map(|e| {
820 (
821 e.unlocked_device_required_symmetric.clone(),
822 e.unlocked_device_required_private.clone(),
823 )
824 })
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800825 .unwrap_or((None, None));
826
Eric Biggersb1f641d2023-10-18 01:54:18 +0000827 if symmetric.is_some() && private.is_some() {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800828 // Already unlocked.
829 return Ok(());
830 }
831
Eric Biggersb1f641d2023-10-18 01:54:18 +0000832 let aes = if let Some(symmetric) = symmetric {
833 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
834 // keys was initialized. This should never happen.
835 symmetric
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800836 } else {
837 self.get_or_create_super_key(
838 db,
839 user_id,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000840 &USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY,
841 password,
842 None,
843 )
844 .context(ks_err!("Trying to get or create symmetric key."))?
845 };
846
847 let ecdh = if let Some(private) = private {
848 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
849 // keys was initialized. This should never happen.
850 private
851 } else {
852 self.get_or_create_super_key(
853 db,
854 user_id,
855 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800856 password,
857 Some(aes.clone()),
858 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000859 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800860 };
861
862 self.data.add_key_to_key_index(&aes)?;
863 self.data.add_key_to_key_index(&ecdh)?;
864 let entry = self.data.user_keys.entry(user_id).or_default();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000865 entry.unlocked_device_required_symmetric = Some(aes);
866 entry.unlocked_device_required_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700867 Ok(())
868 }
869
Eric Biggers6946daa2024-01-17 22:51:37 +0000870 /// Protects the user's UnlockedDeviceRequired super keys in a way such that they can only be
871 /// unlocked by the enabled unlock methods.
Eric Biggersb1f641d2023-10-18 01:54:18 +0000872 pub fn lock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800873 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700874 db: &mut KeystoreDB,
875 user_id: UserId,
876 unlocking_sids: &[i64],
Eric Biggers6946daa2024-01-17 22:51:37 +0000877 weak_unlock_enabled: bool,
Paul Crowley618869e2021-04-08 20:30:54 -0700878 ) {
Chris Wailes53a22af2023-07-12 17:02:47 -0700879 let entry = self.data.user_keys.entry(user_id).or_default();
Eric Biggers6946daa2024-01-17 22:51:37 +0000880 if unlocking_sids.is_empty() {
Eric Biggers9f7ebeb2024-06-20 14:59:32 +0000881 entry.biometric_unlock = None;
Eric Biggers6946daa2024-01-17 22:51:37 +0000882 } else if let (Some(aes), Some(ecdh)) = (
883 entry.unlocked_device_required_symmetric.as_ref().cloned(),
884 entry.unlocked_device_required_private.as_ref().cloned(),
885 ) {
886 // If class 3 biometric unlock methods are enabled, create a biometric-encrypted copy of
887 // the keys. Do this even if weak unlock methods are enabled too; in that case we'll
888 // also retain a plaintext copy of the keys, but that copy will be wiped later if weak
889 // unlock methods expire. So we need the biometric-encrypted copy too just in case.
890 let res = (|| -> Result<()> {
891 let key_desc =
892 KeyMintDevice::internal_descriptor(format!("biometric_unlock_key_{}", user_id));
893 let encrypting_key = generate_aes256_key()?;
894 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
895 .context(ks_err!("KeyMintDevice::get failed"))?;
896 let mut key_params = vec![
897 KeyParameterValue::Algorithm(Algorithm::AES),
898 KeyParameterValue::KeySize(256),
899 KeyParameterValue::BlockMode(BlockMode::GCM),
900 KeyParameterValue::PaddingMode(PaddingMode::NONE),
901 KeyParameterValue::CallerNonce,
902 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
903 KeyParameterValue::MinMacLength(128),
904 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
905 KeyParameterValue::HardwareAuthenticatorType(
906 HardwareAuthenticatorType::FINGERPRINT,
907 ),
908 ];
909 for sid in unlocking_sids {
910 key_params.push(KeyParameterValue::UserSecureID(*sid));
Paul Crowley618869e2021-04-08 20:30:54 -0700911 }
Eric Biggers6946daa2024-01-17 22:51:37 +0000912 let key_params: Vec<KmKeyParameter> =
913 key_params.into_iter().map(|x| x.into()).collect();
914 km_dev.create_and_store_key(
915 db,
916 &key_desc,
917 KeyType::Client, /* TODO Should be Super b/189470584 */
918 |dev| {
David Drysdale541846b2024-05-23 13:16:07 +0100919 let _wp =
David Drysdalec652f6c2024-07-18 13:01:23 +0100920 wd::watch("SKM::lock_unlocked_device_required_keys: calling IKeyMintDevice::importKey.");
Eric Biggers6946daa2024-01-17 22:51:37 +0000921 dev.importKey(key_params.as_slice(), KeyFormat::RAW, &encrypting_key, None)
922 },
923 )?;
924 entry.biometric_unlock = Some(BiometricUnlock {
925 sids: unlocking_sids.into(),
926 key_desc,
927 symmetric: LockedKey::new(&encrypting_key, &aes)?,
928 private: LockedKey::new(&encrypting_key, &ecdh)?,
929 });
930 Ok(())
931 })();
932 if let Err(e) = res {
933 log::error!("Error setting up biometric unlock: {:#?}", e);
934 // The caller can't do anything about the error, and for security reasons we still
935 // wipe the keys (unless a weak unlock method is enabled). So just log the error.
Paul Crowley618869e2021-04-08 20:30:54 -0700936 }
937 }
Eric Biggers6946daa2024-01-17 22:51:37 +0000938 // Wipe the plaintext copy of the keys, unless a weak unlock method is enabled.
939 if !weak_unlock_enabled {
940 entry.unlocked_device_required_symmetric = None;
941 entry.unlocked_device_required_private = None;
942 }
943 Self::log_status_of_unlocked_device_required_keys(user_id, entry);
944 }
945
946 pub fn wipe_plaintext_unlocked_device_required_keys(&mut self, user_id: UserId) {
947 let entry = self.data.user_keys.entry(user_id).or_default();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000948 entry.unlocked_device_required_symmetric = None;
949 entry.unlocked_device_required_private = None;
Eric Biggers6946daa2024-01-17 22:51:37 +0000950 Self::log_status_of_unlocked_device_required_keys(user_id, entry);
951 }
952
953 pub fn wipe_all_unlocked_device_required_keys(&mut self, user_id: UserId) {
954 let entry = self.data.user_keys.entry(user_id).or_default();
955 entry.unlocked_device_required_symmetric = None;
956 entry.unlocked_device_required_private = None;
957 entry.biometric_unlock = None;
958 Self::log_status_of_unlocked_device_required_keys(user_id, entry);
959 }
960
961 fn log_status_of_unlocked_device_required_keys(user_id: UserId, entry: &UserSuperKeys) {
962 let status = match (
963 // Note: the status of the symmetric and private keys should always be in sync.
964 // So we only check one here.
965 entry.unlocked_device_required_symmetric.is_some(),
966 entry.biometric_unlock.is_some(),
967 ) {
968 (false, false) => "fully protected",
969 (false, true) => "biometric-encrypted",
970 (true, false) => "retained in plaintext",
971 (true, true) => "retained in plaintext, with biometric-encrypted copy too",
972 };
973 log::info!("UnlockedDeviceRequired super keys for user {user_id} are {status}.");
Paul Crowley7a658392021-03-18 17:08:20 -0700974 }
Paul Crowley618869e2021-04-08 20:30:54 -0700975
976 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
977 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
978 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800979 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700980 db: &mut KeystoreDB,
981 user_id: UserId,
982 ) -> Result<()> {
Chris Wailes53a22af2023-07-12 17:02:47 -0700983 let entry = self.data.user_keys.entry(user_id).or_default();
Eric Biggers9f7ebeb2024-06-20 14:59:32 +0000984 if entry.unlocked_device_required_symmetric.is_some()
Eric Biggers6946daa2024-01-17 22:51:37 +0000985 && entry.unlocked_device_required_private.is_some()
986 {
987 // If the keys are already cached in plaintext, then there is no need to decrypt the
988 // biometric-encrypted copy. Both copies can be present here if the user has both
989 // class 3 biometric and weak unlock methods enabled, and the device was unlocked before
990 // the weak unlock methods expired.
991 return Ok(());
992 }
Paul Crowley618869e2021-04-08 20:30:54 -0700993 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700994 let (key_id_guard, key_entry) = db
995 .load_key_entry(
996 &biometric.key_desc,
997 KeyType::Client, // This should not be a Client key.
998 KeyEntryLoadBits::KM,
999 AID_KEYSTORE,
1000 |_, _| Ok(()),
1001 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001002 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -07001003 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001004 .context(ks_err!("KeyMintDevice::get failed"))?;
David Drysdalee85523f2023-06-19 12:28:53 +01001005 let mut errs = vec![];
Paul Crowley618869e2021-04-08 20:30:54 -07001006 for sid in &biometric.sids {
David Drysdalee85523f2023-06-19 12:28:53 +01001007 let sid = *sid;
Eric Biggersb5613da2024-03-13 19:31:42 +00001008 if let Some(auth_token_entry) = db.find_auth_token_entry(|entry| {
David Drysdalee85523f2023-06-19 12:28:53 +01001009 entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001010 }) {
Paul Crowley618869e2021-04-08 20:30:54 -07001011 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
Eric Biggersb1f641d2023-10-18 01:54:18 +00001012 let symmetric = biometric.symmetric.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -07001013 db,
1014 &km_dev,
1015 &key_id_guard,
1016 &key_entry,
1017 auth_token_entry.auth_token(),
1018 None,
1019 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +00001020 let private = biometric.private.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -07001021 db,
1022 &km_dev,
1023 &key_id_guard,
1024 &key_entry,
1025 auth_token_entry.auth_token(),
Eric Biggersb1f641d2023-10-18 01:54:18 +00001026 Some(symmetric.clone()),
Paul Crowley618869e2021-04-08 20:30:54 -07001027 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +00001028 Ok((symmetric, private))
Paul Crowley618869e2021-04-08 20:30:54 -07001029 })();
1030 match res {
Eric Biggersb1f641d2023-10-18 01:54:18 +00001031 Ok((symmetric, private)) => {
1032 entry.unlocked_device_required_symmetric = Some(symmetric.clone());
1033 entry.unlocked_device_required_private = Some(private.clone());
1034 self.data.add_key_to_key_index(&symmetric)?;
1035 self.data.add_key_to_key_index(&private)?;
David Drysdalee85523f2023-06-19 12:28:53 +01001036 log::info!("Successfully unlocked user {user_id} with biometric {sid}",);
Paul Crowley618869e2021-04-08 20:30:54 -07001037 return Ok(());
1038 }
1039 Err(e) => {
David Drysdalee85523f2023-06-19 12:28:53 +01001040 // Don't log an error yet, as some other biometric SID might work.
1041 errs.push((sid, e));
Paul Crowley618869e2021-04-08 20:30:54 -07001042 }
1043 }
1044 }
1045 }
David Drysdalee85523f2023-06-19 12:28:53 +01001046 if !errs.is_empty() {
1047 log::warn!("biometric unlock failed for all SIDs, with errors:");
1048 for (sid, err) in errs {
1049 log::warn!(" biometric {sid}: {err}");
1050 }
1051 }
Paul Crowley618869e2021-04-08 20:30:54 -07001052 }
1053 Ok(())
1054 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001055
1056 /// Returns the keystore locked state of the given user. It requires the thread local
1057 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001058 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001059 pub fn get_user_state(
1060 &self,
1061 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001062 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001063 user_id: UserId,
1064 ) -> Result<UserState> {
Eric Biggers673d34a2023-10-18 01:54:18 +00001065 match self.get_after_first_unlock_key_by_user_id_internal(user_id) {
Eric Biggers13869372023-10-18 01:54:18 +00001066 Some(super_key) => Ok(UserState::AfterFirstUnlock(super_key)),
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001067 None => {
1068 // Check if a super key exists in the database or legacy database.
1069 // If so, return locked user state.
1070 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001071 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001072 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001073 {
Eric Biggers13869372023-10-18 01:54:18 +00001074 Ok(UserState::BeforeFirstUnlock)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001075 } else {
1076 Ok(UserState::Uninitialized)
1077 }
1078 }
1079 }
1080 }
1081
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001082 /// Deletes all keys and super keys for the given user.
1083 /// This is called when a user is deleted.
1084 pub fn remove_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001085 &mut self,
1086 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001087 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001088 user_id: UserId,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001089 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001090 log::info!("remove_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001091 // Mark keys created on behalf of the user as unreferenced.
1092 legacy_importer
1093 .bulk_delete_user(user_id, false)
1094 .context(ks_err!("Trying to delete legacy keys."))?;
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00001095 db.unbind_keys_for_user(user_id).context(ks_err!("Error in unbinding keys."))?;
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001096
1097 // Delete super key in cache, if exists.
1098 self.forget_all_keys_for_user(user_id);
1099 Ok(())
1100 }
1101
Eric Biggersb0478cf2023-10-27 03:55:29 +00001102 /// Initializes the given user by creating their super keys, both AfterFirstUnlock and
1103 /// UnlockedDeviceRequired. If allow_existing is true, then the user already being initialized
1104 /// is not considered an error.
1105 pub fn initialize_user(
1106 &mut self,
1107 db: &mut KeystoreDB,
1108 legacy_importer: &LegacyImporter,
1109 user_id: UserId,
1110 password: &Password,
1111 allow_existing: bool,
1112 ) -> Result<()> {
1113 // Create the AfterFirstUnlock super key.
1114 if self.super_key_exists_in_db_for_user(db, legacy_importer, user_id)? {
1115 log::info!("AfterFirstUnlock super key already exists");
1116 if !allow_existing {
1117 return Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"));
1118 }
1119 } else {
1120 let super_key = self
1121 .create_super_key(db, user_id, &USER_AFTER_FIRST_UNLOCK_SUPER_KEY, password, None)
1122 .context(ks_err!("Failed to create AfterFirstUnlock super key"))?;
1123
1124 self.install_after_first_unlock_key_for_user(user_id, super_key)
1125 .context(ks_err!("Failed to install AfterFirstUnlock super key for user"))?;
1126 }
1127
1128 // Create the UnlockedDeviceRequired super keys.
1129 self.unlock_unlocked_device_required_keys(db, user_id, password)
1130 .context(ks_err!("Failed to create UnlockedDeviceRequired super keys"))
1131 }
1132
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001133 /// Unlocks the given user with the given password.
1134 ///
Eric Biggers13869372023-10-18 01:54:18 +00001135 /// If the user state is BeforeFirstUnlock:
Eric Biggers673d34a2023-10-18 01:54:18 +00001136 /// - Unlock the user's AfterFirstUnlock super key
Eric Biggersb1f641d2023-10-18 01:54:18 +00001137 /// - Unlock the user's UnlockedDeviceRequired super keys
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001138 ///
Eric Biggers13869372023-10-18 01:54:18 +00001139 /// If the user state is AfterFirstUnlock:
Eric Biggersb1f641d2023-10-18 01:54:18 +00001140 /// - Unlock the user's UnlockedDeviceRequired super keys only
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001141 ///
1142 pub fn unlock_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001143 &mut self,
1144 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001145 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001146 user_id: UserId,
1147 password: &Password,
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001148 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001149 log::info!("unlock_user(user={user_id})");
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001150 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001151 UserState::AfterFirstUnlock(_) => {
Eric Biggersb1f641d2023-10-18 01:54:18 +00001152 self.unlock_unlocked_device_required_keys(db, user_id, password)
Eric Biggers13869372023-10-18 01:54:18 +00001153 }
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001154 UserState::Uninitialized => {
1155 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001156 }
Eric Biggers13869372023-10-18 01:54:18 +00001157 UserState::BeforeFirstUnlock => {
Eric Biggers673d34a2023-10-18 01:54:18 +00001158 let alias = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001159 let result = legacy_importer
1160 .with_try_import_super_key(user_id, password, || {
1161 db.load_super_key(alias, user_id)
1162 })
1163 .context(ks_err!("Failed to load super key"))?;
1164
1165 match result {
1166 Some((_, entry)) => {
1167 self.populate_cache_from_super_key_blob(
1168 user_id,
1169 alias.algorithm,
1170 entry,
1171 password,
1172 )
1173 .context(ks_err!("Failed when unlocking user."))?;
Eric Biggersb1f641d2023-10-18 01:54:18 +00001174 self.unlock_unlocked_device_required_keys(db, user_id, password)
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001175 }
1176 None => {
1177 Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))
1178 }
1179 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001180 }
1181 }
1182 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001183}
1184
1185/// This enum represents different states of the user's life cycle in the device.
1186/// For now, only three states are defined. More states may be added later.
1187pub enum UserState {
Eric Biggersb0478cf2023-10-27 03:55:29 +00001188 // The user's super keys exist, and the user has unlocked the device at least once since boot.
1189 // Hence, the AfterFirstUnlock super key is available in the cache.
Eric Biggers13869372023-10-18 01:54:18 +00001190 AfterFirstUnlock(Arc<SuperKey>),
Eric Biggersb0478cf2023-10-27 03:55:29 +00001191 // The user's super keys exist, but the user hasn't unlocked the device at least once since
1192 // boot. Hence, the AfterFirstUnlock and UnlockedDeviceRequired super keys are not available in
1193 // the cache. However, they exist in the database in encrypted form.
Eric Biggers13869372023-10-18 01:54:18 +00001194 BeforeFirstUnlock,
Eric Biggersb0478cf2023-10-27 03:55:29 +00001195 // The user's super keys don't exist. I.e., there's no user with the given user ID, or the user
1196 // is in the process of being created or destroyed.
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001197 Uninitialized,
1198}
1199
Janis Danisevskiseed69842021-02-18 20:04:10 -08001200/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1201/// `Sensitive` holds the non encrypted key and a reference to its super key.
1202/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1203/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1204/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001205pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001206 Sensitive {
1207 key: ZVec,
1208 /// If KeyMint reports that the key must be upgraded, we must
1209 /// re-encrypt the key before writing to the database; we use
1210 /// this key.
1211 reencrypt_with: Arc<SuperKey>,
1212 /// If this key was decrypted with an ECDH key, we want to
1213 /// re-encrypt it on first use whether it was upgraded or not;
1214 /// this field indicates that that's necessary.
1215 force_reencrypt: bool,
1216 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001217 NonSensitive(Vec<u8>),
1218 Ref(&'a [u8]),
1219}
1220
Paul Crowley8d5b2532021-03-19 10:53:07 -07001221impl<'a> KeyBlob<'a> {
1222 pub fn force_reencrypt(&self) -> bool {
1223 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1224 *force_reencrypt
1225 } else {
1226 false
1227 }
1228 }
1229}
1230
Janis Danisevskiseed69842021-02-18 20:04:10 -08001231/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001232impl<'a> Deref for KeyBlob<'a> {
1233 type Target = [u8];
1234
1235 fn deref(&self) -> &Self::Target {
1236 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001237 Self::Sensitive { key, .. } => key,
1238 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001239 Self::Ref(key) => key,
1240 }
1241 }
1242}