Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1 | // 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 | |
| 17 | use crate::{ |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 18 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 32 | }; |
| 33 | use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain; |
| 34 | use anyhow::{Context, Result}; |
| 35 | use keystore2_crypto::{ |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 36 | aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec, |
| 37 | AES_256_KEY_LENGTH, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 38 | }; |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 39 | use std::ops::Deref; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 40 | use std::{ |
| 41 | collections::HashMap, |
| 42 | sync::Arc, |
| 43 | sync::{Mutex, Weak}, |
| 44 | }; |
| 45 | |
| 46 | type UserId = u32; |
| 47 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 48 | /// Encryption algorithm used by a particular type of superencryption key |
| 49 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 50 | pub enum SuperEncryptionAlgorithm { |
| 51 | /// Symmetric encryption with AES-256-GCM |
| 52 | Aes256Gcm, |
| 53 | /// Public-key encryption with ECDH P-256 |
| 54 | EcdhP256, |
| 55 | } |
| 56 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 57 | /// 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. |
| 60 | pub struct SuperKeyType { |
| 61 | /// Alias used to look the key up in the `persistent.keyentry` table. |
| 62 | pub alias: &'static str, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 63 | /// Encryption algorithm |
| 64 | pub algorithm: SuperEncryptionAlgorithm, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 65 | } |
| 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 69 | pub const USER_SUPER_KEY: SuperKeyType = |
| 70 | SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm }; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 71 | /// 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 73 | /// Symmetric. |
| 74 | pub 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. |
| 81 | pub const USER_SCREEN_LOCK_BOUND_ECDH_KEY: SuperKeyType = SuperKeyType { |
| 82 | alias: "USER_SCREEN_LOCK_BOUND_ECDH_KEY", |
| 83 | algorithm: SuperEncryptionAlgorithm::EcdhP256, |
| 84 | }; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 85 | |
| 86 | /// Superencryption to apply to a new key. |
| 87 | #[derive(Debug, Clone, Copy)] |
| 88 | pub 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 97 | #[derive(Default)] |
| 98 | struct 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 104 | per_boot: Option<Arc<SuperKey>>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 105 | /// 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 107 | screen_lock_bound: Option<Arc<SuperKey>>, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 108 | /// 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 111 | } |
| 112 | |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 113 | pub struct SuperKey { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 114 | algorithm: SuperEncryptionAlgorithm, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 115 | key: ZVec, |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 116 | // id of the super key in the database. |
| 117 | id: i64, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 118 | /// 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 Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 122 | } |
| 123 | |
| 124 | impl SuperKey { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 125 | /// 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 128 | 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 Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 134 | } |
| 135 | |
| 136 | pub fn get_id(&self) -> i64 { |
| 137 | self.id |
| 138 | } |
| 139 | } |
| 140 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 141 | #[derive(Default)] |
| 142 | struct SkmState { |
| 143 | user_keys: HashMap<UserId, UserSuperKeys>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 144 | key_index: HashMap<i64, Weak<SuperKey>>, |
| 145 | } |
| 146 | |
| 147 | impl 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 151 | } |
| 152 | |
| 153 | #[derive(Default)] |
| 154 | pub struct SuperKeyManager { |
| 155 | data: Mutex<SkmState>, |
| 156 | } |
| 157 | |
| 158 | impl SuperKeyManager { |
| 159 | pub fn new() -> Self { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 160 | Default::default() |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 161 | } |
| 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 168 | fn install_per_boot_key_for_user(&self, user: UserId, super_key: Arc<SuperKey>) { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 169 | let mut data = self.data.lock().unwrap(); |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 170 | data.add_key_to_key_index(&super_key); |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 171 | data.user_keys.entry(user).or_default().per_boot = Some(super_key); |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 172 | } |
| 173 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 174 | fn get_key(&self, key_id: &i64) -> Option<Arc<SuperKey>> { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 175 | self.data.lock().unwrap().key_index.get(key_id).and_then(|k| k.upgrade()) |
| 176 | } |
| 177 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 178 | pub fn get_per_boot_key_by_user_id(&self, user_id: UserId) -> Option<Arc<SuperKey>> { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 179 | let data = self.data.lock().unwrap(); |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 180 | data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned()) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 181 | } |
| 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 Danisevskis | a51ccbc | 2020-11-25 21:04:24 -0800 | [diff] [blame] | 187 | pub fn unlock_user_key( |
| 188 | &self, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 189 | db: &mut KeystoreDB, |
Janis Danisevskis | a51ccbc | 2020-11-25 21:04:24 -0800 | [diff] [blame] | 190 | user: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 191 | pw: &Password, |
Janis Danisevskis | a51ccbc | 2020-11-25 21:04:24 -0800 | [diff] [blame] | 192 | legacy_blob_loader: &LegacyBlobLoader, |
| 193 | ) -> Result<()> { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 194 | let (_, entry) = db |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 195 | .get_or_create_key_with( |
| 196 | Domain::APP, |
| 197 | user as u64 as i64, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 198 | &USER_SUPER_KEY.alias, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 199 | 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 Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 208 | generate_aes256_key() |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 209 | .context("In create_new_key: Failed to generate AES 256 key.")? |
| 210 | } |
| 211 | Some(key) => key, |
| 212 | }; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 213 | // 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 219 | }, |
| 220 | ) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 221 | .context("In unlock_user_key: Failed to get key id.")?; |
| 222 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 223 | self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw) |
| 224 | .context("In unlock_user_key.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 225 | 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 Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 232 | pub fn unwrap_key<'a>(&self, blob: &'a [u8], metadata: &BlobMetaData) -> Result<KeyBlob<'a>> { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 233 | match metadata.encrypted_by() { |
| 234 | Some(EncryptedBy::KeyId(key_id)) => match self.get_key(key_id) { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 235 | 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 238 | reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(), |
| 239 | force_reencrypt: super_key.reencrypt_with.is_some(), |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 240 | }), |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 241 | None => Err(Error::Rc(ResponseCode::LOCKED)) |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 242 | .context("In unwrap_key: Required super decryption key is not in memory."), |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 243 | }, |
| 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 250 | fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 251 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 288 | } |
| 289 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 290 | |
| 291 | /// Checks if user has setup LSKF, even when super key cache is empty for the user. |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 292 | pub fn super_key_exists_in_db_for_user( |
| 293 | db: &mut KeystoreDB, |
| 294 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 295 | user_id: UserId, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 296 | ) -> Result<bool> { |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 297 | let key_in_db = db |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 298 | .key_exists(Domain::APP, user_id as u64 as i64, &USER_SUPER_KEY.alias, KeyType::Super) |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 299 | .context("In super_key_exists_in_db_for_user.")?; |
| 300 | |
| 301 | if key_in_db { |
| 302 | Ok(key_in_db) |
| 303 | } else { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 304 | legacy_migrator |
| 305 | .has_super_key(user_id) |
| 306 | .context("In super_key_exists_in_db_for_user: Trying to query legacy db.") |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 307 | } |
| 308 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 309 | |
| 310 | /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 311 | /// 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 Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 316 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 317 | user_id: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 318 | pw: &Password, |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 319 | ) -> Result<UserState> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 320 | let alias = &USER_SUPER_KEY; |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 321 | let result = legacy_migrator |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 322 | .with_try_migrate_super_key(user_id, pw, || db.load_super_key(alias, user_id)) |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 323 | .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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 328 | .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw) |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 329 | .context("In check_and_unlock_super_key.")?; |
| 330 | Ok(UserState::LskfUnlocked(super_key)) |
| 331 | } |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 332 | None => Ok(UserState::Uninitialized), |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 333 | } |
| 334 | } |
| 335 | |
| 336 | /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 337 | /// 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 Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 345 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 346 | user_id: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 347 | pw: Option<&Password>, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 348 | ) -> Result<UserState> { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 349 | 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 Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 353 | if super_key_exists_in_db { |
| 354 | Ok(UserState::LskfLocked) |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 355 | } 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 365 | .store_super_key( |
| 366 | user_id, |
| 367 | &USER_SUPER_KEY, |
| 368 | &encrypted_super_key, |
| 369 | &blob_metadata, |
| 370 | &KeyMetaData::new(), |
| 371 | ) |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 372 | .context("In check_and_initialize_super_key. Failed to store super key.")?; |
| 373 | |
| 374 | let super_key = self |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 375 | .populate_cache_from_super_key_blob( |
| 376 | user_id, |
| 377 | USER_SUPER_KEY.algorithm, |
| 378 | key_entry, |
| 379 | pw, |
| 380 | ) |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 381 | .context("In check_and_initialize_super_key.")?; |
| 382 | Ok(UserState::LskfUnlocked(super_key)) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 383 | } else { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 384 | Ok(UserState::Uninitialized) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 385 | } |
| 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 391 | user_id: UserId, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 392 | algorithm: SuperEncryptionAlgorithm, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 393 | entry: KeyEntry, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 394 | pw: &Password, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 395 | ) -> Result<Arc<SuperKey>> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 396 | 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 Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 400 | 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 405 | pub fn extract_super_key_from_key_entry( |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 406 | algorithm: SuperEncryptionAlgorithm, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 407 | entry: KeyEntry, |
| 408 | pw: &Password, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 409 | reencrypt_with: Option<Arc<SuperKey>>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 410 | ) -> Result<Arc<SuperKey>> { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 411 | 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 419 | // Note that password encryption is AES no matter the value of algorithm |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 420 | 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 Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 423 | |
| 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 441 | Ok(Arc::new(SuperKey { algorithm, key, id: entry.id(), reencrypt_with })) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 442 | } 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 Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 449 | pub fn encrypt_with_password( |
| 450 | super_key: &[u8], |
| 451 | pw: &Password, |
| 452 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 453 | let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?; |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 454 | let derived_key = pw |
| 455 | .derive_key(Some(&salt), AES_256_KEY_LENGTH) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 456 | .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 Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 466 | |
| 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 Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 472 | &self, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 473 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 474 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 475 | user_id: UserId, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 476 | key_blob: &[u8], |
| 477 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 478 | match UserState::get(db, legacy_migrator, self, user_id) |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 479 | .context("In super_encrypt. Failed to get user state.")? |
| 480 | { |
| 481 | UserState::LskfUnlocked(super_key) => { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 482 | Self::encrypt_with_aes_super_key(key_blob, &super_key) |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 483 | .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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 496 | fn encrypt_with_aes_super_key( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 497 | key_blob: &[u8], |
| 498 | super_key: &SuperKey, |
| 499 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 500 | if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm { |
| 501 | return Err(Error::sys()) |
| 502 | .context("In encrypt_with_aes_super_key: unexpected algorithm"); |
| 503 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 504 | let mut metadata = BlobMetaData::new(); |
| 505 | let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key)) |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 506 | .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?; |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 507 | 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 Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 515 | #[allow(clippy::clippy::too_many_arguments)] |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 516 | pub fn handle_super_encryption_on_key_init( |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 517 | &self, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 518 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 519 | legacy_migrator: &LegacyMigrator, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 520 | domain: &Domain, |
| 521 | key_parameters: &[KeyParameter], |
| 522 | flags: Option<i32>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 523 | user_id: UserId, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 524 | key_blob: &[u8], |
| 525 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 526 | match Enforcements::super_encryption_required(domain, key_parameters, flags) { |
| 527 | SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())), |
| 528 | SuperEncryptionType::LskfBound => { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 529 | self.super_encrypt_on_key_init(db, legacy_migrator, user_id, &key_blob).context( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 530 | "In handle_super_encryption_on_key_init. |
| 531 | Failed to super encrypt the key.", |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 532 | ) |
| 533 | } |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 534 | 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 538 | Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!( |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 539 | "In handle_super_encryption_on_key_init. ", |
| 540 | "Failed to encrypt the key with screen_lock_bound key." |
| 541 | )) |
| 542 | } else { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 543 | // 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 567 | } |
| 568 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 569 | } |
| 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 592 | pub fn reencrypt_if_required<'a>( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 593 | key_blob_before_upgrade: &KeyBlob, |
| 594 | key_after_upgrade: &'a [u8], |
| 595 | ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> { |
| 596 | match key_blob_before_upgrade { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 597 | KeyBlob::Sensitive { reencrypt_with: super_key, .. } => { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 598 | 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 Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 601 | 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 614 | |
| 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 623 | reencrypt_with: Option<Arc<SuperKey>>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 624 | ) -> Result<Arc<SuperKey>> { |
| 625 | let loaded_key = db.load_super_key(key_type, user_id)?; |
| 626 | if let Some((_, key_entry)) = loaded_key { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 627 | Ok(Self::extract_super_key_from_key_entry( |
| 628 | key_type.algorithm, |
| 629 | key_entry, |
| 630 | password, |
| 631 | reencrypt_with, |
| 632 | )?) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 633 | } else { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 634 | 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 653 | //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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 658 | let mut key_metadata = KeyMetaData::new(); |
| 659 | if let Some(pk) = public_key { |
| 660 | key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk)); |
| 661 | } |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 662 | let key_entry = db |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 663 | .store_super_key( |
| 664 | user_id, |
| 665 | key_type, |
| 666 | &encrypted_super_key, |
| 667 | &blob_metadata, |
| 668 | &key_metadata, |
| 669 | ) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 670 | .context("In get_or_create_super_key. Failed to store super key.")?; |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 671 | Ok(Arc::new(SuperKey { |
| 672 | algorithm: key_type.algorithm, |
| 673 | key: super_key, |
| 674 | id: key_entry.id(), |
| 675 | reencrypt_with, |
| 676 | })) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 677 | } |
| 678 | } |
| 679 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 680 | /// Decrypt the screen-lock bound keys for this user using the password and store in memory. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 681 | 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 692 | 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 711 | })? |
| 712 | .clone(); |
| 713 | data.add_key_to_key_index(&aes); |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 714 | data.add_key_to_key_index(&ecdh); |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 715 | Ok(()) |
| 716 | } |
| 717 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 718 | /// Wipe the screen-lock bound keys for this user from memory. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 719 | 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 Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 723 | entry.screen_lock_bound_private = None; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 724 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 725 | } |
| 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. |
| 729 | pub 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 Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 732 | LskfUnlocked(Arc<SuperKey>), |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 733 | // 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 | |
| 742 | impl UserState { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 743 | pub fn get( |
| 744 | db: &mut KeystoreDB, |
| 745 | legacy_migrator: &LegacyMigrator, |
| 746 | skm: &SuperKeyManager, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 747 | user_id: UserId, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 748 | ) -> Result<UserState> { |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 749 | 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 Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 754 | if SuperKeyManager::super_key_exists_in_db_for_user(db, legacy_migrator, user_id) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 755 | .context("In get.")? |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 756 | { |
| 757 | Ok(UserState::LskfLocked) |
| 758 | } else { |
| 759 | Ok(UserState::Uninitialized) |
| 760 | } |
| 761 | } |
| 762 | } |
| 763 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 764 | |
| 765 | /// Queries user state when serving password change requests. |
| 766 | pub fn get_with_password_changed( |
| 767 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 768 | legacy_migrator: &LegacyMigrator, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 769 | skm: &SuperKeyManager, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 770 | user_id: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 771 | password: Option<&Password>, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 772 | ) -> 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 Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 778 | 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 Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 781 | //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 Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 794 | skm.check_and_initialize_super_key(db, legacy_migrator, user_id, password) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 795 | } |
| 796 | } |
| 797 | } |
| 798 | |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 799 | /// Queries user state when serving password unlock requests. |
| 800 | pub fn get_with_password_unlock( |
| 801 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 802 | legacy_migrator: &LegacyMigrator, |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 803 | skm: &SuperKeyManager, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 804 | user_id: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 805 | password: &Password, |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 806 | ) -> 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 Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 817 | skm.check_and_unlock_super_key(db, legacy_migrator, user_id, password) |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 818 | .context("In get_with_password_unlock. Failed to unlock super key.") |
| 819 | } |
| 820 | } |
| 821 | } |
| 822 | |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 823 | /// 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 Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 829 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 830 | user_id: UserId, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 831 | keep_non_super_encrypted_keys: bool, |
| 832 | ) -> Result<()> { |
| 833 | // mark keys created on behalf of the user as unreferenced. |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 834 | legacy_migrator |
| 835 | .bulk_delete_user(user_id, keep_non_super_encrypted_keys) |
| 836 | .context("In reset_user: Trying to delete legacy keys.")?; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 837 | db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 838 | .context("In reset user. Error in unbinding keys.")?; |
| 839 | |
| 840 | //delete super key in cache, if exists |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 841 | skm.forget_all_keys_for_user(user_id); |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 842 | Ok(()) |
| 843 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 844 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 845 | |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 846 | /// 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 Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 851 | pub enum KeyBlob<'a> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 852 | 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 Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 863 | NonSensitive(Vec<u8>), |
| 864 | Ref(&'a [u8]), |
| 865 | } |
| 866 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame^] | 867 | impl<'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 Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 877 | /// Deref returns a reference to the key material in any variant. |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 878 | impl<'a> Deref for KeyBlob<'a> { |
| 879 | type Target = [u8]; |
| 880 | |
| 881 | fn deref(&self) -> &Self::Target { |
| 882 | match self { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 883 | Self::Sensitive { key, .. } => &key, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 884 | Self::NonSensitive(key) => &key, |
| 885 | Self::Ref(key) => key, |
| 886 | } |
| 887 | } |
| 888 | } |