blob: 655e0ced700016eab64c5678cfb2535c9a0f31b1 [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
15#![allow(dead_code)]
16
17use crate::{
Paul Crowley8d5b2532021-03-19 10:53:07 -070018 database::BlobMetaData,
19 database::BlobMetaEntry,
20 database::EncryptedBy,
21 database::KeyEntry,
22 database::KeyType,
23 database::{KeyMetaData, KeyMetaEntry, KeystoreDB},
24 ec_crypto::ECDHPrivateKey,
25 enforcements::Enforcements,
26 error::Error,
27 error::ResponseCode,
28 key_parameter::KeyParameter,
29 legacy_blob::LegacyBlobLoader,
30 legacy_migrator::LegacyMigrator,
31 try_insert::TryInsert,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080032};
33use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
34use anyhow::{Context, Result};
35use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070036 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
37 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080038};
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000039use std::ops::Deref;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080040use std::{
41 collections::HashMap,
42 sync::Arc,
43 sync::{Mutex, Weak},
44};
45
46type UserId = u32;
47
Paul Crowley8d5b2532021-03-19 10:53:07 -070048/// Encryption algorithm used by a particular type of superencryption key
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum SuperEncryptionAlgorithm {
51 /// Symmetric encryption with AES-256-GCM
52 Aes256Gcm,
53 /// Public-key encryption with ECDH P-256
54 EcdhP256,
55}
56
Paul Crowley7a658392021-03-18 17:08:20 -070057/// A particular user may have several superencryption keys in the database, each for a
58/// different purpose, distinguished by alias. Each is associated with a static
59/// constant of this type.
60pub struct SuperKeyType {
61 /// Alias used to look the key up in the `persistent.keyentry` table.
62 pub alias: &'static str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070063 /// Encryption algorithm
64 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070065}
66
67/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
68/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070069pub const USER_SUPER_KEY: SuperKeyType =
70 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070071/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
72/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070073/// Symmetric.
74pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
75 alias: "USER_SCREEN_LOCK_BOUND_KEY",
76 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
77};
78/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
79/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
80/// Asymmetric, so keys can be encrypted when the device is locked.
81pub const USER_SCREEN_LOCK_BOUND_ECDH_KEY: SuperKeyType = SuperKeyType {
82 alias: "USER_SCREEN_LOCK_BOUND_ECDH_KEY",
83 algorithm: SuperEncryptionAlgorithm::EcdhP256,
84};
Paul Crowley7a658392021-03-18 17:08:20 -070085
86/// Superencryption to apply to a new key.
87#[derive(Debug, Clone, Copy)]
88pub enum SuperEncryptionType {
89 /// Do not superencrypt this key.
90 None,
91 /// Superencrypt with a key that remains in memory from first unlock to reboot.
92 LskfBound,
93 /// Superencrypt with a key cleared from memory when the device is locked.
94 ScreenLockBound,
95}
96
Janis Danisevskisb42fc182020-12-15 08:41:27 -080097#[derive(Default)]
98struct UserSuperKeys {
99 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
100 /// key per android user. The key is stored on flash encrypted with a key derived from a
101 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
102 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
103 /// and stays memory resident until the device reboots.
Paul Crowley7a658392021-03-18 17:08:20 -0700104 per_boot: Option<Arc<SuperKey>>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800105 /// The screen lock key works like the per boot key with the distinction that it is cleared
106 /// from memory when the screen lock is engaged.
Paul Crowley7a658392021-03-18 17:08:20 -0700107 screen_lock_bound: Option<Arc<SuperKey>>,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700108 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
109 /// ECDH public-key encryption. This field holds the decryption private key.
110 screen_lock_bound_private: Option<Arc<SuperKey>>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800111}
112
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000113pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700114 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700115 key: ZVec,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000116 // id of the super key in the database.
117 id: i64,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700118 /// ECDH is more expensive than AES. So on ECDH private keys we set the
119 /// reencrypt_with field to point at the corresponding AES key, and the
120 /// keys will be re-encrypted with AES on first use.
121 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000122}
123
124impl SuperKey {
Paul Crowley7a658392021-03-18 17:08:20 -0700125 /// For most purposes `unwrap_key` handles decryption,
126 /// but legacy handling and some tests need to assume AES and decrypt directly.
127 pub fn aes_gcm_decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700128 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
129 aes_gcm_decrypt(data, iv, tag, &self.key)
130 .context("In aes_gcm_decrypt: decryption failed")
131 } else {
132 Err(Error::sys()).context("In aes_gcm_decrypt: Key is not an AES key")
133 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000134 }
135
136 pub fn get_id(&self) -> i64 {
137 self.id
138 }
139}
140
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800141#[derive(Default)]
142struct SkmState {
143 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700144 key_index: HashMap<i64, Weak<SuperKey>>,
145}
146
147impl SkmState {
148 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) {
149 self.key_index.insert(super_key.id, Arc::downgrade(super_key));
150 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800151}
152
153#[derive(Default)]
154pub struct SuperKeyManager {
155 data: Mutex<SkmState>,
156}
157
158impl SuperKeyManager {
159 pub fn new() -> Self {
Paul Crowley7a658392021-03-18 17:08:20 -0700160 Default::default()
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800161 }
162
163 pub fn forget_all_keys_for_user(&self, user: UserId) {
164 let mut data = self.data.lock().unwrap();
165 data.user_keys.remove(&user);
166 }
167
Paul Crowley7a658392021-03-18 17:08:20 -0700168 fn install_per_boot_key_for_user(&self, user: UserId, super_key: Arc<SuperKey>) {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800169 let mut data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700170 data.add_key_to_key_index(&super_key);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000171 data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800172 }
173
Paul Crowley7a658392021-03-18 17:08:20 -0700174 fn get_key(&self, key_id: &i64) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800175 self.data.lock().unwrap().key_index.get(key_id).and_then(|k| k.upgrade())
176 }
177
Paul Crowley7a658392021-03-18 17:08:20 -0700178 pub fn get_per_boot_key_by_user_id(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800179 let data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700180 data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800181 }
182
183 /// This function unlocks the super keys for a given user.
184 /// This means the key is loaded from the database, decrypted and placed in the
185 /// super key cache. If there is no such key a new key is created, encrypted with
186 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800187 pub fn unlock_user_key(
188 &self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000189 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800190 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700191 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800192 legacy_blob_loader: &LegacyBlobLoader,
193 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800194 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800195 .get_or_create_key_with(
196 Domain::APP,
197 user as u64 as i64,
Paul Crowley7a658392021-03-18 17:08:20 -0700198 &USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800199 crate::database::KEYSTORE_UUID,
200 || {
201 // For backward compatibility we need to check if there is a super key present.
202 let super_key = legacy_blob_loader
203 .load_super_key(user, pw)
204 .context("In create_new_key: Failed to load legacy key blob.")?;
205 let super_key = match super_key {
206 None => {
207 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000208 generate_aes256_key()
Max Bires8e93d2b2021-01-14 13:17:59 -0800209 .context("In create_new_key: Failed to generate AES 256 key.")?
210 }
211 Some(key) => key,
212 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000213 // Regardless of whether we loaded an old AES128 key or generated a new AES256
214 // key as the super key, we derive a AES256 key from the password and re-encrypt
215 // the super key before we insert it in the database. The length of the key is
216 // preserved by the encryption so we don't need any extra flags to inform us
217 // which algorithm to use it with.
218 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800219 },
220 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800221 .context("In unlock_user_key: Failed to get key id.")?;
222
Paul Crowley8d5b2532021-03-19 10:53:07 -0700223 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
224 .context("In unlock_user_key.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800225 Ok(())
226 }
227
228 /// Unwraps an encrypted key blob given metadata identifying the encryption key.
229 /// The function queries `metadata.encrypted_by()` to determine the encryption key.
230 /// It then check if the required key is memory resident, and if so decrypts the
231 /// blob.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000232 pub fn unwrap_key<'a>(&self, blob: &'a [u8], metadata: &BlobMetaData) -> Result<KeyBlob<'a>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800233 match metadata.encrypted_by() {
234 Some(EncryptedBy::KeyId(key_id)) => match self.get_key(key_id) {
Paul Crowley7a658392021-03-18 17:08:20 -0700235 Some(super_key) => Ok(KeyBlob::Sensitive {
236 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
237 .context("In unwrap_key: unwrap_key_with_key failed")?,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700238 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
239 force_reencrypt: super_key.reencrypt_with.is_some(),
Paul Crowley7a658392021-03-18 17:08:20 -0700240 }),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800241 None => Err(Error::Rc(ResponseCode::LOCKED))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700242 .context("In unwrap_key: Required super decryption key is not in memory."),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800243 },
244 _ => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
245 .context("In unwrap_key: Cannot determined wrapping key."),
246 }
247 }
248
249 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700250 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700251 match key.algorithm {
252 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
253 (Some(iv), Some(tag)) => key
254 .aes_gcm_decrypt(blob, iv, tag)
255 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
256 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
257 concat!(
258 "In unwrap_key_with_key: Key has incomplete metadata.",
259 "Present: iv: {}, aead_tag: {}."
260 ),
261 iv.is_some(),
262 tag.is_some(),
263 )),
264 },
265 SuperEncryptionAlgorithm::EcdhP256 => {
266 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
267 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
268 ECDHPrivateKey::from_private_key(&key.key)
269 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
270 .context(
271 "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.",
272 )
273 }
274 (public_key, salt, iv, aead_tag) => {
275 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
276 concat!(
277 "In unwrap_key_with_key: Key has incomplete metadata.",
278 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
279 ),
280 public_key.is_some(),
281 salt.is_some(),
282 iv.is_some(),
283 aead_tag.is_some(),
284 ))
285 }
286 }
287 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800288 }
289 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000290
291 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000292 pub fn super_key_exists_in_db_for_user(
293 db: &mut KeystoreDB,
294 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700295 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000296 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000297 let key_in_db = db
Paul Crowley7a658392021-03-18 17:08:20 -0700298 .key_exists(Domain::APP, user_id as u64 as i64, &USER_SUPER_KEY.alias, KeyType::Super)
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000299 .context("In super_key_exists_in_db_for_user.")?;
300
301 if key_in_db {
302 Ok(key_in_db)
303 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000304 legacy_migrator
305 .has_super_key(user_id)
306 .context("In super_key_exists_in_db_for_user: Trying to query legacy db.")
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000307 }
308 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000309
310 /// 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 +0000311 /// legacy database). If not, return Uninitialized state.
312 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
313 pub fn check_and_unlock_super_key(
314 &self,
315 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000316 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700317 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700318 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000319 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700320 let alias = &USER_SUPER_KEY;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000321 let result = legacy_migrator
Paul Crowley8d5b2532021-03-19 10:53:07 -0700322 .with_try_migrate_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000323 .context("In check_and_unlock_super_key. Failed to load super key")?;
324
325 match result {
326 Some((_, entry)) => {
327 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700328 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000329 .context("In check_and_unlock_super_key.")?;
330 Ok(UserState::LskfUnlocked(super_key))
331 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000332 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000333 }
334 }
335
336 /// 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 +0000337 /// legacy database). If so, return LskfLocked state.
338 /// If the password is provided, generate a new super key, encrypt with the password,
339 /// store in the database and populate the super key cache for the new user
340 /// and return LskfUnlocked state.
341 /// If the password is not provided, return Uninitialized state.
342 pub fn check_and_initialize_super_key(
343 &self,
344 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000345 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700346 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700347 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000348 ) -> Result<UserState> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000349 let super_key_exists_in_db =
350 Self::super_key_exists_in_db_for_user(db, legacy_migrator, user_id).context(
351 "In check_and_initialize_super_key. Failed to check if super key exists.",
352 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000353 if super_key_exists_in_db {
354 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000355 } else if let Some(pw) = pw {
356 //generate a new super key.
357 let super_key = generate_aes256_key()
358 .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?;
359 //derive an AES256 key from the password and re-encrypt the super key
360 //before we insert it in the database.
361 let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw)
362 .context("In check_and_initialize_super_key.")?;
363
364 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700365 .store_super_key(
366 user_id,
367 &USER_SUPER_KEY,
368 &encrypted_super_key,
369 &blob_metadata,
370 &KeyMetaData::new(),
371 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000372 .context("In check_and_initialize_super_key. Failed to store super key.")?;
373
374 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700375 .populate_cache_from_super_key_blob(
376 user_id,
377 USER_SUPER_KEY.algorithm,
378 key_entry,
379 pw,
380 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000381 .context("In check_and_initialize_super_key.")?;
382 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000383 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000384 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000385 }
386 }
387
388 //helper function to populate super key cache from the super key blob loaded from the database
389 fn populate_cache_from_super_key_blob(
390 &self,
Paul Crowley7a658392021-03-18 17:08:20 -0700391 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700392 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000393 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700394 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700395 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700396 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
397 .context(
398 "In populate_cache_from_super_key_blob. Failed to extract super key from key entry",
399 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000400 self.install_per_boot_key_for_user(user_id, super_key.clone());
401 Ok(super_key)
402 }
403
404 /// Extracts super key from the entry loaded from the database
Paul Crowley7a658392021-03-18 17:08:20 -0700405 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700406 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700407 entry: KeyEntry,
408 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700409 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700410 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000411 if let Some((blob, metadata)) = entry.key_blob_info() {
412 let key = match (
413 metadata.encrypted_by(),
414 metadata.salt(),
415 metadata.iv(),
416 metadata.aead_tag(),
417 ) {
418 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700419 // Note that password encryption is AES no matter the value of algorithm
Paul Crowleyf61fee72021-03-17 14:38:44 -0700420 let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context(
421 "In extract_super_key_from_key_entry: Failed to generate key from password.",
422 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000423
424 aes_gcm_decrypt(blob, iv, tag, &key).context(
425 "In extract_super_key_from_key_entry: Failed to decrypt key blob.",
426 )?
427 }
428 (enc_by, salt, iv, tag) => {
429 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
430 concat!(
431 "In extract_super_key_from_key_entry: Super key has incomplete metadata.",
432 "Present: encrypted_by: {}, salt: {}, iv: {}, aead_tag: {}."
433 ),
434 enc_by.is_some(),
435 salt.is_some(),
436 iv.is_some(),
437 tag.is_some()
438 ));
439 }
440 };
Paul Crowley8d5b2532021-03-19 10:53:07 -0700441 Ok(Arc::new(SuperKey { algorithm, key, id: entry.id(), reencrypt_with }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000442 } else {
443 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
444 .context("In extract_super_key_from_key_entry: No key blob info.")
445 }
446 }
447
448 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700449 pub fn encrypt_with_password(
450 super_key: &[u8],
451 pw: &Password,
452 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000453 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700454 let derived_key = pw
455 .derive_key(Some(&salt), AES_256_KEY_LENGTH)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000456 .context("In encrypt_with_password: Failed to derive password.")?;
457 let mut metadata = BlobMetaData::new();
458 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
459 metadata.add(BlobMetaEntry::Salt(salt));
460 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
461 .context("In encrypt_with_password: Failed to encrypt new super key.")?;
462 metadata.add(BlobMetaEntry::Iv(iv));
463 metadata.add(BlobMetaEntry::AeadTag(tag));
464 Ok((encrypted_key, metadata))
465 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000466
467 // Encrypt the given key blob with the user's super key, if the super key exists and the device
468 // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
469 // return error. Note that it is out of the scope of this function to check if super encryption
470 // is required. Such check should be performed before calling this function.
471 fn super_encrypt_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000472 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000473 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000474 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700475 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000476 key_blob: &[u8],
477 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000478 match UserState::get(db, legacy_migrator, self, user_id)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000479 .context("In super_encrypt. Failed to get user state.")?
480 {
481 UserState::LskfUnlocked(super_key) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700482 Self::encrypt_with_aes_super_key(key_blob, &super_key)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000483 .context("In super_encrypt_on_key_init. Failed to encrypt the key.")
484 }
485 UserState::LskfLocked => {
486 Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.")
487 }
488 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
489 .context("In super_encrypt. LSKF is not setup for the user."),
490 }
491 }
492
493 //Helper function to encrypt a key with the given super key. Callers should select which super
494 //key to be used. This is called when a key is super encrypted at its creation as well as at its
495 //upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700496 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000497 key_blob: &[u8],
498 super_key: &SuperKey,
499 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700500 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
501 return Err(Error::sys())
502 .context("In encrypt_with_aes_super_key: unexpected algorithm");
503 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000504 let mut metadata = BlobMetaData::new();
505 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700506 .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000507 metadata.add(BlobMetaEntry::Iv(iv));
508 metadata.add(BlobMetaEntry::AeadTag(tag));
509 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key.id)));
510 Ok((encrypted_key, metadata))
511 }
512
513 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
514 /// the database.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000515 #[allow(clippy::clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000516 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000517 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000518 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000519 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000520 domain: &Domain,
521 key_parameters: &[KeyParameter],
522 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700523 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000524 key_blob: &[u8],
525 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700526 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
527 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
528 SuperEncryptionType::LskfBound => {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000529 self.super_encrypt_on_key_init(db, legacy_migrator, user_id, &key_blob).context(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000530 "In handle_super_encryption_on_key_init.
531 Failed to super encrypt the key.",
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000532 )
533 }
Paul Crowley7a658392021-03-18 17:08:20 -0700534 SuperEncryptionType::ScreenLockBound => {
535 let mut data = self.data.lock().unwrap();
536 let entry = data.user_keys.entry(user_id).or_default();
537 if let Some(super_key) = entry.screen_lock_bound.as_ref() {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700538 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
Paul Crowley7a658392021-03-18 17:08:20 -0700539 "In handle_super_encryption_on_key_init. ",
540 "Failed to encrypt the key with screen_lock_bound key."
541 ))
542 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700543 // Symmetric key is not available, use public key encryption
544 let loaded =
545 db.load_super_key(&USER_SCREEN_LOCK_BOUND_ECDH_KEY, user_id).context(
546 "In handle_super_encryption_on_key_init: load_super_key failed.",
547 )?;
548 let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context(
549 "In handle_super_encryption_on_key_init: User ECDH key missing.",
550 )?;
551 let public_key =
552 key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context(
553 "In handle_super_encryption_on_key_init: sec1_public_key missing.",
554 )?;
555 let mut metadata = BlobMetaData::new();
556 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
557 ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!(
558 "In handle_super_encryption_on_key_init: ",
559 "ECDHPrivateKey::encrypt_message failed."
560 ))?;
561 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
562 metadata.add(BlobMetaEntry::Salt(salt));
563 metadata.add(BlobMetaEntry::Iv(iv));
564 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
565 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(key_id_guard.id())));
566 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700567 }
568 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000569 }
570 }
571
572 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
573 /// the relevant super key.
574 pub fn unwrap_key_if_required<'a>(
575 &self,
576 metadata: &BlobMetaData,
577 key_blob: &'a [u8],
578 ) -> Result<KeyBlob<'a>> {
579 if Self::key_super_encrypted(&metadata) {
580 let unwrapped_key = self
581 .unwrap_key(key_blob, metadata)
582 .context("In unwrap_key_if_required. Error in unwrapping the key.")?;
583 Ok(unwrapped_key)
584 } else {
585 Ok(KeyBlob::Ref(key_blob))
586 }
587 }
588
589 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
590 /// If so, re-super-encrypt the key and return a new set of metadata,
591 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700592 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000593 key_blob_before_upgrade: &KeyBlob,
594 key_after_upgrade: &'a [u8],
595 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
596 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700597 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700598 let (key, metadata) =
599 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
600 .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000601 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
602 }
603 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
604 }
605 }
606
607 // Helper function to decide if a key is super encrypted, given metadata.
608 fn key_super_encrypted(metadata: &BlobMetaData) -> bool {
609 if let Some(&EncryptedBy::KeyId(_)) = metadata.encrypted_by() {
610 return true;
611 }
612 false
613 }
Paul Crowley7a658392021-03-18 17:08:20 -0700614
615 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
616 /// When this is called, the caller must hold the lock on the SuperKeyManager.
617 /// So it's OK that the check and creation are different DB transactions.
618 fn get_or_create_super_key(
619 db: &mut KeystoreDB,
620 user_id: UserId,
621 key_type: &SuperKeyType,
622 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700623 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700624 ) -> Result<Arc<SuperKey>> {
625 let loaded_key = db.load_super_key(key_type, user_id)?;
626 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700627 Ok(Self::extract_super_key_from_key_entry(
628 key_type.algorithm,
629 key_entry,
630 password,
631 reencrypt_with,
632 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700633 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700634 let (super_key, public_key) = match key_type.algorithm {
635 SuperEncryptionAlgorithm::Aes256Gcm => (
636 generate_aes256_key()
637 .context("In get_or_create_super_key: Failed to generate AES 256 key.")?,
638 None,
639 ),
640 SuperEncryptionAlgorithm::EcdhP256 => {
641 let key = ECDHPrivateKey::generate()
642 .context("In get_or_create_super_key: Failed to generate ECDH key")?;
643 (
644 key.private_key()
645 .context("In get_or_create_super_key: private_key failed")?,
646 Some(
647 key.public_key()
648 .context("In get_or_create_super_key: public_key failed")?,
649 ),
650 )
651 }
652 };
Paul Crowley7a658392021-03-18 17:08:20 -0700653 //derive an AES256 key from the password and re-encrypt the super key
654 //before we insert it in the database.
655 let (encrypted_super_key, blob_metadata) =
656 Self::encrypt_with_password(&super_key, password)
657 .context("In get_or_create_super_key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700658 let mut key_metadata = KeyMetaData::new();
659 if let Some(pk) = public_key {
660 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
661 }
Paul Crowley7a658392021-03-18 17:08:20 -0700662 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700663 .store_super_key(
664 user_id,
665 key_type,
666 &encrypted_super_key,
667 &blob_metadata,
668 &key_metadata,
669 )
Paul Crowley7a658392021-03-18 17:08:20 -0700670 .context("In get_or_create_super_key. Failed to store super key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700671 Ok(Arc::new(SuperKey {
672 algorithm: key_type.algorithm,
673 key: super_key,
674 id: key_entry.id(),
675 reencrypt_with,
676 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700677 }
678 }
679
Paul Crowley8d5b2532021-03-19 10:53:07 -0700680 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700681 pub fn unlock_screen_lock_bound_key(
682 &self,
683 db: &mut KeystoreDB,
684 user_id: UserId,
685 password: &Password,
686 ) -> Result<()> {
687 let mut data = self.data.lock().unwrap();
688 let entry = data.user_keys.entry(user_id).or_default();
689 let aes = entry
690 .screen_lock_bound
691 .get_or_try_to_insert_with(|| {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700692 Self::get_or_create_super_key(
693 db,
694 user_id,
695 &USER_SCREEN_LOCK_BOUND_KEY,
696 password,
697 None,
698 )
699 })?
700 .clone();
701 let ecdh = entry
702 .screen_lock_bound_private
703 .get_or_try_to_insert_with(|| {
704 Self::get_or_create_super_key(
705 db,
706 user_id,
707 &USER_SCREEN_LOCK_BOUND_ECDH_KEY,
708 password,
709 Some(aes.clone()),
710 )
Paul Crowley7a658392021-03-18 17:08:20 -0700711 })?
712 .clone();
713 data.add_key_to_key_index(&aes);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700714 data.add_key_to_key_index(&ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700715 Ok(())
716 }
717
Paul Crowley8d5b2532021-03-19 10:53:07 -0700718 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700719 pub fn lock_screen_lock_bound_key(&self, user_id: UserId) {
720 let mut data = self.data.lock().unwrap();
721 let mut entry = data.user_keys.entry(user_id).or_default();
722 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700723 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700724 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000725}
726
727/// This enum represents different states of the user's life cycle in the device.
728/// For now, only three states are defined. More states may be added later.
729pub enum UserState {
730 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
731 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -0700732 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000733 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
734 // Hence the per-boot super-key(s) is not available in the cache.
735 // However, the encrypted super key is available in the database.
736 LskfLocked,
737 // There's no user in the device for the given user id, or the user with the user id has not
738 // setup LSKF.
739 Uninitialized,
740}
741
742impl UserState {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000743 pub fn get(
744 db: &mut KeystoreDB,
745 legacy_migrator: &LegacyMigrator,
746 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700747 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000748 ) -> Result<UserState> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000749 match skm.get_per_boot_key_by_user_id(user_id) {
750 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
751 None => {
752 //Check if a super key exists in the database or legacy database.
753 //If so, return locked user state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000754 if SuperKeyManager::super_key_exists_in_db_for_user(db, legacy_migrator, user_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000755 .context("In get.")?
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000756 {
757 Ok(UserState::LskfLocked)
758 } else {
759 Ok(UserState::Uninitialized)
760 }
761 }
762 }
763 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000764
765 /// Queries user state when serving password change requests.
766 pub fn get_with_password_changed(
767 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000768 legacy_migrator: &LegacyMigrator,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000769 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700770 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700771 password: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000772 ) -> Result<UserState> {
773 match skm.get_per_boot_key_by_user_id(user_id) {
774 Some(super_key) => {
775 if password.is_none() {
776 //transitioning to swiping, delete only the super key in database and cache, and
777 //super-encrypted keys in database (and in KM)
Janis Danisevskiseed69842021-02-18 20:04:10 -0800778 Self::reset_user(db, skm, legacy_migrator, user_id, true).context(
779 "In get_with_password_changed: Trying to delete keys from the db.",
780 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000781 //Lskf is now removed in Keystore
782 Ok(UserState::Uninitialized)
783 } else {
784 //Keystore won't be notified when changing to a new password when LSKF is
785 //already setup. Therefore, ideally this path wouldn't be reached.
786 Ok(UserState::LskfUnlocked(super_key))
787 }
788 }
789 None => {
790 //Check if a super key exists in the database or legacy database.
791 //If so, return LskfLocked state.
792 //Otherwise, i) if the password is provided, initialize the super key and return
793 //LskfUnlocked state ii) if password is not provided, return Uninitialized state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000794 skm.check_and_initialize_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000795 }
796 }
797 }
798
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000799 /// Queries user state when serving password unlock requests.
800 pub fn get_with_password_unlock(
801 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000802 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000803 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700804 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700805 password: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000806 ) -> Result<UserState> {
807 match skm.get_per_boot_key_by_user_id(user_id) {
808 Some(super_key) => {
809 log::info!("In get_with_password_unlock. Trying to unlock when already unlocked.");
810 Ok(UserState::LskfUnlocked(super_key))
811 }
812 None => {
813 //Check if a super key exists in the database or legacy database.
814 //If not, return Uninitialized state.
815 //Otherwise, try to unlock the super key and if successful,
816 //return LskfUnlocked state
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000817 skm.check_and_unlock_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000818 .context("In get_with_password_unlock. Failed to unlock super key.")
819 }
820 }
821 }
822
Hasini Gunasingheda895552021-01-27 19:34:37 +0000823 /// Delete all the keys created on behalf of the user.
824 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
825 /// encrypted keys.
826 pub fn reset_user(
827 db: &mut KeystoreDB,
828 skm: &SuperKeyManager,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800829 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700830 user_id: UserId,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000831 keep_non_super_encrypted_keys: bool,
832 ) -> Result<()> {
833 // mark keys created on behalf of the user as unreferenced.
Janis Danisevskiseed69842021-02-18 20:04:10 -0800834 legacy_migrator
835 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
836 .context("In reset_user: Trying to delete legacy keys.")?;
Paul Crowley7a658392021-03-18 17:08:20 -0700837 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000838 .context("In reset user. Error in unbinding keys.")?;
839
840 //delete super key in cache, if exists
Paul Crowley7a658392021-03-18 17:08:20 -0700841 skm.forget_all_keys_for_user(user_id);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000842 Ok(())
843 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800844}
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000845
Janis Danisevskiseed69842021-02-18 20:04:10 -0800846/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
847/// `Sensitive` holds the non encrypted key and a reference to its super key.
848/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
849/// `Ref` holds a reference to a key blob when it does not need to be modified if its
850/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000851pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700852 Sensitive {
853 key: ZVec,
854 /// If KeyMint reports that the key must be upgraded, we must
855 /// re-encrypt the key before writing to the database; we use
856 /// this key.
857 reencrypt_with: Arc<SuperKey>,
858 /// If this key was decrypted with an ECDH key, we want to
859 /// re-encrypt it on first use whether it was upgraded or not;
860 /// this field indicates that that's necessary.
861 force_reencrypt: bool,
862 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000863 NonSensitive(Vec<u8>),
864 Ref(&'a [u8]),
865}
866
Paul Crowley8d5b2532021-03-19 10:53:07 -0700867impl<'a> KeyBlob<'a> {
868 pub fn force_reencrypt(&self) -> bool {
869 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
870 *force_reencrypt
871 } else {
872 false
873 }
874 }
875}
876
Janis Danisevskiseed69842021-02-18 20:04:10 -0800877/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000878impl<'a> Deref for KeyBlob<'a> {
879 type Target = [u8];
880
881 fn deref(&self) -> &Self::Target {
882 match self {
Paul Crowley7a658392021-03-18 17:08:20 -0700883 Self::Sensitive { key, .. } => &key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000884 Self::NonSensitive(key) => &key,
885 Self::Ref(key) => key,
886 }
887 }
888}