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; |
Hasini Gunasinghe | f04d07a | 2020-11-25 22:41:35 +0000 | [diff] [blame] | 20 | use crate::background_task_handler::BackgroundTaskHandler; |
Hasini Gunasinghe | 888dd35 | 2020-11-17 23:08:39 +0000 | [diff] [blame] | 21 | use crate::enforcements::Enforcements; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 22 | use crate::gc::Gc; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 23 | use crate::super_key::SuperKeyManager; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 24 | use crate::utils::Asp; |
| 25 | use crate::{ |
| 26 | database::KeystoreDB, |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 27 | error::{map_binder_status, map_binder_status_code, Error, ErrorCode}, |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 28 | }; |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 29 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel; |
| 30 | use android_hardware_security_keymint::binder::StatusCode; |
| 31 | use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 32 | use anyhow::{Context, Result}; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 33 | use lazy_static::lazy_static; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 34 | use std::collections::HashMap; |
| 35 | use std::sync::Mutex; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 36 | use std::{cell::RefCell, sync::Once}; |
| 37 | |
| 38 | static DB_INIT: Once = Once::new(); |
| 39 | |
| 40 | /// Open a connection to the Keystore 2.0 database. This is called during the initialization of |
| 41 | /// the thread local DB field. It should never be called directly. The first time this is called |
| 42 | /// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the |
| 43 | /// documentation of cleanup_leftovers for more details. |
| 44 | fn create_thread_local_db() -> KeystoreDB { |
| 45 | let mut db = KeystoreDB::new( |
| 46 | // Keystore changes to the database directory on startup |
| 47 | // (see keystore2_main.rs). |
| 48 | &std::env::current_dir().expect("Could not get the current working directory."), |
| 49 | ) |
| 50 | .expect("Failed to open database."); |
| 51 | DB_INIT.call_once(|| { |
| 52 | log::info!("Touching Keystore 2.0 database for this first time since boot."); |
| 53 | log::info!("Calling cleanup leftovers."); |
| 54 | let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup."); |
| 55 | if n != 0 { |
| 56 | log::info!( |
| 57 | concat!( |
| 58 | "Cleaned up {} failed entries. ", |
| 59 | "This indicates keystore crashed during key generation." |
| 60 | ), |
| 61 | n |
| 62 | ); |
| 63 | } |
| 64 | Gc::notify_gc(); |
| 65 | }); |
| 66 | db |
| 67 | } |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 68 | |
| 69 | thread_local! { |
| 70 | /// Database connections are not thread safe, but connecting to the |
| 71 | /// same database multiple times is safe as long as each connection is |
| 72 | /// used by only one thread. So we store one database connection per |
| 73 | /// thread in this thread local key. |
| 74 | pub static DB: RefCell<KeystoreDB> = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 75 | RefCell::new(create_thread_local_db()); |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 76 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 77 | |
| 78 | lazy_static! { |
| 79 | /// Runtime database of unwrapped super keys. |
| 80 | pub static ref SUPER_KEY: SuperKeyManager = Default::default(); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 81 | /// Map of KeyMint devices. |
| 82 | static ref KEY_MINT_DEVICES: Mutex<HashMap<SecurityLevel, Asp>> = Default::default(); |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame^] | 83 | /// Timestamp service. |
| 84 | static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 85 | /// A single on-demand worker thread that handles deferred tasks with two different |
| 86 | /// priorities. |
| 87 | pub static ref ASYNC_TASK: AsyncTask = Default::default(); |
Hasini Gunasinghe | 888dd35 | 2020-11-17 23:08:39 +0000 | [diff] [blame] | 88 | /// Singeleton for enforcements. |
Hasini Gunasinghe | 888dd35 | 2020-11-17 23:08:39 +0000 | [diff] [blame] | 89 | pub static ref ENFORCEMENTS: Enforcements = Enforcements::new(); |
Hasini Gunasinghe | f04d07a | 2020-11-25 22:41:35 +0000 | [diff] [blame] | 90 | /// Background task handler is initialized and exists globally. |
| 91 | /// The other modules (e.g. enforcements) communicate with it via a channel initialized during |
| 92 | /// keystore startup. |
| 93 | pub static ref BACKGROUND_TASK_HANDLER: BackgroundTaskHandler = BackgroundTaskHandler::new(); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 94 | } |
| 95 | |
| 96 | static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice"; |
| 97 | |
| 98 | /// 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] | 99 | /// If no native KeyMint device can be found this function also brings |
| 100 | /// up the compatibility service and attempts to connect to the legacy wrapper. |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 101 | fn connect_keymint(security_level: SecurityLevel) -> Result<Asp> { |
| 102 | let service_name = match security_level { |
| 103 | SecurityLevel::TRUSTED_ENVIRONMENT => format!("{}/default", KEYMINT_SERVICE_NAME), |
| 104 | SecurityLevel::STRONGBOX => format!("{}/strongbox", KEYMINT_SERVICE_NAME), |
| 105 | _ => { |
| 106 | return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)) |
| 107 | .context("In connect_keymint.") |
| 108 | } |
| 109 | }; |
| 110 | |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 111 | let keymint = map_binder_status_code(binder::get_interface(&service_name)) |
| 112 | .context("In connect_keymint: Trying to connect to genuine KeyMint service.") |
| 113 | .or_else(|e| { |
| 114 | match e.root_cause().downcast_ref::<Error>() { |
| 115 | Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => { |
| 116 | // This is a no-op if it was called before. |
| 117 | keystore2_km_compat::add_keymint_device_service(); |
| 118 | |
| 119 | let keystore_compat_service: Box<dyn IKeystoreCompatService> = |
| 120 | map_binder_status_code(binder::get_interface("android.security.compat")) |
| 121 | .context("In connect_keymint: Trying to connect to compat service.")?; |
| 122 | map_binder_status(keystore_compat_service.getKeyMintDevice(security_level)) |
| 123 | .map_err(|e| match e { |
| 124 | Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => { |
| 125 | Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE) |
| 126 | } |
| 127 | e => e, |
| 128 | }) |
| 129 | .context("In connext_keymint: Trying to get Legacy wrapper.") |
| 130 | } |
| 131 | _ => Err(e), |
| 132 | } |
| 133 | })?; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 134 | |
| 135 | Ok(Asp::new(keymint.as_binder())) |
| 136 | } |
| 137 | |
| 138 | /// Get a keymint device for the given security level either from our cache or |
| 139 | /// by making a new connection. |
| 140 | pub fn get_keymint_device(security_level: SecurityLevel) -> Result<Asp> { |
| 141 | let mut devices_map = KEY_MINT_DEVICES.lock().unwrap(); |
| 142 | if let Some(dev) = devices_map.get(&security_level) { |
| 143 | Ok(dev.clone()) |
| 144 | } else { |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame^] | 145 | let dev = connect_keymint(security_level).context("In get_keymint_device.")?; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 146 | devices_map.insert(security_level, dev.clone()); |
| 147 | Ok(dev) |
| 148 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 149 | } |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame^] | 150 | |
| 151 | static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock"; |
| 152 | |
| 153 | /// Make a new connection to a secure clock service. |
| 154 | /// If no native SecureClock device can be found brings up the compatibility service and attempts |
| 155 | /// to connect to the legacy wrapper. |
| 156 | fn connect_secureclock() -> Result<Asp> { |
| 157 | let secureclock = map_binder_status_code(binder::get_interface(TIME_STAMP_SERVICE_NAME)) |
| 158 | .context("In connect_secureclock: Trying to connect to genuine secure clock service.") |
| 159 | .or_else(|e| { |
| 160 | match e.root_cause().downcast_ref::<Error>() { |
| 161 | Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => { |
| 162 | // This is a no-op if it was called before. |
| 163 | keystore2_km_compat::add_keymint_device_service(); |
| 164 | |
| 165 | let keystore_compat_service: Box<dyn IKeystoreCompatService> = |
| 166 | map_binder_status_code(binder::get_interface("android.security.compat")) |
| 167 | .context( |
| 168 | "In connect_secureclock: Trying to connect to compat service.", |
| 169 | )?; |
| 170 | |
| 171 | // Legacy secure clock services were only implemented by TEE. |
| 172 | map_binder_status(keystore_compat_service.getSecureClock()) |
| 173 | .map_err(|e| match e { |
| 174 | Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => { |
| 175 | Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE) |
| 176 | } |
| 177 | e => e, |
| 178 | }) |
| 179 | .context("In connect_secureclock: Trying to get Legacy wrapper.") |
| 180 | } |
| 181 | _ => Err(e), |
| 182 | } |
| 183 | })?; |
| 184 | |
| 185 | Ok(Asp::new(secureclock.as_binder())) |
| 186 | } |
| 187 | |
| 188 | /// Get the timestamp service that verifies auth token timeliness towards security levels with |
| 189 | /// different clocks. |
| 190 | pub fn get_timestamp_service() -> Result<Asp> { |
| 191 | let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap(); |
| 192 | if let Some(dev) = &*ts_device { |
| 193 | Ok(dev.clone()) |
| 194 | } else { |
| 195 | let dev = connect_secureclock().context("In get_timestamp_service.")?; |
| 196 | *ts_device = Some(dev.clone()); |
| 197 | Ok(dev) |
| 198 | } |
| 199 | } |