blob: bde83fd2e3ea5cc0099edffad2d1e0976d9362e4 [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
Eric Biggersb5613da2024-03-13 19:31:42 +000019use crate::async_task::AsyncTask;
Janis Danisevskis93927dd2020-12-23 12:23:08 -080020use crate::gc::Gc;
Shaquille Johnsondf83fb72023-03-24 12:26:52 +000021use crate::km_compat::{BacklevelKeyMintWrapper, KeyMintV1};
22use crate::ks_err;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000023use crate::legacy_blob::LegacyBlobLoader;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080024use crate::legacy_importer::LegacyImporter;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080025use crate::super_key::SuperKeyManager;
Alice Wang81dbef72024-07-31 15:13:14 +000026use crate::utils::{retry_get_interface, watchdog as wd};
Janis Danisevskisba998992020-12-29 16:08:40 -080027use crate::{
28 database::KeystoreDB,
Max Bires8e93d2b2021-01-14 13:17:59 -080029 database::Uuid,
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080030 error::{map_binder_status, map_binder_status_code, Error, ErrorCode},
Janis Danisevskisba998992020-12-29 16:08:40 -080031};
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::{
Shaquille Johnson8d67b752023-03-31 11:17:34 +010034 IKeyMintDevice::BpKeyMintDevice, IKeyMintDevice::IKeyMintDevice,
35 KeyMintHardwareInfo::KeyMintHardwareInfo, SecurityLevel::SecurityLevel,
Max Bires8e93d2b2021-01-14 13:17:59 -080036};
Stephen Crane221bbb52020-12-16 15:52:10 -080037use android_hardware_security_keymint::binder::{StatusCode, Strong};
Shaquille Johnsondf83fb72023-03-24 12:26:52 +000038use android_hardware_security_rkp::aidl::android::hardware::security::keymint::{
39 IRemotelyProvisionedComponent::BpRemotelyProvisionedComponent,
40 IRemotelyProvisionedComponent::IRemotelyProvisionedComponent,
41};
42use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
43 ISecureClock::BpSecureClock, ISecureClock::ISecureClock,
44};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080045use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080046use anyhow::{Context, Result};
Shaquille Johnsondf83fb72023-03-24 12:26:52 +000047use binder::FromIBinder;
Karuna Wadhera9ae66c02024-05-16 19:40:59 +000048use binder::{get_declared_instances, is_declared};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use lazy_static::lazy_static;
Seth Moorea3e611a2021-05-11 10:07:45 -070050use std::sync::{Arc, Mutex, RwLock};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080051use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080052use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080053
54static DB_INIT: Once = Once::new();
55
56/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
57/// the thread local DB field. It should never be called directly. The first time this is called
58/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080059/// documentation of cleanup_leftovers for more details. The function also constructs a blob
60/// garbage collector. The initializing closure constructs another database connection without
61/// a gc. Although one GC is created for each thread local database connection, this closure
62/// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
63/// database connection is created for the garbage collector worker.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000064pub fn create_thread_local_db() -> KeystoreDB {
David Drysdale18c29f32024-07-19 12:54:19 +010065 let db_path = DB_PATH.read().expect("Could not get the database directory");
Seth Moore472fcbb2021-05-12 10:07:51 -070066
David Drysdale18c29f32024-07-19 12:54:19 +010067 let result = KeystoreDB::new(&db_path, Some(GC.clone()));
68 let mut db = match result {
69 Ok(db) => db,
70 Err(e) => {
71 log::error!("Failed to open Keystore database at {db_path:?}: {e:?}");
72 log::error!("Has /data been mounted correctly?");
73 panic!("Failed to open database for Keystore, cannot continue: {e:?}")
74 }
75 };
Seth Moore472fcbb2021-05-12 10:07:51 -070076
Janis Danisevskis93927dd2020-12-23 12:23:08 -080077 DB_INIT.call_once(|| {
78 log::info!("Touching Keystore 2.0 database for this first time since boot.");
79 log::info!("Calling cleanup leftovers.");
David Drysdale18c29f32024-07-19 12:54:19 +010080 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080081 if n != 0 {
82 log::info!(
David Drysdale18c29f32024-07-19 12:54:19 +010083 "Cleaned up {n} failed entries, indicating keystore crash on key generation"
Janis Danisevskis93927dd2020-12-23 12:23:08 -080084 );
85 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -080086 });
87 db
88}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070089
90thread_local! {
91 /// Database connections are not thread safe, but connecting to the
92 /// same database multiple times is safe as long as each connection is
93 /// used by only one thread. So we store one database connection per
94 /// thread in this thread local key.
David Drysdale18c29f32024-07-19 12:54:19 +010095 pub static DB: RefCell<KeystoreDB> = RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070096}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080097
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070098struct DevicesMap<T: FromIBinder + ?Sized> {
99 devices_by_uuid: HashMap<Uuid, (Strong<T>, KeyMintHardwareInfo)>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800100 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
101}
102
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700103impl<T: FromIBinder + ?Sized> DevicesMap<T> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800104 fn dev_by_sec_level(
105 &self,
106 sec_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700107 ) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800108 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
109 }
110
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700111 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800112 self.devices_by_uuid
113 .get(uuid)
114 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
115 }
116
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700117 fn devices(&self) -> Vec<Strong<T>> {
118 self.devices_by_uuid.values().map(|(dev, _)| dev.clone()).collect()
David Drysdale0e45a612021-02-25 17:24:36 +0000119 }
120
Max Bires8e93d2b2021-01-14 13:17:59 -0800121 /// The requested security level and the security level of the actual implementation may
122 /// differ. So we map the requested security level to the uuid of the implementation
123 /// so that there cannot be any confusion as to which KeyMint instance is requested.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700124 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>, hw_info: KeyMintHardwareInfo) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800125 // For now we use the reported security level of the KM instance as UUID.
126 // TODO update this section once UUID was added to the KM hardware info.
127 let uuid: Uuid = sec_level.into();
128 self.devices_by_uuid.insert(uuid, (dev, hw_info));
129 self.uuid_by_sec_level.insert(sec_level, uuid);
130 }
131}
132
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700133impl<T: FromIBinder + ?Sized> Default for DevicesMap<T> {
134 fn default() -> Self {
135 Self {
136 devices_by_uuid: HashMap::<Uuid, (Strong<T>, KeyMintHardwareInfo)>::new(),
137 uuid_by_sec_level: Default::default(),
138 }
139 }
Max Biresb2e1d032021-02-08 21:35:05 -0800140}
141
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800142lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800143 /// The path where keystore stores all its keys.
Seth Moorea3e611a2021-05-11 10:07:45 -0700144 pub static ref DB_PATH: RwLock<PathBuf> = RwLock::new(
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800145 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800146 /// Runtime database of unwrapped super keys.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800147 pub static ref SUPER_KEY: Arc<RwLock<SuperKeyManager>> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800148 /// Map of KeyMint devices.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700149 static ref KEY_MINT_DEVICES: Mutex<DevicesMap<dyn IKeyMintDevice>> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800150 /// Timestamp service.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700151 static ref TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800152 /// A single on-demand worker thread that handles deferred tasks with two different
153 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800154 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800155 /// Singleton for enforcements.
Paul Crowley7c57bf12021-02-02 16:26:57 -0800156 pub static ref ENFORCEMENTS: Enforcements = Default::default();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000157 /// LegacyBlobLoader is initialized and exists globally.
158 /// The same directory used by the database is used by the LegacyBlobLoader as well.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000159 pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
David Drysdale18c29f32024-07-19 12:54:19 +0100160 &DB_PATH.read().expect("Could not determine database path for legacy blob loader")));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000161 /// Legacy migrator. Atomically migrates legacy blobs to the database.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800162 pub static ref LEGACY_IMPORTER: Arc<LegacyImporter> =
163 Arc::new(LegacyImporter::new(Arc::new(Default::default())));
Pavel Grafov94243c22021-04-21 18:03:11 +0100164 /// Background thread which handles logging via statsd and logd
165 pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
Janis Danisevskis3395f862021-05-06 10:54:17 -0700166
167 static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
168 (
169 Box::new(|uuid, blob| {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700170 let km_dev = get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?;
David Drysdalec652f6c2024-07-18 13:01:23 +0100171 let _wp = wd::watch("invalidate key closure: calling IKeyMintDevice::deleteKey");
Chris Wailes263de9f2022-08-11 15:00:51 -0700172 map_km_error(km_dev.deleteKey(blob))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000173 .context(ks_err!("Trying to invalidate key blob."))
Janis Danisevskis3395f862021-05-06 10:54:17 -0700174 }),
David Drysdale18c29f32024-07-19 12:54:19 +0100175 KeystoreDB::new(&DB_PATH.read().expect("Could not determine database path for GC"), None)
176 .expect("Failed to open database"),
Janis Danisevskis3395f862021-05-06 10:54:17 -0700177 SUPER_KEY.clone(),
178 )
179 }));
Janis Danisevskisba998992020-12-29 16:08:40 -0800180}
181
David Drysdalec97eb9e2022-01-26 13:03:48 -0800182/// Determine the service name for a KeyMint device of the given security level
Shaquille Johnsondf83fb72023-03-24 12:26:52 +0000183/// gotten by binder service from the device and determining what services
184/// are available.
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100185fn keymint_service_name(security_level: &SecurityLevel) -> Result<Option<String>> {
186 let keymint_descriptor: &str = <BpKeyMintDevice as IKeyMintDevice>::get_descriptor();
187 let keymint_instances = get_declared_instances(keymint_descriptor).unwrap();
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800188
Max Bires8e93d2b2021-01-14 13:17:59 -0800189 let service_name = match *security_level {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800190 SecurityLevel::TRUSTED_ENVIRONMENT => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700191 if keymint_instances.iter().any(|instance| *instance == "default") {
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100192 Some(format!("{}/default", keymint_descriptor))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800193 } else {
194 None
195 }
196 }
197 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700198 if keymint_instances.iter().any(|instance| *instance == "strongbox") {
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100199 Some(format!("{}/strongbox", keymint_descriptor))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800200 } else {
201 None
202 }
203 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800204 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000205 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!(
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100206 "Trying to find keymint for security level: {:?}",
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000207 security_level
David Drysdalec97eb9e2022-01-26 13:03:48 -0800208 ));
Janis Danisevskisba998992020-12-29 16:08:40 -0800209 }
210 };
211
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100212 Ok(service_name)
David Drysdalec97eb9e2022-01-26 13:03:48 -0800213}
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)> {
Shaquille Johnsondf83fb72023-03-24 12:26:52 +0000221 // Show the keymint interface that is registered in the binder
222 // service and use the security level to get the service name.
223 let service_name = keymint_service_name(security_level)
224 .context(ks_err!("Get service name from binder service"))?;
David Drysdalec97eb9e2022-01-26 13:03:48 -0800225
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100226 let (keymint, hal_version) = if let Some(service_name) = service_name {
David Drysdalea6c82a92021-12-06 11:24:26 +0000227 let km: Strong<dyn IKeyMintDevice> =
Alice Wang81dbef72024-07-31 15:13:14 +0000228 if SecurityLevel::TRUSTED_ENVIRONMENT == *security_level {
229 map_binder_status_code(retry_get_interface(&service_name))
230 } else {
231 map_binder_status_code(binder::get_interface(&service_name))
232 }
233 .context(ks_err!("Trying to connect to genuine KeyMint service."))?;
David Drysdalea6c82a92021-12-06 11:24:26 +0000234 // Map the HAL version code for KeyMint to be <AIDL version> * 100, so
235 // - V1 is 100
236 // - V2 is 200
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100237 // - V3 is 300
David Drysdalea6c82a92021-12-06 11:24:26 +0000238 // etc.
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100239 let km_version = km.getInterfaceVersion()?;
240 (km, Some(km_version * 100))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800241 } else {
242 // This is a no-op if it was called before.
243 keystore2_km_compat::add_keymint_device_service();
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800244
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800245 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
246 map_binder_status_code(binder::get_interface("android.security.compat"))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000247 .context(ks_err!("Trying to connect to compat service."))?;
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700248 (
249 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
250 .map_err(|e| match e {
251 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
252 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
253 }
254 e => e,
255 })
Shaquille Johnson69c92a02024-02-28 22:14:05 +0000256 .context(ks_err!(
257 "Trying to get Legacy wrapper. Attempt to get keystore \
258 compat service for security level {:?}",
259 *security_level
260 ))?,
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700261 None,
262 )
263 };
Janis Danisevskisba998992020-12-29 16:08:40 -0800264
David Drysdalec97eb9e2022-01-26 13:03:48 -0800265 // If the KeyMint device is back-level, use a wrapper that intercepts and
266 // emulates things that are not supported by the hardware.
267 let keymint = match hal_version {
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100268 Some(300) => {
269 // Current KeyMint version: use as-is as v3 Keymint is current version
270 log::info!(
271 "KeyMint device is current version ({:?}) for security level: {:?}",
272 hal_version,
273 security_level
274 );
275 keymint
276 }
David Drysdalec97eb9e2022-01-26 13:03:48 -0800277 Some(200) => {
Shaquille Johnson8d67b752023-03-31 11:17:34 +0100278 // Previous KeyMint version: use as-is as we don't have any software emulation of v3-specific KeyMint features.
David Drysdalec97eb9e2022-01-26 13:03:48 -0800279 log::info!(
280 "KeyMint device is current version ({:?}) for security level: {:?}",
281 hal_version,
282 security_level
283 );
284 keymint
285 }
286 Some(100) => {
287 // KeyMint v1: perform software emulation.
288 log::info!(
289 "Add emulation wrapper around {:?} device for security level: {:?}",
290 hal_version,
291 security_level
292 );
293 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000294 .context(ks_err!("Trying to create V1 compatibility wrapper."))?
David Drysdalec97eb9e2022-01-26 13:03:48 -0800295 }
296 None => {
297 // Compatibility wrapper around a KeyMaster device: this roughly
298 // behaves like KeyMint V1 (e.g. it includes AGREE_KEY support,
299 // albeit in software.)
300 log::info!(
301 "Add emulation wrapper around Keymaster device for security level: {:?}",
302 security_level
303 );
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000304 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
305 .context(ks_err!("Trying to create km_compat V1 compatibility wrapper ."))?
David Drysdalec97eb9e2022-01-26 13:03:48 -0800306 }
307 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000308 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!(
309 "unexpected hal_version {:?} for security level: {:?}",
310 hal_version,
311 security_level
312 ));
David Drysdalec97eb9e2022-01-26 13:03:48 -0800313 }
314 };
315
David Drysdalec652f6c2024-07-18 13:01:23 +0100316 let wp = wd::watch("connect_keymint: calling IKeyMintDevice::getHardwareInfo()");
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000317 let mut hw_info =
318 map_km_error(keymint.getHardwareInfo()).context(ks_err!("Failed to get hardware info."))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700319 drop(wp);
Max Bires8e93d2b2021-01-14 13:17:59 -0800320
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700321 // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
322 // 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 +0000323 //
324 // For KeyMint the returned versionNumber is implementation defined and thus completely
325 // meaningless to Keystore 2.0. So set the versionNumber field that is returned to
326 // the rest of the code to be the <AIDL version> * 100, so KeyMint V1 is 100, KeyMint V2 is 200
327 // and so on.
328 //
329 // This ensures that versionNumber value across KeyMaster and KeyMint is monotonically
330 // increasing (and so comparisons like `versionNumber >= KEY_MINT_1` are valid).
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700331 if let Some(hal_version) = hal_version {
332 hw_info.versionNumber = hal_version;
333 }
334
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700335 Ok((keymint, hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800336}
337
338/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800339/// by making a new connection. Returns the device, the hardware info and the uuid.
340/// TODO the latter can be removed when the uuid is part of the hardware info.
341pub fn get_keymint_device(
342 security_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700343) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800344 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700345 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(security_level) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800346 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800347 } else {
Shaquille Johnsond4443c62023-02-23 17:39:24 +0000348 let (dev, hw_info) =
349 connect_keymint(security_level).context(ks_err!("Cannot connect to Keymint"))?;
Max Bires8e93d2b2021-01-14 13:17:59 -0800350 devices_map.insert(*security_level, dev, hw_info);
351 // Unwrap must succeed because we just inserted it.
352 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
353 }
354}
355
356/// Get a keymint device for the given uuid. This will only access the cache, but will not
357/// attempt to establish a new connection. It is assumed that the cache is already populated
358/// when this is called. This is a fair assumption, because service.rs iterates through all
359/// security levels when it gets instantiated.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700360pub fn get_keymint_dev_by_uuid(
361 uuid: &Uuid,
362) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800363 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
364 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
365 Ok((dev, hw_info))
366 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000367 Err(Error::sys()).context(ks_err!("No KeyMint instance found."))
Janis Danisevskisba998992020-12-29 16:08:40 -0800368 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800369}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800370
David Drysdale0e45a612021-02-25 17:24:36 +0000371/// Return all known keymint devices.
372pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
373 KEY_MINT_DEVICES.lock().unwrap().devices()
374}
375
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800376/// Make a new connection to a secure clock service.
377/// If no native SecureClock device can be found brings up the compatibility service and attempts
378/// to connect to the legacy wrapper.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700379fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> {
Shaquille Johnsondf83fb72023-03-24 12:26:52 +0000380 let secure_clock_descriptor: &str = <BpSecureClock as ISecureClock>::get_descriptor();
381 let secureclock_instances = get_declared_instances(secure_clock_descriptor).unwrap();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800382
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800383 let secure_clock_available =
Joel Galensonec7872a2021-07-02 14:37:10 -0700384 secureclock_instances.iter().any(|instance| *instance == "default");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800385
Shaquille Johnsondf83fb72023-03-24 12:26:52 +0000386 let default_time_stamp_service_name = format!("{}/default", secure_clock_descriptor);
Max Bires130e51b2021-04-05 14:07:20 -0700387
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800388 let secureclock = if secure_clock_available {
Max Bires130e51b2021-04-05 14:07:20 -0700389 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000390 .context(ks_err!("Trying to connect to genuine secure clock service."))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800391 } else {
392 // This is a no-op if it was called before.
393 keystore2_km_compat::add_keymint_device_service();
394
395 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
396 map_binder_status_code(binder::get_interface("android.security.compat"))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000397 .context(ks_err!("Trying to connect to compat service."))?;
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800398
399 // Legacy secure clock services were only implemented by TEE.
400 map_binder_status(keystore_compat_service.getSecureClock())
401 .map_err(|e| match e {
402 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
403 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800404 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800405 e => e,
406 })
Shaquille Johnson69c92a02024-02-28 22:14:05 +0000407 .context(ks_err!("Failed attempt to get legacy secure clock."))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800408 }?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800409
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700410 Ok(secureclock)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800411}
412
413/// Get the timestamp service that verifies auth token timeliness towards security levels with
414/// different clocks.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700415pub fn get_timestamp_service() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800416 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
417 if let Some(dev) = &*ts_device {
418 Ok(dev.clone())
419 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000420 let dev = connect_secureclock().context(ks_err!())?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800421 *ts_device = Some(dev.clone());
422 Ok(dev)
423 }
424}
Max Biresb2e1d032021-02-08 21:35:05 -0800425
Tri Voe8f04442022-12-21 08:53:56 -0800426/// Get the service name of a remotely provisioned component corresponding to given security level.
427pub fn get_remotely_provisioned_component_name(security_level: &SecurityLevel) -> Result<String> {
Shaquille Johnsondf83fb72023-03-24 12:26:52 +0000428 let remote_prov_descriptor: &str =
429 <BpRemotelyProvisionedComponent as IRemotelyProvisionedComponent>::get_descriptor();
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800430
Tri Voe8f04442022-12-21 08:53:56 -0800431 match *security_level {
Max Biresb2e1d032021-02-08 21:35:05 -0800432 SecurityLevel::TRUSTED_ENVIRONMENT => {
Karuna Wadhera9ae66c02024-05-16 19:40:59 +0000433 let instance = format!("{}/default", remote_prov_descriptor);
434 if is_declared(&instance)? {
435 Some(instance)
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800436 } else {
437 None
438 }
Max Biresb2e1d032021-02-08 21:35:05 -0800439 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800440 SecurityLevel::STRONGBOX => {
Karuna Wadhera9ae66c02024-05-16 19:40:59 +0000441 let instance = format!("{}/strongbox", remote_prov_descriptor);
442 if is_declared(&instance)? {
443 Some(instance)
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800444 } else {
445 None
446 }
Max Biresb2e1d032021-02-08 21:35:05 -0800447 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800448 _ => None,
449 }
450 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
Shaquille Johnson69c92a02024-02-28 22:14:05 +0000451 .context(ks_err!("Failed to get rpc for sec level {:?}", *security_level))
Tri Voe8f04442022-12-21 08:53:56 -0800452}