blob: 8b26cebb5d1115dfd4c9b383113abc6bd8911175 [file] [log] [blame]
Janis Danisevskisa75e2082020-10-07 16:44:26 -07001// 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 Johnson9da2e1c2022-09-19 12:39:01 +000019use crate::ks_err;
Janis Danisevskis93927dd2020-12-23 12:23:08 -080020use crate::gc::Gc;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000021use crate::legacy_blob::LegacyBlobLoader;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080022use crate::legacy_importer::LegacyImporter;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080023use crate::super_key::SuperKeyManager;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070024use crate::utils::watchdog as wd;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080025use crate::{async_task::AsyncTask, database::MonotonicRawTime};
Janis Danisevskisba998992020-12-29 16:08:40 -080026use crate::{
27 database::KeystoreDB,
Max Bires8e93d2b2021-01-14 13:17:59 -080028 database::Uuid,
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080029 error::{map_binder_status, map_binder_status_code, Error, ErrorCode},
Janis Danisevskisba998992020-12-29 16:08:40 -080030};
David Drysdalec97eb9e2022-01-26 13:03:48 -080031use crate::km_compat::{KeyMintV1, BacklevelKeyMintWrapper};
Max Bires8e93d2b2021-01-14 13:17:59 -080032use crate::{enforcements::Enforcements, error::map_km_error};
33use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Seth Moorecd6e9182022-11-04 17:39:05 +000034 IKeyMintDevice::IKeyMintDevice, KeyMintHardwareInfo::KeyMintHardwareInfo,
35 SecurityLevel::SecurityLevel,
Max Bires8e93d2b2021-01-14 13:17:59 -080036};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070037use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
38 ISecureClock::ISecureClock,
39};
Stephen Crane221bbb52020-12-16 15:52:10 -080040use android_hardware_security_keymint::binder::{StatusCode, Strong};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080041use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080042use anyhow::{Context, Result};
David Drysdale0e45a612021-02-25 17:24:36 +000043use binder::FromIBinder;
Shaquille Johnsond4443c62023-02-23 17:39:24 +000044use binder::get_declared_instances;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080045use lazy_static::lazy_static;
Seth Moorea3e611a2021-05-11 10:07:45 -070046use std::sync::{Arc, Mutex, RwLock};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080047use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080048use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080049
50static 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 Danisevskis7e8b4622021-02-13 10:01:59 -080055/// 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 Gunasinghe3ed5da72021-02-04 15:18:54 +000060pub fn create_thread_local_db() -> KeystoreDB {
Seth Moore472fcbb2021-05-12 10:07:51 -070061 let db_path = DB_PATH.read().expect("Could not get the database directory.");
62
Seth Moore472fcbb2021-05-12 10:07:51 -070063 let mut db = KeystoreDB::new(&db_path, Some(GC.clone())).expect("Failed to open database.");
64
Janis Danisevskis93927dd2020-12-23 12:23:08 -080065 DB_INIT.call_once(|| {
66 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Matthew Maurerd7815ca2021-05-06 21:58:45 -070067 db.insert_last_off_body(MonotonicRawTime::now());
Janis Danisevskis93927dd2020-12-23 12:23:08 -080068 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 Danisevskis93927dd2020-12-23 12:23:08 -080079 });
80 db
81}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070082
83thread_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 Danisevskis93927dd2020-12-23 12:23:08 -080089 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070090}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080091
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070092struct DevicesMap<T: FromIBinder + ?Sized> {
93 devices_by_uuid: HashMap<Uuid, (Strong<T>, KeyMintHardwareInfo)>,
Max Bires8e93d2b2021-01-14 13:17:59 -080094 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
95}
96
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070097impl<T: FromIBinder + ?Sized> DevicesMap<T> {
Max Bires8e93d2b2021-01-14 13:17:59 -080098 fn dev_by_sec_level(
99 &self,
100 sec_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700101 ) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800102 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
103 }
104
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700105 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800106 self.devices_by_uuid
107 .get(uuid)
108 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
109 }
110
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700111 fn devices(&self) -> Vec<Strong<T>> {
112 self.devices_by_uuid.values().map(|(dev, _)| dev.clone()).collect()
David Drysdale0e45a612021-02-25 17:24:36 +0000113 }
114
Max Bires8e93d2b2021-01-14 13:17:59 -0800115 /// 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 Danisevskis5f3a0572021-06-18 11:26:42 -0700118 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>, hw_info: KeyMintHardwareInfo) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800119 // 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 Danisevskis5f3a0572021-06-18 11:26:42 -0700127impl<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 Biresb2e1d032021-02-08 21:35:05 -0800134}
135
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800136lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800137 /// The path where keystore stores all its keys.
Seth Moorea3e611a2021-05-11 10:07:45 -0700138 pub static ref DB_PATH: RwLock<PathBuf> = RwLock::new(
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800139 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800140 /// Runtime database of unwrapped super keys.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800141 pub static ref SUPER_KEY: Arc<RwLock<SuperKeyManager>> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800142 /// Map of KeyMint devices.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700143 static ref KEY_MINT_DEVICES: Mutex<DevicesMap<dyn IKeyMintDevice>> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800144 /// Timestamp service.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700145 static ref TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800146 /// A single on-demand worker thread that handles deferred tasks with two different
147 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800148 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800149 /// Singleton for enforcements.
Paul Crowley7c57bf12021-02-02 16:26:57 -0800150 pub static ref ENFORCEMENTS: Enforcements = Default::default();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000151 /// LegacyBlobLoader is initialized and exists globally.
152 /// The same directory used by the database is used by the LegacyBlobLoader as well.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000153 pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
Seth Moorea3e611a2021-05-11 10:07:45 -0700154 &DB_PATH.read().expect("Could not get the database path for legacy blob loader.")));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000155 /// Legacy migrator. Atomically migrates legacy blobs to the database.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800156 pub static ref LEGACY_IMPORTER: Arc<LegacyImporter> =
157 Arc::new(LegacyImporter::new(Arc::new(Default::default())));
Pavel Grafov94243c22021-04-21 18:03:11 +0100158 /// Background thread which handles logging via statsd and logd
159 pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
Janis Danisevskis3395f862021-05-06 10:54:17 -0700160
161 static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
162 (
163 Box::new(|uuid, blob| {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700164 let km_dev = get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?;
Janis Danisevskis3395f862021-05-06 10:54:17 -0700165 let _wp = wd::watch_millis("In invalidate key closure: calling deleteKey", 500);
Chris Wailes263de9f2022-08-11 15:00:51 -0700166 map_km_error(km_dev.deleteKey(blob))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000167 .context(ks_err!("Trying to invalidate key blob."))
Janis Danisevskis3395f862021-05-06 10:54:17 -0700168 }),
Seth Moorea3e611a2021-05-11 10:07:45 -0700169 KeystoreDB::new(&DB_PATH.read().expect("Could not get the database directory."), None)
Janis Danisevskis3395f862021-05-06 10:54:17 -0700170 .expect("Failed to open database."),
171 SUPER_KEY.clone(),
172 )
173 }));
Janis Danisevskisba998992020-12-29 16:08:40 -0800174}
175
176static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
177
David Drysdalec97eb9e2022-01-26 13:03:48 -0800178/// Determine the service name for a KeyMint device of the given security level
179/// which implements at least the specified version of the `IKeyMintDevice`
180/// interface.
181fn keymint_service_name_by_version(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700182 security_level: &SecurityLevel,
David Drysdalec97eb9e2022-01-26 13:03:48 -0800183 version: i32,
184) -> Result<Option<(i32, String)>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800185 let keymint_instances =
Shaquille Johnsond4443c62023-02-23 17:39:24 +0000186 get_declared_instances("android.hardware.security.keymint.IKeyMintDevice").unwrap();
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800187
Max Bires8e93d2b2021-01-14 13:17:59 -0800188 let service_name = match *security_level {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800189 SecurityLevel::TRUSTED_ENVIRONMENT => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700190 if keymint_instances.iter().any(|instance| *instance == "default") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800191 Some(format!("{}/default", KEYMINT_SERVICE_NAME))
192 } else {
193 None
194 }
195 }
196 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700197 if keymint_instances.iter().any(|instance| *instance == "strongbox") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800198 Some(format!("{}/strongbox", KEYMINT_SERVICE_NAME))
199 } else {
200 None
201 }
202 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800203 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000204 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!(
205 "Trying to find keymint V{} for security level: {:?}",
206 version,
207 security_level
David Drysdalec97eb9e2022-01-26 13:03:48 -0800208 ));
Janis Danisevskisba998992020-12-29 16:08:40 -0800209 }
210 };
211
David Drysdalec97eb9e2022-01-26 13:03:48 -0800212 Ok(service_name.map(|service_name| (version, service_name)))
213}
214
215/// Make a new connection to a KeyMint device of the given security level.
216/// If no native KeyMint device can be found this function also brings
217/// up the compatibility service and attempts to connect to the legacy wrapper.
218fn connect_keymint(
219 security_level: &SecurityLevel,
220) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
221 // Count down from the current interface version back to one in order to
222 // also find out the interface version -- an implementation of V2 will show
223 // up in the list of V1-capable devices, but not vice-versa.
224 let service_name = keymint_service_name_by_version(security_level, 2)
225 .and_then(|sl| {
226 if sl.is_none() {
227 keymint_service_name_by_version(security_level, 1)
228 } else {
229 Ok(sl)
230 }
231 })
Shaquille Johnsond4443c62023-02-23 17:39:24 +0000232 .context(ks_err!("Get service name by version"))?;
David Drysdalec97eb9e2022-01-26 13:03:48 -0800233
234 let (keymint, hal_version) = if let Some((version, service_name)) = service_name {
David Drysdalea6c82a92021-12-06 11:24:26 +0000235 let km: Strong<dyn IKeyMintDevice> =
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700236 map_binder_status_code(binder::get_interface(&service_name))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000237 .context(ks_err!("Trying to connect to genuine KeyMint service."))?;
David Drysdalea6c82a92021-12-06 11:24:26 +0000238 // Map the HAL version code for KeyMint to be <AIDL version> * 100, so
239 // - V1 is 100
240 // - V2 is 200
241 // etc.
David Drysdalec97eb9e2022-01-26 13:03:48 -0800242 (km, Some(version * 100))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800243 } else {
244 // This is a no-op if it was called before.
245 keystore2_km_compat::add_keymint_device_service();
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800246
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800247 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
248 map_binder_status_code(binder::get_interface("android.security.compat"))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000249 .context(ks_err!("Trying to connect to compat service."))?;
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700250 (
251 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
252 .map_err(|e| match e {
253 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
254 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
255 }
256 e => e,
257 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000258 .context(ks_err!("Trying to get Legacy wrapper."))?,
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700259 None,
260 )
261 };
Janis Danisevskisba998992020-12-29 16:08:40 -0800262
David Drysdalec97eb9e2022-01-26 13:03:48 -0800263 // If the KeyMint device is back-level, use a wrapper that intercepts and
264 // emulates things that are not supported by the hardware.
265 let keymint = match hal_version {
266 Some(200) => {
267 // Current KeyMint version: use as-is.
268 log::info!(
269 "KeyMint device is current version ({:?}) for security level: {:?}",
270 hal_version,
271 security_level
272 );
273 keymint
274 }
275 Some(100) => {
276 // KeyMint v1: perform software emulation.
277 log::info!(
278 "Add emulation wrapper around {:?} device for security level: {:?}",
279 hal_version,
280 security_level
281 );
282 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000283 .context(ks_err!("Trying to create V1 compatibility wrapper."))?
David Drysdalec97eb9e2022-01-26 13:03:48 -0800284 }
285 None => {
286 // Compatibility wrapper around a KeyMaster device: this roughly
287 // behaves like KeyMint V1 (e.g. it includes AGREE_KEY support,
288 // albeit in software.)
289 log::info!(
290 "Add emulation wrapper around Keymaster device for security level: {:?}",
291 security_level
292 );
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000293 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
294 .context(ks_err!("Trying to create km_compat V1 compatibility wrapper ."))?
David Drysdalec97eb9e2022-01-26 13:03:48 -0800295 }
296 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000297 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!(
298 "unexpected hal_version {:?} for security level: {:?}",
299 hal_version,
300 security_level
301 ));
David Drysdalec97eb9e2022-01-26 13:03:48 -0800302 }
303 };
304
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700305 let wp = wd::watch_millis("In connect_keymint: calling getHardwareInfo()", 500);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000306 let mut hw_info =
307 map_km_error(keymint.getHardwareInfo()).context(ks_err!("Failed to get hardware info."))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700308 drop(wp);
Max Bires8e93d2b2021-01-14 13:17:59 -0800309
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700310 // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
311 // 10 * <major> + <minor>, e.g., KM 3.0 = 30. So 30, 40, and 41 are the only viable values.
David Drysdalea6c82a92021-12-06 11:24:26 +0000312 //
313 // For KeyMint the returned versionNumber is implementation defined and thus completely
314 // meaningless to Keystore 2.0. So set the versionNumber field that is returned to
315 // the rest of the code to be the <AIDL version> * 100, so KeyMint V1 is 100, KeyMint V2 is 200
316 // and so on.
317 //
318 // This ensures that versionNumber value across KeyMaster and KeyMint is monotonically
319 // increasing (and so comparisons like `versionNumber >= KEY_MINT_1` are valid).
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700320 if let Some(hal_version) = hal_version {
321 hw_info.versionNumber = hal_version;
322 }
323
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700324 Ok((keymint, hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800325}
326
327/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800328/// by making a new connection. Returns the device, the hardware info and the uuid.
329/// TODO the latter can be removed when the uuid is part of the hardware info.
330pub fn get_keymint_device(
331 security_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700332) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800333 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700334 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(security_level) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800335 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800336 } else {
Shaquille Johnsond4443c62023-02-23 17:39:24 +0000337 let (dev, hw_info) =
338 connect_keymint(security_level).context(ks_err!("Cannot connect to Keymint"))?;
Max Bires8e93d2b2021-01-14 13:17:59 -0800339 devices_map.insert(*security_level, dev, hw_info);
340 // Unwrap must succeed because we just inserted it.
341 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
342 }
343}
344
345/// Get a keymint device for the given uuid. This will only access the cache, but will not
346/// attempt to establish a new connection. It is assumed that the cache is already populated
347/// when this is called. This is a fair assumption, because service.rs iterates through all
348/// security levels when it gets instantiated.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700349pub fn get_keymint_dev_by_uuid(
350 uuid: &Uuid,
351) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800352 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
353 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
354 Ok((dev, hw_info))
355 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000356 Err(Error::sys()).context(ks_err!("No KeyMint instance found."))
Janis Danisevskisba998992020-12-29 16:08:40 -0800357 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800358}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800359
David Drysdale0e45a612021-02-25 17:24:36 +0000360/// Return all known keymint devices.
361pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
362 KEY_MINT_DEVICES.lock().unwrap().devices()
363}
364
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800365static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
366
367/// Make a new connection to a secure clock service.
368/// If no native SecureClock device can be found brings up the compatibility service and attempts
369/// to connect to the legacy wrapper.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700370fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800371 let secureclock_instances =
Shaquille Johnsond4443c62023-02-23 17:39:24 +0000372 get_declared_instances("android.hardware.security.secureclock.ISecureClock").unwrap();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800373
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800374 let secure_clock_available =
Joel Galensonec7872a2021-07-02 14:37:10 -0700375 secureclock_instances.iter().any(|instance| *instance == "default");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800376
Max Bires130e51b2021-04-05 14:07:20 -0700377 let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
378
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800379 let secureclock = if secure_clock_available {
Max Bires130e51b2021-04-05 14:07:20 -0700380 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000381 .context(ks_err!("Trying to connect to genuine secure clock service."))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800382 } else {
383 // This is a no-op if it was called before.
384 keystore2_km_compat::add_keymint_device_service();
385
386 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
387 map_binder_status_code(binder::get_interface("android.security.compat"))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000388 .context(ks_err!("Trying to connect to compat service."))?;
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800389
390 // Legacy secure clock services were only implemented by TEE.
391 map_binder_status(keystore_compat_service.getSecureClock())
392 .map_err(|e| match e {
393 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
394 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800395 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800396 e => e,
397 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000398 .context(ks_err!("Trying to get Legacy wrapper."))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800399 }?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800400
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700401 Ok(secureclock)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800402}
403
404/// Get the timestamp service that verifies auth token timeliness towards security levels with
405/// different clocks.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700406pub fn get_timestamp_service() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800407 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
408 if let Some(dev) = &*ts_device {
409 Ok(dev.clone())
410 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000411 let dev = connect_secureclock().context(ks_err!())?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800412 *ts_device = Some(dev.clone());
413 Ok(dev)
414 }
415}
Max Biresb2e1d032021-02-08 21:35:05 -0800416
417static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
418 "android.hardware.security.keymint.IRemotelyProvisionedComponent";
419
Tri Voe8f04442022-12-21 08:53:56 -0800420/// Get the service name of a remotely provisioned component corresponding to given security level.
421pub fn get_remotely_provisioned_component_name(security_level: &SecurityLevel) -> Result<String> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800422 let remotely_prov_instances =
Shaquille Johnsond4443c62023-02-23 17:39:24 +0000423 get_declared_instances(REMOTE_PROVISIONING_HAL_SERVICE_NAME).unwrap();
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800424
Tri Voe8f04442022-12-21 08:53:56 -0800425 match *security_level {
Max Biresb2e1d032021-02-08 21:35:05 -0800426 SecurityLevel::TRUSTED_ENVIRONMENT => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700427 if remotely_prov_instances.iter().any(|instance| *instance == "default") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800428 Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
429 } else {
430 None
431 }
Max Biresb2e1d032021-02-08 21:35:05 -0800432 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800433 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700434 if remotely_prov_instances.iter().any(|instance| *instance == "strongbox") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800435 Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
436 } else {
437 None
438 }
Max Biresb2e1d032021-02-08 21:35:05 -0800439 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800440 _ => None,
441 }
442 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
Tri Voe8f04442022-12-21 08:53:56 -0800443 .context(ks_err!())
444}