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