Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 1 | // Copyright 2020, 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 holds global state of Keystore such as the thread local |
| 16 | //! database connections and connections to services that Keystore needs |
| 17 | //! to talk to. |
| 18 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 19 | use crate::async_task::AsyncTask; |
| 20 | use crate::gc::Gc; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 21 | use crate::super_key::SuperKeyManager; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 22 | use crate::utils::Asp; |
| 23 | use crate::{ |
| 24 | database::KeystoreDB, |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame^] | 25 | error::{map_binder_status, map_binder_status_code, Error, ErrorCode}, |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 26 | }; |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame^] | 27 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel; |
| 28 | use android_hardware_security_keymint::binder::StatusCode; |
| 29 | use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 30 | use anyhow::{Context, Result}; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 31 | use lazy_static::lazy_static; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 32 | use std::collections::HashMap; |
| 33 | use std::sync::Mutex; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 34 | use std::{cell::RefCell, sync::Once}; |
| 35 | |
| 36 | static DB_INIT: Once = Once::new(); |
| 37 | |
| 38 | /// Open a connection to the Keystore 2.0 database. This is called during the initialization of |
| 39 | /// the thread local DB field. It should never be called directly. The first time this is called |
| 40 | /// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the |
| 41 | /// documentation of cleanup_leftovers for more details. |
| 42 | fn create_thread_local_db() -> KeystoreDB { |
| 43 | let mut db = KeystoreDB::new( |
| 44 | // Keystore changes to the database directory on startup |
| 45 | // (see keystore2_main.rs). |
| 46 | &std::env::current_dir().expect("Could not get the current working directory."), |
| 47 | ) |
| 48 | .expect("Failed to open database."); |
| 49 | DB_INIT.call_once(|| { |
| 50 | log::info!("Touching Keystore 2.0 database for this first time since boot."); |
| 51 | log::info!("Calling cleanup leftovers."); |
| 52 | let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup."); |
| 53 | if n != 0 { |
| 54 | log::info!( |
| 55 | concat!( |
| 56 | "Cleaned up {} failed entries. ", |
| 57 | "This indicates keystore crashed during key generation." |
| 58 | ), |
| 59 | n |
| 60 | ); |
| 61 | } |
| 62 | Gc::notify_gc(); |
| 63 | }); |
| 64 | db |
| 65 | } |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 66 | |
| 67 | thread_local! { |
| 68 | /// Database connections are not thread safe, but connecting to the |
| 69 | /// same database multiple times is safe as long as each connection is |
| 70 | /// used by only one thread. So we store one database connection per |
| 71 | /// thread in this thread local key. |
| 72 | pub static DB: RefCell<KeystoreDB> = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 73 | RefCell::new(create_thread_local_db()); |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 74 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 75 | |
| 76 | lazy_static! { |
| 77 | /// Runtime database of unwrapped super keys. |
| 78 | pub static ref SUPER_KEY: SuperKeyManager = Default::default(); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 79 | /// Map of KeyMint devices. |
| 80 | static ref KEY_MINT_DEVICES: Mutex<HashMap<SecurityLevel, Asp>> = Default::default(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 81 | /// A single on-demand worker thread that handles deferred tasks with two different |
| 82 | /// priorities. |
| 83 | pub static ref ASYNC_TASK: AsyncTask = Default::default(); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 84 | } |
| 85 | |
| 86 | static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice"; |
| 87 | |
| 88 | /// Make a new connection to a KeyMint device of the given security level. |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame^] | 89 | /// If no native KeyMint device can be found this function also brings |
| 90 | /// up the compatibility service and attempts to connect to the legacy wrapper. |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 91 | fn connect_keymint(security_level: SecurityLevel) -> Result<Asp> { |
| 92 | let service_name = match security_level { |
| 93 | SecurityLevel::TRUSTED_ENVIRONMENT => format!("{}/default", KEYMINT_SERVICE_NAME), |
| 94 | SecurityLevel::STRONGBOX => format!("{}/strongbox", KEYMINT_SERVICE_NAME), |
| 95 | _ => { |
| 96 | return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)) |
| 97 | .context("In connect_keymint.") |
| 98 | } |
| 99 | }; |
| 100 | |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame^] | 101 | let keymint = map_binder_status_code(binder::get_interface(&service_name)) |
| 102 | .context("In connect_keymint: Trying to connect to genuine KeyMint service.") |
| 103 | .or_else(|e| { |
| 104 | match e.root_cause().downcast_ref::<Error>() { |
| 105 | Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => { |
| 106 | // This is a no-op if it was called before. |
| 107 | keystore2_km_compat::add_keymint_device_service(); |
| 108 | |
| 109 | let keystore_compat_service: Box<dyn IKeystoreCompatService> = |
| 110 | map_binder_status_code(binder::get_interface("android.security.compat")) |
| 111 | .context("In connect_keymint: Trying to connect to compat service.")?; |
| 112 | map_binder_status(keystore_compat_service.getKeyMintDevice(security_level)) |
| 113 | .map_err(|e| match e { |
| 114 | Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => { |
| 115 | Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE) |
| 116 | } |
| 117 | e => e, |
| 118 | }) |
| 119 | .context("In connext_keymint: Trying to get Legacy wrapper.") |
| 120 | } |
| 121 | _ => Err(e), |
| 122 | } |
| 123 | })?; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 124 | |
| 125 | Ok(Asp::new(keymint.as_binder())) |
| 126 | } |
| 127 | |
| 128 | /// Get a keymint device for the given security level either from our cache or |
| 129 | /// by making a new connection. |
| 130 | pub fn get_keymint_device(security_level: SecurityLevel) -> Result<Asp> { |
| 131 | let mut devices_map = KEY_MINT_DEVICES.lock().unwrap(); |
| 132 | if let Some(dev) = devices_map.get(&security_level) { |
| 133 | Ok(dev.clone()) |
| 134 | } else { |
| 135 | let dev = connect_keymint(security_level).map_err(|e| { |
| 136 | anyhow::anyhow!(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)) |
| 137 | .context(format!("In get_keymint_device: {:?}", e)) |
| 138 | })?; |
| 139 | devices_map.insert(security_level, dev.clone()); |
| 140 | Ok(dev) |
| 141 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 142 | } |