blob: 7028aae95f43204161d5ff0cfc16beea4f5e2ede [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 => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700211 if keymint_instances.iter().any(|instance| *instance == "default") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800212 Some(format!("{}/default", KEYMINT_SERVICE_NAME))
213 } else {
214 None
215 }
216 }
217 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700218 if keymint_instances.iter().any(|instance| *instance == "strongbox") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800219 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 {
David Drysdalea6c82a92021-12-06 11:24:26 +0000231 let km: Strong<dyn IKeyMintDevice> =
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700232 map_binder_status_code(binder::get_interface(&service_name))
David Drysdalea6c82a92021-12-06 11:24:26 +0000233 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")?;
234 // Map the HAL version code for KeyMint to be <AIDL version> * 100, so
235 // - V1 is 100
236 // - V2 is 200
237 // etc.
238 let hal_version = km
239 .getInterfaceVersion()
240 .map(|v| v * 100i32)
241 .context("In connect_keymint: Trying to determine KeyMint AIDL version")?;
242 (km, Some(hal_version))
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"))
249 .context("In connect_keymint: 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 })
258 .context("In connect_keymint: Trying to get Legacy wrapper.")?,
259 None,
260 )
261 };
Janis Danisevskisba998992020-12-29 16:08:40 -0800262
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700263 let wp = wd::watch_millis("In connect_keymint: calling getHardwareInfo()", 500);
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700264 let mut hw_info = map_km_error(keymint.getHardwareInfo())
Max Bires8e93d2b2021-01-14 13:17:59 -0800265 .context("In connect_keymint: Failed to get hardware info.")?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700266 drop(wp);
Max Bires8e93d2b2021-01-14 13:17:59 -0800267
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700268 // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
269 // 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 +0000270 //
271 // For KeyMint the returned versionNumber is implementation defined and thus completely
272 // meaningless to Keystore 2.0. So set the versionNumber field that is returned to
273 // the rest of the code to be the <AIDL version> * 100, so KeyMint V1 is 100, KeyMint V2 is 200
274 // and so on.
275 //
276 // This ensures that versionNumber value across KeyMaster and KeyMint is monotonically
277 // increasing (and so comparisons like `versionNumber >= KEY_MINT_1` are valid).
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700278 if let Some(hal_version) = hal_version {
279 hw_info.versionNumber = hal_version;
280 }
281
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700282 Ok((keymint, hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800283}
284
285/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800286/// by making a new connection. Returns the device, the hardware info and the uuid.
287/// TODO the latter can be removed when the uuid is part of the hardware info.
288pub fn get_keymint_device(
289 security_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700290) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800291 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700292 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(security_level) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800293 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800294 } else {
Max Bires8e93d2b2021-01-14 13:17:59 -0800295 let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
296 devices_map.insert(*security_level, dev, hw_info);
297 // Unwrap must succeed because we just inserted it.
298 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
299 }
300}
301
302/// Get a keymint device for the given uuid. This will only access the cache, but will not
303/// attempt to establish a new connection. It is assumed that the cache is already populated
304/// when this is called. This is a fair assumption, because service.rs iterates through all
305/// security levels when it gets instantiated.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700306pub fn get_keymint_dev_by_uuid(
307 uuid: &Uuid,
308) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800309 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
310 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
311 Ok((dev, hw_info))
312 } else {
313 Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
Janis Danisevskisba998992020-12-29 16:08:40 -0800314 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800315}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800316
David Drysdale0e45a612021-02-25 17:24:36 +0000317/// Return all known keymint devices.
318pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
319 KEY_MINT_DEVICES.lock().unwrap().devices()
320}
321
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800322static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
323
324/// Make a new connection to a secure clock service.
325/// If no native SecureClock device can be found brings up the compatibility service and attempts
326/// to connect to the legacy wrapper.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700327fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800328 let secureclock_instances =
329 get_aidl_instances("android.hardware.security.secureclock", 1, "ISecureClock");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800330
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800331 let secure_clock_available =
Joel Galensonec7872a2021-07-02 14:37:10 -0700332 secureclock_instances.iter().any(|instance| *instance == "default");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800333
Max Bires130e51b2021-04-05 14:07:20 -0700334 let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
335
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800336 let secureclock = if secure_clock_available {
Max Bires130e51b2021-04-05 14:07:20 -0700337 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800338 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
339 } else {
340 // This is a no-op if it was called before.
341 keystore2_km_compat::add_keymint_device_service();
342
343 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
344 map_binder_status_code(binder::get_interface("android.security.compat"))
345 .context("In connect_secureclock: Trying to connect to compat service.")?;
346
347 // Legacy secure clock services were only implemented by TEE.
348 map_binder_status(keystore_compat_service.getSecureClock())
349 .map_err(|e| match e {
350 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
351 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800352 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800353 e => e,
354 })
355 .context("In connect_secureclock: Trying to get Legacy wrapper.")
356 }?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800357
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700358 Ok(secureclock)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800359}
360
361/// Get the timestamp service that verifies auth token timeliness towards security levels with
362/// different clocks.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700363pub fn get_timestamp_service() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800364 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
365 if let Some(dev) = &*ts_device {
366 Ok(dev.clone())
367 } else {
368 let dev = connect_secureclock().context("In get_timestamp_service.")?;
369 *ts_device = Some(dev.clone());
370 Ok(dev)
371 }
372}
Max Biresb2e1d032021-02-08 21:35:05 -0800373
374static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
375 "android.hardware.security.keymint.IRemotelyProvisionedComponent";
376
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700377fn connect_remotely_provisioned_component(
378 security_level: &SecurityLevel,
379) -> Result<Strong<dyn IRemotelyProvisionedComponent>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800380 let remotely_prov_instances =
381 get_aidl_instances("android.hardware.security.keymint", 1, "IRemotelyProvisionedComponent");
382
Max Biresb2e1d032021-02-08 21:35:05 -0800383 let service_name = match *security_level {
384 SecurityLevel::TRUSTED_ENVIRONMENT => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700385 if remotely_prov_instances.iter().any(|instance| *instance == "default") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800386 Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
387 } else {
388 None
389 }
Max Biresb2e1d032021-02-08 21:35:05 -0800390 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800391 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700392 if remotely_prov_instances.iter().any(|instance| *instance == "strongbox") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800393 Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
394 } else {
395 None
396 }
Max Biresb2e1d032021-02-08 21:35:05 -0800397 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800398 _ => None,
399 }
400 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
401 .context("In connect_remotely_provisioned_component.")?;
Max Biresb2e1d032021-02-08 21:35:05 -0800402
403 let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> =
404 map_binder_status_code(binder::get_interface(&service_name))
405 .context(concat!(
406 "In connect_remotely_provisioned_component: Trying to connect to",
407 " RemotelyProvisionedComponent service."
408 ))
409 .map_err(|e| e)?;
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700410 Ok(rem_prov_hal)
Max Biresb2e1d032021-02-08 21:35:05 -0800411}
412
413/// Get a remote provisiong component device for the given security level either from the cache or
414/// by making a new connection. Returns the device.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700415pub fn get_remotely_provisioned_component(
416 security_level: &SecurityLevel,
417) -> Result<Strong<dyn IRemotelyProvisionedComponent>> {
Max Biresb2e1d032021-02-08 21:35:05 -0800418 let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap();
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700419 if let Some(dev) = devices_map.dev_by_sec_level(security_level) {
Max Biresb2e1d032021-02-08 21:35:05 -0800420 Ok(dev)
421 } else {
422 let dev = connect_remotely_provisioned_component(security_level)
423 .context("In get_remotely_provisioned_component.")?;
424 devices_map.insert(*security_level, dev);
425 // Unwrap must succeed because we just inserted it.
426 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
427 }
428}