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