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