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