blob: 4b71bb5f4fb184b4d36c6817cba4f77652ef9cb1 [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,
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 Danisevskisacebfa22021-05-25 10:56:10 -070033 utils::AID_KEYSTORE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080034};
Paul Crowley618869e2021-04-08 20:30:54 -070035use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
36 Algorithm::Algorithm, BlockMode::BlockMode, HardwareAuthToken::HardwareAuthToken,
37 HardwareAuthenticatorType::HardwareAuthenticatorType, KeyFormat::KeyFormat,
38 KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
39 SecurityLevel::SecurityLevel,
40};
41use android_system_keystore2::aidl::android::system::keystore2::{
42 Domain::Domain, KeyDescriptor::KeyDescriptor,
43};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080044use anyhow::{Context, Result};
45use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070046 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
47 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080048};
49use 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};
Joel Galensonf2357062021-07-20 12:57:54 -070055use system_properties::PropertyWatcher;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080056
Paul Crowley44c02da2021-04-08 17:04:43 +000057const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
Paul Crowley618869e2021-04-08 20:30:54 -070058/// Allow up to 15 seconds between the user unlocking using a biometric, and the auth
59/// token being used to unlock in [`SuperKeyManager::try_unlock_user_with_biometric`].
60/// This seems short enough for security purposes, while long enough that even the
61/// very slowest device will present the auth token in time.
62const BIOMETRIC_AUTH_TIMEOUT_S: i32 = 15; // seconds
Paul Crowley44c02da2021-04-08 17:04:43 +000063
Janis Danisevskisb42fc182020-12-15 08:41:27 -080064type UserId = u32;
65
Paul Crowley8d5b2532021-03-19 10:53:07 -070066/// Encryption algorithm used by a particular type of superencryption key
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum SuperEncryptionAlgorithm {
69 /// Symmetric encryption with AES-256-GCM
70 Aes256Gcm,
Paul Crowley52f017f2021-06-22 08:16:01 -070071 /// Public-key encryption with ECDH P-521
72 EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -070073}
74
Paul Crowley7a658392021-03-18 17:08:20 -070075/// A particular user may have several superencryption keys in the database, each for a
76/// different purpose, distinguished by alias. Each is associated with a static
77/// constant of this type.
78pub struct SuperKeyType {
79 /// Alias used to look the key up in the `persistent.keyentry` table.
80 pub alias: &'static str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070081 /// Encryption algorithm
82 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070083}
84
85/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
86/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070087pub const USER_SUPER_KEY: SuperKeyType =
88 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070089/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
90/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070091/// Symmetric.
92pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
93 alias: "USER_SCREEN_LOCK_BOUND_KEY",
94 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
95};
96/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
97/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
98/// Asymmetric, so keys can be encrypted when the device is locked.
Paul Crowley52f017f2021-06-22 08:16:01 -070099pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
100 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
101 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700102};
Paul Crowley7a658392021-03-18 17:08:20 -0700103
104/// Superencryption to apply to a new key.
105#[derive(Debug, Clone, Copy)]
106pub enum SuperEncryptionType {
107 /// Do not superencrypt this key.
108 None,
109 /// Superencrypt with a key that remains in memory from first unlock to reboot.
110 LskfBound,
111 /// Superencrypt with a key cleared from memory when the device is locked.
112 ScreenLockBound,
Paul Crowley44c02da2021-04-08 17:04:43 +0000113 /// Superencrypt with a key based on the desired boot level
114 BootLevel(i32),
115}
116
117#[derive(Debug, Clone, Copy)]
118pub enum SuperKeyIdentifier {
119 /// id of the super key in the database.
120 DatabaseId(i64),
121 /// Boot level of the encrypting boot level key
122 BootLevel(i32),
123}
124
125impl SuperKeyIdentifier {
126 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
127 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
128 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000129 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700130 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000131 }
132 }
133
134 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
135 match self {
136 SuperKeyIdentifier::DatabaseId(id) => {
137 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
138 }
139 SuperKeyIdentifier::BootLevel(level) => {
140 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
141 }
142 }
143 }
Paul Crowley7a658392021-03-18 17:08:20 -0700144}
145
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000146pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700147 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700148 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000149 /// Identifier of the encrypting key, used to write an encrypted blob
150 /// back to the database after re-encryption eg on a key update.
151 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700152 /// ECDH is more expensive than AES. So on ECDH private keys we set the
153 /// reencrypt_with field to point at the corresponding AES key, and the
154 /// keys will be re-encrypted with AES on first use.
155 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000156}
157
158impl SuperKey {
Paul Crowley7a658392021-03-18 17:08:20 -0700159 /// For most purposes `unwrap_key` handles decryption,
160 /// but legacy handling and some tests need to assume AES and decrypt directly.
161 pub fn aes_gcm_decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700162 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
163 aes_gcm_decrypt(data, iv, tag, &self.key)
164 .context("In aes_gcm_decrypt: decryption failed")
165 } else {
166 Err(Error::sys()).context("In aes_gcm_decrypt: Key is not an AES key")
167 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000168 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700169}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000170
Paul Crowley618869e2021-04-08 20:30:54 -0700171/// A SuperKey that has been encrypted with an AES-GCM key. For
172/// encryption the key is in memory, and for decryption it is in KM.
173struct LockedKey {
174 algorithm: SuperEncryptionAlgorithm,
175 id: SuperKeyIdentifier,
176 nonce: Vec<u8>,
177 ciphertext: Vec<u8>, // with tag appended
178}
179
180impl LockedKey {
181 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
182 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
183 ciphertext.append(&mut tag);
184 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
185 }
186
187 fn decrypt(
188 &self,
189 db: &mut KeystoreDB,
190 km_dev: &KeyMintDevice,
191 key_id_guard: &KeyIdGuard,
192 key_entry: &KeyEntry,
193 auth_token: &HardwareAuthToken,
194 reencrypt_with: Option<Arc<SuperKey>>,
195 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700196 let key_blob = key_entry
197 .key_blob_info()
198 .as_ref()
199 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
200 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
201 .context("In LockedKey::decrypt: Missing key blob info.")?;
Paul Crowley618869e2021-04-08 20:30:54 -0700202 let key_params = vec![
203 KeyParameterValue::Algorithm(Algorithm::AES),
204 KeyParameterValue::KeySize(256),
205 KeyParameterValue::BlockMode(BlockMode::GCM),
206 KeyParameterValue::PaddingMode(PaddingMode::NONE),
207 KeyParameterValue::Nonce(self.nonce.clone()),
208 KeyParameterValue::MacLength(128),
209 ];
210 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
211 let key = ZVec::try_from(km_dev.use_key_in_one_step(
212 db,
213 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700214 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700215 KeyPurpose::DECRYPT,
216 &key_params,
217 Some(auth_token),
218 &self.ciphertext,
219 )?)?;
220 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
221 }
222}
223
224/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
225/// a database descriptor for the encrypting key and the sids for the auth tokens
226/// that can be used to decrypt it.
227struct BiometricUnlock {
228 /// List of auth token SIDs that can be used to unlock these keys.
229 sids: Vec<i64>,
230 /// Database descriptor of key to use to unlock.
231 key_desc: KeyDescriptor,
232 /// Locked versions of the matching UserSuperKeys fields
233 screen_lock_bound: LockedKey,
234 screen_lock_bound_private: LockedKey,
235}
236
Paul Crowleye8826e52021-03-31 08:33:53 -0700237#[derive(Default)]
238struct UserSuperKeys {
239 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
240 /// key per android user. The key is stored on flash encrypted with a key derived from a
241 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
242 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
243 /// and stays memory resident until the device reboots.
244 per_boot: Option<Arc<SuperKey>>,
245 /// The screen lock key works like the per boot key with the distinction that it is cleared
246 /// from memory when the screen lock is engaged.
247 screen_lock_bound: Option<Arc<SuperKey>>,
248 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
249 /// ECDH public-key encryption. This field holds the decryption private key.
250 screen_lock_bound_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700251 /// Versions of the above two keys, locked behind a biometric.
252 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000253}
254
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800255#[derive(Default)]
256struct SkmState {
257 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700258 key_index: HashMap<i64, Weak<SuperKey>>,
Paul Crowley44c02da2021-04-08 17:04:43 +0000259 boot_level_key_cache: Option<BootLevelKeyCache>,
Paul Crowley7a658392021-03-18 17:08:20 -0700260}
261
262impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000263 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
264 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
265 self.key_index.insert(id, Arc::downgrade(super_key));
266 Ok(())
267 } else {
268 Err(Error::sys()).context(format!(
269 "In add_key_to_key_index: cannot add key with ID {:?}",
270 super_key.id
271 ))
272 }
Paul Crowley7a658392021-03-18 17:08:20 -0700273 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800274}
275
276#[derive(Default)]
277pub struct SuperKeyManager {
278 data: Mutex<SkmState>,
279}
280
281impl SuperKeyManager {
Paul Crowley44c02da2021-04-08 17:04:43 +0000282 pub fn set_up_boot_level_cache(self: &Arc<Self>, db: &mut KeystoreDB) -> Result<()> {
283 let mut data = self.data.lock().unwrap();
284 if data.boot_level_key_cache.is_some() {
285 log::info!("In set_up_boot_level_cache: called for a second time");
286 return Ok(());
287 }
288 let level_zero_key = get_level_zero_key(db)
289 .context("In set_up_boot_level_cache: get_level_zero_key failed")?;
290 data.boot_level_key_cache = Some(BootLevelKeyCache::new(level_zero_key));
291 log::info!("Starting boot level watcher.");
292 let clone = self.clone();
293 std::thread::spawn(move || {
294 clone
295 .watch_boot_level()
296 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
297 });
298 Ok(())
299 }
300
301 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
302 /// Blocks waiting for system property changes, so must be run in its own thread.
303 fn watch_boot_level(&self) -> Result<()> {
304 let mut w = PropertyWatcher::new("keystore.boot_level")
305 .context("In watch_boot_level: PropertyWatcher::new failed")?;
306 loop {
307 let level = w
308 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
309 .context("In watch_boot_level: read of property failed")?;
310 // watch_boot_level should only be called once data.boot_level_key_cache is Some,
311 // so it's safe to unwrap in the branches below.
312 if level < MAX_MAX_BOOT_LEVEL {
313 log::info!("Read keystore.boot_level value {}", level);
314 let mut data = self.data.lock().unwrap();
315 data.boot_level_key_cache
316 .as_mut()
317 .unwrap()
318 .advance_boot_level(level)
319 .context("In watch_boot_level: advance_boot_level failed")?;
320 } else {
321 log::info!(
322 "keystore.boot_level {} hits maximum {}, finishing.",
323 level,
324 MAX_MAX_BOOT_LEVEL
325 );
326 let mut data = self.data.lock().unwrap();
327 data.boot_level_key_cache.as_mut().unwrap().finish();
328 break;
329 }
330 w.wait().context("In watch_boot_level: property wait failed")?;
331 }
332 Ok(())
333 }
334
335 pub fn level_accessible(&self, boot_level: i32) -> bool {
336 self.data
337 .lock()
338 .unwrap()
339 .boot_level_key_cache
340 .as_ref()
341 .map_or(false, |c| c.level_accessible(boot_level as usize))
342 }
343
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800344 pub fn forget_all_keys_for_user(&self, user: UserId) {
345 let mut data = self.data.lock().unwrap();
346 data.user_keys.remove(&user);
347 }
348
Paul Crowley44c02da2021-04-08 17:04:43 +0000349 fn install_per_boot_key_for_user(&self, user: UserId, super_key: Arc<SuperKey>) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800350 let mut data = self.data.lock().unwrap();
Paul Crowley44c02da2021-04-08 17:04:43 +0000351 data.add_key_to_key_index(&super_key)
352 .context("In install_per_boot_key_for_user: add_key_to_key_index failed")?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000353 data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000354 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800355 }
356
Paul Crowley44c02da2021-04-08 17:04:43 +0000357 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
358 let mut data = self.data.lock().unwrap();
359 Ok(match key_id {
360 SuperKeyIdentifier::DatabaseId(id) => data.key_index.get(id).and_then(|k| k.upgrade()),
361 SuperKeyIdentifier::BootLevel(level) => data
362 .boot_level_key_cache
363 .as_mut()
364 .map(|b| b.aes_key(*level as usize))
365 .transpose()
366 .context("In lookup_key: aes_key failed")?
367 .flatten()
368 .map(|key| {
369 Arc::new(SuperKey {
370 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
371 key,
372 id: *key_id,
373 reencrypt_with: None,
374 })
375 }),
376 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800377 }
378
Paul Crowley7a658392021-03-18 17:08:20 -0700379 pub fn get_per_boot_key_by_user_id(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800380 let data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700381 data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800382 }
383
384 /// This function unlocks the super keys for a given user.
385 /// This means the key is loaded from the database, decrypted and placed in the
386 /// super key cache. If there is no such key a new key is created, encrypted with
387 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800388 pub fn unlock_user_key(
389 &self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000390 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800391 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700392 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800393 legacy_blob_loader: &LegacyBlobLoader,
394 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800395 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800396 .get_or_create_key_with(
397 Domain::APP,
398 user as u64 as i64,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700399 USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800400 crate::database::KEYSTORE_UUID,
401 || {
402 // For backward compatibility we need to check if there is a super key present.
403 let super_key = legacy_blob_loader
404 .load_super_key(user, pw)
405 .context("In create_new_key: Failed to load legacy key blob.")?;
406 let super_key = match super_key {
407 None => {
408 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000409 generate_aes256_key()
Max Bires8e93d2b2021-01-14 13:17:59 -0800410 .context("In create_new_key: Failed to generate AES 256 key.")?
411 }
412 Some(key) => key,
413 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000414 // Regardless of whether we loaded an old AES128 key or generated a new AES256
415 // key as the super key, we derive a AES256 key from the password and re-encrypt
416 // the super key before we insert it in the database. The length of the key is
417 // preserved by the encryption so we don't need any extra flags to inform us
418 // which algorithm to use it with.
419 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800420 },
421 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800422 .context("In unlock_user_key: Failed to get key id.")?;
423
Paul Crowley8d5b2532021-03-19 10:53:07 -0700424 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
425 .context("In unlock_user_key.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800426 Ok(())
427 }
428
Paul Crowley44c02da2021-04-08 17:04:43 +0000429 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
430 /// the relevant super key.
431 pub fn unwrap_key_if_required<'a>(
432 &self,
433 metadata: &BlobMetaData,
434 blob: &'a [u8],
435 ) -> Result<KeyBlob<'a>> {
436 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
437 let super_key = self
438 .lookup_key(&key_id)
439 .context("In unwrap_key: lookup_key failed")?
440 .ok_or(Error::Rc(ResponseCode::LOCKED))
441 .context("In unwrap_key: Required super decryption key is not in memory.")?;
442 KeyBlob::Sensitive {
443 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
444 .context("In unwrap_key: unwrap_key_with_key failed")?,
445 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
446 force_reencrypt: super_key.reencrypt_with.is_some(),
447 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700448 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000449 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700450 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800451 }
452
453 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700454 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700455 match key.algorithm {
456 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
457 (Some(iv), Some(tag)) => key
458 .aes_gcm_decrypt(blob, iv, tag)
459 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
460 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
461 concat!(
462 "In unwrap_key_with_key: Key has incomplete metadata.",
463 "Present: iv: {}, aead_tag: {}."
464 ),
465 iv.is_some(),
466 tag.is_some(),
467 )),
468 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700469 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700470 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
471 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
472 ECDHPrivateKey::from_private_key(&key.key)
473 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
474 .context(
475 "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.",
476 )
477 }
478 (public_key, salt, iv, aead_tag) => {
479 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
480 concat!(
481 "In unwrap_key_with_key: Key has incomplete metadata.",
482 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
483 ),
484 public_key.is_some(),
485 salt.is_some(),
486 iv.is_some(),
487 aead_tag.is_some(),
488 ))
489 }
490 }
491 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800492 }
493 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000494
495 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000496 pub fn super_key_exists_in_db_for_user(
497 db: &mut KeystoreDB,
498 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700499 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000500 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000501 let key_in_db = db
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700502 .key_exists(Domain::APP, user_id as u64 as i64, USER_SUPER_KEY.alias, KeyType::Super)
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000503 .context("In super_key_exists_in_db_for_user.")?;
504
505 if key_in_db {
506 Ok(key_in_db)
507 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000508 legacy_migrator
509 .has_super_key(user_id)
510 .context("In super_key_exists_in_db_for_user: Trying to query legacy db.")
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000511 }
512 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000513
514 /// 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 +0000515 /// legacy database). If not, return Uninitialized state.
516 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
517 pub fn check_and_unlock_super_key(
518 &self,
519 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000520 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700521 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700522 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000523 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700524 let alias = &USER_SUPER_KEY;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000525 let result = legacy_migrator
Paul Crowley8d5b2532021-03-19 10:53:07 -0700526 .with_try_migrate_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000527 .context("In check_and_unlock_super_key. Failed to load super key")?;
528
529 match result {
530 Some((_, entry)) => {
531 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700532 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000533 .context("In check_and_unlock_super_key.")?;
534 Ok(UserState::LskfUnlocked(super_key))
535 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000536 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000537 }
538 }
539
540 /// 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 +0000541 /// legacy database). If so, return LskfLocked state.
542 /// If the password is provided, generate a new super key, encrypt with the password,
543 /// store in the database and populate the super key cache for the new user
544 /// and return LskfUnlocked state.
545 /// If the password is not provided, return Uninitialized state.
546 pub fn check_and_initialize_super_key(
547 &self,
548 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000549 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700550 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700551 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000552 ) -> Result<UserState> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000553 let super_key_exists_in_db =
554 Self::super_key_exists_in_db_for_user(db, legacy_migrator, user_id).context(
555 "In check_and_initialize_super_key. Failed to check if super key exists.",
556 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000557 if super_key_exists_in_db {
558 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000559 } else if let Some(pw) = pw {
560 //generate a new super key.
561 let super_key = generate_aes256_key()
562 .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?;
563 //derive an AES256 key from the password and re-encrypt the super key
564 //before we insert it in the database.
565 let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw)
566 .context("In check_and_initialize_super_key.")?;
567
568 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700569 .store_super_key(
570 user_id,
571 &USER_SUPER_KEY,
572 &encrypted_super_key,
573 &blob_metadata,
574 &KeyMetaData::new(),
575 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000576 .context("In check_and_initialize_super_key. Failed to store super key.")?;
577
578 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700579 .populate_cache_from_super_key_blob(
580 user_id,
581 USER_SUPER_KEY.algorithm,
582 key_entry,
583 pw,
584 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000585 .context("In check_and_initialize_super_key.")?;
586 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000587 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000588 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000589 }
590 }
591
592 //helper function to populate super key cache from the super key blob loaded from the database
593 fn populate_cache_from_super_key_blob(
594 &self,
Paul Crowley7a658392021-03-18 17:08:20 -0700595 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700596 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000597 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700598 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700599 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700600 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
601 .context(
602 "In populate_cache_from_super_key_blob. Failed to extract super key from key entry",
603 )?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000604 self.install_per_boot_key_for_user(user_id, super_key.clone())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000605 Ok(super_key)
606 }
607
608 /// Extracts super key from the entry loaded from the database
Paul Crowley7a658392021-03-18 17:08:20 -0700609 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700610 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700611 entry: KeyEntry,
612 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700613 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700614 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000615 if let Some((blob, metadata)) = entry.key_blob_info() {
616 let key = match (
617 metadata.encrypted_by(),
618 metadata.salt(),
619 metadata.iv(),
620 metadata.aead_tag(),
621 ) {
622 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700623 // Note that password encryption is AES no matter the value of algorithm
Paul Crowleyf61fee72021-03-17 14:38:44 -0700624 let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context(
625 "In extract_super_key_from_key_entry: Failed to generate key from password.",
626 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000627
628 aes_gcm_decrypt(blob, iv, tag, &key).context(
629 "In extract_super_key_from_key_entry: Failed to decrypt key blob.",
630 )?
631 }
632 (enc_by, salt, iv, tag) => {
633 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
634 concat!(
635 "In extract_super_key_from_key_entry: Super key has incomplete metadata.",
Paul Crowleye8826e52021-03-31 08:33:53 -0700636 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
Hasini Gunasingheda895552021-01-27 19:34:37 +0000637 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700638 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000639 salt.is_some(),
640 iv.is_some(),
641 tag.is_some()
642 ));
643 }
644 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000645 Ok(Arc::new(SuperKey {
646 algorithm,
647 key,
648 id: SuperKeyIdentifier::DatabaseId(entry.id()),
649 reencrypt_with,
650 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000651 } else {
652 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
653 .context("In extract_super_key_from_key_entry: No key blob info.")
654 }
655 }
656
657 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700658 pub fn encrypt_with_password(
659 super_key: &[u8],
660 pw: &Password,
661 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000662 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700663 let derived_key = pw
664 .derive_key(Some(&salt), AES_256_KEY_LENGTH)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000665 .context("In encrypt_with_password: Failed to derive password.")?;
666 let mut metadata = BlobMetaData::new();
667 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
668 metadata.add(BlobMetaEntry::Salt(salt));
669 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
670 .context("In encrypt_with_password: Failed to encrypt new super key.")?;
671 metadata.add(BlobMetaEntry::Iv(iv));
672 metadata.add(BlobMetaEntry::AeadTag(tag));
673 Ok((encrypted_key, metadata))
674 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000675
676 // Encrypt the given key blob with the user's super key, if the super key exists and the device
677 // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
678 // return error. Note that it is out of the scope of this function to check if super encryption
679 // is required. Such check should be performed before calling this function.
680 fn super_encrypt_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000681 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000682 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000683 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700684 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000685 key_blob: &[u8],
686 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000687 match UserState::get(db, legacy_migrator, self, user_id)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000688 .context("In super_encrypt. Failed to get user state.")?
689 {
690 UserState::LskfUnlocked(super_key) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700691 Self::encrypt_with_aes_super_key(key_blob, &super_key)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000692 .context("In super_encrypt_on_key_init. Failed to encrypt the key.")
693 }
694 UserState::LskfLocked => {
695 Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.")
696 }
697 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
698 .context("In super_encrypt. LSKF is not setup for the user."),
699 }
700 }
701
702 //Helper function to encrypt a key with the given super key. Callers should select which super
703 //key to be used. This is called when a key is super encrypted at its creation as well as at its
704 //upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700705 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000706 key_blob: &[u8],
707 super_key: &SuperKey,
708 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700709 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
710 return Err(Error::sys())
711 .context("In encrypt_with_aes_super_key: unexpected algorithm");
712 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000713 let mut metadata = BlobMetaData::new();
714 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700715 .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000716 metadata.add(BlobMetaEntry::Iv(iv));
717 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000718 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000719 Ok((encrypted_key, metadata))
720 }
721
722 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
723 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700724 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000725 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000726 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000727 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000728 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000729 domain: &Domain,
730 key_parameters: &[KeyParameter],
731 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700732 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000733 key_blob: &[u8],
734 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700735 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
736 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Paul Crowleye8826e52021-03-31 08:33:53 -0700737 SuperEncryptionType::LskfBound => self
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700738 .super_encrypt_on_key_init(db, legacy_migrator, user_id, key_blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700739 .context(concat!(
740 "In handle_super_encryption_on_key_init. ",
741 "Failed to super encrypt with LskfBound key."
742 )),
Paul Crowley7a658392021-03-18 17:08:20 -0700743 SuperEncryptionType::ScreenLockBound => {
744 let mut data = self.data.lock().unwrap();
745 let entry = data.user_keys.entry(user_id).or_default();
746 if let Some(super_key) = entry.screen_lock_bound.as_ref() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700747 Self::encrypt_with_aes_super_key(key_blob, super_key).context(concat!(
Paul Crowley7a658392021-03-18 17:08:20 -0700748 "In handle_super_encryption_on_key_init. ",
Paul Crowleye8826e52021-03-31 08:33:53 -0700749 "Failed to encrypt with ScreenLockBound key."
Paul Crowley7a658392021-03-18 17:08:20 -0700750 ))
751 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700752 // Symmetric key is not available, use public key encryption
753 let loaded =
Paul Crowley52f017f2021-06-22 08:16:01 -0700754 db.load_super_key(&USER_SCREEN_LOCK_BOUND_P521_KEY, user_id).context(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700755 "In handle_super_encryption_on_key_init: load_super_key failed.",
756 )?;
757 let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context(
758 "In handle_super_encryption_on_key_init: User ECDH key missing.",
759 )?;
760 let public_key =
761 key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context(
762 "In handle_super_encryption_on_key_init: sec1_public_key missing.",
763 )?;
764 let mut metadata = BlobMetaData::new();
765 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
766 ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!(
767 "In handle_super_encryption_on_key_init: ",
768 "ECDHPrivateKey::encrypt_message failed."
769 ))?;
770 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
771 metadata.add(BlobMetaEntry::Salt(salt));
772 metadata.add(BlobMetaEntry::Iv(iv));
773 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000774 SuperKeyIdentifier::DatabaseId(key_id_guard.id())
775 .add_to_metadata(&mut metadata);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700776 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700777 }
778 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000779 SuperEncryptionType::BootLevel(level) => {
780 let key_id = SuperKeyIdentifier::BootLevel(level);
781 let super_key = self
782 .lookup_key(&key_id)
783 .context("In handle_super_encryption_on_key_init: lookup_key failed")?
784 .ok_or(Error::Rc(ResponseCode::LOCKED))
785 .context("In handle_super_encryption_on_key_init: Boot stage key absent")?;
786 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
787 "In handle_super_encryption_on_key_init: ",
788 "Failed to encrypt with BootLevel key."
789 ))
790 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000791 }
792 }
793
794 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
795 /// If so, re-super-encrypt the key and return a new set of metadata,
796 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700797 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000798 key_blob_before_upgrade: &KeyBlob,
799 key_after_upgrade: &'a [u8],
800 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
801 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700802 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700803 let (key, metadata) =
804 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
805 .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000806 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
807 }
808 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
809 }
810 }
811
Paul Crowley7a658392021-03-18 17:08:20 -0700812 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
813 /// When this is called, the caller must hold the lock on the SuperKeyManager.
814 /// So it's OK that the check and creation are different DB transactions.
815 fn get_or_create_super_key(
816 db: &mut KeystoreDB,
817 user_id: UserId,
818 key_type: &SuperKeyType,
819 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700820 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700821 ) -> Result<Arc<SuperKey>> {
822 let loaded_key = db.load_super_key(key_type, user_id)?;
823 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700824 Ok(Self::extract_super_key_from_key_entry(
825 key_type.algorithm,
826 key_entry,
827 password,
828 reencrypt_with,
829 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700830 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700831 let (super_key, public_key) = match key_type.algorithm {
832 SuperEncryptionAlgorithm::Aes256Gcm => (
833 generate_aes256_key()
834 .context("In get_or_create_super_key: Failed to generate AES 256 key.")?,
835 None,
836 ),
Paul Crowley52f017f2021-06-22 08:16:01 -0700837 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700838 let key = ECDHPrivateKey::generate()
839 .context("In get_or_create_super_key: Failed to generate ECDH key")?;
840 (
841 key.private_key()
842 .context("In get_or_create_super_key: private_key failed")?,
843 Some(
844 key.public_key()
845 .context("In get_or_create_super_key: public_key failed")?,
846 ),
847 )
848 }
849 };
Paul Crowley7a658392021-03-18 17:08:20 -0700850 //derive an AES256 key from the password and re-encrypt the super key
851 //before we insert it in the database.
852 let (encrypted_super_key, blob_metadata) =
853 Self::encrypt_with_password(&super_key, password)
854 .context("In get_or_create_super_key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700855 let mut key_metadata = KeyMetaData::new();
856 if let Some(pk) = public_key {
857 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
858 }
Paul Crowley7a658392021-03-18 17:08:20 -0700859 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700860 .store_super_key(
861 user_id,
862 key_type,
863 &encrypted_super_key,
864 &blob_metadata,
865 &key_metadata,
866 )
Paul Crowley7a658392021-03-18 17:08:20 -0700867 .context("In get_or_create_super_key. Failed to store super key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700868 Ok(Arc::new(SuperKey {
869 algorithm: key_type.algorithm,
870 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000871 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700872 reencrypt_with,
873 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700874 }
875 }
876
Paul Crowley8d5b2532021-03-19 10:53:07 -0700877 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700878 pub fn unlock_screen_lock_bound_key(
879 &self,
880 db: &mut KeystoreDB,
881 user_id: UserId,
882 password: &Password,
883 ) -> Result<()> {
884 let mut data = self.data.lock().unwrap();
885 let entry = data.user_keys.entry(user_id).or_default();
886 let aes = entry
887 .screen_lock_bound
888 .get_or_try_to_insert_with(|| {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700889 Self::get_or_create_super_key(
890 db,
891 user_id,
892 &USER_SCREEN_LOCK_BOUND_KEY,
893 password,
894 None,
895 )
896 })?
897 .clone();
898 let ecdh = entry
899 .screen_lock_bound_private
900 .get_or_try_to_insert_with(|| {
901 Self::get_or_create_super_key(
902 db,
903 user_id,
Paul Crowley52f017f2021-06-22 08:16:01 -0700904 &USER_SCREEN_LOCK_BOUND_P521_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700905 password,
906 Some(aes.clone()),
907 )
Paul Crowley7a658392021-03-18 17:08:20 -0700908 })?
909 .clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000910 data.add_key_to_key_index(&aes)?;
911 data.add_key_to_key_index(&ecdh)?;
Paul Crowley7a658392021-03-18 17:08:20 -0700912 Ok(())
913 }
914
Paul Crowley8d5b2532021-03-19 10:53:07 -0700915 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley618869e2021-04-08 20:30:54 -0700916 pub fn lock_screen_lock_bound_key(
917 &self,
918 db: &mut KeystoreDB,
919 user_id: UserId,
920 unlocking_sids: &[i64],
921 ) {
922 log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
Paul Crowley7a658392021-03-18 17:08:20 -0700923 let mut data = self.data.lock().unwrap();
924 let mut entry = data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700925 if !unlocking_sids.is_empty() {
926 if let (Some(aes), Some(ecdh)) = (
927 entry.screen_lock_bound.as_ref().cloned(),
928 entry.screen_lock_bound_private.as_ref().cloned(),
929 ) {
930 let res = (|| -> Result<()> {
931 let key_desc = KeyMintDevice::internal_descriptor(format!(
932 "biometric_unlock_key_{}",
933 user_id
934 ));
935 let encrypting_key = generate_aes256_key()?;
936 let km_dev: KeyMintDevice =
937 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
938 .context("In lock_screen_lock_bound_key: KeyMintDevice::get failed")?;
939 let mut key_params = vec![
940 KeyParameterValue::Algorithm(Algorithm::AES),
941 KeyParameterValue::KeySize(256),
942 KeyParameterValue::BlockMode(BlockMode::GCM),
943 KeyParameterValue::PaddingMode(PaddingMode::NONE),
944 KeyParameterValue::CallerNonce,
945 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
946 KeyParameterValue::MinMacLength(128),
947 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
948 KeyParameterValue::HardwareAuthenticatorType(
949 HardwareAuthenticatorType::FINGERPRINT,
950 ),
951 ];
952 for sid in unlocking_sids {
953 key_params.push(KeyParameterValue::UserSecureID(*sid));
954 }
955 let key_params: Vec<KmKeyParameter> =
956 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700957 km_dev.create_and_store_key(
958 db,
959 &key_desc,
960 KeyType::Client, /* TODO Should be Super b/189470584 */
961 |dev| {
962 let _wp = wd::watch_millis(
963 "In lock_screen_lock_bound_key: calling importKey.",
964 500,
965 );
966 dev.importKey(
967 key_params.as_slice(),
968 KeyFormat::RAW,
969 &encrypting_key,
970 None,
971 )
972 },
973 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700974 entry.biometric_unlock = Some(BiometricUnlock {
975 sids: unlocking_sids.into(),
976 key_desc,
977 screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
978 screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
979 });
980 Ok(())
981 })();
982 // There is no reason to propagate an error here upwards. We must discard
983 // entry.screen_lock_bound* in any case.
984 if let Err(e) = res {
985 log::error!("Error setting up biometric unlock: {:#?}", e);
986 }
987 }
988 }
Paul Crowley7a658392021-03-18 17:08:20 -0700989 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700990 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700991 }
Paul Crowley618869e2021-04-08 20:30:54 -0700992
993 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
994 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
995 pub fn try_unlock_user_with_biometric(
996 &self,
997 db: &mut KeystoreDB,
998 user_id: UserId,
999 ) -> Result<()> {
1000 let mut data = self.data.lock().unwrap();
1001 let mut entry = data.user_keys.entry(user_id).or_default();
1002 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -07001003 let (key_id_guard, key_entry) = db
1004 .load_key_entry(
1005 &biometric.key_desc,
1006 KeyType::Client, // This should not be a Client key.
1007 KeyEntryLoadBits::KM,
1008 AID_KEYSTORE,
1009 |_, _| Ok(()),
1010 )
1011 .context("In try_unlock_user_with_biometric: load_key_entry failed")?;
Paul Crowley618869e2021-04-08 20:30:54 -07001012 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
1013 .context("In try_unlock_user_with_biometric: KeyMintDevice::get failed")?;
1014 for sid in &biometric.sids {
1015 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
1016 entry.auth_token().userId == *sid || entry.auth_token().authenticatorId == *sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001017 }) {
Paul Crowley618869e2021-04-08 20:30:54 -07001018 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
1019 let slb = biometric.screen_lock_bound.decrypt(
1020 db,
1021 &km_dev,
1022 &key_id_guard,
1023 &key_entry,
1024 auth_token_entry.auth_token(),
1025 None,
1026 )?;
1027 let slbp = biometric.screen_lock_bound_private.decrypt(
1028 db,
1029 &km_dev,
1030 &key_id_guard,
1031 &key_entry,
1032 auth_token_entry.auth_token(),
1033 Some(slb.clone()),
1034 )?;
1035 Ok((slb, slbp))
1036 })();
1037 match res {
1038 Ok((slb, slbp)) => {
1039 entry.screen_lock_bound = Some(slb.clone());
1040 entry.screen_lock_bound_private = Some(slbp.clone());
1041 data.add_key_to_key_index(&slb)?;
1042 data.add_key_to_key_index(&slbp)?;
1043 log::info!(concat!(
1044 "In try_unlock_user_with_biometric: ",
1045 "Successfully unlocked with biometric"
1046 ));
1047 return Ok(());
1048 }
1049 Err(e) => {
1050 log::warn!("In try_unlock_user_with_biometric: attempt failed: {:?}", e)
1051 }
1052 }
1053 }
1054 }
1055 }
1056 Ok(())
1057 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001058}
1059
1060/// This enum represents different states of the user's life cycle in the device.
1061/// For now, only three states are defined. More states may be added later.
1062pub enum UserState {
1063 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
1064 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -07001065 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001066 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
1067 // Hence the per-boot super-key(s) is not available in the cache.
1068 // However, the encrypted super key is available in the database.
1069 LskfLocked,
1070 // There's no user in the device for the given user id, or the user with the user id has not
1071 // setup LSKF.
1072 Uninitialized,
1073}
1074
1075impl UserState {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001076 pub fn get(
1077 db: &mut KeystoreDB,
1078 legacy_migrator: &LegacyMigrator,
1079 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -07001080 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001081 ) -> Result<UserState> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001082 match skm.get_per_boot_key_by_user_id(user_id) {
1083 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
1084 None => {
1085 //Check if a super key exists in the database or legacy database.
1086 //If so, return locked user state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001087 if SuperKeyManager::super_key_exists_in_db_for_user(db, legacy_migrator, user_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00001088 .context("In get.")?
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001089 {
1090 Ok(UserState::LskfLocked)
1091 } else {
1092 Ok(UserState::Uninitialized)
1093 }
1094 }
1095 }
1096 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00001097
1098 /// Queries user state when serving password change requests.
1099 pub fn get_with_password_changed(
1100 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001101 legacy_migrator: &LegacyMigrator,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001102 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -07001103 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -07001104 password: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001105 ) -> Result<UserState> {
1106 match skm.get_per_boot_key_by_user_id(user_id) {
1107 Some(super_key) => {
1108 if password.is_none() {
1109 //transitioning to swiping, delete only the super key in database and cache, and
1110 //super-encrypted keys in database (and in KM)
Janis Danisevskiseed69842021-02-18 20:04:10 -08001111 Self::reset_user(db, skm, legacy_migrator, user_id, true).context(
1112 "In get_with_password_changed: Trying to delete keys from the db.",
1113 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00001114 //Lskf is now removed in Keystore
1115 Ok(UserState::Uninitialized)
1116 } else {
1117 //Keystore won't be notified when changing to a new password when LSKF is
1118 //already setup. Therefore, ideally this path wouldn't be reached.
1119 Ok(UserState::LskfUnlocked(super_key))
1120 }
1121 }
1122 None => {
1123 //Check if a super key exists in the database or legacy database.
1124 //If so, return LskfLocked state.
1125 //Otherwise, i) if the password is provided, initialize the super key and return
1126 //LskfUnlocked state ii) if password is not provided, return Uninitialized state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001127 skm.check_and_initialize_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasingheda895552021-01-27 19:34:37 +00001128 }
1129 }
1130 }
1131
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001132 /// Queries user state when serving password unlock requests.
1133 pub fn get_with_password_unlock(
1134 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001135 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001136 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -07001137 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -07001138 password: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001139 ) -> Result<UserState> {
1140 match skm.get_per_boot_key_by_user_id(user_id) {
1141 Some(super_key) => {
1142 log::info!("In get_with_password_unlock. Trying to unlock when already unlocked.");
1143 Ok(UserState::LskfUnlocked(super_key))
1144 }
1145 None => {
1146 //Check if a super key exists in the database or legacy database.
1147 //If not, return Uninitialized state.
1148 //Otherwise, try to unlock the super key and if successful,
1149 //return LskfUnlocked state
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001150 skm.check_and_unlock_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001151 .context("In get_with_password_unlock. Failed to unlock super key.")
1152 }
1153 }
1154 }
1155
Hasini Gunasingheda895552021-01-27 19:34:37 +00001156 /// Delete all the keys created on behalf of the user.
1157 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
1158 /// encrypted keys.
1159 pub fn reset_user(
1160 db: &mut KeystoreDB,
1161 skm: &SuperKeyManager,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001162 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -07001163 user_id: UserId,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001164 keep_non_super_encrypted_keys: bool,
1165 ) -> Result<()> {
1166 // mark keys created on behalf of the user as unreferenced.
Janis Danisevskiseed69842021-02-18 20:04:10 -08001167 legacy_migrator
1168 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
1169 .context("In reset_user: Trying to delete legacy keys.")?;
Paul Crowley7a658392021-03-18 17:08:20 -07001170 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
Hasini Gunasingheda895552021-01-27 19:34:37 +00001171 .context("In reset user. Error in unbinding keys.")?;
1172
1173 //delete super key in cache, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001174 skm.forget_all_keys_for_user(user_id);
Hasini Gunasingheda895552021-01-27 19:34:37 +00001175 Ok(())
1176 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001177}
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001178
Janis Danisevskiseed69842021-02-18 20:04:10 -08001179/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1180/// `Sensitive` holds the non encrypted key and a reference to its super key.
1181/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1182/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1183/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001184pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001185 Sensitive {
1186 key: ZVec,
1187 /// If KeyMint reports that the key must be upgraded, we must
1188 /// re-encrypt the key before writing to the database; we use
1189 /// this key.
1190 reencrypt_with: Arc<SuperKey>,
1191 /// If this key was decrypted with an ECDH key, we want to
1192 /// re-encrypt it on first use whether it was upgraded or not;
1193 /// this field indicates that that's necessary.
1194 force_reencrypt: bool,
1195 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001196 NonSensitive(Vec<u8>),
1197 Ref(&'a [u8]),
1198}
1199
Paul Crowley8d5b2532021-03-19 10:53:07 -07001200impl<'a> KeyBlob<'a> {
1201 pub fn force_reencrypt(&self) -> bool {
1202 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1203 *force_reencrypt
1204 } else {
1205 false
1206 }
1207 }
1208}
1209
Janis Danisevskiseed69842021-02-18 20:04:10 -08001210/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001211impl<'a> Deref for KeyBlob<'a> {
1212 type Target = [u8];
1213
1214 fn deref(&self) -> &Self::Target {
1215 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001216 Self::Sensitive { key, .. } => key,
1217 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001218 Self::Ref(key) => key,
1219 }
1220 }
1221}