blob: b0af771d78e53b75b51fa376859f808ced95da6e [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 Danisevskis5ed8c532021-01-11 14:19:42 -080024use crate::{async_task::AsyncTask, database::MonotonicRawTime};
Janis Danisevskisba998992020-12-29 16:08:40 -080025use crate::{
26 database::KeystoreDB,
Max Bires8e93d2b2021-01-14 13:17:59 -080027 database::Uuid,
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080028 error::{map_binder_status, map_binder_status_code, Error, ErrorCode},
Janis Danisevskisba998992020-12-29 16:08:40 -080029};
Max Bires8e93d2b2021-01-14 13:17:59 -080030use crate::{enforcements::Enforcements, error::map_km_error};
31use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Max Biresb2e1d032021-02-08 21:35:05 -080032 IKeyMintDevice::IKeyMintDevice, IRemotelyProvisionedComponent::IRemotelyProvisionedComponent,
33 KeyMintHardwareInfo::KeyMintHardwareInfo, SecurityLevel::SecurityLevel,
Max Bires8e93d2b2021-01-14 13:17:59 -080034};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070035use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
36 ISecureClock::ISecureClock,
37};
Stephen Crane221bbb52020-12-16 15:52:10 -080038use android_hardware_security_keymint::binder::{StatusCode, Strong};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080039use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080040use anyhow::{Context, Result};
David Drysdale0e45a612021-02-25 17:24:36 +000041use binder::FromIBinder;
Janis Danisevskisef14e1a2021-02-23 23:16:55 -080042use keystore2_vintf::get_aidl_instances;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080043use lazy_static::lazy_static;
Seth Moorea3e611a2021-05-11 10:07:45 -070044use std::sync::{Arc, Mutex, RwLock};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080045use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080046use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080047
48static DB_INIT: Once = Once::new();
49
50/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
51/// the thread local DB field. It should never be called directly. The first time this is called
52/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080053/// documentation of cleanup_leftovers for more details. The function also constructs a blob
54/// garbage collector. The initializing closure constructs another database connection without
55/// a gc. Although one GC is created for each thread local database connection, this closure
56/// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
57/// database connection is created for the garbage collector worker.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000058pub fn create_thread_local_db() -> KeystoreDB {
Seth Moore472fcbb2021-05-12 10:07:51 -070059 let db_path = DB_PATH.read().expect("Could not get the database directory.");
60
Seth Moore472fcbb2021-05-12 10:07:51 -070061 let mut db = KeystoreDB::new(&db_path, Some(GC.clone())).expect("Failed to open database.");
62
Janis Danisevskis93927dd2020-12-23 12:23:08 -080063 DB_INIT.call_once(|| {
64 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Matthew Maurerd7815ca2021-05-06 21:58:45 -070065 db.insert_last_off_body(MonotonicRawTime::now());
Janis Danisevskis93927dd2020-12-23 12:23:08 -080066 log::info!("Calling cleanup leftovers.");
67 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
68 if n != 0 {
69 log::info!(
70 concat!(
71 "Cleaned up {} failed entries. ",
72 "This indicates keystore crashed during key generation."
73 ),
74 n
75 );
76 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -080077 });
78 db
79}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070080
81thread_local! {
82 /// Database connections are not thread safe, but connecting to the
83 /// same database multiple times is safe as long as each connection is
84 /// used by only one thread. So we store one database connection per
85 /// thread in this thread local key.
86 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080087 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070088}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080089
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070090struct DevicesMap<T: FromIBinder + ?Sized> {
91 devices_by_uuid: HashMap<Uuid, (Strong<T>, KeyMintHardwareInfo)>,
Max Bires8e93d2b2021-01-14 13:17:59 -080092 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
93}
94
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070095impl<T: FromIBinder + ?Sized> DevicesMap<T> {
Max Bires8e93d2b2021-01-14 13:17:59 -080096 fn dev_by_sec_level(
97 &self,
98 sec_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070099 ) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800100 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
101 }
102
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700103 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800104 self.devices_by_uuid
105 .get(uuid)
106 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
107 }
108
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700109 fn devices(&self) -> Vec<Strong<T>> {
110 self.devices_by_uuid.values().map(|(dev, _)| dev.clone()).collect()
David Drysdale0e45a612021-02-25 17:24:36 +0000111 }
112
Max Bires8e93d2b2021-01-14 13:17:59 -0800113 /// The requested security level and the security level of the actual implementation may
114 /// differ. So we map the requested security level to the uuid of the implementation
115 /// so that there cannot be any confusion as to which KeyMint instance is requested.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700116 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>, hw_info: KeyMintHardwareInfo) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800117 // For now we use the reported security level of the KM instance as UUID.
118 // TODO update this section once UUID was added to the KM hardware info.
119 let uuid: Uuid = sec_level.into();
120 self.devices_by_uuid.insert(uuid, (dev, hw_info));
121 self.uuid_by_sec_level.insert(sec_level, uuid);
122 }
123}
124
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700125impl<T: FromIBinder + ?Sized> Default for DevicesMap<T> {
126 fn default() -> Self {
127 Self {
128 devices_by_uuid: HashMap::<Uuid, (Strong<T>, KeyMintHardwareInfo)>::new(),
129 uuid_by_sec_level: Default::default(),
130 }
131 }
Max Biresb2e1d032021-02-08 21:35:05 -0800132}
133
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700134struct RemotelyProvisionedDevicesMap<T: FromIBinder + ?Sized> {
135 devices_by_sec_level: HashMap<SecurityLevel, Strong<T>>,
136}
137
138impl<T: FromIBinder + ?Sized> Default for RemotelyProvisionedDevicesMap<T> {
139 fn default() -> Self {
140 Self { devices_by_sec_level: HashMap::<SecurityLevel, Strong<T>>::new() }
141 }
142}
143
144impl<T: FromIBinder + ?Sized> RemotelyProvisionedDevicesMap<T> {
145 fn dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Strong<T>> {
Max Biresb2e1d032021-02-08 21:35:05 -0800146 self.devices_by_sec_level.get(sec_level).map(|dev| (*dev).clone())
147 }
148
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700149 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>) {
Max Biresb2e1d032021-02-08 21:35:05 -0800150 self.devices_by_sec_level.insert(sec_level, dev);
151 }
152}
153
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800154lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800155 /// The path where keystore stores all its keys.
Seth Moorea3e611a2021-05-11 10:07:45 -0700156 pub static ref DB_PATH: RwLock<PathBuf> = RwLock::new(
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800157 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800158 /// Runtime database of unwrapped super keys.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800159 pub static ref SUPER_KEY: Arc<SuperKeyManager> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800160 /// Map of KeyMint devices.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700161 static ref KEY_MINT_DEVICES: Mutex<DevicesMap<dyn IKeyMintDevice>> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800162 /// Timestamp service.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700163 static ref TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Default::default();
Max Biresb2e1d032021-02-08 21:35:05 -0800164 /// RemotelyProvisionedComponent HAL devices.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700165 static ref REMOTELY_PROVISIONED_COMPONENT_DEVICES:
166 Mutex<RemotelyProvisionedDevicesMap<dyn IRemotelyProvisionedComponent>> =
167 Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800168 /// A single on-demand worker thread that handles deferred tasks with two different
169 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800171 /// Singleton for enforcements.
Paul Crowley7c57bf12021-02-02 16:26:57 -0800172 pub static ref ENFORCEMENTS: Enforcements = Default::default();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000173 /// LegacyBlobLoader is initialized and exists globally.
174 /// The same directory used by the database is used by the LegacyBlobLoader as well.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000175 pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
Seth Moorea3e611a2021-05-11 10:07:45 -0700176 &DB_PATH.read().expect("Could not get the database path for legacy blob loader.")));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000177 /// Legacy migrator. Atomically migrates legacy blobs to the database.
178 pub static ref LEGACY_MIGRATOR: Arc<LegacyMigrator> =
Janis Danisevskisec6586d2021-04-30 10:54:07 -0700179 Arc::new(LegacyMigrator::new(Arc::new(Default::default())));
Pavel Grafov94243c22021-04-21 18:03:11 +0100180 /// Background thread which handles logging via statsd and logd
181 pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
Janis Danisevskis3395f862021-05-06 10:54:17 -0700182
183 static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
184 (
185 Box::new(|uuid, blob| {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700186 let km_dev = get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?;
Janis Danisevskis3395f862021-05-06 10:54:17 -0700187 let _wp = wd::watch_millis("In invalidate key closure: calling deleteKey", 500);
188 map_km_error(km_dev.deleteKey(&*blob))
189 .context("In invalidate key closure: Trying to invalidate key blob.")
190 }),
Seth Moorea3e611a2021-05-11 10:07:45 -0700191 KeystoreDB::new(&DB_PATH.read().expect("Could not get the database directory."), None)
Janis Danisevskis3395f862021-05-06 10:54:17 -0700192 .expect("Failed to open database."),
193 SUPER_KEY.clone(),
194 )
195 }));
Janis Danisevskisba998992020-12-29 16:08:40 -0800196}
197
198static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
199
200/// Make a new connection to a KeyMint device of the given security level.
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800201/// If no native KeyMint device can be found this function also brings
202/// up the compatibility service and attempts to connect to the legacy wrapper.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700203fn connect_keymint(
204 security_level: &SecurityLevel,
205) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800206 let keymint_instances =
207 get_aidl_instances("android.hardware.security.keymint", 1, "IKeyMintDevice");
208
Max Bires8e93d2b2021-01-14 13:17:59 -0800209 let service_name = match *security_level {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800210 SecurityLevel::TRUSTED_ENVIRONMENT => {
211 if keymint_instances.as_vec()?.iter().any(|instance| *instance == "default") {
212 Some(format!("{}/default", KEYMINT_SERVICE_NAME))
213 } else {
214 None
215 }
216 }
217 SecurityLevel::STRONGBOX => {
218 if keymint_instances.as_vec()?.iter().any(|instance| *instance == "strongbox") {
219 Some(format!("{}/strongbox", KEYMINT_SERVICE_NAME))
220 } else {
221 None
222 }
223 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800224 _ => {
225 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
226 .context("In connect_keymint.")
227 }
228 };
229
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700230 let (keymint, hal_version) = if let Some(service_name) = service_name {
231 (
232 map_binder_status_code(binder::get_interface(&service_name))
233 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")?,
234 Some(100i32), // The HAL version code for KeyMint V1 is 100.
235 )
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800236 } else {
237 // This is a no-op if it was called before.
238 keystore2_km_compat::add_keymint_device_service();
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800239
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800240 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
241 map_binder_status_code(binder::get_interface("android.security.compat"))
242 .context("In connect_keymint: Trying to connect to compat service.")?;
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700243 (
244 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
245 .map_err(|e| match e {
246 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
247 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
248 }
249 e => e,
250 })
251 .context("In connect_keymint: Trying to get Legacy wrapper.")?,
252 None,
253 )
254 };
Janis Danisevskisba998992020-12-29 16:08:40 -0800255
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700256 let wp = wd::watch_millis("In connect_keymint: calling getHardwareInfo()", 500);
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700257 let mut hw_info = map_km_error(keymint.getHardwareInfo())
Max Bires8e93d2b2021-01-14 13:17:59 -0800258 .context("In connect_keymint: Failed to get hardware info.")?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700259 drop(wp);
Max Bires8e93d2b2021-01-14 13:17:59 -0800260
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700261 // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
262 // 10 * <major> + <minor>, e.g., KM 3.0 = 30. So 30, 40, and 41 are the only viable values.
263 // For KeyMint the versionNumber is implementation defined and thus completely meaningless
264 // to Keystore 2.0. So at this point the versionNumber field is set to the HAL version, so
265 // that higher levels have a meaningful guide as to which feature set to expect from the
266 // implementation. As of this writing the only meaningful version number is 100 for KeyMint V1,
267 // and future AIDL versions should follow the pattern <AIDL version> * 100.
268 if let Some(hal_version) = hal_version {
269 hw_info.versionNumber = hal_version;
270 }
271
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700272 Ok((keymint, hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800273}
274
275/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800276/// by making a new connection. Returns the device, the hardware info and the uuid.
277/// TODO the latter can be removed when the uuid is part of the hardware info.
278pub fn get_keymint_device(
279 security_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700280) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800281 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Max Bires8e93d2b2021-01-14 13:17:59 -0800282 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(&security_level) {
283 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800284 } else {
Max Bires8e93d2b2021-01-14 13:17:59 -0800285 let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
286 devices_map.insert(*security_level, dev, hw_info);
287 // Unwrap must succeed because we just inserted it.
288 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
289 }
290}
291
292/// Get a keymint device for the given uuid. This will only access the cache, but will not
293/// attempt to establish a new connection. It is assumed that the cache is already populated
294/// when this is called. This is a fair assumption, because service.rs iterates through all
295/// security levels when it gets instantiated.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700296pub fn get_keymint_dev_by_uuid(
297 uuid: &Uuid,
298) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800299 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
300 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
301 Ok((dev, hw_info))
302 } else {
303 Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
Janis Danisevskisba998992020-12-29 16:08:40 -0800304 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800305}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800306
David Drysdale0e45a612021-02-25 17:24:36 +0000307/// Return all known keymint devices.
308pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
309 KEY_MINT_DEVICES.lock().unwrap().devices()
310}
311
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800312static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
313
314/// Make a new connection to a secure clock service.
315/// If no native SecureClock device can be found brings up the compatibility service and attempts
316/// to connect to the legacy wrapper.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700317fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800318 let secureclock_instances =
319 get_aidl_instances("android.hardware.security.secureclock", 1, "ISecureClock");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800320
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800321 let secure_clock_available =
322 secureclock_instances.as_vec()?.iter().any(|instance| *instance == "default");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800323
Max Bires130e51b2021-04-05 14:07:20 -0700324 let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
325
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800326 let secureclock = if secure_clock_available {
Max Bires130e51b2021-04-05 14:07:20 -0700327 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800328 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
329 } else {
330 // This is a no-op if it was called before.
331 keystore2_km_compat::add_keymint_device_service();
332
333 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
334 map_binder_status_code(binder::get_interface("android.security.compat"))
335 .context("In connect_secureclock: Trying to connect to compat service.")?;
336
337 // Legacy secure clock services were only implemented by TEE.
338 map_binder_status(keystore_compat_service.getSecureClock())
339 .map_err(|e| match e {
340 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
341 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800342 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800343 e => e,
344 })
345 .context("In connect_secureclock: Trying to get Legacy wrapper.")
346 }?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800347
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700348 Ok(secureclock)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800349}
350
351/// Get the timestamp service that verifies auth token timeliness towards security levels with
352/// different clocks.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700353pub fn get_timestamp_service() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800354 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
355 if let Some(dev) = &*ts_device {
356 Ok(dev.clone())
357 } else {
358 let dev = connect_secureclock().context("In get_timestamp_service.")?;
359 *ts_device = Some(dev.clone());
360 Ok(dev)
361 }
362}
Max Biresb2e1d032021-02-08 21:35:05 -0800363
364static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
365 "android.hardware.security.keymint.IRemotelyProvisionedComponent";
366
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700367fn connect_remotely_provisioned_component(
368 security_level: &SecurityLevel,
369) -> Result<Strong<dyn IRemotelyProvisionedComponent>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800370 let remotely_prov_instances =
371 get_aidl_instances("android.hardware.security.keymint", 1, "IRemotelyProvisionedComponent");
372
Max Biresb2e1d032021-02-08 21:35:05 -0800373 let service_name = match *security_level {
374 SecurityLevel::TRUSTED_ENVIRONMENT => {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800375 if remotely_prov_instances.as_vec()?.iter().any(|instance| *instance == "default") {
376 Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
377 } else {
378 None
379 }
Max Biresb2e1d032021-02-08 21:35:05 -0800380 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800381 SecurityLevel::STRONGBOX => {
382 if remotely_prov_instances.as_vec()?.iter().any(|instance| *instance == "strongbox") {
383 Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
384 } else {
385 None
386 }
Max Biresb2e1d032021-02-08 21:35:05 -0800387 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800388 _ => None,
389 }
390 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
391 .context("In connect_remotely_provisioned_component.")?;
Max Biresb2e1d032021-02-08 21:35:05 -0800392
393 let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> =
394 map_binder_status_code(binder::get_interface(&service_name))
395 .context(concat!(
396 "In connect_remotely_provisioned_component: Trying to connect to",
397 " RemotelyProvisionedComponent service."
398 ))
399 .map_err(|e| e)?;
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700400 Ok(rem_prov_hal)
Max Biresb2e1d032021-02-08 21:35:05 -0800401}
402
403/// Get a remote provisiong component device for the given security level either from the cache or
404/// by making a new connection. Returns the device.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700405pub fn get_remotely_provisioned_component(
406 security_level: &SecurityLevel,
407) -> Result<Strong<dyn IRemotelyProvisionedComponent>> {
Max Biresb2e1d032021-02-08 21:35:05 -0800408 let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap();
409 if let Some(dev) = devices_map.dev_by_sec_level(&security_level) {
410 Ok(dev)
411 } else {
412 let dev = connect_remotely_provisioned_component(security_level)
413 .context("In get_remotely_provisioned_component.")?;
414 devices_map.insert(*security_level, dev);
415 // Unwrap must succeed because we just inserted it.
416 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
417 }
418}