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