blob: 9c17ccbf4e8e49e94d697efe8f01564f070282b9 [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 Biggersb0478cf2023-10-27 03:55:29 +0000251 /// The AfterFirstUnlock super key is used for synthetic password binding of authentication
252 /// bound keys. There is one key per android user. The key is stored on flash encrypted with a
253 /// key derived from a secret, that is itself derived from the user's synthetic password. (In
254 /// most cases, the user's synthetic password can, in turn, only be decrypted using the user's
255 /// Lock Screen Knowledge Factor or LSKF.) When the user unlocks the device for the first time,
256 /// this key is unlocked, i.e., decrypted, and stays memory resident until the device reboots.
Eric Biggers673d34a2023-10-18 01:54:18 +0000257 after_first_unlock: Option<Arc<SuperKey>>,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000258 /// The UnlockedDeviceRequired symmetric super key works like the AfterFirstUnlock super key
259 /// with the distinction that it is cleared from memory when the device is locked.
260 unlocked_device_required_symmetric: Option<Arc<SuperKey>>,
261 /// When the device is locked, keys that use the UnlockedDeviceRequired key parameter can still
262 /// be created, using ECDH public-key encryption. This field holds the decryption private key.
263 unlocked_device_required_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700264 /// Versions of the above two keys, locked behind a biometric.
265 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000266}
267
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800268#[derive(Default)]
269struct SkmState {
270 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700271 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800272 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700273}
274
275impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000276 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
277 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
278 self.key_index.insert(id, Arc::downgrade(super_key));
279 Ok(())
280 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000281 Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000282 }
Paul Crowley7a658392021-03-18 17:08:20 -0700283 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800284}
285
286#[derive(Default)]
287pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800288 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800289}
290
291impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800292 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
293 let mut skm_guard = skm.write().unwrap();
294 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000295 log::info!("In set_up_boot_level_cache: called for a second time");
296 return Ok(());
297 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000298 let level_zero_key =
299 get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800300 skm_guard.data.boot_level_key_cache =
301 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000302 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800303 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000304 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800305 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000306 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
307 });
308 Ok(())
309 }
310
311 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
312 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800313 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000314 let mut w = PropertyWatcher::new("keystore.boot_level")
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000315 .context(ks_err!("PropertyWatcher::new failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000316 loop {
317 let level = w
318 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000319 .context(ks_err!("read of property failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800320
321 // This scope limits the skm_guard life, so we don't hold the skm_guard while
322 // waiting.
323 {
324 let mut skm_guard = skm.write().unwrap();
325 let boot_level_key_cache = skm_guard
326 .data
327 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000328 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800329 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000330 .context(ks_err!("Boot level cache not initialized"))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800331 .get_mut()
332 .unwrap();
333 if level < MAX_MAX_BOOT_LEVEL {
334 log::info!("Read keystore.boot_level value {}", level);
335 boot_level_key_cache
336 .advance_boot_level(level)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000337 .context(ks_err!("advance_boot_level failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800338 } else {
339 log::info!(
340 "keystore.boot_level {} hits maximum {}, finishing.",
341 level,
342 MAX_MAX_BOOT_LEVEL
343 );
344 boot_level_key_cache.finish();
345 break;
346 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000347 }
Andrew Walbran48fa9702023-05-10 15:19:30 +0000348 w.wait(None).context(ks_err!("property wait failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000349 }
350 Ok(())
351 }
352
353 pub fn level_accessible(&self, boot_level: i32) -> bool {
354 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000355 .boot_level_key_cache
356 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800357 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000358 }
359
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800360 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
361 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800362 }
363
Eric Biggers673d34a2023-10-18 01:54:18 +0000364 fn install_after_first_unlock_key_for_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800365 &mut self,
366 user: UserId,
367 super_key: Arc<SuperKey>,
368 ) -> Result<()> {
369 self.data
370 .add_key_to_key_index(&super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000371 .context(ks_err!("add_key_to_key_index failed"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000372 self.data.user_keys.entry(user).or_default().after_first_unlock = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000373 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800374 }
375
Paul Crowley44c02da2021-04-08 17:04:43 +0000376 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000377 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800378 SuperKeyIdentifier::DatabaseId(id) => {
379 self.data.key_index.get(id).and_then(|k| k.upgrade())
380 }
381 SuperKeyIdentifier::BootLevel(level) => self
382 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000383 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800384 .as_ref()
385 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000386 .transpose()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000387 .context(ks_err!("aes_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000388 .flatten()
389 .map(|key| {
390 Arc::new(SuperKey {
391 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
392 key,
393 id: *key_id,
394 reencrypt_with: None,
395 })
396 }),
397 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800398 }
399
Eric Biggers673d34a2023-10-18 01:54:18 +0000400 /// Returns the AfterFirstUnlock superencryption key for the given user ID, or None if the user
401 /// has not yet unlocked the device since boot.
402 pub fn get_after_first_unlock_key_by_user_id(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800403 &self,
404 user_id: UserId,
405 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
Eric Biggers673d34a2023-10-18 01:54:18 +0000406 self.get_after_first_unlock_key_by_user_id_internal(user_id)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800407 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
408 }
409
Eric Biggers673d34a2023-10-18 01:54:18 +0000410 fn get_after_first_unlock_key_by_user_id_internal(
411 &self,
412 user_id: UserId,
413 ) -> Option<Arc<SuperKey>> {
414 self.data.user_keys.get(&user_id).and_then(|e| e.after_first_unlock.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800415 }
416
Paul Crowley44c02da2021-04-08 17:04:43 +0000417 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
418 /// the relevant super key.
419 pub fn unwrap_key_if_required<'a>(
420 &self,
421 metadata: &BlobMetaData,
422 blob: &'a [u8],
423 ) -> Result<KeyBlob<'a>> {
424 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
425 let super_key = self
426 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000427 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000428 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000429 .context(ks_err!("Required super decryption key is not in memory."))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000430 KeyBlob::Sensitive {
431 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000432 .context(ks_err!("unwrap_key_with_key failed"))?,
Paul Crowley44c02da2021-04-08 17:04:43 +0000433 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
434 force_reencrypt: super_key.reencrypt_with.is_some(),
435 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700436 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000437 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700438 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800439 }
440
441 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700442 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700443 match key.algorithm {
444 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000445 (Some(iv), Some(tag)) => {
446 key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
447 }
448 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
449 "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700450 iv.is_some(),
451 tag.is_some(),
452 )),
453 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700454 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700455 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
456 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
457 ECDHPrivateKey::from_private_key(&key.key)
458 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000459 .context(ks_err!("Failed to decrypt the key blob with ECDH."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700460 }
461 (public_key, salt, iv, aead_tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000462 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700463 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000464 "Key has incomplete metadata. ",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700465 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
466 ),
467 public_key.is_some(),
468 salt.is_some(),
469 iv.is_some(),
470 aead_tag.is_some(),
471 ))
472 }
473 }
474 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800475 }
476 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000477
Eric Biggersb0478cf2023-10-27 03:55:29 +0000478 /// Checks if the user's AfterFirstUnlock super key exists in the database (or legacy database).
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800479 /// The reference to self is unused but it is required to prevent calling this function
480 /// concurrently with skm state database changes.
481 fn super_key_exists_in_db_for_user(
482 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000483 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800484 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700485 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000486 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000487 let key_in_db = db
Eric Biggers673d34a2023-10-18 01:54:18 +0000488 .key_exists(
489 Domain::APP,
490 user_id as u64 as i64,
491 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
492 KeyType::Super,
493 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000494 .context(ks_err!())?;
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000495
496 if key_in_db {
497 Ok(key_in_db)
498 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000499 legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000500 }
501 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000502
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800503 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000504 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800505 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700506 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700507 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000508 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700509 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700510 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700511 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000512 .context(ks_err!("Failed to extract super key from key entry"))?;
Eric Biggers673d34a2023-10-18 01:54:18 +0000513 self.install_after_first_unlock_key_for_user(user_id, super_key.clone())
514 .context(ks_err!("Failed to install AfterFirstUnlock super key for user!"))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000515 Ok(super_key)
516 }
517
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800518 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700519 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700520 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700521 entry: KeyEntry,
522 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700523 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700524 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000525 if let Some((blob, metadata)) = entry.key_blob_info() {
526 let key = match (
527 metadata.encrypted_by(),
528 metadata.salt(),
529 metadata.iv(),
530 metadata.aead_tag(),
531 ) {
532 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800533 // Note that password encryption is AES no matter the value of algorithm.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000534 let key = pw
Eric Biggers6e5ccd72024-01-17 03:54:11 +0000535 .derive_key_hkdf(salt, AES_256_KEY_LENGTH)
536 .context(ks_err!("Failed to derive key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000537
Eric Biggers6e5ccd72024-01-17 03:54:11 +0000538 aes_gcm_decrypt(blob, iv, tag, &key).or_else(|_e| {
539 // Handle old key stored before the switch to HKDF.
540 let key = pw
541 .derive_key_pbkdf2(salt, AES_256_KEY_LENGTH)
542 .context(ks_err!("Failed to derive key from password (PBKDF2)."))?;
543 aes_gcm_decrypt(blob, iv, tag, &key)
544 .context(ks_err!("Failed to decrypt key blob."))
545 })?
Hasini Gunasingheda895552021-01-27 19:34:37 +0000546 }
547 (enc_by, salt, iv, tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000548 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Hasini Gunasingheda895552021-01-27 19:34:37 +0000549 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000550 "Super key has incomplete metadata.",
551 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
552 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700553 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000554 salt.is_some(),
555 iv.is_some(),
556 tag.is_some()
557 ));
558 }
559 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000560 Ok(Arc::new(SuperKey {
561 algorithm,
562 key,
563 id: SuperKeyIdentifier::DatabaseId(entry.id()),
564 reencrypt_with,
565 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000566 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000567 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000568 }
569 }
570
571 /// Encrypts the super key from a key derived from the password, before storing in the database.
Eric Biggers6e5ccd72024-01-17 03:54:11 +0000572 /// This does not stretch the password; i.e., it assumes that the password is a high-entropy
573 /// synthetic password, not a low-entropy user provided password.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700574 pub fn encrypt_with_password(
575 super_key: &[u8],
576 pw: &Password,
577 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000578 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Eric Biggers6e5ccd72024-01-17 03:54:11 +0000579 let derived_key = if android_security_flags::fix_unlocked_device_required_keys_v2() {
580 pw.derive_key_hkdf(&salt, AES_256_KEY_LENGTH)
581 .context(ks_err!("Failed to derive key from password."))?
582 } else {
583 pw.derive_key_pbkdf2(&salt, AES_256_KEY_LENGTH)
584 .context(ks_err!("Failed to derive password."))?
585 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000586 let mut metadata = BlobMetaData::new();
587 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
588 metadata.add(BlobMetaEntry::Salt(salt));
589 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000590 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000591 metadata.add(BlobMetaEntry::Iv(iv));
592 metadata.add(BlobMetaEntry::AeadTag(tag));
593 Ok((encrypted_key, metadata))
594 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000595
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800596 // Helper function to encrypt a key with the given super key. Callers should select which super
597 // key to be used. This is called when a key is super encrypted at its creation as well as at
598 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700599 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000600 key_blob: &[u8],
601 super_key: &SuperKey,
602 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700603 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000604 return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
Paul Crowley8d5b2532021-03-19 10:53:07 -0700605 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000606 let mut metadata = BlobMetaData::new();
607 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000608 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000609 metadata.add(BlobMetaEntry::Iv(iv));
610 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000611 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000612 Ok((encrypted_key, metadata))
613 }
614
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000615 // Encrypts a given key_blob using a hybrid approach, which can either use the symmetric super
616 // key or the public super key depending on which is available.
617 //
618 // If the symmetric_key is available, the key_blob is encrypted using symmetric encryption with
619 // the provided symmetric super key. Otherwise, the function loads the public super key from
620 // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be
621 // re-encrypted with the symmetric super key on the first use.
622 //
Eric Biggersb1f641d2023-10-18 01:54:18 +0000623 // This hybrid scheme allows keys that use the UnlockedDeviceRequired key parameter to be
624 // created while the device is locked.
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000625 fn encrypt_with_hybrid_super_key(
626 key_blob: &[u8],
627 symmetric_key: Option<&SuperKey>,
628 public_key_type: &SuperKeyType,
629 db: &mut KeystoreDB,
630 user_id: UserId,
631 ) -> Result<(Vec<u8>, BlobMetaData)> {
632 if let Some(super_key) = symmetric_key {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000633 Self::encrypt_with_aes_super_key(key_blob, super_key).context(ks_err!(
634 "Failed to encrypt with UnlockedDeviceRequired symmetric super key."
635 ))
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000636 } else {
637 // Symmetric key is not available, use public key encryption
638 let loaded = db
639 .load_super_key(public_key_type, user_id)
640 .context(ks_err!("load_super_key failed."))?;
641 let (key_id_guard, key_entry) =
642 loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH super key missing."))?;
643 let public_key = key_entry
644 .metadata()
645 .sec1_public_key()
646 .ok_or_else(Error::sys)
647 .context(ks_err!("sec1_public_key missing."))?;
648 let mut metadata = BlobMetaData::new();
649 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
650 ECDHPrivateKey::encrypt_message(public_key, key_blob)
651 .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
652 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
653 metadata.add(BlobMetaEntry::Salt(salt));
654 metadata.add(BlobMetaEntry::Iv(iv));
655 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
656 SuperKeyIdentifier::DatabaseId(key_id_guard.id()).add_to_metadata(&mut metadata);
657 Ok((encrypted_key, metadata))
658 }
659 }
660
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000661 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
662 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700663 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000664 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000665 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000666 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800667 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000668 domain: &Domain,
669 key_parameters: &[KeyParameter],
670 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700671 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000672 key_blob: &[u8],
673 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700674 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
675 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Eric Biggers673d34a2023-10-18 01:54:18 +0000676 SuperEncryptionType::AfterFirstUnlock => {
677 // Encrypt the given key blob with the user's AfterFirstUnlock super key. If the
Eric Biggersb0478cf2023-10-27 03:55:29 +0000678 // user has not unlocked the device since boot or the super keys were never
679 // initialized for the user for some reason, an error is returned.
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000680 match self
681 .get_user_state(db, legacy_importer, user_id)
David Drysdalee85523f2023-06-19 12:28:53 +0100682 .context(ks_err!("Failed to get user state for user {user_id}"))?
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000683 {
Eric Biggers673d34a2023-10-18 01:54:18 +0000684 UserState::AfterFirstUnlock(super_key) => {
685 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(ks_err!(
686 "Failed to encrypt with AfterFirstUnlock super key for user {user_id}"
687 ))
688 }
Eric Biggers13869372023-10-18 01:54:18 +0000689 UserState::BeforeFirstUnlock => {
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000690 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
691 }
692 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
Eric Biggersb0478cf2023-10-27 03:55:29 +0000693 .context(ks_err!("User {user_id} does not have super keys")),
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000694 }
695 }
Eric Biggersb1f641d2023-10-18 01:54:18 +0000696 SuperEncryptionType::UnlockedDeviceRequired => {
697 let symmetric_key = self
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000698 .data
699 .user_keys
700 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000701 .and_then(|e| e.unlocked_device_required_symmetric.as_ref())
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000702 .map(|arc| arc.as_ref());
703 Self::encrypt_with_hybrid_super_key(
704 key_blob,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000705 symmetric_key,
706 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000707 db,
708 user_id,
709 )
Eric Biggersb1f641d2023-10-18 01:54:18 +0000710 .context(ks_err!("Failed to encrypt with UnlockedDeviceRequired hybrid scheme."))
Paul Crowley7a658392021-03-18 17:08:20 -0700711 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000712 SuperEncryptionType::BootLevel(level) => {
713 let key_id = SuperKeyIdentifier::BootLevel(level);
714 let super_key = self
715 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000716 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000717 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000718 .context(ks_err!("Boot stage key absent"))?;
719 Self::encrypt_with_aes_super_key(key_blob, &super_key)
720 .context(ks_err!("Failed to encrypt with BootLevel key."))
Paul Crowley44c02da2021-04-08 17:04:43 +0000721 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000722 }
723 }
724
725 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
726 /// If so, re-super-encrypt the key and return a new set of metadata,
727 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700728 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000729 key_blob_before_upgrade: &KeyBlob,
730 key_after_upgrade: &'a [u8],
731 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
732 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700733 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700734 let (key, metadata) =
735 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000736 .context(ks_err!("Failed to re-super-encrypt key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000737 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
738 }
739 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
740 }
741 }
742
Eric Biggers456a3a62023-10-27 03:55:28 +0000743 fn create_super_key(
744 &mut self,
745 db: &mut KeystoreDB,
746 user_id: UserId,
747 key_type: &SuperKeyType,
748 password: &Password,
749 reencrypt_with: Option<Arc<SuperKey>>,
750 ) -> Result<Arc<SuperKey>> {
Eric Biggers6745f532023-10-27 03:55:28 +0000751 log::info!("Creating {} for user {}", key_type.name, user_id);
Eric Biggers456a3a62023-10-27 03:55:28 +0000752 let (super_key, public_key) = match key_type.algorithm {
753 SuperEncryptionAlgorithm::Aes256Gcm => {
754 (generate_aes256_key().context(ks_err!("Failed to generate AES-256 key."))?, None)
755 }
756 SuperEncryptionAlgorithm::EcdhP521 => {
757 let key =
758 ECDHPrivateKey::generate().context(ks_err!("Failed to generate ECDH key"))?;
759 (
760 key.private_key().context(ks_err!("private_key failed"))?,
761 Some(key.public_key().context(ks_err!("public_key failed"))?),
762 )
763 }
764 };
765 // Derive an AES-256 key from the password and re-encrypt the super key before we insert it
766 // in the database.
767 let (encrypted_super_key, blob_metadata) =
768 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
769 let mut key_metadata = KeyMetaData::new();
770 if let Some(pk) = public_key {
771 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
772 }
773 let key_entry = db
774 .store_super_key(user_id, key_type, &encrypted_super_key, &blob_metadata, &key_metadata)
775 .context(ks_err!("Failed to store super key."))?;
776 Ok(Arc::new(SuperKey {
777 algorithm: key_type.algorithm,
778 key: super_key,
779 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
780 reencrypt_with,
781 }))
782 }
783
Paul Crowley7a658392021-03-18 17:08:20 -0700784 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
785 /// When this is called, the caller must hold the lock on the SuperKeyManager.
786 /// So it's OK that the check and creation are different DB transactions.
787 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800788 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700789 db: &mut KeystoreDB,
790 user_id: UserId,
791 key_type: &SuperKeyType,
792 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700793 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700794 ) -> Result<Arc<SuperKey>> {
795 let loaded_key = db.load_super_key(key_type, user_id)?;
796 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700797 Ok(Self::extract_super_key_from_key_entry(
798 key_type.algorithm,
799 key_entry,
800 password,
801 reencrypt_with,
802 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700803 } else {
Eric Biggers456a3a62023-10-27 03:55:28 +0000804 self.create_super_key(db, user_id, key_type, password, reencrypt_with)
Paul Crowley7a658392021-03-18 17:08:20 -0700805 }
806 }
807
Eric Biggersb1f641d2023-10-18 01:54:18 +0000808 /// Decrypt the UnlockedDeviceRequired super keys for this user using the password and store
809 /// them in memory. If these keys don't exist yet, create them.
810 pub fn unlock_unlocked_device_required_keys(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800811 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700812 db: &mut KeystoreDB,
813 user_id: UserId,
814 password: &Password,
815 ) -> Result<()> {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000816 let (symmetric, private) = self
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800817 .data
818 .user_keys
819 .get(&user_id)
Eric Biggersb1f641d2023-10-18 01:54:18 +0000820 .map(|e| {
821 (
822 e.unlocked_device_required_symmetric.clone(),
823 e.unlocked_device_required_private.clone(),
824 )
825 })
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800826 .unwrap_or((None, None));
827
Eric Biggersb1f641d2023-10-18 01:54:18 +0000828 if symmetric.is_some() && private.is_some() {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800829 // Already unlocked.
830 return Ok(());
831 }
832
Eric Biggersb1f641d2023-10-18 01:54:18 +0000833 let aes = if let Some(symmetric) = symmetric {
834 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
835 // keys was initialized. This should never happen.
836 symmetric
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800837 } else {
838 self.get_or_create_super_key(
839 db,
840 user_id,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000841 &USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY,
842 password,
843 None,
844 )
845 .context(ks_err!("Trying to get or create symmetric key."))?
846 };
847
848 let ecdh = if let Some(private) = private {
849 // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
850 // keys was initialized. This should never happen.
851 private
852 } else {
853 self.get_or_create_super_key(
854 db,
855 user_id,
856 &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800857 password,
858 Some(aes.clone()),
859 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000860 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800861 };
862
863 self.data.add_key_to_key_index(&aes)?;
864 self.data.add_key_to_key_index(&ecdh)?;
865 let entry = self.data.user_keys.entry(user_id).or_default();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000866 entry.unlocked_device_required_symmetric = Some(aes);
867 entry.unlocked_device_required_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700868 Ok(())
869 }
870
Eric Biggersb1f641d2023-10-18 01:54:18 +0000871 /// Wipe the user's UnlockedDeviceRequired super keys from memory.
872 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],
877 ) {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000878 log::info!(
879 "Locking UnlockedDeviceRequired super keys for user {}; unlocking_sids={:?}",
880 user_id,
881 unlocking_sids
882 );
Chris Wailes53a22af2023-07-12 17:02:47 -0700883 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700884 if !unlocking_sids.is_empty() {
885 if let (Some(aes), Some(ecdh)) = (
Eric Biggersb1f641d2023-10-18 01:54:18 +0000886 entry.unlocked_device_required_symmetric.as_ref().cloned(),
887 entry.unlocked_device_required_private.as_ref().cloned(),
Paul Crowley618869e2021-04-08 20:30:54 -0700888 ) {
889 let res = (|| -> Result<()> {
890 let key_desc = KeyMintDevice::internal_descriptor(format!(
891 "biometric_unlock_key_{}",
892 user_id
893 ));
894 let encrypting_key = generate_aes256_key()?;
895 let km_dev: KeyMintDevice =
896 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000897 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700898 let mut key_params = vec![
899 KeyParameterValue::Algorithm(Algorithm::AES),
900 KeyParameterValue::KeySize(256),
901 KeyParameterValue::BlockMode(BlockMode::GCM),
902 KeyParameterValue::PaddingMode(PaddingMode::NONE),
903 KeyParameterValue::CallerNonce,
904 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
905 KeyParameterValue::MinMacLength(128),
906 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
907 KeyParameterValue::HardwareAuthenticatorType(
908 HardwareAuthenticatorType::FINGERPRINT,
909 ),
910 ];
911 for sid in unlocking_sids {
912 key_params.push(KeyParameterValue::UserSecureID(*sid));
913 }
914 let key_params: Vec<KmKeyParameter> =
915 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700916 km_dev.create_and_store_key(
917 db,
918 &key_desc,
919 KeyType::Client, /* TODO Should be Super b/189470584 */
920 |dev| {
921 let _wp = wd::watch_millis(
Eric Biggersb1f641d2023-10-18 01:54:18 +0000922 "In lock_unlocked_device_required_keys: calling importKey.",
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700923 500,
924 );
925 dev.importKey(
926 key_params.as_slice(),
927 KeyFormat::RAW,
928 &encrypting_key,
929 None,
930 )
931 },
932 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700933 entry.biometric_unlock = Some(BiometricUnlock {
934 sids: unlocking_sids.into(),
935 key_desc,
Eric Biggersb1f641d2023-10-18 01:54:18 +0000936 symmetric: LockedKey::new(&encrypting_key, &aes)?,
937 private: LockedKey::new(&encrypting_key, &ecdh)?,
Paul Crowley618869e2021-04-08 20:30:54 -0700938 });
939 Ok(())
940 })();
Eric Biggersb1f641d2023-10-18 01:54:18 +0000941 // There is no reason to propagate an error here upwards. We must clear the keys
942 // from memory in any case.
Paul Crowley618869e2021-04-08 20:30:54 -0700943 if let Err(e) = res {
944 log::error!("Error setting up biometric unlock: {:#?}", e);
945 }
946 }
947 }
Eric Biggersb1f641d2023-10-18 01:54:18 +0000948 entry.unlocked_device_required_symmetric = None;
949 entry.unlocked_device_required_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700950 }
Paul Crowley618869e2021-04-08 20:30:54 -0700951
952 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
953 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
954 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800955 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700956 db: &mut KeystoreDB,
957 user_id: UserId,
958 ) -> Result<()> {
Chris Wailes53a22af2023-07-12 17:02:47 -0700959 let entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700960 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700961 let (key_id_guard, key_entry) = db
962 .load_key_entry(
963 &biometric.key_desc,
964 KeyType::Client, // This should not be a Client key.
965 KeyEntryLoadBits::KM,
966 AID_KEYSTORE,
967 |_, _| Ok(()),
968 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000969 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700970 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000971 .context(ks_err!("KeyMintDevice::get failed"))?;
David Drysdalee85523f2023-06-19 12:28:53 +0100972 let mut errs = vec![];
Paul Crowley618869e2021-04-08 20:30:54 -0700973 for sid in &biometric.sids {
David Drysdalee85523f2023-06-19 12:28:53 +0100974 let sid = *sid;
Paul Crowley618869e2021-04-08 20:30:54 -0700975 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
David Drysdalee85523f2023-06-19 12:28:53 +0100976 entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700977 }) {
Paul Crowley618869e2021-04-08 20:30:54 -0700978 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000979 let symmetric = biometric.symmetric.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -0700980 db,
981 &km_dev,
982 &key_id_guard,
983 &key_entry,
984 auth_token_entry.auth_token(),
985 None,
986 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +0000987 let private = biometric.private.decrypt(
Paul Crowley618869e2021-04-08 20:30:54 -0700988 db,
989 &km_dev,
990 &key_id_guard,
991 &key_entry,
992 auth_token_entry.auth_token(),
Eric Biggersb1f641d2023-10-18 01:54:18 +0000993 Some(symmetric.clone()),
Paul Crowley618869e2021-04-08 20:30:54 -0700994 )?;
Eric Biggersb1f641d2023-10-18 01:54:18 +0000995 Ok((symmetric, private))
Paul Crowley618869e2021-04-08 20:30:54 -0700996 })();
997 match res {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000998 Ok((symmetric, private)) => {
999 entry.unlocked_device_required_symmetric = Some(symmetric.clone());
1000 entry.unlocked_device_required_private = Some(private.clone());
1001 self.data.add_key_to_key_index(&symmetric)?;
1002 self.data.add_key_to_key_index(&private)?;
David Drysdalee85523f2023-06-19 12:28:53 +01001003 log::info!("Successfully unlocked user {user_id} with biometric {sid}",);
Paul Crowley618869e2021-04-08 20:30:54 -07001004 return Ok(());
1005 }
1006 Err(e) => {
David Drysdalee85523f2023-06-19 12:28:53 +01001007 // Don't log an error yet, as some other biometric SID might work.
1008 errs.push((sid, e));
Paul Crowley618869e2021-04-08 20:30:54 -07001009 }
1010 }
1011 }
1012 }
David Drysdalee85523f2023-06-19 12:28:53 +01001013 if !errs.is_empty() {
1014 log::warn!("biometric unlock failed for all SIDs, with errors:");
1015 for (sid, err) in errs {
1016 log::warn!(" biometric {sid}: {err}");
1017 }
1018 }
Paul Crowley618869e2021-04-08 20:30:54 -07001019 }
1020 Ok(())
1021 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001022
1023 /// Returns the keystore locked state of the given user. It requires the thread local
1024 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001025 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001026 pub fn get_user_state(
1027 &self,
1028 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001029 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001030 user_id: UserId,
1031 ) -> Result<UserState> {
Eric Biggers673d34a2023-10-18 01:54:18 +00001032 match self.get_after_first_unlock_key_by_user_id_internal(user_id) {
Eric Biggers13869372023-10-18 01:54:18 +00001033 Some(super_key) => Ok(UserState::AfterFirstUnlock(super_key)),
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001034 None => {
1035 // Check if a super key exists in the database or legacy database.
1036 // If so, return locked user state.
1037 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001038 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001039 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001040 {
Eric Biggers13869372023-10-18 01:54:18 +00001041 Ok(UserState::BeforeFirstUnlock)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001042 } else {
1043 Ok(UserState::Uninitialized)
1044 }
1045 }
1046 }
1047 }
1048
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001049 /// Deletes all keys and super keys for the given user.
1050 /// This is called when a user is deleted.
1051 pub fn remove_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001052 &mut self,
1053 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001054 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001055 user_id: UserId,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001056 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001057 log::info!("remove_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001058 // Mark keys created on behalf of the user as unreferenced.
1059 legacy_importer
1060 .bulk_delete_user(user_id, false)
1061 .context(ks_err!("Trying to delete legacy keys."))?;
1062 db.unbind_keys_for_user(user_id, false).context(ks_err!("Error in unbinding keys."))?;
1063
1064 // Delete super key in cache, if exists.
1065 self.forget_all_keys_for_user(user_id);
1066 Ok(())
1067 }
1068
1069 /// Deletes all authentication bound keys and super keys for the given user. The user must be
1070 /// unlocked before this function is called. This function is used to transition a user to
1071 /// swipe.
1072 pub fn reset_user(
1073 &mut self,
1074 db: &mut KeystoreDB,
1075 legacy_importer: &LegacyImporter,
1076 user_id: UserId,
1077 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001078 log::info!("reset_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001079 match self.get_user_state(db, legacy_importer, user_id)? {
1080 UserState::Uninitialized => {
1081 Err(Error::sys()).context(ks_err!("Tried to reset an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001082 }
Eric Biggers13869372023-10-18 01:54:18 +00001083 UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001084 Err(Error::sys()).context(ks_err!("Tried to reset a locked user's password!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001085 }
Eric Biggers13869372023-10-18 01:54:18 +00001086 UserState::AfterFirstUnlock(_) => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001087 // Mark keys created on behalf of the user as unreferenced.
1088 legacy_importer
1089 .bulk_delete_user(user_id, true)
1090 .context(ks_err!("Trying to delete legacy keys."))?;
1091 db.unbind_keys_for_user(user_id, true)
1092 .context(ks_err!("Error in unbinding keys."))?;
1093
1094 // Delete super key in cache, if exists.
1095 self.forget_all_keys_for_user(user_id);
1096 Ok(())
1097 }
1098 }
1099 }
1100
Eric Biggers673d34a2023-10-18 01:54:18 +00001101 /// If the user hasn't been initialized yet, then this function generates the user's
1102 /// AfterFirstUnlock super key and sets the user's state to AfterFirstUnlock. Otherwise this
1103 /// function returns an error.
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001104 pub fn init_user(
1105 &mut self,
1106 db: &mut KeystoreDB,
1107 legacy_importer: &LegacyImporter,
1108 user_id: UserId,
1109 password: &Password,
1110 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001111 log::info!("init_user(user={user_id})");
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001112 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001113 UserState::AfterFirstUnlock(_) | UserState::BeforeFirstUnlock => {
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001114 Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"))
1115 }
1116 UserState::Uninitialized => {
1117 // Generate a new super key.
1118 let super_key =
1119 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
1120 // Derive an AES256 key from the password and re-encrypt the super key
1121 // before we insert it in the database.
1122 let (encrypted_super_key, blob_metadata) =
1123 Self::encrypt_with_password(&super_key, password)
1124 .context(ks_err!("Failed to encrypt super key with password!"))?;
1125
1126 let key_entry = db
1127 .store_super_key(
1128 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001129 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001130 &encrypted_super_key,
1131 &blob_metadata,
1132 &KeyMetaData::new(),
1133 )
1134 .context(ks_err!("Failed to store super key."))?;
1135
1136 self.populate_cache_from_super_key_blob(
1137 user_id,
Eric Biggers673d34a2023-10-18 01:54:18 +00001138 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001139 key_entry,
1140 password,
1141 )
1142 .context(ks_err!("Failed to initialize user!"))?;
1143 Ok(())
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001144 }
1145 }
1146 }
1147
Eric Biggersb0478cf2023-10-27 03:55:29 +00001148 /// Initializes the given user by creating their super keys, both AfterFirstUnlock and
1149 /// UnlockedDeviceRequired. If allow_existing is true, then the user already being initialized
1150 /// is not considered an error.
1151 pub fn initialize_user(
1152 &mut self,
1153 db: &mut KeystoreDB,
1154 legacy_importer: &LegacyImporter,
1155 user_id: UserId,
1156 password: &Password,
1157 allow_existing: bool,
1158 ) -> Result<()> {
1159 // Create the AfterFirstUnlock super key.
1160 if self.super_key_exists_in_db_for_user(db, legacy_importer, user_id)? {
1161 log::info!("AfterFirstUnlock super key already exists");
1162 if !allow_existing {
1163 return Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"));
1164 }
1165 } else {
1166 let super_key = self
1167 .create_super_key(db, user_id, &USER_AFTER_FIRST_UNLOCK_SUPER_KEY, password, None)
1168 .context(ks_err!("Failed to create AfterFirstUnlock super key"))?;
1169
1170 self.install_after_first_unlock_key_for_user(user_id, super_key)
1171 .context(ks_err!("Failed to install AfterFirstUnlock super key for user"))?;
1172 }
1173
1174 // Create the UnlockedDeviceRequired super keys.
1175 self.unlock_unlocked_device_required_keys(db, user_id, password)
1176 .context(ks_err!("Failed to create UnlockedDeviceRequired super keys"))
1177 }
1178
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001179 /// Unlocks the given user with the given password.
1180 ///
Eric Biggers13869372023-10-18 01:54:18 +00001181 /// If the user state is BeforeFirstUnlock:
Eric Biggers673d34a2023-10-18 01:54:18 +00001182 /// - Unlock the user's AfterFirstUnlock super key
Eric Biggersb1f641d2023-10-18 01:54:18 +00001183 /// - Unlock the user's UnlockedDeviceRequired super keys
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001184 ///
Eric Biggers13869372023-10-18 01:54:18 +00001185 /// If the user state is AfterFirstUnlock:
Eric Biggersb1f641d2023-10-18 01:54:18 +00001186 /// - Unlock the user's UnlockedDeviceRequired super keys only
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001187 ///
1188 pub fn unlock_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001189 &mut self,
1190 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001191 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001192 user_id: UserId,
1193 password: &Password,
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001194 ) -> Result<()> {
David Drysdalee85523f2023-06-19 12:28:53 +01001195 log::info!("unlock_user(user={user_id})");
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001196 match self.get_user_state(db, legacy_importer, user_id)? {
Eric Biggers13869372023-10-18 01:54:18 +00001197 UserState::AfterFirstUnlock(_) => {
Eric Biggersb1f641d2023-10-18 01:54:18 +00001198 self.unlock_unlocked_device_required_keys(db, user_id, password)
Eric Biggers13869372023-10-18 01:54:18 +00001199 }
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001200 UserState::Uninitialized => {
1201 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001202 }
Eric Biggers13869372023-10-18 01:54:18 +00001203 UserState::BeforeFirstUnlock => {
Eric Biggers673d34a2023-10-18 01:54:18 +00001204 let alias = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001205 let result = legacy_importer
1206 .with_try_import_super_key(user_id, password, || {
1207 db.load_super_key(alias, user_id)
1208 })
1209 .context(ks_err!("Failed to load super key"))?;
1210
1211 match result {
1212 Some((_, entry)) => {
1213 self.populate_cache_from_super_key_blob(
1214 user_id,
1215 alias.algorithm,
1216 entry,
1217 password,
1218 )
1219 .context(ks_err!("Failed when unlocking user."))?;
Eric Biggersb1f641d2023-10-18 01:54:18 +00001220 self.unlock_unlocked_device_required_keys(db, user_id, password)
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001221 }
1222 None => {
1223 Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))
1224 }
1225 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001226 }
1227 }
1228 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001229}
1230
1231/// This enum represents different states of the user's life cycle in the device.
1232/// For now, only three states are defined. More states may be added later.
1233pub enum UserState {
Eric Biggersb0478cf2023-10-27 03:55:29 +00001234 // The user's super keys exist, and the user has unlocked the device at least once since boot.
1235 // Hence, the AfterFirstUnlock super key is available in the cache.
Eric Biggers13869372023-10-18 01:54:18 +00001236 AfterFirstUnlock(Arc<SuperKey>),
Eric Biggersb0478cf2023-10-27 03:55:29 +00001237 // The user's super keys exist, but the user hasn't unlocked the device at least once since
1238 // boot. Hence, the AfterFirstUnlock and UnlockedDeviceRequired super keys are not available in
1239 // the cache. However, they exist in the database in encrypted form.
Eric Biggers13869372023-10-18 01:54:18 +00001240 BeforeFirstUnlock,
Eric Biggersb0478cf2023-10-27 03:55:29 +00001241 // The user's super keys don't exist. I.e., there's no user with the given user ID, or the user
1242 // is in the process of being created or destroyed.
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001243 Uninitialized,
1244}
1245
Janis Danisevskiseed69842021-02-18 20:04:10 -08001246/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1247/// `Sensitive` holds the non encrypted key and a reference to its super key.
1248/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1249/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1250/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001251pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001252 Sensitive {
1253 key: ZVec,
1254 /// If KeyMint reports that the key must be upgraded, we must
1255 /// re-encrypt the key before writing to the database; we use
1256 /// this key.
1257 reencrypt_with: Arc<SuperKey>,
1258 /// If this key was decrypted with an ECDH key, we want to
1259 /// re-encrypt it on first use whether it was upgraded or not;
1260 /// this field indicates that that's necessary.
1261 force_reencrypt: bool,
1262 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001263 NonSensitive(Vec<u8>),
1264 Ref(&'a [u8]),
1265}
1266
Paul Crowley8d5b2532021-03-19 10:53:07 -07001267impl<'a> KeyBlob<'a> {
1268 pub fn force_reencrypt(&self) -> bool {
1269 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1270 *force_reencrypt
1271 } else {
1272 false
1273 }
1274 }
1275}
1276
Janis Danisevskiseed69842021-02-18 20:04:10 -08001277/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001278impl<'a> Deref for KeyBlob<'a> {
1279 type Target = [u8];
1280
1281 fn deref(&self) -> &Self::Target {
1282 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001283 Self::Sensitive { key, .. } => key,
1284 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001285 Self::Ref(key) => key,
1286 }
1287 }
1288}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001289
1290#[cfg(test)]
1291mod tests {
1292 use super::*;
1293 use crate::database::tests::make_bootlevel_key_entry;
1294 use crate::database::tests::make_test_key_entry;
1295 use crate::database::tests::new_test_db;
1296 use rand::prelude::*;
1297 const USER_ID: u32 = 0;
1298 const TEST_KEY_ALIAS: &str = "TEST_KEY";
1299 const TEST_BOOT_KEY_ALIAS: &str = "TEST_BOOT_KEY";
1300
1301 pub fn generate_password_blob() -> Password<'static> {
1302 let mut rng = rand::thread_rng();
1303 let mut password = vec![0u8; 64];
1304 rng.fill_bytes(&mut password);
1305
1306 let mut zvec = ZVec::new(64).expect("Failed to create ZVec");
1307 zvec[..].copy_from_slice(&password[..]);
1308
1309 Password::Owned(zvec)
1310 }
1311
1312 fn setup_test(pw: &Password) -> (Arc<RwLock<SuperKeyManager>>, KeystoreDB, LegacyImporter) {
1313 let mut keystore_db = new_test_db().unwrap();
1314 let mut legacy_importer = LegacyImporter::new(Arc::new(Default::default()));
1315 legacy_importer.set_empty();
1316 let skm: Arc<RwLock<SuperKeyManager>> = Default::default();
1317 assert!(skm
1318 .write()
1319 .unwrap()
1320 .init_user(&mut keystore_db, &legacy_importer, USER_ID, pw)
1321 .is_ok());
1322 (skm, keystore_db, legacy_importer)
1323 }
1324
1325 fn assert_unlocked(
1326 skm: &Arc<RwLock<SuperKeyManager>>,
1327 keystore_db: &mut KeystoreDB,
1328 legacy_importer: &LegacyImporter,
1329 user_id: u32,
1330 err_msg: &str,
1331 ) {
1332 let user_state =
1333 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1334 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001335 UserState::AfterFirstUnlock(_) => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001336 _ => panic!("{}", err_msg),
1337 }
1338 }
1339
1340 fn assert_locked(
1341 skm: &Arc<RwLock<SuperKeyManager>>,
1342 keystore_db: &mut KeystoreDB,
1343 legacy_importer: &LegacyImporter,
1344 user_id: u32,
1345 err_msg: &str,
1346 ) {
1347 let user_state =
1348 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1349 match user_state {
Eric Biggers13869372023-10-18 01:54:18 +00001350 UserState::BeforeFirstUnlock => {}
Nathan Huckleberry95dca012023-05-10 18:02:11 +00001351 _ => panic!("{}", err_msg),
1352 }
1353 }
1354
1355 fn assert_uninitialized(
1356 skm: &Arc<RwLock<SuperKeyManager>>,
1357 keystore_db: &mut KeystoreDB,
1358 legacy_importer: &LegacyImporter,
1359 user_id: u32,
1360 err_msg: &str,
1361 ) {
1362 let user_state =
1363 skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap();
1364 match user_state {
1365 UserState::Uninitialized => {}
1366 _ => panic!("{}", err_msg),
1367 }
1368 }
1369
1370 #[test]
1371 fn test_init_user() {
1372 let pw: Password = generate_password_blob();
1373 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1374 assert_unlocked(
1375 &skm,
1376 &mut keystore_db,
1377 &legacy_importer,
1378 USER_ID,
1379 "The user was not unlocked after initialization!",
1380 );
1381 }
1382
1383 #[test]
1384 fn test_unlock_user() {
1385 let pw: Password = generate_password_blob();
1386 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1387 assert_unlocked(
1388 &skm,
1389 &mut keystore_db,
1390 &legacy_importer,
1391 USER_ID,
1392 "The user was not unlocked after initialization!",
1393 );
1394
1395 skm.write().unwrap().data.user_keys.clear();
1396 assert_locked(
1397 &skm,
1398 &mut keystore_db,
1399 &legacy_importer,
1400 USER_ID,
1401 "Clearing the cache did not lock the user!",
1402 );
1403
1404 assert!(skm
1405 .write()
1406 .unwrap()
1407 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1408 .is_ok());
1409 assert_unlocked(
1410 &skm,
1411 &mut keystore_db,
1412 &legacy_importer,
1413 USER_ID,
1414 "The user did not unlock!",
1415 );
1416 }
1417
1418 #[test]
1419 fn test_unlock_wrong_password() {
1420 let pw: Password = generate_password_blob();
1421 let wrong_pw: Password = generate_password_blob();
1422 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1423 assert_unlocked(
1424 &skm,
1425 &mut keystore_db,
1426 &legacy_importer,
1427 USER_ID,
1428 "The user was not unlocked after initialization!",
1429 );
1430
1431 skm.write().unwrap().data.user_keys.clear();
1432 assert_locked(
1433 &skm,
1434 &mut keystore_db,
1435 &legacy_importer,
1436 USER_ID,
1437 "Clearing the cache did not lock the user!",
1438 );
1439
1440 assert!(skm
1441 .write()
1442 .unwrap()
1443 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &wrong_pw)
1444 .is_err());
1445 assert_locked(
1446 &skm,
1447 &mut keystore_db,
1448 &legacy_importer,
1449 USER_ID,
1450 "The user was unlocked with an incorrect password!",
1451 );
1452 }
1453
1454 #[test]
1455 fn test_unlock_user_idempotent() {
1456 let pw: Password = generate_password_blob();
1457 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1458 assert_unlocked(
1459 &skm,
1460 &mut keystore_db,
1461 &legacy_importer,
1462 USER_ID,
1463 "The user was not unlocked after initialization!",
1464 );
1465
1466 skm.write().unwrap().data.user_keys.clear();
1467 assert_locked(
1468 &skm,
1469 &mut keystore_db,
1470 &legacy_importer,
1471 USER_ID,
1472 "Clearing the cache did not lock the user!",
1473 );
1474
1475 for _ in 0..5 {
1476 assert!(skm
1477 .write()
1478 .unwrap()
1479 .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw)
1480 .is_ok());
1481 assert_unlocked(
1482 &skm,
1483 &mut keystore_db,
1484 &legacy_importer,
1485 USER_ID,
1486 "The user did not unlock!",
1487 );
1488 }
1489 }
1490
1491 fn test_user_removal(locked: bool) {
1492 let pw: Password = generate_password_blob();
1493 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1494 assert_unlocked(
1495 &skm,
1496 &mut keystore_db,
1497 &legacy_importer,
1498 USER_ID,
1499 "The user was not unlocked after initialization!",
1500 );
1501
1502 assert!(make_test_key_entry(
1503 &mut keystore_db,
1504 Domain::APP,
1505 USER_ID.into(),
1506 TEST_KEY_ALIAS,
1507 None
1508 )
1509 .is_ok());
1510 assert!(make_bootlevel_key_entry(
1511 &mut keystore_db,
1512 Domain::APP,
1513 USER_ID.into(),
1514 TEST_BOOT_KEY_ALIAS,
1515 false
1516 )
1517 .is_ok());
1518
1519 assert!(keystore_db
1520 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1521 .unwrap());
1522 assert!(keystore_db
1523 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1524 .unwrap());
1525
1526 if locked {
1527 skm.write().unwrap().data.user_keys.clear();
1528 assert_locked(
1529 &skm,
1530 &mut keystore_db,
1531 &legacy_importer,
1532 USER_ID,
1533 "Clearing the cache did not lock the user!",
1534 );
1535 }
1536
1537 assert!(skm
1538 .write()
1539 .unwrap()
1540 .remove_user(&mut keystore_db, &legacy_importer, USER_ID)
1541 .is_ok());
1542 assert_uninitialized(
1543 &skm,
1544 &mut keystore_db,
1545 &legacy_importer,
1546 USER_ID,
1547 "The user was not removed!",
1548 );
1549
1550 assert!(!skm
1551 .write()
1552 .unwrap()
1553 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1554 .unwrap());
1555
1556 assert!(!keystore_db
1557 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1558 .unwrap());
1559 assert!(!keystore_db
1560 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1561 .unwrap());
1562 }
1563
1564 fn test_user_reset(locked: bool) {
1565 let pw: Password = generate_password_blob();
1566 let (skm, mut keystore_db, legacy_importer) = setup_test(&pw);
1567 assert_unlocked(
1568 &skm,
1569 &mut keystore_db,
1570 &legacy_importer,
1571 USER_ID,
1572 "The user was not unlocked after initialization!",
1573 );
1574
1575 assert!(make_test_key_entry(
1576 &mut keystore_db,
1577 Domain::APP,
1578 USER_ID.into(),
1579 TEST_KEY_ALIAS,
1580 None
1581 )
1582 .is_ok());
1583 assert!(make_bootlevel_key_entry(
1584 &mut keystore_db,
1585 Domain::APP,
1586 USER_ID.into(),
1587 TEST_BOOT_KEY_ALIAS,
1588 false
1589 )
1590 .is_ok());
1591 assert!(keystore_db
1592 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1593 .unwrap());
1594 assert!(keystore_db
1595 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1596 .unwrap());
1597
1598 if locked {
1599 skm.write().unwrap().data.user_keys.clear();
1600 assert_locked(
1601 &skm,
1602 &mut keystore_db,
1603 &legacy_importer,
1604 USER_ID,
1605 "Clearing the cache did not lock the user!",
1606 );
1607 assert!(skm
1608 .write()
1609 .unwrap()
1610 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1611 .is_err());
1612 assert_locked(
1613 &skm,
1614 &mut keystore_db,
1615 &legacy_importer,
1616 USER_ID,
1617 "User state should not have changed!",
1618 );
1619
1620 // Keys should still exist.
1621 assert!(keystore_db
1622 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1623 .unwrap());
1624 assert!(keystore_db
1625 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1626 .unwrap());
1627 } else {
1628 assert!(skm
1629 .write()
1630 .unwrap()
1631 .reset_user(&mut keystore_db, &legacy_importer, USER_ID)
1632 .is_ok());
1633 assert_uninitialized(
1634 &skm,
1635 &mut keystore_db,
1636 &legacy_importer,
1637 USER_ID,
1638 "The user was not reset!",
1639 );
1640 assert!(!skm
1641 .write()
1642 .unwrap()
1643 .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID)
1644 .unwrap());
1645
1646 // Auth bound key should no longer exist.
1647 assert!(!keystore_db
1648 .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client)
1649 .unwrap());
1650 assert!(keystore_db
1651 .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client)
1652 .unwrap());
1653 }
1654 }
1655
1656 #[test]
1657 fn test_remove_unlocked_user() {
1658 test_user_removal(false);
1659 }
1660
1661 #[test]
1662 fn test_remove_locked_user() {
1663 test_user_removal(true);
1664 }
1665
1666 #[test]
1667 fn test_reset_unlocked_user() {
1668 test_user_reset(false);
1669 }
1670
1671 #[test]
1672 fn test_reset_locked_user() {
1673 test_user_reset(true);
1674 }
1675}