blob: 376d44ad112b32e40ea5823e5ec720eaf4fbd160 [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},
Paul Crowley8d5b2532021-03-19 10:53:07 -070028 legacy_blob::LegacyBlobLoader,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080029 legacy_importer::LegacyImporter,
Paul Crowley618869e2021-04-08 20:30:54 -070030 raw_device::KeyMintDevice,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080031 utils::{watchdog as wd, AesGcm, AID_KEYSTORE},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080032};
Paul Crowley618869e2021-04-08 20:30:54 -070033use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
34 Algorithm::Algorithm, BlockMode::BlockMode, HardwareAuthToken::HardwareAuthToken,
35 HardwareAuthenticatorType::HardwareAuthenticatorType, KeyFormat::KeyFormat,
36 KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
37 SecurityLevel::SecurityLevel,
38};
39use android_system_keystore2::aidl::android::system::keystore2::{
40 Domain::Domain, KeyDescriptor::KeyDescriptor,
41};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080042use anyhow::{Context, Result};
43use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070044 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
45 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046};
Joel Galenson7ead3a22021-07-29 15:27:34 -070047use rustutils::system_properties::PropertyWatcher;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080048use std::{
49 collections::HashMap,
50 sync::Arc,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080051 sync::{Mutex, RwLock, Weak},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080052};
Paul Crowley618869e2021-04-08 20:30:54 -070053use std::{convert::TryFrom, ops::Deref};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080054
Paul Crowley44c02da2021-04-08 17:04:43 +000055const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
Paul Crowley618869e2021-04-08 20:30:54 -070056/// Allow up to 15 seconds between the user unlocking using a biometric, and the auth
57/// token being used to unlock in [`SuperKeyManager::try_unlock_user_with_biometric`].
58/// This seems short enough for security purposes, while long enough that even the
59/// very slowest device will present the auth token in time.
60const BIOMETRIC_AUTH_TIMEOUT_S: i32 = 15; // seconds
Paul Crowley44c02da2021-04-08 17:04:43 +000061
Janis Danisevskisb42fc182020-12-15 08:41:27 -080062type UserId = u32;
63
Paul Crowley8d5b2532021-03-19 10:53:07 -070064/// Encryption algorithm used by a particular type of superencryption key
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum SuperEncryptionAlgorithm {
67 /// Symmetric encryption with AES-256-GCM
68 Aes256Gcm,
Paul Crowley52f017f2021-06-22 08:16:01 -070069 /// Public-key encryption with ECDH P-521
70 EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -070071}
72
Paul Crowley7a658392021-03-18 17:08:20 -070073/// A particular user may have several superencryption keys in the database, each for a
74/// different purpose, distinguished by alias. Each is associated with a static
75/// constant of this type.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080076pub struct SuperKeyType<'a> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080077 /// Alias used to look up the key in the `persistent.keyentry` table.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080078 pub alias: &'a str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070079 /// Encryption algorithm
80 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070081}
82
83/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
84/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070085pub const USER_SUPER_KEY: SuperKeyType =
86 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070087/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
88/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070089/// Symmetric.
90pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
91 alias: "USER_SCREEN_LOCK_BOUND_KEY",
92 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
93};
94/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
95/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
96/// Asymmetric, so keys can be encrypted when the device is locked.
Paul Crowley52f017f2021-06-22 08:16:01 -070097pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
98 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
99 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700100};
Paul Crowley7a658392021-03-18 17:08:20 -0700101
102/// Superencryption to apply to a new key.
103#[derive(Debug, Clone, Copy)]
104pub enum SuperEncryptionType {
105 /// Do not superencrypt this key.
106 None,
107 /// Superencrypt with a key that remains in memory from first unlock to reboot.
108 LskfBound,
109 /// Superencrypt with a key cleared from memory when the device is locked.
110 ScreenLockBound,
Paul Crowley44c02da2021-04-08 17:04:43 +0000111 /// Superencrypt with a key based on the desired boot level
112 BootLevel(i32),
113}
114
115#[derive(Debug, Clone, Copy)]
116pub enum SuperKeyIdentifier {
117 /// id of the super key in the database.
118 DatabaseId(i64),
119 /// Boot level of the encrypting boot level key
120 BootLevel(i32),
121}
122
123impl SuperKeyIdentifier {
124 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
125 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
126 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000127 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700128 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000129 }
130 }
131
132 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
133 match self {
134 SuperKeyIdentifier::DatabaseId(id) => {
135 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
136 }
137 SuperKeyIdentifier::BootLevel(level) => {
138 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
139 }
140 }
141 }
Paul Crowley7a658392021-03-18 17:08:20 -0700142}
143
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000144pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700145 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700146 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000147 /// Identifier of the encrypting key, used to write an encrypted blob
148 /// back to the database after re-encryption eg on a key update.
149 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700150 /// ECDH is more expensive than AES. So on ECDH private keys we set the
151 /// reencrypt_with field to point at the corresponding AES key, and the
152 /// keys will be re-encrypted with AES on first use.
153 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000154}
155
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800156impl AesGcm for SuperKey {
157 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700158 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
159 aes_gcm_decrypt(data, iv, tag, &self.key)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800160 .context("In SuperKey::decrypt: Decryption failed.")
Paul Crowley8d5b2532021-03-19 10:53:07 -0700161 } else {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800162 Err(Error::sys()).context("In SuperKey::decrypt: Key is not an AES key.")
163 }
164 }
165
166 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
167 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
168 aes_gcm_encrypt(plaintext, &self.key)
169 .context("In SuperKey::encrypt: Encryption failed.")
170 } else {
171 Err(Error::sys()).context("In SuperKey::encrypt: Key is not an AES key.")
Paul Crowley8d5b2532021-03-19 10:53:07 -0700172 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000173 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700174}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000175
Paul Crowley618869e2021-04-08 20:30:54 -0700176/// A SuperKey that has been encrypted with an AES-GCM key. For
177/// encryption the key is in memory, and for decryption it is in KM.
178struct LockedKey {
179 algorithm: SuperEncryptionAlgorithm,
180 id: SuperKeyIdentifier,
181 nonce: Vec<u8>,
182 ciphertext: Vec<u8>, // with tag appended
183}
184
185impl LockedKey {
186 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
187 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
188 ciphertext.append(&mut tag);
189 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
190 }
191
192 fn decrypt(
193 &self,
194 db: &mut KeystoreDB,
195 km_dev: &KeyMintDevice,
196 key_id_guard: &KeyIdGuard,
197 key_entry: &KeyEntry,
198 auth_token: &HardwareAuthToken,
199 reencrypt_with: Option<Arc<SuperKey>>,
200 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700201 let key_blob = key_entry
202 .key_blob_info()
203 .as_ref()
204 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
205 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
206 .context("In LockedKey::decrypt: Missing key blob info.")?;
Paul Crowley618869e2021-04-08 20:30:54 -0700207 let key_params = vec![
208 KeyParameterValue::Algorithm(Algorithm::AES),
209 KeyParameterValue::KeySize(256),
210 KeyParameterValue::BlockMode(BlockMode::GCM),
211 KeyParameterValue::PaddingMode(PaddingMode::NONE),
212 KeyParameterValue::Nonce(self.nonce.clone()),
213 KeyParameterValue::MacLength(128),
214 ];
215 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
216 let key = ZVec::try_from(km_dev.use_key_in_one_step(
217 db,
218 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700219 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700220 KeyPurpose::DECRYPT,
221 &key_params,
222 Some(auth_token),
223 &self.ciphertext,
224 )?)?;
225 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
226 }
227}
228
229/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
230/// a database descriptor for the encrypting key and the sids for the auth tokens
231/// that can be used to decrypt it.
232struct BiometricUnlock {
233 /// List of auth token SIDs that can be used to unlock these keys.
234 sids: Vec<i64>,
235 /// Database descriptor of key to use to unlock.
236 key_desc: KeyDescriptor,
237 /// Locked versions of the matching UserSuperKeys fields
238 screen_lock_bound: LockedKey,
239 screen_lock_bound_private: LockedKey,
240}
241
Paul Crowleye8826e52021-03-31 08:33:53 -0700242#[derive(Default)]
243struct UserSuperKeys {
244 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
245 /// key per android user. The key is stored on flash encrypted with a key derived from a
246 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
247 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
248 /// and stays memory resident until the device reboots.
249 per_boot: Option<Arc<SuperKey>>,
250 /// The screen lock key works like the per boot key with the distinction that it is cleared
251 /// from memory when the screen lock is engaged.
252 screen_lock_bound: Option<Arc<SuperKey>>,
253 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
254 /// ECDH public-key encryption. This field holds the decryption private key.
255 screen_lock_bound_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700256 /// Versions of the above two keys, locked behind a biometric.
257 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000258}
259
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800260#[derive(Default)]
261struct SkmState {
262 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700263 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800264 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700265}
266
267impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000268 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
269 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
270 self.key_index.insert(id, Arc::downgrade(super_key));
271 Ok(())
272 } else {
273 Err(Error::sys()).context(format!(
274 "In add_key_to_key_index: cannot add key with ID {:?}",
275 super_key.id
276 ))
277 }
Paul Crowley7a658392021-03-18 17:08:20 -0700278 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800279}
280
281#[derive(Default)]
282pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800283 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800284}
285
286impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800287 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
288 let mut skm_guard = skm.write().unwrap();
289 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000290 log::info!("In set_up_boot_level_cache: called for a second time");
291 return Ok(());
292 }
293 let level_zero_key = get_level_zero_key(db)
294 .context("In set_up_boot_level_cache: get_level_zero_key failed")?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800295 skm_guard.data.boot_level_key_cache =
296 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000297 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800298 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000299 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800300 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000301 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
302 });
303 Ok(())
304 }
305
306 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
307 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800308 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000309 let mut w = PropertyWatcher::new("keystore.boot_level")
310 .context("In watch_boot_level: PropertyWatcher::new failed")?;
311 loop {
312 let level = w
313 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
314 .context("In watch_boot_level: read of property failed")?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800315
316 // This scope limits the skm_guard life, so we don't hold the skm_guard while
317 // waiting.
318 {
319 let mut skm_guard = skm.write().unwrap();
320 let boot_level_key_cache = skm_guard
321 .data
322 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000323 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800324 .ok_or_else(Error::sys)
325 .context("In watch_boot_level: Boot level cache not initialized")?
326 .get_mut()
327 .unwrap();
328 if level < MAX_MAX_BOOT_LEVEL {
329 log::info!("Read keystore.boot_level value {}", level);
330 boot_level_key_cache
331 .advance_boot_level(level)
332 .context("In watch_boot_level: advance_boot_level failed")?;
333 } else {
334 log::info!(
335 "keystore.boot_level {} hits maximum {}, finishing.",
336 level,
337 MAX_MAX_BOOT_LEVEL
338 );
339 boot_level_key_cache.finish();
340 break;
341 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000342 }
343 w.wait().context("In watch_boot_level: property wait failed")?;
344 }
345 Ok(())
346 }
347
348 pub fn level_accessible(&self, boot_level: i32) -> bool {
349 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000350 .boot_level_key_cache
351 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800352 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000353 }
354
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800355 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
356 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800357 }
358
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800359 fn install_per_boot_key_for_user(
360 &mut self,
361 user: UserId,
362 super_key: Arc<SuperKey>,
363 ) -> Result<()> {
364 self.data
365 .add_key_to_key_index(&super_key)
Paul Crowley44c02da2021-04-08 17:04:43 +0000366 .context("In install_per_boot_key_for_user: add_key_to_key_index failed")?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800367 self.data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000368 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800369 }
370
Paul Crowley44c02da2021-04-08 17:04:43 +0000371 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000372 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800373 SuperKeyIdentifier::DatabaseId(id) => {
374 self.data.key_index.get(id).and_then(|k| k.upgrade())
375 }
376 SuperKeyIdentifier::BootLevel(level) => self
377 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000378 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800379 .as_ref()
380 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000381 .transpose()
382 .context("In lookup_key: aes_key failed")?
383 .flatten()
384 .map(|key| {
385 Arc::new(SuperKey {
386 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
387 key,
388 id: *key_id,
389 reencrypt_with: None,
390 })
391 }),
392 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800393 }
394
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800395 pub fn get_per_boot_key_by_user_id(
396 &self,
397 user_id: UserId,
398 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
399 self.get_per_boot_key_by_user_id_internal(user_id)
400 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
401 }
402
403 fn get_per_boot_key_by_user_id_internal(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800404 self.data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800405 }
406
407 /// This function unlocks the super keys for a given user.
408 /// This means the key is loaded from the database, decrypted and placed in the
409 /// super key cache. If there is no such key a new key is created, encrypted with
410 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800411 pub fn unlock_user_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800412 &mut self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000413 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800414 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700415 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800416 legacy_blob_loader: &LegacyBlobLoader,
417 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800418 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800419 .get_or_create_key_with(
420 Domain::APP,
421 user as u64 as i64,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700422 USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800423 crate::database::KEYSTORE_UUID,
424 || {
425 // For backward compatibility we need to check if there is a super key present.
426 let super_key = legacy_blob_loader
427 .load_super_key(user, pw)
428 .context("In create_new_key: Failed to load legacy key blob.")?;
429 let super_key = match super_key {
430 None => {
431 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000432 generate_aes256_key()
Max Bires8e93d2b2021-01-14 13:17:59 -0800433 .context("In create_new_key: Failed to generate AES 256 key.")?
434 }
435 Some(key) => key,
436 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000437 // Regardless of whether we loaded an old AES128 key or generated a new AES256
438 // key as the super key, we derive a AES256 key from the password and re-encrypt
439 // the super key before we insert it in the database. The length of the key is
440 // preserved by the encryption so we don't need any extra flags to inform us
441 // which algorithm to use it with.
442 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800443 },
444 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800445 .context("In unlock_user_key: Failed to get key id.")?;
446
Paul Crowley8d5b2532021-03-19 10:53:07 -0700447 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
448 .context("In unlock_user_key.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800449 Ok(())
450 }
451
Paul Crowley44c02da2021-04-08 17:04:43 +0000452 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
453 /// the relevant super key.
454 pub fn unwrap_key_if_required<'a>(
455 &self,
456 metadata: &BlobMetaData,
457 blob: &'a [u8],
458 ) -> Result<KeyBlob<'a>> {
459 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
460 let super_key = self
461 .lookup_key(&key_id)
462 .context("In unwrap_key: lookup_key failed")?
463 .ok_or(Error::Rc(ResponseCode::LOCKED))
464 .context("In unwrap_key: Required super decryption key is not in memory.")?;
465 KeyBlob::Sensitive {
466 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
467 .context("In unwrap_key: unwrap_key_with_key failed")?,
468 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
469 force_reencrypt: super_key.reencrypt_with.is_some(),
470 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700471 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000472 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700473 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800474 }
475
476 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700477 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700478 match key.algorithm {
479 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
480 (Some(iv), Some(tag)) => key
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800481 .decrypt(blob, iv, tag)
Paul Crowley8d5b2532021-03-19 10:53:07 -0700482 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
483 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
484 concat!(
485 "In unwrap_key_with_key: Key has incomplete metadata.",
486 "Present: iv: {}, aead_tag: {}."
487 ),
488 iv.is_some(),
489 tag.is_some(),
490 )),
491 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700492 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700493 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
494 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
495 ECDHPrivateKey::from_private_key(&key.key)
496 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
497 .context(
498 "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.",
499 )
500 }
501 (public_key, salt, iv, aead_tag) => {
502 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
503 concat!(
504 "In unwrap_key_with_key: Key has incomplete metadata.",
505 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
506 ),
507 public_key.is_some(),
508 salt.is_some(),
509 iv.is_some(),
510 aead_tag.is_some(),
511 ))
512 }
513 }
514 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800515 }
516 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000517
518 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800519 /// The reference to self is unused but it is required to prevent calling this function
520 /// concurrently with skm state database changes.
521 fn super_key_exists_in_db_for_user(
522 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000523 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800524 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700525 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000526 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000527 let key_in_db = db
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700528 .key_exists(Domain::APP, user_id as u64 as i64, USER_SUPER_KEY.alias, KeyType::Super)
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000529 .context("In super_key_exists_in_db_for_user.")?;
530
531 if key_in_db {
532 Ok(key_in_db)
533 } else {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800534 legacy_importer
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000535 .has_super_key(user_id)
536 .context("In super_key_exists_in_db_for_user: Trying to query legacy db.")
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000537 }
538 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000539
540 /// 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 +0000541 /// legacy database). If not, return Uninitialized state.
542 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
543 pub fn check_and_unlock_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800544 &mut self,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000545 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800546 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700547 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700548 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000549 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700550 let alias = &USER_SUPER_KEY;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800551 let result = legacy_importer
552 .with_try_import_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000553 .context("In check_and_unlock_super_key. Failed to load super key")?;
554
555 match result {
556 Some((_, entry)) => {
557 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700558 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000559 .context("In check_and_unlock_super_key.")?;
560 Ok(UserState::LskfUnlocked(super_key))
561 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000562 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000563 }
564 }
565
566 /// 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 +0000567 /// legacy database). If so, return LskfLocked state.
568 /// If the password is provided, generate a new super key, encrypt with the password,
569 /// store in the database and populate the super key cache for the new user
570 /// and return LskfUnlocked state.
571 /// If the password is not provided, return Uninitialized state.
572 pub fn check_and_initialize_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800573 &mut self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000574 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800575 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700576 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700577 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000578 ) -> Result<UserState> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800579 let super_key_exists_in_db = self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800580 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800581 .context("In check_and_initialize_super_key. Failed to check if super key exists.")?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000582 if super_key_exists_in_db {
583 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000584 } else if let Some(pw) = pw {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800585 // Generate a new super key.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000586 let super_key = generate_aes256_key()
587 .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800588 // Derive an AES256 key from the password and re-encrypt the super key
589 // before we insert it in the database.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000590 let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw)
591 .context("In check_and_initialize_super_key.")?;
592
593 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700594 .store_super_key(
595 user_id,
596 &USER_SUPER_KEY,
597 &encrypted_super_key,
598 &blob_metadata,
599 &KeyMetaData::new(),
600 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000601 .context("In check_and_initialize_super_key. Failed to store super key.")?;
602
603 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700604 .populate_cache_from_super_key_blob(
605 user_id,
606 USER_SUPER_KEY.algorithm,
607 key_entry,
608 pw,
609 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000610 .context("In check_and_initialize_super_key.")?;
611 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000612 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000613 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000614 }
615 }
616
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800617 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000618 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800619 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700620 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700621 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000622 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700623 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700624 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700625 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
626 .context(
627 "In populate_cache_from_super_key_blob. Failed to extract super key from key entry",
628 )?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000629 self.install_per_boot_key_for_user(user_id, super_key.clone())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000630 Ok(super_key)
631 }
632
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800633 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700634 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700635 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700636 entry: KeyEntry,
637 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700638 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700639 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000640 if let Some((blob, metadata)) = entry.key_blob_info() {
641 let key = match (
642 metadata.encrypted_by(),
643 metadata.salt(),
644 metadata.iv(),
645 metadata.aead_tag(),
646 ) {
647 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800648 // Note that password encryption is AES no matter the value of algorithm.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700649 let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context(
650 "In extract_super_key_from_key_entry: Failed to generate key from password.",
651 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000652
653 aes_gcm_decrypt(blob, iv, tag, &key).context(
654 "In extract_super_key_from_key_entry: Failed to decrypt key blob.",
655 )?
656 }
657 (enc_by, salt, iv, tag) => {
658 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
659 concat!(
660 "In extract_super_key_from_key_entry: Super key has incomplete metadata.",
Paul Crowleye8826e52021-03-31 08:33:53 -0700661 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
Hasini Gunasingheda895552021-01-27 19:34:37 +0000662 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700663 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000664 salt.is_some(),
665 iv.is_some(),
666 tag.is_some()
667 ));
668 }
669 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000670 Ok(Arc::new(SuperKey {
671 algorithm,
672 key,
673 id: SuperKeyIdentifier::DatabaseId(entry.id()),
674 reencrypt_with,
675 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000676 } else {
677 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
678 .context("In extract_super_key_from_key_entry: No key blob info.")
679 }
680 }
681
682 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700683 pub fn encrypt_with_password(
684 super_key: &[u8],
685 pw: &Password,
686 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000687 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700688 let derived_key = pw
689 .derive_key(Some(&salt), AES_256_KEY_LENGTH)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000690 .context("In encrypt_with_password: Failed to derive password.")?;
691 let mut metadata = BlobMetaData::new();
692 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
693 metadata.add(BlobMetaEntry::Salt(salt));
694 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
695 .context("In encrypt_with_password: Failed to encrypt new super key.")?;
696 metadata.add(BlobMetaEntry::Iv(iv));
697 metadata.add(BlobMetaEntry::AeadTag(tag));
698 Ok((encrypted_key, metadata))
699 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000700
701 // Encrypt the given key blob with the user's super key, if the super key exists and the device
702 // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
703 // return error. Note that it is out of the scope of this function to check if super encryption
704 // is required. Such check should be performed before calling this function.
705 fn super_encrypt_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000706 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000707 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800708 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700709 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000710 key_blob: &[u8],
711 ) -> Result<(Vec<u8>, BlobMetaData)> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800712 match self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800713 .get_user_state(db, legacy_importer, user_id)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000714 .context("In super_encrypt. Failed to get user state.")?
715 {
716 UserState::LskfUnlocked(super_key) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700717 Self::encrypt_with_aes_super_key(key_blob, &super_key)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000718 .context("In super_encrypt_on_key_init. Failed to encrypt the key.")
719 }
720 UserState::LskfLocked => {
721 Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.")
722 }
723 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
724 .context("In super_encrypt. LSKF is not setup for the user."),
725 }
726 }
727
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800728 // Helper function to encrypt a key with the given super key. Callers should select which super
729 // key to be used. This is called when a key is super encrypted at its creation as well as at
730 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700731 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000732 key_blob: &[u8],
733 super_key: &SuperKey,
734 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700735 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
736 return Err(Error::sys())
737 .context("In encrypt_with_aes_super_key: unexpected algorithm");
738 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000739 let mut metadata = BlobMetaData::new();
740 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700741 .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000742 metadata.add(BlobMetaEntry::Iv(iv));
743 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000744 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000745 Ok((encrypted_key, metadata))
746 }
747
748 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
749 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700750 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000751 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000752 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000753 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800754 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000755 domain: &Domain,
756 key_parameters: &[KeyParameter],
757 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700758 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000759 key_blob: &[u8],
760 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700761 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
762 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Paul Crowleye8826e52021-03-31 08:33:53 -0700763 SuperEncryptionType::LskfBound => self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800764 .super_encrypt_on_key_init(db, legacy_importer, user_id, key_blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700765 .context(concat!(
766 "In handle_super_encryption_on_key_init. ",
767 "Failed to super encrypt with LskfBound key."
768 )),
Paul Crowley7a658392021-03-18 17:08:20 -0700769 SuperEncryptionType::ScreenLockBound => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800770 let entry = self
771 .data
772 .user_keys
773 .get(&user_id)
774 .map(|e| e.screen_lock_bound.as_ref())
775 .flatten();
776 if let Some(super_key) = entry {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700777 Self::encrypt_with_aes_super_key(key_blob, super_key).context(concat!(
Paul Crowley7a658392021-03-18 17:08:20 -0700778 "In handle_super_encryption_on_key_init. ",
Paul Crowleye8826e52021-03-31 08:33:53 -0700779 "Failed to encrypt with ScreenLockBound key."
Paul Crowley7a658392021-03-18 17:08:20 -0700780 ))
781 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700782 // Symmetric key is not available, use public key encryption
783 let loaded =
Paul Crowley52f017f2021-06-22 08:16:01 -0700784 db.load_super_key(&USER_SCREEN_LOCK_BOUND_P521_KEY, user_id).context(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700785 "In handle_super_encryption_on_key_init: load_super_key failed.",
786 )?;
787 let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context(
788 "In handle_super_encryption_on_key_init: User ECDH key missing.",
789 )?;
790 let public_key =
791 key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context(
792 "In handle_super_encryption_on_key_init: sec1_public_key missing.",
793 )?;
794 let mut metadata = BlobMetaData::new();
795 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
796 ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!(
797 "In handle_super_encryption_on_key_init: ",
798 "ECDHPrivateKey::encrypt_message failed."
799 ))?;
800 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
801 metadata.add(BlobMetaEntry::Salt(salt));
802 metadata.add(BlobMetaEntry::Iv(iv));
803 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000804 SuperKeyIdentifier::DatabaseId(key_id_guard.id())
805 .add_to_metadata(&mut metadata);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700806 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700807 }
808 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000809 SuperEncryptionType::BootLevel(level) => {
810 let key_id = SuperKeyIdentifier::BootLevel(level);
811 let super_key = self
812 .lookup_key(&key_id)
813 .context("In handle_super_encryption_on_key_init: lookup_key failed")?
814 .ok_or(Error::Rc(ResponseCode::LOCKED))
815 .context("In handle_super_encryption_on_key_init: Boot stage key absent")?;
816 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
817 "In handle_super_encryption_on_key_init: ",
818 "Failed to encrypt with BootLevel key."
819 ))
820 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000821 }
822 }
823
824 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
825 /// If so, re-super-encrypt the key and return a new set of metadata,
826 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700827 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000828 key_blob_before_upgrade: &KeyBlob,
829 key_after_upgrade: &'a [u8],
830 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
831 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700832 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700833 let (key, metadata) =
834 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
835 .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000836 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
837 }
838 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
839 }
840 }
841
Paul Crowley7a658392021-03-18 17:08:20 -0700842 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
843 /// When this is called, the caller must hold the lock on the SuperKeyManager.
844 /// So it's OK that the check and creation are different DB transactions.
845 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800846 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700847 db: &mut KeystoreDB,
848 user_id: UserId,
849 key_type: &SuperKeyType,
850 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700851 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700852 ) -> Result<Arc<SuperKey>> {
853 let loaded_key = db.load_super_key(key_type, user_id)?;
854 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700855 Ok(Self::extract_super_key_from_key_entry(
856 key_type.algorithm,
857 key_entry,
858 password,
859 reencrypt_with,
860 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700861 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700862 let (super_key, public_key) = match key_type.algorithm {
863 SuperEncryptionAlgorithm::Aes256Gcm => (
864 generate_aes256_key()
865 .context("In get_or_create_super_key: Failed to generate AES 256 key.")?,
866 None,
867 ),
Paul Crowley52f017f2021-06-22 08:16:01 -0700868 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700869 let key = ECDHPrivateKey::generate()
870 .context("In get_or_create_super_key: Failed to generate ECDH key")?;
871 (
872 key.private_key()
873 .context("In get_or_create_super_key: private_key failed")?,
874 Some(
875 key.public_key()
876 .context("In get_or_create_super_key: public_key failed")?,
877 ),
878 )
879 }
880 };
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800881 // Derive an AES256 key from the password and re-encrypt the super key
882 // before we insert it in the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700883 let (encrypted_super_key, blob_metadata) =
884 Self::encrypt_with_password(&super_key, password)
885 .context("In get_or_create_super_key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700886 let mut key_metadata = KeyMetaData::new();
887 if let Some(pk) = public_key {
888 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
889 }
Paul Crowley7a658392021-03-18 17:08:20 -0700890 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700891 .store_super_key(
892 user_id,
893 key_type,
894 &encrypted_super_key,
895 &blob_metadata,
896 &key_metadata,
897 )
Paul Crowley7a658392021-03-18 17:08:20 -0700898 .context("In get_or_create_super_key. Failed to store super key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700899 Ok(Arc::new(SuperKey {
900 algorithm: key_type.algorithm,
901 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000902 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700903 reencrypt_with,
904 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700905 }
906 }
907
Paul Crowley8d5b2532021-03-19 10:53:07 -0700908 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700909 pub fn unlock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800910 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700911 db: &mut KeystoreDB,
912 user_id: UserId,
913 password: &Password,
914 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800915 let (screen_lock_bound, screen_lock_bound_private) = self
916 .data
917 .user_keys
918 .get(&user_id)
919 .map(|e| (e.screen_lock_bound.clone(), e.screen_lock_bound_private.clone()))
920 .unwrap_or((None, None));
921
922 if screen_lock_bound.is_some() && screen_lock_bound_private.is_some() {
923 // Already unlocked.
924 return Ok(());
925 }
926
927 let aes = if let Some(screen_lock_bound) = screen_lock_bound {
928 // This is weird. If this point is reached only one of the screen locked keys was
929 // initialized. This should never happen.
930 screen_lock_bound
931 } else {
932 self.get_or_create_super_key(db, user_id, &USER_SCREEN_LOCK_BOUND_KEY, password, None)
933 .context("In unlock_screen_lock_bound_key: Trying to get or create symmetric key.")?
934 };
935
936 let ecdh = if let Some(screen_lock_bound_private) = screen_lock_bound_private {
937 // This is weird. If this point is reached only one of the screen locked keys was
938 // initialized. This should never happen.
939 screen_lock_bound_private
940 } else {
941 self.get_or_create_super_key(
942 db,
943 user_id,
944 &USER_SCREEN_LOCK_BOUND_P521_KEY,
945 password,
946 Some(aes.clone()),
947 )
948 .context("In unlock_screen_lock_bound_key: Trying to get or create asymmetric key.")?
949 };
950
951 self.data.add_key_to_key_index(&aes)?;
952 self.data.add_key_to_key_index(&ecdh)?;
953 let entry = self.data.user_keys.entry(user_id).or_default();
954 entry.screen_lock_bound = Some(aes);
955 entry.screen_lock_bound_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700956 Ok(())
957 }
958
Paul Crowley8d5b2532021-03-19 10:53:07 -0700959 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley618869e2021-04-08 20:30:54 -0700960 pub fn lock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800961 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700962 db: &mut KeystoreDB,
963 user_id: UserId,
964 unlocking_sids: &[i64],
965 ) {
966 log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800967 let mut entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700968 if !unlocking_sids.is_empty() {
969 if let (Some(aes), Some(ecdh)) = (
970 entry.screen_lock_bound.as_ref().cloned(),
971 entry.screen_lock_bound_private.as_ref().cloned(),
972 ) {
973 let res = (|| -> Result<()> {
974 let key_desc = KeyMintDevice::internal_descriptor(format!(
975 "biometric_unlock_key_{}",
976 user_id
977 ));
978 let encrypting_key = generate_aes256_key()?;
979 let km_dev: KeyMintDevice =
980 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
981 .context("In lock_screen_lock_bound_key: KeyMintDevice::get failed")?;
982 let mut key_params = vec![
983 KeyParameterValue::Algorithm(Algorithm::AES),
984 KeyParameterValue::KeySize(256),
985 KeyParameterValue::BlockMode(BlockMode::GCM),
986 KeyParameterValue::PaddingMode(PaddingMode::NONE),
987 KeyParameterValue::CallerNonce,
988 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
989 KeyParameterValue::MinMacLength(128),
990 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
991 KeyParameterValue::HardwareAuthenticatorType(
992 HardwareAuthenticatorType::FINGERPRINT,
993 ),
994 ];
995 for sid in unlocking_sids {
996 key_params.push(KeyParameterValue::UserSecureID(*sid));
997 }
998 let key_params: Vec<KmKeyParameter> =
999 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001000 km_dev.create_and_store_key(
1001 db,
1002 &key_desc,
1003 KeyType::Client, /* TODO Should be Super b/189470584 */
1004 |dev| {
1005 let _wp = wd::watch_millis(
1006 "In lock_screen_lock_bound_key: calling importKey.",
1007 500,
1008 );
1009 dev.importKey(
1010 key_params.as_slice(),
1011 KeyFormat::RAW,
1012 &encrypting_key,
1013 None,
1014 )
1015 },
1016 )?;
Paul Crowley618869e2021-04-08 20:30:54 -07001017 entry.biometric_unlock = Some(BiometricUnlock {
1018 sids: unlocking_sids.into(),
1019 key_desc,
1020 screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
1021 screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
1022 });
1023 Ok(())
1024 })();
1025 // There is no reason to propagate an error here upwards. We must discard
1026 // entry.screen_lock_bound* in any case.
1027 if let Err(e) = res {
1028 log::error!("Error setting up biometric unlock: {:#?}", e);
1029 }
1030 }
1031 }
Paul Crowley7a658392021-03-18 17:08:20 -07001032 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -07001033 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -07001034 }
Paul Crowley618869e2021-04-08 20:30:54 -07001035
1036 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
1037 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
1038 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001039 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -07001040 db: &mut KeystoreDB,
1041 user_id: UserId,
1042 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001043 let mut entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -07001044 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -07001045 let (key_id_guard, key_entry) = db
1046 .load_key_entry(
1047 &biometric.key_desc,
1048 KeyType::Client, // This should not be a Client key.
1049 KeyEntryLoadBits::KM,
1050 AID_KEYSTORE,
1051 |_, _| Ok(()),
1052 )
1053 .context("In try_unlock_user_with_biometric: load_key_entry failed")?;
Paul Crowley618869e2021-04-08 20:30:54 -07001054 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
1055 .context("In try_unlock_user_with_biometric: KeyMintDevice::get failed")?;
1056 for sid in &biometric.sids {
1057 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
1058 entry.auth_token().userId == *sid || entry.auth_token().authenticatorId == *sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001059 }) {
Paul Crowley618869e2021-04-08 20:30:54 -07001060 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
1061 let slb = biometric.screen_lock_bound.decrypt(
1062 db,
1063 &km_dev,
1064 &key_id_guard,
1065 &key_entry,
1066 auth_token_entry.auth_token(),
1067 None,
1068 )?;
1069 let slbp = biometric.screen_lock_bound_private.decrypt(
1070 db,
1071 &km_dev,
1072 &key_id_guard,
1073 &key_entry,
1074 auth_token_entry.auth_token(),
1075 Some(slb.clone()),
1076 )?;
1077 Ok((slb, slbp))
1078 })();
1079 match res {
1080 Ok((slb, slbp)) => {
1081 entry.screen_lock_bound = Some(slb.clone());
1082 entry.screen_lock_bound_private = Some(slbp.clone());
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001083 self.data.add_key_to_key_index(&slb)?;
1084 self.data.add_key_to_key_index(&slbp)?;
Paul Crowley618869e2021-04-08 20:30:54 -07001085 log::info!(concat!(
1086 "In try_unlock_user_with_biometric: ",
1087 "Successfully unlocked with biometric"
1088 ));
1089 return Ok(());
1090 }
1091 Err(e) => {
1092 log::warn!("In try_unlock_user_with_biometric: attempt failed: {:?}", e)
1093 }
1094 }
1095 }
1096 }
1097 }
1098 Ok(())
1099 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001100
1101 /// Returns the keystore locked state of the given user. It requires the thread local
1102 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001103 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001104 pub fn get_user_state(
1105 &self,
1106 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001107 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001108 user_id: UserId,
1109 ) -> Result<UserState> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001110 match self.get_per_boot_key_by_user_id_internal(user_id) {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001111 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
1112 None => {
1113 // Check if a super key exists in the database or legacy database.
1114 // If so, return locked user state.
1115 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001116 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001117 .context("In get_user_state.")?
1118 {
1119 Ok(UserState::LskfLocked)
1120 } else {
1121 Ok(UserState::Uninitialized)
1122 }
1123 }
1124 }
1125 }
1126
1127 /// If the given user is unlocked:
1128 /// * and `password` is None, the user is reset, all authentication bound keys are deleted and
1129 /// `Ok(UserState::Uninitialized)` is returned.
1130 /// * and `password` is Some, `Ok(UserState::LskfUnlocked)` is returned.
1131 /// If the given user is locked:
1132 /// * and the user was initialized before, `Ok(UserState::Locked)` is returned.
1133 /// * and the user was not initialized before:
1134 /// * and `password` is None, `Ok(Uninitialized)` is returned.
1135 /// * and `password` is Some, super keys are generated and `Ok(UserState::LskfUnlocked)` is
1136 /// returned.
1137 pub fn reset_or_init_user_and_get_user_state(
1138 &mut self,
1139 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001140 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001141 user_id: UserId,
1142 password: Option<&Password>,
1143 ) -> Result<UserState> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001144 match self.get_per_boot_key_by_user_id_internal(user_id) {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001145 Some(_) if password.is_none() => {
1146 // Transitioning to swiping, delete only the super key in database and cache,
1147 // and super-encrypted keys in database (and in KM).
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001148 self.reset_user(db, legacy_importer, user_id, true).context(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001149 "In reset_or_init_user_and_get_user_state: Trying to delete keys from the db.",
1150 )?;
1151 // Lskf is now removed in Keystore.
1152 Ok(UserState::Uninitialized)
1153 }
1154 Some(super_key) => {
1155 // Keystore won't be notified when changing to a new password when LSKF is
1156 // already setup. Therefore, ideally this path wouldn't be reached.
1157 Ok(UserState::LskfUnlocked(super_key))
1158 }
1159 None => {
1160 // Check if a super key exists in the database or legacy database.
1161 // If so, return LskfLocked state.
1162 // Otherwise, i) if the password is provided, initialize the super key and return
1163 // LskfUnlocked state ii) if password is not provided, return Uninitialized state.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001164 self.check_and_initialize_super_key(db, legacy_importer, user_id, password)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001165 }
1166 }
1167 }
1168
1169 /// Unlocks the given user with the given password. If the key was already unlocked or unlocking
1170 /// was successful, `Ok(UserState::LskfUnlocked)` is returned.
1171 /// If the user was never initialized `Ok(UserState::Uninitialized)` is returned.
1172 pub fn unlock_and_get_user_state(
1173 &mut self,
1174 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001175 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001176 user_id: UserId,
1177 password: &Password,
1178 ) -> Result<UserState> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001179 match self.get_per_boot_key_by_user_id_internal(user_id) {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001180 Some(super_key) => {
1181 log::info!("In unlock_and_get_user_state. Trying to unlock when already unlocked.");
1182 Ok(UserState::LskfUnlocked(super_key))
1183 }
1184 None => {
1185 // Check if a super key exists in the database or legacy database.
1186 // If not, return Uninitialized state.
1187 // Otherwise, try to unlock the super key and if successful,
1188 // return LskfUnlocked.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001189 self.check_and_unlock_super_key(db, legacy_importer, user_id, password)
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001190 .context("In unlock_and_get_user_state. Failed to unlock super key.")
1191 }
1192 }
1193 }
1194
1195 /// Delete all the keys created on behalf of the user.
1196 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
1197 /// encrypted keys.
1198 pub fn reset_user(
1199 &mut self,
1200 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001201 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001202 user_id: UserId,
1203 keep_non_super_encrypted_keys: bool,
1204 ) -> Result<()> {
1205 // Mark keys created on behalf of the user as unreferenced.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001206 legacy_importer
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001207 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
1208 .context("In reset_user: Trying to delete legacy keys.")?;
1209 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
1210 .context("In reset user. Error in unbinding keys.")?;
1211
1212 // Delete super key in cache, if exists.
1213 self.forget_all_keys_for_user(user_id);
1214 Ok(())
1215 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001216}
1217
1218/// This enum represents different states of the user's life cycle in the device.
1219/// For now, only three states are defined. More states may be added later.
1220pub enum UserState {
1221 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
1222 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -07001223 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001224 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
1225 // Hence the per-boot super-key(s) is not available in the cache.
1226 // However, the encrypted super key is available in the database.
1227 LskfLocked,
1228 // There's no user in the device for the given user id, or the user with the user id has not
1229 // setup LSKF.
1230 Uninitialized,
1231}
1232
Janis Danisevskiseed69842021-02-18 20:04:10 -08001233/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1234/// `Sensitive` holds the non encrypted key and a reference to its super key.
1235/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1236/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1237/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001238pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001239 Sensitive {
1240 key: ZVec,
1241 /// If KeyMint reports that the key must be upgraded, we must
1242 /// re-encrypt the key before writing to the database; we use
1243 /// this key.
1244 reencrypt_with: Arc<SuperKey>,
1245 /// If this key was decrypted with an ECDH key, we want to
1246 /// re-encrypt it on first use whether it was upgraded or not;
1247 /// this field indicates that that's necessary.
1248 force_reencrypt: bool,
1249 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001250 NonSensitive(Vec<u8>),
1251 Ref(&'a [u8]),
1252}
1253
Paul Crowley8d5b2532021-03-19 10:53:07 -07001254impl<'a> KeyBlob<'a> {
1255 pub fn force_reencrypt(&self) -> bool {
1256 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1257 *force_reencrypt
1258 } else {
1259 false
1260 }
1261 }
1262}
1263
Janis Danisevskiseed69842021-02-18 20:04:10 -08001264/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001265impl<'a> Deref for KeyBlob<'a> {
1266 type Target = [u8];
1267
1268 fn deref(&self) -> &Self::Target {
1269 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001270 Self::Sensitive { key, .. } => key,
1271 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001272 Self::Ref(key) => key,
1273 }
1274 }
1275}