blob: 728be24d015e09fce360a5f649608ac6cfd0d0cc [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,
Paul Crowley8d5b2532021-03-19 10:53:07 -070029 legacy_blob::LegacyBlobLoader,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080030 legacy_importer::LegacyImporter,
Paul Crowley618869e2021-04-08 20:30:54 -070031 raw_device::KeyMintDevice,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080032 utils::{watchdog as wd, AesGcm, AID_KEYSTORE},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080033};
Paul Crowley618869e2021-04-08 20:30:54 -070034use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
35 Algorithm::Algorithm, BlockMode::BlockMode, HardwareAuthToken::HardwareAuthToken,
36 HardwareAuthenticatorType::HardwareAuthenticatorType, KeyFormat::KeyFormat,
37 KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
38 SecurityLevel::SecurityLevel,
39};
40use android_system_keystore2::aidl::android::system::keystore2::{
41 Domain::Domain, KeyDescriptor::KeyDescriptor,
42};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080043use anyhow::{Context, Result};
44use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070045 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
46 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080047};
Joel Galenson7ead3a22021-07-29 15:27:34 -070048use rustutils::system_properties::PropertyWatcher;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use std::{
50 collections::HashMap,
51 sync::Arc,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080052 sync::{Mutex, RwLock, Weak},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080053};
Paul Crowley618869e2021-04-08 20:30:54 -070054use std::{convert::TryFrom, ops::Deref};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080055
Paul Crowley44c02da2021-04-08 17:04:43 +000056const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
Paul Crowley618869e2021-04-08 20:30:54 -070057/// Allow up to 15 seconds between the user unlocking using a biometric, and the auth
58/// token being used to unlock in [`SuperKeyManager::try_unlock_user_with_biometric`].
59/// This seems short enough for security purposes, while long enough that even the
60/// very slowest device will present the auth token in time.
61const BIOMETRIC_AUTH_TIMEOUT_S: i32 = 15; // seconds
Paul Crowley44c02da2021-04-08 17:04:43 +000062
Janis Danisevskisb42fc182020-12-15 08:41:27 -080063type UserId = u32;
64
Paul Crowley8d5b2532021-03-19 10:53:07 -070065/// Encryption algorithm used by a particular type of superencryption key
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum SuperEncryptionAlgorithm {
68 /// Symmetric encryption with AES-256-GCM
69 Aes256Gcm,
Paul Crowley52f017f2021-06-22 08:16:01 -070070 /// Public-key encryption with ECDH P-521
71 EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -070072}
73
Paul Crowley7a658392021-03-18 17:08:20 -070074/// A particular user may have several superencryption keys in the database, each for a
75/// different purpose, distinguished by alias. Each is associated with a static
76/// constant of this type.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080077pub struct SuperKeyType<'a> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080078 /// Alias used to look up the key in the `persistent.keyentry` table.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080079 pub alias: &'a str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070080 /// Encryption algorithm
81 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070082}
83
84/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
85/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070086pub const USER_SUPER_KEY: SuperKeyType =
87 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070088/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
89/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070090/// Symmetric.
91pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
92 alias: "USER_SCREEN_LOCK_BOUND_KEY",
93 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
94};
95/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
96/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
97/// Asymmetric, so keys can be encrypted when the device is locked.
Paul Crowley52f017f2021-06-22 08:16:01 -070098pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
99 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
100 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700101};
Paul Crowley7a658392021-03-18 17:08:20 -0700102
103/// Superencryption to apply to a new key.
104#[derive(Debug, Clone, Copy)]
105pub enum SuperEncryptionType {
106 /// Do not superencrypt this key.
107 None,
108 /// Superencrypt with a key that remains in memory from first unlock to reboot.
109 LskfBound,
110 /// Superencrypt with a key cleared from memory when the device is locked.
111 ScreenLockBound,
Paul Crowley44c02da2021-04-08 17:04:43 +0000112 /// Superencrypt with a key based on the desired boot level
113 BootLevel(i32),
114}
115
116#[derive(Debug, Clone, Copy)]
117pub enum SuperKeyIdentifier {
118 /// id of the super key in the database.
119 DatabaseId(i64),
120 /// Boot level of the encrypting boot level key
121 BootLevel(i32),
122}
123
124impl SuperKeyIdentifier {
125 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
126 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
127 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000128 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700129 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000130 }
131 }
132
133 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
134 match self {
135 SuperKeyIdentifier::DatabaseId(id) => {
136 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
137 }
138 SuperKeyIdentifier::BootLevel(level) => {
139 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
140 }
141 }
142 }
Paul Crowley7a658392021-03-18 17:08:20 -0700143}
144
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000145pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700146 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700147 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000148 /// Identifier of the encrypting key, used to write an encrypted blob
149 /// back to the database after re-encryption eg on a key update.
150 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700151 /// ECDH is more expensive than AES. So on ECDH private keys we set the
152 /// reencrypt_with field to point at the corresponding AES key, and the
153 /// keys will be re-encrypted with AES on first use.
154 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000155}
156
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800157impl AesGcm for SuperKey {
158 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700159 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000160 aes_gcm_decrypt(data, iv, tag, &self.key).context(ks_err!("Decryption failed."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700161 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000162 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800163 }
164 }
165
166 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
167 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000168 aes_gcm_encrypt(plaintext, &self.key).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800169 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000170 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700171 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000172 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700173}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000174
Paul Crowley618869e2021-04-08 20:30:54 -0700175/// A SuperKey that has been encrypted with an AES-GCM key. For
176/// encryption the key is in memory, and for decryption it is in KM.
177struct LockedKey {
178 algorithm: SuperEncryptionAlgorithm,
179 id: SuperKeyIdentifier,
180 nonce: Vec<u8>,
181 ciphertext: Vec<u8>, // with tag appended
182}
183
184impl LockedKey {
185 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
186 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
187 ciphertext.append(&mut tag);
188 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
189 }
190
191 fn decrypt(
192 &self,
193 db: &mut KeystoreDB,
194 km_dev: &KeyMintDevice,
195 key_id_guard: &KeyIdGuard,
196 key_entry: &KeyEntry,
197 auth_token: &HardwareAuthToken,
198 reencrypt_with: Option<Arc<SuperKey>>,
199 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700200 let key_blob = key_entry
201 .key_blob_info()
202 .as_ref()
203 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
204 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000205 .context(ks_err!("Missing key blob info."))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700206 let key_params = vec![
207 KeyParameterValue::Algorithm(Algorithm::AES),
208 KeyParameterValue::KeySize(256),
209 KeyParameterValue::BlockMode(BlockMode::GCM),
210 KeyParameterValue::PaddingMode(PaddingMode::NONE),
211 KeyParameterValue::Nonce(self.nonce.clone()),
212 KeyParameterValue::MacLength(128),
213 ];
214 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
215 let key = ZVec::try_from(km_dev.use_key_in_one_step(
216 db,
217 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700218 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700219 KeyPurpose::DECRYPT,
220 &key_params,
221 Some(auth_token),
222 &self.ciphertext,
223 )?)?;
224 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
225 }
226}
227
228/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
229/// a database descriptor for the encrypting key and the sids for the auth tokens
230/// that can be used to decrypt it.
231struct BiometricUnlock {
232 /// List of auth token SIDs that can be used to unlock these keys.
233 sids: Vec<i64>,
234 /// Database descriptor of key to use to unlock.
235 key_desc: KeyDescriptor,
236 /// Locked versions of the matching UserSuperKeys fields
237 screen_lock_bound: LockedKey,
238 screen_lock_bound_private: LockedKey,
239}
240
Paul Crowleye8826e52021-03-31 08:33:53 -0700241#[derive(Default)]
242struct UserSuperKeys {
243 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
244 /// key per android user. The key is stored on flash encrypted with a key derived from a
245 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
246 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
247 /// and stays memory resident until the device reboots.
248 per_boot: Option<Arc<SuperKey>>,
249 /// The screen lock key works like the per boot key with the distinction that it is cleared
250 /// from memory when the screen lock is engaged.
251 screen_lock_bound: Option<Arc<SuperKey>>,
252 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
253 /// ECDH public-key encryption. This field holds the decryption private key.
254 screen_lock_bound_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700255 /// Versions of the above two keys, locked behind a biometric.
256 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000257}
258
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800259#[derive(Default)]
260struct SkmState {
261 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700262 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800263 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700264}
265
266impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000267 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
268 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
269 self.key_index.insert(id, Arc::downgrade(super_key));
270 Ok(())
271 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000272 Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000273 }
Paul Crowley7a658392021-03-18 17:08:20 -0700274 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800275}
276
277#[derive(Default)]
278pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800279 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800280}
281
282impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800283 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
284 let mut skm_guard = skm.write().unwrap();
285 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000286 log::info!("In set_up_boot_level_cache: called for a second time");
287 return Ok(());
288 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000289 let level_zero_key =
290 get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800291 skm_guard.data.boot_level_key_cache =
292 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000293 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800294 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000295 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800296 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000297 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
298 });
299 Ok(())
300 }
301
302 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
303 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800304 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000305 let mut w = PropertyWatcher::new("keystore.boot_level")
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000306 .context(ks_err!("PropertyWatcher::new failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000307 loop {
308 let level = w
309 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000310 .context(ks_err!("read of property failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800311
312 // This scope limits the skm_guard life, so we don't hold the skm_guard while
313 // waiting.
314 {
315 let mut skm_guard = skm.write().unwrap();
316 let boot_level_key_cache = skm_guard
317 .data
318 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000319 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800320 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000321 .context(ks_err!("Boot level cache not initialized"))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800322 .get_mut()
323 .unwrap();
324 if level < MAX_MAX_BOOT_LEVEL {
325 log::info!("Read keystore.boot_level value {}", level);
326 boot_level_key_cache
327 .advance_boot_level(level)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000328 .context(ks_err!("advance_boot_level failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800329 } else {
330 log::info!(
331 "keystore.boot_level {} hits maximum {}, finishing.",
332 level,
333 MAX_MAX_BOOT_LEVEL
334 );
335 boot_level_key_cache.finish();
336 break;
337 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000338 }
Andrew Walbran48fa9702023-05-10 15:19:30 +0000339 w.wait(None).context(ks_err!("property wait failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000340 }
341 Ok(())
342 }
343
344 pub fn level_accessible(&self, boot_level: i32) -> bool {
345 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000346 .boot_level_key_cache
347 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800348 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000349 }
350
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800351 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
352 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800353 }
354
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800355 fn install_per_boot_key_for_user(
356 &mut self,
357 user: UserId,
358 super_key: Arc<SuperKey>,
359 ) -> Result<()> {
360 self.data
361 .add_key_to_key_index(&super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000362 .context(ks_err!("add_key_to_key_index failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800363 self.data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000364 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800365 }
366
Paul Crowley44c02da2021-04-08 17:04:43 +0000367 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000368 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800369 SuperKeyIdentifier::DatabaseId(id) => {
370 self.data.key_index.get(id).and_then(|k| k.upgrade())
371 }
372 SuperKeyIdentifier::BootLevel(level) => self
373 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000374 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800375 .as_ref()
376 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000377 .transpose()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000378 .context(ks_err!("aes_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000379 .flatten()
380 .map(|key| {
381 Arc::new(SuperKey {
382 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
383 key,
384 id: *key_id,
385 reencrypt_with: None,
386 })
387 }),
388 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800389 }
390
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800391 pub fn get_per_boot_key_by_user_id(
392 &self,
393 user_id: UserId,
394 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
395 self.get_per_boot_key_by_user_id_internal(user_id)
396 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
397 }
398
399 fn get_per_boot_key_by_user_id_internal(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800400 self.data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800401 }
402
403 /// This function unlocks the super keys for a given user.
404 /// This means the key is loaded from the database, decrypted and placed in the
405 /// super key cache. If there is no such key a new key is created, encrypted with
406 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800407 pub fn unlock_user_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800408 &mut self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000409 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800410 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700411 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800412 legacy_blob_loader: &LegacyBlobLoader,
413 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800414 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800415 .get_or_create_key_with(
416 Domain::APP,
417 user as u64 as i64,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700418 USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800419 crate::database::KEYSTORE_UUID,
420 || {
421 // For backward compatibility we need to check if there is a super key present.
422 let super_key = legacy_blob_loader
423 .load_super_key(user, pw)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000424 .context(ks_err!("Failed to load legacy key blob."))?;
Max Bires8e93d2b2021-01-14 13:17:59 -0800425 let super_key = match super_key {
426 None => {
427 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000428 generate_aes256_key()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000429 .context(ks_err!("Failed to generate AES 256 key."))?
Max Bires8e93d2b2021-01-14 13:17:59 -0800430 }
431 Some(key) => key,
432 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000433 // Regardless of whether we loaded an old AES128 key or generated a new AES256
434 // key as the super key, we derive a AES256 key from the password and re-encrypt
435 // the super key before we insert it in the database. The length of the key is
436 // preserved by the encryption so we don't need any extra flags to inform us
437 // which algorithm to use it with.
438 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800439 },
440 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000441 .context(ks_err!("Failed to get key id."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800442
Paul Crowley8d5b2532021-03-19 10:53:07 -0700443 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000444 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800445 Ok(())
446 }
447
Paul Crowley44c02da2021-04-08 17:04:43 +0000448 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
449 /// the relevant super key.
450 pub fn unwrap_key_if_required<'a>(
451 &self,
452 metadata: &BlobMetaData,
453 blob: &'a [u8],
454 ) -> Result<KeyBlob<'a>> {
455 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
456 let super_key = self
457 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000458 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000459 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000460 .context(ks_err!("Required super decryption key is not in memory."))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000461 KeyBlob::Sensitive {
462 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000463 .context(ks_err!("unwrap_key_with_key failed"))?,
Paul Crowley44c02da2021-04-08 17:04:43 +0000464 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
465 force_reencrypt: super_key.reencrypt_with.is_some(),
466 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700467 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000468 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700469 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800470 }
471
472 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700473 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700474 match key.algorithm {
475 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000476 (Some(iv), Some(tag)) => {
477 key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
478 }
479 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
480 "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700481 iv.is_some(),
482 tag.is_some(),
483 )),
484 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700485 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700486 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
487 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
488 ECDHPrivateKey::from_private_key(&key.key)
489 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000490 .context(ks_err!("Failed to decrypt the key blob with ECDH."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700491 }
492 (public_key, salt, iv, aead_tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000493 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700494 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000495 "Key has incomplete metadata. ",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700496 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
497 ),
498 public_key.is_some(),
499 salt.is_some(),
500 iv.is_some(),
501 aead_tag.is_some(),
502 ))
503 }
504 }
505 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800506 }
507 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000508
509 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800510 /// The reference to self is unused but it is required to prevent calling this function
511 /// concurrently with skm state database changes.
512 fn super_key_exists_in_db_for_user(
513 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000514 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800515 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700516 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000517 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000518 let key_in_db = db
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700519 .key_exists(Domain::APP, user_id as u64 as i64, USER_SUPER_KEY.alias, KeyType::Super)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000520 .context(ks_err!())?;
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000521
522 if key_in_db {
523 Ok(key_in_db)
524 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000525 legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000526 }
527 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000528
529 /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000530 /// legacy database). If not, return Uninitialized state.
531 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
532 pub fn check_and_unlock_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800533 &mut self,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000534 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800535 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700536 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700537 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000538 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700539 let alias = &USER_SUPER_KEY;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800540 let result = legacy_importer
541 .with_try_import_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000542 .context(ks_err!("Failed to load super key"))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000543
544 match result {
545 Some((_, entry)) => {
546 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700547 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000548 .context(ks_err!())?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000549 Ok(UserState::LskfUnlocked(super_key))
550 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000551 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000552 }
553 }
554
555 /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the
Hasini Gunasingheda895552021-01-27 19:34:37 +0000556 /// legacy database). If so, return LskfLocked state.
557 /// If the password is provided, generate a new super key, encrypt with the password,
558 /// store in the database and populate the super key cache for the new user
559 /// and return LskfUnlocked state.
560 /// If the password is not provided, return Uninitialized state.
561 pub fn check_and_initialize_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800562 &mut self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000563 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800564 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700565 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700566 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000567 ) -> Result<UserState> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800568 let super_key_exists_in_db = self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800569 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000570 .context(ks_err!("Failed to check if super key exists."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000571 if super_key_exists_in_db {
572 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000573 } else if let Some(pw) = pw {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800574 // Generate a new super key.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000575 let super_key =
576 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800577 // Derive an AES256 key from the password and re-encrypt the super key
578 // before we insert it in the database.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000579 let (encrypted_super_key, blob_metadata) =
580 Self::encrypt_with_password(&super_key, pw).context(ks_err!())?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000581
582 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700583 .store_super_key(
584 user_id,
585 &USER_SUPER_KEY,
586 &encrypted_super_key,
587 &blob_metadata,
588 &KeyMetaData::new(),
589 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000590 .context(ks_err!("Failed to store super key."))?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000591
592 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700593 .populate_cache_from_super_key_blob(
594 user_id,
595 USER_SUPER_KEY.algorithm,
596 key_entry,
597 pw,
598 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000599 .context(ks_err!())?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000600 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000601 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000602 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000603 }
604 }
605
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800606 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000607 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800608 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700609 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700610 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000611 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700612 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700613 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700614 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000615 .context(ks_err!("Failed to extract super key from key entry"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000616 self.install_per_boot_key_for_user(user_id, super_key.clone())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000617 Ok(super_key)
618 }
619
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800620 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700621 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700622 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700623 entry: KeyEntry,
624 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700625 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700626 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000627 if let Some((blob, metadata)) = entry.key_blob_info() {
628 let key = match (
629 metadata.encrypted_by(),
630 metadata.salt(),
631 metadata.iv(),
632 metadata.aead_tag(),
633 ) {
634 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800635 // Note that password encryption is AES no matter the value of algorithm.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000636 let key = pw
637 .derive_key(salt, AES_256_KEY_LENGTH)
638 .context(ks_err!("Failed to generate key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000639
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000640 aes_gcm_decrypt(blob, iv, tag, &key)
641 .context(ks_err!("Failed to decrypt key blob."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +0000642 }
643 (enc_by, salt, iv, tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000644 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Hasini Gunasingheda895552021-01-27 19:34:37 +0000645 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000646 "Super key has incomplete metadata.",
647 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
648 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700649 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000650 salt.is_some(),
651 iv.is_some(),
652 tag.is_some()
653 ));
654 }
655 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000656 Ok(Arc::new(SuperKey {
657 algorithm,
658 key,
659 id: SuperKeyIdentifier::DatabaseId(entry.id()),
660 reencrypt_with,
661 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000662 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000663 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000664 }
665 }
666
667 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700668 pub fn encrypt_with_password(
669 super_key: &[u8],
670 pw: &Password,
671 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000672 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700673 let derived_key = pw
David Drysdale6a0ec2c2022-04-19 08:11:18 +0100674 .derive_key(&salt, AES_256_KEY_LENGTH)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000675 .context(ks_err!("Failed to derive password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000676 let mut metadata = BlobMetaData::new();
677 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
678 metadata.add(BlobMetaEntry::Salt(salt));
679 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000680 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000681 metadata.add(BlobMetaEntry::Iv(iv));
682 metadata.add(BlobMetaEntry::AeadTag(tag));
683 Ok((encrypted_key, metadata))
684 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000685
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800686 // Helper function to encrypt a key with the given super key. Callers should select which super
687 // key to be used. This is called when a key is super encrypted at its creation as well as at
688 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700689 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000690 key_blob: &[u8],
691 super_key: &SuperKey,
692 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700693 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000694 return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
Paul Crowley8d5b2532021-03-19 10:53:07 -0700695 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000696 let mut metadata = BlobMetaData::new();
697 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000698 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000699 metadata.add(BlobMetaEntry::Iv(iv));
700 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000701 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000702 Ok((encrypted_key, metadata))
703 }
704
705 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
706 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700707 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000708 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000709 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000710 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800711 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000712 domain: &Domain,
713 key_parameters: &[KeyParameter],
714 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700715 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000716 key_blob: &[u8],
717 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700718 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
719 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000720 SuperEncryptionType::LskfBound => {
721 // Encrypt the given key blob with the user's per-boot super key, if the per-boot
722 // super key is available. If the device is boot-locked or the LSKF is not setup,
723 // an error is returned.
724 match self
725 .get_user_state(db, legacy_importer, user_id)
726 .context(ks_err!("Failed to get user state."))?
727 {
728 UserState::LskfUnlocked(super_key) => {
729 Self::encrypt_with_aes_super_key(key_blob, &super_key)
730 .context(ks_err!("Failed to encrypt with LskfBound key."))
731 }
732 UserState::LskfLocked => {
733 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
734 }
735 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
736 .context(ks_err!("LSKF is not setup for the user.")),
737 }
738 }
Paul Crowley7a658392021-03-18 17:08:20 -0700739 SuperEncryptionType::ScreenLockBound => {
Chariseea1e1c482022-02-26 01:26:35 +0000740 let entry =
741 self.data.user_keys.get(&user_id).and_then(|e| e.screen_lock_bound.as_ref());
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800742 if let Some(super_key) = entry {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000743 Self::encrypt_with_aes_super_key(key_blob, super_key)
744 .context(ks_err!("Failed to encrypt with ScreenLockBound key."))
Paul Crowley7a658392021-03-18 17:08:20 -0700745 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700746 // Symmetric key is not available, use public key encryption
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000747 let loaded = db
748 .load_super_key(&USER_SCREEN_LOCK_BOUND_P521_KEY, user_id)
749 .context(ks_err!("load_super_key failed."))?;
750 let (key_id_guard, key_entry) =
751 loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH key missing."))?;
752 let public_key = key_entry
753 .metadata()
754 .sec1_public_key()
755 .ok_or_else(Error::sys)
756 .context(ks_err!("sec1_public_key missing."))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700757 let mut metadata = BlobMetaData::new();
758 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000759 ECDHPrivateKey::encrypt_message(public_key, key_blob)
760 .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700761 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
762 metadata.add(BlobMetaEntry::Salt(salt));
763 metadata.add(BlobMetaEntry::Iv(iv));
764 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000765 SuperKeyIdentifier::DatabaseId(key_id_guard.id())
766 .add_to_metadata(&mut metadata);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700767 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700768 }
769 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000770 SuperEncryptionType::BootLevel(level) => {
771 let key_id = SuperKeyIdentifier::BootLevel(level);
772 let super_key = self
773 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000774 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000775 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000776 .context(ks_err!("Boot stage key absent"))?;
777 Self::encrypt_with_aes_super_key(key_blob, &super_key)
778 .context(ks_err!("Failed to encrypt with BootLevel key."))
Paul Crowley44c02da2021-04-08 17:04:43 +0000779 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000780 }
781 }
782
783 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
784 /// If so, re-super-encrypt the key and return a new set of metadata,
785 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700786 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000787 key_blob_before_upgrade: &KeyBlob,
788 key_after_upgrade: &'a [u8],
789 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
790 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700791 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700792 let (key, metadata) =
793 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000794 .context(ks_err!("Failed to re-super-encrypt key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000795 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
796 }
797 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
798 }
799 }
800
Paul Crowley7a658392021-03-18 17:08:20 -0700801 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
802 /// When this is called, the caller must hold the lock on the SuperKeyManager.
803 /// So it's OK that the check and creation are different DB transactions.
804 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800805 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700806 db: &mut KeystoreDB,
807 user_id: UserId,
808 key_type: &SuperKeyType,
809 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700810 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700811 ) -> Result<Arc<SuperKey>> {
812 let loaded_key = db.load_super_key(key_type, user_id)?;
813 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700814 Ok(Self::extract_super_key_from_key_entry(
815 key_type.algorithm,
816 key_entry,
817 password,
818 reencrypt_with,
819 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700820 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700821 let (super_key, public_key) = match key_type.algorithm {
822 SuperEncryptionAlgorithm::Aes256Gcm => (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000823 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700824 None,
825 ),
Paul Crowley52f017f2021-06-22 08:16:01 -0700826 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700827 let key = ECDHPrivateKey::generate()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000828 .context(ks_err!("Failed to generate ECDH key"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700829 (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000830 key.private_key().context(ks_err!("private_key failed"))?,
831 Some(key.public_key().context(ks_err!("public_key failed"))?),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700832 )
833 }
834 };
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800835 // Derive an AES256 key from the password and re-encrypt the super key
836 // before we insert it in the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700837 let (encrypted_super_key, blob_metadata) =
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000838 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700839 let mut key_metadata = KeyMetaData::new();
840 if let Some(pk) = public_key {
841 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
842 }
Paul Crowley7a658392021-03-18 17:08:20 -0700843 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700844 .store_super_key(
845 user_id,
846 key_type,
847 &encrypted_super_key,
848 &blob_metadata,
849 &key_metadata,
850 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000851 .context(ks_err!("Failed to store super key."))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700852 Ok(Arc::new(SuperKey {
853 algorithm: key_type.algorithm,
854 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000855 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700856 reencrypt_with,
857 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700858 }
859 }
860
Paul Crowley8d5b2532021-03-19 10:53:07 -0700861 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700862 pub fn unlock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800863 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700864 db: &mut KeystoreDB,
865 user_id: UserId,
866 password: &Password,
867 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800868 let (screen_lock_bound, screen_lock_bound_private) = self
869 .data
870 .user_keys
871 .get(&user_id)
872 .map(|e| (e.screen_lock_bound.clone(), e.screen_lock_bound_private.clone()))
873 .unwrap_or((None, None));
874
875 if screen_lock_bound.is_some() && screen_lock_bound_private.is_some() {
876 // Already unlocked.
877 return Ok(());
878 }
879
880 let aes = if let Some(screen_lock_bound) = screen_lock_bound {
881 // This is weird. If this point is reached only one of the screen locked keys was
882 // initialized. This should never happen.
883 screen_lock_bound
884 } else {
885 self.get_or_create_super_key(db, user_id, &USER_SCREEN_LOCK_BOUND_KEY, password, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000886 .context(ks_err!("Trying to get or create symmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800887 };
888
889 let ecdh = if let Some(screen_lock_bound_private) = screen_lock_bound_private {
890 // This is weird. If this point is reached only one of the screen locked keys was
891 // initialized. This should never happen.
892 screen_lock_bound_private
893 } else {
894 self.get_or_create_super_key(
895 db,
896 user_id,
897 &USER_SCREEN_LOCK_BOUND_P521_KEY,
898 password,
899 Some(aes.clone()),
900 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000901 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800902 };
903
904 self.data.add_key_to_key_index(&aes)?;
905 self.data.add_key_to_key_index(&ecdh)?;
906 let entry = self.data.user_keys.entry(user_id).or_default();
907 entry.screen_lock_bound = Some(aes);
908 entry.screen_lock_bound_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700909 Ok(())
910 }
911
Paul Crowley8d5b2532021-03-19 10:53:07 -0700912 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley618869e2021-04-08 20:30:54 -0700913 pub fn lock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800914 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700915 db: &mut KeystoreDB,
916 user_id: UserId,
917 unlocking_sids: &[i64],
918 ) {
919 log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800920 let mut entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700921 if !unlocking_sids.is_empty() {
922 if let (Some(aes), Some(ecdh)) = (
923 entry.screen_lock_bound.as_ref().cloned(),
924 entry.screen_lock_bound_private.as_ref().cloned(),
925 ) {
926 let res = (|| -> Result<()> {
927 let key_desc = KeyMintDevice::internal_descriptor(format!(
928 "biometric_unlock_key_{}",
929 user_id
930 ));
931 let encrypting_key = generate_aes256_key()?;
932 let km_dev: KeyMintDevice =
933 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000934 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700935 let mut key_params = vec![
936 KeyParameterValue::Algorithm(Algorithm::AES),
937 KeyParameterValue::KeySize(256),
938 KeyParameterValue::BlockMode(BlockMode::GCM),
939 KeyParameterValue::PaddingMode(PaddingMode::NONE),
940 KeyParameterValue::CallerNonce,
941 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
942 KeyParameterValue::MinMacLength(128),
943 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
944 KeyParameterValue::HardwareAuthenticatorType(
945 HardwareAuthenticatorType::FINGERPRINT,
946 ),
947 ];
948 for sid in unlocking_sids {
949 key_params.push(KeyParameterValue::UserSecureID(*sid));
950 }
951 let key_params: Vec<KmKeyParameter> =
952 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700953 km_dev.create_and_store_key(
954 db,
955 &key_desc,
956 KeyType::Client, /* TODO Should be Super b/189470584 */
957 |dev| {
958 let _wp = wd::watch_millis(
959 "In lock_screen_lock_bound_key: calling importKey.",
960 500,
961 );
962 dev.importKey(
963 key_params.as_slice(),
964 KeyFormat::RAW,
965 &encrypting_key,
966 None,
967 )
968 },
969 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700970 entry.biometric_unlock = Some(BiometricUnlock {
971 sids: unlocking_sids.into(),
972 key_desc,
973 screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
974 screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
975 });
976 Ok(())
977 })();
978 // There is no reason to propagate an error here upwards. We must discard
979 // entry.screen_lock_bound* in any case.
980 if let Err(e) = res {
981 log::error!("Error setting up biometric unlock: {:#?}", e);
982 }
983 }
984 }
Paul Crowley7a658392021-03-18 17:08:20 -0700985 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700986 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700987 }
Paul Crowley618869e2021-04-08 20:30:54 -0700988
989 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
990 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
991 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800992 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700993 db: &mut KeystoreDB,
994 user_id: UserId,
995 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800996 let mut entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700997 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700998 let (key_id_guard, key_entry) = db
999 .load_key_entry(
1000 &biometric.key_desc,
1001 KeyType::Client, // This should not be a Client key.
1002 KeyEntryLoadBits::KM,
1003 AID_KEYSTORE,
1004 |_, _| Ok(()),
1005 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001006 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -07001007 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001008 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -07001009 for sid in &biometric.sids {
1010 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
1011 entry.auth_token().userId == *sid || entry.auth_token().authenticatorId == *sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001012 }) {
Paul Crowley618869e2021-04-08 20:30:54 -07001013 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
1014 let slb = biometric.screen_lock_bound.decrypt(
1015 db,
1016 &km_dev,
1017 &key_id_guard,
1018 &key_entry,
1019 auth_token_entry.auth_token(),
1020 None,
1021 )?;
1022 let slbp = biometric.screen_lock_bound_private.decrypt(
1023 db,
1024 &km_dev,
1025 &key_id_guard,
1026 &key_entry,
1027 auth_token_entry.auth_token(),
1028 Some(slb.clone()),
1029 )?;
1030 Ok((slb, slbp))
1031 })();
1032 match res {
1033 Ok((slb, slbp)) => {
1034 entry.screen_lock_bound = Some(slb.clone());
1035 entry.screen_lock_bound_private = Some(slbp.clone());
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001036 self.data.add_key_to_key_index(&slb)?;
1037 self.data.add_key_to_key_index(&slbp)?;
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001038 log::info!("Successfully unlocked with biometric");
Paul Crowley618869e2021-04-08 20:30:54 -07001039 return Ok(());
1040 }
1041 Err(e) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001042 log::warn!("attempt failed: {:?}", e)
Paul Crowley618869e2021-04-08 20:30:54 -07001043 }
1044 }
1045 }
1046 }
1047 }
1048 Ok(())
1049 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001050
1051 /// Returns the keystore locked state of the given user. It requires the thread local
1052 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001053 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001054 pub fn get_user_state(
1055 &self,
1056 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001057 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001058 user_id: UserId,
1059 ) -> Result<UserState> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001060 match self.get_per_boot_key_by_user_id_internal(user_id) {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001061 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
1062 None => {
1063 // Check if a super key exists in the database or legacy database.
1064 // If so, return locked user state.
1065 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001066 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001067 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001068 {
1069 Ok(UserState::LskfLocked)
1070 } else {
1071 Ok(UserState::Uninitialized)
1072 }
1073 }
1074 }
1075 }
1076
1077 /// If the given user is unlocked:
1078 /// * and `password` is None, the user is reset, all authentication bound keys are deleted and
1079 /// `Ok(UserState::Uninitialized)` is returned.
1080 /// * and `password` is Some, `Ok(UserState::LskfUnlocked)` is returned.
1081 /// If the given user is locked:
1082 /// * and the user was initialized before, `Ok(UserState::Locked)` is returned.
1083 /// * and the user was not initialized before:
1084 /// * and `password` is None, `Ok(Uninitialized)` is returned.
1085 /// * and `password` is Some, super keys are generated and `Ok(UserState::LskfUnlocked)` is
1086 /// returned.
1087 pub fn reset_or_init_user_and_get_user_state(
1088 &mut self,
1089 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001090 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001091 user_id: UserId,
1092 password: Option<&Password>,
1093 ) -> Result<UserState> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001094 match self.get_per_boot_key_by_user_id_internal(user_id) {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001095 Some(_) if password.is_none() => {
1096 // Transitioning to swiping, delete only the super key in database and cache,
1097 // and super-encrypted keys in database (and in KM).
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001098 self.reset_user(db, legacy_importer, user_id, true)
1099 .context(ks_err!("Trying to delete keys from the db."))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001100 // Lskf is now removed in Keystore.
1101 Ok(UserState::Uninitialized)
1102 }
1103 Some(super_key) => {
1104 // Keystore won't be notified when changing to a new password when LSKF is
1105 // already setup. Therefore, ideally this path wouldn't be reached.
1106 Ok(UserState::LskfUnlocked(super_key))
1107 }
1108 None => {
1109 // Check if a super key exists in the database or legacy database.
1110 // If so, return LskfLocked state.
1111 // Otherwise, i) if the password is provided, initialize the super key and return
1112 // LskfUnlocked state ii) if password is not provided, return Uninitialized state.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001113 self.check_and_initialize_super_key(db, legacy_importer, user_id, password)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001114 }
1115 }
1116 }
1117
1118 /// Unlocks the given user with the given password. If the key was already unlocked or unlocking
1119 /// was successful, `Ok(UserState::LskfUnlocked)` is returned.
1120 /// If the user was never initialized `Ok(UserState::Uninitialized)` is returned.
1121 pub fn unlock_and_get_user_state(
1122 &mut self,
1123 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001124 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001125 user_id: UserId,
1126 password: &Password,
1127 ) -> Result<UserState> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001128 match self.get_per_boot_key_by_user_id_internal(user_id) {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001129 Some(super_key) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001130 log::info!("Trying to unlock when already unlocked.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001131 Ok(UserState::LskfUnlocked(super_key))
1132 }
1133 None => {
1134 // Check if a super key exists in the database or legacy database.
1135 // If not, return Uninitialized state.
1136 // Otherwise, try to unlock the super key and if successful,
1137 // return LskfUnlocked.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001138 self.check_and_unlock_super_key(db, legacy_importer, user_id, password)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001139 .context(ks_err!("Failed to unlock super key."))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001140 }
1141 }
1142 }
1143
1144 /// Delete all the keys created on behalf of the user.
1145 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
1146 /// encrypted keys.
1147 pub fn reset_user(
1148 &mut self,
1149 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001150 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001151 user_id: UserId,
1152 keep_non_super_encrypted_keys: bool,
1153 ) -> Result<()> {
1154 // Mark keys created on behalf of the user as unreferenced.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001155 legacy_importer
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001156 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001157 .context(ks_err!("Trying to delete legacy keys."))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001158 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +00001159 .context(ks_err!("Error in unbinding keys."))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001160
1161 // Delete super key in cache, if exists.
1162 self.forget_all_keys_for_user(user_id);
1163 Ok(())
1164 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001165}
1166
1167/// This enum represents different states of the user's life cycle in the device.
1168/// For now, only three states are defined. More states may be added later.
1169pub enum UserState {
1170 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
1171 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -07001172 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001173 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
1174 // Hence the per-boot super-key(s) is not available in the cache.
1175 // However, the encrypted super key is available in the database.
1176 LskfLocked,
1177 // There's no user in the device for the given user id, or the user with the user id has not
1178 // setup LSKF.
1179 Uninitialized,
1180}
1181
Janis Danisevskiseed69842021-02-18 20:04:10 -08001182/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1183/// `Sensitive` holds the non encrypted key and a reference to its super key.
1184/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1185/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1186/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001187pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001188 Sensitive {
1189 key: ZVec,
1190 /// If KeyMint reports that the key must be upgraded, we must
1191 /// re-encrypt the key before writing to the database; we use
1192 /// this key.
1193 reencrypt_with: Arc<SuperKey>,
1194 /// If this key was decrypted with an ECDH key, we want to
1195 /// re-encrypt it on first use whether it was upgraded or not;
1196 /// this field indicates that that's necessary.
1197 force_reencrypt: bool,
1198 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001199 NonSensitive(Vec<u8>),
1200 Ref(&'a [u8]),
1201}
1202
Paul Crowley8d5b2532021-03-19 10:53:07 -07001203impl<'a> KeyBlob<'a> {
1204 pub fn force_reencrypt(&self) -> bool {
1205 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1206 *force_reencrypt
1207 } else {
1208 false
1209 }
1210 }
1211}
1212
Janis Danisevskiseed69842021-02-18 20:04:10 -08001213/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001214impl<'a> Deref for KeyBlob<'a> {
1215 type Target = [u8];
1216
1217 fn deref(&self) -> &Self::Target {
1218 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001219 Self::Sensitive { key, .. } => key,
1220 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001221 Self::Ref(key) => key,
1222 }
1223 }
1224}