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