blob: ed5957848b9110c23ea64adde04a7b210136dd3e [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
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000019use crate::ks_err;
Janis Danisevskis93927dd2020-12-23 12:23:08 -080020use crate::gc::Gc;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000021use crate::legacy_blob::LegacyBlobLoader;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080022use crate::legacy_importer::LegacyImporter;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080023use crate::super_key::SuperKeyManager;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070024use crate::utils::watchdog as wd;
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};
David Drysdalec97eb9e2022-01-26 13:03:48 -080031use crate::km_compat::{KeyMintV1, BacklevelKeyMintWrapper};
Max Bires8e93d2b2021-01-14 13:17:59 -080032use crate::{enforcements::Enforcements, error::map_km_error};
33use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Seth Moorecd6e9182022-11-04 17:39:05 +000034 IKeyMintDevice::IKeyMintDevice, KeyMintHardwareInfo::KeyMintHardwareInfo,
35 SecurityLevel::SecurityLevel,
Max Bires8e93d2b2021-01-14 13:17:59 -080036};
Seth Moorecd6e9182022-11-04 17:39:05 +000037use android_hardware_security_rkp::aidl::android::hardware::security::keymint::IRemotelyProvisionedComponent::IRemotelyProvisionedComponent;
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070038use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
39 ISecureClock::ISecureClock,
40};
Stephen Crane221bbb52020-12-16 15:52:10 -080041use android_hardware_security_keymint::binder::{StatusCode, Strong};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080042use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080043use anyhow::{Context, Result};
David Drysdale0e45a612021-02-25 17:24:36 +000044use binder::FromIBinder;
Janis Danisevskisef14e1a2021-02-23 23:16:55 -080045use keystore2_vintf::get_aidl_instances;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046use lazy_static::lazy_static;
Seth Moorea3e611a2021-05-11 10:07:45 -070047use std::sync::{Arc, Mutex, RwLock};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080048use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080049use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080050
51static DB_INIT: Once = Once::new();
52
53/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
54/// the thread local DB field. It should never be called directly. The first time this is called
55/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080056/// documentation of cleanup_leftovers for more details. The function also constructs a blob
57/// garbage collector. The initializing closure constructs another database connection without
58/// a gc. Although one GC is created for each thread local database connection, this closure
59/// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
60/// database connection is created for the garbage collector worker.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000061pub fn create_thread_local_db() -> KeystoreDB {
Seth Moore472fcbb2021-05-12 10:07:51 -070062 let db_path = DB_PATH.read().expect("Could not get the database directory.");
63
Seth Moore472fcbb2021-05-12 10:07:51 -070064 let mut db = KeystoreDB::new(&db_path, Some(GC.clone())).expect("Failed to open database.");
65
Janis Danisevskis93927dd2020-12-23 12:23:08 -080066 DB_INIT.call_once(|| {
67 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Matthew Maurerd7815ca2021-05-06 21:58:45 -070068 db.insert_last_off_body(MonotonicRawTime::now());
Janis Danisevskis93927dd2020-12-23 12:23:08 -080069 log::info!("Calling cleanup leftovers.");
70 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
71 if n != 0 {
72 log::info!(
73 concat!(
74 "Cleaned up {} failed entries. ",
75 "This indicates keystore crashed during key generation."
76 ),
77 n
78 );
79 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -080080 });
81 db
82}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070083
84thread_local! {
85 /// Database connections are not thread safe, but connecting to the
86 /// same database multiple times is safe as long as each connection is
87 /// used by only one thread. So we store one database connection per
88 /// thread in this thread local key.
89 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080090 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070091}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070093struct DevicesMap<T: FromIBinder + ?Sized> {
94 devices_by_uuid: HashMap<Uuid, (Strong<T>, KeyMintHardwareInfo)>,
Max Bires8e93d2b2021-01-14 13:17:59 -080095 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
96}
97
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070098impl<T: FromIBinder + ?Sized> DevicesMap<T> {
Max Bires8e93d2b2021-01-14 13:17:59 -080099 fn dev_by_sec_level(
100 &self,
101 sec_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700102 ) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800103 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
104 }
105
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700106 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800107 self.devices_by_uuid
108 .get(uuid)
109 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
110 }
111
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700112 fn devices(&self) -> Vec<Strong<T>> {
113 self.devices_by_uuid.values().map(|(dev, _)| dev.clone()).collect()
David Drysdale0e45a612021-02-25 17:24:36 +0000114 }
115
Max Bires8e93d2b2021-01-14 13:17:59 -0800116 /// The requested security level and the security level of the actual implementation may
117 /// differ. So we map the requested security level to the uuid of the implementation
118 /// so that there cannot be any confusion as to which KeyMint instance is requested.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700119 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>, hw_info: KeyMintHardwareInfo) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800120 // For now we use the reported security level of the KM instance as UUID.
121 // TODO update this section once UUID was added to the KM hardware info.
122 let uuid: Uuid = sec_level.into();
123 self.devices_by_uuid.insert(uuid, (dev, hw_info));
124 self.uuid_by_sec_level.insert(sec_level, uuid);
125 }
126}
127
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700128impl<T: FromIBinder + ?Sized> Default for DevicesMap<T> {
129 fn default() -> Self {
130 Self {
131 devices_by_uuid: HashMap::<Uuid, (Strong<T>, KeyMintHardwareInfo)>::new(),
132 uuid_by_sec_level: Default::default(),
133 }
134 }
Max Biresb2e1d032021-02-08 21:35:05 -0800135}
136
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700137struct RemotelyProvisionedDevicesMap<T: FromIBinder + ?Sized> {
138 devices_by_sec_level: HashMap<SecurityLevel, Strong<T>>,
139}
140
141impl<T: FromIBinder + ?Sized> Default for RemotelyProvisionedDevicesMap<T> {
142 fn default() -> Self {
143 Self { devices_by_sec_level: HashMap::<SecurityLevel, Strong<T>>::new() }
144 }
145}
146
147impl<T: FromIBinder + ?Sized> RemotelyProvisionedDevicesMap<T> {
148 fn dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Strong<T>> {
Max Biresb2e1d032021-02-08 21:35:05 -0800149 self.devices_by_sec_level.get(sec_level).map(|dev| (*dev).clone())
150 }
151
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700152 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>) {
Max Biresb2e1d032021-02-08 21:35:05 -0800153 self.devices_by_sec_level.insert(sec_level, dev);
154 }
155}
156
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800157lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800158 /// The path where keystore stores all its keys.
Seth Moorea3e611a2021-05-11 10:07:45 -0700159 pub static ref DB_PATH: RwLock<PathBuf> = RwLock::new(
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800160 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800161 /// Runtime database of unwrapped super keys.
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800162 pub static ref SUPER_KEY: Arc<RwLock<SuperKeyManager>> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800163 /// Map of KeyMint devices.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700164 static ref KEY_MINT_DEVICES: Mutex<DevicesMap<dyn IKeyMintDevice>> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800165 /// Timestamp service.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700166 static ref TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Default::default();
Max Biresb2e1d032021-02-08 21:35:05 -0800167 /// RemotelyProvisionedComponent HAL devices.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700168 static ref REMOTELY_PROVISIONED_COMPONENT_DEVICES:
169 Mutex<RemotelyProvisionedDevicesMap<dyn IRemotelyProvisionedComponent>> =
170 Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800171 /// A single on-demand worker thread that handles deferred tasks with two different
172 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800173 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800174 /// Singleton for enforcements.
Paul Crowley7c57bf12021-02-02 16:26:57 -0800175 pub static ref ENFORCEMENTS: Enforcements = Default::default();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000176 /// LegacyBlobLoader is initialized and exists globally.
177 /// The same directory used by the database is used by the LegacyBlobLoader as well.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000178 pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
Seth Moorea3e611a2021-05-11 10:07:45 -0700179 &DB_PATH.read().expect("Could not get the database path for legacy blob loader.")));
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000180 /// Legacy migrator. Atomically migrates legacy blobs to the database.
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800181 pub static ref LEGACY_IMPORTER: Arc<LegacyImporter> =
182 Arc::new(LegacyImporter::new(Arc::new(Default::default())));
Pavel Grafov94243c22021-04-21 18:03:11 +0100183 /// Background thread which handles logging via statsd and logd
184 pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
Janis Danisevskis3395f862021-05-06 10:54:17 -0700185
186 static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
187 (
188 Box::new(|uuid, blob| {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700189 let km_dev = get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?;
Janis Danisevskis3395f862021-05-06 10:54:17 -0700190 let _wp = wd::watch_millis("In invalidate key closure: calling deleteKey", 500);
Chris Wailes263de9f2022-08-11 15:00:51 -0700191 map_km_error(km_dev.deleteKey(blob))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000192 .context(ks_err!("Trying to invalidate key blob."))
Janis Danisevskis3395f862021-05-06 10:54:17 -0700193 }),
Seth Moorea3e611a2021-05-11 10:07:45 -0700194 KeystoreDB::new(&DB_PATH.read().expect("Could not get the database directory."), None)
Janis Danisevskis3395f862021-05-06 10:54:17 -0700195 .expect("Failed to open database."),
196 SUPER_KEY.clone(),
197 )
198 }));
Janis Danisevskisba998992020-12-29 16:08:40 -0800199}
200
201static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
202
David Drysdalec97eb9e2022-01-26 13:03:48 -0800203/// Determine the service name for a KeyMint device of the given security level
204/// which implements at least the specified version of the `IKeyMintDevice`
205/// interface.
206fn keymint_service_name_by_version(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700207 security_level: &SecurityLevel,
David Drysdalec97eb9e2022-01-26 13:03:48 -0800208 version: i32,
209) -> Result<Option<(i32, String)>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800210 let keymint_instances =
David Drysdalec97eb9e2022-01-26 13:03:48 -0800211 get_aidl_instances("android.hardware.security.keymint", version as usize, "IKeyMintDevice");
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800212
Max Bires8e93d2b2021-01-14 13:17:59 -0800213 let service_name = match *security_level {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800214 SecurityLevel::TRUSTED_ENVIRONMENT => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700215 if keymint_instances.iter().any(|instance| *instance == "default") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800216 Some(format!("{}/default", KEYMINT_SERVICE_NAME))
217 } else {
218 None
219 }
220 }
221 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700222 if keymint_instances.iter().any(|instance| *instance == "strongbox") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800223 Some(format!("{}/strongbox", KEYMINT_SERVICE_NAME))
224 } else {
225 None
226 }
227 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800228 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000229 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!(
230 "Trying to find keymint V{} for security level: {:?}",
231 version,
232 security_level
David Drysdalec97eb9e2022-01-26 13:03:48 -0800233 ));
Janis Danisevskisba998992020-12-29 16:08:40 -0800234 }
235 };
236
David Drysdalec97eb9e2022-01-26 13:03:48 -0800237 Ok(service_name.map(|service_name| (version, service_name)))
238}
239
240/// Make a new connection to a KeyMint device of the given security level.
241/// If no native KeyMint device can be found this function also brings
242/// up the compatibility service and attempts to connect to the legacy wrapper.
243fn connect_keymint(
244 security_level: &SecurityLevel,
245) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
246 // Count down from the current interface version back to one in order to
247 // also find out the interface version -- an implementation of V2 will show
248 // up in the list of V1-capable devices, but not vice-versa.
249 let service_name = keymint_service_name_by_version(security_level, 2)
250 .and_then(|sl| {
251 if sl.is_none() {
252 keymint_service_name_by_version(security_level, 1)
253 } else {
254 Ok(sl)
255 }
256 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000257 .context(ks_err!())?;
David Drysdalec97eb9e2022-01-26 13:03:48 -0800258
259 let (keymint, hal_version) = if let Some((version, service_name)) = service_name {
David Drysdalea6c82a92021-12-06 11:24:26 +0000260 let km: Strong<dyn IKeyMintDevice> =
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700261 map_binder_status_code(binder::get_interface(&service_name))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000262 .context(ks_err!("Trying to connect to genuine KeyMint service."))?;
David Drysdalea6c82a92021-12-06 11:24:26 +0000263 // Map the HAL version code for KeyMint to be <AIDL version> * 100, so
264 // - V1 is 100
265 // - V2 is 200
266 // etc.
David Drysdalec97eb9e2022-01-26 13:03:48 -0800267 (km, Some(version * 100))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800268 } else {
269 // This is a no-op if it was called before.
270 keystore2_km_compat::add_keymint_device_service();
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800271
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800272 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
273 map_binder_status_code(binder::get_interface("android.security.compat"))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000274 .context(ks_err!("Trying to connect to compat service."))?;
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700275 (
276 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
277 .map_err(|e| match e {
278 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
279 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
280 }
281 e => e,
282 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000283 .context(ks_err!("Trying to get Legacy wrapper."))?,
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700284 None,
285 )
286 };
Janis Danisevskisba998992020-12-29 16:08:40 -0800287
David Drysdalec97eb9e2022-01-26 13:03:48 -0800288 // If the KeyMint device is back-level, use a wrapper that intercepts and
289 // emulates things that are not supported by the hardware.
290 let keymint = match hal_version {
291 Some(200) => {
292 // Current KeyMint version: use as-is.
293 log::info!(
294 "KeyMint device is current version ({:?}) for security level: {:?}",
295 hal_version,
296 security_level
297 );
298 keymint
299 }
300 Some(100) => {
301 // KeyMint v1: perform software emulation.
302 log::info!(
303 "Add emulation wrapper around {:?} device for security level: {:?}",
304 hal_version,
305 security_level
306 );
307 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000308 .context(ks_err!("Trying to create V1 compatibility wrapper."))?
David Drysdalec97eb9e2022-01-26 13:03:48 -0800309 }
310 None => {
311 // Compatibility wrapper around a KeyMaster device: this roughly
312 // behaves like KeyMint V1 (e.g. it includes AGREE_KEY support,
313 // albeit in software.)
314 log::info!(
315 "Add emulation wrapper around Keymaster device for security level: {:?}",
316 security_level
317 );
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000318 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
319 .context(ks_err!("Trying to create km_compat V1 compatibility wrapper ."))?
David Drysdalec97eb9e2022-01-26 13:03:48 -0800320 }
321 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000322 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!(
323 "unexpected hal_version {:?} for security level: {:?}",
324 hal_version,
325 security_level
326 ));
David Drysdalec97eb9e2022-01-26 13:03:48 -0800327 }
328 };
329
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700330 let wp = wd::watch_millis("In connect_keymint: calling getHardwareInfo()", 500);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000331 let mut hw_info =
332 map_km_error(keymint.getHardwareInfo()).context(ks_err!("Failed to get hardware info."))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700333 drop(wp);
Max Bires8e93d2b2021-01-14 13:17:59 -0800334
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700335 // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
336 // 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 +0000337 //
338 // For KeyMint the returned versionNumber is implementation defined and thus completely
339 // meaningless to Keystore 2.0. So set the versionNumber field that is returned to
340 // the rest of the code to be the <AIDL version> * 100, so KeyMint V1 is 100, KeyMint V2 is 200
341 // and so on.
342 //
343 // This ensures that versionNumber value across KeyMaster and KeyMint is monotonically
344 // increasing (and so comparisons like `versionNumber >= KEY_MINT_1` are valid).
Janis Danisevskisbf855c02021-06-03 13:05:29 -0700345 if let Some(hal_version) = hal_version {
346 hw_info.versionNumber = hal_version;
347 }
348
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700349 Ok((keymint, hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800350}
351
352/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800353/// by making a new connection. Returns the device, the hardware info and the uuid.
354/// TODO the latter can be removed when the uuid is part of the hardware info.
355pub fn get_keymint_device(
356 security_level: &SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700357) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800358 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700359 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(security_level) {
Max Bires8e93d2b2021-01-14 13:17:59 -0800360 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800361 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000362 let (dev, hw_info) = connect_keymint(security_level).context(ks_err!())?;
Max Bires8e93d2b2021-01-14 13:17:59 -0800363 devices_map.insert(*security_level, dev, hw_info);
364 // Unwrap must succeed because we just inserted it.
365 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
366 }
367}
368
369/// Get a keymint device for the given uuid. This will only access the cache, but will not
370/// attempt to establish a new connection. It is assumed that the cache is already populated
371/// when this is called. This is a fair assumption, because service.rs iterates through all
372/// security levels when it gets instantiated.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700373pub fn get_keymint_dev_by_uuid(
374 uuid: &Uuid,
375) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800376 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
377 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
378 Ok((dev, hw_info))
379 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000380 Err(Error::sys()).context(ks_err!("No KeyMint instance found."))
Janis Danisevskisba998992020-12-29 16:08:40 -0800381 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800382}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800383
David Drysdale0e45a612021-02-25 17:24:36 +0000384/// Return all known keymint devices.
385pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
386 KEY_MINT_DEVICES.lock().unwrap().devices()
387}
388
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800389static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
390
391/// Make a new connection to a secure clock service.
392/// If no native SecureClock device can be found brings up the compatibility service and attempts
393/// to connect to the legacy wrapper.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700394fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800395 let secureclock_instances =
396 get_aidl_instances("android.hardware.security.secureclock", 1, "ISecureClock");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800397
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800398 let secure_clock_available =
Joel Galensonec7872a2021-07-02 14:37:10 -0700399 secureclock_instances.iter().any(|instance| *instance == "default");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800400
Max Bires130e51b2021-04-05 14:07:20 -0700401 let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
402
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800403 let secureclock = if secure_clock_available {
Max Bires130e51b2021-04-05 14:07:20 -0700404 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000405 .context(ks_err!("Trying to connect to genuine secure clock service."))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800406 } else {
407 // This is a no-op if it was called before.
408 keystore2_km_compat::add_keymint_device_service();
409
410 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
411 map_binder_status_code(binder::get_interface("android.security.compat"))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000412 .context(ks_err!("Trying to connect to compat service."))?;
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800413
414 // Legacy secure clock services were only implemented by TEE.
415 map_binder_status(keystore_compat_service.getSecureClock())
416 .map_err(|e| match e {
417 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
418 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800419 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800420 e => e,
421 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000422 .context(ks_err!("Trying to get Legacy wrapper."))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800423 }?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800424
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700425 Ok(secureclock)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800426}
427
428/// Get the timestamp service that verifies auth token timeliness towards security levels with
429/// different clocks.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700430pub fn get_timestamp_service() -> Result<Strong<dyn ISecureClock>> {
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800431 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
432 if let Some(dev) = &*ts_device {
433 Ok(dev.clone())
434 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000435 let dev = connect_secureclock().context(ks_err!())?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800436 *ts_device = Some(dev.clone());
437 Ok(dev)
438 }
439}
Max Biresb2e1d032021-02-08 21:35:05 -0800440
441static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
442 "android.hardware.security.keymint.IRemotelyProvisionedComponent";
443
Tri Voe8f04442022-12-21 08:53:56 -0800444/// Get the service name of a remotely provisioned component corresponding to given security level.
445pub fn get_remotely_provisioned_component_name(security_level: &SecurityLevel) -> Result<String> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800446 let remotely_prov_instances =
447 get_aidl_instances("android.hardware.security.keymint", 1, "IRemotelyProvisionedComponent");
448
Tri Voe8f04442022-12-21 08:53:56 -0800449 match *security_level {
Max Biresb2e1d032021-02-08 21:35:05 -0800450 SecurityLevel::TRUSTED_ENVIRONMENT => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700451 if remotely_prov_instances.iter().any(|instance| *instance == "default") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800452 Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
453 } else {
454 None
455 }
Max Biresb2e1d032021-02-08 21:35:05 -0800456 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800457 SecurityLevel::STRONGBOX => {
Joel Galensonec7872a2021-07-02 14:37:10 -0700458 if remotely_prov_instances.iter().any(|instance| *instance == "strongbox") {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800459 Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
460 } else {
461 None
462 }
Max Biresb2e1d032021-02-08 21:35:05 -0800463 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800464 _ => None,
465 }
466 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
Tri Voe8f04442022-12-21 08:53:56 -0800467 .context(ks_err!())
468}
Max Biresb2e1d032021-02-08 21:35:05 -0800469
Tri Voe8f04442022-12-21 08:53:56 -0800470fn connect_remotely_provisioned_component(
471 security_level: &SecurityLevel,
472) -> Result<Strong<dyn IRemotelyProvisionedComponent>> {
473 let service_name = get_remotely_provisioned_component_name(security_level)?;
Max Biresb2e1d032021-02-08 21:35:05 -0800474 let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000475 map_binder_status_code(binder::get_interface(&service_name))
476 .context(ks_err!("Trying to connect to RemotelyProvisionedComponent service."))?;
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700477 Ok(rem_prov_hal)
Max Biresb2e1d032021-02-08 21:35:05 -0800478}
479
480/// Get a remote provisiong component device for the given security level either from the cache or
481/// by making a new connection. Returns the device.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700482pub fn get_remotely_provisioned_component(
483 security_level: &SecurityLevel,
484) -> Result<Strong<dyn IRemotelyProvisionedComponent>> {
Max Biresb2e1d032021-02-08 21:35:05 -0800485 let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap();
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700486 if let Some(dev) = devices_map.dev_by_sec_level(security_level) {
Max Biresb2e1d032021-02-08 21:35:05 -0800487 Ok(dev)
488 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000489 let dev = connect_remotely_provisioned_component(security_level).context(ks_err!())?;
Max Biresb2e1d032021-02-08 21:35:05 -0800490 devices_map.insert(*security_level, dev);
491 // Unwrap must succeed because we just inserted it.
492 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
493 }
494}