blob: 8212213eb20ae897d1a3c08f263bdf35ef279719 [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
Janis Danisevskis93927dd2020-12-23 12:23:08 -080019use crate::gc::Gc;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000020use crate::legacy_blob::LegacyBlobLoader;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000021use crate::legacy_migrator::LegacyMigrator;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080022use crate::super_key::SuperKeyManager;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070023use crate::utils::watchdog as wd;
Janis Danisevskisba998992020-12-29 16:08:40 -080024use crate::utils::Asp;
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};
Max Bires8e93d2b2021-01-14 13:17:59 -080031use crate::{enforcements::Enforcements, error::map_km_error};
32use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Max Biresb2e1d032021-02-08 21:35:05 -080033 IKeyMintDevice::IKeyMintDevice, IRemotelyProvisionedComponent::IRemotelyProvisionedComponent,
34 KeyMintHardwareInfo::KeyMintHardwareInfo, SecurityLevel::SecurityLevel,
Max Bires8e93d2b2021-01-14 13:17:59 -080035};
Stephen Crane221bbb52020-12-16 15:52:10 -080036use android_hardware_security_keymint::binder::{StatusCode, Strong};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080037use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080038use anyhow::{Context, Result};
David Drysdale0e45a612021-02-25 17:24:36 +000039use binder::FromIBinder;
Janis Danisevskisef14e1a2021-02-23 23:16:55 -080040use keystore2_vintf::get_aidl_instances;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080041use lazy_static::lazy_static;
Seth Moorea3e611a2021-05-11 10:07:45 -070042use std::sync::{Arc, Mutex, RwLock};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080043use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080044use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080045
46static DB_INIT: Once = Once::new();
47
48/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
49/// the thread local DB field. It should never be called directly. The first time this is called
50/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080051/// documentation of cleanup_leftovers for more details. The function also constructs a blob
52/// garbage collector. The initializing closure constructs another database connection without
53/// a gc. Although one GC is created for each thread local database connection, this closure
54/// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
55/// database connection is created for the garbage collector worker.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000056pub fn create_thread_local_db() -> KeystoreDB {
Seth Moore472fcbb2021-05-12 10:07:51 -070057 let db_path = DB_PATH.read().expect("Could not get the database directory.");
58
Seth Moore472fcbb2021-05-12 10:07:51 -070059 let mut db = KeystoreDB::new(&db_path, Some(GC.clone())).expect("Failed to open database.");
60
Janis Danisevskis93927dd2020-12-23 12:23:08 -080061 DB_INIT.call_once(|| {
62 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Matthew Maurerd7815ca2021-05-06 21:58:45 -070063 db.insert_last_off_body(MonotonicRawTime::now());
Janis Danisevskis93927dd2020-12-23 12:23:08 -080064 log::info!("Calling cleanup leftovers.");
65 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
66 if n != 0 {
67 log::info!(
68 concat!(
69 "Cleaned up {} failed entries. ",
70 "This indicates keystore crashed during key generation."
71 ),
72 n
73 );
74 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -080075 });
76 db
77}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070078
79thread_local! {
80 /// Database connections are not thread safe, but connecting to the
81 /// same database multiple times is safe as long as each connection is
82 /// used by only one thread. So we store one database connection per
83 /// thread in this thread local key.
84 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080085 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070086}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080087
Max Bires8e93d2b2021-01-14 13:17:59 -080088#[derive(Default)]
89struct DevicesMap {
90 devices_by_uuid: HashMap<Uuid, (Asp, KeyMintHardwareInfo)>,
91 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
92}
93
94impl DevicesMap {
95 fn dev_by_sec_level(
96 &self,
97 sec_level: &SecurityLevel,
98 ) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
99 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
100 }
101
102 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
103 self.devices_by_uuid
104 .get(uuid)
105 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
106 }
107
David Drysdale0e45a612021-02-25 17:24:36 +0000108 fn devices<T: FromIBinder + ?Sized>(&self) -> Vec<Strong<T>> {
109 self.devices_by_uuid.values().filter_map(|(asp, _)| asp.get_interface::<T>().ok()).collect()
110 }
111
Max Bires8e93d2b2021-01-14 13:17:59 -0800112 /// The requested security level and the security level of the actual implementation may
113 /// differ. So we map the requested security level to the uuid of the implementation
114 /// so that there cannot be any confusion as to which KeyMint instance is requested.
115 fn insert(&mut self, sec_level: SecurityLevel, dev: Asp, hw_info: KeyMintHardwareInfo) {
116 // For now we use the reported security level of the KM instance as UUID.
117 // TODO update this section once UUID was added to the KM hardware info.
118 let uuid: Uuid = sec_level.into();
119 self.devices_by_uuid.insert(uuid, (dev, hw_info));
120 self.uuid_by_sec_level.insert(sec_level, uuid);
121 }
122}
123
Max Biresb2e1d032021-02-08 21:35:05 -0800124#[derive(Default)]
125struct RemotelyProvisionedDevicesMap {
126 devices_by_sec_level: HashMap<SecurityLevel, Asp>,
127}
128
129impl RemotelyProvisionedDevicesMap {
130 fn dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Asp> {
131 self.devices_by_sec_level.get(sec_level).map(|dev| (*dev).clone())
132 }
133
134 fn insert(&mut self, sec_level: SecurityLevel, dev: Asp) {
135 self.devices_by_sec_level.insert(sec_level, dev);
136 }
137}
138
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800139lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800140 /// The path where keystore stores all its keys.
Seth Moorea3e611a2021-05-11 10:07:45 -0700141 pub static ref DB_PATH: RwLock<PathBuf> = RwLock::new(
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800142 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800143 /// Runtime database of unwrapped super keys.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800144 pub static ref SUPER_KEY: Arc<SuperKeyManager> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800145 /// Map of KeyMint devices.
Max Bires8e93d2b2021-01-14 13:17:59 -0800146 static ref KEY_MINT_DEVICES: Mutex<DevicesMap> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800147 /// Timestamp service.
148 static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default();
Max Biresb2e1d032021-02-08 21:35:05 -0800149 /// RemotelyProvisionedComponent HAL devices.
150 static ref REMOTELY_PROVISIONED_COMPONENT_DEVICES: Mutex<RemotelyProvisionedDevicesMap> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800151 /// A single on-demand worker thread that handles deferred tasks with two different
152 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800153 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800154 /// Singleton for enforcements.
Paul Crowley7c57bf12021-02-02 16:26:57 -0800155 pub static ref ENFORCEMENTS: Enforcements = Default::default();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000156 /// LegacyBlobLoader is initialized and exists globally.
157 /// The same directory used by the database is used by the LegacyBlobLoader as well.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000158 pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
Seth Moorea3e611a2021-05-11 10:07:45 -0700159 &DB_PATH.read().expect("Could not get the database path for legacy blob loader.")));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000160 /// Legacy migrator. Atomically migrates legacy blobs to the database.
161 pub static ref LEGACY_MIGRATOR: Arc<LegacyMigrator> =
Janis Danisevskisec6586d2021-04-30 10:54:07 -0700162 Arc::new(LegacyMigrator::new(Arc::new(Default::default())));
Pavel Grafov94243c22021-04-21 18:03:11 +0100163 /// Background thread which handles logging via statsd and logd
164 pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
Janis Danisevskis3395f862021-05-06 10:54:17 -0700165
166 static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
167 (
168 Box::new(|uuid, blob| {
169 let km_dev: Strong<dyn IKeyMintDevice> =
170 get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?.get_interface()?;
171 let _wp = wd::watch_millis("In invalidate key closure: calling deleteKey", 500);
172 map_km_error(km_dev.deleteKey(&*blob))
173 .context("In invalidate key closure: Trying to invalidate key blob.")
174 }),
Seth Moorea3e611a2021-05-11 10:07:45 -0700175 KeystoreDB::new(&DB_PATH.read().expect("Could not get the database directory."), None)
Janis Danisevskis3395f862021-05-06 10:54:17 -0700176 .expect("Failed to open database."),
177 SUPER_KEY.clone(),
178 )
179 }));
Janis Danisevskisba998992020-12-29 16:08:40 -0800180}
181
182static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
183
184/// Make a new connection to a KeyMint device of the given security level.
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800185/// If no native KeyMint device can be found this function also brings
186/// up the compatibility service and attempts to connect to the legacy wrapper.
Max Bires8e93d2b2021-01-14 13:17:59 -0800187fn connect_keymint(security_level: &SecurityLevel) -> Result<(Asp, KeyMintHardwareInfo)> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800188 let keymint_instances =
189 get_aidl_instances("android.hardware.security.keymint", 1, "IKeyMintDevice");
190
Max Bires8e93d2b2021-01-14 13:17:59 -0800191 let service_name = match *security_level {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800192 SecurityLevel::TRUSTED_ENVIRONMENT => {
193 if keymint_instances.as_vec()?.iter().any(|instance| *instance == "default") {
194 Some(format!("{}/default", KEYMINT_SERVICE_NAME))
195 } else {
196 None
197 }
198 }
199 SecurityLevel::STRONGBOX => {
200 if keymint_instances.as_vec()?.iter().any(|instance| *instance == "strongbox") {
201 Some(format!("{}/strongbox", KEYMINT_SERVICE_NAME))
202 } else {
203 None
204 }
205 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800206 _ => {
207 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
208 .context("In connect_keymint.")
209 }
210 };
211
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700212 let (keymint, hal_version) = if let Some(service_name) = service_name {
213 (
214 map_binder_status_code(binder::get_interface(&service_name))
215 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")?,
216 Some(100i32), // The HAL version code for KeyMint V1 is 100.
217 )
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800218 } else {
219 // This is a no-op if it was called before.
220 keystore2_km_compat::add_keymint_device_service();
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800221
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800222 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
223 map_binder_status_code(binder::get_interface("android.security.compat"))
224 .context("In connect_keymint: Trying to connect to compat service.")?;
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700225 (
226 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
227 .map_err(|e| match e {
228 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
229 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
230 }
231 e => e,
232 })
233 .context("In connect_keymint: Trying to get Legacy wrapper.")?,
234 None,
235 )
236 };
Janis Danisevskisba998992020-12-29 16:08:40 -0800237
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700238 let wp = wd::watch_millis("In connect_keymint: calling getHardwareInfo()", 500);
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700239 let mut hw_info = map_km_error(keymint.getHardwareInfo())
Max Bires8e93d2b2021-01-14 13:17:59 -0800240 .context("In connect_keymint: Failed to get hardware info.")?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700241 drop(wp);
Max Bires8e93d2b2021-01-14 13:17:59 -0800242
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700243 // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
244 // 10 * <major> + <minor>, e.g., KM 3.0 = 30. So 30, 40, and 41 are the only viable values.
245 // For KeyMint the versionNumber is implementation defined and thus completely meaningless
246 // to Keystore 2.0. So at this point the versionNumber field is set to the HAL version, so
247 // that higher levels have a meaningful guide as to which feature set to expect from the
248 // implementation. As of this writing the only meaningful version number is 100 for KeyMint V1,
249 // and future AIDL versions should follow the pattern <AIDL version> * 100.
250 if let Some(hal_version) = hal_version {
251 hw_info.versionNumber = hal_version;
252 }
253
Max Bires8e93d2b2021-01-14 13:17:59 -0800254 Ok((Asp::new(keymint.as_binder()), hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800255}
256
257/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800258/// by making a new connection. Returns the device, the hardware info and the uuid.
259/// TODO the latter can be removed when the uuid is part of the hardware info.
260pub fn get_keymint_device(
261 security_level: &SecurityLevel,
262) -> Result<(Asp, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800263 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Max Bires8e93d2b2021-01-14 13:17:59 -0800264 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(&security_level) {
265 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800266 } else {
Max Bires8e93d2b2021-01-14 13:17:59 -0800267 let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
268 devices_map.insert(*security_level, dev, hw_info);
269 // Unwrap must succeed because we just inserted it.
270 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
271 }
272}
273
274/// Get a keymint device for the given uuid. This will only access the cache, but will not
275/// attempt to establish a new connection. It is assumed that the cache is already populated
276/// when this is called. This is a fair assumption, because service.rs iterates through all
277/// security levels when it gets instantiated.
278pub fn get_keymint_dev_by_uuid(uuid: &Uuid) -> Result<(Asp, KeyMintHardwareInfo)> {
279 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
280 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
281 Ok((dev, hw_info))
282 } else {
283 Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
Janis Danisevskisba998992020-12-29 16:08:40 -0800284 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800285}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800286
David Drysdale0e45a612021-02-25 17:24:36 +0000287/// Return all known keymint devices.
288pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
289 KEY_MINT_DEVICES.lock().unwrap().devices()
290}
291
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800292static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
293
294/// Make a new connection to a secure clock service.
295/// If no native SecureClock device can be found brings up the compatibility service and attempts
296/// to connect to the legacy wrapper.
297fn connect_secureclock() -> Result<Asp> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800298 let secureclock_instances =
299 get_aidl_instances("android.hardware.security.secureclock", 1, "ISecureClock");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800300
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800301 let secure_clock_available =
302 secureclock_instances.as_vec()?.iter().any(|instance| *instance == "default");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800303
Max Bires130e51b2021-04-05 14:07:20 -0700304 let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
305
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800306 let secureclock = if secure_clock_available {
Max Bires130e51b2021-04-05 14:07:20 -0700307 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800308 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
309 } else {
310 // This is a no-op if it was called before.
311 keystore2_km_compat::add_keymint_device_service();
312
313 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
314 map_binder_status_code(binder::get_interface("android.security.compat"))
315 .context("In connect_secureclock: Trying to connect to compat service.")?;
316
317 // Legacy secure clock services were only implemented by TEE.
318 map_binder_status(keystore_compat_service.getSecureClock())
319 .map_err(|e| match e {
320 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
321 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800322 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800323 e => e,
324 })
325 .context("In connect_secureclock: Trying to get Legacy wrapper.")
326 }?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800327
328 Ok(Asp::new(secureclock.as_binder()))
329}
330
331/// Get the timestamp service that verifies auth token timeliness towards security levels with
332/// different clocks.
333pub fn get_timestamp_service() -> Result<Asp> {
334 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
335 if let Some(dev) = &*ts_device {
336 Ok(dev.clone())
337 } else {
338 let dev = connect_secureclock().context("In get_timestamp_service.")?;
339 *ts_device = Some(dev.clone());
340 Ok(dev)
341 }
342}
Max Biresb2e1d032021-02-08 21:35:05 -0800343
344static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
345 "android.hardware.security.keymint.IRemotelyProvisionedComponent";
346
347fn connect_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800348 let remotely_prov_instances =
349 get_aidl_instances("android.hardware.security.keymint", 1, "IRemotelyProvisionedComponent");
350
Max Biresb2e1d032021-02-08 21:35:05 -0800351 let service_name = match *security_level {
352 SecurityLevel::TRUSTED_ENVIRONMENT => {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800353 if remotely_prov_instances.as_vec()?.iter().any(|instance| *instance == "default") {
354 Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
355 } else {
356 None
357 }
Max Biresb2e1d032021-02-08 21:35:05 -0800358 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800359 SecurityLevel::STRONGBOX => {
360 if remotely_prov_instances.as_vec()?.iter().any(|instance| *instance == "strongbox") {
361 Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
362 } else {
363 None
364 }
Max Biresb2e1d032021-02-08 21:35:05 -0800365 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800366 _ => None,
367 }
368 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
369 .context("In connect_remotely_provisioned_component.")?;
Max Biresb2e1d032021-02-08 21:35:05 -0800370
371 let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> =
372 map_binder_status_code(binder::get_interface(&service_name))
373 .context(concat!(
374 "In connect_remotely_provisioned_component: Trying to connect to",
375 " RemotelyProvisionedComponent service."
376 ))
377 .map_err(|e| e)?;
378 Ok(Asp::new(rem_prov_hal.as_binder()))
379}
380
381/// Get a remote provisiong component device for the given security level either from the cache or
382/// by making a new connection. Returns the device.
383pub fn get_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp> {
384 let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap();
385 if let Some(dev) = devices_map.dev_by_sec_level(&security_level) {
386 Ok(dev)
387 } else {
388 let dev = connect_remotely_provisioned_component(security_level)
389 .context("In get_remotely_provisioned_component.")?;
390 devices_map.insert(*security_level, dev);
391 // Unwrap must succeed because we just inserted it.
392 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
393 }
394}