blob: 93e173582512c943327f59e7b2e2f711f7380703 [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
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080017use crate::database::{
18 BlobInfo, BlobMetaData, BlobMetaEntry, CertificateInfo, DateTime, EncryptedBy, KeyMetaData,
19 KeyMetaEntry, KeyType, KeystoreDB, Uuid, KEYSTORE_UUID,
Paul Crowley7a658392021-03-18 17:08:20 -070020};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080021use crate::error::{map_km_error, Error};
22use crate::key_parameter::{KeyParameter, KeyParameterValue};
23use crate::legacy_blob::{self, Blob, BlobValue, LegacyKeyCharacteristics};
24use crate::super_key::USER_SUPER_KEY;
25use crate::utils::{
26 key_characteristics_to_internal, uid_to_android_user, upgrade_keyblob_if_required_with,
27 watchdog as wd, AesGcm,
28};
29use crate::{async_task::AsyncTask, legacy_blob::LegacyBlobLoader};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000030use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
31use android_system_keystore2::aidl::android::system::keystore2::{
32 Domain::Domain, KeyDescriptor::KeyDescriptor, ResponseCode::ResponseCode,
33};
34use anyhow::{Context, Result};
35use core::ops::Deref;
Paul Crowleyf61fee72021-03-17 14:38:44 -070036use keystore2_crypto::{Password, ZVec};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000037use std::collections::{HashMap, HashSet};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000038use std::sync::atomic::{AtomicU8, Ordering};
39use std::sync::mpsc::channel;
40use std::sync::{Arc, Mutex};
41
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080042/// Represents LegacyImporter.
43pub struct LegacyImporter {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000044 async_task: Arc<AsyncTask>,
45 initializer: Mutex<
46 Option<
47 Box<
48 dyn FnOnce() -> (KeystoreDB, HashMap<SecurityLevel, Uuid>, Arc<LegacyBlobLoader>)
49 + Send
50 + 'static,
51 >,
52 >,
53 >,
54 /// This atomic is used for cheap interior mutability. It is intended to prevent
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080055 /// expensive calls into the legacy importer when the legacy database is empty.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000056 /// When transitioning from READY to EMPTY, spurious calls may occur for a brief period
57 /// of time. This is tolerable in favor of the common case.
58 state: AtomicU8,
59}
60
61#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080062struct RecentImport {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000063 uid: u32,
64 alias: String,
65}
66
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080067impl RecentImport {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000068 fn new(uid: u32, alias: String) -> Self {
69 Self { uid, alias }
70 }
71}
72
Janis Danisevskiseed69842021-02-18 20:04:10 -080073enum BulkDeleteRequest {
74 Uid(u32),
75 User(u32),
76}
77
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080078struct LegacyImporterState {
79 recently_imported: HashSet<RecentImport>,
80 recently_imported_super_key: HashSet<u32>,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000081 legacy_loader: Arc<LegacyBlobLoader>,
82 sec_level_to_km_uuid: HashMap<SecurityLevel, Uuid>,
83 db: KeystoreDB,
84}
85
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080086impl LegacyImporter {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000087 const WIFI_NAMESPACE: i64 = 102;
88 const AID_WIFI: u32 = 1010;
89
90 const STATE_UNINITIALIZED: u8 = 0;
91 const STATE_READY: u8 = 1;
92 const STATE_EMPTY: u8 = 2;
93
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080094 /// Constructs a new LegacyImporter using the given AsyncTask object as import
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000095 /// worker.
96 pub fn new(async_task: Arc<AsyncTask>) -> Self {
97 Self {
98 async_task,
99 initializer: Default::default(),
100 state: AtomicU8::new(Self::STATE_UNINITIALIZED),
101 }
102 }
103
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800104 /// The legacy importer must be initialized deferred, because keystore starts very early.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000105 /// At this time the data partition may not be mounted. So we cannot open database connections
106 /// until we get actual key load requests. This sets the function that the legacy loader
107 /// uses to connect to the database.
108 pub fn set_init<F>(&self, f_init: F) -> Result<()>
109 where
110 F: FnOnce() -> (KeystoreDB, HashMap<SecurityLevel, Uuid>, Arc<LegacyBlobLoader>)
111 + Send
112 + 'static,
113 {
114 let mut initializer = self.initializer.lock().expect("Failed to lock initializer.");
115
116 // If we are not uninitialized we have no business setting the initializer.
117 if self.state.load(Ordering::Relaxed) != Self::STATE_UNINITIALIZED {
118 return Ok(());
119 }
120
121 // Only set the initializer if it hasn't been set before.
122 if initializer.is_none() {
123 *initializer = Some(Box::new(f_init))
124 }
125
126 Ok(())
127 }
128
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800129 /// This function is called by the import requestor to check if it is worth
130 /// making an import request. It also transitions the state from UNINITIALIZED
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000131 /// to READY or EMPTY on first use. The deferred initialization is necessary, because
132 /// Keystore 2.0 runs early during boot, where data may not yet be mounted.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800133 /// Returns Ok(STATE_READY) if an import request is worth undertaking and
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000134 /// Ok(STATE_EMPTY) if the database is empty. An error is returned if the loader
135 /// was not initialized and cannot be initialized.
136 fn check_state(&self) -> Result<u8> {
137 let mut first_try = true;
138 loop {
139 match (self.state.load(Ordering::Relaxed), first_try) {
140 (Self::STATE_EMPTY, _) => {
141 return Ok(Self::STATE_EMPTY);
142 }
143 (Self::STATE_UNINITIALIZED, true) => {
144 // If we find the legacy loader uninitialized, we grab the initializer lock,
145 // check if the legacy database is empty, and if not, schedule an initialization
146 // request. Coming out of the initializer lock, the state is either EMPTY or
147 // READY.
148 let mut initializer = self.initializer.lock().unwrap();
149
150 if let Some(initializer) = initializer.take() {
151 let (db, sec_level_to_km_uuid, legacy_loader) = (initializer)();
152
153 if legacy_loader.is_empty().context(
154 "In check_state: Trying to check if the legacy database is empty.",
155 )? {
156 self.state.store(Self::STATE_EMPTY, Ordering::Relaxed);
157 return Ok(Self::STATE_EMPTY);
158 }
159
160 self.async_task.queue_hi(move |shelf| {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800161 shelf.get_or_put_with(|| LegacyImporterState {
162 recently_imported: Default::default(),
163 recently_imported_super_key: Default::default(),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000164 legacy_loader,
165 sec_level_to_km_uuid,
166 db,
167 });
168 });
169
170 // It is safe to set this here even though the async task may not yet have
171 // run because any thread observing this will not be able to schedule a
172 // task that can run before the initialization.
173 // Also we can only transition out of this state while having the
174 // initializer lock and having found an initializer.
175 self.state.store(Self::STATE_READY, Ordering::Relaxed);
176 return Ok(Self::STATE_READY);
177 } else {
178 // There is a chance that we just lost the race from state.load() to
179 // grabbing the initializer mutex. If that is the case the state must
180 // be EMPTY or READY after coming out of the lock. So we can give it
181 // one more try.
182 first_try = false;
183 continue;
184 }
185 }
186 (Self::STATE_UNINITIALIZED, false) => {
187 // Okay, tough luck. The legacy loader was really completely uninitialized.
188 return Err(Error::sys()).context(
189 "In check_state: Legacy loader should not be called uninitialized.",
190 );
191 }
192 (Self::STATE_READY, _) => return Ok(Self::STATE_READY),
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800193 (s, _) => panic!("Unknown legacy importer state. {} ", s),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000194 }
195 }
196 }
197
198 /// List all aliases for uid in the legacy database.
199 pub fn list_uid(&self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800200 let _wp = wd::watch_millis("LegacyImporter::list_uid", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -0700201
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000202 let uid = match (domain, namespace) {
203 (Domain::APP, namespace) => namespace as u32,
204 (Domain::SELINUX, Self::WIFI_NAMESPACE) => Self::AID_WIFI,
205 _ => return Ok(Vec::new()),
206 };
207 self.do_serialized(move |state| state.list_uid(uid)).unwrap_or_else(|| Ok(Vec::new())).map(
208 |v| {
209 v.into_iter()
210 .map(|alias| KeyDescriptor {
211 domain,
212 nspace: namespace,
213 alias: Some(alias),
214 blob: None,
215 })
216 .collect()
217 },
218 )
219 }
220
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800221 /// Sends the given closure to the importer thread for execution after calling check_state.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000222 /// Returns None if the database was empty and the request was not executed.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800223 /// Otherwise returns Some with the result produced by the import request.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000224 /// The loader state may transition to STATE_EMPTY during the execution of this function.
225 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Option<Result<T>>
226 where
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800227 F: FnOnce(&mut LegacyImporterState) -> Result<T> + Send + 'static,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000228 {
229 // Short circuit if the database is empty or not initialized (error case).
230 match self.check_state().context("In do_serialized: Checking state.") {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800231 Ok(LegacyImporter::STATE_EMPTY) => return None,
232 Ok(LegacyImporter::STATE_READY) => {}
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000233 Err(e) => return Some(Err(e)),
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800234 Ok(s) => panic!("Unknown legacy importer state. {} ", s),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000235 }
236
237 // We have established that there may be a key in the legacy database.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800238 // Now we schedule an import request.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000239 let (sender, receiver) = channel();
240 self.async_task.queue_hi(move |shelf| {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800241 // Get the importer state from the shelf.
242 // There may not be a state. This can happen if this import request was scheduled
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000243 // before a previous request established that the legacy database was empty
244 // and removed the state from the shelf. Since we know now that the database
245 // is empty, we can return None here.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800246 let (new_state, result) = if let Some(legacy_importer_state) =
247 shelf.get_downcast_mut::<LegacyImporterState>()
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000248 {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800249 let result = f(legacy_importer_state);
250 (legacy_importer_state.check_empty(), Some(result))
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000251 } else {
252 (Self::STATE_EMPTY, None)
253 };
254
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800255 // If the import request determined that the database is now empty, we discard
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000256 // the state from the shelf to free up the resources we won't need any longer.
257 if result.is_some() && new_state == Self::STATE_EMPTY {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800258 shelf.remove_downcast_ref::<LegacyImporterState>();
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000259 }
260
261 // Send the result to the requester.
262 if let Err(e) = sender.send((new_state, result)) {
263 log::error!("In do_serialized. Error in sending the result. {:?}", e);
264 }
265 });
266
267 let (new_state, result) = match receiver.recv() {
268 Err(e) => {
269 return Some(Err(e).context("In do_serialized. Failed to receive from the sender."))
270 }
271 Ok(r) => r,
272 };
273
274 // We can only transition to EMPTY but never back.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800275 // The importer never creates any legacy blobs.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000276 if new_state == Self::STATE_EMPTY {
277 self.state.store(Self::STATE_EMPTY, Ordering::Relaxed)
278 }
279
280 result
281 }
282
283 /// Runs the key_accessor function and returns its result. If it returns an error and the
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800284 /// root cause was KEY_NOT_FOUND, tries to import a key with the given parameters from
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000285 /// the legacy database to the new database and runs the key_accessor function again if
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800286 /// the import request was successful.
287 pub fn with_try_import<F, T>(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000288 &self,
289 key: &KeyDescriptor,
290 caller_uid: u32,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800291 super_key: Option<Arc<dyn AesGcm + Send + Sync>>,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000292 key_accessor: F,
293 ) -> Result<T>
294 where
295 F: Fn() -> Result<T>,
296 {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800297 let _wp = wd::watch_millis("LegacyImporter::with_try_import", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -0700298
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000299 // Access the key and return on success.
300 match key_accessor() {
301 Ok(result) => return Ok(result),
302 Err(e) => match e.root_cause().downcast_ref::<Error>() {
303 Some(&Error::Rc(ResponseCode::KEY_NOT_FOUND)) => {}
304 _ => return Err(e),
305 },
306 }
307
308 // Filter inputs. We can only load legacy app domain keys and some special rules due
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800309 // to which we import keys transparently to an SELINUX domain.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000310 let uid = match key {
311 KeyDescriptor { domain: Domain::APP, alias: Some(_), .. } => caller_uid,
312 KeyDescriptor { domain: Domain::SELINUX, nspace, alias: Some(_), .. } => {
313 match *nspace {
314 Self::WIFI_NAMESPACE => Self::AID_WIFI,
315 _ => {
316 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
317 .context(format!("No legacy keys for namespace {}", nspace))
318 }
319 }
320 }
321 _ => {
322 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
323 .context("No legacy keys for key descriptor.")
324 }
325 };
326
327 let key_clone = key.clone();
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800328 let result = self.do_serialized(move |importer_state| {
329 let super_key = super_key.map(|sk| -> Arc<dyn AesGcm> { sk });
330 importer_state.check_and_import(uid, key_clone, super_key)
331 });
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000332
333 if let Some(result) = result {
334 result?;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800335 // After successful import try again.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000336 key_accessor()
337 } else {
338 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND)).context("Legacy database is empty.")
339 }
340 }
341
342 /// Calls key_accessor and returns the result on success. In the case of a KEY_NOT_FOUND error
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800343 /// this function makes an import request and on success retries the key_accessor.
344 pub fn with_try_import_super_key<F, T>(
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000345 &self,
346 user_id: u32,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700347 pw: &Password,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000348 mut key_accessor: F,
349 ) -> Result<Option<T>>
350 where
351 F: FnMut() -> Result<Option<T>>,
352 {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800353 let _wp = wd::watch_millis("LegacyImporter::with_try_import_super_key", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -0700354
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000355 match key_accessor() {
356 Ok(Some(result)) => return Ok(Some(result)),
357 Ok(None) => {}
358 Err(e) => return Err(e),
359 }
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800360 let pw = pw.try_clone().context("In with_try_import_super_key: Cloning password.")?;
361 let result = self.do_serialized(move |importer_state| {
362 importer_state.check_and_import_super_key(user_id, &pw)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000363 });
364
365 if let Some(result) = result {
366 result?;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800367 // After successful import try again.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000368 key_accessor()
369 } else {
370 Ok(None)
371 }
372 }
373
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800374 /// Deletes all keys belonging to the given namespace, importing them into the database
Janis Danisevskiseed69842021-02-18 20:04:10 -0800375 /// for subsequent garbage collection if necessary.
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800376 pub fn bulk_delete_uid(&self, domain: Domain, nspace: i64) -> Result<()> {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800377 let _wp = wd::watch_millis("LegacyImporter::bulk_delete_uid", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -0700378
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800379 let uid = match (domain, nspace) {
380 (Domain::APP, nspace) => nspace as u32,
381 (Domain::SELINUX, Self::WIFI_NAMESPACE) => Self::AID_WIFI,
382 // Nothing to do.
383 _ => return Ok(()),
384 };
385
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800386 let result = self.do_serialized(move |importer_state| {
387 importer_state.bulk_delete(BulkDeleteRequest::Uid(uid), false)
Janis Danisevskiseed69842021-02-18 20:04:10 -0800388 });
389
390 result.unwrap_or(Ok(()))
391 }
392
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800393 /// Deletes all keys belonging to the given android user, importing them into the database
Janis Danisevskiseed69842021-02-18 20:04:10 -0800394 /// for subsequent garbage collection if necessary.
395 pub fn bulk_delete_user(
396 &self,
397 user_id: u32,
398 keep_non_super_encrypted_keys: bool,
399 ) -> Result<()> {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800400 let _wp = wd::watch_millis("LegacyImporter::bulk_delete_user", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -0700401
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800402 let result = self.do_serialized(move |importer_state| {
403 importer_state
Janis Danisevskiseed69842021-02-18 20:04:10 -0800404 .bulk_delete(BulkDeleteRequest::User(user_id), keep_non_super_encrypted_keys)
405 });
406
407 result.unwrap_or(Ok(()))
408 }
409
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000410 /// Queries the legacy database for the presence of a super key for the given user.
411 pub fn has_super_key(&self, user_id: u32) -> Result<bool> {
412 let result =
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800413 self.do_serialized(move |importer_state| importer_state.has_super_key(user_id));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000414 result.unwrap_or(Ok(false))
415 }
416}
417
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800418impl LegacyImporterState {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000419 fn get_km_uuid(&self, is_strongbox: bool) -> Result<Uuid> {
420 let sec_level = if is_strongbox {
421 SecurityLevel::STRONGBOX
422 } else {
423 SecurityLevel::TRUSTED_ENVIRONMENT
424 };
425
426 self.sec_level_to_km_uuid.get(&sec_level).copied().ok_or_else(|| {
427 anyhow::anyhow!(Error::sys()).context("In get_km_uuid: No KM instance for blob.")
428 })
429 }
430
431 fn list_uid(&mut self, uid: u32) -> Result<Vec<String>> {
432 self.legacy_loader
433 .list_keystore_entries_for_uid(uid)
434 .context("In list_uid: Trying to list legacy entries.")
435 }
436
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800437 /// Checks if the key can potentially be unlocked. And deletes the key entry otherwise.
438 /// If the super_key has already been imported, the super key database id is returned.
439 fn get_super_key_id_check_unlockable_or_delete(
440 &mut self,
441 uid: u32,
442 alias: &str,
443 ) -> Result<i64> {
444 let user_id = uid_to_android_user(uid);
445
446 match self
447 .db
448 .load_super_key(&USER_SUPER_KEY, user_id)
449 .context("In get_super_key_id_check_unlockable_or_delete: Failed to load super key")?
450 {
451 Some((_, entry)) => Ok(entry.id()),
452 None => {
453 // This might be the first time we access the super key,
454 // and it may not have been imported. We cannot import
455 // the legacy super_key key now, because we need to reencrypt
456 // it which we cannot do if we are not unlocked, which we are
457 // not because otherwise the key would have been imported.
458 // We can check though if the key exists. If it does,
459 // we can return Locked. Otherwise, we can delete the
460 // key and return NotFound, because the key will never
461 // be unlocked again.
462 if self.legacy_loader.has_super_key(user_id) {
463 Err(Error::Rc(ResponseCode::LOCKED)).context(
464 "In get_super_key_id_check_unlockable_or_delete: \
465 Cannot import super key of this key while user is locked.",
466 )
467 } else {
468 self.legacy_loader.remove_keystore_entry(uid, alias).context(
469 "In get_super_key_id_check_unlockable_or_delete: \
470 Trying to remove obsolete key.",
471 )?;
472 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
473 .context("In get_super_key_id_check_unlockable_or_delete: Obsolete key.")
474 }
475 }
476 }
477 }
478
479 fn characteristics_file_to_cache(
480 &mut self,
481 km_blob_params: Option<(Blob, LegacyKeyCharacteristics)>,
482 super_key: &Option<Arc<dyn AesGcm>>,
483 uid: u32,
484 alias: &str,
485 ) -> Result<(Option<(Blob, Vec<KeyParameter>)>, Option<(LegacyBlob<'static>, BlobMetaData)>)>
486 {
487 let (km_blob, params) = match km_blob_params {
488 Some((km_blob, LegacyKeyCharacteristics::File(params))) => (km_blob, params),
489 Some((km_blob, LegacyKeyCharacteristics::Cache(params))) => {
490 return Ok((Some((km_blob, params)), None))
491 }
492 None => return Ok((None, None)),
493 };
494
495 let km_uuid = self
496 .get_km_uuid(km_blob.is_strongbox())
497 .context("In characteristics_file_to_cache: Trying to get KM UUID")?;
498
499 let blob = match (&km_blob.value(), super_key.as_ref()) {
500 (BlobValue::Encrypted { iv, tag, data }, Some(super_key)) => {
501 let blob = super_key
502 .decrypt(data, iv, tag)
503 .context("In characteristics_file_to_cache: Decryption failed.")?;
504 LegacyBlob::ZVec(blob)
505 }
506 (BlobValue::Encrypted { .. }, None) => {
507 return Err(Error::Rc(ResponseCode::LOCKED)).context(
508 "In characteristics_file_to_cache: Oh uh, so close. \
509 This ancient key cannot be imported unless the user is unlocked.",
510 );
511 }
512 (BlobValue::Decrypted(data), _) => LegacyBlob::Ref(data),
513 _ => {
514 return Err(Error::sys())
515 .context("In characteristics_file_to_cache: Unexpected blob type.")
516 }
517 };
518
519 let (km_params, upgraded_blob) = get_key_characteristics_without_app_data(&km_uuid, &*blob)
520 .context(
521 "In characteristics_file_to_cache: Failed to get key characteristics from device.",
522 )?;
523
524 let flags = km_blob.get_flags();
525
526 let (current_blob, superseded_blob) = if let Some(upgraded_blob) = upgraded_blob {
527 match (km_blob.take_value(), super_key.as_ref()) {
528 (BlobValue::Encrypted { iv, tag, data }, Some(super_key)) => {
529 let super_key_id =
530 self.get_super_key_id_check_unlockable_or_delete(uid, alias).context(
531 "In characteristics_file_to_cache: \
532 How is there a super key but no super key id?",
533 )?;
534
535 let mut superseded_metadata = BlobMetaData::new();
536 superseded_metadata.add(BlobMetaEntry::Iv(iv.to_vec()));
537 superseded_metadata.add(BlobMetaEntry::AeadTag(tag.to_vec()));
538 superseded_metadata
539 .add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
540 superseded_metadata.add(BlobMetaEntry::KmUuid(km_uuid));
541 let superseded_blob = (LegacyBlob::Vec(data), superseded_metadata);
542
543 let (data, iv, tag) = super_key.encrypt(&upgraded_blob).context(
544 "In characteristics_file_to_cache: \
545 Failed to encrypt upgraded key blob.",
546 )?;
547 (
548 Blob::new(flags, BlobValue::Encrypted { data, iv, tag }),
549 Some(superseded_blob),
550 )
551 }
552 (BlobValue::Encrypted { .. }, None) => {
553 return Err(Error::sys()).context(
554 "In characteristics_file_to_cache: This should not be reachable. \
555 The blob could not have been decrypted above.",
556 );
557 }
558 (BlobValue::Decrypted(data), _) => {
559 let mut superseded_metadata = BlobMetaData::new();
560 superseded_metadata.add(BlobMetaEntry::KmUuid(km_uuid));
561 let superseded_blob = (LegacyBlob::ZVec(data), superseded_metadata);
562 (
563 Blob::new(
564 flags,
565 BlobValue::Decrypted(upgraded_blob.try_into().context(
566 "In characteristics_file_to_cache: \
567 Failed to convert upgraded blob to ZVec.",
568 )?),
569 ),
570 Some(superseded_blob),
571 )
572 }
573 _ => {
574 return Err(Error::sys()).context(
575 "In characteristics_file_to_cache: This should not be reachable. \
576 Any other variant should have resulted in a different error.",
577 )
578 }
579 }
580 } else {
581 (km_blob, None)
582 };
583
584 let params =
585 augment_legacy_characteristics_file_with_key_characteristics(km_params, params);
586 Ok((Some((current_blob, params)), superseded_blob))
587 }
588
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800589 /// This is a key import request that must run in the importer thread. This must
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000590 /// be passed to do_serialized.
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800591 fn check_and_import(
592 &mut self,
593 uid: u32,
594 mut key: KeyDescriptor,
595 super_key: Option<Arc<dyn AesGcm>>,
596 ) -> Result<()> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000597 let alias = key.alias.clone().ok_or_else(|| {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800598 anyhow::anyhow!(Error::sys()).context(
599 "In check_and_import: Must be Some because \
600 our caller must not have called us otherwise.",
601 )
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000602 })?;
603
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800604 if self.recently_imported.contains(&RecentImport::new(uid, alias.clone())) {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000605 return Ok(());
606 }
607
608 if key.domain == Domain::APP {
609 key.nspace = uid as i64;
610 }
611
612 // If the key is not found in the cache, try to load from the legacy database.
613 let (km_blob_params, user_cert, ca_cert) = self
614 .legacy_loader
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800615 .load_by_uid_alias(uid, &alias, &super_key)
616 .map_err(|e| {
617 if e.root_cause().downcast_ref::<legacy_blob::Error>()
618 == Some(&legacy_blob::Error::LockedComponent)
619 {
620 // There is no chance to succeed at this point. We just check if there is
621 // a super key so that this entry might be unlockable in the future.
622 // If not the entry will be deleted and KEY_NOT_FOUND is returned.
623 // If a super key id was returned we still have to return LOCKED but the key
624 // may be imported when the user unlocks the device.
625 self.get_super_key_id_check_unlockable_or_delete(uid, &alias)
626 .and_then::<i64, _>(|_| {
627 Err(Error::Rc(ResponseCode::LOCKED))
628 .context("Super key present but locked.")
629 })
630 .unwrap_err()
631 } else {
632 e
633 }
634 })
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800635 .context("In check_and_import: Trying to load legacy blob.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800636
637 let (km_blob_params, superseded_blob) = self
638 .characteristics_file_to_cache(km_blob_params, &super_key, uid, &alias)
639 .context("In check_and_import: Trying to update legacy charateristics.")?;
640
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000641 let result = match km_blob_params {
642 Some((km_blob, params)) => {
643 let is_strongbox = km_blob.is_strongbox();
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800644
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000645 let (blob, mut blob_metadata) = match km_blob.take_value() {
646 BlobValue::Encrypted { iv, tag, data } => {
647 // Get super key id for user id.
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800648 let super_key_id = self
649 .get_super_key_id_check_unlockable_or_delete(uid, &alias)
650 .context("In check_and_import: Failed to get super key id.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000651
652 let mut blob_metadata = BlobMetaData::new();
653 blob_metadata.add(BlobMetaEntry::Iv(iv.to_vec()));
654 blob_metadata.add(BlobMetaEntry::AeadTag(tag.to_vec()));
655 blob_metadata
656 .add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
657 (LegacyBlob::Vec(data), blob_metadata)
658 }
659 BlobValue::Decrypted(data) => (LegacyBlob::ZVec(data), BlobMetaData::new()),
660 _ => {
661 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800662 .context("In check_and_import: Legacy key has unexpected type.")
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000663 }
664 };
665
666 let km_uuid = self
667 .get_km_uuid(is_strongbox)
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800668 .context("In check_and_import: Trying to get KM UUID")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000669 blob_metadata.add(BlobMetaEntry::KmUuid(km_uuid));
670
671 let mut metadata = KeyMetaData::new();
672 let creation_date = DateTime::now()
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800673 .context("In check_and_import: Trying to make creation time.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000674 metadata.add(KeyMetaEntry::CreationDate(creation_date));
675
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800676 let blob_info = BlobInfo::new_with_superseded(
677 &blob,
678 &blob_metadata,
679 superseded_blob.as_ref().map(|(b, m)| (&**b, m)),
680 );
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000681 // Store legacy key in the database.
682 self.db
683 .store_new_key(
684 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700685 KeyType::Client,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000686 &params,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800687 &blob_info,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000688 &CertificateInfo::new(user_cert, ca_cert),
689 &metadata,
690 &km_uuid,
691 )
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800692 .context("In check_and_import.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000693 Ok(())
694 }
695 None => {
696 if let Some(ca_cert) = ca_cert {
697 self.db
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700698 .store_new_certificate(&key, KeyType::Client, &ca_cert, &KEYSTORE_UUID)
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800699 .context("In check_and_import: Failed to insert new certificate.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000700 Ok(())
701 } else {
702 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800703 .context("In check_and_import: Legacy key not found.")
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000704 }
705 }
706 };
707
708 match result {
709 Ok(()) => {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800710 // Add the key to the imported_keys list.
711 self.recently_imported.insert(RecentImport::new(uid, alias.clone()));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000712 // Delete legacy key from the file system
713 self.legacy_loader
714 .remove_keystore_entry(uid, &alias)
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800715 .context("In check_and_import: Trying to remove imported key.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000716 Ok(())
717 }
718 Err(e) => Err(e),
719 }
720 }
721
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800722 fn check_and_import_super_key(&mut self, user_id: u32, pw: &Password) -> Result<()> {
723 if self.recently_imported_super_key.contains(&user_id) {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000724 return Ok(());
725 }
726
727 if let Some(super_key) = self
728 .legacy_loader
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700729 .load_super_key(user_id, pw)
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800730 .context("In check_and_import_super_key: Trying to load legacy super key.")?
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000731 {
732 let (blob, blob_metadata) =
Paul Crowleyf61fee72021-03-17 14:38:44 -0700733 crate::super_key::SuperKeyManager::encrypt_with_password(&super_key, pw)
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800734 .context("In check_and_import_super_key: Trying to encrypt super key.")?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000735
Paul Crowley8d5b2532021-03-19 10:53:07 -0700736 self.db
737 .store_super_key(
738 user_id,
739 &USER_SUPER_KEY,
740 &blob,
741 &blob_metadata,
742 &KeyMetaData::new(),
743 )
744 .context(concat!(
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800745 "In check_and_import_super_key: ",
Paul Crowley7a658392021-03-18 17:08:20 -0700746 "Trying to insert legacy super_key into the database."
Paul Crowley8d5b2532021-03-19 10:53:07 -0700747 ))?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000748 self.legacy_loader.remove_super_key(user_id);
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800749 self.recently_imported_super_key.insert(user_id);
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000750 Ok(())
751 } else {
752 Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800753 .context("In check_and_import_super_key: No key found do import.")
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000754 }
755 }
756
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800757 /// Key importer request to be run by do_serialized.
758 /// See LegacyImporter::bulk_delete_uid and LegacyImporter::bulk_delete_user.
Janis Danisevskiseed69842021-02-18 20:04:10 -0800759 fn bulk_delete(
760 &mut self,
761 bulk_delete_request: BulkDeleteRequest,
762 keep_non_super_encrypted_keys: bool,
763 ) -> Result<()> {
764 let (aliases, user_id) = match bulk_delete_request {
765 BulkDeleteRequest::Uid(uid) => (
766 self.legacy_loader
767 .list_keystore_entries_for_uid(uid)
768 .context("In bulk_delete: Trying to get aliases for uid.")
769 .map(|aliases| {
770 let mut h = HashMap::<u32, HashSet<String>>::new();
771 h.insert(uid, aliases.into_iter().collect());
772 h
773 })?,
774 uid_to_android_user(uid),
775 ),
776 BulkDeleteRequest::User(user_id) => (
777 self.legacy_loader
778 .list_keystore_entries_for_user(user_id)
779 .context("In bulk_delete: Trying to get aliases for user_id.")?,
780 user_id,
781 ),
782 };
783
784 let super_key_id = self
785 .db
Paul Crowley7a658392021-03-18 17:08:20 -0700786 .load_super_key(&USER_SUPER_KEY, user_id)
Janis Danisevskiseed69842021-02-18 20:04:10 -0800787 .context("In bulk_delete: Failed to load super key")?
788 .map(|(_, entry)| entry.id());
789
790 for (uid, alias) in aliases
791 .into_iter()
Chariseea1e1c482022-02-26 01:26:35 +0000792 .flat_map(|(uid, aliases)| aliases.into_iter().map(move |alias| (uid, alias)))
Janis Danisevskiseed69842021-02-18 20:04:10 -0800793 {
794 let (km_blob_params, _, _) = self
795 .legacy_loader
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800796 .load_by_uid_alias(uid, &alias, &None)
Janis Danisevskiseed69842021-02-18 20:04:10 -0800797 .context("In bulk_delete: Trying to load legacy blob.")?;
798
799 // Determine if the key needs special handling to be deleted.
800 let (need_gc, is_super_encrypted) = km_blob_params
801 .as_ref()
802 .map(|(blob, params)| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800803 let params = match params {
804 LegacyKeyCharacteristics::Cache(params)
805 | LegacyKeyCharacteristics::File(params) => params,
806 };
Janis Danisevskiseed69842021-02-18 20:04:10 -0800807 (
808 params.iter().any(|kp| {
809 KeyParameterValue::RollbackResistance == *kp.key_parameter_value()
810 }),
811 blob.is_encrypted(),
812 )
813 })
814 .unwrap_or((false, false));
815
816 if keep_non_super_encrypted_keys && !is_super_encrypted {
817 continue;
818 }
819
820 if need_gc {
821 let mark_deleted = match km_blob_params
822 .map(|(blob, _)| (blob.is_strongbox(), blob.take_value()))
823 {
824 Some((is_strongbox, BlobValue::Encrypted { iv, tag, data })) => {
825 let mut blob_metadata = BlobMetaData::new();
826 if let (Ok(km_uuid), Some(super_key_id)) =
827 (self.get_km_uuid(is_strongbox), super_key_id)
828 {
829 blob_metadata.add(BlobMetaEntry::KmUuid(km_uuid));
830 blob_metadata.add(BlobMetaEntry::Iv(iv.to_vec()));
831 blob_metadata.add(BlobMetaEntry::AeadTag(tag.to_vec()));
832 blob_metadata
833 .add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
834 Some((LegacyBlob::Vec(data), blob_metadata))
835 } else {
836 // Oh well - we tried our best, but if we cannot determine which
837 // KeyMint instance we have to send this blob to, we cannot
838 // do more than delete the key from the file system.
839 // And if we don't know which key wraps this key we cannot
840 // unwrap it for KeyMint either.
841 None
842 }
843 }
844 Some((_, BlobValue::Decrypted(data))) => {
845 Some((LegacyBlob::ZVec(data), BlobMetaData::new()))
846 }
847 _ => None,
848 };
849
850 if let Some((blob, blob_metadata)) = mark_deleted {
851 self.db.set_deleted_blob(&blob, &blob_metadata).context(concat!(
852 "In bulk_delete: Trying to insert deleted ",
853 "blob into the database for garbage collection."
854 ))?;
855 }
856 }
857
858 self.legacy_loader
859 .remove_keystore_entry(uid, &alias)
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800860 .context("In bulk_delete: Trying to remove imported key.")?;
Janis Danisevskiseed69842021-02-18 20:04:10 -0800861 }
862 Ok(())
863 }
864
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000865 fn has_super_key(&mut self, user_id: u32) -> Result<bool> {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800866 Ok(self.recently_imported_super_key.contains(&user_id)
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000867 || self.legacy_loader.has_super_key(user_id))
868 }
869
870 fn check_empty(&self) -> u8 {
871 if self.legacy_loader.is_empty().unwrap_or(false) {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800872 LegacyImporter::STATE_EMPTY
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000873 } else {
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800874 LegacyImporter::STATE_READY
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000875 }
876 }
877}
878
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800879enum LegacyBlob<'a> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000880 Vec(Vec<u8>),
881 ZVec(ZVec),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800882 Ref(&'a [u8]),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000883}
884
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800885impl Deref for LegacyBlob<'_> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000886 type Target = [u8];
887
888 fn deref(&self) -> &Self::Target {
889 match self {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700890 Self::Vec(v) => v,
891 Self::ZVec(v) => v,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800892 Self::Ref(v) => v,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000893 }
894 }
895}
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800896
897/// This function takes two KeyParameter lists. The first is assumed to have been retrieved from the
898/// KM back end using km_dev.getKeyCharacteristics. The second is assumed to have been retrieved
899/// from a legacy key characteristics file (not cache) as used in Android P and older. The function
900/// augments the former with entries from the latter only if no equivalent entry is present ignoring.
901/// the security level of enforcement. All entries in the latter are assumed to have security level
902/// KEYSTORE.
903fn augment_legacy_characteristics_file_with_key_characteristics<T>(
904 mut from_km: Vec<KeyParameter>,
905 legacy: T,
906) -> Vec<KeyParameter>
907where
908 T: IntoIterator<Item = KeyParameter>,
909{
910 for legacy_kp in legacy.into_iter() {
911 if !from_km
912 .iter()
913 .any(|km_kp| km_kp.key_parameter_value() == legacy_kp.key_parameter_value())
914 {
915 from_km.push(legacy_kp);
916 }
917 }
918 from_km
919}
920
921/// Attempts to retrieve the key characteristics for the given blob from the KM back end with the
922/// given UUID. It may upgrade the key blob in the process. In that case the upgraded blob is
923/// returned as the second tuple member.
924fn get_key_characteristics_without_app_data(
925 uuid: &Uuid,
926 blob: &[u8],
927) -> Result<(Vec<KeyParameter>, Option<Vec<u8>>)> {
928 let (km_dev, _) = crate::globals::get_keymint_dev_by_uuid(uuid)
929 .with_context(|| format!("In foo: Trying to get km device for id {:?}", uuid))?;
930
931 let (characteristics, upgraded_blob) = upgrade_keyblob_if_required_with(
932 &*km_dev,
933 blob,
934 &[],
935 |blob| {
936 let _wd = wd::watch_millis("In foo: Calling GetKeyCharacteristics.", 500);
937 map_km_error(km_dev.getKeyCharacteristics(blob, &[], &[]))
938 },
939 |_| Ok(()),
940 )
941 .context("In foo.")?;
942 Ok((key_characteristics_to_internal(characteristics), upgraded_blob))
943}