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