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}, |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 28 | ks_err, |
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, |
Eric Biggers | 6745f53 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 81 | /// What to call this key in log messages. Not used for anything else. |
| 82 | pub name: &'a str, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 83 | } |
| 84 | |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 85 | /// The user's AfterFirstUnlock super key. This super key is loaded into memory when the user first |
| 86 | /// unlocks the device, and it remains in memory until the device reboots. This is used to encrypt |
| 87 | /// keys that require user authentication but not an unlocked device. |
Eric Biggers | 6745f53 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 88 | pub const USER_AFTER_FIRST_UNLOCK_SUPER_KEY: SuperKeyType = SuperKeyType { |
| 89 | alias: "USER_SUPER_KEY", |
| 90 | algorithm: SuperEncryptionAlgorithm::Aes256Gcm, |
| 91 | name: "AfterFirstUnlock super key", |
| 92 | }; |
| 93 | |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 94 | /// The user's UnlockedDeviceRequired symmetric super key. This super key is loaded into memory each |
| 95 | /// time the user unlocks the device, and it is cleared from memory each time the user locks the |
| 96 | /// device. This is used to encrypt keys that use the UnlockedDeviceRequired key parameter. |
| 97 | pub const USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY: SuperKeyType = SuperKeyType { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 98 | alias: "USER_SCREEN_LOCK_BOUND_KEY", |
| 99 | algorithm: SuperEncryptionAlgorithm::Aes256Gcm, |
Eric Biggers | 6745f53 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 100 | name: "UnlockedDeviceRequired symmetric super key", |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 101 | }; |
Eric Biggers | 6745f53 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 102 | |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 103 | /// The user's UnlockedDeviceRequired asymmetric super key. This is used to allow, while the device |
| 104 | /// is locked, the creation of keys that use the UnlockedDeviceRequired key parameter. The private |
| 105 | /// part of this key is loaded and cleared when the symmetric key is loaded and cleared. |
| 106 | pub const USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY: SuperKeyType = SuperKeyType { |
Paul Crowley | 52f017f | 2021-06-22 08:16:01 -0700 | [diff] [blame] | 107 | alias: "USER_SCREEN_LOCK_BOUND_P521_KEY", |
| 108 | algorithm: SuperEncryptionAlgorithm::EcdhP521, |
Eric Biggers | 6745f53 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 109 | name: "UnlockedDeviceRequired asymmetric super key", |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 110 | }; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 111 | |
| 112 | /// Superencryption to apply to a new key. |
| 113 | #[derive(Debug, Clone, Copy)] |
| 114 | pub enum SuperEncryptionType { |
| 115 | /// Do not superencrypt this key. |
| 116 | None, |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 117 | /// Superencrypt with the AfterFirstUnlock super key. |
| 118 | AfterFirstUnlock, |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 119 | /// Superencrypt with an UnlockedDeviceRequired super key. |
| 120 | UnlockedDeviceRequired, |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 121 | /// Superencrypt with a key based on the desired boot level |
| 122 | BootLevel(i32), |
| 123 | } |
| 124 | |
| 125 | #[derive(Debug, Clone, Copy)] |
| 126 | pub enum SuperKeyIdentifier { |
| 127 | /// id of the super key in the database. |
| 128 | DatabaseId(i64), |
| 129 | /// Boot level of the encrypting boot level key |
| 130 | BootLevel(i32), |
| 131 | } |
| 132 | |
| 133 | impl SuperKeyIdentifier { |
| 134 | fn from_metadata(metadata: &BlobMetaData) -> Option<Self> { |
| 135 | if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() { |
| 136 | Some(SuperKeyIdentifier::DatabaseId(*key_id)) |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 137 | } else { |
Chris Wailes | fe0abfe | 2021-07-21 11:39:57 -0700 | [diff] [blame] | 138 | metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level)) |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 139 | } |
| 140 | } |
| 141 | |
| 142 | fn add_to_metadata(&self, metadata: &mut BlobMetaData) { |
| 143 | match self { |
| 144 | SuperKeyIdentifier::DatabaseId(id) => { |
| 145 | metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id))); |
| 146 | } |
| 147 | SuperKeyIdentifier::BootLevel(level) => { |
| 148 | metadata.add(BlobMetaEntry::MaxBootLevel(*level)); |
| 149 | } |
| 150 | } |
| 151 | } |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 152 | } |
| 153 | |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 154 | pub struct SuperKey { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 155 | algorithm: SuperEncryptionAlgorithm, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 156 | key: ZVec, |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 157 | /// Identifier of the encrypting key, used to write an encrypted blob |
| 158 | /// back to the database after re-encryption eg on a key update. |
| 159 | id: SuperKeyIdentifier, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 160 | /// ECDH is more expensive than AES. So on ECDH private keys we set the |
| 161 | /// reencrypt_with field to point at the corresponding AES key, and the |
| 162 | /// keys will be re-encrypted with AES on first use. |
| 163 | reencrypt_with: Option<Arc<SuperKey>>, |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 164 | } |
| 165 | |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 166 | impl AesGcm for SuperKey { |
| 167 | fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 168 | if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 169 | aes_gcm_decrypt(data, iv, tag, &self.key).context(ks_err!("Decryption failed.")) |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 170 | } else { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 171 | Err(Error::sys()).context(ks_err!("Key is not an AES key.")) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 172 | } |
| 173 | } |
| 174 | |
| 175 | fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> { |
| 176 | if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 177 | aes_gcm_encrypt(plaintext, &self.key).context(ks_err!("Encryption failed.")) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 178 | } else { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 179 | Err(Error::sys()).context(ks_err!("Key is not an AES key.")) |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 180 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 181 | } |
Paul Crowley | e8826e5 | 2021-03-31 08:33:53 -0700 | [diff] [blame] | 182 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 183 | |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 184 | /// A SuperKey that has been encrypted with an AES-GCM key. For |
| 185 | /// encryption the key is in memory, and for decryption it is in KM. |
| 186 | struct LockedKey { |
| 187 | algorithm: SuperEncryptionAlgorithm, |
| 188 | id: SuperKeyIdentifier, |
| 189 | nonce: Vec<u8>, |
| 190 | ciphertext: Vec<u8>, // with tag appended |
| 191 | } |
| 192 | |
| 193 | impl LockedKey { |
| 194 | fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> { |
| 195 | let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?; |
| 196 | ciphertext.append(&mut tag); |
| 197 | Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext }) |
| 198 | } |
| 199 | |
| 200 | fn decrypt( |
| 201 | &self, |
| 202 | db: &mut KeystoreDB, |
| 203 | km_dev: &KeyMintDevice, |
| 204 | key_id_guard: &KeyIdGuard, |
| 205 | key_entry: &KeyEntry, |
| 206 | auth_token: &HardwareAuthToken, |
| 207 | reencrypt_with: Option<Arc<SuperKey>>, |
| 208 | ) -> Result<Arc<SuperKey>> { |
Janis Danisevskis | acebfa2 | 2021-05-25 10:56:10 -0700 | [diff] [blame] | 209 | let key_blob = key_entry |
| 210 | .key_blob_info() |
| 211 | .as_ref() |
| 212 | .map(|(key_blob, _)| KeyBlob::Ref(key_blob)) |
| 213 | .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND)) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 214 | .context(ks_err!("Missing key blob info."))?; |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 215 | let key_params = vec![ |
| 216 | KeyParameterValue::Algorithm(Algorithm::AES), |
| 217 | KeyParameterValue::KeySize(256), |
| 218 | KeyParameterValue::BlockMode(BlockMode::GCM), |
| 219 | KeyParameterValue::PaddingMode(PaddingMode::NONE), |
| 220 | KeyParameterValue::Nonce(self.nonce.clone()), |
| 221 | KeyParameterValue::MacLength(128), |
| 222 | ]; |
| 223 | let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect(); |
| 224 | let key = ZVec::try_from(km_dev.use_key_in_one_step( |
| 225 | db, |
| 226 | key_id_guard, |
Janis Danisevskis | acebfa2 | 2021-05-25 10:56:10 -0700 | [diff] [blame] | 227 | &key_blob, |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 228 | KeyPurpose::DECRYPT, |
| 229 | &key_params, |
| 230 | Some(auth_token), |
| 231 | &self.ciphertext, |
| 232 | )?)?; |
| 233 | Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with })) |
| 234 | } |
| 235 | } |
| 236 | |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 237 | /// A user's UnlockedDeviceRequired super keys, encrypted with a biometric-bound key, and |
| 238 | /// information about that biometric-bound key. |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 239 | struct BiometricUnlock { |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 240 | /// List of auth token SIDs that are accepted by the encrypting biometric-bound key. |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 241 | sids: Vec<i64>, |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 242 | /// Key descriptor of the encrypting biometric-bound key. |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 243 | key_desc: KeyDescriptor, |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 244 | /// The UnlockedDeviceRequired super keys, encrypted with a biometric-bound key. |
| 245 | symmetric: LockedKey, |
| 246 | private: LockedKey, |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 247 | } |
| 248 | |
Paul Crowley | e8826e5 | 2021-03-31 08:33:53 -0700 | [diff] [blame] | 249 | #[derive(Default)] |
| 250 | struct UserSuperKeys { |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 251 | /// The AfterFirstUnlock super key is used for LSKF binding of authentication bound keys. There |
| 252 | /// is one key per android user. The key is stored on flash encrypted with a key derived from a |
| 253 | /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF). When the |
| 254 | /// user unlocks the device for the first time, this key is unlocked, i.e., decrypted, and stays |
| 255 | /// memory resident until the device reboots. |
| 256 | after_first_unlock: Option<Arc<SuperKey>>, |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 257 | /// The UnlockedDeviceRequired symmetric super key works like the AfterFirstUnlock super key |
| 258 | /// with the distinction that it is cleared from memory when the device is locked. |
| 259 | unlocked_device_required_symmetric: Option<Arc<SuperKey>>, |
| 260 | /// When the device is locked, keys that use the UnlockedDeviceRequired key parameter can still |
| 261 | /// be created, using ECDH public-key encryption. This field holds the decryption private key. |
| 262 | unlocked_device_required_private: Option<Arc<SuperKey>>, |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 263 | /// Versions of the above two keys, locked behind a biometric. |
| 264 | biometric_unlock: Option<BiometricUnlock>, |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 265 | } |
| 266 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 267 | #[derive(Default)] |
| 268 | struct SkmState { |
| 269 | user_keys: HashMap<UserId, UserSuperKeys>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 270 | key_index: HashMap<i64, Weak<SuperKey>>, |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 271 | boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 272 | } |
| 273 | |
| 274 | impl SkmState { |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 275 | fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> { |
| 276 | if let SuperKeyIdentifier::DatabaseId(id) = super_key.id { |
| 277 | self.key_index.insert(id, Arc::downgrade(super_key)); |
| 278 | Ok(()) |
| 279 | } else { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 280 | Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id)) |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 281 | } |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 282 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 283 | } |
| 284 | |
| 285 | #[derive(Default)] |
| 286 | pub struct SuperKeyManager { |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 287 | data: SkmState, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 288 | } |
| 289 | |
| 290 | impl SuperKeyManager { |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 291 | pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> { |
| 292 | let mut skm_guard = skm.write().unwrap(); |
| 293 | if skm_guard.data.boot_level_key_cache.is_some() { |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 294 | log::info!("In set_up_boot_level_cache: called for a second time"); |
| 295 | return Ok(()); |
| 296 | } |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 297 | let level_zero_key = |
| 298 | get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?; |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 299 | skm_guard.data.boot_level_key_cache = |
| 300 | Some(Mutex::new(BootLevelKeyCache::new(level_zero_key))); |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 301 | log::info!("Starting boot level watcher."); |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 302 | let clone = skm.clone(); |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 303 | std::thread::spawn(move || { |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 304 | Self::watch_boot_level(clone) |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 305 | .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e)); |
| 306 | }); |
| 307 | Ok(()) |
| 308 | } |
| 309 | |
| 310 | /// Watch the `keystore.boot_level` system property, and keep boot level up to date. |
| 311 | /// 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] | 312 | fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> { |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 313 | let mut w = PropertyWatcher::new("keystore.boot_level") |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 314 | .context(ks_err!("PropertyWatcher::new failed"))?; |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 315 | loop { |
| 316 | let level = w |
| 317 | .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into)) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 318 | .context(ks_err!("read of property failed"))?; |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 319 | |
| 320 | // This scope limits the skm_guard life, so we don't hold the skm_guard while |
| 321 | // waiting. |
| 322 | { |
| 323 | let mut skm_guard = skm.write().unwrap(); |
| 324 | let boot_level_key_cache = skm_guard |
| 325 | .data |
| 326 | .boot_level_key_cache |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 327 | .as_mut() |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 328 | .ok_or_else(Error::sys) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 329 | .context(ks_err!("Boot level cache not initialized"))? |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 330 | .get_mut() |
| 331 | .unwrap(); |
| 332 | if level < MAX_MAX_BOOT_LEVEL { |
| 333 | log::info!("Read keystore.boot_level value {}", level); |
| 334 | boot_level_key_cache |
| 335 | .advance_boot_level(level) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 336 | .context(ks_err!("advance_boot_level failed"))?; |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 337 | } else { |
| 338 | log::info!( |
| 339 | "keystore.boot_level {} hits maximum {}, finishing.", |
| 340 | level, |
| 341 | MAX_MAX_BOOT_LEVEL |
| 342 | ); |
| 343 | boot_level_key_cache.finish(); |
| 344 | break; |
| 345 | } |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 346 | } |
Andrew Walbran | 48fa970 | 2023-05-10 15:19:30 +0000 | [diff] [blame] | 347 | w.wait(None).context(ks_err!("property wait failed"))?; |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 348 | } |
| 349 | Ok(()) |
| 350 | } |
| 351 | |
| 352 | pub fn level_accessible(&self, boot_level: i32) -> bool { |
| 353 | self.data |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 354 | .boot_level_key_cache |
| 355 | .as_ref() |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 356 | .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] | 357 | } |
| 358 | |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 359 | pub fn forget_all_keys_for_user(&mut self, user: UserId) { |
| 360 | self.data.user_keys.remove(&user); |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 361 | } |
| 362 | |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 363 | fn install_after_first_unlock_key_for_user( |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 364 | &mut self, |
| 365 | user: UserId, |
| 366 | super_key: Arc<SuperKey>, |
| 367 | ) -> Result<()> { |
| 368 | self.data |
| 369 | .add_key_to_key_index(&super_key) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 370 | .context(ks_err!("add_key_to_key_index failed"))?; |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 371 | self.data.user_keys.entry(user).or_default().after_first_unlock = Some(super_key); |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 372 | Ok(()) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 373 | } |
| 374 | |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 375 | fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> { |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 376 | Ok(match key_id { |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 377 | SuperKeyIdentifier::DatabaseId(id) => { |
| 378 | self.data.key_index.get(id).and_then(|k| k.upgrade()) |
| 379 | } |
| 380 | SuperKeyIdentifier::BootLevel(level) => self |
| 381 | .data |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 382 | .boot_level_key_cache |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 383 | .as_ref() |
| 384 | .map(|b| b.lock().unwrap().aes_key(*level as usize)) |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 385 | .transpose() |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 386 | .context(ks_err!("aes_key failed"))? |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 387 | .flatten() |
| 388 | .map(|key| { |
| 389 | Arc::new(SuperKey { |
| 390 | algorithm: SuperEncryptionAlgorithm::Aes256Gcm, |
| 391 | key, |
| 392 | id: *key_id, |
| 393 | reencrypt_with: None, |
| 394 | }) |
| 395 | }), |
| 396 | }) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 397 | } |
| 398 | |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 399 | /// Returns the AfterFirstUnlock superencryption key for the given user ID, or None if the user |
| 400 | /// has not yet unlocked the device since boot. |
| 401 | pub fn get_after_first_unlock_key_by_user_id( |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 402 | &self, |
| 403 | user_id: UserId, |
| 404 | ) -> Option<Arc<dyn AesGcm + Send + Sync>> { |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 405 | self.get_after_first_unlock_key_by_user_id_internal(user_id) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 406 | .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk }) |
| 407 | } |
| 408 | |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 409 | fn get_after_first_unlock_key_by_user_id_internal( |
| 410 | &self, |
| 411 | user_id: UserId, |
| 412 | ) -> Option<Arc<SuperKey>> { |
| 413 | self.data.user_keys.get(&user_id).and_then(|e| e.after_first_unlock.as_ref().cloned()) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 414 | } |
| 415 | |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 416 | /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using |
| 417 | /// the relevant super key. |
| 418 | pub fn unwrap_key_if_required<'a>( |
| 419 | &self, |
| 420 | metadata: &BlobMetaData, |
| 421 | blob: &'a [u8], |
| 422 | ) -> Result<KeyBlob<'a>> { |
| 423 | Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) { |
| 424 | let super_key = self |
| 425 | .lookup_key(&key_id) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 426 | .context(ks_err!("lookup_key failed"))? |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 427 | .ok_or(Error::Rc(ResponseCode::LOCKED)) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 428 | .context(ks_err!("Required super decryption key is not in memory."))?; |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 429 | KeyBlob::Sensitive { |
| 430 | key: Self::unwrap_key_with_key(blob, metadata, &super_key) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 431 | .context(ks_err!("unwrap_key_with_key failed"))?, |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 432 | reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(), |
| 433 | force_reencrypt: super_key.reencrypt_with.is_some(), |
| 434 | } |
Paul Crowley | e8826e5 | 2021-03-31 08:33:53 -0700 | [diff] [blame] | 435 | } else { |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 436 | KeyBlob::Ref(blob) |
Paul Crowley | e8826e5 | 2021-03-31 08:33:53 -0700 | [diff] [blame] | 437 | }) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 438 | } |
| 439 | |
| 440 | /// Unwraps an encrypted key blob given an encryption key. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 441 | 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] | 442 | match key.algorithm { |
| 443 | SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 444 | (Some(iv), Some(tag)) => { |
| 445 | key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob.")) |
| 446 | } |
| 447 | (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!( |
| 448 | "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.", |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 449 | iv.is_some(), |
| 450 | tag.is_some(), |
| 451 | )), |
| 452 | }, |
Paul Crowley | 52f017f | 2021-06-22 08:16:01 -0700 | [diff] [blame] | 453 | SuperEncryptionAlgorithm::EcdhP521 => { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 454 | match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) { |
| 455 | (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => { |
| 456 | ECDHPrivateKey::from_private_key(&key.key) |
| 457 | .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag)) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 458 | .context(ks_err!("Failed to decrypt the key blob with ECDH.")) |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 459 | } |
| 460 | (public_key, salt, iv, aead_tag) => { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 461 | Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!( |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 462 | concat!( |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 463 | "Key has incomplete metadata. ", |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 464 | "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}." |
| 465 | ), |
| 466 | public_key.is_some(), |
| 467 | salt.is_some(), |
| 468 | iv.is_some(), |
| 469 | aead_tag.is_some(), |
| 470 | )) |
| 471 | } |
| 472 | } |
| 473 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 474 | } |
| 475 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 476 | |
| 477 | /// 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] | 478 | /// The reference to self is unused but it is required to prevent calling this function |
| 479 | /// concurrently with skm state database changes. |
| 480 | fn super_key_exists_in_db_for_user( |
| 481 | &self, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 482 | db: &mut KeystoreDB, |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 483 | legacy_importer: &LegacyImporter, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 484 | user_id: UserId, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 485 | ) -> Result<bool> { |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 486 | let key_in_db = db |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 487 | .key_exists( |
| 488 | Domain::APP, |
| 489 | user_id as u64 as i64, |
| 490 | USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias, |
| 491 | KeyType::Super, |
| 492 | ) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 493 | .context(ks_err!())?; |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 494 | |
| 495 | if key_in_db { |
| 496 | Ok(key_in_db) |
| 497 | } else { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 498 | legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db.")) |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 499 | } |
| 500 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 501 | |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 502 | // 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] | 503 | fn populate_cache_from_super_key_blob( |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 504 | &mut self, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 505 | user_id: UserId, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 506 | algorithm: SuperEncryptionAlgorithm, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 507 | entry: KeyEntry, |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 508 | pw: &Password, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 509 | ) -> Result<Arc<SuperKey>> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 510 | let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 511 | .context(ks_err!("Failed to extract super key from key entry"))?; |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 512 | self.install_after_first_unlock_key_for_user(user_id, super_key.clone()) |
| 513 | .context(ks_err!("Failed to install AfterFirstUnlock super key for user!"))?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 514 | Ok(super_key) |
| 515 | } |
| 516 | |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 517 | /// Extracts super key from the entry loaded from the database. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 518 | pub fn extract_super_key_from_key_entry( |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 519 | algorithm: SuperEncryptionAlgorithm, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 520 | entry: KeyEntry, |
| 521 | pw: &Password, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 522 | reencrypt_with: Option<Arc<SuperKey>>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 523 | ) -> Result<Arc<SuperKey>> { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 524 | if let Some((blob, metadata)) = entry.key_blob_info() { |
| 525 | let key = match ( |
| 526 | metadata.encrypted_by(), |
| 527 | metadata.salt(), |
| 528 | metadata.iv(), |
| 529 | metadata.aead_tag(), |
| 530 | ) { |
| 531 | (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => { |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 532 | // Note that password encryption is AES no matter the value of algorithm. |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 533 | let key = pw |
| 534 | .derive_key(salt, AES_256_KEY_LENGTH) |
| 535 | .context(ks_err!("Failed to generate key from password."))?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 536 | |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 537 | aes_gcm_decrypt(blob, iv, tag, &key) |
| 538 | .context(ks_err!("Failed to decrypt key blob."))? |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 539 | } |
| 540 | (enc_by, salt, iv, tag) => { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 541 | return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!( |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 542 | concat!( |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 543 | "Super key has incomplete metadata.", |
| 544 | "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}." |
| 545 | ), |
Paul Crowley | e8826e5 | 2021-03-31 08:33:53 -0700 | [diff] [blame] | 546 | enc_by, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 547 | salt.is_some(), |
| 548 | iv.is_some(), |
| 549 | tag.is_some() |
| 550 | )); |
| 551 | } |
| 552 | }; |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 553 | Ok(Arc::new(SuperKey { |
| 554 | algorithm, |
| 555 | key, |
| 556 | id: SuperKeyIdentifier::DatabaseId(entry.id()), |
| 557 | reencrypt_with, |
| 558 | })) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 559 | } else { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 560 | Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info.")) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 561 | } |
| 562 | } |
| 563 | |
| 564 | /// 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] | 565 | pub fn encrypt_with_password( |
| 566 | super_key: &[u8], |
| 567 | pw: &Password, |
| 568 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 569 | 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] | 570 | let derived_key = pw |
David Drysdale | 6a0ec2c | 2022-04-19 08:11:18 +0100 | [diff] [blame] | 571 | .derive_key(&salt, AES_256_KEY_LENGTH) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 572 | .context(ks_err!("Failed to derive password."))?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 573 | let mut metadata = BlobMetaData::new(); |
| 574 | metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password)); |
| 575 | metadata.add(BlobMetaEntry::Salt(salt)); |
| 576 | let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 577 | .context(ks_err!("Failed to encrypt new super key."))?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 578 | metadata.add(BlobMetaEntry::Iv(iv)); |
| 579 | metadata.add(BlobMetaEntry::AeadTag(tag)); |
| 580 | Ok((encrypted_key, metadata)) |
| 581 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 582 | |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 583 | // Helper function to encrypt a key with the given super key. Callers should select which super |
| 584 | // key to be used. This is called when a key is super encrypted at its creation as well as at |
| 585 | // its upgrade. |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 586 | fn encrypt_with_aes_super_key( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 587 | key_blob: &[u8], |
| 588 | super_key: &SuperKey, |
| 589 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 590 | if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 591 | return Err(Error::sys()).context(ks_err!("unexpected algorithm")); |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 592 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 593 | let mut metadata = BlobMetaData::new(); |
| 594 | let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key)) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 595 | .context(ks_err!("Failed to encrypt new super key."))?; |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 596 | metadata.add(BlobMetaEntry::Iv(iv)); |
| 597 | metadata.add(BlobMetaEntry::AeadTag(tag)); |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 598 | super_key.id.add_to_metadata(&mut metadata); |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 599 | Ok((encrypted_key, metadata)) |
| 600 | } |
| 601 | |
Nathan Huckleberry | f9494d1 | 2023-03-30 01:22:18 +0000 | [diff] [blame] | 602 | // Encrypts a given key_blob using a hybrid approach, which can either use the symmetric super |
| 603 | // key or the public super key depending on which is available. |
| 604 | // |
| 605 | // If the symmetric_key is available, the key_blob is encrypted using symmetric encryption with |
| 606 | // the provided symmetric super key. Otherwise, the function loads the public super key from |
| 607 | // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be |
| 608 | // re-encrypted with the symmetric super key on the first use. |
| 609 | // |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 610 | // This hybrid scheme allows keys that use the UnlockedDeviceRequired key parameter to be |
| 611 | // created while the device is locked. |
Nathan Huckleberry | f9494d1 | 2023-03-30 01:22:18 +0000 | [diff] [blame] | 612 | fn encrypt_with_hybrid_super_key( |
| 613 | key_blob: &[u8], |
| 614 | symmetric_key: Option<&SuperKey>, |
| 615 | public_key_type: &SuperKeyType, |
| 616 | db: &mut KeystoreDB, |
| 617 | user_id: UserId, |
| 618 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
| 619 | if let Some(super_key) = symmetric_key { |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 620 | Self::encrypt_with_aes_super_key(key_blob, super_key).context(ks_err!( |
| 621 | "Failed to encrypt with UnlockedDeviceRequired symmetric super key." |
| 622 | )) |
Nathan Huckleberry | f9494d1 | 2023-03-30 01:22:18 +0000 | [diff] [blame] | 623 | } else { |
| 624 | // Symmetric key is not available, use public key encryption |
| 625 | let loaded = db |
| 626 | .load_super_key(public_key_type, user_id) |
| 627 | .context(ks_err!("load_super_key failed."))?; |
| 628 | let (key_id_guard, key_entry) = |
| 629 | loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH super key missing."))?; |
| 630 | let public_key = key_entry |
| 631 | .metadata() |
| 632 | .sec1_public_key() |
| 633 | .ok_or_else(Error::sys) |
| 634 | .context(ks_err!("sec1_public_key missing."))?; |
| 635 | let mut metadata = BlobMetaData::new(); |
| 636 | let (ephem_key, salt, iv, encrypted_key, aead_tag) = |
| 637 | ECDHPrivateKey::encrypt_message(public_key, key_blob) |
| 638 | .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?; |
| 639 | metadata.add(BlobMetaEntry::PublicKey(ephem_key)); |
| 640 | metadata.add(BlobMetaEntry::Salt(salt)); |
| 641 | metadata.add(BlobMetaEntry::Iv(iv)); |
| 642 | metadata.add(BlobMetaEntry::AeadTag(aead_tag)); |
| 643 | SuperKeyIdentifier::DatabaseId(key_id_guard.id()).add_to_metadata(&mut metadata); |
| 644 | Ok((encrypted_key, metadata)) |
| 645 | } |
| 646 | } |
| 647 | |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 648 | /// Check if super encryption is required and if so, super-encrypt the key to be stored in |
| 649 | /// the database. |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 650 | #[allow(clippy::too_many_arguments)] |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 651 | pub fn handle_super_encryption_on_key_init( |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 652 | &self, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 653 | db: &mut KeystoreDB, |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 654 | legacy_importer: &LegacyImporter, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 655 | domain: &Domain, |
| 656 | key_parameters: &[KeyParameter], |
| 657 | flags: Option<i32>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 658 | user_id: UserId, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 659 | key_blob: &[u8], |
| 660 | ) -> Result<(Vec<u8>, BlobMetaData)> { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 661 | match Enforcements::super_encryption_required(domain, key_parameters, flags) { |
| 662 | SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())), |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 663 | SuperEncryptionType::AfterFirstUnlock => { |
| 664 | // Encrypt the given key blob with the user's AfterFirstUnlock super key. If the |
| 665 | // user has not unlocked the device since boot or has no LSKF, an error is returned. |
Nathan Huckleberry | a405d0e | 2023-03-28 18:01:43 +0000 | [diff] [blame] | 666 | match self |
| 667 | .get_user_state(db, legacy_importer, user_id) |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 668 | .context(ks_err!("Failed to get user state for user {user_id}"))? |
Nathan Huckleberry | a405d0e | 2023-03-28 18:01:43 +0000 | [diff] [blame] | 669 | { |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 670 | UserState::AfterFirstUnlock(super_key) => { |
| 671 | Self::encrypt_with_aes_super_key(key_blob, &super_key).context(ks_err!( |
| 672 | "Failed to encrypt with AfterFirstUnlock super key for user {user_id}" |
| 673 | )) |
| 674 | } |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 675 | UserState::BeforeFirstUnlock => { |
Nathan Huckleberry | a405d0e | 2023-03-28 18:01:43 +0000 | [diff] [blame] | 676 | Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked.")) |
| 677 | } |
| 678 | UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED)) |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 679 | .context(ks_err!("LSKF is not setup for user {user_id}")), |
Nathan Huckleberry | a405d0e | 2023-03-28 18:01:43 +0000 | [diff] [blame] | 680 | } |
| 681 | } |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 682 | SuperEncryptionType::UnlockedDeviceRequired => { |
| 683 | let symmetric_key = self |
Nathan Huckleberry | f9494d1 | 2023-03-30 01:22:18 +0000 | [diff] [blame] | 684 | .data |
| 685 | .user_keys |
| 686 | .get(&user_id) |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 687 | .and_then(|e| e.unlocked_device_required_symmetric.as_ref()) |
Nathan Huckleberry | f9494d1 | 2023-03-30 01:22:18 +0000 | [diff] [blame] | 688 | .map(|arc| arc.as_ref()); |
| 689 | Self::encrypt_with_hybrid_super_key( |
| 690 | key_blob, |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 691 | symmetric_key, |
| 692 | &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY, |
Nathan Huckleberry | f9494d1 | 2023-03-30 01:22:18 +0000 | [diff] [blame] | 693 | db, |
| 694 | user_id, |
| 695 | ) |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 696 | .context(ks_err!("Failed to encrypt with UnlockedDeviceRequired hybrid scheme.")) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 697 | } |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 698 | SuperEncryptionType::BootLevel(level) => { |
| 699 | let key_id = SuperKeyIdentifier::BootLevel(level); |
| 700 | let super_key = self |
| 701 | .lookup_key(&key_id) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 702 | .context(ks_err!("lookup_key failed"))? |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 703 | .ok_or(Error::Rc(ResponseCode::LOCKED)) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 704 | .context(ks_err!("Boot stage key absent"))?; |
| 705 | Self::encrypt_with_aes_super_key(key_blob, &super_key) |
| 706 | .context(ks_err!("Failed to encrypt with BootLevel key.")) |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 707 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 708 | } |
| 709 | } |
| 710 | |
| 711 | /// Check if a given key needs re-super-encryption, from its KeyBlob type. |
| 712 | /// If so, re-super-encrypt the key and return a new set of metadata, |
| 713 | /// containing the new super encryption information. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 714 | pub fn reencrypt_if_required<'a>( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 715 | key_blob_before_upgrade: &KeyBlob, |
| 716 | key_after_upgrade: &'a [u8], |
| 717 | ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> { |
| 718 | match key_blob_before_upgrade { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 719 | KeyBlob::Sensitive { reencrypt_with: super_key, .. } => { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 720 | let (key, metadata) = |
| 721 | Self::encrypt_with_aes_super_key(key_after_upgrade, super_key) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 722 | .context(ks_err!("Failed to re-super-encrypt key."))?; |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 723 | Ok((KeyBlob::NonSensitive(key), Some(metadata))) |
| 724 | } |
| 725 | _ => Ok((KeyBlob::Ref(key_after_upgrade), None)), |
| 726 | } |
| 727 | } |
| 728 | |
Eric Biggers | 456a3a6 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 729 | fn create_super_key( |
| 730 | &mut self, |
| 731 | db: &mut KeystoreDB, |
| 732 | user_id: UserId, |
| 733 | key_type: &SuperKeyType, |
| 734 | password: &Password, |
| 735 | reencrypt_with: Option<Arc<SuperKey>>, |
| 736 | ) -> Result<Arc<SuperKey>> { |
Eric Biggers | 6745f53 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 737 | log::info!("Creating {} for user {}", key_type.name, user_id); |
Eric Biggers | 456a3a6 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 738 | let (super_key, public_key) = match key_type.algorithm { |
| 739 | SuperEncryptionAlgorithm::Aes256Gcm => { |
| 740 | (generate_aes256_key().context(ks_err!("Failed to generate AES-256 key."))?, None) |
| 741 | } |
| 742 | SuperEncryptionAlgorithm::EcdhP521 => { |
| 743 | let key = |
| 744 | ECDHPrivateKey::generate().context(ks_err!("Failed to generate ECDH key"))?; |
| 745 | ( |
| 746 | key.private_key().context(ks_err!("private_key failed"))?, |
| 747 | Some(key.public_key().context(ks_err!("public_key failed"))?), |
| 748 | ) |
| 749 | } |
| 750 | }; |
| 751 | // Derive an AES-256 key from the password and re-encrypt the super key before we insert it |
| 752 | // in the database. |
| 753 | let (encrypted_super_key, blob_metadata) = |
| 754 | Self::encrypt_with_password(&super_key, password).context(ks_err!())?; |
| 755 | let mut key_metadata = KeyMetaData::new(); |
| 756 | if let Some(pk) = public_key { |
| 757 | key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk)); |
| 758 | } |
| 759 | let key_entry = db |
| 760 | .store_super_key(user_id, key_type, &encrypted_super_key, &blob_metadata, &key_metadata) |
| 761 | .context(ks_err!("Failed to store super key."))?; |
| 762 | Ok(Arc::new(SuperKey { |
| 763 | algorithm: key_type.algorithm, |
| 764 | key: super_key, |
| 765 | id: SuperKeyIdentifier::DatabaseId(key_entry.id()), |
| 766 | reencrypt_with, |
| 767 | })) |
| 768 | } |
| 769 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 770 | /// Fetch a superencryption key from the database, or create it if it doesn't already exist. |
| 771 | /// When this is called, the caller must hold the lock on the SuperKeyManager. |
| 772 | /// So it's OK that the check and creation are different DB transactions. |
| 773 | fn get_or_create_super_key( |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 774 | &mut self, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 775 | db: &mut KeystoreDB, |
| 776 | user_id: UserId, |
| 777 | key_type: &SuperKeyType, |
| 778 | password: &Password, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 779 | reencrypt_with: Option<Arc<SuperKey>>, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 780 | ) -> Result<Arc<SuperKey>> { |
| 781 | let loaded_key = db.load_super_key(key_type, user_id)?; |
| 782 | if let Some((_, key_entry)) = loaded_key { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 783 | Ok(Self::extract_super_key_from_key_entry( |
| 784 | key_type.algorithm, |
| 785 | key_entry, |
| 786 | password, |
| 787 | reencrypt_with, |
| 788 | )?) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 789 | } else { |
Eric Biggers | 456a3a6 | 2023-10-27 03:55:28 +0000 | [diff] [blame] | 790 | self.create_super_key(db, user_id, key_type, password, reencrypt_with) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 791 | } |
| 792 | } |
| 793 | |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 794 | /// Decrypt the UnlockedDeviceRequired super keys for this user using the password and store |
| 795 | /// them in memory. If these keys don't exist yet, create them. |
| 796 | pub fn unlock_unlocked_device_required_keys( |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 797 | &mut self, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 798 | db: &mut KeystoreDB, |
| 799 | user_id: UserId, |
| 800 | password: &Password, |
| 801 | ) -> Result<()> { |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 802 | let (symmetric, private) = self |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 803 | .data |
| 804 | .user_keys |
| 805 | .get(&user_id) |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 806 | .map(|e| { |
| 807 | ( |
| 808 | e.unlocked_device_required_symmetric.clone(), |
| 809 | e.unlocked_device_required_private.clone(), |
| 810 | ) |
| 811 | }) |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 812 | .unwrap_or((None, None)); |
| 813 | |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 814 | if symmetric.is_some() && private.is_some() { |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 815 | // Already unlocked. |
| 816 | return Ok(()); |
| 817 | } |
| 818 | |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 819 | let aes = if let Some(symmetric) = symmetric { |
| 820 | // This is weird. If this point is reached only one of the UnlockedDeviceRequired super |
| 821 | // keys was initialized. This should never happen. |
| 822 | symmetric |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 823 | } else { |
| 824 | self.get_or_create_super_key( |
| 825 | db, |
| 826 | user_id, |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 827 | &USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY, |
| 828 | password, |
| 829 | None, |
| 830 | ) |
| 831 | .context(ks_err!("Trying to get or create symmetric key."))? |
| 832 | }; |
| 833 | |
| 834 | let ecdh = if let Some(private) = private { |
| 835 | // This is weird. If this point is reached only one of the UnlockedDeviceRequired super |
| 836 | // keys was initialized. This should never happen. |
| 837 | private |
| 838 | } else { |
| 839 | self.get_or_create_super_key( |
| 840 | db, |
| 841 | user_id, |
| 842 | &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY, |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 843 | password, |
| 844 | Some(aes.clone()), |
| 845 | ) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 846 | .context(ks_err!("Trying to get or create asymmetric key."))? |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 847 | }; |
| 848 | |
| 849 | self.data.add_key_to_key_index(&aes)?; |
| 850 | self.data.add_key_to_key_index(&ecdh)?; |
| 851 | let entry = self.data.user_keys.entry(user_id).or_default(); |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 852 | entry.unlocked_device_required_symmetric = Some(aes); |
| 853 | entry.unlocked_device_required_private = Some(ecdh); |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 854 | Ok(()) |
| 855 | } |
| 856 | |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 857 | /// Wipe the user's UnlockedDeviceRequired super keys from memory. |
| 858 | pub fn lock_unlocked_device_required_keys( |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 859 | &mut self, |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 860 | db: &mut KeystoreDB, |
| 861 | user_id: UserId, |
| 862 | unlocking_sids: &[i64], |
| 863 | ) { |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 864 | log::info!( |
| 865 | "Locking UnlockedDeviceRequired super keys for user {}; unlocking_sids={:?}", |
| 866 | user_id, |
| 867 | unlocking_sids |
| 868 | ); |
Chris Wailes | 53a22af | 2023-07-12 17:02:47 -0700 | [diff] [blame] | 869 | let entry = self.data.user_keys.entry(user_id).or_default(); |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 870 | if !unlocking_sids.is_empty() { |
| 871 | if let (Some(aes), Some(ecdh)) = ( |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 872 | entry.unlocked_device_required_symmetric.as_ref().cloned(), |
| 873 | entry.unlocked_device_required_private.as_ref().cloned(), |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 874 | ) { |
| 875 | let res = (|| -> Result<()> { |
| 876 | let key_desc = KeyMintDevice::internal_descriptor(format!( |
| 877 | "biometric_unlock_key_{}", |
| 878 | user_id |
| 879 | )); |
| 880 | let encrypting_key = generate_aes256_key()?; |
| 881 | let km_dev: KeyMintDevice = |
| 882 | KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 883 | .context(ks_err!("KeyMintDevice::get failed"))?; |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 884 | let mut key_params = vec![ |
| 885 | KeyParameterValue::Algorithm(Algorithm::AES), |
| 886 | KeyParameterValue::KeySize(256), |
| 887 | KeyParameterValue::BlockMode(BlockMode::GCM), |
| 888 | KeyParameterValue::PaddingMode(PaddingMode::NONE), |
| 889 | KeyParameterValue::CallerNonce, |
| 890 | KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT), |
| 891 | KeyParameterValue::MinMacLength(128), |
| 892 | KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S), |
| 893 | KeyParameterValue::HardwareAuthenticatorType( |
| 894 | HardwareAuthenticatorType::FINGERPRINT, |
| 895 | ), |
| 896 | ]; |
| 897 | for sid in unlocking_sids { |
| 898 | key_params.push(KeyParameterValue::UserSecureID(*sid)); |
| 899 | } |
| 900 | let key_params: Vec<KmKeyParameter> = |
| 901 | key_params.into_iter().map(|x| x.into()).collect(); |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 902 | km_dev.create_and_store_key( |
| 903 | db, |
| 904 | &key_desc, |
| 905 | KeyType::Client, /* TODO Should be Super b/189470584 */ |
| 906 | |dev| { |
| 907 | let _wp = wd::watch_millis( |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 908 | "In lock_unlocked_device_required_keys: calling importKey.", |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 909 | 500, |
| 910 | ); |
| 911 | dev.importKey( |
| 912 | key_params.as_slice(), |
| 913 | KeyFormat::RAW, |
| 914 | &encrypting_key, |
| 915 | None, |
| 916 | ) |
| 917 | }, |
| 918 | )?; |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 919 | entry.biometric_unlock = Some(BiometricUnlock { |
| 920 | sids: unlocking_sids.into(), |
| 921 | key_desc, |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 922 | symmetric: LockedKey::new(&encrypting_key, &aes)?, |
| 923 | private: LockedKey::new(&encrypting_key, &ecdh)?, |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 924 | }); |
| 925 | Ok(()) |
| 926 | })(); |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 927 | // There is no reason to propagate an error here upwards. We must clear the keys |
| 928 | // from memory in any case. |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 929 | if let Err(e) = res { |
| 930 | log::error!("Error setting up biometric unlock: {:#?}", e); |
| 931 | } |
| 932 | } |
| 933 | } |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 934 | entry.unlocked_device_required_symmetric = None; |
| 935 | entry.unlocked_device_required_private = None; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 936 | } |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 937 | |
| 938 | /// User has unlocked, not using a password. See if any of our stored auth tokens can be used |
| 939 | /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys. |
| 940 | pub fn try_unlock_user_with_biometric( |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 941 | &mut self, |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 942 | db: &mut KeystoreDB, |
| 943 | user_id: UserId, |
| 944 | ) -> Result<()> { |
Chris Wailes | 53a22af | 2023-07-12 17:02:47 -0700 | [diff] [blame] | 945 | let entry = self.data.user_keys.entry(user_id).or_default(); |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 946 | if let Some(biometric) = entry.biometric_unlock.as_ref() { |
Janis Danisevskis | acebfa2 | 2021-05-25 10:56:10 -0700 | [diff] [blame] | 947 | let (key_id_guard, key_entry) = db |
| 948 | .load_key_entry( |
| 949 | &biometric.key_desc, |
| 950 | KeyType::Client, // This should not be a Client key. |
| 951 | KeyEntryLoadBits::KM, |
| 952 | AID_KEYSTORE, |
| 953 | |_, _| Ok(()), |
| 954 | ) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 955 | .context(ks_err!("load_key_entry failed"))?; |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 956 | let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 957 | .context(ks_err!("KeyMintDevice::get failed"))?; |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 958 | let mut errs = vec![]; |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 959 | for sid in &biometric.sids { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 960 | let sid = *sid; |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 961 | if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 962 | entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 963 | }) { |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 964 | let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| { |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 965 | let symmetric = biometric.symmetric.decrypt( |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 966 | db, |
| 967 | &km_dev, |
| 968 | &key_id_guard, |
| 969 | &key_entry, |
| 970 | auth_token_entry.auth_token(), |
| 971 | None, |
| 972 | )?; |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 973 | let private = biometric.private.decrypt( |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 974 | db, |
| 975 | &km_dev, |
| 976 | &key_id_guard, |
| 977 | &key_entry, |
| 978 | auth_token_entry.auth_token(), |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 979 | Some(symmetric.clone()), |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 980 | )?; |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 981 | Ok((symmetric, private)) |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 982 | })(); |
| 983 | match res { |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 984 | Ok((symmetric, private)) => { |
| 985 | entry.unlocked_device_required_symmetric = Some(symmetric.clone()); |
| 986 | entry.unlocked_device_required_private = Some(private.clone()); |
| 987 | self.data.add_key_to_key_index(&symmetric)?; |
| 988 | self.data.add_key_to_key_index(&private)?; |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 989 | log::info!("Successfully unlocked user {user_id} with biometric {sid}",); |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 990 | return Ok(()); |
| 991 | } |
| 992 | Err(e) => { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 993 | // Don't log an error yet, as some other biometric SID might work. |
| 994 | errs.push((sid, e)); |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 995 | } |
| 996 | } |
| 997 | } |
| 998 | } |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 999 | if !errs.is_empty() { |
| 1000 | log::warn!("biometric unlock failed for all SIDs, with errors:"); |
| 1001 | for (sid, err) in errs { |
| 1002 | log::warn!(" biometric {sid}: {err}"); |
| 1003 | } |
| 1004 | } |
Paul Crowley | 618869e | 2021-04-08 20:30:54 -0700 | [diff] [blame] | 1005 | } |
| 1006 | Ok(()) |
| 1007 | } |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1008 | |
| 1009 | /// Returns the keystore locked state of the given user. It requires the thread local |
| 1010 | /// 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] | 1011 | /// 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] | 1012 | pub fn get_user_state( |
| 1013 | &self, |
| 1014 | db: &mut KeystoreDB, |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 1015 | legacy_importer: &LegacyImporter, |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1016 | user_id: UserId, |
| 1017 | ) -> Result<UserState> { |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1018 | match self.get_after_first_unlock_key_by_user_id_internal(user_id) { |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1019 | Some(super_key) => Ok(UserState::AfterFirstUnlock(super_key)), |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1020 | None => { |
| 1021 | // Check if a super key exists in the database or legacy database. |
| 1022 | // If so, return locked user state. |
| 1023 | if self |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 1024 | .super_key_exists_in_db_for_user(db, legacy_importer, user_id) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 1025 | .context(ks_err!())? |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1026 | { |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1027 | Ok(UserState::BeforeFirstUnlock) |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1028 | } else { |
| 1029 | Ok(UserState::Uninitialized) |
| 1030 | } |
| 1031 | } |
| 1032 | } |
| 1033 | } |
| 1034 | |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1035 | /// Deletes all keys and super keys for the given user. |
| 1036 | /// This is called when a user is deleted. |
| 1037 | pub fn remove_user( |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1038 | &mut self, |
| 1039 | db: &mut KeystoreDB, |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 1040 | legacy_importer: &LegacyImporter, |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1041 | user_id: UserId, |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1042 | ) -> Result<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 1043 | log::info!("remove_user(user={user_id})"); |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1044 | // Mark keys created on behalf of the user as unreferenced. |
| 1045 | legacy_importer |
| 1046 | .bulk_delete_user(user_id, false) |
| 1047 | .context(ks_err!("Trying to delete legacy keys."))?; |
| 1048 | db.unbind_keys_for_user(user_id, false).context(ks_err!("Error in unbinding keys."))?; |
| 1049 | |
| 1050 | // Delete super key in cache, if exists. |
| 1051 | self.forget_all_keys_for_user(user_id); |
| 1052 | Ok(()) |
| 1053 | } |
| 1054 | |
| 1055 | /// Deletes all authentication bound keys and super keys for the given user. The user must be |
| 1056 | /// unlocked before this function is called. This function is used to transition a user to |
| 1057 | /// swipe. |
| 1058 | pub fn reset_user( |
| 1059 | &mut self, |
| 1060 | db: &mut KeystoreDB, |
| 1061 | legacy_importer: &LegacyImporter, |
| 1062 | user_id: UserId, |
| 1063 | ) -> Result<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 1064 | log::info!("reset_user(user={user_id})"); |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1065 | match self.get_user_state(db, legacy_importer, user_id)? { |
| 1066 | UserState::Uninitialized => { |
| 1067 | Err(Error::sys()).context(ks_err!("Tried to reset an uninitialized user!")) |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1068 | } |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1069 | UserState::BeforeFirstUnlock => { |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1070 | Err(Error::sys()).context(ks_err!("Tried to reset a locked user's password!")) |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1071 | } |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1072 | UserState::AfterFirstUnlock(_) => { |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1073 | // Mark keys created on behalf of the user as unreferenced. |
| 1074 | legacy_importer |
| 1075 | .bulk_delete_user(user_id, true) |
| 1076 | .context(ks_err!("Trying to delete legacy keys."))?; |
| 1077 | db.unbind_keys_for_user(user_id, true) |
| 1078 | .context(ks_err!("Error in unbinding keys."))?; |
| 1079 | |
| 1080 | // Delete super key in cache, if exists. |
| 1081 | self.forget_all_keys_for_user(user_id); |
| 1082 | Ok(()) |
| 1083 | } |
| 1084 | } |
| 1085 | } |
| 1086 | |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1087 | /// If the user hasn't been initialized yet, then this function generates the user's |
| 1088 | /// AfterFirstUnlock super key and sets the user's state to AfterFirstUnlock. Otherwise this |
| 1089 | /// function returns an error. |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1090 | pub fn init_user( |
| 1091 | &mut self, |
| 1092 | db: &mut KeystoreDB, |
| 1093 | legacy_importer: &LegacyImporter, |
| 1094 | user_id: UserId, |
| 1095 | password: &Password, |
| 1096 | ) -> Result<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 1097 | log::info!("init_user(user={user_id})"); |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1098 | match self.get_user_state(db, legacy_importer, user_id)? { |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1099 | UserState::AfterFirstUnlock(_) | UserState::BeforeFirstUnlock => { |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1100 | Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!")) |
| 1101 | } |
| 1102 | UserState::Uninitialized => { |
| 1103 | // Generate a new super key. |
| 1104 | let super_key = |
| 1105 | generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?; |
| 1106 | // Derive an AES256 key from the password and re-encrypt the super key |
| 1107 | // before we insert it in the database. |
| 1108 | let (encrypted_super_key, blob_metadata) = |
| 1109 | Self::encrypt_with_password(&super_key, password) |
| 1110 | .context(ks_err!("Failed to encrypt super key with password!"))?; |
| 1111 | |
| 1112 | let key_entry = db |
| 1113 | .store_super_key( |
| 1114 | user_id, |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1115 | &USER_AFTER_FIRST_UNLOCK_SUPER_KEY, |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1116 | &encrypted_super_key, |
| 1117 | &blob_metadata, |
| 1118 | &KeyMetaData::new(), |
| 1119 | ) |
| 1120 | .context(ks_err!("Failed to store super key."))?; |
| 1121 | |
| 1122 | self.populate_cache_from_super_key_blob( |
| 1123 | user_id, |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1124 | USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm, |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 1125 | key_entry, |
| 1126 | password, |
| 1127 | ) |
| 1128 | .context(ks_err!("Failed to initialize user!"))?; |
| 1129 | Ok(()) |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1130 | } |
| 1131 | } |
| 1132 | } |
| 1133 | |
Nathan Huckleberry | 7dfe818 | 2023-04-04 20:41:01 +0000 | [diff] [blame] | 1134 | /// Unlocks the given user with the given password. |
| 1135 | /// |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1136 | /// If the user state is BeforeFirstUnlock: |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1137 | /// - Unlock the user's AfterFirstUnlock super key |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1138 | /// - Unlock the user's UnlockedDeviceRequired super keys |
Nathan Huckleberry | 7dfe818 | 2023-04-04 20:41:01 +0000 | [diff] [blame] | 1139 | /// |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1140 | /// If the user state is AfterFirstUnlock: |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1141 | /// - Unlock the user's UnlockedDeviceRequired super keys only |
Nathan Huckleberry | 7dfe818 | 2023-04-04 20:41:01 +0000 | [diff] [blame] | 1142 | /// |
| 1143 | pub fn unlock_user( |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1144 | &mut self, |
| 1145 | db: &mut KeystoreDB, |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 1146 | legacy_importer: &LegacyImporter, |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1147 | user_id: UserId, |
| 1148 | password: &Password, |
Nathan Huckleberry | 7dfe818 | 2023-04-04 20:41:01 +0000 | [diff] [blame] | 1149 | ) -> Result<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 1150 | log::info!("unlock_user(user={user_id})"); |
Nathan Huckleberry | 7dfe818 | 2023-04-04 20:41:01 +0000 | [diff] [blame] | 1151 | match self.get_user_state(db, legacy_importer, user_id)? { |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1152 | UserState::AfterFirstUnlock(_) => { |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1153 | self.unlock_unlocked_device_required_keys(db, user_id, password) |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1154 | } |
Nathan Huckleberry | 7dfe818 | 2023-04-04 20:41:01 +0000 | [diff] [blame] | 1155 | UserState::Uninitialized => { |
| 1156 | Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!")) |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1157 | } |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1158 | UserState::BeforeFirstUnlock => { |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1159 | let alias = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY; |
Nathan Huckleberry | 7dfe818 | 2023-04-04 20:41:01 +0000 | [diff] [blame] | 1160 | let result = legacy_importer |
| 1161 | .with_try_import_super_key(user_id, password, || { |
| 1162 | db.load_super_key(alias, user_id) |
| 1163 | }) |
| 1164 | .context(ks_err!("Failed to load super key"))?; |
| 1165 | |
| 1166 | match result { |
| 1167 | Some((_, entry)) => { |
| 1168 | self.populate_cache_from_super_key_blob( |
| 1169 | user_id, |
| 1170 | alias.algorithm, |
| 1171 | entry, |
| 1172 | password, |
| 1173 | ) |
| 1174 | .context(ks_err!("Failed when unlocking user."))?; |
Eric Biggers | b1f641d | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1175 | self.unlock_unlocked_device_required_keys(db, user_id, password) |
Nathan Huckleberry | 7dfe818 | 2023-04-04 20:41:01 +0000 | [diff] [blame] | 1176 | } |
| 1177 | None => { |
| 1178 | Err(Error::sys()).context(ks_err!("Locked user does not have a super key!")) |
| 1179 | } |
| 1180 | } |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 1181 | } |
| 1182 | } |
| 1183 | } |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1184 | } |
| 1185 | |
| 1186 | /// This enum represents different states of the user's life cycle in the device. |
| 1187 | /// For now, only three states are defined. More states may be added later. |
| 1188 | pub enum UserState { |
| 1189 | // The user has registered LSKF and has unlocked the device by entering PIN/Password, |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1190 | // and hence the AfterFirstUnlock super key is available in the cache. |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1191 | AfterFirstUnlock(Arc<SuperKey>), |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1192 | // The user has registered LSKF, but has not unlocked the device using password, after reboot. |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1193 | // Hence the AfterFirstUnlock and UnlockedDeviceRequired super keys are not available in the |
| 1194 | // cache. However, they exist in the database in encrypted form. |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1195 | BeforeFirstUnlock, |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1196 | // There's no user in the device for the given user id, or the user with the user id has not |
| 1197 | // setup LSKF. |
| 1198 | Uninitialized, |
| 1199 | } |
| 1200 | |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 1201 | /// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption. |
| 1202 | /// `Sensitive` holds the non encrypted key and a reference to its super key. |
| 1203 | /// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted. |
| 1204 | /// `Ref` holds a reference to a key blob when it does not need to be modified if its |
| 1205 | /// life time allows it. |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1206 | pub enum KeyBlob<'a> { |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 1207 | Sensitive { |
| 1208 | key: ZVec, |
| 1209 | /// If KeyMint reports that the key must be upgraded, we must |
| 1210 | /// re-encrypt the key before writing to the database; we use |
| 1211 | /// this key. |
| 1212 | reencrypt_with: Arc<SuperKey>, |
| 1213 | /// If this key was decrypted with an ECDH key, we want to |
| 1214 | /// re-encrypt it on first use whether it was upgraded or not; |
| 1215 | /// this field indicates that that's necessary. |
| 1216 | force_reencrypt: bool, |
| 1217 | }, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1218 | NonSensitive(Vec<u8>), |
| 1219 | Ref(&'a [u8]), |
| 1220 | } |
| 1221 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 1222 | impl<'a> KeyBlob<'a> { |
| 1223 | pub fn force_reencrypt(&self) -> bool { |
| 1224 | if let KeyBlob::Sensitive { force_reencrypt, .. } = self { |
| 1225 | *force_reencrypt |
| 1226 | } else { |
| 1227 | false |
| 1228 | } |
| 1229 | } |
| 1230 | } |
| 1231 | |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 1232 | /// Deref returns a reference to the key material in any variant. |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1233 | impl<'a> Deref for KeyBlob<'a> { |
| 1234 | type Target = [u8]; |
| 1235 | |
| 1236 | fn deref(&self) -> &Self::Target { |
| 1237 | match self { |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1238 | Self::Sensitive { key, .. } => key, |
| 1239 | Self::NonSensitive(key) => key, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1240 | Self::Ref(key) => key, |
| 1241 | } |
| 1242 | } |
| 1243 | } |
Nathan Huckleberry | 95dca01 | 2023-05-10 18:02:11 +0000 | [diff] [blame] | 1244 | |
| 1245 | #[cfg(test)] |
| 1246 | mod tests { |
| 1247 | use super::*; |
| 1248 | use crate::database::tests::make_bootlevel_key_entry; |
| 1249 | use crate::database::tests::make_test_key_entry; |
| 1250 | use crate::database::tests::new_test_db; |
| 1251 | use rand::prelude::*; |
| 1252 | const USER_ID: u32 = 0; |
| 1253 | const TEST_KEY_ALIAS: &str = "TEST_KEY"; |
| 1254 | const TEST_BOOT_KEY_ALIAS: &str = "TEST_BOOT_KEY"; |
| 1255 | |
| 1256 | pub fn generate_password_blob() -> Password<'static> { |
| 1257 | let mut rng = rand::thread_rng(); |
| 1258 | let mut password = vec![0u8; 64]; |
| 1259 | rng.fill_bytes(&mut password); |
| 1260 | |
| 1261 | let mut zvec = ZVec::new(64).expect("Failed to create ZVec"); |
| 1262 | zvec[..].copy_from_slice(&password[..]); |
| 1263 | |
| 1264 | Password::Owned(zvec) |
| 1265 | } |
| 1266 | |
| 1267 | fn setup_test(pw: &Password) -> (Arc<RwLock<SuperKeyManager>>, KeystoreDB, LegacyImporter) { |
| 1268 | let mut keystore_db = new_test_db().unwrap(); |
| 1269 | let mut legacy_importer = LegacyImporter::new(Arc::new(Default::default())); |
| 1270 | legacy_importer.set_empty(); |
| 1271 | let skm: Arc<RwLock<SuperKeyManager>> = Default::default(); |
| 1272 | assert!(skm |
| 1273 | .write() |
| 1274 | .unwrap() |
| 1275 | .init_user(&mut keystore_db, &legacy_importer, USER_ID, pw) |
| 1276 | .is_ok()); |
| 1277 | (skm, keystore_db, legacy_importer) |
| 1278 | } |
| 1279 | |
| 1280 | fn assert_unlocked( |
| 1281 | skm: &Arc<RwLock<SuperKeyManager>>, |
| 1282 | keystore_db: &mut KeystoreDB, |
| 1283 | legacy_importer: &LegacyImporter, |
| 1284 | user_id: u32, |
| 1285 | err_msg: &str, |
| 1286 | ) { |
| 1287 | let user_state = |
| 1288 | skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap(); |
| 1289 | match user_state { |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1290 | UserState::AfterFirstUnlock(_) => {} |
Nathan Huckleberry | 95dca01 | 2023-05-10 18:02:11 +0000 | [diff] [blame] | 1291 | _ => panic!("{}", err_msg), |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | fn assert_locked( |
| 1296 | skm: &Arc<RwLock<SuperKeyManager>>, |
| 1297 | keystore_db: &mut KeystoreDB, |
| 1298 | legacy_importer: &LegacyImporter, |
| 1299 | user_id: u32, |
| 1300 | err_msg: &str, |
| 1301 | ) { |
| 1302 | let user_state = |
| 1303 | skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap(); |
| 1304 | match user_state { |
Eric Biggers | 1386937 | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 1305 | UserState::BeforeFirstUnlock => {} |
Nathan Huckleberry | 95dca01 | 2023-05-10 18:02:11 +0000 | [diff] [blame] | 1306 | _ => panic!("{}", err_msg), |
| 1307 | } |
| 1308 | } |
| 1309 | |
| 1310 | fn assert_uninitialized( |
| 1311 | skm: &Arc<RwLock<SuperKeyManager>>, |
| 1312 | keystore_db: &mut KeystoreDB, |
| 1313 | legacy_importer: &LegacyImporter, |
| 1314 | user_id: u32, |
| 1315 | err_msg: &str, |
| 1316 | ) { |
| 1317 | let user_state = |
| 1318 | skm.write().unwrap().get_user_state(keystore_db, legacy_importer, user_id).unwrap(); |
| 1319 | match user_state { |
| 1320 | UserState::Uninitialized => {} |
| 1321 | _ => panic!("{}", err_msg), |
| 1322 | } |
| 1323 | } |
| 1324 | |
| 1325 | #[test] |
| 1326 | fn test_init_user() { |
| 1327 | let pw: Password = generate_password_blob(); |
| 1328 | let (skm, mut keystore_db, legacy_importer) = setup_test(&pw); |
| 1329 | assert_unlocked( |
| 1330 | &skm, |
| 1331 | &mut keystore_db, |
| 1332 | &legacy_importer, |
| 1333 | USER_ID, |
| 1334 | "The user was not unlocked after initialization!", |
| 1335 | ); |
| 1336 | } |
| 1337 | |
| 1338 | #[test] |
| 1339 | fn test_unlock_user() { |
| 1340 | let pw: Password = generate_password_blob(); |
| 1341 | let (skm, mut keystore_db, legacy_importer) = setup_test(&pw); |
| 1342 | assert_unlocked( |
| 1343 | &skm, |
| 1344 | &mut keystore_db, |
| 1345 | &legacy_importer, |
| 1346 | USER_ID, |
| 1347 | "The user was not unlocked after initialization!", |
| 1348 | ); |
| 1349 | |
| 1350 | skm.write().unwrap().data.user_keys.clear(); |
| 1351 | assert_locked( |
| 1352 | &skm, |
| 1353 | &mut keystore_db, |
| 1354 | &legacy_importer, |
| 1355 | USER_ID, |
| 1356 | "Clearing the cache did not lock the user!", |
| 1357 | ); |
| 1358 | |
| 1359 | assert!(skm |
| 1360 | .write() |
| 1361 | .unwrap() |
| 1362 | .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw) |
| 1363 | .is_ok()); |
| 1364 | assert_unlocked( |
| 1365 | &skm, |
| 1366 | &mut keystore_db, |
| 1367 | &legacy_importer, |
| 1368 | USER_ID, |
| 1369 | "The user did not unlock!", |
| 1370 | ); |
| 1371 | } |
| 1372 | |
| 1373 | #[test] |
| 1374 | fn test_unlock_wrong_password() { |
| 1375 | let pw: Password = generate_password_blob(); |
| 1376 | let wrong_pw: Password = generate_password_blob(); |
| 1377 | let (skm, mut keystore_db, legacy_importer) = setup_test(&pw); |
| 1378 | assert_unlocked( |
| 1379 | &skm, |
| 1380 | &mut keystore_db, |
| 1381 | &legacy_importer, |
| 1382 | USER_ID, |
| 1383 | "The user was not unlocked after initialization!", |
| 1384 | ); |
| 1385 | |
| 1386 | skm.write().unwrap().data.user_keys.clear(); |
| 1387 | assert_locked( |
| 1388 | &skm, |
| 1389 | &mut keystore_db, |
| 1390 | &legacy_importer, |
| 1391 | USER_ID, |
| 1392 | "Clearing the cache did not lock the user!", |
| 1393 | ); |
| 1394 | |
| 1395 | assert!(skm |
| 1396 | .write() |
| 1397 | .unwrap() |
| 1398 | .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &wrong_pw) |
| 1399 | .is_err()); |
| 1400 | assert_locked( |
| 1401 | &skm, |
| 1402 | &mut keystore_db, |
| 1403 | &legacy_importer, |
| 1404 | USER_ID, |
| 1405 | "The user was unlocked with an incorrect password!", |
| 1406 | ); |
| 1407 | } |
| 1408 | |
| 1409 | #[test] |
| 1410 | fn test_unlock_user_idempotent() { |
| 1411 | let pw: Password = generate_password_blob(); |
| 1412 | let (skm, mut keystore_db, legacy_importer) = setup_test(&pw); |
| 1413 | assert_unlocked( |
| 1414 | &skm, |
| 1415 | &mut keystore_db, |
| 1416 | &legacy_importer, |
| 1417 | USER_ID, |
| 1418 | "The user was not unlocked after initialization!", |
| 1419 | ); |
| 1420 | |
| 1421 | skm.write().unwrap().data.user_keys.clear(); |
| 1422 | assert_locked( |
| 1423 | &skm, |
| 1424 | &mut keystore_db, |
| 1425 | &legacy_importer, |
| 1426 | USER_ID, |
| 1427 | "Clearing the cache did not lock the user!", |
| 1428 | ); |
| 1429 | |
| 1430 | for _ in 0..5 { |
| 1431 | assert!(skm |
| 1432 | .write() |
| 1433 | .unwrap() |
| 1434 | .unlock_user(&mut keystore_db, &legacy_importer, USER_ID, &pw) |
| 1435 | .is_ok()); |
| 1436 | assert_unlocked( |
| 1437 | &skm, |
| 1438 | &mut keystore_db, |
| 1439 | &legacy_importer, |
| 1440 | USER_ID, |
| 1441 | "The user did not unlock!", |
| 1442 | ); |
| 1443 | } |
| 1444 | } |
| 1445 | |
| 1446 | fn test_user_removal(locked: bool) { |
| 1447 | let pw: Password = generate_password_blob(); |
| 1448 | let (skm, mut keystore_db, legacy_importer) = setup_test(&pw); |
| 1449 | assert_unlocked( |
| 1450 | &skm, |
| 1451 | &mut keystore_db, |
| 1452 | &legacy_importer, |
| 1453 | USER_ID, |
| 1454 | "The user was not unlocked after initialization!", |
| 1455 | ); |
| 1456 | |
| 1457 | assert!(make_test_key_entry( |
| 1458 | &mut keystore_db, |
| 1459 | Domain::APP, |
| 1460 | USER_ID.into(), |
| 1461 | TEST_KEY_ALIAS, |
| 1462 | None |
| 1463 | ) |
| 1464 | .is_ok()); |
| 1465 | assert!(make_bootlevel_key_entry( |
| 1466 | &mut keystore_db, |
| 1467 | Domain::APP, |
| 1468 | USER_ID.into(), |
| 1469 | TEST_BOOT_KEY_ALIAS, |
| 1470 | false |
| 1471 | ) |
| 1472 | .is_ok()); |
| 1473 | |
| 1474 | assert!(keystore_db |
| 1475 | .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client) |
| 1476 | .unwrap()); |
| 1477 | assert!(keystore_db |
| 1478 | .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client) |
| 1479 | .unwrap()); |
| 1480 | |
| 1481 | if locked { |
| 1482 | skm.write().unwrap().data.user_keys.clear(); |
| 1483 | assert_locked( |
| 1484 | &skm, |
| 1485 | &mut keystore_db, |
| 1486 | &legacy_importer, |
| 1487 | USER_ID, |
| 1488 | "Clearing the cache did not lock the user!", |
| 1489 | ); |
| 1490 | } |
| 1491 | |
| 1492 | assert!(skm |
| 1493 | .write() |
| 1494 | .unwrap() |
| 1495 | .remove_user(&mut keystore_db, &legacy_importer, USER_ID) |
| 1496 | .is_ok()); |
| 1497 | assert_uninitialized( |
| 1498 | &skm, |
| 1499 | &mut keystore_db, |
| 1500 | &legacy_importer, |
| 1501 | USER_ID, |
| 1502 | "The user was not removed!", |
| 1503 | ); |
| 1504 | |
| 1505 | assert!(!skm |
| 1506 | .write() |
| 1507 | .unwrap() |
| 1508 | .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID) |
| 1509 | .unwrap()); |
| 1510 | |
| 1511 | assert!(!keystore_db |
| 1512 | .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client) |
| 1513 | .unwrap()); |
| 1514 | assert!(!keystore_db |
| 1515 | .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client) |
| 1516 | .unwrap()); |
| 1517 | } |
| 1518 | |
| 1519 | fn test_user_reset(locked: bool) { |
| 1520 | let pw: Password = generate_password_blob(); |
| 1521 | let (skm, mut keystore_db, legacy_importer) = setup_test(&pw); |
| 1522 | assert_unlocked( |
| 1523 | &skm, |
| 1524 | &mut keystore_db, |
| 1525 | &legacy_importer, |
| 1526 | USER_ID, |
| 1527 | "The user was not unlocked after initialization!", |
| 1528 | ); |
| 1529 | |
| 1530 | assert!(make_test_key_entry( |
| 1531 | &mut keystore_db, |
| 1532 | Domain::APP, |
| 1533 | USER_ID.into(), |
| 1534 | TEST_KEY_ALIAS, |
| 1535 | None |
| 1536 | ) |
| 1537 | .is_ok()); |
| 1538 | assert!(make_bootlevel_key_entry( |
| 1539 | &mut keystore_db, |
| 1540 | Domain::APP, |
| 1541 | USER_ID.into(), |
| 1542 | TEST_BOOT_KEY_ALIAS, |
| 1543 | false |
| 1544 | ) |
| 1545 | .is_ok()); |
| 1546 | assert!(keystore_db |
| 1547 | .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client) |
| 1548 | .unwrap()); |
| 1549 | assert!(keystore_db |
| 1550 | .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client) |
| 1551 | .unwrap()); |
| 1552 | |
| 1553 | if locked { |
| 1554 | skm.write().unwrap().data.user_keys.clear(); |
| 1555 | assert_locked( |
| 1556 | &skm, |
| 1557 | &mut keystore_db, |
| 1558 | &legacy_importer, |
| 1559 | USER_ID, |
| 1560 | "Clearing the cache did not lock the user!", |
| 1561 | ); |
| 1562 | assert!(skm |
| 1563 | .write() |
| 1564 | .unwrap() |
| 1565 | .reset_user(&mut keystore_db, &legacy_importer, USER_ID) |
| 1566 | .is_err()); |
| 1567 | assert_locked( |
| 1568 | &skm, |
| 1569 | &mut keystore_db, |
| 1570 | &legacy_importer, |
| 1571 | USER_ID, |
| 1572 | "User state should not have changed!", |
| 1573 | ); |
| 1574 | |
| 1575 | // Keys should still exist. |
| 1576 | assert!(keystore_db |
| 1577 | .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client) |
| 1578 | .unwrap()); |
| 1579 | assert!(keystore_db |
| 1580 | .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client) |
| 1581 | .unwrap()); |
| 1582 | } else { |
| 1583 | assert!(skm |
| 1584 | .write() |
| 1585 | .unwrap() |
| 1586 | .reset_user(&mut keystore_db, &legacy_importer, USER_ID) |
| 1587 | .is_ok()); |
| 1588 | assert_uninitialized( |
| 1589 | &skm, |
| 1590 | &mut keystore_db, |
| 1591 | &legacy_importer, |
| 1592 | USER_ID, |
| 1593 | "The user was not reset!", |
| 1594 | ); |
| 1595 | assert!(!skm |
| 1596 | .write() |
| 1597 | .unwrap() |
| 1598 | .super_key_exists_in_db_for_user(&mut keystore_db, &legacy_importer, USER_ID) |
| 1599 | .unwrap()); |
| 1600 | |
| 1601 | // Auth bound key should no longer exist. |
| 1602 | assert!(!keystore_db |
| 1603 | .key_exists(Domain::APP, USER_ID.into(), TEST_KEY_ALIAS, KeyType::Client) |
| 1604 | .unwrap()); |
| 1605 | assert!(keystore_db |
| 1606 | .key_exists(Domain::APP, USER_ID.into(), TEST_BOOT_KEY_ALIAS, KeyType::Client) |
| 1607 | .unwrap()); |
| 1608 | } |
| 1609 | } |
| 1610 | |
| 1611 | #[test] |
| 1612 | fn test_remove_unlocked_user() { |
| 1613 | test_user_removal(false); |
| 1614 | } |
| 1615 | |
| 1616 | #[test] |
| 1617 | fn test_remove_locked_user() { |
| 1618 | test_user_removal(true); |
| 1619 | } |
| 1620 | |
| 1621 | #[test] |
| 1622 | fn test_reset_unlocked_user() { |
| 1623 | test_user_reset(false); |
| 1624 | } |
| 1625 | |
| 1626 | #[test] |
| 1627 | fn test_reset_locked_user() { |
| 1628 | test_user_reset(true); |
| 1629 | } |
| 1630 | } |