blob: 70b78bad55d744b338faf82fef701c1ebbba7c52 [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;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080021use crate::legacy_importer::LegacyImporter;
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};
David Drysdalec97eb9e2022-01-26 13:03:48 -080030use crate::km_compat::{KeyMintV1, BacklevelKeyMintWrapper};
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};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070036use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
37 ISecureClock::ISecureClock,
38};
Stephen Crane221bbb52020-12-16 15:52:10 -080039use android_hardware_security_keymint::binder::{StatusCode, Strong};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080040use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080041use anyhow::{Context, Result};
David Drysdale0e45a612021-02-25 17:24:36 +000042use binder::FromIBinder;
Janis Danisevskisef14e1a2021-02-23 23:16:55 -080043use keystore2_vintf::get_aidl_instances;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080044use lazy_static::lazy_static;
Seth Moorea3e611a2021-05-11 10:07:45 -070045use std::sync::{Arc, Mutex, RwLock};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080046use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080047use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080048
49static DB_INIT: Once = Once::new();
50
51/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
52/// the thread local DB field. It should never be called directly. The first time this is called
53/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054/// documentation of cleanup_leftovers for more details. The function also constructs a blob
55/// garbage collector. The initializing closure constructs another database connection without
56/// a gc. Although one GC is created for each thread local database connection, this closure
57/// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
58/// database connection is created for the garbage collector worker.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000059pub fn create_thread_local_db() -> KeystoreDB {
Seth Moore472fcbb2021-05-12 10:07:51 -070060 let db_path = DB_PATH.read().expect("Could not get the database directory.");
61
Seth Moore472fcbb2021-05-12 10:07:51 -070062 let mut db = KeystoreDB::new(&db_path, Some(GC.clone())).expect("Failed to open database.");
63
Janis Danisevskis93927dd2020-12-23 12:23:08 -080064 DB_INIT.call_once(|| {
65 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Matthew Maurerd7815ca2021-05-06 21:58:45 -070066 db.insert_last_off_body(MonotonicRawTime::now());
Janis Danisevskis93927dd2020-12-23 12:23:08 -080067 log::info!("Calling cleanup leftovers.");
68 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
69 if n != 0 {
70 log::info!(
71 concat!(
72 "Cleaned up {} failed entries. ",
73 "This indicates keystore crashed during key generation."
74 ),
75 n
76 );
77 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -080078 });
79 db
80}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070081
82thread_local! {
83 /// Database connections are not thread safe, but connecting to the
84 /// same database multiple times is safe as long as each connection is
85 /// used by only one thread. So we store one database connection per
86 /// thread in this thread local key.
87 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080088 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070089}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080090
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070091struct DevicesMap<T: FromIBinder + ?Sized> {
92 devices_by_uuid: HashMap<Uuid, (Strong<T>, KeyMintHardwareInfo)>,
Max Bires8e93d2b2021-01-14 13:17:59 -080093 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
94}
95
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070096impl<T: FromIBinder + ?Sized> DevicesMap<T> {
Max Bires8e93d2b2021-01-14 13:17:59 -080097 fn dev_by_sec_level(
98 &self,
99 sec_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700100 ) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800101 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
102 }
103
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700104 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800105 self.devices_by_uuid
106 .get(uuid)
107 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
108 }
109
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700110 fn devices(&self) -> Vec<Strong<T>> {
111 self.devices_by_uuid.values().map(|(dev, _)| dev.clone()).collect()
David Drysdale0e45a612021-02-25 17:24:36 +0000112 }
113
Max Bires8e93d2b2021-01-14 13:17:59 -0800114 /// The requested security level and the security level of the actual implementation may
115 /// differ. So we map the requested security level to the uuid of the implementation
116 /// so that there cannot be any confusion as to which KeyMint instance is requested.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700117 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>, hw_info: KeyMintHardwareInfo) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800118 // For now we use the reported security level of the KM instance as UUID.
119 // TODO update this section once UUID was added to the KM hardware info.
120 let uuid: Uuid = sec_level.into();
121 self.devices_by_uuid.insert(uuid, (dev, hw_info));
122 self.uuid_by_sec_level.insert(sec_level, uuid);
123 }
124}
125
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700126impl<T: FromIBinder + ?Sized> Default for DevicesMap<T> {
127 fn default() -> Self {
128 Self {
129 devices_by_uuid: HashMap::<Uuid, (Strong<T>, KeyMintHardwareInfo)>::new(),
130 uuid_by_sec_level: Default::default(),
131 }
132 }
Max Biresb2e1d032021-02-08 21:35:05 -0800133}
134
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700135struct RemotelyProvisionedDevicesMap<T: FromIBinder + ?Sized> {
136 devices_by_sec_level: HashMap<SecurityLevel, Strong<T>>,
137}
138
139impl<T: FromIBinder + ?Sized> Default for RemotelyProvisionedDevicesMap<T> {
140 fn default() -> Self {
141 Self { devices_by_sec_level: HashMap::<SecurityLevel, Strong<T>>::new() }
142 }
143}
144
145impl<T: FromIBinder + ?Sized> RemotelyProvisionedDevicesMap<T> {
146 fn dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Strong<T>> {
Max Biresb2e1d032021-02-08 21:35:05 -0800147 self.devices_by_sec_level.get(sec_level).map(|dev| (*dev).clone())
148 }
149
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700150 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>) {
Max Biresb2e1d032021-02-08 21:35:05 -0800151 self.devices_by_sec_level.insert(sec_level, dev);
152 }
153}
154
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800155lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800156 /// The path where keystore stores all its keys.
Seth Moorea3e611a2021-05-11 10:07:45 -0700157 pub static ref DB_PATH: RwLock<PathBuf> = RwLock::new(
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800158 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800159 /// Runtime database of unwrapped super keys.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800160 pub static ref SUPER_KEY: Arc<RwLock<SuperKeyManager>> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800161 /// Map of KeyMint devices.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700162 static ref KEY_MINT_DEVICES: Mutex<DevicesMap<dyn IKeyMintDevice>> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800163 /// Timestamp service.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700164 static ref TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Default::default();
Max Biresb2e1d032021-02-08 21:35:05 -0800165 /// RemotelyProvisionedComponent HAL devices.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700166 static ref REMOTELY_PROVISIONED_COMPONENT_DEVICES:
167 Mutex<RemotelyProvisionedDevicesMap<dyn IRemotelyProvisionedComponent>> =
168 Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800169 /// A single on-demand worker thread that handles deferred tasks with two different
170 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800171 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800172 /// Singleton for enforcements.
Paul Crowley7c57bf12021-02-02 16:26:57 -0800173 pub static ref ENFORCEMENTS: Enforcements = Default::default();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000174 /// LegacyBlobLoader is initialized and exists globally.
175 /// The same directory used by the database is used by the LegacyBlobLoader as well.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000176 pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
Seth Moorea3e611a2021-05-11 10:07:45 -0700177 &DB_PATH.read().expect("Could not get the database path for legacy blob loader.")));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000178 /// Legacy migrator. Atomically migrates legacy blobs to the database.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800179 pub static ref LEGACY_IMPORTER: Arc<LegacyImporter> =
180 Arc::new(LegacyImporter::new(Arc::new(Default::default())));
Pavel Grafov94243c22021-04-21 18:03:11 +0100181 /// Background thread which handles logging via statsd and logd
182 pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
Janis Danisevskis3395f862021-05-06 10:54:17 -0700183
184 static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
185 (
186 Box::new(|uuid, blob| {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700187 let km_dev = get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?;
Janis Danisevskis3395f862021-05-06 10:54:17 -0700188 let _wp = wd::watch_millis("In invalidate key closure: calling deleteKey", 500);
189 map_km_error(km_dev.deleteKey(&*blob))
190 .context("In invalidate key closure: Trying to invalidate key blob.")
191 }),
Seth Moorea3e611a2021-05-11 10:07:45 -0700192 KeystoreDB::new(&DB_PATH.read().expect("Could not get the database directory."), None)
Janis Danisevskis3395f862021-05-06 10:54:17 -0700193 .expect("Failed to open database."),
194 SUPER_KEY.clone(),
195 )
196 }));
Janis Danisevskisba998992020-12-29 16:08:40 -0800197}
198
199static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
200
David Drysdalec97eb9e2022-01-26 13:03:48 -0800201/// Determine the service name for a KeyMint device of the given security level
202/// which implements at least the specified version of the `IKeyMintDevice`
203/// interface.
204fn keymint_service_name_by_version(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700205 security_level: &SecurityLevel,
David Drysdalec97eb9e2022-01-26 13:03:48 -0800206 version: i32,
207) -> Result<Option<(i32, String)>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800208 let keymint_instances =
David Drysdalec97eb9e2022-01-26 13:03:48 -0800209 get_aidl_instances("android.hardware.security.keymint", version as usize, "IKeyMintDevice");
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800210
Max Bires8e93d2b2021-01-14 13:17:59 -0800211 let service_name = match *security_level {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800212 SecurityLevel::TRUSTED_ENVIRONMENT => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700213 if keymint_instances.iter().any(|instance| *instance == "default") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800214 Some(format!("{}/default", KEYMINT_SERVICE_NAME))
215 } else {
216 None
217 }
218 }
219 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700220 if keymint_instances.iter().any(|instance| *instance == "strongbox") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800221 Some(format!("{}/strongbox", KEYMINT_SERVICE_NAME))
222 } else {
223 None
224 }
225 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800226 _ => {
David Drysdalec97eb9e2022-01-26 13:03:48 -0800227 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(format!(
228 "In keymint_service_name_by_version: Trying to find keymint V{} for security level: {:?}",
229 version, security_level
230 ));
Janis Danisevskisba998992020-12-29 16:08:40 -0800231 }
232 };
233
David Drysdalec97eb9e2022-01-26 13:03:48 -0800234 Ok(service_name.map(|service_name| (version, service_name)))
235}
236
237/// Make a new connection to a KeyMint device of the given security level.
238/// If no native KeyMint device can be found this function also brings
239/// up the compatibility service and attempts to connect to the legacy wrapper.
240fn connect_keymint(
241 security_level: &SecurityLevel,
242) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
243 // Count down from the current interface version back to one in order to
244 // also find out the interface version -- an implementation of V2 will show
245 // up in the list of V1-capable devices, but not vice-versa.
246 let service_name = keymint_service_name_by_version(security_level, 2)
247 .and_then(|sl| {
248 if sl.is_none() {
249 keymint_service_name_by_version(security_level, 1)
250 } else {
251 Ok(sl)
252 }
253 })
254 .context("In connect_keymint.")?;
255
256 let (keymint, hal_version) = if let Some((version, service_name)) = service_name {
David Drysdalea6c82a92021-12-06 11:24:26 +0000257 let km: Strong<dyn IKeyMintDevice> =
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700258 map_binder_status_code(binder::get_interface(&service_name))
David Drysdalea6c82a92021-12-06 11:24:26 +0000259 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")?;
260 // Map the HAL version code for KeyMint to be <AIDL version> * 100, so
261 // - V1 is 100
262 // - V2 is 200
263 // etc.
David Drysdalec97eb9e2022-01-26 13:03:48 -0800264 (km, Some(version * 100))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800265 } else {
266 // This is a no-op if it was called before.
267 keystore2_km_compat::add_keymint_device_service();
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800268
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800269 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
270 map_binder_status_code(binder::get_interface("android.security.compat"))
271 .context("In connect_keymint: Trying to connect to compat service.")?;
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700272 (
273 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
274 .map_err(|e| match e {
275 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
276 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
277 }
278 e => e,
279 })
280 .context("In connect_keymint: Trying to get Legacy wrapper.")?,
281 None,
282 )
283 };
Janis Danisevskisba998992020-12-29 16:08:40 -0800284
David Drysdalec97eb9e2022-01-26 13:03:48 -0800285 // If the KeyMint device is back-level, use a wrapper that intercepts and
286 // emulates things that are not supported by the hardware.
287 let keymint = match hal_version {
288 Some(200) => {
289 // Current KeyMint version: use as-is.
290 log::info!(
291 "KeyMint device is current version ({:?}) for security level: {:?}",
292 hal_version,
293 security_level
294 );
295 keymint
296 }
297 Some(100) => {
298 // KeyMint v1: perform software emulation.
299 log::info!(
300 "Add emulation wrapper around {:?} device for security level: {:?}",
301 hal_version,
302 security_level
303 );
304 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
305 .context("In connect_keymint: Trying to create V1 compatibility wrapper.")?
306 }
307 None => {
308 // Compatibility wrapper around a KeyMaster device: this roughly
309 // behaves like KeyMint V1 (e.g. it includes AGREE_KEY support,
310 // albeit in software.)
311 log::info!(
312 "Add emulation wrapper around Keymaster device for security level: {:?}",
313 security_level
314 );
315 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint).context(
316 "In connect_keymint: Trying to create km_compat V1 compatibility wrapper .",
317 )?
318 }
319 _ => {
320 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(format!(
321 "In connect_keymint: unexpected hal_version {:?} for security level: {:?}",
322 hal_version, security_level
323 ))
324 }
325 };
326
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700327 let wp = wd::watch_millis("In connect_keymint: calling getHardwareInfo()", 500);
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700328 let mut hw_info = map_km_error(keymint.getHardwareInfo())
Max Bires8e93d2b2021-01-14 13:17:59 -0800329 .context("In connect_keymint: Failed to get hardware info.")?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700330 drop(wp);
Max Bires8e93d2b2021-01-14 13:17:59 -0800331
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700332 // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
333 // 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 +0000334 //
335 // For KeyMint the returned versionNumber is implementation defined and thus completely
336 // meaningless to Keystore 2.0. So set the versionNumber field that is returned to
337 // the rest of the code to be the <AIDL version> * 100, so KeyMint V1 is 100, KeyMint V2 is 200
338 // and so on.
339 //
340 // This ensures that versionNumber value across KeyMaster and KeyMint is monotonically
341 // increasing (and so comparisons like `versionNumber >= KEY_MINT_1` are valid).
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700342 if let Some(hal_version) = hal_version {
343 hw_info.versionNumber = hal_version;
344 }
345
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700346 Ok((keymint, hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800347}
348
349/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800350/// by making a new connection. Returns the device, the hardware info and the uuid.
351/// TODO the latter can be removed when the uuid is part of the hardware info.
352pub fn get_keymint_device(
353 security_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700354) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800355 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700356 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(security_level) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800357 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800358 } else {
Max Bires8e93d2b2021-01-14 13:17:59 -0800359 let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
360 devices_map.insert(*security_level, dev, hw_info);
361 // Unwrap must succeed because we just inserted it.
362 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
363 }
364}
365
366/// Get a keymint device for the given uuid. This will only access the cache, but will not
367/// attempt to establish a new connection. It is assumed that the cache is already populated
368/// when this is called. This is a fair assumption, because service.rs iterates through all
369/// security levels when it gets instantiated.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700370pub fn get_keymint_dev_by_uuid(
371 uuid: &Uuid,
372) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800373 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
374 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
375 Ok((dev, hw_info))
376 } else {
377 Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
Janis Danisevskisba998992020-12-29 16:08:40 -0800378 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800379}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800380
David Drysdale0e45a612021-02-25 17:24:36 +0000381/// Return all known keymint devices.
382pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
383 KEY_MINT_DEVICES.lock().unwrap().devices()
384}
385
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800386static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
387
388/// Make a new connection to a secure clock service.
389/// If no native SecureClock device can be found brings up the compatibility service and attempts
390/// to connect to the legacy wrapper.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700391fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800392 let secureclock_instances =
393 get_aidl_instances("android.hardware.security.secureclock", 1, "ISecureClock");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800394
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800395 let secure_clock_available =
Joel Galensonec7872a2021-07-02 14:37:10 -0700396 secureclock_instances.iter().any(|instance| *instance == "default");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800397
Max Bires130e51b2021-04-05 14:07:20 -0700398 let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
399
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800400 let secureclock = if secure_clock_available {
Max Bires130e51b2021-04-05 14:07:20 -0700401 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800402 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
403 } else {
404 // This is a no-op if it was called before.
405 keystore2_km_compat::add_keymint_device_service();
406
407 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
408 map_binder_status_code(binder::get_interface("android.security.compat"))
409 .context("In connect_secureclock: Trying to connect to compat service.")?;
410
411 // Legacy secure clock services were only implemented by TEE.
412 map_binder_status(keystore_compat_service.getSecureClock())
413 .map_err(|e| match e {
414 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
415 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800416 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800417 e => e,
418 })
419 .context("In connect_secureclock: Trying to get Legacy wrapper.")
420 }?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800421
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700422 Ok(secureclock)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800423}
424
425/// Get the timestamp service that verifies auth token timeliness towards security levels with
426/// different clocks.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700427pub fn get_timestamp_service() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800428 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
429 if let Some(dev) = &*ts_device {
430 Ok(dev.clone())
431 } else {
432 let dev = connect_secureclock().context("In get_timestamp_service.")?;
433 *ts_device = Some(dev.clone());
434 Ok(dev)
435 }
436}
Max Biresb2e1d032021-02-08 21:35:05 -0800437
438static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
439 "android.hardware.security.keymint.IRemotelyProvisionedComponent";
440
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700441fn connect_remotely_provisioned_component(
442 security_level: &SecurityLevel,
443) -> Result<Strong<dyn IRemotelyProvisionedComponent>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800444 let remotely_prov_instances =
445 get_aidl_instances("android.hardware.security.keymint", 1, "IRemotelyProvisionedComponent");
446
Max Biresb2e1d032021-02-08 21:35:05 -0800447 let service_name = match *security_level {
448 SecurityLevel::TRUSTED_ENVIRONMENT => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700449 if remotely_prov_instances.iter().any(|instance| *instance == "default") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800450 Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
451 } else {
452 None
453 }
Max Biresb2e1d032021-02-08 21:35:05 -0800454 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800455 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700456 if remotely_prov_instances.iter().any(|instance| *instance == "strongbox") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800457 Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
458 } else {
459 None
460 }
Max Biresb2e1d032021-02-08 21:35:05 -0800461 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800462 _ => None,
463 }
464 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
465 .context("In connect_remotely_provisioned_component.")?;
Max Biresb2e1d032021-02-08 21:35:05 -0800466
467 let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> =
Chariseeb48992e2022-06-24 23:15:30 +0000468 map_binder_status_code(binder::get_interface(&service_name)).context(concat!(
469 "In connect_remotely_provisioned_component: Trying to connect to",
470 " RemotelyProvisionedComponent service."
471 ))?;
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700472 Ok(rem_prov_hal)
Max Biresb2e1d032021-02-08 21:35:05 -0800473}
474
475/// Get a remote provisiong component device for the given security level either from the cache or
476/// by making a new connection. Returns the device.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700477pub fn get_remotely_provisioned_component(
478 security_level: &SecurityLevel,
479) -> Result<Strong<dyn IRemotelyProvisionedComponent>> {
Max Biresb2e1d032021-02-08 21:35:05 -0800480 let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap();
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700481 if let Some(dev) = devices_map.dev_by_sec_level(security_level) {
Max Biresb2e1d032021-02-08 21:35:05 -0800482 Ok(dev)
483 } else {
484 let dev = connect_remotely_provisioned_component(security_level)
485 .context("In get_remotely_provisioned_component.")?;
486 devices_map.insert(*security_level, dev);
487 // Unwrap must succeed because we just inserted it.
488 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
489 }
490}