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