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