blob: bd28ca669a170ed29fb440e4dd971201e5bbf64c [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 Danisevskisba998992020-12-29 16:08:40 -080023use crate::utils::Asp;
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};
Stephen Crane221bbb52020-12-16 15:52:10 -080035use android_hardware_security_keymint::binder::{StatusCode, Strong};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080036use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080037use anyhow::{Context, Result};
David Drysdale0e45a612021-02-25 17:24:36 +000038use binder::FromIBinder;
Janis Danisevskisef14e1a2021-02-23 23:16:55 -080039use keystore2_vintf::get_aidl_instances;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080040use lazy_static::lazy_static;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080041use std::sync::{Arc, Mutex};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080042use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080043use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080044
45static DB_INIT: Once = Once::new();
46
47/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
48/// the thread local DB field. It should never be called directly. The first time this is called
49/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080050/// documentation of cleanup_leftovers for more details. The function also constructs a blob
51/// garbage collector. The initializing closure constructs another database connection without
52/// a gc. Although one GC is created for each thread local database connection, this closure
53/// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
54/// database connection is created for the garbage collector worker.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000055pub fn create_thread_local_db() -> KeystoreDB {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080056 let gc = Gc::new_init_with(ASYNC_TASK.clone(), || {
57 (
58 Box::new(|uuid, blob| {
59 let km_dev: Strong<dyn IKeyMintDevice> =
60 get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?.get_interface()?;
61 map_km_error(km_dev.deleteKey(&*blob))
62 .context("In invalidate key closure: Trying to invalidate key blob.")
63 }),
64 KeystoreDB::new(&DB_PATH.lock().expect("Could not get the database directory."), None)
65 .expect("Failed to open database."),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000066 SUPER_KEY.clone(),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080067 )
68 });
69
70 let mut db =
71 KeystoreDB::new(&DB_PATH.lock().expect("Could not get the database directory."), Some(gc))
72 .expect("Failed to open database.");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080073 DB_INIT.call_once(|| {
74 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080075 db.insert_last_off_body(MonotonicRawTime::now())
76 .expect("Could not initialize database with last off body.");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080077 log::info!("Calling cleanup leftovers.");
78 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
79 if n != 0 {
80 log::info!(
81 concat!(
82 "Cleaned up {} failed entries. ",
83 "This indicates keystore crashed during key generation."
84 ),
85 n
86 );
87 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -080088 });
89 db
90}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070091
92thread_local! {
93 /// Database connections are not thread safe, but connecting to the
94 /// same database multiple times is safe as long as each connection is
95 /// used by only one thread. So we store one database connection per
96 /// thread in this thread local key.
97 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080098 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070099}
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800100
Max Bires8e93d2b2021-01-14 13:17:59 -0800101#[derive(Default)]
102struct DevicesMap {
103 devices_by_uuid: HashMap<Uuid, (Asp, KeyMintHardwareInfo)>,
104 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
105}
106
107impl DevicesMap {
108 fn dev_by_sec_level(
109 &self,
110 sec_level: &SecurityLevel,
111 ) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
112 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
113 }
114
115 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
116 self.devices_by_uuid
117 .get(uuid)
118 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
119 }
120
David Drysdale0e45a612021-02-25 17:24:36 +0000121 fn devices<T: FromIBinder + ?Sized>(&self) -> Vec<Strong<T>> {
122 self.devices_by_uuid.values().filter_map(|(asp, _)| asp.get_interface::<T>().ok()).collect()
123 }
124
Max Bires8e93d2b2021-01-14 13:17:59 -0800125 /// The requested security level and the security level of the actual implementation may
126 /// differ. So we map the requested security level to the uuid of the implementation
127 /// so that there cannot be any confusion as to which KeyMint instance is requested.
128 fn insert(&mut self, sec_level: SecurityLevel, dev: Asp, hw_info: KeyMintHardwareInfo) {
129 // For now we use the reported security level of the KM instance as UUID.
130 // TODO update this section once UUID was added to the KM hardware info.
131 let uuid: Uuid = sec_level.into();
132 self.devices_by_uuid.insert(uuid, (dev, hw_info));
133 self.uuid_by_sec_level.insert(sec_level, uuid);
134 }
135}
136
Max Biresb2e1d032021-02-08 21:35:05 -0800137#[derive(Default)]
138struct RemotelyProvisionedDevicesMap {
139 devices_by_sec_level: HashMap<SecurityLevel, Asp>,
140}
141
142impl RemotelyProvisionedDevicesMap {
143 fn dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Asp> {
144 self.devices_by_sec_level.get(sec_level).map(|dev| (*dev).clone())
145 }
146
147 fn insert(&mut self, sec_level: SecurityLevel, dev: Asp) {
148 self.devices_by_sec_level.insert(sec_level, dev);
149 }
150}
151
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800152lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800153 /// The path where keystore stores all its keys.
154 pub static ref DB_PATH: Mutex<PathBuf> = Mutex::new(
155 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800156 /// Runtime database of unwrapped super keys.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800157 pub static ref SUPER_KEY: Arc<SuperKeyManager> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800158 /// Map of KeyMint devices.
Max Bires8e93d2b2021-01-14 13:17:59 -0800159 static ref KEY_MINT_DEVICES: Mutex<DevicesMap> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800160 /// Timestamp service.
161 static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default();
Max Biresb2e1d032021-02-08 21:35:05 -0800162 /// RemotelyProvisionedComponent HAL devices.
163 static ref REMOTELY_PROVISIONED_COMPONENT_DEVICES: Mutex<RemotelyProvisionedDevicesMap> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800164 /// A single on-demand worker thread that handles deferred tasks with two different
165 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800166 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800167 /// Singleton for enforcements.
Paul Crowley7c57bf12021-02-02 16:26:57 -0800168 pub static ref ENFORCEMENTS: Enforcements = Default::default();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000169 /// LegacyBlobLoader is initialized and exists globally.
170 /// The same directory used by the database is used by the LegacyBlobLoader as well.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000171 pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
172 &DB_PATH.lock().expect("Could not get the database path for legacy blob loader.")));
173 /// Legacy migrator. Atomically migrates legacy blobs to the database.
174 pub static ref LEGACY_MIGRATOR: Arc<LegacyMigrator> =
Janis Danisevskisec6586d2021-04-30 10:54:07 -0700175 Arc::new(LegacyMigrator::new(Arc::new(Default::default())));
Pavel Grafov94243c22021-04-21 18:03:11 +0100176 /// Background thread which handles logging via statsd and logd
177 pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800178}
179
180static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
181
182/// Make a new connection to a KeyMint device of the given security level.
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800183/// If no native KeyMint device can be found this function also brings
184/// up the compatibility service and attempts to connect to the legacy wrapper.
Max Bires8e93d2b2021-01-14 13:17:59 -0800185fn connect_keymint(security_level: &SecurityLevel) -> Result<(Asp, KeyMintHardwareInfo)> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800186 let keymint_instances =
187 get_aidl_instances("android.hardware.security.keymint", 1, "IKeyMintDevice");
188
Max Bires8e93d2b2021-01-14 13:17:59 -0800189 let service_name = match *security_level {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800190 SecurityLevel::TRUSTED_ENVIRONMENT => {
191 if keymint_instances.as_vec()?.iter().any(|instance| *instance == "default") {
192 Some(format!("{}/default", KEYMINT_SERVICE_NAME))
193 } else {
194 None
195 }
196 }
197 SecurityLevel::STRONGBOX => {
198 if keymint_instances.as_vec()?.iter().any(|instance| *instance == "strongbox") {
199 Some(format!("{}/strongbox", KEYMINT_SERVICE_NAME))
200 } else {
201 None
202 }
203 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800204 _ => {
205 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
206 .context("In connect_keymint.")
207 }
208 };
209
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800210 let keymint = if let Some(service_name) = service_name {
211 map_binder_status_code(binder::get_interface(&service_name))
212 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")
213 } else {
214 // This is a no-op if it was called before.
215 keystore2_km_compat::add_keymint_device_service();
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800216
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800217 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
218 map_binder_status_code(binder::get_interface("android.security.compat"))
219 .context("In connect_keymint: Trying to connect to compat service.")?;
220 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
221 .map_err(|e| match e {
222 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
223 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800224 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800225 e => e,
226 })
227 .context("In connect_keymint: Trying to get Legacy wrapper.")
228 }?;
Janis Danisevskisba998992020-12-29 16:08:40 -0800229
Max Bires8e93d2b2021-01-14 13:17:59 -0800230 let hw_info = map_km_error(keymint.getHardwareInfo())
231 .context("In connect_keymint: Failed to get hardware info.")?;
232
233 Ok((Asp::new(keymint.as_binder()), hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800234}
235
236/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800237/// by making a new connection. Returns the device, the hardware info and the uuid.
238/// TODO the latter can be removed when the uuid is part of the hardware info.
239pub fn get_keymint_device(
240 security_level: &SecurityLevel,
241) -> Result<(Asp, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800242 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Max Bires8e93d2b2021-01-14 13:17:59 -0800243 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(&security_level) {
244 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800245 } else {
Max Bires8e93d2b2021-01-14 13:17:59 -0800246 let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
247 devices_map.insert(*security_level, dev, hw_info);
248 // Unwrap must succeed because we just inserted it.
249 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
250 }
251}
252
253/// Get a keymint device for the given uuid. This will only access the cache, but will not
254/// attempt to establish a new connection. It is assumed that the cache is already populated
255/// when this is called. This is a fair assumption, because service.rs iterates through all
256/// security levels when it gets instantiated.
257pub fn get_keymint_dev_by_uuid(uuid: &Uuid) -> Result<(Asp, KeyMintHardwareInfo)> {
258 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
259 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
260 Ok((dev, hw_info))
261 } else {
262 Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
Janis Danisevskisba998992020-12-29 16:08:40 -0800263 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800264}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800265
David Drysdale0e45a612021-02-25 17:24:36 +0000266/// Return all known keymint devices.
267pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
268 KEY_MINT_DEVICES.lock().unwrap().devices()
269}
270
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800271static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
272
273/// Make a new connection to a secure clock service.
274/// If no native SecureClock device can be found brings up the compatibility service and attempts
275/// to connect to the legacy wrapper.
276fn connect_secureclock() -> Result<Asp> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800277 let secureclock_instances =
278 get_aidl_instances("android.hardware.security.secureclock", 1, "ISecureClock");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800279
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800280 let secure_clock_available =
281 secureclock_instances.as_vec()?.iter().any(|instance| *instance == "default");
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800282
Max Bires130e51b2021-04-05 14:07:20 -0700283 let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
284
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800285 let secureclock = if secure_clock_available {
Max Bires130e51b2021-04-05 14:07:20 -0700286 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800287 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
288 } else {
289 // This is a no-op if it was called before.
290 keystore2_km_compat::add_keymint_device_service();
291
292 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
293 map_binder_status_code(binder::get_interface("android.security.compat"))
294 .context("In connect_secureclock: Trying to connect to compat service.")?;
295
296 // Legacy secure clock services were only implemented by TEE.
297 map_binder_status(keystore_compat_service.getSecureClock())
298 .map_err(|e| match e {
299 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
300 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800301 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800302 e => e,
303 })
304 .context("In connect_secureclock: Trying to get Legacy wrapper.")
305 }?;
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800306
307 Ok(Asp::new(secureclock.as_binder()))
308}
309
310/// Get the timestamp service that verifies auth token timeliness towards security levels with
311/// different clocks.
312pub fn get_timestamp_service() -> Result<Asp> {
313 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
314 if let Some(dev) = &*ts_device {
315 Ok(dev.clone())
316 } else {
317 let dev = connect_secureclock().context("In get_timestamp_service.")?;
318 *ts_device = Some(dev.clone());
319 Ok(dev)
320 }
321}
Max Biresb2e1d032021-02-08 21:35:05 -0800322
323static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
324 "android.hardware.security.keymint.IRemotelyProvisionedComponent";
325
326fn connect_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp> {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800327 let remotely_prov_instances =
328 get_aidl_instances("android.hardware.security.keymint", 1, "IRemotelyProvisionedComponent");
329
Max Biresb2e1d032021-02-08 21:35:05 -0800330 let service_name = match *security_level {
331 SecurityLevel::TRUSTED_ENVIRONMENT => {
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800332 if remotely_prov_instances.as_vec()?.iter().any(|instance| *instance == "default") {
333 Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
334 } else {
335 None
336 }
Max Biresb2e1d032021-02-08 21:35:05 -0800337 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800338 SecurityLevel::STRONGBOX => {
339 if remotely_prov_instances.as_vec()?.iter().any(|instance| *instance == "strongbox") {
340 Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
341 } else {
342 None
343 }
Max Biresb2e1d032021-02-08 21:35:05 -0800344 }
Janis Danisevskisef14e1a2021-02-23 23:16:55 -0800345 _ => None,
346 }
347 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
348 .context("In connect_remotely_provisioned_component.")?;
Max Biresb2e1d032021-02-08 21:35:05 -0800349
350 let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> =
351 map_binder_status_code(binder::get_interface(&service_name))
352 .context(concat!(
353 "In connect_remotely_provisioned_component: Trying to connect to",
354 " RemotelyProvisionedComponent service."
355 ))
356 .map_err(|e| e)?;
357 Ok(Asp::new(rem_prov_hal.as_binder()))
358}
359
360/// Get a remote provisiong component device for the given security level either from the cache or
361/// by making a new connection. Returns the device.
362pub fn get_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp> {
363 let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap();
364 if let Some(dev) = devices_map.dev_by_sec_level(&security_level) {
365 Ok(dev)
366 } else {
367 let dev = connect_remotely_provisioned_component(security_level)
368 .context("In get_remotely_provisioned_component.")?;
369 devices_map.insert(*security_level, dev);
370 // Unwrap must succeed because we just inserted it.
371 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
372 }
373}