blob: 686201122906e94183f4fbaec88dc1d834fd2023 [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,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070031 utils::watchdog as wd,
Janis Danisevskisacebfa22021-05-25 10:56:10 -070032 utils::AID_KEYSTORE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080033};
Paul Crowley618869e2021-04-08 20:30:54 -070034use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
35 Algorithm::Algorithm, BlockMode::BlockMode, HardwareAuthToken::HardwareAuthToken,
36 HardwareAuthenticatorType::HardwareAuthenticatorType, KeyFormat::KeyFormat,
37 KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
38 SecurityLevel::SecurityLevel,
39};
40use android_system_keystore2::aidl::android::system::keystore2::{
41 Domain::Domain, KeyDescriptor::KeyDescriptor,
42};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080043use anyhow::{Context, Result};
44use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070045 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
46 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080047};
Joel Galenson7ead3a22021-07-29 15:27:34 -070048use rustutils::system_properties::PropertyWatcher;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use std::{
50 collections::HashMap,
51 sync::Arc,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080052 sync::{Mutex, RwLock, Weak},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080053};
Paul Crowley618869e2021-04-08 20:30:54 -070054use std::{convert::TryFrom, ops::Deref};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080055
Paul Crowley44c02da2021-04-08 17:04:43 +000056const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
Paul Crowley618869e2021-04-08 20:30:54 -070057/// Allow up to 15 seconds between the user unlocking using a biometric, and the auth
58/// token being used to unlock in [`SuperKeyManager::try_unlock_user_with_biometric`].
59/// This seems short enough for security purposes, while long enough that even the
60/// very slowest device will present the auth token in time.
61const BIOMETRIC_AUTH_TIMEOUT_S: i32 = 15; // seconds
Paul Crowley44c02da2021-04-08 17:04:43 +000062
Janis Danisevskisb42fc182020-12-15 08:41:27 -080063type UserId = u32;
64
Paul Crowley8d5b2532021-03-19 10:53:07 -070065/// Encryption algorithm used by a particular type of superencryption key
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum SuperEncryptionAlgorithm {
68 /// Symmetric encryption with AES-256-GCM
69 Aes256Gcm,
Paul Crowley52f017f2021-06-22 08:16:01 -070070 /// Public-key encryption with ECDH P-521
71 EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -070072}
73
Paul Crowley7a658392021-03-18 17:08:20 -070074/// A particular user may have several superencryption keys in the database, each for a
75/// different purpose, distinguished by alias. Each is associated with a static
76/// constant of this type.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080077pub struct SuperKeyType<'a> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080078 /// Alias used to look up the key in the `persistent.keyentry` table.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080079 pub alias: &'a str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070080 /// Encryption algorithm
81 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070082}
83
84/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
85/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070086pub const USER_SUPER_KEY: SuperKeyType =
87 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070088/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
89/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070090/// Symmetric.
91pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
92 alias: "USER_SCREEN_LOCK_BOUND_KEY",
93 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
94};
95/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
96/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
97/// Asymmetric, so keys can be encrypted when the device is locked.
Paul Crowley52f017f2021-06-22 08:16:01 -070098pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
99 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
100 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700101};
Paul Crowley7a658392021-03-18 17:08:20 -0700102
103/// Superencryption to apply to a new key.
104#[derive(Debug, Clone, Copy)]
105pub enum SuperEncryptionType {
106 /// Do not superencrypt this key.
107 None,
108 /// Superencrypt with a key that remains in memory from first unlock to reboot.
109 LskfBound,
110 /// Superencrypt with a key cleared from memory when the device is locked.
111 ScreenLockBound,
Paul Crowley44c02da2021-04-08 17:04:43 +0000112 /// Superencrypt with a key based on the desired boot level
113 BootLevel(i32),
114}
115
116#[derive(Debug, Clone, Copy)]
117pub enum SuperKeyIdentifier {
118 /// id of the super key in the database.
119 DatabaseId(i64),
120 /// Boot level of the encrypting boot level key
121 BootLevel(i32),
122}
123
124impl SuperKeyIdentifier {
125 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
126 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
127 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000128 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700129 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000130 }
131 }
132
133 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
134 match self {
135 SuperKeyIdentifier::DatabaseId(id) => {
136 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
137 }
138 SuperKeyIdentifier::BootLevel(level) => {
139 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
140 }
141 }
142 }
Paul Crowley7a658392021-03-18 17:08:20 -0700143}
144
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000145pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700146 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700147 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000148 /// Identifier of the encrypting key, used to write an encrypted blob
149 /// back to the database after re-encryption eg on a key update.
150 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700151 /// ECDH is more expensive than AES. So on ECDH private keys we set the
152 /// reencrypt_with field to point at the corresponding AES key, and the
153 /// keys will be re-encrypted with AES on first use.
154 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000155}
156
157impl SuperKey {
Paul Crowley7a658392021-03-18 17:08:20 -0700158 /// For most purposes `unwrap_key` handles decryption,
159 /// but legacy handling and some tests need to assume AES and decrypt directly.
160 pub fn aes_gcm_decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700161 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
162 aes_gcm_decrypt(data, iv, tag, &self.key)
163 .context("In aes_gcm_decrypt: decryption failed")
164 } else {
165 Err(Error::sys()).context("In aes_gcm_decrypt: Key is not an AES key")
166 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000167 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700168}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000169
Paul Crowley618869e2021-04-08 20:30:54 -0700170/// A SuperKey that has been encrypted with an AES-GCM key. For
171/// encryption the key is in memory, and for decryption it is in KM.
172struct LockedKey {
173 algorithm: SuperEncryptionAlgorithm,
174 id: SuperKeyIdentifier,
175 nonce: Vec<u8>,
176 ciphertext: Vec<u8>, // with tag appended
177}
178
179impl LockedKey {
180 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
181 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
182 ciphertext.append(&mut tag);
183 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
184 }
185
186 fn decrypt(
187 &self,
188 db: &mut KeystoreDB,
189 km_dev: &KeyMintDevice,
190 key_id_guard: &KeyIdGuard,
191 key_entry: &KeyEntry,
192 auth_token: &HardwareAuthToken,
193 reencrypt_with: Option<Arc<SuperKey>>,
194 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700195 let key_blob = key_entry
196 .key_blob_info()
197 .as_ref()
198 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
199 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
200 .context("In LockedKey::decrypt: Missing key blob info.")?;
Paul Crowley618869e2021-04-08 20:30:54 -0700201 let key_params = vec![
202 KeyParameterValue::Algorithm(Algorithm::AES),
203 KeyParameterValue::KeySize(256),
204 KeyParameterValue::BlockMode(BlockMode::GCM),
205 KeyParameterValue::PaddingMode(PaddingMode::NONE),
206 KeyParameterValue::Nonce(self.nonce.clone()),
207 KeyParameterValue::MacLength(128),
208 ];
209 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
210 let key = ZVec::try_from(km_dev.use_key_in_one_step(
211 db,
212 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700213 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700214 KeyPurpose::DECRYPT,
215 &key_params,
216 Some(auth_token),
217 &self.ciphertext,
218 )?)?;
219 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
220 }
221}
222
223/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
224/// a database descriptor for the encrypting key and the sids for the auth tokens
225/// that can be used to decrypt it.
226struct BiometricUnlock {
227 /// List of auth token SIDs that can be used to unlock these keys.
228 sids: Vec<i64>,
229 /// Database descriptor of key to use to unlock.
230 key_desc: KeyDescriptor,
231 /// Locked versions of the matching UserSuperKeys fields
232 screen_lock_bound: LockedKey,
233 screen_lock_bound_private: LockedKey,
234}
235
Paul Crowleye8826e52021-03-31 08:33:53 -0700236#[derive(Default)]
237struct UserSuperKeys {
238 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
239 /// key per android user. The key is stored on flash encrypted with a key derived from a
240 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
241 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
242 /// and stays memory resident until the device reboots.
243 per_boot: Option<Arc<SuperKey>>,
244 /// The screen lock key works like the per boot key with the distinction that it is cleared
245 /// from memory when the screen lock is engaged.
246 screen_lock_bound: Option<Arc<SuperKey>>,
247 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
248 /// ECDH public-key encryption. This field holds the decryption private key.
249 screen_lock_bound_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700250 /// Versions of the above two keys, locked behind a biometric.
251 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000252}
253
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800254#[derive(Default)]
255struct SkmState {
256 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700257 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800258 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700259}
260
261impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000262 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
263 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
264 self.key_index.insert(id, Arc::downgrade(super_key));
265 Ok(())
266 } else {
267 Err(Error::sys()).context(format!(
268 "In add_key_to_key_index: cannot add key with ID {:?}",
269 super_key.id
270 ))
271 }
Paul Crowley7a658392021-03-18 17:08:20 -0700272 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800273}
274
275#[derive(Default)]
276pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800277 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800278}
279
280impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800281 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
282 let mut skm_guard = skm.write().unwrap();
283 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000284 log::info!("In set_up_boot_level_cache: called for a second time");
285 return Ok(());
286 }
287 let level_zero_key = get_level_zero_key(db)
288 .context("In set_up_boot_level_cache: get_level_zero_key failed")?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800289 skm_guard.data.boot_level_key_cache =
290 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000291 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800292 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000293 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800294 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000295 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
296 });
297 Ok(())
298 }
299
300 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
301 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800302 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000303 let mut w = PropertyWatcher::new("keystore.boot_level")
304 .context("In watch_boot_level: PropertyWatcher::new failed")?;
305 loop {
306 let level = w
307 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
308 .context("In watch_boot_level: read of property failed")?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800309
310 // This scope limits the skm_guard life, so we don't hold the skm_guard while
311 // waiting.
312 {
313 let mut skm_guard = skm.write().unwrap();
314 let boot_level_key_cache = skm_guard
315 .data
316 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000317 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800318 .ok_or_else(Error::sys)
319 .context("In watch_boot_level: Boot level cache not initialized")?
320 .get_mut()
321 .unwrap();
322 if level < MAX_MAX_BOOT_LEVEL {
323 log::info!("Read keystore.boot_level value {}", level);
324 boot_level_key_cache
325 .advance_boot_level(level)
326 .context("In watch_boot_level: advance_boot_level failed")?;
327 } else {
328 log::info!(
329 "keystore.boot_level {} hits maximum {}, finishing.",
330 level,
331 MAX_MAX_BOOT_LEVEL
332 );
333 boot_level_key_cache.finish();
334 break;
335 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000336 }
337 w.wait().context("In watch_boot_level: property wait failed")?;
338 }
339 Ok(())
340 }
341
342 pub fn level_accessible(&self, boot_level: i32) -> bool {
343 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000344 .boot_level_key_cache
345 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800346 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000347 }
348
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800349 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
350 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800351 }
352
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800353 fn install_per_boot_key_for_user(
354 &mut self,
355 user: UserId,
356 super_key: Arc<SuperKey>,
357 ) -> Result<()> {
358 self.data
359 .add_key_to_key_index(&super_key)
Paul Crowley44c02da2021-04-08 17:04:43 +0000360 .context("In install_per_boot_key_for_user: add_key_to_key_index failed")?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800361 self.data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000362 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800363 }
364
Paul Crowley44c02da2021-04-08 17:04:43 +0000365 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000366 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800367 SuperKeyIdentifier::DatabaseId(id) => {
368 self.data.key_index.get(id).and_then(|k| k.upgrade())
369 }
370 SuperKeyIdentifier::BootLevel(level) => self
371 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000372 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800373 .as_ref()
374 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000375 .transpose()
376 .context("In lookup_key: aes_key failed")?
377 .flatten()
378 .map(|key| {
379 Arc::new(SuperKey {
380 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
381 key,
382 id: *key_id,
383 reencrypt_with: None,
384 })
385 }),
386 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800387 }
388
Paul Crowley7a658392021-03-18 17:08:20 -0700389 pub fn get_per_boot_key_by_user_id(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800390 self.data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800391 }
392
393 /// This function unlocks the super keys for a given user.
394 /// This means the key is loaded from the database, decrypted and placed in the
395 /// super key cache. If there is no such key a new key is created, encrypted with
396 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800397 pub fn unlock_user_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800398 &mut self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000399 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800400 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700401 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800402 legacy_blob_loader: &LegacyBlobLoader,
403 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800404 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800405 .get_or_create_key_with(
406 Domain::APP,
407 user as u64 as i64,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700408 USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800409 crate::database::KEYSTORE_UUID,
410 || {
411 // For backward compatibility we need to check if there is a super key present.
412 let super_key = legacy_blob_loader
413 .load_super_key(user, pw)
414 .context("In create_new_key: Failed to load legacy key blob.")?;
415 let super_key = match super_key {
416 None => {
417 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000418 generate_aes256_key()
Max Bires8e93d2b2021-01-14 13:17:59 -0800419 .context("In create_new_key: Failed to generate AES 256 key.")?
420 }
421 Some(key) => key,
422 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000423 // Regardless of whether we loaded an old AES128 key or generated a new AES256
424 // key as the super key, we derive a AES256 key from the password and re-encrypt
425 // the super key before we insert it in the database. The length of the key is
426 // preserved by the encryption so we don't need any extra flags to inform us
427 // which algorithm to use it with.
428 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800429 },
430 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800431 .context("In unlock_user_key: Failed to get key id.")?;
432
Paul Crowley8d5b2532021-03-19 10:53:07 -0700433 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
434 .context("In unlock_user_key.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800435 Ok(())
436 }
437
Paul Crowley44c02da2021-04-08 17:04:43 +0000438 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
439 /// the relevant super key.
440 pub fn unwrap_key_if_required<'a>(
441 &self,
442 metadata: &BlobMetaData,
443 blob: &'a [u8],
444 ) -> Result<KeyBlob<'a>> {
445 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
446 let super_key = self
447 .lookup_key(&key_id)
448 .context("In unwrap_key: lookup_key failed")?
449 .ok_or(Error::Rc(ResponseCode::LOCKED))
450 .context("In unwrap_key: Required super decryption key is not in memory.")?;
451 KeyBlob::Sensitive {
452 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
453 .context("In unwrap_key: unwrap_key_with_key failed")?,
454 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
455 force_reencrypt: super_key.reencrypt_with.is_some(),
456 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700457 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000458 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700459 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800460 }
461
462 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700463 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700464 match key.algorithm {
465 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
466 (Some(iv), Some(tag)) => key
467 .aes_gcm_decrypt(blob, iv, tag)
468 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
469 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
470 concat!(
471 "In unwrap_key_with_key: Key has incomplete metadata.",
472 "Present: iv: {}, aead_tag: {}."
473 ),
474 iv.is_some(),
475 tag.is_some(),
476 )),
477 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700478 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700479 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
480 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
481 ECDHPrivateKey::from_private_key(&key.key)
482 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
483 .context(
484 "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.",
485 )
486 }
487 (public_key, salt, iv, aead_tag) => {
488 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
489 concat!(
490 "In unwrap_key_with_key: Key has incomplete metadata.",
491 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
492 ),
493 public_key.is_some(),
494 salt.is_some(),
495 iv.is_some(),
496 aead_tag.is_some(),
497 ))
498 }
499 }
500 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800501 }
502 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000503
504 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800505 /// The reference to self is unused but it is required to prevent calling this function
506 /// concurrently with skm state database changes.
507 fn super_key_exists_in_db_for_user(
508 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000509 db: &mut KeystoreDB,
510 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700511 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000512 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000513 let key_in_db = db
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700514 .key_exists(Domain::APP, user_id as u64 as i64, USER_SUPER_KEY.alias, KeyType::Super)
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000515 .context("In super_key_exists_in_db_for_user.")?;
516
517 if key_in_db {
518 Ok(key_in_db)
519 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000520 legacy_migrator
521 .has_super_key(user_id)
522 .context("In super_key_exists_in_db_for_user: Trying to query legacy db.")
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000523 }
524 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000525
526 /// 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 +0000527 /// legacy database). If not, return Uninitialized state.
528 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
529 pub fn check_and_unlock_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800530 &mut self,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000531 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000532 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700533 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700534 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000535 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700536 let alias = &USER_SUPER_KEY;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000537 let result = legacy_migrator
Paul Crowley8d5b2532021-03-19 10:53:07 -0700538 .with_try_migrate_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000539 .context("In check_and_unlock_super_key. Failed to load super key")?;
540
541 match result {
542 Some((_, entry)) => {
543 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700544 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000545 .context("In check_and_unlock_super_key.")?;
546 Ok(UserState::LskfUnlocked(super_key))
547 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000548 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000549 }
550 }
551
552 /// 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 +0000553 /// legacy database). If so, return LskfLocked state.
554 /// If the password is provided, generate a new super key, encrypt with the password,
555 /// store in the database and populate the super key cache for the new user
556 /// and return LskfUnlocked state.
557 /// If the password is not provided, return Uninitialized state.
558 pub fn check_and_initialize_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800559 &mut self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000560 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000561 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700562 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700563 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000564 ) -> Result<UserState> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800565 let super_key_exists_in_db = self
566 .super_key_exists_in_db_for_user(db, legacy_migrator, user_id)
567 .context("In check_and_initialize_super_key. Failed to check if super key exists.")?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000568 if super_key_exists_in_db {
569 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000570 } else if let Some(pw) = pw {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800571 // Generate a new super key.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000572 let super_key = generate_aes256_key()
573 .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800574 // Derive an AES256 key from the password and re-encrypt the super key
575 // before we insert it in the database.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000576 let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw)
577 .context("In check_and_initialize_super_key.")?;
578
579 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700580 .store_super_key(
581 user_id,
582 &USER_SUPER_KEY,
583 &encrypted_super_key,
584 &blob_metadata,
585 &KeyMetaData::new(),
586 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000587 .context("In check_and_initialize_super_key. Failed to store super key.")?;
588
589 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700590 .populate_cache_from_super_key_blob(
591 user_id,
592 USER_SUPER_KEY.algorithm,
593 key_entry,
594 pw,
595 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000596 .context("In check_and_initialize_super_key.")?;
597 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000598 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000599 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000600 }
601 }
602
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800603 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000604 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800605 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700606 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700607 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000608 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700609 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700610 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700611 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
612 .context(
613 "In populate_cache_from_super_key_blob. Failed to extract super key from key entry",
614 )?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000615 self.install_per_boot_key_for_user(user_id, super_key.clone())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000616 Ok(super_key)
617 }
618
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800619 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700620 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700621 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700622 entry: KeyEntry,
623 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700624 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700625 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000626 if let Some((blob, metadata)) = entry.key_blob_info() {
627 let key = match (
628 metadata.encrypted_by(),
629 metadata.salt(),
630 metadata.iv(),
631 metadata.aead_tag(),
632 ) {
633 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800634 // Note that password encryption is AES no matter the value of algorithm.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700635 let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context(
636 "In extract_super_key_from_key_entry: Failed to generate key from password.",
637 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000638
639 aes_gcm_decrypt(blob, iv, tag, &key).context(
640 "In extract_super_key_from_key_entry: Failed to decrypt key blob.",
641 )?
642 }
643 (enc_by, salt, iv, tag) => {
644 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
645 concat!(
646 "In extract_super_key_from_key_entry: Super key has incomplete metadata.",
Paul Crowleye8826e52021-03-31 08:33:53 -0700647 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
Hasini Gunasingheda895552021-01-27 19:34:37 +0000648 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700649 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000650 salt.is_some(),
651 iv.is_some(),
652 tag.is_some()
653 ));
654 }
655 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000656 Ok(Arc::new(SuperKey {
657 algorithm,
658 key,
659 id: SuperKeyIdentifier::DatabaseId(entry.id()),
660 reencrypt_with,
661 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000662 } else {
663 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
664 .context("In extract_super_key_from_key_entry: No key blob info.")
665 }
666 }
667
668 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700669 pub fn encrypt_with_password(
670 super_key: &[u8],
671 pw: &Password,
672 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000673 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700674 let derived_key = pw
675 .derive_key(Some(&salt), AES_256_KEY_LENGTH)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000676 .context("In encrypt_with_password: Failed to derive password.")?;
677 let mut metadata = BlobMetaData::new();
678 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
679 metadata.add(BlobMetaEntry::Salt(salt));
680 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
681 .context("In encrypt_with_password: Failed to encrypt new super key.")?;
682 metadata.add(BlobMetaEntry::Iv(iv));
683 metadata.add(BlobMetaEntry::AeadTag(tag));
684 Ok((encrypted_key, metadata))
685 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000686
687 // Encrypt the given key blob with the user's super key, if the super key exists and the device
688 // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
689 // return error. Note that it is out of the scope of this function to check if super encryption
690 // is required. Such check should be performed before calling this function.
691 fn super_encrypt_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000692 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000693 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000694 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700695 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000696 key_blob: &[u8],
697 ) -> Result<(Vec<u8>, BlobMetaData)> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800698 match self
699 .get_user_state(db, legacy_migrator, user_id)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000700 .context("In super_encrypt. Failed to get user state.")?
701 {
702 UserState::LskfUnlocked(super_key) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700703 Self::encrypt_with_aes_super_key(key_blob, &super_key)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000704 .context("In super_encrypt_on_key_init. Failed to encrypt the key.")
705 }
706 UserState::LskfLocked => {
707 Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.")
708 }
709 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
710 .context("In super_encrypt. LSKF is not setup for the user."),
711 }
712 }
713
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800714 // Helper function to encrypt a key with the given super key. Callers should select which super
715 // key to be used. This is called when a key is super encrypted at its creation as well as at
716 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700717 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000718 key_blob: &[u8],
719 super_key: &SuperKey,
720 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700721 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
722 return Err(Error::sys())
723 .context("In encrypt_with_aes_super_key: unexpected algorithm");
724 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000725 let mut metadata = BlobMetaData::new();
726 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700727 .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000728 metadata.add(BlobMetaEntry::Iv(iv));
729 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000730 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000731 Ok((encrypted_key, metadata))
732 }
733
734 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
735 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700736 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000737 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000738 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000739 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000740 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000741 domain: &Domain,
742 key_parameters: &[KeyParameter],
743 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700744 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000745 key_blob: &[u8],
746 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700747 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
748 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Paul Crowleye8826e52021-03-31 08:33:53 -0700749 SuperEncryptionType::LskfBound => self
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700750 .super_encrypt_on_key_init(db, legacy_migrator, user_id, key_blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700751 .context(concat!(
752 "In handle_super_encryption_on_key_init. ",
753 "Failed to super encrypt with LskfBound key."
754 )),
Paul Crowley7a658392021-03-18 17:08:20 -0700755 SuperEncryptionType::ScreenLockBound => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800756 let entry = self
757 .data
758 .user_keys
759 .get(&user_id)
760 .map(|e| e.screen_lock_bound.as_ref())
761 .flatten();
762 if let Some(super_key) = entry {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700763 Self::encrypt_with_aes_super_key(key_blob, super_key).context(concat!(
Paul Crowley7a658392021-03-18 17:08:20 -0700764 "In handle_super_encryption_on_key_init. ",
Paul Crowleye8826e52021-03-31 08:33:53 -0700765 "Failed to encrypt with ScreenLockBound key."
Paul Crowley7a658392021-03-18 17:08:20 -0700766 ))
767 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700768 // Symmetric key is not available, use public key encryption
769 let loaded =
Paul Crowley52f017f2021-06-22 08:16:01 -0700770 db.load_super_key(&USER_SCREEN_LOCK_BOUND_P521_KEY, user_id).context(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700771 "In handle_super_encryption_on_key_init: load_super_key failed.",
772 )?;
773 let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context(
774 "In handle_super_encryption_on_key_init: User ECDH key missing.",
775 )?;
776 let public_key =
777 key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context(
778 "In handle_super_encryption_on_key_init: sec1_public_key missing.",
779 )?;
780 let mut metadata = BlobMetaData::new();
781 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
782 ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!(
783 "In handle_super_encryption_on_key_init: ",
784 "ECDHPrivateKey::encrypt_message failed."
785 ))?;
786 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
787 metadata.add(BlobMetaEntry::Salt(salt));
788 metadata.add(BlobMetaEntry::Iv(iv));
789 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000790 SuperKeyIdentifier::DatabaseId(key_id_guard.id())
791 .add_to_metadata(&mut metadata);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700792 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700793 }
794 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000795 SuperEncryptionType::BootLevel(level) => {
796 let key_id = SuperKeyIdentifier::BootLevel(level);
797 let super_key = self
798 .lookup_key(&key_id)
799 .context("In handle_super_encryption_on_key_init: lookup_key failed")?
800 .ok_or(Error::Rc(ResponseCode::LOCKED))
801 .context("In handle_super_encryption_on_key_init: Boot stage key absent")?;
802 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
803 "In handle_super_encryption_on_key_init: ",
804 "Failed to encrypt with BootLevel key."
805 ))
806 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000807 }
808 }
809
810 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
811 /// If so, re-super-encrypt the key and return a new set of metadata,
812 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700813 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000814 key_blob_before_upgrade: &KeyBlob,
815 key_after_upgrade: &'a [u8],
816 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
817 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700818 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700819 let (key, metadata) =
820 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
821 .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000822 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
823 }
824 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
825 }
826 }
827
Paul Crowley7a658392021-03-18 17:08:20 -0700828 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
829 /// When this is called, the caller must hold the lock on the SuperKeyManager.
830 /// So it's OK that the check and creation are different DB transactions.
831 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800832 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700833 db: &mut KeystoreDB,
834 user_id: UserId,
835 key_type: &SuperKeyType,
836 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700837 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700838 ) -> Result<Arc<SuperKey>> {
839 let loaded_key = db.load_super_key(key_type, user_id)?;
840 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700841 Ok(Self::extract_super_key_from_key_entry(
842 key_type.algorithm,
843 key_entry,
844 password,
845 reencrypt_with,
846 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700847 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700848 let (super_key, public_key) = match key_type.algorithm {
849 SuperEncryptionAlgorithm::Aes256Gcm => (
850 generate_aes256_key()
851 .context("In get_or_create_super_key: Failed to generate AES 256 key.")?,
852 None,
853 ),
Paul Crowley52f017f2021-06-22 08:16:01 -0700854 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700855 let key = ECDHPrivateKey::generate()
856 .context("In get_or_create_super_key: Failed to generate ECDH key")?;
857 (
858 key.private_key()
859 .context("In get_or_create_super_key: private_key failed")?,
860 Some(
861 key.public_key()
862 .context("In get_or_create_super_key: public_key failed")?,
863 ),
864 )
865 }
866 };
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800867 // Derive an AES256 key from the password and re-encrypt the super key
868 // before we insert it in the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700869 let (encrypted_super_key, blob_metadata) =
870 Self::encrypt_with_password(&super_key, password)
871 .context("In get_or_create_super_key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700872 let mut key_metadata = KeyMetaData::new();
873 if let Some(pk) = public_key {
874 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
875 }
Paul Crowley7a658392021-03-18 17:08:20 -0700876 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700877 .store_super_key(
878 user_id,
879 key_type,
880 &encrypted_super_key,
881 &blob_metadata,
882 &key_metadata,
883 )
Paul Crowley7a658392021-03-18 17:08:20 -0700884 .context("In get_or_create_super_key. Failed to store super key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700885 Ok(Arc::new(SuperKey {
886 algorithm: key_type.algorithm,
887 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000888 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700889 reencrypt_with,
890 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700891 }
892 }
893
Paul Crowley8d5b2532021-03-19 10:53:07 -0700894 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700895 pub fn unlock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800896 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700897 db: &mut KeystoreDB,
898 user_id: UserId,
899 password: &Password,
900 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800901 let (screen_lock_bound, screen_lock_bound_private) = self
902 .data
903 .user_keys
904 .get(&user_id)
905 .map(|e| (e.screen_lock_bound.clone(), e.screen_lock_bound_private.clone()))
906 .unwrap_or((None, None));
907
908 if screen_lock_bound.is_some() && screen_lock_bound_private.is_some() {
909 // Already unlocked.
910 return Ok(());
911 }
912
913 let aes = if let Some(screen_lock_bound) = screen_lock_bound {
914 // This is weird. If this point is reached only one of the screen locked keys was
915 // initialized. This should never happen.
916 screen_lock_bound
917 } else {
918 self.get_or_create_super_key(db, user_id, &USER_SCREEN_LOCK_BOUND_KEY, password, None)
919 .context("In unlock_screen_lock_bound_key: Trying to get or create symmetric key.")?
920 };
921
922 let ecdh = if let Some(screen_lock_bound_private) = screen_lock_bound_private {
923 // This is weird. If this point is reached only one of the screen locked keys was
924 // initialized. This should never happen.
925 screen_lock_bound_private
926 } else {
927 self.get_or_create_super_key(
928 db,
929 user_id,
930 &USER_SCREEN_LOCK_BOUND_P521_KEY,
931 password,
932 Some(aes.clone()),
933 )
934 .context("In unlock_screen_lock_bound_key: Trying to get or create asymmetric key.")?
935 };
936
937 self.data.add_key_to_key_index(&aes)?;
938 self.data.add_key_to_key_index(&ecdh)?;
939 let entry = self.data.user_keys.entry(user_id).or_default();
940 entry.screen_lock_bound = Some(aes);
941 entry.screen_lock_bound_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700942 Ok(())
943 }
944
Paul Crowley8d5b2532021-03-19 10:53:07 -0700945 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley618869e2021-04-08 20:30:54 -0700946 pub fn lock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800947 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700948 db: &mut KeystoreDB,
949 user_id: UserId,
950 unlocking_sids: &[i64],
951 ) {
952 log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800953 let mut entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700954 if !unlocking_sids.is_empty() {
955 if let (Some(aes), Some(ecdh)) = (
956 entry.screen_lock_bound.as_ref().cloned(),
957 entry.screen_lock_bound_private.as_ref().cloned(),
958 ) {
959 let res = (|| -> Result<()> {
960 let key_desc = KeyMintDevice::internal_descriptor(format!(
961 "biometric_unlock_key_{}",
962 user_id
963 ));
964 let encrypting_key = generate_aes256_key()?;
965 let km_dev: KeyMintDevice =
966 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
967 .context("In lock_screen_lock_bound_key: KeyMintDevice::get failed")?;
968 let mut key_params = vec![
969 KeyParameterValue::Algorithm(Algorithm::AES),
970 KeyParameterValue::KeySize(256),
971 KeyParameterValue::BlockMode(BlockMode::GCM),
972 KeyParameterValue::PaddingMode(PaddingMode::NONE),
973 KeyParameterValue::CallerNonce,
974 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
975 KeyParameterValue::MinMacLength(128),
976 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
977 KeyParameterValue::HardwareAuthenticatorType(
978 HardwareAuthenticatorType::FINGERPRINT,
979 ),
980 ];
981 for sid in unlocking_sids {
982 key_params.push(KeyParameterValue::UserSecureID(*sid));
983 }
984 let key_params: Vec<KmKeyParameter> =
985 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700986 km_dev.create_and_store_key(
987 db,
988 &key_desc,
989 KeyType::Client, /* TODO Should be Super b/189470584 */
990 |dev| {
991 let _wp = wd::watch_millis(
992 "In lock_screen_lock_bound_key: calling importKey.",
993 500,
994 );
995 dev.importKey(
996 key_params.as_slice(),
997 KeyFormat::RAW,
998 &encrypting_key,
999 None,
1000 )
1001 },
1002 )?;
Paul Crowley618869e2021-04-08 20:30:54 -07001003 entry.biometric_unlock = Some(BiometricUnlock {
1004 sids: unlocking_sids.into(),
1005 key_desc,
1006 screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
1007 screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
1008 });
1009 Ok(())
1010 })();
1011 // There is no reason to propagate an error here upwards. We must discard
1012 // entry.screen_lock_bound* in any case.
1013 if let Err(e) = res {
1014 log::error!("Error setting up biometric unlock: {:#?}", e);
1015 }
1016 }
1017 }
Paul Crowley7a658392021-03-18 17:08:20 -07001018 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -07001019 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -07001020 }
Paul Crowley618869e2021-04-08 20:30:54 -07001021
1022 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
1023 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
1024 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001025 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -07001026 db: &mut KeystoreDB,
1027 user_id: UserId,
1028 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001029 let mut entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -07001030 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -07001031 let (key_id_guard, key_entry) = db
1032 .load_key_entry(
1033 &biometric.key_desc,
1034 KeyType::Client, // This should not be a Client key.
1035 KeyEntryLoadBits::KM,
1036 AID_KEYSTORE,
1037 |_, _| Ok(()),
1038 )
1039 .context("In try_unlock_user_with_biometric: load_key_entry failed")?;
Paul Crowley618869e2021-04-08 20:30:54 -07001040 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
1041 .context("In try_unlock_user_with_biometric: KeyMintDevice::get failed")?;
1042 for sid in &biometric.sids {
1043 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
1044 entry.auth_token().userId == *sid || entry.auth_token().authenticatorId == *sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001045 }) {
Paul Crowley618869e2021-04-08 20:30:54 -07001046 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
1047 let slb = biometric.screen_lock_bound.decrypt(
1048 db,
1049 &km_dev,
1050 &key_id_guard,
1051 &key_entry,
1052 auth_token_entry.auth_token(),
1053 None,
1054 )?;
1055 let slbp = biometric.screen_lock_bound_private.decrypt(
1056 db,
1057 &km_dev,
1058 &key_id_guard,
1059 &key_entry,
1060 auth_token_entry.auth_token(),
1061 Some(slb.clone()),
1062 )?;
1063 Ok((slb, slbp))
1064 })();
1065 match res {
1066 Ok((slb, slbp)) => {
1067 entry.screen_lock_bound = Some(slb.clone());
1068 entry.screen_lock_bound_private = Some(slbp.clone());
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001069 self.data.add_key_to_key_index(&slb)?;
1070 self.data.add_key_to_key_index(&slbp)?;
Paul Crowley618869e2021-04-08 20:30:54 -07001071 log::info!(concat!(
1072 "In try_unlock_user_with_biometric: ",
1073 "Successfully unlocked with biometric"
1074 ));
1075 return Ok(());
1076 }
1077 Err(e) => {
1078 log::warn!("In try_unlock_user_with_biometric: attempt failed: {:?}", e)
1079 }
1080 }
1081 }
1082 }
1083 }
1084 Ok(())
1085 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001086
1087 /// Returns the keystore locked state of the given user. It requires the thread local
1088 /// keystore database and a reference to the legacy migrator because it may need to
1089 /// migrate the super key from the legacy blob database to the keystore database.
1090 pub fn get_user_state(
1091 &self,
1092 db: &mut KeystoreDB,
1093 legacy_migrator: &LegacyMigrator,
1094 user_id: UserId,
1095 ) -> Result<UserState> {
1096 match self.get_per_boot_key_by_user_id(user_id) {
1097 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
1098 None => {
1099 // Check if a super key exists in the database or legacy database.
1100 // If so, return locked user state.
1101 if self
1102 .super_key_exists_in_db_for_user(db, legacy_migrator, user_id)
1103 .context("In get_user_state.")?
1104 {
1105 Ok(UserState::LskfLocked)
1106 } else {
1107 Ok(UserState::Uninitialized)
1108 }
1109 }
1110 }
1111 }
1112
1113 /// If the given user is unlocked:
1114 /// * and `password` is None, the user is reset, all authentication bound keys are deleted and
1115 /// `Ok(UserState::Uninitialized)` is returned.
1116 /// * and `password` is Some, `Ok(UserState::LskfUnlocked)` is returned.
1117 /// If the given user is locked:
1118 /// * and the user was initialized before, `Ok(UserState::Locked)` is returned.
1119 /// * and the user was not initialized before:
1120 /// * and `password` is None, `Ok(Uninitialized)` is returned.
1121 /// * and `password` is Some, super keys are generated and `Ok(UserState::LskfUnlocked)` is
1122 /// returned.
1123 pub fn reset_or_init_user_and_get_user_state(
1124 &mut self,
1125 db: &mut KeystoreDB,
1126 legacy_migrator: &LegacyMigrator,
1127 user_id: UserId,
1128 password: Option<&Password>,
1129 ) -> Result<UserState> {
1130 match self.get_per_boot_key_by_user_id(user_id) {
1131 Some(_) if password.is_none() => {
1132 // Transitioning to swiping, delete only the super key in database and cache,
1133 // and super-encrypted keys in database (and in KM).
1134 self.reset_user(db, legacy_migrator, user_id, true).context(
1135 "In reset_or_init_user_and_get_user_state: Trying to delete keys from the db.",
1136 )?;
1137 // Lskf is now removed in Keystore.
1138 Ok(UserState::Uninitialized)
1139 }
1140 Some(super_key) => {
1141 // Keystore won't be notified when changing to a new password when LSKF is
1142 // already setup. Therefore, ideally this path wouldn't be reached.
1143 Ok(UserState::LskfUnlocked(super_key))
1144 }
1145 None => {
1146 // Check if a super key exists in the database or legacy database.
1147 // If so, return LskfLocked state.
1148 // Otherwise, i) if the password is provided, initialize the super key and return
1149 // LskfUnlocked state ii) if password is not provided, return Uninitialized state.
1150 self.check_and_initialize_super_key(db, legacy_migrator, user_id, password)
1151 }
1152 }
1153 }
1154
1155 /// Unlocks the given user with the given password. If the key was already unlocked or unlocking
1156 /// was successful, `Ok(UserState::LskfUnlocked)` is returned.
1157 /// If the user was never initialized `Ok(UserState::Uninitialized)` is returned.
1158 pub fn unlock_and_get_user_state(
1159 &mut self,
1160 db: &mut KeystoreDB,
1161 legacy_migrator: &LegacyMigrator,
1162 user_id: UserId,
1163 password: &Password,
1164 ) -> Result<UserState> {
1165 match self.get_per_boot_key_by_user_id(user_id) {
1166 Some(super_key) => {
1167 log::info!("In unlock_and_get_user_state. Trying to unlock when already unlocked.");
1168 Ok(UserState::LskfUnlocked(super_key))
1169 }
1170 None => {
1171 // Check if a super key exists in the database or legacy database.
1172 // If not, return Uninitialized state.
1173 // Otherwise, try to unlock the super key and if successful,
1174 // return LskfUnlocked.
1175 self.check_and_unlock_super_key(db, legacy_migrator, user_id, password)
1176 .context("In unlock_and_get_user_state. Failed to unlock super key.")
1177 }
1178 }
1179 }
1180
1181 /// Delete all the keys created on behalf of the user.
1182 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
1183 /// encrypted keys.
1184 pub fn reset_user(
1185 &mut self,
1186 db: &mut KeystoreDB,
1187 legacy_migrator: &LegacyMigrator,
1188 user_id: UserId,
1189 keep_non_super_encrypted_keys: bool,
1190 ) -> Result<()> {
1191 // Mark keys created on behalf of the user as unreferenced.
1192 legacy_migrator
1193 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
1194 .context("In reset_user: Trying to delete legacy keys.")?;
1195 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
1196 .context("In reset user. Error in unbinding keys.")?;
1197
1198 // Delete super key in cache, if exists.
1199 self.forget_all_keys_for_user(user_id);
1200 Ok(())
1201 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001202}
1203
1204/// This enum represents different states of the user's life cycle in the device.
1205/// For now, only three states are defined. More states may be added later.
1206pub enum UserState {
1207 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
1208 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -07001209 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001210 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
1211 // Hence the per-boot super-key(s) is not available in the cache.
1212 // However, the encrypted super key is available in the database.
1213 LskfLocked,
1214 // There's no user in the device for the given user id, or the user with the user id has not
1215 // setup LSKF.
1216 Uninitialized,
1217}
1218
Janis Danisevskiseed69842021-02-18 20:04:10 -08001219/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1220/// `Sensitive` holds the non encrypted key and a reference to its super key.
1221/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1222/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1223/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001224pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001225 Sensitive {
1226 key: ZVec,
1227 /// If KeyMint reports that the key must be upgraded, we must
1228 /// re-encrypt the key before writing to the database; we use
1229 /// this key.
1230 reencrypt_with: Arc<SuperKey>,
1231 /// If this key was decrypted with an ECDH key, we want to
1232 /// re-encrypt it on first use whether it was upgraded or not;
1233 /// this field indicates that that's necessary.
1234 force_reencrypt: bool,
1235 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001236 NonSensitive(Vec<u8>),
1237 Ref(&'a [u8]),
1238}
1239
Paul Crowley8d5b2532021-03-19 10:53:07 -07001240impl<'a> KeyBlob<'a> {
1241 pub fn force_reencrypt(&self) -> bool {
1242 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1243 *force_reencrypt
1244 } else {
1245 false
1246 }
1247 }
1248}
1249
Janis Danisevskiseed69842021-02-18 20:04:10 -08001250/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001251impl<'a> Deref for KeyBlob<'a> {
1252 type Target = [u8];
1253
1254 fn deref(&self) -> &Self::Target {
1255 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001256 Self::Sensitive { key, .. } => key,
1257 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001258 Self::Ref(key) => key,
1259 }
1260 }
1261}