blob: fc825387ab0995184ca32f22ee9f10253310465e [file] [log] [blame]
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001// 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 Danisevskisb42fc182020-12-15 08:41:27 -080015use crate::{
Paul Crowley44c02da2021-04-08 17:04:43 +000016 boot_level_keys::{get_level_zero_key, BootLevelKeyCache},
Paul Crowley8d5b2532021-03-19 10:53:07 -070017 database::BlobMetaData,
18 database::BlobMetaEntry,
19 database::EncryptedBy,
20 database::KeyEntry,
21 database::KeyType,
Janis Danisevskisacebfa22021-05-25 10:56:10 -070022 database::{KeyEntryLoadBits, KeyIdGuard, KeyMetaData, KeyMetaEntry, KeystoreDB},
Paul Crowley8d5b2532021-03-19 10:53:07 -070023 ec_crypto::ECDHPrivateKey,
24 enforcements::Enforcements,
25 error::Error,
26 error::ResponseCode,
Paul Crowley618869e2021-04-08 20:30:54 -070027 key_parameter::{KeyParameter, KeyParameterValue},
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000028 ks_err,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080029 legacy_importer::LegacyImporter,
Paul Crowley618869e2021-04-08 20:30:54 -070030 raw_device::KeyMintDevice,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080031 utils::{watchdog as wd, AesGcm, AID_KEYSTORE},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080032};
Paul Crowley618869e2021-04-08 20:30:54 -070033use 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};
39use android_system_keystore2::aidl::android::system::keystore2::{
40 Domain::Domain, KeyDescriptor::KeyDescriptor,
41};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080042use anyhow::{Context, Result};
43use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070044 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
45 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046};
Joel Galenson7ead3a22021-07-29 15:27:34 -070047use rustutils::system_properties::PropertyWatcher;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080048use std::{
49 collections::HashMap,
50 sync::Arc,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080051 sync::{Mutex, RwLock, Weak},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080052};
Paul Crowley618869e2021-04-08 20:30:54 -070053use std::{convert::TryFrom, ops::Deref};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080054
Paul Crowley44c02da2021-04-08 17:04:43 +000055const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
Paul Crowley618869e2021-04-08 20:30:54 -070056/// Allow up to 15 seconds between the user unlocking using a biometric, and the auth
57/// token being used to unlock in [`SuperKeyManager::try_unlock_user_with_biometric`].
58/// This seems short enough for security purposes, while long enough that even the
59/// very slowest device will present the auth token in time.
60const BIOMETRIC_AUTH_TIMEOUT_S: i32 = 15; // seconds
Paul Crowley44c02da2021-04-08 17:04:43 +000061
Janis Danisevskisb42fc182020-12-15 08:41:27 -080062type UserId = u32;
63
Paul Crowley8d5b2532021-03-19 10:53:07 -070064/// Encryption algorithm used by a particular type of superencryption key
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum SuperEncryptionAlgorithm {
67 /// Symmetric encryption with AES-256-GCM
68 Aes256Gcm,
Paul Crowley52f017f2021-06-22 08:16:01 -070069 /// Public-key encryption with ECDH P-521
70 EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -070071}
72
Paul Crowley7a658392021-03-18 17:08:20 -070073/// A particular user may have several superencryption keys in the database, each for a
74/// different purpose, distinguished by alias. Each is associated with a static
75/// constant of this type.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080076pub struct SuperKeyType<'a> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -080077 /// Alias used to look up the key in the `persistent.keyentry` table.
Janis Danisevskis11bd2592022-01-04 19:59:26 -080078 pub alias: &'a str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070079 /// Encryption algorithm
80 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070081}
82
83/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
84/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070085pub const USER_SUPER_KEY: SuperKeyType =
86 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070087/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
88/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070089/// Symmetric.
90pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
91 alias: "USER_SCREEN_LOCK_BOUND_KEY",
92 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
93};
94/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
95/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
96/// Asymmetric, so keys can be encrypted when the device is locked.
Paul Crowley52f017f2021-06-22 08:16:01 -070097pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
98 alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
99 algorithm: SuperEncryptionAlgorithm::EcdhP521,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700100};
Paul Crowley7a658392021-03-18 17:08:20 -0700101
102/// Superencryption to apply to a new key.
103#[derive(Debug, Clone, Copy)]
104pub enum SuperEncryptionType {
105 /// Do not superencrypt this key.
106 None,
107 /// Superencrypt with a key that remains in memory from first unlock to reboot.
108 LskfBound,
109 /// Superencrypt with a key cleared from memory when the device is locked.
110 ScreenLockBound,
Paul Crowley44c02da2021-04-08 17:04:43 +0000111 /// Superencrypt with a key based on the desired boot level
112 BootLevel(i32),
113}
114
115#[derive(Debug, Clone, Copy)]
116pub enum SuperKeyIdentifier {
117 /// id of the super key in the database.
118 DatabaseId(i64),
119 /// Boot level of the encrypting boot level key
120 BootLevel(i32),
121}
122
123impl SuperKeyIdentifier {
124 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
125 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
126 Some(SuperKeyIdentifier::DatabaseId(*key_id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000127 } else {
Chris Wailesfe0abfe2021-07-21 11:39:57 -0700128 metadata.max_boot_level().map(|boot_level| SuperKeyIdentifier::BootLevel(*boot_level))
Paul Crowley44c02da2021-04-08 17:04:43 +0000129 }
130 }
131
132 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
133 match self {
134 SuperKeyIdentifier::DatabaseId(id) => {
135 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
136 }
137 SuperKeyIdentifier::BootLevel(level) => {
138 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
139 }
140 }
141 }
Paul Crowley7a658392021-03-18 17:08:20 -0700142}
143
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000144pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700145 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700146 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000147 /// Identifier of the encrypting key, used to write an encrypted blob
148 /// back to the database after re-encryption eg on a key update.
149 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700150 /// ECDH is more expensive than AES. So on ECDH private keys we set the
151 /// reencrypt_with field to point at the corresponding AES key, and the
152 /// keys will be re-encrypted with AES on first use.
153 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000154}
155
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800156impl AesGcm for SuperKey {
157 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700158 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000159 aes_gcm_decrypt(data, iv, tag, &self.key).context(ks_err!("Decryption failed."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700160 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000161 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800162 }
163 }
164
165 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
166 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000167 aes_gcm_encrypt(plaintext, &self.key).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800168 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000169 Err(Error::sys()).context(ks_err!("Key is not an AES key."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700170 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000171 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700172}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000173
Paul Crowley618869e2021-04-08 20:30:54 -0700174/// A SuperKey that has been encrypted with an AES-GCM key. For
175/// encryption the key is in memory, and for decryption it is in KM.
176struct LockedKey {
177 algorithm: SuperEncryptionAlgorithm,
178 id: SuperKeyIdentifier,
179 nonce: Vec<u8>,
180 ciphertext: Vec<u8>, // with tag appended
181}
182
183impl LockedKey {
184 fn new(key: &[u8], to_encrypt: &Arc<SuperKey>) -> Result<Self> {
185 let (mut ciphertext, nonce, mut tag) = aes_gcm_encrypt(&to_encrypt.key, key)?;
186 ciphertext.append(&mut tag);
187 Ok(LockedKey { algorithm: to_encrypt.algorithm, id: to_encrypt.id, nonce, ciphertext })
188 }
189
190 fn decrypt(
191 &self,
192 db: &mut KeystoreDB,
193 km_dev: &KeyMintDevice,
194 key_id_guard: &KeyIdGuard,
195 key_entry: &KeyEntry,
196 auth_token: &HardwareAuthToken,
197 reencrypt_with: Option<Arc<SuperKey>>,
198 ) -> Result<Arc<SuperKey>> {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700199 let key_blob = key_entry
200 .key_blob_info()
201 .as_ref()
202 .map(|(key_blob, _)| KeyBlob::Ref(key_blob))
203 .ok_or(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000204 .context(ks_err!("Missing key blob info."))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700205 let key_params = vec![
206 KeyParameterValue::Algorithm(Algorithm::AES),
207 KeyParameterValue::KeySize(256),
208 KeyParameterValue::BlockMode(BlockMode::GCM),
209 KeyParameterValue::PaddingMode(PaddingMode::NONE),
210 KeyParameterValue::Nonce(self.nonce.clone()),
211 KeyParameterValue::MacLength(128),
212 ];
213 let key_params: Vec<KmKeyParameter> = key_params.into_iter().map(|x| x.into()).collect();
214 let key = ZVec::try_from(km_dev.use_key_in_one_step(
215 db,
216 key_id_guard,
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700217 &key_blob,
Paul Crowley618869e2021-04-08 20:30:54 -0700218 KeyPurpose::DECRYPT,
219 &key_params,
220 Some(auth_token),
221 &self.ciphertext,
222 )?)?;
223 Ok(Arc::new(SuperKey { algorithm: self.algorithm, key, id: self.id, reencrypt_with }))
224 }
225}
226
227/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
228/// a database descriptor for the encrypting key and the sids for the auth tokens
229/// that can be used to decrypt it.
230struct BiometricUnlock {
231 /// List of auth token SIDs that can be used to unlock these keys.
232 sids: Vec<i64>,
233 /// Database descriptor of key to use to unlock.
234 key_desc: KeyDescriptor,
235 /// Locked versions of the matching UserSuperKeys fields
236 screen_lock_bound: LockedKey,
237 screen_lock_bound_private: LockedKey,
238}
239
Paul Crowleye8826e52021-03-31 08:33:53 -0700240#[derive(Default)]
241struct UserSuperKeys {
242 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
243 /// key per android user. The key is stored on flash encrypted with a key derived from a
244 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
245 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
246 /// and stays memory resident until the device reboots.
247 per_boot: Option<Arc<SuperKey>>,
248 /// The screen lock key works like the per boot key with the distinction that it is cleared
249 /// from memory when the screen lock is engaged.
250 screen_lock_bound: Option<Arc<SuperKey>>,
251 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
252 /// ECDH public-key encryption. This field holds the decryption private key.
253 screen_lock_bound_private: Option<Arc<SuperKey>>,
Paul Crowley618869e2021-04-08 20:30:54 -0700254 /// Versions of the above two keys, locked behind a biometric.
255 biometric_unlock: Option<BiometricUnlock>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000256}
257
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800258#[derive(Default)]
259struct SkmState {
260 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700261 key_index: HashMap<i64, Weak<SuperKey>>,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800262 boot_level_key_cache: Option<Mutex<BootLevelKeyCache>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700263}
264
265impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000266 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
267 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
268 self.key_index.insert(id, Arc::downgrade(super_key));
269 Ok(())
270 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000271 Err(Error::sys()).context(ks_err!("Cannot add key with ID {:?}", super_key.id))
Paul Crowley44c02da2021-04-08 17:04:43 +0000272 }
Paul Crowley7a658392021-03-18 17:08:20 -0700273 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800274}
275
276#[derive(Default)]
277pub struct SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800278 data: SkmState,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800279}
280
281impl SuperKeyManager {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800282 pub fn set_up_boot_level_cache(skm: &Arc<RwLock<Self>>, db: &mut KeystoreDB) -> Result<()> {
283 let mut skm_guard = skm.write().unwrap();
284 if skm_guard.data.boot_level_key_cache.is_some() {
Paul Crowley44c02da2021-04-08 17:04:43 +0000285 log::info!("In set_up_boot_level_cache: called for a second time");
286 return Ok(());
287 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000288 let level_zero_key =
289 get_level_zero_key(db).context(ks_err!("get_level_zero_key failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800290 skm_guard.data.boot_level_key_cache =
291 Some(Mutex::new(BootLevelKeyCache::new(level_zero_key)));
Paul Crowley44c02da2021-04-08 17:04:43 +0000292 log::info!("Starting boot level watcher.");
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800293 let clone = skm.clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000294 std::thread::spawn(move || {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800295 Self::watch_boot_level(clone)
Paul Crowley44c02da2021-04-08 17:04:43 +0000296 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
297 });
298 Ok(())
299 }
300
301 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
302 /// Blocks waiting for system property changes, so must be run in its own thread.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800303 fn watch_boot_level(skm: Arc<RwLock<Self>>) -> Result<()> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000304 let mut w = PropertyWatcher::new("keystore.boot_level")
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000305 .context(ks_err!("PropertyWatcher::new failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000306 loop {
307 let level = w
308 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000309 .context(ks_err!("read of property failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800310
311 // This scope limits the skm_guard life, so we don't hold the skm_guard while
312 // waiting.
313 {
314 let mut skm_guard = skm.write().unwrap();
315 let boot_level_key_cache = skm_guard
316 .data
317 .boot_level_key_cache
Paul Crowley44c02da2021-04-08 17:04:43 +0000318 .as_mut()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800319 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000320 .context(ks_err!("Boot level cache not initialized"))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800321 .get_mut()
322 .unwrap();
323 if level < MAX_MAX_BOOT_LEVEL {
324 log::info!("Read keystore.boot_level value {}", level);
325 boot_level_key_cache
326 .advance_boot_level(level)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000327 .context(ks_err!("advance_boot_level failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800328 } else {
329 log::info!(
330 "keystore.boot_level {} hits maximum {}, finishing.",
331 level,
332 MAX_MAX_BOOT_LEVEL
333 );
334 boot_level_key_cache.finish();
335 break;
336 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000337 }
Andrew Walbran48fa9702023-05-10 15:19:30 +0000338 w.wait(None).context(ks_err!("property wait failed"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000339 }
340 Ok(())
341 }
342
343 pub fn level_accessible(&self, boot_level: i32) -> bool {
344 self.data
Paul Crowley44c02da2021-04-08 17:04:43 +0000345 .boot_level_key_cache
346 .as_ref()
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800347 .map_or(false, |c| c.lock().unwrap().level_accessible(boot_level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000348 }
349
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800350 pub fn forget_all_keys_for_user(&mut self, user: UserId) {
351 self.data.user_keys.remove(&user);
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800352 }
353
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800354 fn install_per_boot_key_for_user(
355 &mut self,
356 user: UserId,
357 super_key: Arc<SuperKey>,
358 ) -> Result<()> {
359 self.data
360 .add_key_to_key_index(&super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000361 .context(ks_err!("add_key_to_key_index failed"))?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800362 self.data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000363 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800364 }
365
Paul Crowley44c02da2021-04-08 17:04:43 +0000366 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
Paul Crowley44c02da2021-04-08 17:04:43 +0000367 Ok(match key_id {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800368 SuperKeyIdentifier::DatabaseId(id) => {
369 self.data.key_index.get(id).and_then(|k| k.upgrade())
370 }
371 SuperKeyIdentifier::BootLevel(level) => self
372 .data
Paul Crowley44c02da2021-04-08 17:04:43 +0000373 .boot_level_key_cache
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800374 .as_ref()
375 .map(|b| b.lock().unwrap().aes_key(*level as usize))
Paul Crowley44c02da2021-04-08 17:04:43 +0000376 .transpose()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000377 .context(ks_err!("aes_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000378 .flatten()
379 .map(|key| {
380 Arc::new(SuperKey {
381 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
382 key,
383 id: *key_id,
384 reencrypt_with: None,
385 })
386 }),
387 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800388 }
389
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800390 pub fn get_per_boot_key_by_user_id(
391 &self,
392 user_id: UserId,
393 ) -> Option<Arc<dyn AesGcm + Send + Sync>> {
394 self.get_per_boot_key_by_user_id_internal(user_id)
395 .map(|sk| -> Arc<dyn AesGcm + Send + Sync> { sk })
396 }
397
398 fn get_per_boot_key_by_user_id_internal(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800399 self.data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800400 }
401
Paul Crowley44c02da2021-04-08 17:04:43 +0000402 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
403 /// the relevant super key.
404 pub fn unwrap_key_if_required<'a>(
405 &self,
406 metadata: &BlobMetaData,
407 blob: &'a [u8],
408 ) -> Result<KeyBlob<'a>> {
409 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
410 let super_key = self
411 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000412 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000413 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000414 .context(ks_err!("Required super decryption key is not in memory."))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000415 KeyBlob::Sensitive {
416 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000417 .context(ks_err!("unwrap_key_with_key failed"))?,
Paul Crowley44c02da2021-04-08 17:04:43 +0000418 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
419 force_reencrypt: super_key.reencrypt_with.is_some(),
420 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700421 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000422 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700423 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800424 }
425
426 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700427 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700428 match key.algorithm {
429 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000430 (Some(iv), Some(tag)) => {
431 key.decrypt(blob, iv, tag).context(ks_err!("Failed to decrypt the key blob."))
432 }
433 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
434 "Key has incomplete metadata. Present: iv: {}, aead_tag: {}.",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700435 iv.is_some(),
436 tag.is_some(),
437 )),
438 },
Paul Crowley52f017f2021-06-22 08:16:01 -0700439 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700440 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
441 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
442 ECDHPrivateKey::from_private_key(&key.key)
443 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000444 .context(ks_err!("Failed to decrypt the key blob with ECDH."))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700445 }
446 (public_key, salt, iv, aead_tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000447 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700448 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000449 "Key has incomplete metadata. ",
Paul Crowley8d5b2532021-03-19 10:53:07 -0700450 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
451 ),
452 public_key.is_some(),
453 salt.is_some(),
454 iv.is_some(),
455 aead_tag.is_some(),
456 ))
457 }
458 }
459 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800460 }
461 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000462
463 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800464 /// The reference to self is unused but it is required to prevent calling this function
465 /// concurrently with skm state database changes.
466 fn super_key_exists_in_db_for_user(
467 &self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000468 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800469 legacy_importer: &LegacyImporter,
Paul Crowley7a658392021-03-18 17:08:20 -0700470 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000471 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000472 let key_in_db = db
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700473 .key_exists(Domain::APP, user_id as u64 as i64, USER_SUPER_KEY.alias, KeyType::Super)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000474 .context(ks_err!())?;
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000475
476 if key_in_db {
477 Ok(key_in_db)
478 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000479 legacy_importer.has_super_key(user_id).context(ks_err!("Trying to query legacy db."))
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000480 }
481 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000482
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800483 // Helper function to populate super key cache from the super key blob loaded from the database.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000484 fn populate_cache_from_super_key_blob(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800485 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700486 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700487 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000488 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700489 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700490 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700491 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000492 .context(ks_err!("Failed to extract super key from key entry"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000493 self.install_per_boot_key_for_user(user_id, super_key.clone())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000494 Ok(super_key)
495 }
496
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800497 /// Extracts super key from the entry loaded from the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700498 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700499 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700500 entry: KeyEntry,
501 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700502 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700503 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000504 if let Some((blob, metadata)) = entry.key_blob_info() {
505 let key = match (
506 metadata.encrypted_by(),
507 metadata.salt(),
508 metadata.iv(),
509 metadata.aead_tag(),
510 ) {
511 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800512 // Note that password encryption is AES no matter the value of algorithm.
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000513 let key = pw
514 .derive_key(salt, AES_256_KEY_LENGTH)
515 .context(ks_err!("Failed to generate key from password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000516
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000517 aes_gcm_decrypt(blob, iv, tag, &key)
518 .context(ks_err!("Failed to decrypt key blob."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +0000519 }
520 (enc_by, salt, iv, tag) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000521 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!(
Hasini Gunasingheda895552021-01-27 19:34:37 +0000522 concat!(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000523 "Super key has incomplete metadata.",
524 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
525 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700526 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000527 salt.is_some(),
528 iv.is_some(),
529 tag.is_some()
530 ));
531 }
532 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000533 Ok(Arc::new(SuperKey {
534 algorithm,
535 key,
536 id: SuperKeyIdentifier::DatabaseId(entry.id()),
537 reencrypt_with,
538 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000539 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000540 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(ks_err!("No key blob info."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000541 }
542 }
543
544 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700545 pub fn encrypt_with_password(
546 super_key: &[u8],
547 pw: &Password,
548 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000549 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700550 let derived_key = pw
David Drysdale6a0ec2c2022-04-19 08:11:18 +0100551 .derive_key(&salt, AES_256_KEY_LENGTH)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000552 .context(ks_err!("Failed to derive password."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000553 let mut metadata = BlobMetaData::new();
554 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
555 metadata.add(BlobMetaEntry::Salt(salt));
556 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000557 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000558 metadata.add(BlobMetaEntry::Iv(iv));
559 metadata.add(BlobMetaEntry::AeadTag(tag));
560 Ok((encrypted_key, metadata))
561 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000562
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800563 // Helper function to encrypt a key with the given super key. Callers should select which super
564 // key to be used. This is called when a key is super encrypted at its creation as well as at
565 // its upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700566 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000567 key_blob: &[u8],
568 super_key: &SuperKey,
569 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700570 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000571 return Err(Error::sys()).context(ks_err!("unexpected algorithm"));
Paul Crowley8d5b2532021-03-19 10:53:07 -0700572 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000573 let mut metadata = BlobMetaData::new();
574 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000575 .context(ks_err!("Failed to encrypt new super key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000576 metadata.add(BlobMetaEntry::Iv(iv));
577 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000578 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000579 Ok((encrypted_key, metadata))
580 }
581
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000582 // Encrypts a given key_blob using a hybrid approach, which can either use the symmetric super
583 // key or the public super key depending on which is available.
584 //
585 // If the symmetric_key is available, the key_blob is encrypted using symmetric encryption with
586 // the provided symmetric super key. Otherwise, the function loads the public super key from
587 // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be
588 // re-encrypted with the symmetric super key on the first use.
589 //
590 // This hybrid scheme allows lock-screen-bound keys to be added when the screen is locked.
591 fn encrypt_with_hybrid_super_key(
592 key_blob: &[u8],
593 symmetric_key: Option<&SuperKey>,
594 public_key_type: &SuperKeyType,
595 db: &mut KeystoreDB,
596 user_id: UserId,
597 ) -> Result<(Vec<u8>, BlobMetaData)> {
598 if let Some(super_key) = symmetric_key {
599 Self::encrypt_with_aes_super_key(key_blob, super_key)
600 .context(ks_err!("Failed to encrypt with ScreenLockBound super key."))
601 } else {
602 // Symmetric key is not available, use public key encryption
603 let loaded = db
604 .load_super_key(public_key_type, user_id)
605 .context(ks_err!("load_super_key failed."))?;
606 let (key_id_guard, key_entry) =
607 loaded.ok_or_else(Error::sys).context(ks_err!("User ECDH super key missing."))?;
608 let public_key = key_entry
609 .metadata()
610 .sec1_public_key()
611 .ok_or_else(Error::sys)
612 .context(ks_err!("sec1_public_key missing."))?;
613 let mut metadata = BlobMetaData::new();
614 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
615 ECDHPrivateKey::encrypt_message(public_key, key_blob)
616 .context(ks_err!("ECDHPrivateKey::encrypt_message failed."))?;
617 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
618 metadata.add(BlobMetaEntry::Salt(salt));
619 metadata.add(BlobMetaEntry::Iv(iv));
620 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
621 SuperKeyIdentifier::DatabaseId(key_id_guard.id()).add_to_metadata(&mut metadata);
622 Ok((encrypted_key, metadata))
623 }
624 }
625
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000626 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
627 /// the database.
Paul Crowley618869e2021-04-08 20:30:54 -0700628 #[allow(clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000629 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000630 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000631 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800632 legacy_importer: &LegacyImporter,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000633 domain: &Domain,
634 key_parameters: &[KeyParameter],
635 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700636 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000637 key_blob: &[u8],
638 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700639 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
640 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000641 SuperEncryptionType::LskfBound => {
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +0000642 // Encrypt the given key blob with the user's per-boot super key. If the per-boot
643 // super key is not unlocked or the LSKF is not setup, an error is returned.
Nathan Huckleberrya405d0e2023-03-28 18:01:43 +0000644 match self
645 .get_user_state(db, legacy_importer, user_id)
646 .context(ks_err!("Failed to get user state."))?
647 {
648 UserState::LskfUnlocked(super_key) => {
649 Self::encrypt_with_aes_super_key(key_blob, &super_key)
650 .context(ks_err!("Failed to encrypt with LskfBound key."))
651 }
652 UserState::LskfLocked => {
653 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked."))
654 }
655 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
656 .context(ks_err!("LSKF is not setup for the user.")),
657 }
658 }
Paul Crowley7a658392021-03-18 17:08:20 -0700659 SuperEncryptionType::ScreenLockBound => {
Nathan Huckleberryf9494d12023-03-30 01:22:18 +0000660 let screen_lock_bound_symmetric_key = self
661 .data
662 .user_keys
663 .get(&user_id)
664 .and_then(|e| e.screen_lock_bound.as_ref())
665 .map(|arc| arc.as_ref());
666 Self::encrypt_with_hybrid_super_key(
667 key_blob,
668 screen_lock_bound_symmetric_key,
669 &USER_SCREEN_LOCK_BOUND_P521_KEY,
670 db,
671 user_id,
672 )
673 .context(ks_err!("Failed to encrypt with ScreenLockBound hybrid scheme."))
Paul Crowley7a658392021-03-18 17:08:20 -0700674 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000675 SuperEncryptionType::BootLevel(level) => {
676 let key_id = SuperKeyIdentifier::BootLevel(level);
677 let super_key = self
678 .lookup_key(&key_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000679 .context(ks_err!("lookup_key failed"))?
Paul Crowley44c02da2021-04-08 17:04:43 +0000680 .ok_or(Error::Rc(ResponseCode::LOCKED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000681 .context(ks_err!("Boot stage key absent"))?;
682 Self::encrypt_with_aes_super_key(key_blob, &super_key)
683 .context(ks_err!("Failed to encrypt with BootLevel key."))
Paul Crowley44c02da2021-04-08 17:04:43 +0000684 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000685 }
686 }
687
688 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
689 /// If so, re-super-encrypt the key and return a new set of metadata,
690 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700691 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000692 key_blob_before_upgrade: &KeyBlob,
693 key_after_upgrade: &'a [u8],
694 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
695 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700696 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700697 let (key, metadata) =
698 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000699 .context(ks_err!("Failed to re-super-encrypt key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000700 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
701 }
702 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
703 }
704 }
705
Paul Crowley7a658392021-03-18 17:08:20 -0700706 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
707 /// When this is called, the caller must hold the lock on the SuperKeyManager.
708 /// So it's OK that the check and creation are different DB transactions.
709 fn get_or_create_super_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800710 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700711 db: &mut KeystoreDB,
712 user_id: UserId,
713 key_type: &SuperKeyType,
714 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700715 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700716 ) -> Result<Arc<SuperKey>> {
717 let loaded_key = db.load_super_key(key_type, user_id)?;
718 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700719 Ok(Self::extract_super_key_from_key_entry(
720 key_type.algorithm,
721 key_entry,
722 password,
723 reencrypt_with,
724 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700725 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700726 let (super_key, public_key) = match key_type.algorithm {
727 SuperEncryptionAlgorithm::Aes256Gcm => (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000728 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700729 None,
730 ),
Paul Crowley52f017f2021-06-22 08:16:01 -0700731 SuperEncryptionAlgorithm::EcdhP521 => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700732 let key = ECDHPrivateKey::generate()
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000733 .context(ks_err!("Failed to generate ECDH key"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700734 (
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000735 key.private_key().context(ks_err!("private_key failed"))?,
736 Some(key.public_key().context(ks_err!("public_key failed"))?),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700737 )
738 }
739 };
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800740 // Derive an AES256 key from the password and re-encrypt the super key
741 // before we insert it in the database.
Paul Crowley7a658392021-03-18 17:08:20 -0700742 let (encrypted_super_key, blob_metadata) =
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000743 Self::encrypt_with_password(&super_key, password).context(ks_err!())?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700744 let mut key_metadata = KeyMetaData::new();
745 if let Some(pk) = public_key {
746 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
747 }
Paul Crowley7a658392021-03-18 17:08:20 -0700748 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700749 .store_super_key(
750 user_id,
751 key_type,
752 &encrypted_super_key,
753 &blob_metadata,
754 &key_metadata,
755 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000756 .context(ks_err!("Failed to store super key."))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700757 Ok(Arc::new(SuperKey {
758 algorithm: key_type.algorithm,
759 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000760 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700761 reencrypt_with,
762 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700763 }
764 }
765
Paul Crowley8d5b2532021-03-19 10:53:07 -0700766 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700767 pub fn unlock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800768 &mut self,
Paul Crowley7a658392021-03-18 17:08:20 -0700769 db: &mut KeystoreDB,
770 user_id: UserId,
771 password: &Password,
772 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800773 let (screen_lock_bound, screen_lock_bound_private) = self
774 .data
775 .user_keys
776 .get(&user_id)
777 .map(|e| (e.screen_lock_bound.clone(), e.screen_lock_bound_private.clone()))
778 .unwrap_or((None, None));
779
780 if screen_lock_bound.is_some() && screen_lock_bound_private.is_some() {
781 // Already unlocked.
782 return Ok(());
783 }
784
785 let aes = if let Some(screen_lock_bound) = screen_lock_bound {
786 // This is weird. If this point is reached only one of the screen locked keys was
787 // initialized. This should never happen.
788 screen_lock_bound
789 } else {
790 self.get_or_create_super_key(db, user_id, &USER_SCREEN_LOCK_BOUND_KEY, password, None)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000791 .context(ks_err!("Trying to get or create symmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800792 };
793
794 let ecdh = if let Some(screen_lock_bound_private) = screen_lock_bound_private {
795 // This is weird. If this point is reached only one of the screen locked keys was
796 // initialized. This should never happen.
797 screen_lock_bound_private
798 } else {
799 self.get_or_create_super_key(
800 db,
801 user_id,
802 &USER_SCREEN_LOCK_BOUND_P521_KEY,
803 password,
804 Some(aes.clone()),
805 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000806 .context(ks_err!("Trying to get or create asymmetric key."))?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800807 };
808
809 self.data.add_key_to_key_index(&aes)?;
810 self.data.add_key_to_key_index(&ecdh)?;
811 let entry = self.data.user_keys.entry(user_id).or_default();
812 entry.screen_lock_bound = Some(aes);
813 entry.screen_lock_bound_private = Some(ecdh);
Paul Crowley7a658392021-03-18 17:08:20 -0700814 Ok(())
815 }
816
Paul Crowley8d5b2532021-03-19 10:53:07 -0700817 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley618869e2021-04-08 20:30:54 -0700818 pub fn lock_screen_lock_bound_key(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800819 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700820 db: &mut KeystoreDB,
821 user_id: UserId,
822 unlocking_sids: &[i64],
823 ) {
824 log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800825 let mut entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700826 if !unlocking_sids.is_empty() {
827 if let (Some(aes), Some(ecdh)) = (
828 entry.screen_lock_bound.as_ref().cloned(),
829 entry.screen_lock_bound_private.as_ref().cloned(),
830 ) {
831 let res = (|| -> Result<()> {
832 let key_desc = KeyMintDevice::internal_descriptor(format!(
833 "biometric_unlock_key_{}",
834 user_id
835 ));
836 let encrypting_key = generate_aes256_key()?;
837 let km_dev: KeyMintDevice =
838 KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000839 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700840 let mut key_params = vec![
841 KeyParameterValue::Algorithm(Algorithm::AES),
842 KeyParameterValue::KeySize(256),
843 KeyParameterValue::BlockMode(BlockMode::GCM),
844 KeyParameterValue::PaddingMode(PaddingMode::NONE),
845 KeyParameterValue::CallerNonce,
846 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
847 KeyParameterValue::MinMacLength(128),
848 KeyParameterValue::AuthTimeout(BIOMETRIC_AUTH_TIMEOUT_S),
849 KeyParameterValue::HardwareAuthenticatorType(
850 HardwareAuthenticatorType::FINGERPRINT,
851 ),
852 ];
853 for sid in unlocking_sids {
854 key_params.push(KeyParameterValue::UserSecureID(*sid));
855 }
856 let key_params: Vec<KmKeyParameter> =
857 key_params.into_iter().map(|x| x.into()).collect();
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700858 km_dev.create_and_store_key(
859 db,
860 &key_desc,
861 KeyType::Client, /* TODO Should be Super b/189470584 */
862 |dev| {
863 let _wp = wd::watch_millis(
864 "In lock_screen_lock_bound_key: calling importKey.",
865 500,
866 );
867 dev.importKey(
868 key_params.as_slice(),
869 KeyFormat::RAW,
870 &encrypting_key,
871 None,
872 )
873 },
874 )?;
Paul Crowley618869e2021-04-08 20:30:54 -0700875 entry.biometric_unlock = Some(BiometricUnlock {
876 sids: unlocking_sids.into(),
877 key_desc,
878 screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
879 screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
880 });
881 Ok(())
882 })();
883 // There is no reason to propagate an error here upwards. We must discard
884 // entry.screen_lock_bound* in any case.
885 if let Err(e) = res {
886 log::error!("Error setting up biometric unlock: {:#?}", e);
887 }
888 }
889 }
Paul Crowley7a658392021-03-18 17:08:20 -0700890 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700891 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700892 }
Paul Crowley618869e2021-04-08 20:30:54 -0700893
894 /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
895 /// to unlock the keys protecting UNLOCKED_DEVICE_REQUIRED keys.
896 pub fn try_unlock_user_with_biometric(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800897 &mut self,
Paul Crowley618869e2021-04-08 20:30:54 -0700898 db: &mut KeystoreDB,
899 user_id: UserId,
900 ) -> Result<()> {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800901 let mut entry = self.data.user_keys.entry(user_id).or_default();
Paul Crowley618869e2021-04-08 20:30:54 -0700902 if let Some(biometric) = entry.biometric_unlock.as_ref() {
Janis Danisevskisacebfa22021-05-25 10:56:10 -0700903 let (key_id_guard, key_entry) = db
904 .load_key_entry(
905 &biometric.key_desc,
906 KeyType::Client, // This should not be a Client key.
907 KeyEntryLoadBits::KM,
908 AID_KEYSTORE,
909 |_, _| Ok(()),
910 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000911 .context(ks_err!("load_key_entry failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700912 let km_dev: KeyMintDevice = KeyMintDevice::get(SecurityLevel::TRUSTED_ENVIRONMENT)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000913 .context(ks_err!("KeyMintDevice::get failed"))?;
Paul Crowley618869e2021-04-08 20:30:54 -0700914 for sid in &biometric.sids {
915 if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
916 entry.auth_token().userId == *sid || entry.auth_token().authenticatorId == *sid
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700917 }) {
Paul Crowley618869e2021-04-08 20:30:54 -0700918 let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
919 let slb = biometric.screen_lock_bound.decrypt(
920 db,
921 &km_dev,
922 &key_id_guard,
923 &key_entry,
924 auth_token_entry.auth_token(),
925 None,
926 )?;
927 let slbp = biometric.screen_lock_bound_private.decrypt(
928 db,
929 &km_dev,
930 &key_id_guard,
931 &key_entry,
932 auth_token_entry.auth_token(),
933 Some(slb.clone()),
934 )?;
935 Ok((slb, slbp))
936 })();
937 match res {
938 Ok((slb, slbp)) => {
939 entry.screen_lock_bound = Some(slb.clone());
940 entry.screen_lock_bound_private = Some(slbp.clone());
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800941 self.data.add_key_to_key_index(&slb)?;
942 self.data.add_key_to_key_index(&slbp)?;
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000943 log::info!("Successfully unlocked with biometric");
Paul Crowley618869e2021-04-08 20:30:54 -0700944 return Ok(());
945 }
946 Err(e) => {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000947 log::warn!("attempt failed: {:?}", e)
Paul Crowley618869e2021-04-08 20:30:54 -0700948 }
949 }
950 }
951 }
952 }
953 Ok(())
954 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800955
956 /// Returns the keystore locked state of the given user. It requires the thread local
957 /// keystore database and a reference to the legacy migrator because it may need to
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800958 /// import the super key from the legacy blob database to the keystore database.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800959 pub fn get_user_state(
960 &self,
961 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800962 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800963 user_id: UserId,
964 ) -> Result<UserState> {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800965 match self.get_per_boot_key_by_user_id_internal(user_id) {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800966 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
967 None => {
968 // Check if a super key exists in the database or legacy database.
969 // If so, return locked user state.
970 if self
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800971 .super_key_exists_in_db_for_user(db, legacy_importer, user_id)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000972 .context(ks_err!())?
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800973 {
974 Ok(UserState::LskfLocked)
975 } else {
976 Ok(UserState::Uninitialized)
977 }
978 }
979 }
980 }
981
Nathan Huckleberry204a0442023-03-30 17:27:47 +0000982 /// Deletes all keys and super keys for the given user.
983 /// This is called when a user is deleted.
984 pub fn remove_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800985 &mut self,
986 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800987 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800988 user_id: UserId,
Nathan Huckleberry204a0442023-03-30 17:27:47 +0000989 ) -> Result<()> {
990 // Mark keys created on behalf of the user as unreferenced.
991 legacy_importer
992 .bulk_delete_user(user_id, false)
993 .context(ks_err!("Trying to delete legacy keys."))?;
994 db.unbind_keys_for_user(user_id, false).context(ks_err!("Error in unbinding keys."))?;
995
996 // Delete super key in cache, if exists.
997 self.forget_all_keys_for_user(user_id);
998 Ok(())
999 }
1000
1001 /// Deletes all authentication bound keys and super keys for the given user. The user must be
1002 /// unlocked before this function is called. This function is used to transition a user to
1003 /// swipe.
1004 pub fn reset_user(
1005 &mut self,
1006 db: &mut KeystoreDB,
1007 legacy_importer: &LegacyImporter,
1008 user_id: UserId,
1009 ) -> Result<()> {
1010 match self.get_user_state(db, legacy_importer, user_id)? {
1011 UserState::Uninitialized => {
1012 Err(Error::sys()).context(ks_err!("Tried to reset an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001013 }
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001014 UserState::LskfLocked => {
1015 Err(Error::sys()).context(ks_err!("Tried to reset a locked user's password!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001016 }
Nathan Huckleberry204a0442023-03-30 17:27:47 +00001017 UserState::LskfUnlocked(_) => {
1018 // Mark keys created on behalf of the user as unreferenced.
1019 legacy_importer
1020 .bulk_delete_user(user_id, true)
1021 .context(ks_err!("Trying to delete legacy keys."))?;
1022 db.unbind_keys_for_user(user_id, true)
1023 .context(ks_err!("Error in unbinding keys."))?;
1024
1025 // Delete super key in cache, if exists.
1026 self.forget_all_keys_for_user(user_id);
1027 Ok(())
1028 }
1029 }
1030 }
1031
1032 /// If the user hasn't been initialized yet, then this function generates the user's super keys
1033 /// and sets the user's state to LskfUnlocked. Otherwise this function returns an error.
1034 pub fn init_user(
1035 &mut self,
1036 db: &mut KeystoreDB,
1037 legacy_importer: &LegacyImporter,
1038 user_id: UserId,
1039 password: &Password,
1040 ) -> Result<()> {
1041 match self.get_user_state(db, legacy_importer, user_id)? {
1042 UserState::LskfUnlocked(_) | UserState::LskfLocked => {
1043 Err(Error::sys()).context(ks_err!("Tried to re-init an initialized user!"))
1044 }
1045 UserState::Uninitialized => {
1046 // Generate a new super key.
1047 let super_key =
1048 generate_aes256_key().context(ks_err!("Failed to generate AES 256 key."))?;
1049 // Derive an AES256 key from the password and re-encrypt the super key
1050 // before we insert it in the database.
1051 let (encrypted_super_key, blob_metadata) =
1052 Self::encrypt_with_password(&super_key, password)
1053 .context(ks_err!("Failed to encrypt super key with password!"))?;
1054
1055 let key_entry = db
1056 .store_super_key(
1057 user_id,
1058 &USER_SUPER_KEY,
1059 &encrypted_super_key,
1060 &blob_metadata,
1061 &KeyMetaData::new(),
1062 )
1063 .context(ks_err!("Failed to store super key."))?;
1064
1065 self.populate_cache_from_super_key_blob(
1066 user_id,
1067 USER_SUPER_KEY.algorithm,
1068 key_entry,
1069 password,
1070 )
1071 .context(ks_err!("Failed to initialize user!"))?;
1072 Ok(())
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001073 }
1074 }
1075 }
1076
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001077 /// Unlocks the given user with the given password.
1078 ///
1079 /// If the user is LskfLocked:
1080 /// - Unlock the per_boot super key
1081 /// - Unlock the screen_lock_bound super key
1082 ///
1083 /// If the user is LskfUnlocked:
1084 /// - Unlock the screen_lock_bound super key only
1085 ///
1086 pub fn unlock_user(
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001087 &mut self,
1088 db: &mut KeystoreDB,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -08001089 legacy_importer: &LegacyImporter,
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001090 user_id: UserId,
1091 password: &Password,
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001092 ) -> Result<()> {
1093 match self.get_user_state(db, legacy_importer, user_id)? {
1094 UserState::LskfUnlocked(_) => self.unlock_screen_lock_bound_key(db, user_id, password),
1095 UserState::Uninitialized => {
1096 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001097 }
Nathan Huckleberry7dfe8182023-04-04 20:41:01 +00001098 UserState::LskfLocked => {
1099 let alias = &USER_SUPER_KEY;
1100 let result = legacy_importer
1101 .with_try_import_super_key(user_id, password, || {
1102 db.load_super_key(alias, user_id)
1103 })
1104 .context(ks_err!("Failed to load super key"))?;
1105
1106 match result {
1107 Some((_, entry)) => {
1108 self.populate_cache_from_super_key_blob(
1109 user_id,
1110 alias.algorithm,
1111 entry,
1112 password,
1113 )
1114 .context(ks_err!("Failed when unlocking user."))?;
1115 self.unlock_screen_lock_bound_key(db, user_id, password)
1116 }
1117 None => {
1118 Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))
1119 }
1120 }
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08001121 }
1122 }
1123 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001124}
1125
1126/// This enum represents different states of the user's life cycle in the device.
1127/// For now, only three states are defined. More states may be added later.
1128pub enum UserState {
1129 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
1130 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -07001131 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001132 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
1133 // Hence the per-boot super-key(s) is not available in the cache.
1134 // However, the encrypted super key is available in the database.
1135 LskfLocked,
1136 // There's no user in the device for the given user id, or the user with the user id has not
1137 // setup LSKF.
1138 Uninitialized,
1139}
1140
Janis Danisevskiseed69842021-02-18 20:04:10 -08001141/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
1142/// `Sensitive` holds the non encrypted key and a reference to its super key.
1143/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
1144/// `Ref` holds a reference to a key blob when it does not need to be modified if its
1145/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001146pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -07001147 Sensitive {
1148 key: ZVec,
1149 /// If KeyMint reports that the key must be upgraded, we must
1150 /// re-encrypt the key before writing to the database; we use
1151 /// this key.
1152 reencrypt_with: Arc<SuperKey>,
1153 /// If this key was decrypted with an ECDH key, we want to
1154 /// re-encrypt it on first use whether it was upgraded or not;
1155 /// this field indicates that that's necessary.
1156 force_reencrypt: bool,
1157 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001158 NonSensitive(Vec<u8>),
1159 Ref(&'a [u8]),
1160}
1161
Paul Crowley8d5b2532021-03-19 10:53:07 -07001162impl<'a> KeyBlob<'a> {
1163 pub fn force_reencrypt(&self) -> bool {
1164 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
1165 *force_reencrypt
1166 } else {
1167 false
1168 }
1169 }
1170}
1171
Janis Danisevskiseed69842021-02-18 20:04:10 -08001172/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001173impl<'a> Deref for KeyBlob<'a> {
1174 type Target = [u8];
1175
1176 fn deref(&self) -> &Self::Target {
1177 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001178 Self::Sensitive { key, .. } => key,
1179 Self::NonSensitive(key) => key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001180 Self::Ref(key) => key,
1181 }
1182 }
1183}