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 | |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 19 | use crate::ks_err; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 20 | use crate::gc::Gc; |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 21 | use crate::legacy_blob::LegacyBlobLoader; |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 22 | use crate::legacy_importer::LegacyImporter; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 23 | use crate::super_key::SuperKeyManager; |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 24 | use crate::utils::watchdog as wd; |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 25 | use crate::{async_task::AsyncTask, database::MonotonicRawTime}; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 26 | use crate::{ |
| 27 | database::KeystoreDB, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 28 | database::Uuid, |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 29 | error::{map_binder_status, map_binder_status_code, Error, ErrorCode}, |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 30 | }; |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 31 | use crate::km_compat::{KeyMintV1, BacklevelKeyMintWrapper}; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 32 | use crate::{enforcements::Enforcements, error::map_km_error}; |
| 33 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 34 | IKeyMintDevice::IKeyMintDevice, IRemotelyProvisionedComponent::IRemotelyProvisionedComponent, |
| 35 | KeyMintHardwareInfo::KeyMintHardwareInfo, SecurityLevel::SecurityLevel, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 36 | }; |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 37 | use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{ |
| 38 | ISecureClock::ISecureClock, |
| 39 | }; |
Stephen Crane | 221bbb5 | 2020-12-16 15:52:10 -0800 | [diff] [blame] | 40 | use android_hardware_security_keymint::binder::{StatusCode, Strong}; |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 41 | use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 42 | use anyhow::{Context, Result}; |
David Drysdale | 0e45a61 | 2021-02-25 17:24:36 +0000 | [diff] [blame] | 43 | use binder::FromIBinder; |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 44 | use keystore2_vintf::get_aidl_instances; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 45 | use lazy_static::lazy_static; |
Seth Moore | a3e611a | 2021-05-11 10:07:45 -0700 | [diff] [blame] | 46 | use std::sync::{Arc, Mutex, RwLock}; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 47 | use std::{cell::RefCell, sync::Once}; |
Janis Danisevskis | 3f2955c | 2021-02-02 21:53:35 -0800 | [diff] [blame] | 48 | use std::{collections::HashMap, path::Path, path::PathBuf}; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 49 | |
| 50 | static DB_INIT: Once = Once::new(); |
| 51 | |
| 52 | /// Open a connection to the Keystore 2.0 database. This is called during the initialization of |
| 53 | /// the thread local DB field. It should never be called directly. The first time this is called |
| 54 | /// 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] | 55 | /// documentation of cleanup_leftovers for more details. The function also constructs a blob |
| 56 | /// garbage collector. The initializing closure constructs another database connection without |
| 57 | /// a gc. Although one GC is created for each thread local database connection, this closure |
| 58 | /// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional |
| 59 | /// database connection is created for the garbage collector worker. |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 60 | pub fn create_thread_local_db() -> KeystoreDB { |
Seth Moore | 472fcbb | 2021-05-12 10:07:51 -0700 | [diff] [blame] | 61 | let db_path = DB_PATH.read().expect("Could not get the database directory."); |
| 62 | |
Seth Moore | 472fcbb | 2021-05-12 10:07:51 -0700 | [diff] [blame] | 63 | let mut db = KeystoreDB::new(&db_path, Some(GC.clone())).expect("Failed to open database."); |
| 64 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 65 | DB_INIT.call_once(|| { |
| 66 | log::info!("Touching Keystore 2.0 database for this first time since boot."); |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 67 | db.insert_last_off_body(MonotonicRawTime::now()); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 68 | log::info!("Calling cleanup leftovers."); |
| 69 | let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup."); |
| 70 | if n != 0 { |
| 71 | log::info!( |
| 72 | concat!( |
| 73 | "Cleaned up {} failed entries. ", |
| 74 | "This indicates keystore crashed during key generation." |
| 75 | ), |
| 76 | n |
| 77 | ); |
| 78 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 79 | }); |
| 80 | db |
| 81 | } |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 82 | |
| 83 | thread_local! { |
| 84 | /// Database connections are not thread safe, but connecting to the |
| 85 | /// same database multiple times is safe as long as each connection is |
| 86 | /// used by only one thread. So we store one database connection per |
| 87 | /// thread in this thread local key. |
| 88 | pub static DB: RefCell<KeystoreDB> = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 89 | RefCell::new(create_thread_local_db()); |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 90 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 91 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 92 | struct DevicesMap<T: FromIBinder + ?Sized> { |
| 93 | devices_by_uuid: HashMap<Uuid, (Strong<T>, KeyMintHardwareInfo)>, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 94 | uuid_by_sec_level: HashMap<SecurityLevel, Uuid>, |
| 95 | } |
| 96 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 97 | impl<T: FromIBinder + ?Sized> DevicesMap<T> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 98 | fn dev_by_sec_level( |
| 99 | &self, |
| 100 | sec_level: &SecurityLevel, |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 101 | ) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 102 | self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid)) |
| 103 | } |
| 104 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 105 | fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 106 | self.devices_by_uuid |
| 107 | .get(uuid) |
| 108 | .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid)) |
| 109 | } |
| 110 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 111 | fn devices(&self) -> Vec<Strong<T>> { |
| 112 | self.devices_by_uuid.values().map(|(dev, _)| dev.clone()).collect() |
David Drysdale | 0e45a61 | 2021-02-25 17:24:36 +0000 | [diff] [blame] | 113 | } |
| 114 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 115 | /// The requested security level and the security level of the actual implementation may |
| 116 | /// differ. So we map the requested security level to the uuid of the implementation |
| 117 | /// so that there cannot be any confusion as to which KeyMint instance is requested. |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 118 | fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>, hw_info: KeyMintHardwareInfo) { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 119 | // For now we use the reported security level of the KM instance as UUID. |
| 120 | // TODO update this section once UUID was added to the KM hardware info. |
| 121 | let uuid: Uuid = sec_level.into(); |
| 122 | self.devices_by_uuid.insert(uuid, (dev, hw_info)); |
| 123 | self.uuid_by_sec_level.insert(sec_level, uuid); |
| 124 | } |
| 125 | } |
| 126 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 127 | impl<T: FromIBinder + ?Sized> Default for DevicesMap<T> { |
| 128 | fn default() -> Self { |
| 129 | Self { |
| 130 | devices_by_uuid: HashMap::<Uuid, (Strong<T>, KeyMintHardwareInfo)>::new(), |
| 131 | uuid_by_sec_level: Default::default(), |
| 132 | } |
| 133 | } |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 134 | } |
| 135 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 136 | struct RemotelyProvisionedDevicesMap<T: FromIBinder + ?Sized> { |
| 137 | devices_by_sec_level: HashMap<SecurityLevel, Strong<T>>, |
| 138 | } |
| 139 | |
| 140 | impl<T: FromIBinder + ?Sized> Default for RemotelyProvisionedDevicesMap<T> { |
| 141 | fn default() -> Self { |
| 142 | Self { devices_by_sec_level: HashMap::<SecurityLevel, Strong<T>>::new() } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | impl<T: FromIBinder + ?Sized> RemotelyProvisionedDevicesMap<T> { |
| 147 | fn dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Strong<T>> { |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 148 | self.devices_by_sec_level.get(sec_level).map(|dev| (*dev).clone()) |
| 149 | } |
| 150 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 151 | fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>) { |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 152 | self.devices_by_sec_level.insert(sec_level, dev); |
| 153 | } |
| 154 | } |
| 155 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 156 | lazy_static! { |
Janis Danisevskis | 3f2955c | 2021-02-02 21:53:35 -0800 | [diff] [blame] | 157 | /// The path where keystore stores all its keys. |
Seth Moore | a3e611a | 2021-05-11 10:07:45 -0700 | [diff] [blame] | 158 | pub static ref DB_PATH: RwLock<PathBuf> = RwLock::new( |
Janis Danisevskis | 3f2955c | 2021-02-02 21:53:35 -0800 | [diff] [blame] | 159 | Path::new("/data/misc/keystore").to_path_buf()); |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 160 | /// Runtime database of unwrapped super keys. |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 161 | pub static ref SUPER_KEY: Arc<RwLock<SuperKeyManager>> = Default::default(); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 162 | /// Map of KeyMint devices. |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 163 | static ref KEY_MINT_DEVICES: Mutex<DevicesMap<dyn IKeyMintDevice>> = Default::default(); |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 164 | /// Timestamp service. |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 165 | static ref TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Default::default(); |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 166 | /// RemotelyProvisionedComponent HAL devices. |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 167 | static ref REMOTELY_PROVISIONED_COMPONENT_DEVICES: |
| 168 | Mutex<RemotelyProvisionedDevicesMap<dyn IRemotelyProvisionedComponent>> = |
| 169 | Default::default(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 170 | /// A single on-demand worker thread that handles deferred tasks with two different |
| 171 | /// priorities. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 172 | pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default(); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 173 | /// Singleton for enforcements. |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 174 | pub static ref ENFORCEMENTS: Enforcements = Default::default(); |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 175 | /// LegacyBlobLoader is initialized and exists globally. |
| 176 | /// The same directory used by the database is used by the LegacyBlobLoader as well. |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 177 | pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new( |
Seth Moore | a3e611a | 2021-05-11 10:07:45 -0700 | [diff] [blame] | 178 | &DB_PATH.read().expect("Could not get the database path for legacy blob loader."))); |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 179 | /// Legacy migrator. Atomically migrates legacy blobs to the database. |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 180 | pub static ref LEGACY_IMPORTER: Arc<LegacyImporter> = |
| 181 | Arc::new(LegacyImporter::new(Arc::new(Default::default()))); |
Pavel Grafov | 94243c2 | 2021-04-21 18:03:11 +0100 | [diff] [blame] | 182 | /// Background thread which handles logging via statsd and logd |
| 183 | pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default(); |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 184 | |
| 185 | static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || { |
| 186 | ( |
| 187 | Box::new(|uuid, blob| { |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 188 | let km_dev = get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?; |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 189 | let _wp = wd::watch_millis("In invalidate key closure: calling deleteKey", 500); |
Chris Wailes | 263de9f | 2022-08-11 15:00:51 -0700 | [diff] [blame] | 190 | map_km_error(km_dev.deleteKey(blob)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 191 | .context(ks_err!("Trying to invalidate key blob.")) |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 192 | }), |
Seth Moore | a3e611a | 2021-05-11 10:07:45 -0700 | [diff] [blame] | 193 | KeystoreDB::new(&DB_PATH.read().expect("Could not get the database directory."), None) |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 194 | .expect("Failed to open database."), |
| 195 | SUPER_KEY.clone(), |
| 196 | ) |
| 197 | })); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 198 | } |
| 199 | |
| 200 | static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice"; |
| 201 | |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 202 | /// Determine the service name for a KeyMint device of the given security level |
| 203 | /// which implements at least the specified version of the `IKeyMintDevice` |
| 204 | /// interface. |
| 205 | fn keymint_service_name_by_version( |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 206 | security_level: &SecurityLevel, |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 207 | version: i32, |
| 208 | ) -> Result<Option<(i32, String)>> { |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 209 | let keymint_instances = |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 210 | get_aidl_instances("android.hardware.security.keymint", version as usize, "IKeyMintDevice"); |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 211 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 212 | let service_name = match *security_level { |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 213 | SecurityLevel::TRUSTED_ENVIRONMENT => { |
Joel Galenson | ec7872a | 2021-07-02 14:37:10 -0700 | [diff] [blame] | 214 | if keymint_instances.iter().any(|instance| *instance == "default") { |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 215 | Some(format!("{}/default", KEYMINT_SERVICE_NAME)) |
| 216 | } else { |
| 217 | None |
| 218 | } |
| 219 | } |
| 220 | SecurityLevel::STRONGBOX => { |
Joel Galenson | ec7872a | 2021-07-02 14:37:10 -0700 | [diff] [blame] | 221 | if keymint_instances.iter().any(|instance| *instance == "strongbox") { |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 222 | Some(format!("{}/strongbox", KEYMINT_SERVICE_NAME)) |
| 223 | } else { |
| 224 | None |
| 225 | } |
| 226 | } |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 227 | _ => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 228 | return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!( |
| 229 | "Trying to find keymint V{} for security level: {:?}", |
| 230 | version, |
| 231 | security_level |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 232 | )); |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 233 | } |
| 234 | }; |
| 235 | |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 236 | Ok(service_name.map(|service_name| (version, service_name))) |
| 237 | } |
| 238 | |
| 239 | /// Make a new connection to a KeyMint device of the given security level. |
| 240 | /// If no native KeyMint device can be found this function also brings |
| 241 | /// up the compatibility service and attempts to connect to the legacy wrapper. |
| 242 | fn connect_keymint( |
| 243 | security_level: &SecurityLevel, |
| 244 | ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> { |
| 245 | // Count down from the current interface version back to one in order to |
| 246 | // also find out the interface version -- an implementation of V2 will show |
| 247 | // up in the list of V1-capable devices, but not vice-versa. |
| 248 | let service_name = keymint_service_name_by_version(security_level, 2) |
| 249 | .and_then(|sl| { |
| 250 | if sl.is_none() { |
| 251 | keymint_service_name_by_version(security_level, 1) |
| 252 | } else { |
| 253 | Ok(sl) |
| 254 | } |
| 255 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 256 | .context(ks_err!())?; |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 257 | |
| 258 | let (keymint, hal_version) = if let Some((version, service_name)) = service_name { |
David Drysdale | a6c82a9 | 2021-12-06 11:24:26 +0000 | [diff] [blame] | 259 | let km: Strong<dyn IKeyMintDevice> = |
Janis Danisevskis | bf855c0 | 2021-06-03 13:05:29 -0700 | [diff] [blame] | 260 | map_binder_status_code(binder::get_interface(&service_name)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 261 | .context(ks_err!("Trying to connect to genuine KeyMint service."))?; |
David Drysdale | a6c82a9 | 2021-12-06 11:24:26 +0000 | [diff] [blame] | 262 | // Map the HAL version code for KeyMint to be <AIDL version> * 100, so |
| 263 | // - V1 is 100 |
| 264 | // - V2 is 200 |
| 265 | // etc. |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 266 | (km, Some(version * 100)) |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 267 | } else { |
| 268 | // This is a no-op if it was called before. |
| 269 | keystore2_km_compat::add_keymint_device_service(); |
Janis Danisevskis | 8c6378e | 2021-01-01 09:30:37 -0800 | [diff] [blame] | 270 | |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 271 | let keystore_compat_service: Strong<dyn IKeystoreCompatService> = |
| 272 | map_binder_status_code(binder::get_interface("android.security.compat")) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 273 | .context(ks_err!("Trying to connect to compat service."))?; |
Janis Danisevskis | bf855c0 | 2021-06-03 13:05:29 -0700 | [diff] [blame] | 274 | ( |
| 275 | map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level)) |
| 276 | .map_err(|e| match e { |
| 277 | Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => { |
| 278 | Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE) |
| 279 | } |
| 280 | e => e, |
| 281 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 282 | .context(ks_err!("Trying to get Legacy wrapper."))?, |
Janis Danisevskis | bf855c0 | 2021-06-03 13:05:29 -0700 | [diff] [blame] | 283 | None, |
| 284 | ) |
| 285 | }; |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 286 | |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 287 | // If the KeyMint device is back-level, use a wrapper that intercepts and |
| 288 | // emulates things that are not supported by the hardware. |
| 289 | let keymint = match hal_version { |
| 290 | Some(200) => { |
| 291 | // Current KeyMint version: use as-is. |
| 292 | log::info!( |
| 293 | "KeyMint device is current version ({:?}) for security level: {:?}", |
| 294 | hal_version, |
| 295 | security_level |
| 296 | ); |
| 297 | keymint |
| 298 | } |
| 299 | Some(100) => { |
| 300 | // KeyMint v1: perform software emulation. |
| 301 | log::info!( |
| 302 | "Add emulation wrapper around {:?} device for security level: {:?}", |
| 303 | hal_version, |
| 304 | security_level |
| 305 | ); |
| 306 | BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 307 | .context(ks_err!("Trying to create V1 compatibility wrapper."))? |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 308 | } |
| 309 | None => { |
| 310 | // Compatibility wrapper around a KeyMaster device: this roughly |
| 311 | // behaves like KeyMint V1 (e.g. it includes AGREE_KEY support, |
| 312 | // albeit in software.) |
| 313 | log::info!( |
| 314 | "Add emulation wrapper around Keymaster device for security level: {:?}", |
| 315 | security_level |
| 316 | ); |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 317 | BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint) |
| 318 | .context(ks_err!("Trying to create km_compat V1 compatibility wrapper ."))? |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 319 | } |
| 320 | _ => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 321 | return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!( |
| 322 | "unexpected hal_version {:?} for security level: {:?}", |
| 323 | hal_version, |
| 324 | security_level |
| 325 | )); |
David Drysdale | c97eb9e | 2022-01-26 13:03:48 -0800 | [diff] [blame] | 326 | } |
| 327 | }; |
| 328 | |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 329 | let wp = wd::watch_millis("In connect_keymint: calling getHardwareInfo()", 500); |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 330 | let mut hw_info = |
| 331 | map_km_error(keymint.getHardwareInfo()).context(ks_err!("Failed to get hardware info."))?; |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 332 | drop(wp); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 333 | |
Janis Danisevskis | bf855c0 | 2021-06-03 13:05:29 -0700 | [diff] [blame] | 334 | // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so: |
| 335 | // 10 * <major> + <minor>, e.g., KM 3.0 = 30. So 30, 40, and 41 are the only viable values. |
David Drysdale | a6c82a9 | 2021-12-06 11:24:26 +0000 | [diff] [blame] | 336 | // |
| 337 | // For KeyMint the returned versionNumber is implementation defined and thus completely |
| 338 | // meaningless to Keystore 2.0. So set the versionNumber field that is returned to |
| 339 | // the rest of the code to be the <AIDL version> * 100, so KeyMint V1 is 100, KeyMint V2 is 200 |
| 340 | // and so on. |
| 341 | // |
| 342 | // This ensures that versionNumber value across KeyMaster and KeyMint is monotonically |
| 343 | // increasing (and so comparisons like `versionNumber >= KEY_MINT_1` are valid). |
Janis Danisevskis | bf855c0 | 2021-06-03 13:05:29 -0700 | [diff] [blame] | 344 | if let Some(hal_version) = hal_version { |
| 345 | hw_info.versionNumber = hal_version; |
| 346 | } |
| 347 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 348 | Ok((keymint, hw_info)) |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 349 | } |
| 350 | |
| 351 | /// 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] | 352 | /// by making a new connection. Returns the device, the hardware info and the uuid. |
| 353 | /// TODO the latter can be removed when the uuid is part of the hardware info. |
| 354 | pub fn get_keymint_device( |
| 355 | security_level: &SecurityLevel, |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 356 | ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)> { |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 357 | let mut devices_map = KEY_MINT_DEVICES.lock().unwrap(); |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 358 | if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(security_level) { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 359 | Ok((dev, hw_info, uuid)) |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 360 | } else { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 361 | let (dev, hw_info) = connect_keymint(security_level).context(ks_err!())?; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 362 | devices_map.insert(*security_level, dev, hw_info); |
| 363 | // Unwrap must succeed because we just inserted it. |
| 364 | Ok(devices_map.dev_by_sec_level(security_level).unwrap()) |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /// Get a keymint device for the given uuid. This will only access the cache, but will not |
| 369 | /// attempt to establish a new connection. It is assumed that the cache is already populated |
| 370 | /// when this is called. This is a fair assumption, because service.rs iterates through all |
| 371 | /// security levels when it gets instantiated. |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 372 | pub fn get_keymint_dev_by_uuid( |
| 373 | uuid: &Uuid, |
| 374 | ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 375 | let devices_map = KEY_MINT_DEVICES.lock().unwrap(); |
| 376 | if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) { |
| 377 | Ok((dev, hw_info)) |
| 378 | } else { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 379 | Err(Error::sys()).context(ks_err!("No KeyMint instance found.")) |
Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 380 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 381 | } |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 382 | |
David Drysdale | 0e45a61 | 2021-02-25 17:24:36 +0000 | [diff] [blame] | 383 | /// Return all known keymint devices. |
| 384 | pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> { |
| 385 | KEY_MINT_DEVICES.lock().unwrap().devices() |
| 386 | } |
| 387 | |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 388 | static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock"; |
| 389 | |
| 390 | /// Make a new connection to a secure clock service. |
| 391 | /// If no native SecureClock device can be found brings up the compatibility service and attempts |
| 392 | /// to connect to the legacy wrapper. |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 393 | fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> { |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 394 | let secureclock_instances = |
| 395 | get_aidl_instances("android.hardware.security.secureclock", 1, "ISecureClock"); |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 396 | |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 397 | let secure_clock_available = |
Joel Galenson | ec7872a | 2021-07-02 14:37:10 -0700 | [diff] [blame] | 398 | secureclock_instances.iter().any(|instance| *instance == "default"); |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 399 | |
Max Bires | 130e51b | 2021-04-05 14:07:20 -0700 | [diff] [blame] | 400 | let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME); |
| 401 | |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 402 | let secureclock = if secure_clock_available { |
Max Bires | 130e51b | 2021-04-05 14:07:20 -0700 | [diff] [blame] | 403 | map_binder_status_code(binder::get_interface(&default_time_stamp_service_name)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 404 | .context(ks_err!("Trying to connect to genuine secure clock service.")) |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 405 | } else { |
| 406 | // This is a no-op if it was called before. |
| 407 | keystore2_km_compat::add_keymint_device_service(); |
| 408 | |
| 409 | let keystore_compat_service: Strong<dyn IKeystoreCompatService> = |
| 410 | map_binder_status_code(binder::get_interface("android.security.compat")) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 411 | .context(ks_err!("Trying to connect to compat service."))?; |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 412 | |
| 413 | // Legacy secure clock services were only implemented by TEE. |
| 414 | map_binder_status(keystore_compat_service.getSecureClock()) |
| 415 | .map_err(|e| match e { |
| 416 | Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => { |
| 417 | Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE) |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 418 | } |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 419 | e => e, |
| 420 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 421 | .context(ks_err!("Trying to get Legacy wrapper.")) |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 422 | }?; |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 423 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 424 | Ok(secureclock) |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 425 | } |
| 426 | |
| 427 | /// Get the timestamp service that verifies auth token timeliness towards security levels with |
| 428 | /// different clocks. |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 429 | pub fn get_timestamp_service() -> Result<Strong<dyn ISecureClock>> { |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 430 | let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap(); |
| 431 | if let Some(dev) = &*ts_device { |
| 432 | Ok(dev.clone()) |
| 433 | } else { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 434 | let dev = connect_secureclock().context(ks_err!())?; |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 435 | *ts_device = Some(dev.clone()); |
| 436 | Ok(dev) |
| 437 | } |
| 438 | } |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 439 | |
| 440 | static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str = |
| 441 | "android.hardware.security.keymint.IRemotelyProvisionedComponent"; |
| 442 | |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 443 | fn connect_remotely_provisioned_component( |
| 444 | security_level: &SecurityLevel, |
| 445 | ) -> Result<Strong<dyn IRemotelyProvisionedComponent>> { |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 446 | let remotely_prov_instances = |
| 447 | get_aidl_instances("android.hardware.security.keymint", 1, "IRemotelyProvisionedComponent"); |
| 448 | |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 449 | let service_name = match *security_level { |
| 450 | SecurityLevel::TRUSTED_ENVIRONMENT => { |
Joel Galenson | ec7872a | 2021-07-02 14:37:10 -0700 | [diff] [blame] | 451 | if remotely_prov_instances.iter().any(|instance| *instance == "default") { |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 452 | Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME)) |
| 453 | } else { |
| 454 | None |
| 455 | } |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 456 | } |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 457 | SecurityLevel::STRONGBOX => { |
Joel Galenson | ec7872a | 2021-07-02 14:37:10 -0700 | [diff] [blame] | 458 | if remotely_prov_instances.iter().any(|instance| *instance == "strongbox") { |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 459 | Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME)) |
| 460 | } else { |
| 461 | None |
| 462 | } |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 463 | } |
Janis Danisevskis | ef14e1a | 2021-02-23 23:16:55 -0800 | [diff] [blame] | 464 | _ => None, |
| 465 | } |
| 466 | .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 467 | .context(ks_err!())?; |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 468 | |
| 469 | let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> = |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 470 | map_binder_status_code(binder::get_interface(&service_name)) |
| 471 | .context(ks_err!("Trying to connect to RemotelyProvisionedComponent service."))?; |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 472 | Ok(rem_prov_hal) |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 473 | } |
| 474 | |
| 475 | /// Get a remote provisiong component device for the given security level either from the cache or |
| 476 | /// by making a new connection. Returns the device. |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 477 | pub fn get_remotely_provisioned_component( |
| 478 | security_level: &SecurityLevel, |
| 479 | ) -> Result<Strong<dyn IRemotelyProvisionedComponent>> { |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 480 | let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap(); |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 481 | if let Some(dev) = devices_map.dev_by_sec_level(security_level) { |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 482 | Ok(dev) |
| 483 | } else { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 484 | let dev = connect_remotely_provisioned_component(security_level).context(ks_err!())?; |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 485 | devices_map.insert(*security_level, dev); |
| 486 | // Unwrap must succeed because we just inserted it. |
| 487 | Ok(devices_map.dev_by_sec_level(security_level).unwrap()) |
| 488 | } |
| 489 | } |