blob: 9ffe86c8dfbd1c215d7d0440d32c3d5011271362 [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 Danisevskiseed69842021-02-18 20:04:10 -0800365 /// Deletes all keys belonging to the given uid, migrating them into the database
366 /// for subsequent garbage collection if necessary.
367 pub fn bulk_delete_uid(&self, uid: u32, keep_non_super_encrypted_keys: bool) -> Result<()> {
368 let result = self.do_serialized(move |migrator_state| {
369 migrator_state.bulk_delete(BulkDeleteRequest::Uid(uid), keep_non_super_encrypted_keys)
370 });
371
372 result.unwrap_or(Ok(()))
373 }
374
375 /// Deletes all keys belonging to the given android user, migrating them into the database
376 /// for subsequent garbage collection if necessary.
377 pub fn bulk_delete_user(
378 &self,
379 user_id: u32,
380 keep_non_super_encrypted_keys: bool,
381 ) -> Result<()> {
382 let result = self.do_serialized(move |migrator_state| {
383 migrator_state
384 .bulk_delete(BulkDeleteRequest::User(user_id), keep_non_super_encrypted_keys)
385 });
386
387 result.unwrap_or(Ok(()))
388 }
389
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000390 /// Queries the legacy database for the presence of a super key for the given user.
391 pub fn has_super_key(&self, user_id: u32) -> Result<bool> {
392 let result =
393 self.do_serialized(move |migrator_state| migrator_state.has_super_key(user_id));
394 result.unwrap_or(Ok(false))
395 }
396}
397
398impl LegacyMigratorState {
399 fn get_km_uuid(&self, is_strongbox: bool) -> Result<Uuid> {
400 let sec_level = if is_strongbox {
401 SecurityLevel::STRONGBOX
402 } else {
403 SecurityLevel::TRUSTED_ENVIRONMENT
404 };
405
406 self.sec_level_to_km_uuid.get(&sec_level).copied().ok_or_else(|| {
407 anyhow::anyhow!(Error::sys()).context("In get_km_uuid: No KM instance for blob.")
408 })
409 }
410
411 fn list_uid(&mut self, uid: u32) -> Result<Vec<String>> {
412 self.legacy_loader
413 .list_keystore_entries_for_uid(uid)
414 .context("In list_uid: Trying to list legacy entries.")
415 }
416
417 /// This is a key migration request that can run in the migrator thread. This should
418 /// be passed to do_serialized.
419 fn check_and_migrate(&mut self, uid: u32, mut key: KeyDescriptor) -> Result<()> {
420 let alias = key.alias.clone().ok_or_else(|| {
421 anyhow::anyhow!(Error::sys()).context(concat!(
422 "In check_and_migrate: Must be Some because ",
423 "our caller must not have called us otherwise."
424 ))
425 })?;
426
427 if self.recently_migrated.contains(&RecentMigration::new(uid, alias.clone())) {
428 return Ok(());
429 }
430
431 if key.domain == Domain::APP {
432 key.nspace = uid as i64;
433 }
434
435 // If the key is not found in the cache, try to load from the legacy database.
436 let (km_blob_params, user_cert, ca_cert) = self
437 .legacy_loader
438 .load_by_uid_alias(uid, &alias, None)
439 .context("In check_and_migrate: Trying to load legacy blob.")?;
440 let result = match km_blob_params {
441 Some((km_blob, params)) => {
442 let is_strongbox = km_blob.is_strongbox();
443 let (blob, mut blob_metadata) = match km_blob.take_value() {
444 BlobValue::Encrypted { iv, tag, data } => {
445 // Get super key id for user id.
446 let user_id = uid_to_android_user(uid as u32);
447
448 let super_key_id = match self
449 .db
450 .load_super_key(user_id)
451 .context("In check_and_migrate: Failed to load super key")?
452 {
453 Some((_, entry)) => entry.id(),
454 None => {
455 // This might be the first time we access the super key,
456 // and it may not have been migrated. We cannot import
457 // the legacy super_key key now, because we need to reencrypt
458 // it which we cannot do if we are not unlocked, which we are
459 // not because otherwise the key would have been migrated.
460 // We can check though if the key exists. If it does,
461 // we can return Locked. Otherwise, we can delete the
462 // key and return NotFound, because the key will never
463 // be unlocked again.
464 if self.legacy_loader.has_super_key(user_id) {
465 return Err(Error::Rc(ResponseCode::LOCKED)).context(concat!(
466 "In check_and_migrate: Cannot migrate super key of this ",
467 "key while user is locked."
468 ));
469 } else {
470 self.legacy_loader.remove_keystore_entry(uid, &alias).context(
471 concat!(
472 "In check_and_migrate: ",
473 "Trying to remove obsolete key."
474 ),
475 )?;
476 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
477 .context("In check_and_migrate: Obsolete key.");
478 }
479 }
480 };
481
482 let mut blob_metadata = BlobMetaData::new();
483 blob_metadata.add(BlobMetaEntry::Iv(iv.to_vec()));
484 blob_metadata.add(BlobMetaEntry::AeadTag(tag.to_vec()));
485 blob_metadata
486 .add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
487 (LegacyBlob::Vec(data), blob_metadata)
488 }
489 BlobValue::Decrypted(data) => (LegacyBlob::ZVec(data), BlobMetaData::new()),
490 _ => {
491 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
492 .context("In check_and_migrate: Legacy key has unexpected type.")
493 }
494 };
495
496 let km_uuid = self
497 .get_km_uuid(is_strongbox)
498 .context("In check_and_migrate: Trying to get KM UUID")?;
499 blob_metadata.add(BlobMetaEntry::KmUuid(km_uuid));
500
501 let mut metadata = KeyMetaData::new();
502 let creation_date = DateTime::now()
503 .context("In check_and_migrate: Trying to make creation time.")?;
504 metadata.add(KeyMetaEntry::CreationDate(creation_date));
505
506 // Store legacy key in the database.
507 self.db
508 .store_new_key(
509 &key,
510 &params,
511 &(&blob, &blob_metadata),
512 &CertificateInfo::new(user_cert, ca_cert),
513 &metadata,
514 &km_uuid,
515 )
516 .context("In check_and_migrate.")?;
517 Ok(())
518 }
519 None => {
520 if let Some(ca_cert) = ca_cert {
521 self.db
522 .store_new_certificate(&key, &ca_cert, &KEYSTORE_UUID)
523 .context("In check_and_migrate: Failed to insert new certificate.")?;
524 Ok(())
525 } else {
526 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
527 .context("In check_and_migrate: Legacy key not found.")
528 }
529 }
530 };
531
532 match result {
533 Ok(()) => {
534 // Add the key to the migrated_keys list.
535 self.recently_migrated.insert(RecentMigration::new(uid, alias.clone()));
536 // Delete legacy key from the file system
537 self.legacy_loader
538 .remove_keystore_entry(uid, &alias)
539 .context("In check_and_migrate: Trying to remove migrated key.")?;
540 Ok(())
541 }
542 Err(e) => Err(e),
543 }
544 }
545
546 fn check_and_migrate_super_key(&mut self, user_id: u32, pw: ZVec) -> Result<()> {
547 if self.recently_migrated_super_key.contains(&user_id) {
548 return Ok(());
549 }
550
551 if let Some(super_key) = self
552 .legacy_loader
553 .load_super_key(user_id, &pw)
554 .context("In check_and_migrate_super_key: Trying to load legacy super key.")?
555 {
556 let (blob, blob_metadata) =
557 crate::super_key::SuperKeyManager::encrypt_with_password(&super_key, &pw)
558 .context("In check_and_migrate_super_key: Trying to encrypt super key.")?;
559
560 self.db.store_super_key(user_id, &(&blob, &blob_metadata)).context(concat!(
561 "In check_and_migrate_super_key: ",
562 "Trying to insert legacy super_key into the database."
563 ))?;
564 self.legacy_loader.remove_super_key(user_id);
565 self.recently_migrated_super_key.insert(user_id);
566 Ok(())
567 } else {
568 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
569 .context("In check_and_migrate_super_key: No key found do migrate.")
570 }
571 }
572
Janis Danisevskiseed69842021-02-18 20:04:10 -0800573 /// Key migrator request to be run by do_serialized.
574 /// See LegacyMigrator::bulk_delete_uid and LegacyMigrator::bulk_delete_user.
575 fn bulk_delete(
576 &mut self,
577 bulk_delete_request: BulkDeleteRequest,
578 keep_non_super_encrypted_keys: bool,
579 ) -> Result<()> {
580 let (aliases, user_id) = match bulk_delete_request {
581 BulkDeleteRequest::Uid(uid) => (
582 self.legacy_loader
583 .list_keystore_entries_for_uid(uid)
584 .context("In bulk_delete: Trying to get aliases for uid.")
585 .map(|aliases| {
586 let mut h = HashMap::<u32, HashSet<String>>::new();
587 h.insert(uid, aliases.into_iter().collect());
588 h
589 })?,
590 uid_to_android_user(uid),
591 ),
592 BulkDeleteRequest::User(user_id) => (
593 self.legacy_loader
594 .list_keystore_entries_for_user(user_id)
595 .context("In bulk_delete: Trying to get aliases for user_id.")?,
596 user_id,
597 ),
598 };
599
600 let super_key_id = self
601 .db
602 .load_super_key(user_id)
603 .context("In bulk_delete: Failed to load super key")?
604 .map(|(_, entry)| entry.id());
605
606 for (uid, alias) in aliases
607 .into_iter()
608 .map(|(uid, aliases)| aliases.into_iter().map(move |alias| (uid, alias)))
609 .flatten()
610 {
611 let (km_blob_params, _, _) = self
612 .legacy_loader
613 .load_by_uid_alias(uid, &alias, None)
614 .context("In bulk_delete: Trying to load legacy blob.")?;
615
616 // Determine if the key needs special handling to be deleted.
617 let (need_gc, is_super_encrypted) = km_blob_params
618 .as_ref()
619 .map(|(blob, params)| {
620 (
621 params.iter().any(|kp| {
622 KeyParameterValue::RollbackResistance == *kp.key_parameter_value()
623 }),
624 blob.is_encrypted(),
625 )
626 })
627 .unwrap_or((false, false));
628
629 if keep_non_super_encrypted_keys && !is_super_encrypted {
630 continue;
631 }
632
633 if need_gc {
634 let mark_deleted = match km_blob_params
635 .map(|(blob, _)| (blob.is_strongbox(), blob.take_value()))
636 {
637 Some((is_strongbox, BlobValue::Encrypted { iv, tag, data })) => {
638 let mut blob_metadata = BlobMetaData::new();
639 if let (Ok(km_uuid), Some(super_key_id)) =
640 (self.get_km_uuid(is_strongbox), super_key_id)
641 {
642 blob_metadata.add(BlobMetaEntry::KmUuid(km_uuid));
643 blob_metadata.add(BlobMetaEntry::Iv(iv.to_vec()));
644 blob_metadata.add(BlobMetaEntry::AeadTag(tag.to_vec()));
645 blob_metadata
646 .add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
647 Some((LegacyBlob::Vec(data), blob_metadata))
648 } else {
649 // Oh well - we tried our best, but if we cannot determine which
650 // KeyMint instance we have to send this blob to, we cannot
651 // do more than delete the key from the file system.
652 // And if we don't know which key wraps this key we cannot
653 // unwrap it for KeyMint either.
654 None
655 }
656 }
657 Some((_, BlobValue::Decrypted(data))) => {
658 Some((LegacyBlob::ZVec(data), BlobMetaData::new()))
659 }
660 _ => None,
661 };
662
663 if let Some((blob, blob_metadata)) = mark_deleted {
664 self.db.set_deleted_blob(&blob, &blob_metadata).context(concat!(
665 "In bulk_delete: Trying to insert deleted ",
666 "blob into the database for garbage collection."
667 ))?;
668 }
669 }
670
671 self.legacy_loader
672 .remove_keystore_entry(uid, &alias)
673 .context("In bulk_delete: Trying to remove migrated key.")?;
674 }
675 Ok(())
676 }
677
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000678 fn has_super_key(&mut self, user_id: u32) -> Result<bool> {
679 Ok(self.recently_migrated_super_key.contains(&user_id)
680 || self.legacy_loader.has_super_key(user_id))
681 }
682
683 fn check_empty(&self) -> u8 {
684 if self.legacy_loader.is_empty().unwrap_or(false) {
685 LegacyMigrator::STATE_EMPTY
686 } else {
687 LegacyMigrator::STATE_READY
688 }
689 }
690}
691
692enum LegacyBlob {
693 Vec(Vec<u8>),
694 ZVec(ZVec),
695}
696
697impl Deref for LegacyBlob {
698 type Target = [u8];
699
700 fn deref(&self) -> &Self::Target {
701 match self {
702 Self::Vec(v) => &v,
703 Self::ZVec(v) => &v,
704 }
705 }
706}