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