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::gc::Gc; |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 20 | use crate::legacy_blob::LegacyBlobLoader; |
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; |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 23 | use crate::{async_task::AsyncTask, database::MonotonicRawTime}; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 24 | use crate::{ |
| 25 | database::KeystoreDB, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 26 | database::Uuid, |
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 | }; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 29 | use crate::{enforcements::Enforcements, error::map_km_error}; |
| 30 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
| 31 | KeyMintHardwareInfo::KeyMintHardwareInfo, SecurityLevel::SecurityLevel, |
| 32 | }; |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 33 | use android_hardware_security_keymint::binder::StatusCode; |
| 34 | use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 35 | use anyhow::{Context, Result}; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 36 | use lazy_static::lazy_static; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 37 | use std::sync::Mutex; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 38 | use std::{cell::RefCell, sync::Once}; |
Janis Danisevskis | 3f2955c | 2021-02-02 21:53:35 -0800 | [diff] [blame] | 39 | use std::{collections::HashMap, path::Path, path::PathBuf}; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 40 | |
| 41 | static DB_INIT: Once = Once::new(); |
| 42 | |
| 43 | /// Open a connection to the Keystore 2.0 database. This is called during the initialization of |
| 44 | /// the thread local DB field. It should never be called directly. The first time this is called |
| 45 | /// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the |
| 46 | /// documentation of cleanup_leftovers for more details. |
| 47 | fn create_thread_local_db() -> KeystoreDB { |
Janis Danisevskis | 3f2955c | 2021-02-02 21:53:35 -0800 | [diff] [blame] | 48 | let mut db = KeystoreDB::new(&DB_PATH.lock().expect("Could not get the database directory.")) |
| 49 | .expect("Failed to open database."); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 50 | DB_INIT.call_once(|| { |
| 51 | log::info!("Touching Keystore 2.0 database for this first time since boot."); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 52 | db.insert_last_off_body(MonotonicRawTime::now()) |
| 53 | .expect("Could not initialize database with last off body."); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 54 | log::info!("Calling cleanup leftovers."); |
| 55 | let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup."); |
| 56 | if n != 0 { |
| 57 | log::info!( |
| 58 | concat!( |
| 59 | "Cleaned up {} failed entries. ", |
| 60 | "This indicates keystore crashed during key generation." |
| 61 | ), |
| 62 | n |
| 63 | ); |
| 64 | } |
| 65 | Gc::notify_gc(); |
| 66 | }); |
| 67 | db |
| 68 | } |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 69 | |
| 70 | thread_local! { |
| 71 | /// Database connections are not thread safe, but connecting to the |
| 72 | /// same database multiple times is safe as long as each connection is |
| 73 | /// used by only one thread. So we store one database connection per |
| 74 | /// thread in this thread local key. |
| 75 | pub static DB: RefCell<KeystoreDB> = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 76 | RefCell::new(create_thread_local_db()); |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 77 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 78 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 79 | #[derive(Default)] |
| 80 | struct DevicesMap { |
| 81 | devices_by_uuid: HashMap<Uuid, (Asp, KeyMintHardwareInfo)>, |
| 82 | uuid_by_sec_level: HashMap<SecurityLevel, Uuid>, |
| 83 | } |
| 84 | |
| 85 | impl DevicesMap { |
| 86 | fn dev_by_sec_level( |
| 87 | &self, |
| 88 | sec_level: &SecurityLevel, |
| 89 | ) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> { |
| 90 | self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid)) |
| 91 | } |
| 92 | |
| 93 | fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> { |
| 94 | self.devices_by_uuid |
| 95 | .get(uuid) |
| 96 | .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid)) |
| 97 | } |
| 98 | |
| 99 | /// The requested security level and the security level of the actual implementation may |
| 100 | /// differ. So we map the requested security level to the uuid of the implementation |
| 101 | /// so that there cannot be any confusion as to which KeyMint instance is requested. |
| 102 | fn insert(&mut self, sec_level: SecurityLevel, dev: Asp, hw_info: KeyMintHardwareInfo) { |
| 103 | // For now we use the reported security level of the KM instance as UUID. |
| 104 | // TODO update this section once UUID was added to the KM hardware info. |
| 105 | let uuid: Uuid = sec_level.into(); |
| 106 | self.devices_by_uuid.insert(uuid, (dev, hw_info)); |
| 107 | self.uuid_by_sec_level.insert(sec_level, uuid); |
| 108 | } |
| 109 | } |
| 110 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 111 | lazy_static! { |
Janis Danisevskis | 3f2955c | 2021-02-02 21:53:35 -0800 | [diff] [blame] | 112 | /// The path where keystore stores all its keys. |
| 113 | pub static ref DB_PATH: Mutex<PathBuf> = Mutex::new( |
| 114 | Path::new("/data/misc/keystore").to_path_buf()); |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 115 | /// Runtime database of unwrapped super keys. |
| 116 | pub static ref SUPER_KEY: SuperKeyManager = Default::default(); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 117 | /// Map of KeyMint devices. |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 118 | static ref KEY_MINT_DEVICES: Mutex<DevicesMap> = Default::default(); |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 119 | /// Timestamp service. |
| 120 | static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 121 | /// A single on-demand worker thread that handles deferred tasks with two different |
| 122 | /// priorities. |
| 123 | pub static ref ASYNC_TASK: AsyncTask = Default::default(); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 124 | /// Singleton for enforcements. |
Hasini Gunasinghe | 888dd35 | 2020-11-17 23:08:39 +0000 | [diff] [blame] | 125 | pub static ref ENFORCEMENTS: Enforcements = Enforcements::new(); |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 126 | /// LegacyBlobLoader is initialized and exists globally. |
| 127 | /// The same directory used by the database is used by the LegacyBlobLoader as well. |
| 128 | pub static ref LEGACY_BLOB_LOADER: LegacyBlobLoader = LegacyBlobLoader::new( |
Janis Danisevskis | 3f2955c | 2021-02-02 21:53:35 -0800 | [diff] [blame] | 129 | &DB_PATH.lock().expect("Could not get the database path for legacy blob loader.")); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 130 | } |
| 131 | |
| 132 | static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice"; |
| 133 | |
| 134 | /// 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] | 135 | /// If no native KeyMint device can be found this function also brings |
| 136 | /// up the compatibility service and attempts to connect to the legacy wrapper. |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 137 | fn connect_keymint(security_level: &SecurityLevel) -> Result<(Asp, KeyMintHardwareInfo)> { |
| 138 | let service_name = match *security_level { |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 139 | SecurityLevel::TRUSTED_ENVIRONMENT => format!("{}/default", KEYMINT_SERVICE_NAME), |
| 140 | SecurityLevel::STRONGBOX => format!("{}/strongbox", KEYMINT_SERVICE_NAME), |
| 141 | _ => { |
| 142 | return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)) |
| 143 | .context("In connect_keymint.") |
| 144 | } |
| 145 | }; |
| 146 | |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 147 | let keymint = map_binder_status_code(binder::get_interface(&service_name)) |
| 148 | .context("In connect_keymint: Trying to connect to genuine KeyMint service.") |
| 149 | .or_else(|e| { |
| 150 | match e.root_cause().downcast_ref::<Error>() { |
| 151 | Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => { |
| 152 | // This is a no-op if it was called before. |
| 153 | keystore2_km_compat::add_keymint_device_service(); |
| 154 | |
| 155 | let keystore_compat_service: Box<dyn IKeystoreCompatService> = |
| 156 | map_binder_status_code(binder::get_interface("android.security.compat")) |
| 157 | .context("In connect_keymint: Trying to connect to compat service.")?; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 158 | map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level)) |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 159 | .map_err(|e| match e { |
| 160 | Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => { |
| 161 | Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE) |
| 162 | } |
| 163 | e => e, |
| 164 | }) |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 165 | .context("In connect_keymint: Trying to get Legacy wrapper.") |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 166 | } |
| 167 | _ => Err(e), |
| 168 | } |
| 169 | })?; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 170 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 171 | let hw_info = map_km_error(keymint.getHardwareInfo()) |
| 172 | .context("In connect_keymint: Failed to get hardware info.")?; |
| 173 | |
| 174 | Ok((Asp::new(keymint.as_binder()), hw_info)) |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 175 | } |
| 176 | |
| 177 | /// Get a keymint device for the given security level either from our cache or |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 178 | /// by making a new connection. Returns the device, the hardware info and the uuid. |
| 179 | /// TODO the latter can be removed when the uuid is part of the hardware info. |
| 180 | pub fn get_keymint_device( |
| 181 | security_level: &SecurityLevel, |
| 182 | ) -> Result<(Asp, KeyMintHardwareInfo, Uuid)> { |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 183 | let mut devices_map = KEY_MINT_DEVICES.lock().unwrap(); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 184 | if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(&security_level) { |
| 185 | Ok((dev, hw_info, uuid)) |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 186 | } else { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 187 | let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?; |
| 188 | devices_map.insert(*security_level, dev, hw_info); |
| 189 | // Unwrap must succeed because we just inserted it. |
| 190 | Ok(devices_map.dev_by_sec_level(security_level).unwrap()) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | /// Get a keymint device for the given uuid. This will only access the cache, but will not |
| 195 | /// attempt to establish a new connection. It is assumed that the cache is already populated |
| 196 | /// when this is called. This is a fair assumption, because service.rs iterates through all |
| 197 | /// security levels when it gets instantiated. |
| 198 | pub fn get_keymint_dev_by_uuid(uuid: &Uuid) -> Result<(Asp, KeyMintHardwareInfo)> { |
| 199 | let devices_map = KEY_MINT_DEVICES.lock().unwrap(); |
| 200 | if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) { |
| 201 | Ok((dev, hw_info)) |
| 202 | } else { |
| 203 | Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.") |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 204 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 205 | } |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 206 | |
| 207 | static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock"; |
| 208 | |
| 209 | /// Make a new connection to a secure clock service. |
| 210 | /// If no native SecureClock device can be found brings up the compatibility service and attempts |
| 211 | /// to connect to the legacy wrapper. |
| 212 | fn connect_secureclock() -> Result<Asp> { |
| 213 | let secureclock = map_binder_status_code(binder::get_interface(TIME_STAMP_SERVICE_NAME)) |
| 214 | .context("In connect_secureclock: Trying to connect to genuine secure clock service.") |
| 215 | .or_else(|e| { |
| 216 | match e.root_cause().downcast_ref::<Error>() { |
| 217 | Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => { |
| 218 | // This is a no-op if it was called before. |
| 219 | keystore2_km_compat::add_keymint_device_service(); |
| 220 | |
| 221 | let keystore_compat_service: Box<dyn IKeystoreCompatService> = |
| 222 | map_binder_status_code(binder::get_interface("android.security.compat")) |
| 223 | .context( |
| 224 | "In connect_secureclock: Trying to connect to compat service.", |
| 225 | )?; |
| 226 | |
| 227 | // Legacy secure clock services were only implemented by TEE. |
| 228 | map_binder_status(keystore_compat_service.getSecureClock()) |
| 229 | .map_err(|e| match e { |
| 230 | Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => { |
| 231 | Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE) |
| 232 | } |
| 233 | e => e, |
| 234 | }) |
| 235 | .context("In connect_secureclock: Trying to get Legacy wrapper.") |
| 236 | } |
| 237 | _ => Err(e), |
| 238 | } |
| 239 | })?; |
| 240 | |
| 241 | Ok(Asp::new(secureclock.as_binder())) |
| 242 | } |
| 243 | |
| 244 | /// Get the timestamp service that verifies auth token timeliness towards security levels with |
| 245 | /// different clocks. |
| 246 | pub fn get_timestamp_service() -> Result<Asp> { |
| 247 | let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap(); |
| 248 | if let Some(dev) = &*ts_device { |
| 249 | Ok(dev.clone()) |
| 250 | } else { |
| 251 | let dev = connect_secureclock().context("In get_timestamp_service.")?; |
| 252 | *ts_device = Some(dev.clone()); |
| 253 | Ok(dev) |
| 254 | } |
| 255 | } |