blob: 1ae871977b12d334c356db6849bf8820989a35af [file] [log] [blame]
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001// Copyright 2021, 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
15//! This module acts as a bridge between the legacy key database and the keystore2 database.
16
17use crate::database::{
18 BlobMetaData, BlobMetaEntry, CertificateInfo, DateTime, EncryptedBy, KeyMetaData, KeyMetaEntry,
19 KeystoreDB, Uuid, KEYSTORE_UUID,
20};
21use crate::error::Error;
Janis Danisevskiseed69842021-02-18 20:04:10 -080022use crate::key_parameter::KeyParameterValue;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000023use crate::legacy_blob::BlobValue;
24use crate::utils::uid_to_android_user;
25use crate::{async_task::AsyncTask, legacy_blob::LegacyBlobLoader};
26use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
27use android_system_keystore2::aidl::android::system::keystore2::{
28 Domain::Domain, KeyDescriptor::KeyDescriptor, ResponseCode::ResponseCode,
29};
30use anyhow::{Context, Result};
31use core::ops::Deref;
32use keystore2_crypto::ZVec;
33use std::collections::{HashMap, HashSet};
34use std::convert::TryInto;
35use std::sync::atomic::{AtomicU8, Ordering};
36use std::sync::mpsc::channel;
37use std::sync::{Arc, Mutex};
38
39/// Represents LegacyMigrator.
40pub struct LegacyMigrator {
41 async_task: Arc<AsyncTask>,
42 initializer: Mutex<
43 Option<
44 Box<
45 dyn FnOnce() -> (KeystoreDB, HashMap<SecurityLevel, Uuid>, Arc<LegacyBlobLoader>)
46 + Send
47 + 'static,
48 >,
49 >,
50 >,
51 /// This atomic is used for cheap interior mutability. It is intended to prevent
52 /// expensive calls into the legacy migrator when the legacy database is empty.
53 /// When transitioning from READY to EMPTY, spurious calls may occur for a brief period
54 /// of time. This is tolerable in favor of the common case.
55 state: AtomicU8,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
59struct RecentMigration {
60 uid: u32,
61 alias: String,
62}
63
64impl RecentMigration {
65 fn new(uid: u32, alias: String) -> Self {
66 Self { uid, alias }
67 }
68}
69
Janis Danisevskiseed69842021-02-18 20:04:10 -080070enum BulkDeleteRequest {
71 Uid(u32),
72 User(u32),
73}
74
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000075struct LegacyMigratorState {
76 recently_migrated: HashSet<RecentMigration>,
77 recently_migrated_super_key: HashSet<u32>,
78 legacy_loader: Arc<LegacyBlobLoader>,
79 sec_level_to_km_uuid: HashMap<SecurityLevel, Uuid>,
80 db: KeystoreDB,
81}
82
83impl LegacyMigrator {
84 const WIFI_NAMESPACE: i64 = 102;
85 const AID_WIFI: u32 = 1010;
86
87 const STATE_UNINITIALIZED: u8 = 0;
88 const STATE_READY: u8 = 1;
89 const STATE_EMPTY: u8 = 2;
90
91 /// Constructs a new LegacyMigrator using the given AsyncTask object as migration
92 /// worker.
93 pub fn new(async_task: Arc<AsyncTask>) -> Self {
94 Self {
95 async_task,
96 initializer: Default::default(),
97 state: AtomicU8::new(Self::STATE_UNINITIALIZED),
98 }
99 }
100
101 /// The legacy migrator must be initialized deferred, because keystore starts very early.
102 /// At this time the data partition may not be mounted. So we cannot open database connections
103 /// until we get actual key load requests. This sets the function that the legacy loader
104 /// uses to connect to the database.
105 pub fn set_init<F>(&self, f_init: F) -> Result<()>
106 where
107 F: FnOnce() -> (KeystoreDB, HashMap<SecurityLevel, Uuid>, Arc<LegacyBlobLoader>)
108 + Send
109 + 'static,
110 {
111 let mut initializer = self.initializer.lock().expect("Failed to lock initializer.");
112
113 // If we are not uninitialized we have no business setting the initializer.
114 if self.state.load(Ordering::Relaxed) != Self::STATE_UNINITIALIZED {
115 return Ok(());
116 }
117
118 // Only set the initializer if it hasn't been set before.
119 if initializer.is_none() {
120 *initializer = Some(Box::new(f_init))
121 }
122
123 Ok(())
124 }
125
126 /// This function is called by the migration requestor to check if it is worth
127 /// making a migration request. It also transitions the state from UNINITIALIZED
128 /// to READY or EMPTY on first use. The deferred initialization is necessary, because
129 /// Keystore 2.0 runs early during boot, where data may not yet be mounted.
130 /// Returns Ok(STATE_READY) if a migration request is worth undertaking and
131 /// Ok(STATE_EMPTY) if the database is empty. An error is returned if the loader
132 /// was not initialized and cannot be initialized.
133 fn check_state(&self) -> Result<u8> {
134 let mut first_try = true;
135 loop {
136 match (self.state.load(Ordering::Relaxed), first_try) {
137 (Self::STATE_EMPTY, _) => {
138 return Ok(Self::STATE_EMPTY);
139 }
140 (Self::STATE_UNINITIALIZED, true) => {
141 // If we find the legacy loader uninitialized, we grab the initializer lock,
142 // check if the legacy database is empty, and if not, schedule an initialization
143 // request. Coming out of the initializer lock, the state is either EMPTY or
144 // READY.
145 let mut initializer = self.initializer.lock().unwrap();
146
147 if let Some(initializer) = initializer.take() {
148 let (db, sec_level_to_km_uuid, legacy_loader) = (initializer)();
149
150 if legacy_loader.is_empty().context(
151 "In check_state: Trying to check if the legacy database is empty.",
152 )? {
153 self.state.store(Self::STATE_EMPTY, Ordering::Relaxed);
154 return Ok(Self::STATE_EMPTY);
155 }
156
157 self.async_task.queue_hi(move |shelf| {
158 shelf.get_or_put_with(|| LegacyMigratorState {
159 recently_migrated: Default::default(),
160 recently_migrated_super_key: Default::default(),
161 legacy_loader,
162 sec_level_to_km_uuid,
163 db,
164 });
165 });
166
167 // It is safe to set this here even though the async task may not yet have
168 // run because any thread observing this will not be able to schedule a
169 // task that can run before the initialization.
170 // Also we can only transition out of this state while having the
171 // initializer lock and having found an initializer.
172 self.state.store(Self::STATE_READY, Ordering::Relaxed);
173 return Ok(Self::STATE_READY);
174 } else {
175 // There is a chance that we just lost the race from state.load() to
176 // grabbing the initializer mutex. If that is the case the state must
177 // be EMPTY or READY after coming out of the lock. So we can give it
178 // one more try.
179 first_try = false;
180 continue;
181 }
182 }
183 (Self::STATE_UNINITIALIZED, false) => {
184 // Okay, tough luck. The legacy loader was really completely uninitialized.
185 return Err(Error::sys()).context(
186 "In check_state: Legacy loader should not be called uninitialized.",
187 );
188 }
189 (Self::STATE_READY, _) => return Ok(Self::STATE_READY),
190 (s, _) => panic!("Unknown legacy migrator state. {} ", s),
191 }
192 }
193 }
194
195 /// List all aliases for uid in the legacy database.
196 pub fn list_uid(&self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
197 let uid = match (domain, namespace) {
198 (Domain::APP, namespace) => namespace as u32,
199 (Domain::SELINUX, Self::WIFI_NAMESPACE) => Self::AID_WIFI,
200 _ => return Ok(Vec::new()),
201 };
202 self.do_serialized(move |state| state.list_uid(uid)).unwrap_or_else(|| Ok(Vec::new())).map(
203 |v| {
204 v.into_iter()
205 .map(|alias| KeyDescriptor {
206 domain,
207 nspace: namespace,
208 alias: Some(alias),
209 blob: None,
210 })
211 .collect()
212 },
213 )
214 }
215
216 /// Sends the given closure to the migrator thread for execution after calling check_state.
217 /// Returns None if the database was empty and the request was not executed.
218 /// Otherwise returns Some with the result produced by the migration request.
219 /// The loader state may transition to STATE_EMPTY during the execution of this function.
220 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Option<Result<T>>
221 where
222 F: FnOnce(&mut LegacyMigratorState) -> Result<T> + Send + 'static,
223 {
224 // Short circuit if the database is empty or not initialized (error case).
225 match self.check_state().context("In do_serialized: Checking state.") {
226 Ok(LegacyMigrator::STATE_EMPTY) => return None,
227 Ok(LegacyMigrator::STATE_READY) => {}
228 Err(e) => return Some(Err(e)),
229 Ok(s) => panic!("Unknown legacy migrator state. {} ", s),
230 }
231
232 // We have established that there may be a key in the legacy database.
233 // Now we schedule a migration request.
234 let (sender, receiver) = channel();
235 self.async_task.queue_hi(move |shelf| {
236 // Get the migrator state from the shelf.
237 // There may not be a state. This can happen if this migration request was scheduled
238 // before a previous request established that the legacy database was empty
239 // and removed the state from the shelf. Since we know now that the database
240 // is empty, we can return None here.
241 let (new_state, result) = if let Some(legacy_migrator_state) =
242 shelf.get_downcast_mut::<LegacyMigratorState>()
243 {
244 let result = f(legacy_migrator_state);
245 (legacy_migrator_state.check_empty(), Some(result))
246 } else {
247 (Self::STATE_EMPTY, None)
248 };
249
250 // If the migration request determined that the database is now empty, we discard
251 // the state from the shelf to free up the resources we won't need any longer.
252 if result.is_some() && new_state == Self::STATE_EMPTY {
253 shelf.remove_downcast_ref::<LegacyMigratorState>();
254 }
255
256 // Send the result to the requester.
257 if let Err(e) = sender.send((new_state, result)) {
258 log::error!("In do_serialized. Error in sending the result. {:?}", e);
259 }
260 });
261
262 let (new_state, result) = match receiver.recv() {
263 Err(e) => {
264 return Some(Err(e).context("In do_serialized. Failed to receive from the sender."))
265 }
266 Ok(r) => r,
267 };
268
269 // We can only transition to EMPTY but never back.
270 // The migrator never creates any legacy blobs.
271 if new_state == Self::STATE_EMPTY {
272 self.state.store(Self::STATE_EMPTY, Ordering::Relaxed)
273 }
274
275 result
276 }
277
278 /// Runs the key_accessor function and returns its result. If it returns an error and the
279 /// root cause was KEY_NOT_FOUND, tries to migrate a key with the given parameters from
280 /// the legacy database to the new database and runs the key_accessor function again if
281 /// the migration request was successful.
282 pub fn with_try_migrate<F, T>(
283 &self,
284 key: &KeyDescriptor,
285 caller_uid: u32,
286 key_accessor: F,
287 ) -> Result<T>
288 where
289 F: Fn() -> Result<T>,
290 {
291 // Access the key and return on success.
292 match key_accessor() {
293 Ok(result) => return Ok(result),
294 Err(e) => match e.root_cause().downcast_ref::<Error>() {
295 Some(&Error::Rc(ResponseCode::KEY_NOT_FOUND)) => {}
296 _ => return Err(e),
297 },
298 }
299
300 // Filter inputs. We can only load legacy app domain keys and some special rules due
301 // to which we migrate keys transparently to an SELINUX domain.
302 let uid = match key {
303 KeyDescriptor { domain: Domain::APP, alias: Some(_), .. } => caller_uid,
304 KeyDescriptor { domain: Domain::SELINUX, nspace, alias: Some(_), .. } => {
305 match *nspace {
306 Self::WIFI_NAMESPACE => Self::AID_WIFI,
307 _ => {
308 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
309 .context(format!("No legacy keys for namespace {}", nspace))
310 }
311 }
312 }
313 _ => {
314 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
315 .context("No legacy keys for key descriptor.")
316 }
317 };
318
319 let key_clone = key.clone();
320 let result = self
321 .do_serialized(move |migrator_state| migrator_state.check_and_migrate(uid, key_clone));
322
323 if let Some(result) = result {
324 result?;
325 // After successful migration try again.
326 key_accessor()
327 } else {
328 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND)).context("Legacy database is empty.")
329 }
330 }
331
332 /// Calls key_accessor and returns the result on success. In the case of a KEY_NOT_FOUND error
333 /// this function makes a migration request and on success retries the key_accessor.
334 pub fn with_try_migrate_super_key<F, T>(
335 &self,
336 user_id: u32,
337 pw: &[u8],
338 mut key_accessor: F,
339 ) -> Result<Option<T>>
340 where
341 F: FnMut() -> Result<Option<T>>,
342 {
343 match key_accessor() {
344 Ok(Some(result)) => return Ok(Some(result)),
345 Ok(None) => {}
346 Err(e) => return Err(e),
347 }
348
349 let pw: ZVec = pw
350 .try_into()
351 .context("In with_try_migrate_super_key: copying the password into a zvec.")?;
352 let result = self.do_serialized(move |migrator_state| {
353 migrator_state.check_and_migrate_super_key(user_id, pw)
354 });
355
356 if let Some(result) = result {
357 result?;
358 // After successful migration try again.
359 key_accessor()
360 } else {
361 Ok(None)
362 }
363 }
364
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800365 /// Deletes all keys belonging to the given namespace, migrating them into the database
Janis Danisevskiseed69842021-02-18 20:04:10 -0800366 /// for subsequent garbage collection if necessary.
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800367 pub fn bulk_delete_uid(&self, domain: Domain, nspace: i64) -> Result<()> {
368 let uid = match (domain, nspace) {
369 (Domain::APP, nspace) => nspace as u32,
370 (Domain::SELINUX, Self::WIFI_NAMESPACE) => Self::AID_WIFI,
371 // Nothing to do.
372 _ => return Ok(()),
373 };
374
Janis Danisevskiseed69842021-02-18 20:04:10 -0800375 let result = self.do_serialized(move |migrator_state| {
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800376 migrator_state.bulk_delete(BulkDeleteRequest::Uid(uid), false)
Janis Danisevskiseed69842021-02-18 20:04:10 -0800377 });
378
379 result.unwrap_or(Ok(()))
380 }
381
382 /// Deletes all keys belonging to the given android user, migrating them into the database
383 /// for subsequent garbage collection if necessary.
384 pub fn bulk_delete_user(
385 &self,
386 user_id: u32,
387 keep_non_super_encrypted_keys: bool,
388 ) -> Result<()> {
389 let result = self.do_serialized(move |migrator_state| {
390 migrator_state
391 .bulk_delete(BulkDeleteRequest::User(user_id), keep_non_super_encrypted_keys)
392 });
393
394 result.unwrap_or(Ok(()))
395 }
396
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000397 /// Queries the legacy database for the presence of a super key for the given user.
398 pub fn has_super_key(&self, user_id: u32) -> Result<bool> {
399 let result =
400 self.do_serialized(move |migrator_state| migrator_state.has_super_key(user_id));
401 result.unwrap_or(Ok(false))
402 }
403}
404
405impl LegacyMigratorState {
406 fn get_km_uuid(&self, is_strongbox: bool) -> Result<Uuid> {
407 let sec_level = if is_strongbox {
408 SecurityLevel::STRONGBOX
409 } else {
410 SecurityLevel::TRUSTED_ENVIRONMENT
411 };
412
413 self.sec_level_to_km_uuid.get(&sec_level).copied().ok_or_else(|| {
414 anyhow::anyhow!(Error::sys()).context("In get_km_uuid: No KM instance for blob.")
415 })
416 }
417
418 fn list_uid(&mut self, uid: u32) -> Result<Vec<String>> {
419 self.legacy_loader
420 .list_keystore_entries_for_uid(uid)
421 .context("In list_uid: Trying to list legacy entries.")
422 }
423
424 /// This is a key migration request that can run in the migrator thread. This should
425 /// be passed to do_serialized.
426 fn check_and_migrate(&mut self, uid: u32, mut key: KeyDescriptor) -> Result<()> {
427 let alias = key.alias.clone().ok_or_else(|| {
428 anyhow::anyhow!(Error::sys()).context(concat!(
429 "In check_and_migrate: Must be Some because ",
430 "our caller must not have called us otherwise."
431 ))
432 })?;
433
434 if self.recently_migrated.contains(&RecentMigration::new(uid, alias.clone())) {
435 return Ok(());
436 }
437
438 if key.domain == Domain::APP {
439 key.nspace = uid as i64;
440 }
441
442 // If the key is not found in the cache, try to load from the legacy database.
443 let (km_blob_params, user_cert, ca_cert) = self
444 .legacy_loader
445 .load_by_uid_alias(uid, &alias, None)
446 .context("In check_and_migrate: Trying to load legacy blob.")?;
447 let result = match km_blob_params {
448 Some((km_blob, params)) => {
449 let is_strongbox = km_blob.is_strongbox();
450 let (blob, mut blob_metadata) = match km_blob.take_value() {
451 BlobValue::Encrypted { iv, tag, data } => {
452 // Get super key id for user id.
453 let user_id = uid_to_android_user(uid as u32);
454
455 let super_key_id = match self
456 .db
457 .load_super_key(user_id)
458 .context("In check_and_migrate: Failed to load super key")?
459 {
460 Some((_, entry)) => entry.id(),
461 None => {
462 // This might be the first time we access the super key,
463 // and it may not have been migrated. We cannot import
464 // the legacy super_key key now, because we need to reencrypt
465 // it which we cannot do if we are not unlocked, which we are
466 // not because otherwise the key would have been migrated.
467 // We can check though if the key exists. If it does,
468 // we can return Locked. Otherwise, we can delete the
469 // key and return NotFound, because the key will never
470 // be unlocked again.
471 if self.legacy_loader.has_super_key(user_id) {
472 return Err(Error::Rc(ResponseCode::LOCKED)).context(concat!(
473 "In check_and_migrate: Cannot migrate super key of this ",
474 "key while user is locked."
475 ));
476 } else {
477 self.legacy_loader.remove_keystore_entry(uid, &alias).context(
478 concat!(
479 "In check_and_migrate: ",
480 "Trying to remove obsolete key."
481 ),
482 )?;
483 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
484 .context("In check_and_migrate: Obsolete key.");
485 }
486 }
487 };
488
489 let mut blob_metadata = BlobMetaData::new();
490 blob_metadata.add(BlobMetaEntry::Iv(iv.to_vec()));
491 blob_metadata.add(BlobMetaEntry::AeadTag(tag.to_vec()));
492 blob_metadata
493 .add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
494 (LegacyBlob::Vec(data), blob_metadata)
495 }
496 BlobValue::Decrypted(data) => (LegacyBlob::ZVec(data), BlobMetaData::new()),
497 _ => {
498 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
499 .context("In check_and_migrate: Legacy key has unexpected type.")
500 }
501 };
502
503 let km_uuid = self
504 .get_km_uuid(is_strongbox)
505 .context("In check_and_migrate: Trying to get KM UUID")?;
506 blob_metadata.add(BlobMetaEntry::KmUuid(km_uuid));
507
508 let mut metadata = KeyMetaData::new();
509 let creation_date = DateTime::now()
510 .context("In check_and_migrate: Trying to make creation time.")?;
511 metadata.add(KeyMetaEntry::CreationDate(creation_date));
512
513 // Store legacy key in the database.
514 self.db
515 .store_new_key(
516 &key,
517 &params,
518 &(&blob, &blob_metadata),
519 &CertificateInfo::new(user_cert, ca_cert),
520 &metadata,
521 &km_uuid,
522 )
523 .context("In check_and_migrate.")?;
524 Ok(())
525 }
526 None => {
527 if let Some(ca_cert) = ca_cert {
528 self.db
529 .store_new_certificate(&key, &ca_cert, &KEYSTORE_UUID)
530 .context("In check_and_migrate: Failed to insert new certificate.")?;
531 Ok(())
532 } else {
533 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
534 .context("In check_and_migrate: Legacy key not found.")
535 }
536 }
537 };
538
539 match result {
540 Ok(()) => {
541 // Add the key to the migrated_keys list.
542 self.recently_migrated.insert(RecentMigration::new(uid, alias.clone()));
543 // Delete legacy key from the file system
544 self.legacy_loader
545 .remove_keystore_entry(uid, &alias)
546 .context("In check_and_migrate: Trying to remove migrated key.")?;
547 Ok(())
548 }
549 Err(e) => Err(e),
550 }
551 }
552
553 fn check_and_migrate_super_key(&mut self, user_id: u32, pw: ZVec) -> Result<()> {
554 if self.recently_migrated_super_key.contains(&user_id) {
555 return Ok(());
556 }
557
558 if let Some(super_key) = self
559 .legacy_loader
560 .load_super_key(user_id, &pw)
561 .context("In check_and_migrate_super_key: Trying to load legacy super key.")?
562 {
563 let (blob, blob_metadata) =
564 crate::super_key::SuperKeyManager::encrypt_with_password(&super_key, &pw)
565 .context("In check_and_migrate_super_key: Trying to encrypt super key.")?;
566
567 self.db.store_super_key(user_id, &(&blob, &blob_metadata)).context(concat!(
568 "In check_and_migrate_super_key: ",
569 "Trying to insert legacy super_key into the database."
570 ))?;
571 self.legacy_loader.remove_super_key(user_id);
572 self.recently_migrated_super_key.insert(user_id);
573 Ok(())
574 } else {
575 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
576 .context("In check_and_migrate_super_key: No key found do migrate.")
577 }
578 }
579
Janis Danisevskiseed69842021-02-18 20:04:10 -0800580 /// Key migrator request to be run by do_serialized.
581 /// See LegacyMigrator::bulk_delete_uid and LegacyMigrator::bulk_delete_user.
582 fn bulk_delete(
583 &mut self,
584 bulk_delete_request: BulkDeleteRequest,
585 keep_non_super_encrypted_keys: bool,
586 ) -> Result<()> {
587 let (aliases, user_id) = match bulk_delete_request {
588 BulkDeleteRequest::Uid(uid) => (
589 self.legacy_loader
590 .list_keystore_entries_for_uid(uid)
591 .context("In bulk_delete: Trying to get aliases for uid.")
592 .map(|aliases| {
593 let mut h = HashMap::<u32, HashSet<String>>::new();
594 h.insert(uid, aliases.into_iter().collect());
595 h
596 })?,
597 uid_to_android_user(uid),
598 ),
599 BulkDeleteRequest::User(user_id) => (
600 self.legacy_loader
601 .list_keystore_entries_for_user(user_id)
602 .context("In bulk_delete: Trying to get aliases for user_id.")?,
603 user_id,
604 ),
605 };
606
607 let super_key_id = self
608 .db
609 .load_super_key(user_id)
610 .context("In bulk_delete: Failed to load super key")?
611 .map(|(_, entry)| entry.id());
612
613 for (uid, alias) in aliases
614 .into_iter()
615 .map(|(uid, aliases)| aliases.into_iter().map(move |alias| (uid, alias)))
616 .flatten()
617 {
618 let (km_blob_params, _, _) = self
619 .legacy_loader
620 .load_by_uid_alias(uid, &alias, None)
621 .context("In bulk_delete: Trying to load legacy blob.")?;
622
623 // Determine if the key needs special handling to be deleted.
624 let (need_gc, is_super_encrypted) = km_blob_params
625 .as_ref()
626 .map(|(blob, params)| {
627 (
628 params.iter().any(|kp| {
629 KeyParameterValue::RollbackResistance == *kp.key_parameter_value()
630 }),
631 blob.is_encrypted(),
632 )
633 })
634 .unwrap_or((false, false));
635
636 if keep_non_super_encrypted_keys && !is_super_encrypted {
637 continue;
638 }
639
640 if need_gc {
641 let mark_deleted = match km_blob_params
642 .map(|(blob, _)| (blob.is_strongbox(), blob.take_value()))
643 {
644 Some((is_strongbox, BlobValue::Encrypted { iv, tag, data })) => {
645 let mut blob_metadata = BlobMetaData::new();
646 if let (Ok(km_uuid), Some(super_key_id)) =
647 (self.get_km_uuid(is_strongbox), super_key_id)
648 {
649 blob_metadata.add(BlobMetaEntry::KmUuid(km_uuid));
650 blob_metadata.add(BlobMetaEntry::Iv(iv.to_vec()));
651 blob_metadata.add(BlobMetaEntry::AeadTag(tag.to_vec()));
652 blob_metadata
653 .add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
654 Some((LegacyBlob::Vec(data), blob_metadata))
655 } else {
656 // Oh well - we tried our best, but if we cannot determine which
657 // KeyMint instance we have to send this blob to, we cannot
658 // do more than delete the key from the file system.
659 // And if we don't know which key wraps this key we cannot
660 // unwrap it for KeyMint either.
661 None
662 }
663 }
664 Some((_, BlobValue::Decrypted(data))) => {
665 Some((LegacyBlob::ZVec(data), BlobMetaData::new()))
666 }
667 _ => None,
668 };
669
670 if let Some((blob, blob_metadata)) = mark_deleted {
671 self.db.set_deleted_blob(&blob, &blob_metadata).context(concat!(
672 "In bulk_delete: Trying to insert deleted ",
673 "blob into the database for garbage collection."
674 ))?;
675 }
676 }
677
678 self.legacy_loader
679 .remove_keystore_entry(uid, &alias)
680 .context("In bulk_delete: Trying to remove migrated key.")?;
681 }
682 Ok(())
683 }
684
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000685 fn has_super_key(&mut self, user_id: u32) -> Result<bool> {
686 Ok(self.recently_migrated_super_key.contains(&user_id)
687 || self.legacy_loader.has_super_key(user_id))
688 }
689
690 fn check_empty(&self) -> u8 {
691 if self.legacy_loader.is_empty().unwrap_or(false) {
692 LegacyMigrator::STATE_EMPTY
693 } else {
694 LegacyMigrator::STATE_READY
695 }
696 }
697}
698
699enum LegacyBlob {
700 Vec(Vec<u8>),
701 ZVec(ZVec),
702}
703
704impl Deref for LegacyBlob {
705 type Target = [u8];
706
707 fn deref(&self) -> &Self::Target {
708 match self {
709 Self::Vec(v) => &v,
710 Self::ZVec(v) => &v,
711 }
712 }
713}