blob: 7a8b9bec9397ac01636d78886bda078ccc9e9401 [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,
Paul Crowley618869e2021-04-08 20:30:54 -070022 database::{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,
29 legacy_migrator::LegacyMigrator,
Paul Crowley618869e2021-04-08 20:30:54 -070030 raw_device::KeyMintDevice,
Paul Crowley8d5b2532021-03-19 10:53:07 -070031 try_insert::TryInsert,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070032 utils::watchdog as wd,
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};
Paul Crowley44c02da2021-04-08 17:04:43 +000048use keystore2_system_property::PropertyWatcher;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use std::{
50 collections::HashMap,
51 sync::Arc,
52 sync::{Mutex, Weak},
53};
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,
70 /// Public-key encryption with ECDH P-256
71 EcdhP256,
72}
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.
77pub struct SuperKeyType {
78 /// Alias used to look the key up in the `persistent.keyentry` table.
79 pub alias: &'static 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.
98pub const USER_SCREEN_LOCK_BOUND_ECDH_KEY: SuperKeyType = SuperKeyType {
99 alias: "USER_SCREEN_LOCK_BOUND_ECDH_KEY",
100 algorithm: SuperEncryptionAlgorithm::EcdhP256,
101};
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))
128 } else if let Some(boot_level) = metadata.max_boot_level() {
129 Some(SuperKeyIdentifier::BootLevel(*boot_level))
130 } else {
131 None
132 }
133 }
134
135 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
136 match self {
137 SuperKeyIdentifier::DatabaseId(id) => {
138 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
139 }
140 SuperKeyIdentifier::BootLevel(level) => {
141 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
142 }
143 }
144 }
Paul Crowley7a658392021-03-18 17:08:20 -0700145}
146
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000147pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700148 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700149 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000150 /// Identifier of the encrypting key, used to write an encrypted blob
151 /// back to the database after re-encryption eg on a key update.
152 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700153 /// ECDH is more expensive than AES. So on ECDH private keys we set the
154 /// reencrypt_with field to point at the corresponding AES key, and the
155 /// keys will be re-encrypted with AES on first use.
156 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000157}
158
159impl SuperKey {
Paul Crowley7a658392021-03-18 17:08:20 -0700160 /// For most purposes `unwrap_key` handles decryption,
161 /// but legacy handling and some tests need to assume AES and decrypt directly.
162 pub fn aes_gcm_decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700163 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
164 aes_gcm_decrypt(data, iv, tag, &self.key)
165 .context("In aes_gcm_decrypt: decryption failed")
166 } else {
167 Err(Error::sys()).context("In aes_gcm_decrypt: Key is not an AES key")
168 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000169 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700170}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000171
Paul Crowley618869e2021-04-08 20:30:54 -0700172/// A SuperKey that has been encrypted with an AES-GCM key. For
173/// encryption the key is in memory, and for decryption it is in KM.
174struct LockedKey {
175 algorithm: SuperEncryptionAlgorithm,
176 id: SuperKeyIdentifier,
177 nonce: Vec<u8>,
178 ciphertext: Vec<u8>, // with tag appended
179}
180
181impl LockedKey {
182 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
183 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
184 ciphertext.append(&mut tag);
185 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
186 }
187
188 fn decrypt(
189 &self,
190 db: &mut KeystoreDB,
191 km_dev: &KeyMintDevice,
192 key_id_guard: &KeyIdGuard,
193 key_entry: &KeyEntry,
194 auth_token: &HardwareAuthToken,
195 reencrypt_with: Option<Arc<SuperKey>>,
196 ) -> Result<Arc<SuperKey>> {
197 let key_params = vec![
198 KeyParameterValue::Algorithm(Algorithm::AES),
199 KeyParameterValue::KeySize(256),
200 KeyParameterValue::BlockMode(BlockMode::GCM),
201 KeyParameterValue::PaddingMode(PaddingMode::NONE),
202 KeyParameterValue::Nonce(self.nonce.clone()),
203 KeyParameterValue::MacLength(128),
204 ];
205 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
206 let key = ZVec::try_from(km_dev.use_key_in_one_step(
207 db,
208 key_id_guard,
209 key_entry,
210 KeyPurpose::DECRYPT,
211 &key_params,
212 Some(auth_token),
213 &self.ciphertext,
214 )?)?;
215 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
216 }
217}
218
219/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
220/// a database descriptor for the encrypting key and the sids for the auth tokens
221/// that can be used to decrypt it.
222struct BiometricUnlock {
223 /// List of auth token SIDs that can be used to unlock these keys.
224 sids: Vec<i64>,
225 /// Database descriptor of key to use to unlock.
226 key_desc: KeyDescriptor,
227 /// Locked versions of the matching UserSuperKeys fields
228 screen_lock_bound: LockedKey,
229 screen_lock_bound_private: LockedKey,
230}
231
Paul Crowleye8826e52021-03-31 08:33:53 -0700232#[derive(Default)]
233struct UserSuperKeys {
234 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
235 /// key per android user. The key is stored on flash encrypted with a key derived from a
236 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
237 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
238 /// and stays memory resident until the device reboots.
239 per_boot: Option<Arc<SuperKey>>,
240 /// The screen lock key works like the per boot key with the distinction that it is cleared
241 /// from memory when the screen lock is engaged.
242 screen_lock_bound: Option<Arc<SuperKey>>,
243 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
244 /// ECDH public-key encryption. This field holds the decryption private key.
245 screen_lock_bound_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700246 /// Versions of the above two keys, locked behind a biometric.
247 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000248}
249
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800250#[derive(Default)]
251struct SkmState {
252 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700253 key_index: HashMap<i64, Weak<SuperKey>>,
Paul Crowley44c02da2021-04-08 17:04:43 +0000254 boot_level_key_cache: Option<BootLevelKeyCache>,
Paul Crowley7a658392021-03-18 17:08:20 -0700255}
256
257impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000258 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
259 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
260 self.key_index.insert(id, Arc::downgrade(super_key));
261 Ok(())
262 } else {
263 Err(Error::sys()).context(format!(
264 "In add_key_to_key_index: cannot add key with ID {:?}",
265 super_key.id
266 ))
267 }
Paul Crowley7a658392021-03-18 17:08:20 -0700268 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800269}
270
271#[derive(Default)]
272pub struct SuperKeyManager {
273 data: Mutex<SkmState>,
274}
275
276impl SuperKeyManager {
Paul Crowley44c02da2021-04-08 17:04:43 +0000277 pub fn set_up_boot_level_cache(self: &Arc<Self>, db: &mut KeystoreDB) -> Result<()> {
278 let mut data = self.data.lock().unwrap();
279 if data.boot_level_key_cache.is_some() {
280 log::info!("In set_up_boot_level_cache: called for a second time");
281 return Ok(());
282 }
283 let level_zero_key = get_level_zero_key(db)
284 .context("In set_up_boot_level_cache: get_level_zero_key failed")?;
285 data.boot_level_key_cache = Some(BootLevelKeyCache::new(level_zero_key));
286 log::info!("Starting boot level watcher.");
287 let clone = self.clone();
288 std::thread::spawn(move || {
289 clone
290 .watch_boot_level()
291 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
292 });
293 Ok(())
294 }
295
296 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
297 /// Blocks waiting for system property changes, so must be run in its own thread.
298 fn watch_boot_level(&self) -> Result<()> {
299 let mut w = PropertyWatcher::new("keystore.boot_level")
300 .context("In watch_boot_level: PropertyWatcher::new failed")?;
301 loop {
302 let level = w
303 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
304 .context("In watch_boot_level: read of property failed")?;
305 // watch_boot_level should only be called once data.boot_level_key_cache is Some,
306 // so it's safe to unwrap in the branches below.
307 if level < MAX_MAX_BOOT_LEVEL {
308 log::info!("Read keystore.boot_level value {}", level);
309 let mut data = self.data.lock().unwrap();
310 data.boot_level_key_cache
311 .as_mut()
312 .unwrap()
313 .advance_boot_level(level)
314 .context("In watch_boot_level: advance_boot_level failed")?;
315 } else {
316 log::info!(
317 "keystore.boot_level {} hits maximum {}, finishing.",
318 level,
319 MAX_MAX_BOOT_LEVEL
320 );
321 let mut data = self.data.lock().unwrap();
322 data.boot_level_key_cache.as_mut().unwrap().finish();
323 break;
324 }
325 w.wait().context("In watch_boot_level: property wait failed")?;
326 }
327 Ok(())
328 }
329
330 pub fn level_accessible(&self, boot_level: i32) -> bool {
331 self.data
332 .lock()
333 .unwrap()
334 .boot_level_key_cache
335 .as_ref()
336 .map_or(false, |c| c.level_accessible(boot_level as usize))
337 }
338
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800339 pub fn forget_all_keys_for_user(&self, user: UserId) {
340 let mut data = self.data.lock().unwrap();
341 data.user_keys.remove(&user);
342 }
343
Paul Crowley44c02da2021-04-08 17:04:43 +0000344 fn install_per_boot_key_for_user(&self, user: UserId, super_key: Arc<SuperKey>) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800345 let mut data = self.data.lock().unwrap();
Paul Crowley44c02da2021-04-08 17:04:43 +0000346 data.add_key_to_key_index(&super_key)
347 .context("In install_per_boot_key_for_user: add_key_to_key_index failed")?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000348 data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000349 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800350 }
351
Paul Crowley44c02da2021-04-08 17:04:43 +0000352 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
353 let mut data = self.data.lock().unwrap();
354 Ok(match key_id {
355 SuperKeyIdentifier::DatabaseId(id) => data.key_index.get(id).and_then(|k| k.upgrade()),
356 SuperKeyIdentifier::BootLevel(level) => data
357 .boot_level_key_cache
358 .as_mut()
359 .map(|b| b.aes_key(*level as usize))
360 .transpose()
361 .context("In lookup_key: aes_key failed")?
362 .flatten()
363 .map(|key| {
364 Arc::new(SuperKey {
365 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
366 key,
367 id: *key_id,
368 reencrypt_with: None,
369 })
370 }),
371 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800372 }
373
Paul Crowley7a658392021-03-18 17:08:20 -0700374 pub fn get_per_boot_key_by_user_id(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800375 let data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700376 data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800377 }
378
379 /// This function unlocks the super keys for a given user.
380 /// This means the key is loaded from the database, decrypted and placed in the
381 /// super key cache. If there is no such key a new key is created, encrypted with
382 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800383 pub fn unlock_user_key(
384 &self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000385 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800386 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700387 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800388 legacy_blob_loader: &LegacyBlobLoader,
389 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800390 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800391 .get_or_create_key_with(
392 Domain::APP,
393 user as u64 as i64,
Paul Crowley7a658392021-03-18 17:08:20 -0700394 &USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800395 crate::database::KEYSTORE_UUID,
396 || {
397 // For backward compatibility we need to check if there is a super key present.
398 let super_key = legacy_blob_loader
399 .load_super_key(user, pw)
400 .context("In create_new_key: Failed to load legacy key blob.")?;
401 let super_key = match super_key {
402 None => {
403 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000404 generate_aes256_key()
Max Bires8e93d2b2021-01-14 13:17:59 -0800405 .context("In create_new_key: Failed to generate AES 256 key.")?
406 }
407 Some(key) => key,
408 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000409 // Regardless of whether we loaded an old AES128 key or generated a new AES256
410 // key as the super key, we derive a AES256 key from the password and re-encrypt
411 // the super key before we insert it in the database. The length of the key is
412 // preserved by the encryption so we don't need any extra flags to inform us
413 // which algorithm to use it with.
414 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800415 },
416 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800417 .context("In unlock_user_key: Failed to get key id.")?;
418
Paul Crowley8d5b2532021-03-19 10:53:07 -0700419 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
420 .context("In unlock_user_key.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800421 Ok(())
422 }
423
Paul Crowley44c02da2021-04-08 17:04:43 +0000424 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
425 /// the relevant super key.
426 pub fn unwrap_key_if_required<'a>(
427 &self,
428 metadata: &BlobMetaData,
429 blob: &'a [u8],
430 ) -> Result<KeyBlob<'a>> {
431 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
432 let super_key = self
433 .lookup_key(&key_id)
434 .context("In unwrap_key: lookup_key failed")?
435 .ok_or(Error::Rc(ResponseCode::LOCKED))
436 .context("In unwrap_key: Required super decryption key is not in memory.")?;
437 KeyBlob::Sensitive {
438 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
439 .context("In unwrap_key: unwrap_key_with_key failed")?,
440 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
441 force_reencrypt: super_key.reencrypt_with.is_some(),
442 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700443 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000444 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700445 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800446 }
447
448 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700449 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700450 match key.algorithm {
451 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
452 (Some(iv), Some(tag)) => key
453 .aes_gcm_decrypt(blob, iv, tag)
454 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
455 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
456 concat!(
457 "In unwrap_key_with_key: Key has incomplete metadata.",
458 "Present: iv: {}, aead_tag: {}."
459 ),
460 iv.is_some(),
461 tag.is_some(),
462 )),
463 },
464 SuperEncryptionAlgorithm::EcdhP256 => {
465 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
466 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
467 ECDHPrivateKey::from_private_key(&key.key)
468 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
469 .context(
470 "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.",
471 )
472 }
473 (public_key, salt, iv, aead_tag) => {
474 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
475 concat!(
476 "In unwrap_key_with_key: Key has incomplete metadata.",
477 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
478 ),
479 public_key.is_some(),
480 salt.is_some(),
481 iv.is_some(),
482 aead_tag.is_some(),
483 ))
484 }
485 }
486 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800487 }
488 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000489
490 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000491 pub fn super_key_exists_in_db_for_user(
492 db: &mut KeystoreDB,
493 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700494 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000495 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000496 let key_in_db = db
Paul Crowley7a658392021-03-18 17:08:20 -0700497 .key_exists(Domain::APP, user_id as u64 as i64, &USER_SUPER_KEY.alias, KeyType::Super)
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000498 .context("In super_key_exists_in_db_for_user.")?;
499
500 if key_in_db {
501 Ok(key_in_db)
502 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000503 legacy_migrator
504 .has_super_key(user_id)
505 .context("In super_key_exists_in_db_for_user: Trying to query legacy db.")
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000506 }
507 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000508
509 /// 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 +0000510 /// legacy database). If not, return Uninitialized state.
511 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
512 pub fn check_and_unlock_super_key(
513 &self,
514 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000515 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700516 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700517 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000518 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700519 let alias = &USER_SUPER_KEY;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000520 let result = legacy_migrator
Paul Crowley8d5b2532021-03-19 10:53:07 -0700521 .with_try_migrate_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000522 .context("In check_and_unlock_super_key. Failed to load super key")?;
523
524 match result {
525 Some((_, entry)) => {
526 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700527 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000528 .context("In check_and_unlock_super_key.")?;
529 Ok(UserState::LskfUnlocked(super_key))
530 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000531 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000532 }
533 }
534
535 /// 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 +0000536 /// legacy database). If so, return LskfLocked state.
537 /// If the password is provided, generate a new super key, encrypt with the password,
538 /// store in the database and populate the super key cache for the new user
539 /// and return LskfUnlocked state.
540 /// If the password is not provided, return Uninitialized state.
541 pub fn check_and_initialize_super_key(
542 &self,
543 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000544 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700545 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700546 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000547 ) -> Result<UserState> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000548 let super_key_exists_in_db =
549 Self::super_key_exists_in_db_for_user(db, legacy_migrator, user_id).context(
550 "In check_and_initialize_super_key. Failed to check if super key exists.",
551 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000552 if super_key_exists_in_db {
553 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000554 } else if let Some(pw) = pw {
555 //generate a new super key.
556 let super_key = generate_aes256_key()
557 .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?;
558 //derive an AES256 key from the password and re-encrypt the super key
559 //before we insert it in the database.
560 let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw)
561 .context("In check_and_initialize_super_key.")?;
562
563 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700564 .store_super_key(
565 user_id,
566 &USER_SUPER_KEY,
567 &encrypted_super_key,
568 &blob_metadata,
569 &KeyMetaData::new(),
570 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000571 .context("In check_and_initialize_super_key. Failed to store super key.")?;
572
573 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700574 .populate_cache_from_super_key_blob(
575 user_id,
576 USER_SUPER_KEY.algorithm,
577 key_entry,
578 pw,
579 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000580 .context("In check_and_initialize_super_key.")?;
581 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000582 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000583 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000584 }
585 }
586
587 //helper function to populate super key cache from the super key blob loaded from the database
588 fn populate_cache_from_super_key_blob(
589 &self,
Paul Crowley7a658392021-03-18 17:08:20 -0700590 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700591 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000592 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700593 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700594 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700595 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
596 .context(
597 "In populate_cache_from_super_key_blob. Failed to extract super key from key entry",
598 )?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000599 self.install_per_boot_key_for_user(user_id, super_key.clone())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000600 Ok(super_key)
601 }
602
603 /// Extracts super key from the entry loaded from the database
Paul Crowley7a658392021-03-18 17:08:20 -0700604 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700605 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700606 entry: KeyEntry,
607 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700608 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700609 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000610 if let Some((blob, metadata)) = entry.key_blob_info() {
611 let key = match (
612 metadata.encrypted_by(),
613 metadata.salt(),
614 metadata.iv(),
615 metadata.aead_tag(),
616 ) {
617 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700618 // Note that password encryption is AES no matter the value of algorithm
Paul Crowleyf61fee72021-03-17 14:38:44 -0700619 let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context(
620 "In extract_super_key_from_key_entry: Failed to generate key from password.",
621 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000622
623 aes_gcm_decrypt(blob, iv, tag, &key).context(
624 "In extract_super_key_from_key_entry: Failed to decrypt key blob.",
625 )?
626 }
627 (enc_by, salt, iv, tag) => {
628 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
629 concat!(
630 "In extract_super_key_from_key_entry: Super key has incomplete metadata.",
Paul Crowleye8826e52021-03-31 08:33:53 -0700631 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
Hasini Gunasingheda895552021-01-27 19:34:37 +0000632 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700633 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000634 salt.is_some(),
635 iv.is_some(),
636 tag.is_some()
637 ));
638 }
639 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000640 Ok(Arc::new(SuperKey {
641 algorithm,
642 key,
643 id: SuperKeyIdentifier::DatabaseId(entry.id()),
644 reencrypt_with,
645 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000646 } else {
647 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
648 .context("In extract_super_key_from_key_entry: No key blob info.")
649 }
650 }
651
652 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700653 pub fn encrypt_with_password(
654 super_key: &[u8],
655 pw: &Password,
656 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000657 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700658 let derived_key = pw
659 .derive_key(Some(&salt), AES_256_KEY_LENGTH)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000660 .context("In encrypt_with_password: Failed to derive password.")?;
661 let mut metadata = BlobMetaData::new();
662 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
663 metadata.add(BlobMetaEntry::Salt(salt));
664 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
665 .context("In encrypt_with_password: Failed to encrypt new super key.")?;
666 metadata.add(BlobMetaEntry::Iv(iv));
667 metadata.add(BlobMetaEntry::AeadTag(tag));
668 Ok((encrypted_key, metadata))
669 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000670
671 // Encrypt the given key blob with the user's super key, if the super key exists and the device
672 // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
673 // return error. Note that it is out of the scope of this function to check if super encryption
674 // is required. Such check should be performed before calling this function.
675 fn super_encrypt_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000676 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000677 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000678 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700679 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000680 key_blob: &[u8],
681 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000682 match UserState::get(db, legacy_migrator, self, user_id)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000683 .context("In super_encrypt. Failed to get user state.")?
684 {
685 UserState::LskfUnlocked(super_key) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700686 Self::encrypt_with_aes_super_key(key_blob, &super_key)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000687 .context("In super_encrypt_on_key_init. Failed to encrypt the key.")
688 }
689 UserState::LskfLocked => {
690 Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.")
691 }
692 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
693 .context("In super_encrypt. LSKF is not setup for the user."),
694 }
695 }
696
697 //Helper function to encrypt a key with the given super key. Callers should select which super
698 //key to be used. This is called when a key is super encrypted at its creation as well as at its
699 //upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700700 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000701 key_blob: &[u8],
702 super_key: &SuperKey,
703 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700704 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
705 return Err(Error::sys())
706 .context("In encrypt_with_aes_super_key: unexpected algorithm");
707 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000708 let mut metadata = BlobMetaData::new();
709 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700710 .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000711 metadata.add(BlobMetaEntry::Iv(iv));
712 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000713 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000714 Ok((encrypted_key, metadata))
715 }
716
717 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
718 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700719 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000720 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000721 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000722 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000723 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000724 domain: &Domain,
725 key_parameters: &[KeyParameter],
726 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700727 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000728 key_blob: &[u8],
729 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700730 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
731 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Paul Crowleye8826e52021-03-31 08:33:53 -0700732 SuperEncryptionType::LskfBound => self
733 .super_encrypt_on_key_init(db, legacy_migrator, user_id, &key_blob)
734 .context(concat!(
735 "In handle_super_encryption_on_key_init. ",
736 "Failed to super encrypt with LskfBound key."
737 )),
Paul Crowley7a658392021-03-18 17:08:20 -0700738 SuperEncryptionType::ScreenLockBound => {
739 let mut data = self.data.lock().unwrap();
740 let entry = data.user_keys.entry(user_id).or_default();
741 if let Some(super_key) = entry.screen_lock_bound.as_ref() {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700742 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
Paul Crowley7a658392021-03-18 17:08:20 -0700743 "In handle_super_encryption_on_key_init. ",
Paul Crowleye8826e52021-03-31 08:33:53 -0700744 "Failed to encrypt with ScreenLockBound key."
Paul Crowley7a658392021-03-18 17:08:20 -0700745 ))
746 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700747 // Symmetric key is not available, use public key encryption
748 let loaded =
749 db.load_super_key(&USER_SCREEN_LOCK_BOUND_ECDH_KEY, user_id).context(
750 "In handle_super_encryption_on_key_init: load_super_key failed.",
751 )?;
752 let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context(
753 "In handle_super_encryption_on_key_init: User ECDH key missing.",
754 )?;
755 let public_key =
756 key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context(
757 "In handle_super_encryption_on_key_init: sec1_public_key missing.",
758 )?;
759 let mut metadata = BlobMetaData::new();
760 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
761 ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!(
762 "In handle_super_encryption_on_key_init: ",
763 "ECDHPrivateKey::encrypt_message failed."
764 ))?;
765 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
766 metadata.add(BlobMetaEntry::Salt(salt));
767 metadata.add(BlobMetaEntry::Iv(iv));
768 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000769 SuperKeyIdentifier::DatabaseId(key_id_guard.id())
770 .add_to_metadata(&mut metadata);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700771 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700772 }
773 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000774 SuperEncryptionType::BootLevel(level) => {
775 let key_id = SuperKeyIdentifier::BootLevel(level);
776 let super_key = self
777 .lookup_key(&key_id)
778 .context("In handle_super_encryption_on_key_init: lookup_key failed")?
779 .ok_or(Error::Rc(ResponseCode::LOCKED))
780 .context("In handle_super_encryption_on_key_init: Boot stage key absent")?;
781 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
782 "In handle_super_encryption_on_key_init: ",
783 "Failed to encrypt with BootLevel key."
784 ))
785 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000786 }
787 }
788
789 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
790 /// If so, re-super-encrypt the key and return a new set of metadata,
791 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700792 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000793 key_blob_before_upgrade: &KeyBlob,
794 key_after_upgrade: &'a [u8],
795 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
796 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700797 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700798 let (key, metadata) =
799 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
800 .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000801 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
802 }
803 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
804 }
805 }
806
Paul Crowley7a658392021-03-18 17:08:20 -0700807 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
808 /// When this is called, the caller must hold the lock on the SuperKeyManager.
809 /// So it's OK that the check and creation are different DB transactions.
810 fn get_or_create_super_key(
811 db: &mut KeystoreDB,
812 user_id: UserId,
813 key_type: &SuperKeyType,
814 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700815 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700816 ) -> Result<Arc<SuperKey>> {
817 let loaded_key = db.load_super_key(key_type, user_id)?;
818 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700819 Ok(Self::extract_super_key_from_key_entry(
820 key_type.algorithm,
821 key_entry,
822 password,
823 reencrypt_with,
824 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700825 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700826 let (super_key, public_key) = match key_type.algorithm {
827 SuperEncryptionAlgorithm::Aes256Gcm => (
828 generate_aes256_key()
829 .context("In get_or_create_super_key: Failed to generate AES 256 key.")?,
830 None,
831 ),
832 SuperEncryptionAlgorithm::EcdhP256 => {
833 let key = ECDHPrivateKey::generate()
834 .context("In get_or_create_super_key: Failed to generate ECDH key")?;
835 (
836 key.private_key()
837 .context("In get_or_create_super_key: private_key failed")?,
838 Some(
839 key.public_key()
840 .context("In get_or_create_super_key: public_key failed")?,
841 ),
842 )
843 }
844 };
Paul Crowley7a658392021-03-18 17:08:20 -0700845 //derive an AES256 key from the password and re-encrypt the super key
846 //before we insert it in the database.
847 let (encrypted_super_key, blob_metadata) =
848 Self::encrypt_with_password(&super_key, password)
849 .context("In get_or_create_super_key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700850 let mut key_metadata = KeyMetaData::new();
851 if let Some(pk) = public_key {
852 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
853 }
Paul Crowley7a658392021-03-18 17:08:20 -0700854 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700855 .store_super_key(
856 user_id,
857 key_type,
858 &encrypted_super_key,
859 &blob_metadata,
860 &key_metadata,
861 )
Paul Crowley7a658392021-03-18 17:08:20 -0700862 .context("In get_or_create_super_key. Failed to store super key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700863 Ok(Arc::new(SuperKey {
864 algorithm: key_type.algorithm,
865 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000866 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700867 reencrypt_with,
868 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700869 }
870 }
871
Paul Crowley8d5b2532021-03-19 10:53:07 -0700872 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700873 pub fn unlock_screen_lock_bound_key(
874 &self,
875 db: &mut KeystoreDB,
876 user_id: UserId,
877 password: &Password,
878 ) -> Result<()> {
879 let mut data = self.data.lock().unwrap();
880 let entry = data.user_keys.entry(user_id).or_default();
881 let aes = entry
882 .screen_lock_bound
883 .get_or_try_to_insert_with(|| {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700884 Self::get_or_create_super_key(
885 db,
886 user_id,
887 &USER_SCREEN_LOCK_BOUND_KEY,
888 password,
889 None,
890 )
891 })?
892 .clone();
893 let ecdh = entry
894 .screen_lock_bound_private
895 .get_or_try_to_insert_with(|| {
896 Self::get_or_create_super_key(
897 db,
898 user_id,
899 &USER_SCREEN_LOCK_BOUND_ECDH_KEY,
900 password,
901 Some(aes.clone()),
902 )
Paul Crowley7a658392021-03-18 17:08:20 -0700903 })?
904 .clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000905 data.add_key_to_key_index(&aes)?;
906 data.add_key_to_key_index(&ecdh)?;
Paul Crowley7a658392021-03-18 17:08:20 -0700907 Ok(())
908 }
909
Paul Crowley8d5b2532021-03-19 10:53:07 -0700910 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley618869e2021-04-08 20:30:54 -0700911 pub fn lock_screen_lock_bound_key(
912 &self,
913 db: &mut KeystoreDB,
914 user_id: UserId,
915 unlocking_sids: &[i64],
916 ) {
917 log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
Paul Crowley7a658392021-03-18 17:08:20 -0700918 let mut data = self.data.lock().unwrap();
919 let mut entry = data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700920 if !unlocking_sids.is_empty() {
921 if let (Some(aes), Some(ecdh)) = (
922 entry.screen_lock_bound.as_ref().cloned(),
923 entry.screen_lock_bound_private.as_ref().cloned(),
924 ) {
925 let res = (|| -> Result<()> {
926 let key_desc = KeyMintDevice::internal_descriptor(format!(
927 "biometric_unlock_key_{}",
928 user_id
929 ));
930 let encrypting_key = generate_aes256_key()?;
931 let km_dev: KeyMintDevice =
932 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
933 .context("In lock_screen_lock_bound_key: KeyMintDevice::get failed")?;
934 let mut key_params = vec![
935 KeyParameterValue::Algorithm(Algorithm::AES),
936 KeyParameterValue::KeySize(256),
937 KeyParameterValue::BlockMode(BlockMode::GCM),
938 KeyParameterValue::PaddingMode(PaddingMode::NONE),
939 KeyParameterValue::CallerNonce,
940 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
941 KeyParameterValue::MinMacLength(128),
942 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
943 KeyParameterValue::HardwareAuthenticatorType(
944 HardwareAuthenticatorType::FINGERPRINT,
945 ),
946 ];
947 for sid in unlocking_sids {
948 key_params.push(KeyParameterValue::UserSecureID(*sid));
949 }
950 let key_params: Vec<KmKeyParameter> =
951 key_params.into_iter().map(|x| x.into()).collect();
952 km_dev.create_and_store_key(db, &key_desc, |dev| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700953 let _wp = wd::watch_millis(
954 "In lock_screen_lock_bound_key: calling importKey.",
955 500,
956 );
Paul Crowley618869e2021-04-08 20:30:54 -0700957 dev.importKey(key_params.as_slice(), KeyFormat::RAW, &encrypting_key, None)
958 })?;
959 entry.biometric_unlock = Some(BiometricUnlock {
960 sids: unlocking_sids.into(),
961 key_desc,
962 screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
963 screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
964 });
965 Ok(())
966 })();
967 // There is no reason to propagate an error here upwards. We must discard
968 // entry.screen_lock_bound* in any case.
969 if let Err(e) = res {
970 log::error!("Error setting up biometric unlock: {:#?}", e);
971 }
972 }
973 }
Paul Crowley7a658392021-03-18 17:08:20 -0700974 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700975 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700976 }
Paul Crowley618869e2021-04-08 20:30:54 -0700977
978 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
979 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
980 pub fn try_unlock_user_with_biometric(
981 &self,
982 db: &mut KeystoreDB,
983 user_id: UserId,
984 ) -> Result<()> {
985 let mut data = self.data.lock().unwrap();
986 let mut entry = data.user_keys.entry(user_id).or_default();
987 if let Some(biometric) = entry.biometric_unlock.as_ref() {
988 let (key_id_guard, key_entry) =
989 KeyMintDevice::lookup_from_desc(db, &biometric.key_desc)?;
990 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
991 .context("In try_unlock_user_with_biometric: KeyMintDevice::get failed")?;
992 for sid in &biometric.sids {
993 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
994 entry.auth_token().userId == *sid || entry.auth_token().authenticatorId == *sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700995 }) {
Paul Crowley618869e2021-04-08 20:30:54 -0700996 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
997 let slb = biometric.screen_lock_bound.decrypt(
998 db,
999 &km_dev,
1000 &key_id_guard,
1001 &key_entry,
1002 auth_token_entry.auth_token(),
1003 None,
1004 )?;
1005 let slbp = biometric.screen_lock_bound_private.decrypt(
1006 db,
1007 &km_dev,
1008 &key_id_guard,
1009 &key_entry,
1010 auth_token_entry.auth_token(),
1011 Some(slb.clone()),
1012 )?;
1013 Ok((slb, slbp))
1014 })();
1015 match res {
1016 Ok((slb, slbp)) => {
1017 entry.screen_lock_bound = Some(slb.clone());
1018 entry.screen_lock_bound_private = Some(slbp.clone());
1019 data.add_key_to_key_index(&slb)?;
1020 data.add_key_to_key_index(&slbp)?;
1021 log::info!(concat!(
1022 "In try_unlock_user_with_biometric: ",
1023 "Successfully unlocked with biometric"
1024 ));
1025 return Ok(());
1026 }
1027 Err(e) => {
1028 log::warn!("In try_unlock_user_with_biometric: attempt failed: {:?}", e)
1029 }
1030 }
1031 }
1032 }
1033 }
1034 Ok(())
1035 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001036}
1037
1038/// This enum represents different states of the user's life cycle in the device.
1039/// For now, only three states are defined. More states may be added later.
1040pub enum UserState {
1041 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
1042 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -07001043 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001044 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
1045 // Hence the per-boot super-key(s) is not available in the cache.
1046 // However, the encrypted super key is available in the database.
1047 LskfLocked,
1048 // There's no user in the device for the given user id, or the user with the user id has not
1049 // setup LSKF.
1050 Uninitialized,
1051}
1052
1053impl UserState {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001054 pub fn get(
1055 db: &mut KeystoreDB,
1056 legacy_migrator: &LegacyMigrator,
1057 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -07001058 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001059 ) -> Result<UserState> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001060 match skm.get_per_boot_key_by_user_id(user_id) {
1061 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.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001065 if SuperKeyManager::super_key_exists_in_db_for_user(db, legacy_migrator, user_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00001066 .context("In get.")?
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001067 {
1068 Ok(UserState::LskfLocked)
1069 } else {
1070 Ok(UserState::Uninitialized)
1071 }
1072 }
1073 }
1074 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00001075
1076 /// Queries user state when serving password change requests.
1077 pub fn get_with_password_changed(
1078 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001079 legacy_migrator: &LegacyMigrator,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001080 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -07001081 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -07001082 password: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001083 ) -> Result<UserState> {
1084 match skm.get_per_boot_key_by_user_id(user_id) {
1085 Some(super_key) => {
1086 if password.is_none() {
1087 //transitioning to swiping, delete only the super key in database and cache, and
1088 //super-encrypted keys in database (and in KM)
Janis Danisevskiseed69842021-02-18 20:04:10 -08001089 Self::reset_user(db, skm, legacy_migrator, user_id, true).context(
1090 "In get_with_password_changed: Trying to delete keys from the db.",
1091 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00001092 //Lskf is now removed in Keystore
1093 Ok(UserState::Uninitialized)
1094 } else {
1095 //Keystore won't be notified when changing to a new password when LSKF is
1096 //already setup. Therefore, ideally this path wouldn't be reached.
1097 Ok(UserState::LskfUnlocked(super_key))
1098 }
1099 }
1100 None => {
1101 //Check if a super key exists in the database or legacy database.
1102 //If so, return LskfLocked state.
1103 //Otherwise, i) if the password is provided, initialize the super key and return
1104 //LskfUnlocked state ii) if password is not provided, return Uninitialized state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001105 skm.check_and_initialize_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasingheda895552021-01-27 19:34:37 +00001106 }
1107 }
1108 }
1109
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001110 /// Queries user state when serving password unlock requests.
1111 pub fn get_with_password_unlock(
1112 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001113 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001114 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -07001115 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -07001116 password: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001117 ) -> Result<UserState> {
1118 match skm.get_per_boot_key_by_user_id(user_id) {
1119 Some(super_key) => {
1120 log::info!("In get_with_password_unlock. Trying to unlock when already unlocked.");
1121 Ok(UserState::LskfUnlocked(super_key))
1122 }
1123 None => {
1124 //Check if a super key exists in the database or legacy database.
1125 //If not, return Uninitialized state.
1126 //Otherwise, try to unlock the super key and if successful,
1127 //return LskfUnlocked state
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001128 skm.check_and_unlock_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001129 .context("In get_with_password_unlock. Failed to unlock super key.")
1130 }
1131 }
1132 }
1133
Hasini Gunasingheda895552021-01-27 19:34:37 +00001134 /// Delete all the keys created on behalf of the user.
1135 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
1136 /// encrypted keys.
1137 pub fn reset_user(
1138 db: &mut KeystoreDB,
1139 skm: &SuperKeyManager,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001140 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -07001141 user_id: UserId,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001142 keep_non_super_encrypted_keys: bool,
1143 ) -> Result<()> {
1144 // mark keys created on behalf of the user as unreferenced.
Janis Danisevskiseed69842021-02-18 20:04:10 -08001145 legacy_migrator
1146 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
1147 .context("In reset_user: Trying to delete legacy keys.")?;
Paul Crowley7a658392021-03-18 17:08:20 -07001148 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
Hasini Gunasingheda895552021-01-27 19:34:37 +00001149 .context("In reset user. Error in unbinding keys.")?;
1150
1151 //delete super key in cache, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001152 skm.forget_all_keys_for_user(user_id);
Hasini Gunasingheda895552021-01-27 19:34:37 +00001153 Ok(())
1154 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001155}
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001156
Janis Danisevskiseed69842021-02-18 20:04:10 -08001157/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1158/// `Sensitive` holds the non encrypted key and a reference to its super key.
1159/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1160/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1161/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001162pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001163 Sensitive {
1164 key: ZVec,
1165 /// If KeyMint reports that the key must be upgraded, we must
1166 /// re-encrypt the key before writing to the database; we use
1167 /// this key.
1168 reencrypt_with: Arc<SuperKey>,
1169 /// If this key was decrypted with an ECDH key, we want to
1170 /// re-encrypt it on first use whether it was upgraded or not;
1171 /// this field indicates that that's necessary.
1172 force_reencrypt: bool,
1173 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001174 NonSensitive(Vec<u8>),
1175 Ref(&'a [u8]),
1176}
1177
Paul Crowley8d5b2532021-03-19 10:53:07 -07001178impl<'a> KeyBlob<'a> {
1179 pub fn force_reencrypt(&self) -> bool {
1180 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1181 *force_reencrypt
1182 } else {
1183 false
1184 }
1185 }
1186}
1187
Janis Danisevskiseed69842021-02-18 20:04:10 -08001188/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001189impl<'a> Deref for KeyBlob<'a> {
1190 type Target = [u8];
1191
1192 fn deref(&self) -> &Self::Target {
1193 match self {
Paul Crowley7a658392021-03-18 17:08:20 -07001194 Self::Sensitive { key, .. } => &key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001195 Self::NonSensitive(key) => &key,
1196 Self::Ref(key) => key,
1197 }
1198 }
1199}