blob: b78560f7f51acb5f02f1a2644fffb2abca9fb030 [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,
22 database::{KeyMetaData, KeyMetaEntry, KeystoreDB},
23 ec_crypto::ECDHPrivateKey,
24 enforcements::Enforcements,
25 error::Error,
26 error::ResponseCode,
27 key_parameter::KeyParameter,
28 legacy_blob::LegacyBlobLoader,
29 legacy_migrator::LegacyMigrator,
30 try_insert::TryInsert,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080031};
32use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
33use anyhow::{Context, Result};
34use keystore2_crypto::{
Paul Crowleyf61fee72021-03-17 14:38:44 -070035 aes_gcm_decrypt, aes_gcm_encrypt, generate_aes256_key, generate_salt, Password, ZVec,
36 AES_256_KEY_LENGTH,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080037};
Paul Crowley44c02da2021-04-08 17:04:43 +000038use keystore2_system_property::PropertyWatcher;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000039use std::ops::Deref;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080040use std::{
41 collections::HashMap,
42 sync::Arc,
43 sync::{Mutex, Weak},
44};
45
Paul Crowley44c02da2021-04-08 17:04:43 +000046const MAX_MAX_BOOT_LEVEL: usize = 1_000_000_000;
47
Janis Danisevskisb42fc182020-12-15 08:41:27 -080048type UserId = u32;
49
Paul Crowley8d5b2532021-03-19 10:53:07 -070050/// Encryption algorithm used by a particular type of superencryption key
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum SuperEncryptionAlgorithm {
53 /// Symmetric encryption with AES-256-GCM
54 Aes256Gcm,
55 /// Public-key encryption with ECDH P-256
56 EcdhP256,
57}
58
Paul Crowley7a658392021-03-18 17:08:20 -070059/// A particular user may have several superencryption keys in the database, each for a
60/// different purpose, distinguished by alias. Each is associated with a static
61/// constant of this type.
62pub struct SuperKeyType {
63 /// Alias used to look the key up in the `persistent.keyentry` table.
64 pub alias: &'static str,
Paul Crowley8d5b2532021-03-19 10:53:07 -070065 /// Encryption algorithm
66 pub algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -070067}
68
69/// Key used for LskfLocked keys; the corresponding superencryption key is loaded in memory
70/// when the user first unlocks, and remains in memory until the device reboots.
Paul Crowley8d5b2532021-03-19 10:53:07 -070071pub const USER_SUPER_KEY: SuperKeyType =
72 SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
Paul Crowley7a658392021-03-18 17:08:20 -070073/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
74/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
Paul Crowley8d5b2532021-03-19 10:53:07 -070075/// Symmetric.
76pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
77 alias: "USER_SCREEN_LOCK_BOUND_KEY",
78 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
79};
80/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
81/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
82/// Asymmetric, so keys can be encrypted when the device is locked.
83pub const USER_SCREEN_LOCK_BOUND_ECDH_KEY: SuperKeyType = SuperKeyType {
84 alias: "USER_SCREEN_LOCK_BOUND_ECDH_KEY",
85 algorithm: SuperEncryptionAlgorithm::EcdhP256,
86};
Paul Crowley7a658392021-03-18 17:08:20 -070087
88/// Superencryption to apply to a new key.
89#[derive(Debug, Clone, Copy)]
90pub enum SuperEncryptionType {
91 /// Do not superencrypt this key.
92 None,
93 /// Superencrypt with a key that remains in memory from first unlock to reboot.
94 LskfBound,
95 /// Superencrypt with a key cleared from memory when the device is locked.
96 ScreenLockBound,
Paul Crowley44c02da2021-04-08 17:04:43 +000097 /// Superencrypt with a key based on the desired boot level
98 BootLevel(i32),
99}
100
101#[derive(Debug, Clone, Copy)]
102pub enum SuperKeyIdentifier {
103 /// id of the super key in the database.
104 DatabaseId(i64),
105 /// Boot level of the encrypting boot level key
106 BootLevel(i32),
107}
108
109impl SuperKeyIdentifier {
110 fn from_metadata(metadata: &BlobMetaData) -> Option<Self> {
111 if let Some(EncryptedBy::KeyId(key_id)) = metadata.encrypted_by() {
112 Some(SuperKeyIdentifier::DatabaseId(*key_id))
113 } else if let Some(boot_level) = metadata.max_boot_level() {
114 Some(SuperKeyIdentifier::BootLevel(*boot_level))
115 } else {
116 None
117 }
118 }
119
120 fn add_to_metadata(&self, metadata: &mut BlobMetaData) {
121 match self {
122 SuperKeyIdentifier::DatabaseId(id) => {
123 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(*id)));
124 }
125 SuperKeyIdentifier::BootLevel(level) => {
126 metadata.add(BlobMetaEntry::MaxBootLevel(*level));
127 }
128 }
129 }
Paul Crowley7a658392021-03-18 17:08:20 -0700130}
131
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000132pub struct SuperKey {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700133 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700134 key: ZVec,
Paul Crowley44c02da2021-04-08 17:04:43 +0000135 /// Identifier of the encrypting key, used to write an encrypted blob
136 /// back to the database after re-encryption eg on a key update.
137 id: SuperKeyIdentifier,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700138 /// ECDH is more expensive than AES. So on ECDH private keys we set the
139 /// reencrypt_with field to point at the corresponding AES key, and the
140 /// keys will be re-encrypted with AES on first use.
141 reencrypt_with: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000142}
143
144impl SuperKey {
Paul Crowley7a658392021-03-18 17:08:20 -0700145 /// For most purposes `unwrap_key` handles decryption,
146 /// but legacy handling and some tests need to assume AES and decrypt directly.
147 pub fn aes_gcm_decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700148 if self.algorithm == SuperEncryptionAlgorithm::Aes256Gcm {
149 aes_gcm_decrypt(data, iv, tag, &self.key)
150 .context("In aes_gcm_decrypt: decryption failed")
151 } else {
152 Err(Error::sys()).context("In aes_gcm_decrypt: Key is not an AES key")
153 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000154 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700155}
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000156
Paul Crowleye8826e52021-03-31 08:33:53 -0700157#[derive(Default)]
158struct UserSuperKeys {
159 /// The per boot key is used for LSKF binding of authentication bound keys. There is one
160 /// key per android user. The key is stored on flash encrypted with a key derived from a
161 /// secret, that is itself derived from the user's lock screen knowledge factor (LSKF).
162 /// When the user unlocks the device for the first time, this key is unlocked, i.e., decrypted,
163 /// and stays memory resident until the device reboots.
164 per_boot: Option<Arc<SuperKey>>,
165 /// The screen lock key works like the per boot key with the distinction that it is cleared
166 /// from memory when the screen lock is engaged.
167 screen_lock_bound: Option<Arc<SuperKey>>,
168 /// When the device is locked, screen-lock-bound keys can still be encrypted, using
169 /// ECDH public-key encryption. This field holds the decryption private key.
170 screen_lock_bound_private: Option<Arc<SuperKey>>,
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000171}
172
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800173#[derive(Default)]
174struct SkmState {
175 user_keys: HashMap<UserId, UserSuperKeys>,
Paul Crowley7a658392021-03-18 17:08:20 -0700176 key_index: HashMap<i64, Weak<SuperKey>>,
Paul Crowley44c02da2021-04-08 17:04:43 +0000177 boot_level_key_cache: Option<BootLevelKeyCache>,
Paul Crowley7a658392021-03-18 17:08:20 -0700178}
179
180impl SkmState {
Paul Crowley44c02da2021-04-08 17:04:43 +0000181 fn add_key_to_key_index(&mut self, super_key: &Arc<SuperKey>) -> Result<()> {
182 if let SuperKeyIdentifier::DatabaseId(id) = super_key.id {
183 self.key_index.insert(id, Arc::downgrade(super_key));
184 Ok(())
185 } else {
186 Err(Error::sys()).context(format!(
187 "In add_key_to_key_index: cannot add key with ID {:?}",
188 super_key.id
189 ))
190 }
Paul Crowley7a658392021-03-18 17:08:20 -0700191 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800192}
193
194#[derive(Default)]
195pub struct SuperKeyManager {
196 data: Mutex<SkmState>,
197}
198
199impl SuperKeyManager {
Paul Crowley44c02da2021-04-08 17:04:43 +0000200 pub fn set_up_boot_level_cache(self: &Arc<Self>, db: &mut KeystoreDB) -> Result<()> {
201 let mut data = self.data.lock().unwrap();
202 if data.boot_level_key_cache.is_some() {
203 log::info!("In set_up_boot_level_cache: called for a second time");
204 return Ok(());
205 }
206 let level_zero_key = get_level_zero_key(db)
207 .context("In set_up_boot_level_cache: get_level_zero_key failed")?;
208 data.boot_level_key_cache = Some(BootLevelKeyCache::new(level_zero_key));
209 log::info!("Starting boot level watcher.");
210 let clone = self.clone();
211 std::thread::spawn(move || {
212 clone
213 .watch_boot_level()
214 .unwrap_or_else(|e| log::error!("watch_boot_level failed:\n{:?}", e));
215 });
216 Ok(())
217 }
218
219 /// Watch the `keystore.boot_level` system property, and keep boot level up to date.
220 /// Blocks waiting for system property changes, so must be run in its own thread.
221 fn watch_boot_level(&self) -> Result<()> {
222 let mut w = PropertyWatcher::new("keystore.boot_level")
223 .context("In watch_boot_level: PropertyWatcher::new failed")?;
224 loop {
225 let level = w
226 .read(|_n, v| v.parse::<usize>().map_err(std::convert::Into::into))
227 .context("In watch_boot_level: read of property failed")?;
228 // watch_boot_level should only be called once data.boot_level_key_cache is Some,
229 // so it's safe to unwrap in the branches below.
230 if level < MAX_MAX_BOOT_LEVEL {
231 log::info!("Read keystore.boot_level value {}", level);
232 let mut data = self.data.lock().unwrap();
233 data.boot_level_key_cache
234 .as_mut()
235 .unwrap()
236 .advance_boot_level(level)
237 .context("In watch_boot_level: advance_boot_level failed")?;
238 } else {
239 log::info!(
240 "keystore.boot_level {} hits maximum {}, finishing.",
241 level,
242 MAX_MAX_BOOT_LEVEL
243 );
244 let mut data = self.data.lock().unwrap();
245 data.boot_level_key_cache.as_mut().unwrap().finish();
246 break;
247 }
248 w.wait().context("In watch_boot_level: property wait failed")?;
249 }
250 Ok(())
251 }
252
253 pub fn level_accessible(&self, boot_level: i32) -> bool {
254 self.data
255 .lock()
256 .unwrap()
257 .boot_level_key_cache
258 .as_ref()
259 .map_or(false, |c| c.level_accessible(boot_level as usize))
260 }
261
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800262 pub fn forget_all_keys_for_user(&self, user: UserId) {
263 let mut data = self.data.lock().unwrap();
264 data.user_keys.remove(&user);
265 }
266
Paul Crowley44c02da2021-04-08 17:04:43 +0000267 fn install_per_boot_key_for_user(&self, user: UserId, super_key: Arc<SuperKey>) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800268 let mut data = self.data.lock().unwrap();
Paul Crowley44c02da2021-04-08 17:04:43 +0000269 data.add_key_to_key_index(&super_key)
270 .context("In install_per_boot_key_for_user: add_key_to_key_index failed")?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000271 data.user_keys.entry(user).or_default().per_boot = Some(super_key);
Paul Crowley44c02da2021-04-08 17:04:43 +0000272 Ok(())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800273 }
274
Paul Crowley44c02da2021-04-08 17:04:43 +0000275 fn lookup_key(&self, key_id: &SuperKeyIdentifier) -> Result<Option<Arc<SuperKey>>> {
276 let mut data = self.data.lock().unwrap();
277 Ok(match key_id {
278 SuperKeyIdentifier::DatabaseId(id) => data.key_index.get(id).and_then(|k| k.upgrade()),
279 SuperKeyIdentifier::BootLevel(level) => data
280 .boot_level_key_cache
281 .as_mut()
282 .map(|b| b.aes_key(*level as usize))
283 .transpose()
284 .context("In lookup_key: aes_key failed")?
285 .flatten()
286 .map(|key| {
287 Arc::new(SuperKey {
288 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
289 key,
290 id: *key_id,
291 reencrypt_with: None,
292 })
293 }),
294 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800295 }
296
Paul Crowley7a658392021-03-18 17:08:20 -0700297 pub fn get_per_boot_key_by_user_id(&self, user_id: UserId) -> Option<Arc<SuperKey>> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800298 let data = self.data.lock().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700299 data.user_keys.get(&user_id).and_then(|e| e.per_boot.as_ref().cloned())
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800300 }
301
302 /// This function unlocks the super keys for a given user.
303 /// This means the key is loaded from the database, decrypted and placed in the
304 /// super key cache. If there is no such key a new key is created, encrypted with
305 /// a key derived from the given password and stored in the database.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800306 pub fn unlock_user_key(
307 &self,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000308 db: &mut KeystoreDB,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800309 user: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700310 pw: &Password,
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800311 legacy_blob_loader: &LegacyBlobLoader,
312 ) -> Result<()> {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800313 let (_, entry) = db
Max Bires8e93d2b2021-01-14 13:17:59 -0800314 .get_or_create_key_with(
315 Domain::APP,
316 user as u64 as i64,
Paul Crowley7a658392021-03-18 17:08:20 -0700317 &USER_SUPER_KEY.alias,
Max Bires8e93d2b2021-01-14 13:17:59 -0800318 crate::database::KEYSTORE_UUID,
319 || {
320 // For backward compatibility we need to check if there is a super key present.
321 let super_key = legacy_blob_loader
322 .load_super_key(user, pw)
323 .context("In create_new_key: Failed to load legacy key blob.")?;
324 let super_key = match super_key {
325 None => {
326 // No legacy file was found. So we generate a new key.
Hasini Gunasingheda895552021-01-27 19:34:37 +0000327 generate_aes256_key()
Max Bires8e93d2b2021-01-14 13:17:59 -0800328 .context("In create_new_key: Failed to generate AES 256 key.")?
329 }
330 Some(key) => key,
331 };
Hasini Gunasingheda895552021-01-27 19:34:37 +0000332 // Regardless of whether we loaded an old AES128 key or generated a new AES256
333 // key as the super key, we derive a AES256 key from the password and re-encrypt
334 // the super key before we insert it in the database. The length of the key is
335 // preserved by the encryption so we don't need any extra flags to inform us
336 // which algorithm to use it with.
337 Self::encrypt_with_password(&super_key, pw).context("In create_new_key.")
Max Bires8e93d2b2021-01-14 13:17:59 -0800338 },
339 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800340 .context("In unlock_user_key: Failed to get key id.")?;
341
Paul Crowley8d5b2532021-03-19 10:53:07 -0700342 self.populate_cache_from_super_key_blob(user, USER_SUPER_KEY.algorithm, entry, pw)
343 .context("In unlock_user_key.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800344 Ok(())
345 }
346
Paul Crowley44c02da2021-04-08 17:04:43 +0000347 /// Check if a given key is super-encrypted, from its metadata. If so, unwrap the key using
348 /// the relevant super key.
349 pub fn unwrap_key_if_required<'a>(
350 &self,
351 metadata: &BlobMetaData,
352 blob: &'a [u8],
353 ) -> Result<KeyBlob<'a>> {
354 Ok(if let Some(key_id) = SuperKeyIdentifier::from_metadata(metadata) {
355 let super_key = self
356 .lookup_key(&key_id)
357 .context("In unwrap_key: lookup_key failed")?
358 .ok_or(Error::Rc(ResponseCode::LOCKED))
359 .context("In unwrap_key: Required super decryption key is not in memory.")?;
360 KeyBlob::Sensitive {
361 key: Self::unwrap_key_with_key(blob, metadata, &super_key)
362 .context("In unwrap_key: unwrap_key_with_key failed")?,
363 reencrypt_with: super_key.reencrypt_with.as_ref().unwrap_or(&super_key).clone(),
364 force_reencrypt: super_key.reencrypt_with.is_some(),
365 }
Paul Crowleye8826e52021-03-31 08:33:53 -0700366 } else {
Paul Crowley44c02da2021-04-08 17:04:43 +0000367 KeyBlob::Ref(blob)
Paul Crowleye8826e52021-03-31 08:33:53 -0700368 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800369 }
370
371 /// Unwraps an encrypted key blob given an encryption key.
Paul Crowley7a658392021-03-18 17:08:20 -0700372 fn unwrap_key_with_key(blob: &[u8], metadata: &BlobMetaData, key: &SuperKey) -> Result<ZVec> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700373 match key.algorithm {
374 SuperEncryptionAlgorithm::Aes256Gcm => match (metadata.iv(), metadata.aead_tag()) {
375 (Some(iv), Some(tag)) => key
376 .aes_gcm_decrypt(blob, iv, tag)
377 .context("In unwrap_key_with_key: Failed to decrypt the key blob."),
378 (iv, tag) => Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
379 concat!(
380 "In unwrap_key_with_key: Key has incomplete metadata.",
381 "Present: iv: {}, aead_tag: {}."
382 ),
383 iv.is_some(),
384 tag.is_some(),
385 )),
386 },
387 SuperEncryptionAlgorithm::EcdhP256 => {
388 match (metadata.public_key(), metadata.salt(), metadata.iv(), metadata.aead_tag()) {
389 (Some(public_key), Some(salt), Some(iv), Some(aead_tag)) => {
390 ECDHPrivateKey::from_private_key(&key.key)
391 .and_then(|k| k.decrypt_message(public_key, salt, iv, blob, aead_tag))
392 .context(
393 "In unwrap_key_with_key: Failed to decrypt the key blob with ECDH.",
394 )
395 }
396 (public_key, salt, iv, aead_tag) => {
397 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
398 concat!(
399 "In unwrap_key_with_key: Key has incomplete metadata.",
400 "Present: public_key: {}, salt: {}, iv: {}, aead_tag: {}."
401 ),
402 public_key.is_some(),
403 salt.is_some(),
404 iv.is_some(),
405 aead_tag.is_some(),
406 ))
407 }
408 }
409 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800410 }
411 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000412
413 /// Checks if user has setup LSKF, even when super key cache is empty for the user.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000414 pub fn super_key_exists_in_db_for_user(
415 db: &mut KeystoreDB,
416 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700417 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000418 ) -> Result<bool> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000419 let key_in_db = db
Paul Crowley7a658392021-03-18 17:08:20 -0700420 .key_exists(Domain::APP, user_id as u64 as i64, &USER_SUPER_KEY.alias, KeyType::Super)
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000421 .context("In super_key_exists_in_db_for_user.")?;
422
423 if key_in_db {
424 Ok(key_in_db)
425 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000426 legacy_migrator
427 .has_super_key(user_id)
428 .context("In super_key_exists_in_db_for_user: Trying to query legacy db.")
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000429 }
430 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000431
432 /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000433 /// legacy database). If not, return Uninitialized state.
434 /// Otherwise, decrypt the super key from the password and return LskfUnlocked state.
435 pub fn check_and_unlock_super_key(
436 &self,
437 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000438 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700439 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700440 pw: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000441 ) -> Result<UserState> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700442 let alias = &USER_SUPER_KEY;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000443 let result = legacy_migrator
Paul Crowley8d5b2532021-03-19 10:53:07 -0700444 .with_try_migrate_super_key(user_id, pw, || db.load_super_key(alias, user_id))
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000445 .context("In check_and_unlock_super_key. Failed to load super key")?;
446
447 match result {
448 Some((_, entry)) => {
449 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700450 .populate_cache_from_super_key_blob(user_id, alias.algorithm, entry, pw)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000451 .context("In check_and_unlock_super_key.")?;
452 Ok(UserState::LskfUnlocked(super_key))
453 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000454 None => Ok(UserState::Uninitialized),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000455 }
456 }
457
458 /// Checks if user has already setup LSKF (i.e. a super key is persisted in the database or the
Hasini Gunasingheda895552021-01-27 19:34:37 +0000459 /// legacy database). If so, return LskfLocked state.
460 /// If the password is provided, generate a new super key, encrypt with the password,
461 /// store in the database and populate the super key cache for the new user
462 /// and return LskfUnlocked state.
463 /// If the password is not provided, return Uninitialized state.
464 pub fn check_and_initialize_super_key(
465 &self,
466 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000467 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700468 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700469 pw: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000470 ) -> Result<UserState> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000471 let super_key_exists_in_db =
472 Self::super_key_exists_in_db_for_user(db, legacy_migrator, user_id).context(
473 "In check_and_initialize_super_key. Failed to check if super key exists.",
474 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000475 if super_key_exists_in_db {
476 Ok(UserState::LskfLocked)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000477 } else if let Some(pw) = pw {
478 //generate a new super key.
479 let super_key = generate_aes256_key()
480 .context("In check_and_initialize_super_key: Failed to generate AES 256 key.")?;
481 //derive an AES256 key from the password and re-encrypt the super key
482 //before we insert it in the database.
483 let (encrypted_super_key, blob_metadata) = Self::encrypt_with_password(&super_key, pw)
484 .context("In check_and_initialize_super_key.")?;
485
486 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700487 .store_super_key(
488 user_id,
489 &USER_SUPER_KEY,
490 &encrypted_super_key,
491 &blob_metadata,
492 &KeyMetaData::new(),
493 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000494 .context("In check_and_initialize_super_key. Failed to store super key.")?;
495
496 let super_key = self
Paul Crowley8d5b2532021-03-19 10:53:07 -0700497 .populate_cache_from_super_key_blob(
498 user_id,
499 USER_SUPER_KEY.algorithm,
500 key_entry,
501 pw,
502 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000503 .context("In check_and_initialize_super_key.")?;
504 Ok(UserState::LskfUnlocked(super_key))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000505 } else {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000506 Ok(UserState::Uninitialized)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000507 }
508 }
509
510 //helper function to populate super key cache from the super key blob loaded from the database
511 fn populate_cache_from_super_key_blob(
512 &self,
Paul Crowley7a658392021-03-18 17:08:20 -0700513 user_id: UserId,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700514 algorithm: SuperEncryptionAlgorithm,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000515 entry: KeyEntry,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700516 pw: &Password,
Paul Crowley7a658392021-03-18 17:08:20 -0700517 ) -> Result<Arc<SuperKey>> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700518 let super_key = Self::extract_super_key_from_key_entry(algorithm, entry, pw, None)
519 .context(
520 "In populate_cache_from_super_key_blob. Failed to extract super key from key entry",
521 )?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000522 self.install_per_boot_key_for_user(user_id, super_key.clone())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000523 Ok(super_key)
524 }
525
526 /// Extracts super key from the entry loaded from the database
Paul Crowley7a658392021-03-18 17:08:20 -0700527 pub fn extract_super_key_from_key_entry(
Paul Crowley8d5b2532021-03-19 10:53:07 -0700528 algorithm: SuperEncryptionAlgorithm,
Paul Crowley7a658392021-03-18 17:08:20 -0700529 entry: KeyEntry,
530 pw: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700531 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700532 ) -> Result<Arc<SuperKey>> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000533 if let Some((blob, metadata)) = entry.key_blob_info() {
534 let key = match (
535 metadata.encrypted_by(),
536 metadata.salt(),
537 metadata.iv(),
538 metadata.aead_tag(),
539 ) {
540 (Some(&EncryptedBy::Password), Some(salt), Some(iv), Some(tag)) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700541 // Note that password encryption is AES no matter the value of algorithm
Paul Crowleyf61fee72021-03-17 14:38:44 -0700542 let key = pw.derive_key(Some(salt), AES_256_KEY_LENGTH).context(
543 "In extract_super_key_from_key_entry: Failed to generate key from password.",
544 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000545
546 aes_gcm_decrypt(blob, iv, tag, &key).context(
547 "In extract_super_key_from_key_entry: Failed to decrypt key blob.",
548 )?
549 }
550 (enc_by, salt, iv, tag) => {
551 return Err(Error::Rc(ResponseCode::VALUE_CORRUPTED)).context(format!(
552 concat!(
553 "In extract_super_key_from_key_entry: Super key has incomplete metadata.",
Paul Crowleye8826e52021-03-31 08:33:53 -0700554 "encrypted_by: {:?}; Present: salt: {}, iv: {}, aead_tag: {}."
Hasini Gunasingheda895552021-01-27 19:34:37 +0000555 ),
Paul Crowleye8826e52021-03-31 08:33:53 -0700556 enc_by,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000557 salt.is_some(),
558 iv.is_some(),
559 tag.is_some()
560 ));
561 }
562 };
Paul Crowley44c02da2021-04-08 17:04:43 +0000563 Ok(Arc::new(SuperKey {
564 algorithm,
565 key,
566 id: SuperKeyIdentifier::DatabaseId(entry.id()),
567 reencrypt_with,
568 }))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000569 } else {
570 Err(Error::Rc(ResponseCode::VALUE_CORRUPTED))
571 .context("In extract_super_key_from_key_entry: No key blob info.")
572 }
573 }
574
575 /// Encrypts the super key from a key derived from the password, before storing in the database.
Paul Crowleyf61fee72021-03-17 14:38:44 -0700576 pub fn encrypt_with_password(
577 super_key: &[u8],
578 pw: &Password,
579 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000580 let salt = generate_salt().context("In encrypt_with_password: Failed to generate salt.")?;
Paul Crowleyf61fee72021-03-17 14:38:44 -0700581 let derived_key = pw
582 .derive_key(Some(&salt), AES_256_KEY_LENGTH)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000583 .context("In encrypt_with_password: Failed to derive password.")?;
584 let mut metadata = BlobMetaData::new();
585 metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
586 metadata.add(BlobMetaEntry::Salt(salt));
587 let (encrypted_key, iv, tag) = aes_gcm_encrypt(super_key, &derived_key)
588 .context("In encrypt_with_password: Failed to encrypt new super key.")?;
589 metadata.add(BlobMetaEntry::Iv(iv));
590 metadata.add(BlobMetaEntry::AeadTag(tag));
591 Ok((encrypted_key, metadata))
592 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000593
594 // Encrypt the given key blob with the user's super key, if the super key exists and the device
595 // is unlocked. If the super key exists and the device is locked, or LSKF is not setup,
596 // return error. Note that it is out of the scope of this function to check if super encryption
597 // is required. Such check should be performed before calling this function.
598 fn super_encrypt_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000599 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000600 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000601 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700602 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000603 key_blob: &[u8],
604 ) -> Result<(Vec<u8>, BlobMetaData)> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000605 match UserState::get(db, legacy_migrator, self, user_id)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000606 .context("In super_encrypt. Failed to get user state.")?
607 {
608 UserState::LskfUnlocked(super_key) => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700609 Self::encrypt_with_aes_super_key(key_blob, &super_key)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000610 .context("In super_encrypt_on_key_init. Failed to encrypt the key.")
611 }
612 UserState::LskfLocked => {
613 Err(Error::Rc(ResponseCode::LOCKED)).context("In super_encrypt. Device is locked.")
614 }
615 UserState::Uninitialized => Err(Error::Rc(ResponseCode::UNINITIALIZED))
616 .context("In super_encrypt. LSKF is not setup for the user."),
617 }
618 }
619
620 //Helper function to encrypt a key with the given super key. Callers should select which super
621 //key to be used. This is called when a key is super encrypted at its creation as well as at its
622 //upgrade.
Paul Crowley8d5b2532021-03-19 10:53:07 -0700623 fn encrypt_with_aes_super_key(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000624 key_blob: &[u8],
625 super_key: &SuperKey,
626 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700627 if super_key.algorithm != SuperEncryptionAlgorithm::Aes256Gcm {
628 return Err(Error::sys())
629 .context("In encrypt_with_aes_super_key: unexpected algorithm");
630 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000631 let mut metadata = BlobMetaData::new();
632 let (encrypted_key, iv, tag) = aes_gcm_encrypt(key_blob, &(super_key.key))
Paul Crowley8d5b2532021-03-19 10:53:07 -0700633 .context("In encrypt_with_aes_super_key: Failed to encrypt new super key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000634 metadata.add(BlobMetaEntry::Iv(iv));
635 metadata.add(BlobMetaEntry::AeadTag(tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000636 super_key.id.add_to_metadata(&mut metadata);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000637 Ok((encrypted_key, metadata))
638 }
639
640 /// Check if super encryption is required and if so, super-encrypt the key to be stored in
641 /// the database.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000642 #[allow(clippy::clippy::too_many_arguments)]
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000643 pub fn handle_super_encryption_on_key_init(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000644 &self,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000645 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000646 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000647 domain: &Domain,
648 key_parameters: &[KeyParameter],
649 flags: Option<i32>,
Paul Crowley7a658392021-03-18 17:08:20 -0700650 user_id: UserId,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000651 key_blob: &[u8],
652 ) -> Result<(Vec<u8>, BlobMetaData)> {
Paul Crowley7a658392021-03-18 17:08:20 -0700653 match Enforcements::super_encryption_required(domain, key_parameters, flags) {
654 SuperEncryptionType::None => Ok((key_blob.to_vec(), BlobMetaData::new())),
Paul Crowleye8826e52021-03-31 08:33:53 -0700655 SuperEncryptionType::LskfBound => self
656 .super_encrypt_on_key_init(db, legacy_migrator, user_id, &key_blob)
657 .context(concat!(
658 "In handle_super_encryption_on_key_init. ",
659 "Failed to super encrypt with LskfBound key."
660 )),
Paul Crowley7a658392021-03-18 17:08:20 -0700661 SuperEncryptionType::ScreenLockBound => {
662 let mut data = self.data.lock().unwrap();
663 let entry = data.user_keys.entry(user_id).or_default();
664 if let Some(super_key) = entry.screen_lock_bound.as_ref() {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700665 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
Paul Crowley7a658392021-03-18 17:08:20 -0700666 "In handle_super_encryption_on_key_init. ",
Paul Crowleye8826e52021-03-31 08:33:53 -0700667 "Failed to encrypt with ScreenLockBound key."
Paul Crowley7a658392021-03-18 17:08:20 -0700668 ))
669 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700670 // Symmetric key is not available, use public key encryption
671 let loaded =
672 db.load_super_key(&USER_SCREEN_LOCK_BOUND_ECDH_KEY, user_id).context(
673 "In handle_super_encryption_on_key_init: load_super_key failed.",
674 )?;
675 let (key_id_guard, key_entry) = loaded.ok_or_else(Error::sys).context(
676 "In handle_super_encryption_on_key_init: User ECDH key missing.",
677 )?;
678 let public_key =
679 key_entry.metadata().sec1_public_key().ok_or_else(Error::sys).context(
680 "In handle_super_encryption_on_key_init: sec1_public_key missing.",
681 )?;
682 let mut metadata = BlobMetaData::new();
683 let (ephem_key, salt, iv, encrypted_key, aead_tag) =
684 ECDHPrivateKey::encrypt_message(public_key, key_blob).context(concat!(
685 "In handle_super_encryption_on_key_init: ",
686 "ECDHPrivateKey::encrypt_message failed."
687 ))?;
688 metadata.add(BlobMetaEntry::PublicKey(ephem_key));
689 metadata.add(BlobMetaEntry::Salt(salt));
690 metadata.add(BlobMetaEntry::Iv(iv));
691 metadata.add(BlobMetaEntry::AeadTag(aead_tag));
Paul Crowley44c02da2021-04-08 17:04:43 +0000692 SuperKeyIdentifier::DatabaseId(key_id_guard.id())
693 .add_to_metadata(&mut metadata);
Paul Crowley8d5b2532021-03-19 10:53:07 -0700694 Ok((encrypted_key, metadata))
Paul Crowley7a658392021-03-18 17:08:20 -0700695 }
696 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000697 SuperEncryptionType::BootLevel(level) => {
698 let key_id = SuperKeyIdentifier::BootLevel(level);
699 let super_key = self
700 .lookup_key(&key_id)
701 .context("In handle_super_encryption_on_key_init: lookup_key failed")?
702 .ok_or(Error::Rc(ResponseCode::LOCKED))
703 .context("In handle_super_encryption_on_key_init: Boot stage key absent")?;
704 Self::encrypt_with_aes_super_key(key_blob, &super_key).context(concat!(
705 "In handle_super_encryption_on_key_init: ",
706 "Failed to encrypt with BootLevel key."
707 ))
708 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000709 }
710 }
711
712 /// Check if a given key needs re-super-encryption, from its KeyBlob type.
713 /// If so, re-super-encrypt the key and return a new set of metadata,
714 /// containing the new super encryption information.
Paul Crowley7a658392021-03-18 17:08:20 -0700715 pub fn reencrypt_if_required<'a>(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000716 key_blob_before_upgrade: &KeyBlob,
717 key_after_upgrade: &'a [u8],
718 ) -> Result<(KeyBlob<'a>, Option<BlobMetaData>)> {
719 match key_blob_before_upgrade {
Paul Crowley7a658392021-03-18 17:08:20 -0700720 KeyBlob::Sensitive { reencrypt_with: super_key, .. } => {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700721 let (key, metadata) =
722 Self::encrypt_with_aes_super_key(key_after_upgrade, super_key)
723 .context("In reencrypt_if_required: Failed to re-super-encrypt key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000724 Ok((KeyBlob::NonSensitive(key), Some(metadata)))
725 }
726 _ => Ok((KeyBlob::Ref(key_after_upgrade), None)),
727 }
728 }
729
Paul Crowley7a658392021-03-18 17:08:20 -0700730 /// Fetch a superencryption key from the database, or create it if it doesn't already exist.
731 /// When this is called, the caller must hold the lock on the SuperKeyManager.
732 /// So it's OK that the check and creation are different DB transactions.
733 fn get_or_create_super_key(
734 db: &mut KeystoreDB,
735 user_id: UserId,
736 key_type: &SuperKeyType,
737 password: &Password,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700738 reencrypt_with: Option<Arc<SuperKey>>,
Paul Crowley7a658392021-03-18 17:08:20 -0700739 ) -> Result<Arc<SuperKey>> {
740 let loaded_key = db.load_super_key(key_type, user_id)?;
741 if let Some((_, key_entry)) = loaded_key {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700742 Ok(Self::extract_super_key_from_key_entry(
743 key_type.algorithm,
744 key_entry,
745 password,
746 reencrypt_with,
747 )?)
Paul Crowley7a658392021-03-18 17:08:20 -0700748 } else {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700749 let (super_key, public_key) = match key_type.algorithm {
750 SuperEncryptionAlgorithm::Aes256Gcm => (
751 generate_aes256_key()
752 .context("In get_or_create_super_key: Failed to generate AES 256 key.")?,
753 None,
754 ),
755 SuperEncryptionAlgorithm::EcdhP256 => {
756 let key = ECDHPrivateKey::generate()
757 .context("In get_or_create_super_key: Failed to generate ECDH key")?;
758 (
759 key.private_key()
760 .context("In get_or_create_super_key: private_key failed")?,
761 Some(
762 key.public_key()
763 .context("In get_or_create_super_key: public_key failed")?,
764 ),
765 )
766 }
767 };
Paul Crowley7a658392021-03-18 17:08:20 -0700768 //derive an AES256 key from the password and re-encrypt the super key
769 //before we insert it in the database.
770 let (encrypted_super_key, blob_metadata) =
771 Self::encrypt_with_password(&super_key, password)
772 .context("In get_or_create_super_key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700773 let mut key_metadata = KeyMetaData::new();
774 if let Some(pk) = public_key {
775 key_metadata.add(KeyMetaEntry::Sec1PublicKey(pk));
776 }
Paul Crowley7a658392021-03-18 17:08:20 -0700777 let key_entry = db
Paul Crowley8d5b2532021-03-19 10:53:07 -0700778 .store_super_key(
779 user_id,
780 key_type,
781 &encrypted_super_key,
782 &blob_metadata,
783 &key_metadata,
784 )
Paul Crowley7a658392021-03-18 17:08:20 -0700785 .context("In get_or_create_super_key. Failed to store super key.")?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700786 Ok(Arc::new(SuperKey {
787 algorithm: key_type.algorithm,
788 key: super_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000789 id: SuperKeyIdentifier::DatabaseId(key_entry.id()),
Paul Crowley8d5b2532021-03-19 10:53:07 -0700790 reencrypt_with,
791 }))
Paul Crowley7a658392021-03-18 17:08:20 -0700792 }
793 }
794
Paul Crowley8d5b2532021-03-19 10:53:07 -0700795 /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700796 pub fn unlock_screen_lock_bound_key(
797 &self,
798 db: &mut KeystoreDB,
799 user_id: UserId,
800 password: &Password,
801 ) -> Result<()> {
802 let mut data = self.data.lock().unwrap();
803 let entry = data.user_keys.entry(user_id).or_default();
804 let aes = entry
805 .screen_lock_bound
806 .get_or_try_to_insert_with(|| {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700807 Self::get_or_create_super_key(
808 db,
809 user_id,
810 &USER_SCREEN_LOCK_BOUND_KEY,
811 password,
812 None,
813 )
814 })?
815 .clone();
816 let ecdh = entry
817 .screen_lock_bound_private
818 .get_or_try_to_insert_with(|| {
819 Self::get_or_create_super_key(
820 db,
821 user_id,
822 &USER_SCREEN_LOCK_BOUND_ECDH_KEY,
823 password,
824 Some(aes.clone()),
825 )
Paul Crowley7a658392021-03-18 17:08:20 -0700826 })?
827 .clone();
Paul Crowley44c02da2021-04-08 17:04:43 +0000828 data.add_key_to_key_index(&aes)?;
829 data.add_key_to_key_index(&ecdh)?;
Paul Crowley7a658392021-03-18 17:08:20 -0700830 Ok(())
831 }
832
Paul Crowley8d5b2532021-03-19 10:53:07 -0700833 /// Wipe the screen-lock bound keys for this user from memory.
Paul Crowley7a658392021-03-18 17:08:20 -0700834 pub fn lock_screen_lock_bound_key(&self, user_id: UserId) {
835 let mut data = self.data.lock().unwrap();
836 let mut entry = data.user_keys.entry(user_id).or_default();
837 entry.screen_lock_bound = None;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700838 entry.screen_lock_bound_private = None;
Paul Crowley7a658392021-03-18 17:08:20 -0700839 }
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000840}
841
842/// This enum represents different states of the user's life cycle in the device.
843/// For now, only three states are defined. More states may be added later.
844pub enum UserState {
845 // The user has registered LSKF and has unlocked the device by entering PIN/Password,
846 // and hence the per-boot super key is available in the cache.
Paul Crowley7a658392021-03-18 17:08:20 -0700847 LskfUnlocked(Arc<SuperKey>),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000848 // The user has registered LSKF, but has not unlocked the device using password, after reboot.
849 // Hence the per-boot super-key(s) is not available in the cache.
850 // However, the encrypted super key is available in the database.
851 LskfLocked,
852 // There's no user in the device for the given user id, or the user with the user id has not
853 // setup LSKF.
854 Uninitialized,
855}
856
857impl UserState {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000858 pub fn get(
859 db: &mut KeystoreDB,
860 legacy_migrator: &LegacyMigrator,
861 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700862 user_id: UserId,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000863 ) -> Result<UserState> {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000864 match skm.get_per_boot_key_by_user_id(user_id) {
865 Some(super_key) => Ok(UserState::LskfUnlocked(super_key)),
866 None => {
867 //Check if a super key exists in the database or legacy database.
868 //If so, return locked user state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000869 if SuperKeyManager::super_key_exists_in_db_for_user(db, legacy_migrator, user_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000870 .context("In get.")?
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000871 {
872 Ok(UserState::LskfLocked)
873 } else {
874 Ok(UserState::Uninitialized)
875 }
876 }
877 }
878 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000879
880 /// Queries user state when serving password change requests.
881 pub fn get_with_password_changed(
882 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000883 legacy_migrator: &LegacyMigrator,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000884 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700885 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700886 password: Option<&Password>,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000887 ) -> Result<UserState> {
888 match skm.get_per_boot_key_by_user_id(user_id) {
889 Some(super_key) => {
890 if password.is_none() {
891 //transitioning to swiping, delete only the super key in database and cache, and
892 //super-encrypted keys in database (and in KM)
Janis Danisevskiseed69842021-02-18 20:04:10 -0800893 Self::reset_user(db, skm, legacy_migrator, user_id, true).context(
894 "In get_with_password_changed: Trying to delete keys from the db.",
895 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +0000896 //Lskf is now removed in Keystore
897 Ok(UserState::Uninitialized)
898 } else {
899 //Keystore won't be notified when changing to a new password when LSKF is
900 //already setup. Therefore, ideally this path wouldn't be reached.
901 Ok(UserState::LskfUnlocked(super_key))
902 }
903 }
904 None => {
905 //Check if a super key exists in the database or legacy database.
906 //If so, return LskfLocked state.
907 //Otherwise, i) if the password is provided, initialize the super key and return
908 //LskfUnlocked state ii) if password is not provided, return Uninitialized state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000909 skm.check_and_initialize_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000910 }
911 }
912 }
913
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000914 /// Queries user state when serving password unlock requests.
915 pub fn get_with_password_unlock(
916 db: &mut KeystoreDB,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000917 legacy_migrator: &LegacyMigrator,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000918 skm: &SuperKeyManager,
Paul Crowley7a658392021-03-18 17:08:20 -0700919 user_id: UserId,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700920 password: &Password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000921 ) -> Result<UserState> {
922 match skm.get_per_boot_key_by_user_id(user_id) {
923 Some(super_key) => {
924 log::info!("In get_with_password_unlock. Trying to unlock when already unlocked.");
925 Ok(UserState::LskfUnlocked(super_key))
926 }
927 None => {
928 //Check if a super key exists in the database or legacy database.
929 //If not, return Uninitialized state.
930 //Otherwise, try to unlock the super key and if successful,
931 //return LskfUnlocked state
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000932 skm.check_and_unlock_super_key(db, legacy_migrator, user_id, password)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000933 .context("In get_with_password_unlock. Failed to unlock super key.")
934 }
935 }
936 }
937
Hasini Gunasingheda895552021-01-27 19:34:37 +0000938 /// Delete all the keys created on behalf of the user.
939 /// If 'keep_non_super_encrypted_keys' is set to true, delete only the super key and super
940 /// encrypted keys.
941 pub fn reset_user(
942 db: &mut KeystoreDB,
943 skm: &SuperKeyManager,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800944 legacy_migrator: &LegacyMigrator,
Paul Crowley7a658392021-03-18 17:08:20 -0700945 user_id: UserId,
Hasini Gunasingheda895552021-01-27 19:34:37 +0000946 keep_non_super_encrypted_keys: bool,
947 ) -> Result<()> {
948 // mark keys created on behalf of the user as unreferenced.
Janis Danisevskiseed69842021-02-18 20:04:10 -0800949 legacy_migrator
950 .bulk_delete_user(user_id, keep_non_super_encrypted_keys)
951 .context("In reset_user: Trying to delete legacy keys.")?;
Paul Crowley7a658392021-03-18 17:08:20 -0700952 db.unbind_keys_for_user(user_id, keep_non_super_encrypted_keys)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000953 .context("In reset user. Error in unbinding keys.")?;
954
955 //delete super key in cache, if exists
Paul Crowley7a658392021-03-18 17:08:20 -0700956 skm.forget_all_keys_for_user(user_id);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000957 Ok(())
958 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800959}
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000960
Janis Danisevskiseed69842021-02-18 20:04:10 -0800961/// This enum represents three states a KeyMint Blob can be in, w.r.t super encryption.
962/// `Sensitive` holds the non encrypted key and a reference to its super key.
963/// `NonSensitive` holds a non encrypted key that is never supposed to be encrypted.
964/// `Ref` holds a reference to a key blob when it does not need to be modified if its
965/// life time allows it.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000966pub enum KeyBlob<'a> {
Paul Crowley8d5b2532021-03-19 10:53:07 -0700967 Sensitive {
968 key: ZVec,
969 /// If KeyMint reports that the key must be upgraded, we must
970 /// re-encrypt the key before writing to the database; we use
971 /// this key.
972 reencrypt_with: Arc<SuperKey>,
973 /// If this key was decrypted with an ECDH key, we want to
974 /// re-encrypt it on first use whether it was upgraded or not;
975 /// this field indicates that that's necessary.
976 force_reencrypt: bool,
977 },
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000978 NonSensitive(Vec<u8>),
979 Ref(&'a [u8]),
980}
981
Paul Crowley8d5b2532021-03-19 10:53:07 -0700982impl<'a> KeyBlob<'a> {
983 pub fn force_reencrypt(&self) -> bool {
984 if let KeyBlob::Sensitive { force_reencrypt, .. } = self {
985 *force_reencrypt
986 } else {
987 false
988 }
989 }
990}
991
Janis Danisevskiseed69842021-02-18 20:04:10 -0800992/// Deref returns a reference to the key material in any variant.
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000993impl<'a> Deref for KeyBlob<'a> {
994 type Target = [u8];
995
996 fn deref(&self) -> &Self::Target {
997 match self {
Paul Crowley7a658392021-03-18 17:08:20 -0700998 Self::Sensitive { key, .. } => &key,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000999 Self::NonSensitive(key) => &key,
1000 Self::Ref(key) => key,
1001 }
1002 }
1003}