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