blob: d490354546eb2fbe89f72d98edc871f6597377a1 [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 Crowley8d5b2532021-03-19 10:53:07 -070016 database::BlobMetaData,
17 database::BlobMetaEntry,
18 database::EncryptedBy,
19 database::KeyEntry,
20 database::KeyType,
21 database::{KeyMetaData, KeyMetaEntry, KeystoreDB},
22 ec_crypto::ECDHPrivateKey,
23 enforcements::Enforcements,
24 error::Error,
25 error::ResponseCode,
26 key_parameter::KeyParameter,
27 legacy_blob::LegacyBlobLoader,
28 legacy_migrator::LegacyMigrator,
29 try_insert::TryInsert,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080030};
31use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
32use anyhow::{Context, Result};
33use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070034 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
35 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080036};
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000037use std::ops::Deref;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080038use std::{
39 collections::HashMap,
40 sync::Arc,
41 sync::{Mutex, Weak},
42};
43
44type UserId = u32;
45
Paul Crowley8d5b2532021-03-19 10:53:07 -070046/// Encryption algorithm used by a particular type of superencryption key
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum SuperEncryptionAlgorithm {
49 /// Symmetric encryption with AES-256-GCM
50 Aes256Gcm,
51 /// Public-key encryption with ECDH P-256
52 EcdhP256,
53}
54
Paul Crowley7a658392021-03-18 17:08:20 -070055/// A particular user may have several superencryption keys in the database, each for a
56/// different purpose, distinguished by alias. Each is associated with a static
57/// constant of this type.
58pub struct SuperKeyType {
59 /// Alias used to look the key up in the `persistent.keyentry` table.
60 pub alias: &'static str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070061 /// Encryption algorithm
62 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070063}
64
65/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
66/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070067pub const USER_SUPER_KEY: SuperKeyType =
68 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070069/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
70/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070071/// Symmetric.
72pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
73 alias: "USER_SCREEN_LOCK_BOUND_KEY",
74 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
75};
76/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
77/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
78/// Asymmetric, so keys can be encrypted when the device is locked.
79pub const USER_SCREEN_LOCK_BOUND_ECDH_KEY: SuperKeyType = SuperKeyType {
80 alias: "USER_SCREEN_LOCK_BOUND_ECDH_KEY",
81 algorithm: SuperEncryptionAlgorithm::EcdhP256,
82};
Paul Crowley7a658392021-03-18 17:08:20 -070083
84/// Superencryption to apply to a new key.
85#[derive(Debug, Clone, Copy)]
86pub enum SuperEncryptionType {
87 /// Do not superencrypt this key.
88 None,
89 /// Superencrypt with a key that remains in memory from first unlock to reboot.
90 LskfBound,
91 /// Superencrypt with a key cleared from memory when the device is locked.
92 ScreenLockBound,
93}
94
Janis Danisevskisb42fc182020-12-15 08:41:27 -080095#[derive(Default)]
96struct UserSuperKeys {
97 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
98 /// key per android user. The key is stored on flash encrypted with a key derived from a
99 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
100 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
101 /// and stays memory resident until the device reboots.
Paul Crowley7a658392021-03-18 17:08:20 -0700102 per_boot: Option<Arc<SuperKey>>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800103 /// The screen lock key works like the per boot key with the distinction that it is cleared
104 /// from memory when the screen lock is engaged.
Paul Crowley7a658392021-03-18 17:08:20 -0700105 screen_lock_bound: Option<Arc<SuperKey>>,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700106 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
107 /// ECDH public-key encryption. This field holds the decryption private key.
108 screen_lock_bound_private: Option<Arc<SuperKey>>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800109}
110
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000111pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700112 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700113 key: ZVec,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000114 // id of the super key in the database.
115 id: i64,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700116 /// ECDH is more expensive than AES. So on ECDH private keys we set the
117 /// reencrypt_with field to point at the corresponding AES key, and the
118 /// keys will be re-encrypted with AES on first use.
119 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000120}
121
122impl SuperKey {
Paul Crowley7a658392021-03-18 17:08:20 -0700123 /// For most purposes `unwrap_key` handles decryption,
124 /// but legacy handling and some tests need to assume AES and decrypt directly.
125 pub fn aes_gcm_decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700126 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
127 aes_gcm_decrypt(data, iv, tag, &self.key)
128 .context("In aes_gcm_decrypt: decryption failed")
129 } else {
130 Err(Error::sys()).context("In aes_gcm_decrypt: Key is not an AES key")
131 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000132 }
133
134 pub fn get_id(&self) -> i64 {
135 self.id
136 }
137}
138
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800139#[derive(Default)]
140struct SkmState {
141 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700142 key_index: HashMap<i64, Weak<SuperKey>>,
143}
144
145impl SkmState {
146 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) {
147 self.key_index.insert(super_key.id, Arc::downgrade(super_key));
148 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800149}
150
151#[derive(Default)]
152pub struct SuperKeyManager {
153 data: Mutex<SkmState>,
154}
155
156impl SuperKeyManager {
157 pub fn new() -> Self {
Paul Crowley7a658392021-03-18 17:08:20 -0700158 Default::default()
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800159 }
160
161 pub fn forget_all_keys_for_user(&self, user: UserId) {
162 let mut data = self.data.lock().unwrap();
163 data.user_keys.remove(&user);
164 }
165
Paul Crowley7a658392021-03-18 17:08:20 -0700166 fn install_per_boot_key_for_user(&self, user: UserId, super_key: Arc<SuperKey>) {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800167 let mut data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700168 data.add_key_to_key_index(&super_key);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000169 data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800170 }
171
Paul Crowley7a658392021-03-18 17:08:20 -0700172 fn get_key(&self, key_id: &i64) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800173 self.data.lock().unwrap().key_index.get(key_id).and_then(|k| k.upgrade())
174 }
175
Paul Crowley7a658392021-03-18 17:08:20 -0700176 pub fn get_per_boot_key_by_user_id(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800177 let data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700178 data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800179 }
180
181 /// This function unlocks the super keys for a given user.
182 /// This means the key is loaded from the database, decrypted and placed in the
183 /// super key cache. If there is no such key a new key is created, encrypted with
184 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800185 pub fn unlock_user_key(
186 &self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000187 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800188 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700189 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800190 legacy_blob_loader: &LegacyBlobLoader,
191 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800192 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800193 .get_or_create_key_with(
194 Domain::APP,
195 user as u64 as i64,
Paul Crowley7a658392021-03-18 17:08:20 -0700196 &USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800197 crate::database::KEYSTORE_UUID,
198 || {
199 // For backward compatibility we need to check if there is a super key present.
200 let super_key = legacy_blob_loader
201 .load_super_key(user, pw)
202 .context("In create_new_key: Failed to load legacy key blob.")?;
203 let super_key = match super_key {
204 None => {
205 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000206 generate_aes256_key()
Max Bires8e93d2b2021-01-14 13:17:59 -0800207 .context("In create_new_key: Failed to generate AES 256 key.")?
208 }
209 Some(key) => key,
210 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000211 // Regardless of whether we loaded an old AES128 key or generated a new AES256
212 // key as the super key, we derive a AES256 key from the password and re-encrypt
213 // the super key before we insert it in the database. The length of the key is
214 // preserved by the encryption so we don't need any extra flags to inform us
215 // which algorithm to use it with.
216 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800217 },
218 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800219 .context("In unlock_user_key: Failed to get key id.")?;
220
Paul Crowley8d5b2532021-03-19 10:53:07 -0700221 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
222 .context("In unlock_user_key.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800223 Ok(())
224 }
225
226 /// Unwraps an encrypted key blob given metadata identifying the encryption key.
227 /// The function queries `metadata.encrypted_by()` to determine the encryption key.
228 /// It then check if the required key is memory resident, and if so decrypts the
229 /// blob.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000230 pub fn unwrap_key<'a>(&self, blob: &'a [u8], metadata: &BlobMetaData) -> Result<KeyBlob<'a>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800231 match metadata.encrypted_by() {
232 Some(EncryptedBy::KeyId(key_id)) => match self.get_key(key_id) {
Paul Crowley7a658392021-03-18 17:08:20 -0700233 Some(super_key) => Ok(KeyBlob::Sensitive {
234 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
235 .context("In unwrap_key: unwrap_key_with_key failed")?,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700236 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
237 force_reencrypt: super_key.reencrypt_with.is_some(),
Paul Crowley7a658392021-03-18 17:08:20 -0700238 }),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800239 None => Err(Error::Rc(ResponseCode::LOCKED))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700240 .context("In unwrap_key: Required super decryption key is not in memory."),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800241 },
242 _ => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
243 .context("In unwrap_key: Cannot determined wrapping key."),
244 }
245 }
246
247 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700248 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700249 match key.algorithm {
250 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
251 (Some(iv), Some(tag)) => key
252 .aes_gcm_decrypt(blob, iv, tag)
253 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
254 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
255 concat!(
256 "In unwrap_key_with_key: Key has incomplete metadata.",
257 "Present: iv: {}, aead_tag: {}."
258 ),
259 iv.is_some(),
260 tag.is_some(),
261 )),
262 },
263 SuperEncryptionAlgorithm::EcdhP256 => {
264 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
265 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
266 ECDHPrivateKey::from_private_key(&key.key)
267 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
268 .context(
269 "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.",
270 )
271 }
272 (public_key, salt, iv, aead_tag) => {
273 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
274 concat!(
275 "In unwrap_key_with_key: Key has incomplete metadata.",
276 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
277 ),
278 public_key.is_some(),
279 salt.is_some(),
280 iv.is_some(),
281 aead_tag.is_some(),
282 ))
283 }
284 }
285 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800286 }
287 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000288
289 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000290 pub fn super_key_exists_in_db_for_user(
291 db: &mut KeystoreDB,
292 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700293 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000294 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000295 let key_in_db = db
Paul Crowley7a658392021-03-18 17:08:20 -0700296 .key_exists(Domain::APP, user_id as u64 as i64, &USER_SUPER_KEY.alias, KeyType::Super)
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000297 .context("In super_key_exists_in_db_for_user.")?;
298
299 if key_in_db {
300 Ok(key_in_db)
301 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000302 legacy_migrator
303 .has_super_key(user_id)
304 .context("In super_key_exists_in_db_for_user: Trying to query legacy db.")
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000305 }
306 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000307
308 /// 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 +0000309 /// legacy database). If not, return Uninitialized state.
310 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
311 pub fn check_and_unlock_super_key(
312 &self,
313 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000314 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700315 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700316 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000317 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700318 let alias = &USER_SUPER_KEY;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000319 let result = legacy_migrator
Paul Crowley8d5b2532021-03-19 10:53:07 -0700320 .with_try_migrate_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000321 .context("In check_and_unlock_super_key. Failed to load super key")?;
322
323 match result {
324 Some((_, entry)) => {
325 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700326 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000327 .context("In check_and_unlock_super_key.")?;
328 Ok(UserState::LskfUnlocked(super_key))
329 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000330 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000331 }
332 }
333
334 /// 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 +0000335 /// legacy database). If so, return LskfLocked state.
336 /// If the password is provided, generate a new super key, encrypt with the password,
337 /// store in the database and populate the super key cache for the new user
338 /// and return LskfUnlocked state.
339 /// If the password is not provided, return Uninitialized state.
340 pub fn check_and_initialize_super_key(
341 &self,
342 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000343 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700344 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700345 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000346 ) -> Result<UserState> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000347 let super_key_exists_in_db =
348 Self::super_key_exists_in_db_for_user(db, legacy_migrator, user_id).context(
349 "In check_and_initialize_super_key. Failed to check if super key exists.",
350 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000351 if super_key_exists_in_db {
352 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000353 } else if let Some(pw) = pw {
354 //generate a new super key.
355 let super_key = generate_aes256_key()
356 .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?;
357 //derive an AES256 key from the password and re-encrypt the super key
358 //before we insert it in the database.
359 let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw)
360 .context("In check_and_initialize_super_key.")?;
361
362 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700363 .store_super_key(
364 user_id,
365 &USER_SUPER_KEY,
366 &encrypted_super_key,
367 &blob_metadata,
368 &KeyMetaData::new(),
369 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000370 .context("In check_and_initialize_super_key. Failed to store super key.")?;
371
372 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700373 .populate_cache_from_super_key_blob(
374 user_id,
375 USER_SUPER_KEY.algorithm,
376 key_entry,
377 pw,
378 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000379 .context("In check_and_initialize_super_key.")?;
380 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000381 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000382 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000383 }
384 }
385
386 //helper function to populate super key cache from the super key blob loaded from the database
387 fn populate_cache_from_super_key_blob(
388 &self,
Paul Crowley7a658392021-03-18 17:08:20 -0700389 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700390 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000391 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700392 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700393 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700394 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
395 .context(
396 "In populate_cache_from_super_key_blob. Failed to extract super key from key entry",
397 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000398 self.install_per_boot_key_for_user(user_id, super_key.clone());
399 Ok(super_key)
400 }
401
402 /// Extracts super key from the entry loaded from the database
Paul Crowley7a658392021-03-18 17:08:20 -0700403 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700404 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700405 entry: KeyEntry,
406 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700407 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700408 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000409 if let Some((blob, metadata)) = entry.key_blob_info() {
410 let key = match (
411 metadata.encrypted_by(),
412 metadata.salt(),
413 metadata.iv(),
414 metadata.aead_tag(),
415 ) {
416 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700417 // Note that password encryption is AES no matter the value of algorithm
Paul Crowleyf61fee72021-03-17 14:38:44 -0700418 let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context(
419 "In extract_super_key_from_key_entry: Failed to generate key from password.",
420 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000421
422 aes_gcm_decrypt(blob, iv, tag, &key).context(
423 "In extract_super_key_from_key_entry: Failed to decrypt key blob.",
424 )?
425 }
426 (enc_by, salt, iv, tag) => {
427 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
428 concat!(
429 "In extract_super_key_from_key_entry: Super key has incomplete metadata.",
430 "Present: encrypted_by: {}, salt: {}, iv: {}, aead_tag: {}."
431 ),
432 enc_by.is_some(),
433 salt.is_some(),
434 iv.is_some(),
435 tag.is_some()
436 ));
437 }
438 };
Paul Crowley8d5b2532021-03-19 10:53:07 -0700439 Ok(Arc::new(SuperKey { algorithm, key, id: entry.id(), reencrypt_with }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000440 } else {
441 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
442 .context("In extract_super_key_from_key_entry: No key blob info.")
443 }
444 }
445
446 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700447 pub fn encrypt_with_password(
448 super_key: &[u8],
449 pw: &Password,
450 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000451 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700452 let derived_key = pw
453 .derive_key(Some(&salt), AES_256_KEY_LENGTH)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000454 .context("In encrypt_with_password: Failed to derive password.")?;
455 let mut metadata = BlobMetaData::new();
456 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
457 metadata.add(BlobMetaEntry::Salt(salt));
458 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
459 .context("In encrypt_with_password: Failed to encrypt new super key.")?;
460 metadata.add(BlobMetaEntry::Iv(iv));
461 metadata.add(BlobMetaEntry::AeadTag(tag));
462 Ok((encrypted_key, metadata))
463 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000464
465 // Encrypt the given key blob with the user's super key, if the super key exists and the device
466 // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
467 // return error. Note that it is out of the scope of this function to check if super encryption
468 // is required. Such check should be performed before calling this function.
469 fn super_encrypt_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000470 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000471 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000472 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700473 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000474 key_blob: &[u8],
475 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000476 match UserState::get(db, legacy_migrator, self, user_id)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000477 .context("In super_encrypt. Failed to get user state.")?
478 {
479 UserState::LskfUnlocked(super_key) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700480 Self::encrypt_with_aes_super_key(key_blob, &super_key)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000481 .context("In super_encrypt_on_key_init. Failed to encrypt the key.")
482 }
483 UserState::LskfLocked => {
484 Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.")
485 }
486 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
487 .context("In super_encrypt. LSKF is not setup for the user."),
488 }
489 }
490
491 //Helper function to encrypt a key with the given super key. Callers should select which super
492 //key to be used. This is called when a key is super encrypted at its creation as well as at its
493 //upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700494 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000495 key_blob: &[u8],
496 super_key: &SuperKey,
497 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700498 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
499 return Err(Error::sys())
500 .context("In encrypt_with_aes_super_key: unexpected algorithm");
501 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000502 let mut metadata = BlobMetaData::new();
503 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700504 .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000505 metadata.add(BlobMetaEntry::Iv(iv));
506 metadata.add(BlobMetaEntry::AeadTag(tag));
507 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key.id)));
508 Ok((encrypted_key, metadata))
509 }
510
511 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
512 /// the database.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000513 #[allow(clippy::clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000514 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000515 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000516 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000517 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000518 domain: &Domain,
519 key_parameters: &[KeyParameter],
520 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700521 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000522 key_blob: &[u8],
523 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700524 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
525 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
526 SuperEncryptionType::LskfBound => {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000527 self.super_encrypt_on_key_init(db, legacy_migrator, user_id, &key_blob).context(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000528 "In handle_super_encryption_on_key_init.
529 Failed to super encrypt the key.",
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000530 )
531 }
Paul Crowley7a658392021-03-18 17:08:20 -0700532 SuperEncryptionType::ScreenLockBound => {
533 let mut data = self.data.lock().unwrap();
534 let entry = data.user_keys.entry(user_id).or_default();
535 if let Some(super_key) = entry.screen_lock_bound.as_ref() {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700536 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
Paul Crowley7a658392021-03-18 17:08:20 -0700537 "In handle_super_encryption_on_key_init. ",
538 "Failed to encrypt the key with screen_lock_bound key."
539 ))
540 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700541 // Symmetric key is not available, use public key encryption
542 let loaded =
543 db.load_super_key(&USER_SCREEN_LOCK_BOUND_ECDH_KEY, user_id).context(
544 "In handle_super_encryption_on_key_init: load_super_key failed.",
545 )?;
546 let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context(
547 "In handle_super_encryption_on_key_init: User ECDH key missing.",
548 )?;
549 let public_key =
550 key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context(
551 "In handle_super_encryption_on_key_init: sec1_public_key missing.",
552 )?;
553 let mut metadata = BlobMetaData::new();
554 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
555 ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!(
556 "In handle_super_encryption_on_key_init: ",
557 "ECDHPrivateKey::encrypt_message failed."
558 ))?;
559 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
560 metadata.add(BlobMetaEntry::Salt(salt));
561 metadata.add(BlobMetaEntry::Iv(iv));
562 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
563 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(key_id_guard.id())));
564 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700565 }
566 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000567 }
568 }
569
570 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
571 /// the relevant super key.
572 pub fn unwrap_key_if_required<'a>(
573 &self,
574 metadata: &BlobMetaData,
575 key_blob: &'a [u8],
576 ) -> Result<KeyBlob<'a>> {
577 if Self::key_super_encrypted(&metadata) {
578 let unwrapped_key = self
579 .unwrap_key(key_blob, metadata)
580 .context("In unwrap_key_if_required. Error in unwrapping the key.")?;
581 Ok(unwrapped_key)
582 } else {
583 Ok(KeyBlob::Ref(key_blob))
584 }
585 }
586
587 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
588 /// If so, re-super-encrypt the key and return a new set of metadata,
589 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700590 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000591 key_blob_before_upgrade: &KeyBlob,
592 key_after_upgrade: &'a [u8],
593 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
594 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700595 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700596 let (key, metadata) =
597 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
598 .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000599 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
600 }
601 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
602 }
603 }
604
605 // Helper function to decide if a key is super encrypted, given metadata.
606 fn key_super_encrypted(metadata: &BlobMetaData) -> bool {
607 if let Some(&EncryptedBy::KeyId(_)) = metadata.encrypted_by() {
608 return true;
609 }
610 false
611 }
Paul Crowley7a658392021-03-18 17:08:20 -0700612
613 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
614 /// When this is called, the caller must hold the lock on the SuperKeyManager.
615 /// So it's OK that the check and creation are different DB transactions.
616 fn get_or_create_super_key(
617 db: &mut KeystoreDB,
618 user_id: UserId,
619 key_type: &SuperKeyType,
620 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700621 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700622 ) -> Result<Arc<SuperKey>> {
623 let loaded_key = db.load_super_key(key_type, user_id)?;
624 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700625 Ok(Self::extract_super_key_from_key_entry(
626 key_type.algorithm,
627 key_entry,
628 password,
629 reencrypt_with,
630 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700631 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700632 let (super_key, public_key) = match key_type.algorithm {
633 SuperEncryptionAlgorithm::Aes256Gcm => (
634 generate_aes256_key()
635 .context("In get_or_create_super_key: Failed to generate AES 256 key.")?,
636 None,
637 ),
638 SuperEncryptionAlgorithm::EcdhP256 => {
639 let key = ECDHPrivateKey::generate()
640 .context("In get_or_create_super_key: Failed to generate ECDH key")?;
641 (
642 key.private_key()
643 .context("In get_or_create_super_key: private_key failed")?,
644 Some(
645 key.public_key()
646 .context("In get_or_create_super_key: public_key failed")?,
647 ),
648 )
649 }
650 };
Paul Crowley7a658392021-03-18 17:08:20 -0700651 //derive an AES256 key from the password and re-encrypt the super key
652 //before we insert it in the database.
653 let (encrypted_super_key, blob_metadata) =
654 Self::encrypt_with_password(&super_key, password)
655 .context("In get_or_create_super_key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700656 let mut key_metadata = KeyMetaData::new();
657 if let Some(pk) = public_key {
658 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
659 }
Paul Crowley7a658392021-03-18 17:08:20 -0700660 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700661 .store_super_key(
662 user_id,
663 key_type,
664 &encrypted_super_key,
665 &blob_metadata,
666 &key_metadata,
667 )
Paul Crowley7a658392021-03-18 17:08:20 -0700668 .context("In get_or_create_super_key. Failed to store super key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700669 Ok(Arc::new(SuperKey {
670 algorithm: key_type.algorithm,
671 key: super_key,
672 id: key_entry.id(),
673 reencrypt_with,
674 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700675 }
676 }
677
Paul Crowley8d5b2532021-03-19 10:53:07 -0700678 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700679 pub fn unlock_screen_lock_bound_key(
680 &self,
681 db: &mut KeystoreDB,
682 user_id: UserId,
683 password: &Password,
684 ) -> Result<()> {
685 let mut data = self.data.lock().unwrap();
686 let entry = data.user_keys.entry(user_id).or_default();
687 let aes = entry
688 .screen_lock_bound
689 .get_or_try_to_insert_with(|| {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700690 Self::get_or_create_super_key(
691 db,
692 user_id,
693 &USER_SCREEN_LOCK_BOUND_KEY,
694 password,
695 None,
696 )
697 })?
698 .clone();
699 let ecdh = entry
700 .screen_lock_bound_private
701 .get_or_try_to_insert_with(|| {
702 Self::get_or_create_super_key(
703 db,
704 user_id,
705 &USER_SCREEN_LOCK_BOUND_ECDH_KEY,
706 password,
707 Some(aes.clone()),
708 )
Paul Crowley7a658392021-03-18 17:08:20 -0700709 })?
710 .clone();
711 data.add_key_to_key_index(&aes);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700712 data.add_key_to_key_index(&ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700713 Ok(())
714 }
715
Paul Crowley8d5b2532021-03-19 10:53:07 -0700716 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700717 pub fn lock_screen_lock_bound_key(&self, user_id: UserId) {
718 let mut data = self.data.lock().unwrap();
719 let mut entry = data.user_keys.entry(user_id).or_default();
720 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700721 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700722 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000723}
724
725/// This enum represents different states of the user's life cycle in the device.
726/// For now, only three states are defined. More states may be added later.
727pub enum UserState {
728 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
729 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -0700730 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000731 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
732 // Hence the per-boot super-key(s) is not available in the cache.
733 // However, the encrypted super key is available in the database.
734 LskfLocked,
735 // There's no user in the device for the given user id, or the user with the user id has not
736 // setup LSKF.
737 Uninitialized,
738}
739
740impl UserState {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000741 pub fn get(
742 db: &mut KeystoreDB,
743 legacy_migrator: &LegacyMigrator,
744 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700745 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000746 ) -> Result<UserState> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000747 match skm.get_per_boot_key_by_user_id(user_id) {
748 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
749 None => {
750 //Check if a super key exists in the database or legacy database.
751 //If so, return locked user state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000752 if SuperKeyManager::super_key_exists_in_db_for_user(db, legacy_migrator, user_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000753 .context("In get.")?
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000754 {
755 Ok(UserState::LskfLocked)
756 } else {
757 Ok(UserState::Uninitialized)
758 }
759 }
760 }
761 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000762
763 /// Queries user state when serving password change requests.
764 pub fn get_with_password_changed(
765 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000766 legacy_migrator: &LegacyMigrator,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000767 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700768 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700769 password: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000770 ) -> Result<UserState> {
771 match skm.get_per_boot_key_by_user_id(user_id) {
772 Some(super_key) => {
773 if password.is_none() {
774 //transitioning to swiping, delete only the super key in database and cache, and
775 //super-encrypted keys in database (and in KM)
Janis Danisevskiseed69842021-02-18 20:04:10 -0800776 Self::reset_user(db, skm, legacy_migrator, user_id, true).context(
777 "In get_with_password_changed: Trying to delete keys from the db.",
778 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000779 //Lskf is now removed in Keystore
780 Ok(UserState::Uninitialized)
781 } else {
782 //Keystore won't be notified when changing to a new password when LSKF is
783 //already setup. Therefore, ideally this path wouldn't be reached.
784 Ok(UserState::LskfUnlocked(super_key))
785 }
786 }
787 None => {
788 //Check if a super key exists in the database or legacy database.
789 //If so, return LskfLocked state.
790 //Otherwise, i) if the password is provided, initialize the super key and return
791 //LskfUnlocked state ii) if password is not provided, return Uninitialized state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000792 skm.check_and_initialize_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000793 }
794 }
795 }
796
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000797 /// Queries user state when serving password unlock requests.
798 pub fn get_with_password_unlock(
799 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000800 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000801 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700802 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700803 password: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000804 ) -> Result<UserState> {
805 match skm.get_per_boot_key_by_user_id(user_id) {
806 Some(super_key) => {
807 log::info!("In get_with_password_unlock. Trying to unlock when already unlocked.");
808 Ok(UserState::LskfUnlocked(super_key))
809 }
810 None => {
811 //Check if a super key exists in the database or legacy database.
812 //If not, return Uninitialized state.
813 //Otherwise, try to unlock the super key and if successful,
814 //return LskfUnlocked state
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000815 skm.check_and_unlock_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000816 .context("In get_with_password_unlock. Failed to unlock super key.")
817 }
818 }
819 }
820
Hasini Gunasingheda895552021-01-27 19:34:37 +0000821 /// Delete all the keys created on behalf of the user.
822 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
823 /// encrypted keys.
824 pub fn reset_user(
825 db: &mut KeystoreDB,
826 skm: &SuperKeyManager,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800827 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700828 user_id: UserId,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000829 keep_non_super_encrypted_keys: bool,
830 ) -> Result<()> {
831 // mark keys created on behalf of the user as unreferenced.
Janis Danisevskiseed69842021-02-18 20:04:10 -0800832 legacy_migrator
833 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
834 .context("In reset_user: Trying to delete legacy keys.")?;
Paul Crowley7a658392021-03-18 17:08:20 -0700835 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000836 .context("In reset user. Error in unbinding keys.")?;
837
838 //delete super key in cache, if exists
Paul Crowley7a658392021-03-18 17:08:20 -0700839 skm.forget_all_keys_for_user(user_id);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000840 Ok(())
841 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800842}
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000843
Janis Danisevskiseed69842021-02-18 20:04:10 -0800844/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
845/// `Sensitive` holds the non encrypted key and a reference to its super key.
846/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
847/// `Ref` holds a reference to a key blob when it does not need to be modified if its
848/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000849pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700850 Sensitive {
851 key: ZVec,
852 /// If KeyMint reports that the key must be upgraded, we must
853 /// re-encrypt the key before writing to the database; we use
854 /// this key.
855 reencrypt_with: Arc<SuperKey>,
856 /// If this key was decrypted with an ECDH key, we want to
857 /// re-encrypt it on first use whether it was upgraded or not;
858 /// this field indicates that that's necessary.
859 force_reencrypt: bool,
860 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000861 NonSensitive(Vec<u8>),
862 Ref(&'a [u8]),
863}
864
Paul Crowley8d5b2532021-03-19 10:53:07 -0700865impl<'a> KeyBlob<'a> {
866 pub fn force_reencrypt(&self) -> bool {
867 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
868 *force_reencrypt
869 } else {
870 false
871 }
872 }
873}
874
Janis Danisevskiseed69842021-02-18 20:04:10 -0800875/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000876impl<'a> Deref for KeyBlob<'a> {
877 type Target = [u8];
878
879 fn deref(&self) -> &Self::Target {
880 match self {
Paul Crowley7a658392021-03-18 17:08:20 -0700881 Self::Sensitive { key, .. } => &key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000882 Self::NonSensitive(key) => &key,
883 Self::Ref(key) => key,
884 }
885 }
886}