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 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 15 | use crate::{ |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 16 | database::BlobMetaData, |
| 17 | database::BlobMetaEntry, |
| 18 | database::EncryptedBy, |
| 19 | database::KeyEntry, |
| 20 | database::KeyType, |
| 21 | database::{KeyMetaData, KeyMetaEntry, KeystoreDB}, |
| 22 | ec_crypto::ECDHPrivateKey, |
| 23 | enforcements::Enforcements, |
| 24 | error::Error, |
| 25 | error::ResponseCode, |
| 26 | key_parameter::KeyParameter, |
| 27 | legacy_blob::LegacyBlobLoader, |
| 28 | legacy_migrator::LegacyMigrator, |
| 29 | try_insert::TryInsert, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 30 | }; |
| 31 | use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain; |
| 32 | use anyhow::{Context, Result}; |
| 33 | use keystore2_crypto::{ |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 34 | aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec, |
| 35 | AES_256_KEY_LENGTH, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 36 | }; |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 37 | use std::ops::Deref; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 38 | use std::{ |
| 39 | collections::HashMap, |
| 40 | sync::Arc, |
| 41 | sync::{Mutex, Weak}, |
| 42 | }; |
| 43 | |
| 44 | type UserId = u32; |
| 45 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 46 | /// Encryption algorithm used by a particular type of superencryption key |
| 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 48 | pub enum SuperEncryptionAlgorithm { |
| 49 | /// Symmetric encryption with AES-256-GCM |
| 50 | Aes256Gcm, |
| 51 | /// Public-key encryption with ECDH P-256 |
| 52 | EcdhP256, |
| 53 | } |
| 54 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 55 | /// A particular user may have several superencryption keys in the database, each for a |
| 56 | /// different purpose, distinguished by alias. Each is associated with a static |
| 57 | /// constant of this type. |
| 58 | pub struct SuperKeyType { |
| 59 | /// Alias used to look the key up in the `persistent.keyentry` table. |
| 60 | pub alias: &'static str, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 61 | /// Encryption algorithm |
| 62 | pub algorithm: SuperEncryptionAlgorithm, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 63 | } |
| 64 | |
| 65 | /// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory |
| 66 | /// when the user first unlocks, and remains in memory until the device reboots. |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 67 | pub const USER_SUPER_KEY: SuperKeyType = |
| 68 | SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm }; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 69 | /// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory |
| 70 | /// each time the user enters their LSKF, and cleared from memory each time the device is locked. |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 71 | /// Symmetric. |
| 72 | pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType { |
| 73 | alias: "USER_SCREEN_LOCK_BOUND_KEY", |
| 74 | algorithm: SuperEncryptionAlgorithm::Aes256Gcm, |
| 75 | }; |
| 76 | /// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory |
| 77 | /// each time the user enters their LSKF, and cleared from memory each time the device is locked. |
| 78 | /// Asymmetric, so keys can be encrypted when the device is locked. |
| 79 | pub const USER_SCREEN_LOCK_BOUND_ECDH_KEY: SuperKeyType = SuperKeyType { |
| 80 | alias: "USER_SCREEN_LOCK_BOUND_ECDH_KEY", |
| 81 | algorithm: SuperEncryptionAlgorithm::EcdhP256, |
| 82 | }; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 83 | |
| 84 | /// Superencryption to apply to a new key. |
| 85 | #[derive(Debug, Clone, Copy)] |
| 86 | pub enum SuperEncryptionType { |
| 87 | /// Do not superencrypt this key. |
| 88 | None, |
| 89 | /// Superencrypt with a key that remains in memory from first unlock to reboot. |
| 90 | LskfBound, |
| 91 | /// Superencrypt with a key cleared from memory when the device is locked. |
| 92 | ScreenLockBound, |
| 93 | } |
| 94 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 95 | #[derive(Default)] |
| 96 | struct UserSuperKeys { |
| 97 | /// The per boot key is used for LSKF binding of authentication bound keys. There is one |
| 98 | /// key per android user. The key is stored on flash encrypted with a key derived from a |
| 99 | /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF). |
| 100 | /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted, |
| 101 | /// and stays memory resident until the device reboots. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 102 | per_boot: Option<Arc<SuperKey>>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 103 | /// The screen lock key works like the per boot key with the distinction that it is cleared |
| 104 | /// from memory when the screen lock is engaged. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 105 | screen_lock_bound: Option<Arc<SuperKey>>, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 106 | /// When the device is locked, screen-lock-bound keys can still be encrypted, using |
| 107 | /// ECDH public-key encryption. This field holds the decryption private key. |
| 108 | screen_lock_bound_private: Option<Arc<SuperKey>>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 109 | } |
| 110 | |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 111 | pub struct SuperKey { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 112 | algorithm: SuperEncryptionAlgorithm, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 113 | key: ZVec, |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 114 | // id of the super key in the database. |
| 115 | id: i64, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 116 | /// ECDH is more expensive than AES. So on ECDH private keys we set the |
| 117 | /// reencrypt_with field to point at the corresponding AES key, and the |
| 118 | /// keys will be re-encrypted with AES on first use. |
| 119 | reencrypt_with: Option<Arc<SuperKey>>, |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 120 | } |
| 121 | |
| 122 | impl SuperKey { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 123 | /// For most purposes `unwrap_key` handles decryption, |
| 124 | /// but legacy handling and some tests need to assume AES and decrypt directly. |
| 125 | pub fn aes_gcm_decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 126 | if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm { |
| 127 | aes_gcm_decrypt(data, iv, tag, &self.key) |
| 128 | .context("In aes_gcm_decrypt: decryption failed") |
| 129 | } else { |
| 130 | Err(Error::sys()).context("In aes_gcm_decrypt: Key is not an AES key") |
| 131 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 132 | } |
| 133 | |
| 134 | pub fn get_id(&self) -> i64 { |
| 135 | self.id |
| 136 | } |
| 137 | } |
| 138 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 139 | #[derive(Default)] |
| 140 | struct SkmState { |
| 141 | user_keys: HashMap<UserId, UserSuperKeys>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 142 | key_index: HashMap<i64, Weak<SuperKey>>, |
| 143 | } |
| 144 | |
| 145 | impl SkmState { |
| 146 | fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) { |
| 147 | self.key_index.insert(super_key.id, Arc::downgrade(super_key)); |
| 148 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 149 | } |
| 150 | |
| 151 | #[derive(Default)] |
| 152 | pub struct SuperKeyManager { |
| 153 | data: Mutex<SkmState>, |
| 154 | } |
| 155 | |
| 156 | impl SuperKeyManager { |
| 157 | pub fn new() -> Self { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 158 | Default::default() |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 159 | } |
| 160 | |
| 161 | pub fn forget_all_keys_for_user(&self, user: UserId) { |
| 162 | let mut data = self.data.lock().unwrap(); |
| 163 | data.user_keys.remove(&user); |
| 164 | } |
| 165 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 166 | 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] | 167 | let mut data = self.data.lock().unwrap(); |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 168 | data.add_key_to_key_index(&super_key); |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 169 | data.user_keys.entry(user).or_default().per_boot = Some(super_key); |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 170 | } |
| 171 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 172 | fn get_key(&self, key_id: &i64) -> Option<Arc<SuperKey>> { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 173 | self.data.lock().unwrap().key_index.get(key_id).and_then(|k| k.upgrade()) |
| 174 | } |
| 175 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 176 | 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] | 177 | let data = self.data.lock().unwrap(); |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 178 | 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] | 179 | } |
| 180 | |
| 181 | /// This function unlocks the super keys for a given user. |
| 182 | /// This means the key is loaded from the database, decrypted and placed in the |
| 183 | /// super key cache. If there is no such key a new key is created, encrypted with |
| 184 | /// a key derived from the given password and stored in the database. |
Janis Danisevskis | a51ccbc | 2020-11-25 21:04:24 -0800 | [diff] [blame] | 185 | pub fn unlock_user_key( |
| 186 | &self, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 187 | db: &mut KeystoreDB, |
Janis Danisevskis | a51ccbc | 2020-11-25 21:04:24 -0800 | [diff] [blame] | 188 | user: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 189 | pw: &Password, |
Janis Danisevskis | a51ccbc | 2020-11-25 21:04:24 -0800 | [diff] [blame] | 190 | legacy_blob_loader: &LegacyBlobLoader, |
| 191 | ) -> Result<()> { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 192 | let (_, entry) = db |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 193 | .get_or_create_key_with( |
| 194 | Domain::APP, |
| 195 | user as u64 as i64, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 196 | &USER_SUPER_KEY.alias, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 197 | crate::database::KEYSTORE_UUID, |
| 198 | || { |
| 199 | // For backward compatibility we need to check if there is a super key present. |
| 200 | let super_key = legacy_blob_loader |
| 201 | .load_super_key(user, pw) |
| 202 | .context("In create_new_key: Failed to load legacy key blob.")?; |
| 203 | let super_key = match super_key { |
| 204 | None => { |
| 205 | // No legacy file was found. So we generate a new key. |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 206 | generate_aes256_key() |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 207 | .context("In create_new_key: Failed to generate AES 256 key.")? |
| 208 | } |
| 209 | Some(key) => key, |
| 210 | }; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 211 | // Regardless of whether we loaded an old AES128 key or generated a new AES256 |
| 212 | // key as the super key, we derive a AES256 key from the password and re-encrypt |
| 213 | // the super key before we insert it in the database. The length of the key is |
| 214 | // preserved by the encryption so we don't need any extra flags to inform us |
| 215 | // which algorithm to use it with. |
| 216 | Self::encrypt_with_password(&super_key, pw).context("In create_new_key.") |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 217 | }, |
| 218 | ) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 219 | .context("In unlock_user_key: Failed to get key id.")?; |
| 220 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 221 | self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw) |
| 222 | .context("In unlock_user_key.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 223 | Ok(()) |
| 224 | } |
| 225 | |
| 226 | /// Unwraps an encrypted key blob given metadata identifying the encryption key. |
| 227 | /// The function queries `metadata.encrypted_by()` to determine the encryption key. |
| 228 | /// It then check if the required key is memory resident, and if so decrypts the |
| 229 | /// blob. |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 230 | 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] | 231 | match metadata.encrypted_by() { |
| 232 | Some(EncryptedBy::KeyId(key_id)) => match self.get_key(key_id) { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 233 | Some(super_key) => Ok(KeyBlob::Sensitive { |
| 234 | key: Self::unwrap_key_with_key(blob, metadata, &super_key) |
| 235 | .context("In unwrap_key: unwrap_key_with_key failed")?, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 236 | reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(), |
| 237 | force_reencrypt: super_key.reencrypt_with.is_some(), |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 238 | }), |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 239 | None => Err(Error::Rc(ResponseCode::LOCKED)) |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 240 | .context("In unwrap_key: Required super decryption key is not in memory."), |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 241 | }, |
| 242 | _ => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)) |
| 243 | .context("In unwrap_key: Cannot determined wrapping key."), |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | /// Unwraps an encrypted key blob given an encryption key. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 248 | 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] | 249 | match key.algorithm { |
| 250 | SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) { |
| 251 | (Some(iv), Some(tag)) => key |
| 252 | .aes_gcm_decrypt(blob, iv, tag) |
| 253 | .context("In unwrap_key_with_key: Failed to decrypt the key blob."), |
| 254 | (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!( |
| 255 | concat!( |
| 256 | "In unwrap_key_with_key: Key has incomplete metadata.", |
| 257 | "Present: iv: {}, aead_tag: {}." |
| 258 | ), |
| 259 | iv.is_some(), |
| 260 | tag.is_some(), |
| 261 | )), |
| 262 | }, |
| 263 | SuperEncryptionAlgorithm::EcdhP256 => { |
| 264 | match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) { |
| 265 | (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => { |
| 266 | ECDHPrivateKey::from_private_key(&key.key) |
| 267 | .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag)) |
| 268 | .context( |
| 269 | "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.", |
| 270 | ) |
| 271 | } |
| 272 | (public_key, salt, iv, aead_tag) => { |
| 273 | Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!( |
| 274 | concat!( |
| 275 | "In unwrap_key_with_key: Key has incomplete metadata.", |
| 276 | "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}." |
| 277 | ), |
| 278 | public_key.is_some(), |
| 279 | salt.is_some(), |
| 280 | iv.is_some(), |
| 281 | aead_tag.is_some(), |
| 282 | )) |
| 283 | } |
| 284 | } |
| 285 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 286 | } |
| 287 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 288 | |
| 289 | /// 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] | 290 | pub fn super_key_exists_in_db_for_user( |
| 291 | db: &mut KeystoreDB, |
| 292 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 293 | user_id: UserId, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 294 | ) -> Result<bool> { |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 295 | let key_in_db = db |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 296 | .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] | 297 | .context("In super_key_exists_in_db_for_user.")?; |
| 298 | |
| 299 | if key_in_db { |
| 300 | Ok(key_in_db) |
| 301 | } else { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 302 | legacy_migrator |
| 303 | .has_super_key(user_id) |
| 304 | .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] | 305 | } |
| 306 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 307 | |
| 308 | /// 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] | 309 | /// legacy database). If not, return Uninitialized state. |
| 310 | /// Otherwise, decrypt the super key from the password and return LskfUnlocked state. |
| 311 | pub fn check_and_unlock_super_key( |
| 312 | &self, |
| 313 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 314 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 315 | user_id: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 316 | pw: &Password, |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 317 | ) -> Result<UserState> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 318 | let alias = &USER_SUPER_KEY; |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 319 | let result = legacy_migrator |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 320 | .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] | 321 | .context("In check_and_unlock_super_key. Failed to load super key")?; |
| 322 | |
| 323 | match result { |
| 324 | Some((_, entry)) => { |
| 325 | let super_key = self |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 326 | .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw) |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 327 | .context("In check_and_unlock_super_key.")?; |
| 328 | Ok(UserState::LskfUnlocked(super_key)) |
| 329 | } |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 330 | None => Ok(UserState::Uninitialized), |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 331 | } |
| 332 | } |
| 333 | |
| 334 | /// 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] | 335 | /// legacy database). If so, return LskfLocked state. |
| 336 | /// If the password is provided, generate a new super key, encrypt with the password, |
| 337 | /// store in the database and populate the super key cache for the new user |
| 338 | /// and return LskfUnlocked state. |
| 339 | /// If the password is not provided, return Uninitialized state. |
| 340 | pub fn check_and_initialize_super_key( |
| 341 | &self, |
| 342 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 343 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 344 | user_id: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 345 | pw: Option<&Password>, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 346 | ) -> Result<UserState> { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 347 | let super_key_exists_in_db = |
| 348 | Self::super_key_exists_in_db_for_user(db, legacy_migrator, user_id).context( |
| 349 | "In check_and_initialize_super_key. Failed to check if super key exists.", |
| 350 | )?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 351 | if super_key_exists_in_db { |
| 352 | Ok(UserState::LskfLocked) |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 353 | } else if let Some(pw) = pw { |
| 354 | //generate a new super key. |
| 355 | let super_key = generate_aes256_key() |
| 356 | .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?; |
| 357 | //derive an AES256 key from the password and re-encrypt the super key |
| 358 | //before we insert it in the database. |
| 359 | let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw) |
| 360 | .context("In check_and_initialize_super_key.")?; |
| 361 | |
| 362 | let key_entry = db |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 363 | .store_super_key( |
| 364 | user_id, |
| 365 | &USER_SUPER_KEY, |
| 366 | &encrypted_super_key, |
| 367 | &blob_metadata, |
| 368 | &KeyMetaData::new(), |
| 369 | ) |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 370 | .context("In check_and_initialize_super_key. Failed to store super key.")?; |
| 371 | |
| 372 | let super_key = self |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 373 | .populate_cache_from_super_key_blob( |
| 374 | user_id, |
| 375 | USER_SUPER_KEY.algorithm, |
| 376 | key_entry, |
| 377 | pw, |
| 378 | ) |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 379 | .context("In check_and_initialize_super_key.")?; |
| 380 | Ok(UserState::LskfUnlocked(super_key)) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 381 | } else { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 382 | Ok(UserState::Uninitialized) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 383 | } |
| 384 | } |
| 385 | |
| 386 | //helper function to populate super key cache from the super key blob loaded from the database |
| 387 | fn populate_cache_from_super_key_blob( |
| 388 | &self, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 389 | user_id: UserId, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 390 | algorithm: SuperEncryptionAlgorithm, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 391 | entry: KeyEntry, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 392 | pw: &Password, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 393 | ) -> Result<Arc<SuperKey>> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 394 | let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None) |
| 395 | .context( |
| 396 | "In populate_cache_from_super_key_blob. Failed to extract super key from key entry", |
| 397 | )?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 398 | self.install_per_boot_key_for_user(user_id, super_key.clone()); |
| 399 | Ok(super_key) |
| 400 | } |
| 401 | |
| 402 | /// Extracts super key from the entry loaded from the database |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 403 | pub fn extract_super_key_from_key_entry( |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 404 | algorithm: SuperEncryptionAlgorithm, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 405 | entry: KeyEntry, |
| 406 | pw: &Password, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 407 | reencrypt_with: Option<Arc<SuperKey>>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 408 | ) -> Result<Arc<SuperKey>> { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 409 | if let Some((blob, metadata)) = entry.key_blob_info() { |
| 410 | let key = match ( |
| 411 | metadata.encrypted_by(), |
| 412 | metadata.salt(), |
| 413 | metadata.iv(), |
| 414 | metadata.aead_tag(), |
| 415 | ) { |
| 416 | (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 417 | // Note that password encryption is AES no matter the value of algorithm |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 418 | let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context( |
| 419 | "In extract_super_key_from_key_entry: Failed to generate key from password.", |
| 420 | )?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 421 | |
| 422 | aes_gcm_decrypt(blob, iv, tag, &key).context( |
| 423 | "In extract_super_key_from_key_entry: Failed to decrypt key blob.", |
| 424 | )? |
| 425 | } |
| 426 | (enc_by, salt, iv, tag) => { |
| 427 | return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!( |
| 428 | concat!( |
| 429 | "In extract_super_key_from_key_entry: Super key has incomplete metadata.", |
| 430 | "Present: encrypted_by: {}, salt: {}, iv: {}, aead_tag: {}." |
| 431 | ), |
| 432 | enc_by.is_some(), |
| 433 | salt.is_some(), |
| 434 | iv.is_some(), |
| 435 | tag.is_some() |
| 436 | )); |
| 437 | } |
| 438 | }; |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 439 | Ok(Arc::new(SuperKey { algorithm, key, id: entry.id(), reencrypt_with })) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 440 | } else { |
| 441 | Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)) |
| 442 | .context("In extract_super_key_from_key_entry: No key blob info.") |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | /// Encrypts the super key from a key derived from the password, before storing in the database. |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 447 | pub fn encrypt_with_password( |
| 448 | super_key: &[u8], |
| 449 | pw: &Password, |
| 450 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 451 | 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] | 452 | let derived_key = pw |
| 453 | .derive_key(Some(&salt), AES_256_KEY_LENGTH) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 454 | .context("In encrypt_with_password: Failed to derive password.")?; |
| 455 | let mut metadata = BlobMetaData::new(); |
| 456 | metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password)); |
| 457 | metadata.add(BlobMetaEntry::Salt(salt)); |
| 458 | let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key) |
| 459 | .context("In encrypt_with_password: Failed to encrypt new super key.")?; |
| 460 | metadata.add(BlobMetaEntry::Iv(iv)); |
| 461 | metadata.add(BlobMetaEntry::AeadTag(tag)); |
| 462 | Ok((encrypted_key, metadata)) |
| 463 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 464 | |
| 465 | // Encrypt the given key blob with the user's super key, if the super key exists and the device |
| 466 | // is unlocked. If the super key exists and the device is locked, or LSKF is not setup, |
| 467 | // return error. Note that it is out of the scope of this function to check if super encryption |
| 468 | // is required. Such check should be performed before calling this function. |
| 469 | fn super_encrypt_on_key_init( |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 470 | &self, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 471 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 472 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 473 | user_id: UserId, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 474 | key_blob: &[u8], |
| 475 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 476 | match UserState::get(db, legacy_migrator, self, user_id) |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 477 | .context("In super_encrypt. Failed to get user state.")? |
| 478 | { |
| 479 | UserState::LskfUnlocked(super_key) => { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 480 | Self::encrypt_with_aes_super_key(key_blob, &super_key) |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 481 | .context("In super_encrypt_on_key_init. Failed to encrypt the key.") |
| 482 | } |
| 483 | UserState::LskfLocked => { |
| 484 | Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.") |
| 485 | } |
| 486 | UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED)) |
| 487 | .context("In super_encrypt. LSKF is not setup for the user."), |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | //Helper function to encrypt a key with the given super key. Callers should select which super |
| 492 | //key to be used. This is called when a key is super encrypted at its creation as well as at its |
| 493 | //upgrade. |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 494 | fn encrypt_with_aes_super_key( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 495 | key_blob: &[u8], |
| 496 | super_key: &SuperKey, |
| 497 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 498 | if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm { |
| 499 | return Err(Error::sys()) |
| 500 | .context("In encrypt_with_aes_super_key: unexpected algorithm"); |
| 501 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 502 | let mut metadata = BlobMetaData::new(); |
| 503 | 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] | 504 | .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] | 505 | metadata.add(BlobMetaEntry::Iv(iv)); |
| 506 | metadata.add(BlobMetaEntry::AeadTag(tag)); |
| 507 | metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key.id))); |
| 508 | Ok((encrypted_key, metadata)) |
| 509 | } |
| 510 | |
| 511 | /// Check if super encryption is required and if so, super-encrypt the key to be stored in |
| 512 | /// the database. |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 513 | #[allow(clippy::clippy::too_many_arguments)] |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 514 | pub fn handle_super_encryption_on_key_init( |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 515 | &self, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 516 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 517 | legacy_migrator: &LegacyMigrator, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 518 | domain: &Domain, |
| 519 | key_parameters: &[KeyParameter], |
| 520 | flags: Option<i32>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 521 | user_id: UserId, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 522 | key_blob: &[u8], |
| 523 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 524 | match Enforcements::super_encryption_required(domain, key_parameters, flags) { |
| 525 | SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())), |
| 526 | SuperEncryptionType::LskfBound => { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 527 | 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] | 528 | "In handle_super_encryption_on_key_init. |
| 529 | Failed to super encrypt the key.", |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 530 | ) |
| 531 | } |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 532 | SuperEncryptionType::ScreenLockBound => { |
| 533 | let mut data = self.data.lock().unwrap(); |
| 534 | let entry = data.user_keys.entry(user_id).or_default(); |
| 535 | if let Some(super_key) = entry.screen_lock_bound.as_ref() { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 536 | Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!( |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 537 | "In handle_super_encryption_on_key_init. ", |
| 538 | "Failed to encrypt the key with screen_lock_bound key." |
| 539 | )) |
| 540 | } else { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 541 | // Symmetric key is not available, use public key encryption |
| 542 | let loaded = |
| 543 | db.load_super_key(&USER_SCREEN_LOCK_BOUND_ECDH_KEY, user_id).context( |
| 544 | "In handle_super_encryption_on_key_init: load_super_key failed.", |
| 545 | )?; |
| 546 | let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context( |
| 547 | "In handle_super_encryption_on_key_init: User ECDH key missing.", |
| 548 | )?; |
| 549 | let public_key = |
| 550 | key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context( |
| 551 | "In handle_super_encryption_on_key_init: sec1_public_key missing.", |
| 552 | )?; |
| 553 | let mut metadata = BlobMetaData::new(); |
| 554 | let (ephem_key, salt, iv, encrypted_key, aead_tag) = |
| 555 | ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!( |
| 556 | "In handle_super_encryption_on_key_init: ", |
| 557 | "ECDHPrivateKey::encrypt_message failed." |
| 558 | ))?; |
| 559 | metadata.add(BlobMetaEntry::PublicKey(ephem_key)); |
| 560 | metadata.add(BlobMetaEntry::Salt(salt)); |
| 561 | metadata.add(BlobMetaEntry::Iv(iv)); |
| 562 | metadata.add(BlobMetaEntry::AeadTag(aead_tag)); |
| 563 | metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(key_id_guard.id()))); |
| 564 | Ok((encrypted_key, metadata)) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 565 | } |
| 566 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 567 | } |
| 568 | } |
| 569 | |
| 570 | /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using |
| 571 | /// the relevant super key. |
| 572 | pub fn unwrap_key_if_required<'a>( |
| 573 | &self, |
| 574 | metadata: &BlobMetaData, |
| 575 | key_blob: &'a [u8], |
| 576 | ) -> Result<KeyBlob<'a>> { |
| 577 | if Self::key_super_encrypted(&metadata) { |
| 578 | let unwrapped_key = self |
| 579 | .unwrap_key(key_blob, metadata) |
| 580 | .context("In unwrap_key_if_required. Error in unwrapping the key.")?; |
| 581 | Ok(unwrapped_key) |
| 582 | } else { |
| 583 | Ok(KeyBlob::Ref(key_blob)) |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | /// Check if a given key needs re-super-encryption, from its KeyBlob type. |
| 588 | /// If so, re-super-encrypt the key and return a new set of metadata, |
| 589 | /// containing the new super encryption information. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 590 | pub fn reencrypt_if_required<'a>( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 591 | key_blob_before_upgrade: &KeyBlob, |
| 592 | key_after_upgrade: &'a [u8], |
| 593 | ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> { |
| 594 | match key_blob_before_upgrade { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 595 | KeyBlob::Sensitive { reencrypt_with: super_key, .. } => { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 596 | let (key, metadata) = |
| 597 | Self::encrypt_with_aes_super_key(key_after_upgrade, super_key) |
| 598 | .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?; |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 599 | Ok((KeyBlob::NonSensitive(key), Some(metadata))) |
| 600 | } |
| 601 | _ => Ok((KeyBlob::Ref(key_after_upgrade), None)), |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | // Helper function to decide if a key is super encrypted, given metadata. |
| 606 | fn key_super_encrypted(metadata: &BlobMetaData) -> bool { |
| 607 | if let Some(&EncryptedBy::KeyId(_)) = metadata.encrypted_by() { |
| 608 | return true; |
| 609 | } |
| 610 | false |
| 611 | } |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 612 | |
| 613 | /// Fetch a superencryption key from the database, or create it if it doesn't already exist. |
| 614 | /// When this is called, the caller must hold the lock on the SuperKeyManager. |
| 615 | /// So it's OK that the check and creation are different DB transactions. |
| 616 | fn get_or_create_super_key( |
| 617 | db: &mut KeystoreDB, |
| 618 | user_id: UserId, |
| 619 | key_type: &SuperKeyType, |
| 620 | password: &Password, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 621 | reencrypt_with: Option<Arc<SuperKey>>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 622 | ) -> Result<Arc<SuperKey>> { |
| 623 | let loaded_key = db.load_super_key(key_type, user_id)?; |
| 624 | if let Some((_, key_entry)) = loaded_key { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 625 | Ok(Self::extract_super_key_from_key_entry( |
| 626 | key_type.algorithm, |
| 627 | key_entry, |
| 628 | password, |
| 629 | reencrypt_with, |
| 630 | )?) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 631 | } else { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 632 | let (super_key, public_key) = match key_type.algorithm { |
| 633 | SuperEncryptionAlgorithm::Aes256Gcm => ( |
| 634 | generate_aes256_key() |
| 635 | .context("In get_or_create_super_key: Failed to generate AES 256 key.")?, |
| 636 | None, |
| 637 | ), |
| 638 | SuperEncryptionAlgorithm::EcdhP256 => { |
| 639 | let key = ECDHPrivateKey::generate() |
| 640 | .context("In get_or_create_super_key: Failed to generate ECDH key")?; |
| 641 | ( |
| 642 | key.private_key() |
| 643 | .context("In get_or_create_super_key: private_key failed")?, |
| 644 | Some( |
| 645 | key.public_key() |
| 646 | .context("In get_or_create_super_key: public_key failed")?, |
| 647 | ), |
| 648 | ) |
| 649 | } |
| 650 | }; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 651 | //derive an AES256 key from the password and re-encrypt the super key |
| 652 | //before we insert it in the database. |
| 653 | let (encrypted_super_key, blob_metadata) = |
| 654 | Self::encrypt_with_password(&super_key, password) |
| 655 | .context("In get_or_create_super_key.")?; |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 656 | let mut key_metadata = KeyMetaData::new(); |
| 657 | if let Some(pk) = public_key { |
| 658 | key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk)); |
| 659 | } |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 660 | let key_entry = db |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 661 | .store_super_key( |
| 662 | user_id, |
| 663 | key_type, |
| 664 | &encrypted_super_key, |
| 665 | &blob_metadata, |
| 666 | &key_metadata, |
| 667 | ) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 668 | .context("In get_or_create_super_key. Failed to store super key.")?; |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 669 | Ok(Arc::new(SuperKey { |
| 670 | algorithm: key_type.algorithm, |
| 671 | key: super_key, |
| 672 | id: key_entry.id(), |
| 673 | reencrypt_with, |
| 674 | })) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 675 | } |
| 676 | } |
| 677 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 678 | /// 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] | 679 | pub fn unlock_screen_lock_bound_key( |
| 680 | &self, |
| 681 | db: &mut KeystoreDB, |
| 682 | user_id: UserId, |
| 683 | password: &Password, |
| 684 | ) -> Result<()> { |
| 685 | let mut data = self.data.lock().unwrap(); |
| 686 | let entry = data.user_keys.entry(user_id).or_default(); |
| 687 | let aes = entry |
| 688 | .screen_lock_bound |
| 689 | .get_or_try_to_insert_with(|| { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 690 | Self::get_or_create_super_key( |
| 691 | db, |
| 692 | user_id, |
| 693 | &USER_SCREEN_LOCK_BOUND_KEY, |
| 694 | password, |
| 695 | None, |
| 696 | ) |
| 697 | })? |
| 698 | .clone(); |
| 699 | let ecdh = entry |
| 700 | .screen_lock_bound_private |
| 701 | .get_or_try_to_insert_with(|| { |
| 702 | Self::get_or_create_super_key( |
| 703 | db, |
| 704 | user_id, |
| 705 | &USER_SCREEN_LOCK_BOUND_ECDH_KEY, |
| 706 | password, |
| 707 | Some(aes.clone()), |
| 708 | ) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 709 | })? |
| 710 | .clone(); |
| 711 | data.add_key_to_key_index(&aes); |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 712 | data.add_key_to_key_index(&ecdh); |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 713 | Ok(()) |
| 714 | } |
| 715 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 716 | /// Wipe the screen-lock bound keys for this user from memory. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 717 | pub fn lock_screen_lock_bound_key(&self, user_id: UserId) { |
| 718 | let mut data = self.data.lock().unwrap(); |
| 719 | let mut entry = data.user_keys.entry(user_id).or_default(); |
| 720 | entry.screen_lock_bound = None; |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 721 | entry.screen_lock_bound_private = None; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 722 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 723 | } |
| 724 | |
| 725 | /// This enum represents different states of the user's life cycle in the device. |
| 726 | /// For now, only three states are defined. More states may be added later. |
| 727 | pub enum UserState { |
| 728 | // The user has registered LSKF and has unlocked the device by entering PIN/Password, |
| 729 | // and hence the per-boot super key is available in the cache. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 730 | LskfUnlocked(Arc<SuperKey>), |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 731 | // The user has registered LSKF, but has not unlocked the device using password, after reboot. |
| 732 | // Hence the per-boot super-key(s) is not available in the cache. |
| 733 | // However, the encrypted super key is available in the database. |
| 734 | LskfLocked, |
| 735 | // There's no user in the device for the given user id, or the user with the user id has not |
| 736 | // setup LSKF. |
| 737 | Uninitialized, |
| 738 | } |
| 739 | |
| 740 | impl UserState { |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 741 | pub fn get( |
| 742 | db: &mut KeystoreDB, |
| 743 | legacy_migrator: &LegacyMigrator, |
| 744 | skm: &SuperKeyManager, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 745 | user_id: UserId, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 746 | ) -> Result<UserState> { |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 747 | match skm.get_per_boot_key_by_user_id(user_id) { |
| 748 | Some(super_key) => Ok(UserState::LskfUnlocked(super_key)), |
| 749 | None => { |
| 750 | //Check if a super key exists in the database or legacy database. |
| 751 | //If so, return locked user state. |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 752 | 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] | 753 | .context("In get.")? |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 754 | { |
| 755 | Ok(UserState::LskfLocked) |
| 756 | } else { |
| 757 | Ok(UserState::Uninitialized) |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 762 | |
| 763 | /// Queries user state when serving password change requests. |
| 764 | pub fn get_with_password_changed( |
| 765 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 766 | legacy_migrator: &LegacyMigrator, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 767 | skm: &SuperKeyManager, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 768 | user_id: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 769 | password: Option<&Password>, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 770 | ) -> Result<UserState> { |
| 771 | match skm.get_per_boot_key_by_user_id(user_id) { |
| 772 | Some(super_key) => { |
| 773 | if password.is_none() { |
| 774 | //transitioning to swiping, delete only the super key in database and cache, and |
| 775 | //super-encrypted keys in database (and in KM) |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 776 | Self::reset_user(db, skm, legacy_migrator, user_id, true).context( |
| 777 | "In get_with_password_changed: Trying to delete keys from the db.", |
| 778 | )?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 779 | //Lskf is now removed in Keystore |
| 780 | Ok(UserState::Uninitialized) |
| 781 | } else { |
| 782 | //Keystore won't be notified when changing to a new password when LSKF is |
| 783 | //already setup. Therefore, ideally this path wouldn't be reached. |
| 784 | Ok(UserState::LskfUnlocked(super_key)) |
| 785 | } |
| 786 | } |
| 787 | None => { |
| 788 | //Check if a super key exists in the database or legacy database. |
| 789 | //If so, return LskfLocked state. |
| 790 | //Otherwise, i) if the password is provided, initialize the super key and return |
| 791 | //LskfUnlocked state ii) if password is not provided, return Uninitialized state. |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 792 | skm.check_and_initialize_super_key(db, legacy_migrator, user_id, password) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 793 | } |
| 794 | } |
| 795 | } |
| 796 | |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 797 | /// Queries user state when serving password unlock requests. |
| 798 | pub fn get_with_password_unlock( |
| 799 | db: &mut KeystoreDB, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 800 | legacy_migrator: &LegacyMigrator, |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 801 | skm: &SuperKeyManager, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 802 | user_id: UserId, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 803 | password: &Password, |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 804 | ) -> Result<UserState> { |
| 805 | match skm.get_per_boot_key_by_user_id(user_id) { |
| 806 | Some(super_key) => { |
| 807 | log::info!("In get_with_password_unlock. Trying to unlock when already unlocked."); |
| 808 | Ok(UserState::LskfUnlocked(super_key)) |
| 809 | } |
| 810 | None => { |
| 811 | //Check if a super key exists in the database or legacy database. |
| 812 | //If not, return Uninitialized state. |
| 813 | //Otherwise, try to unlock the super key and if successful, |
| 814 | //return LskfUnlocked state |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 815 | skm.check_and_unlock_super_key(db, legacy_migrator, user_id, password) |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 816 | .context("In get_with_password_unlock. Failed to unlock super key.") |
| 817 | } |
| 818 | } |
| 819 | } |
| 820 | |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 821 | /// Delete all the keys created on behalf of the user. |
| 822 | /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super |
| 823 | /// encrypted keys. |
| 824 | pub fn reset_user( |
| 825 | db: &mut KeystoreDB, |
| 826 | skm: &SuperKeyManager, |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 827 | legacy_migrator: &LegacyMigrator, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 828 | user_id: UserId, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 829 | keep_non_super_encrypted_keys: bool, |
| 830 | ) -> Result<()> { |
| 831 | // mark keys created on behalf of the user as unreferenced. |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 832 | legacy_migrator |
| 833 | .bulk_delete_user(user_id, keep_non_super_encrypted_keys) |
| 834 | .context("In reset_user: Trying to delete legacy keys.")?; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 835 | db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 836 | .context("In reset user. Error in unbinding keys.")?; |
| 837 | |
| 838 | //delete super key in cache, if exists |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 839 | skm.forget_all_keys_for_user(user_id); |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 840 | Ok(()) |
| 841 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 842 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 843 | |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 844 | /// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption. |
| 845 | /// `Sensitive` holds the non encrypted key and a reference to its super key. |
| 846 | /// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted. |
| 847 | /// `Ref` holds a reference to a key blob when it does not need to be modified if its |
| 848 | /// life time allows it. |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 849 | pub enum KeyBlob<'a> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 850 | Sensitive { |
| 851 | key: ZVec, |
| 852 | /// If KeyMint reports that the key must be upgraded, we must |
| 853 | /// re-encrypt the key before writing to the database; we use |
| 854 | /// this key. |
| 855 | reencrypt_with: Arc<SuperKey>, |
| 856 | /// If this key was decrypted with an ECDH key, we want to |
| 857 | /// re-encrypt it on first use whether it was upgraded or not; |
| 858 | /// this field indicates that that's necessary. |
| 859 | force_reencrypt: bool, |
| 860 | }, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 861 | NonSensitive(Vec<u8>), |
| 862 | Ref(&'a [u8]), |
| 863 | } |
| 864 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 865 | impl<'a> KeyBlob<'a> { |
| 866 | pub fn force_reencrypt(&self) -> bool { |
| 867 | if let KeyBlob::Sensitive { force_reencrypt, .. } = self { |
| 868 | *force_reencrypt |
| 869 | } else { |
| 870 | false |
| 871 | } |
| 872 | } |
| 873 | } |
| 874 | |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 875 | /// Deref returns a reference to the key material in any variant. |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 876 | impl<'a> Deref for KeyBlob<'a> { |
| 877 | type Target = [u8]; |
| 878 | |
| 879 | fn deref(&self) -> &Self::Target { |
| 880 | match self { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 881 | Self::Sensitive { key, .. } => &key, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 882 | Self::NonSensitive(key) => &key, |
| 883 | Self::Ref(key) => key, |
| 884 | } |
| 885 | } |
| 886 | } |