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