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