blob: 9668ee3dc89595401a12a88b035908ba1733e7c2 [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};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080038use lazy_static::lazy_static;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080039use std::sync::{Arc, Mutex};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080040use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080041use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080042
43static DB_INIT: Once = Once::new();
44
45/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
46/// the thread local DB field. It should never be called directly. The first time this is called
47/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080048/// documentation of cleanup_leftovers for more details. The function also constructs a blob
49/// garbage collector. The initializing closure constructs another database connection without
50/// a gc. Although one GC is created for each thread local database connection, this closure
51/// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
52/// database connection is created for the garbage collector worker.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000053pub fn create_thread_local_db() -> KeystoreDB {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054 let gc = Gc::new_init_with(ASYNC_TASK.clone(), || {
55 (
56 Box::new(|uuid, blob| {
57 let km_dev: Strong<dyn IKeyMintDevice> =
58 get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?.get_interface()?;
59 map_km_error(km_dev.deleteKey(&*blob))
60 .context("In invalidate key closure: Trying to invalidate key blob.")
61 }),
62 KeystoreDB::new(&DB_PATH.lock().expect("Could not get the database directory."), None)
63 .expect("Failed to open database."),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000064 SUPER_KEY.clone(),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080065 )
66 });
67
68 let mut db =
69 KeystoreDB::new(&DB_PATH.lock().expect("Could not get the database directory."), Some(gc))
70 .expect("Failed to open database.");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080071 DB_INIT.call_once(|| {
72 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080073 db.insert_last_off_body(MonotonicRawTime::now())
74 .expect("Could not initialize database with last off body.");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080075 log::info!("Calling cleanup leftovers.");
76 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
77 if n != 0 {
78 log::info!(
79 concat!(
80 "Cleaned up {} failed entries. ",
81 "This indicates keystore crashed during key generation."
82 ),
83 n
84 );
85 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -080086 });
87 db
88}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070089
90thread_local! {
91 /// Database connections are not thread safe, but connecting to the
92 /// same database multiple times is safe as long as each connection is
93 /// used by only one thread. So we store one database connection per
94 /// thread in this thread local key.
95 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080096 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070097}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080098
Max Bires8e93d2b2021-01-14 13:17:59 -080099#[derive(Default)]
100struct DevicesMap {
101 devices_by_uuid: HashMap<Uuid, (Asp, KeyMintHardwareInfo)>,
102 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
103}
104
105impl DevicesMap {
106 fn dev_by_sec_level(
107 &self,
108 sec_level: &SecurityLevel,
109 ) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
110 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
111 }
112
113 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
114 self.devices_by_uuid
115 .get(uuid)
116 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
117 }
118
119 /// The requested security level and the security level of the actual implementation may
120 /// differ. So we map the requested security level to the uuid of the implementation
121 /// so that there cannot be any confusion as to which KeyMint instance is requested.
122 fn insert(&mut self, sec_level: SecurityLevel, dev: Asp, hw_info: KeyMintHardwareInfo) {
123 // For now we use the reported security level of the KM instance as UUID.
124 // TODO update this section once UUID was added to the KM hardware info.
125 let uuid: Uuid = sec_level.into();
126 self.devices_by_uuid.insert(uuid, (dev, hw_info));
127 self.uuid_by_sec_level.insert(sec_level, uuid);
128 }
129}
130
Max Biresb2e1d032021-02-08 21:35:05 -0800131#[derive(Default)]
132struct RemotelyProvisionedDevicesMap {
133 devices_by_sec_level: HashMap<SecurityLevel, Asp>,
134}
135
136impl RemotelyProvisionedDevicesMap {
137 fn dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Asp> {
138 self.devices_by_sec_level.get(sec_level).map(|dev| (*dev).clone())
139 }
140
141 fn insert(&mut self, sec_level: SecurityLevel, dev: Asp) {
142 self.devices_by_sec_level.insert(sec_level, dev);
143 }
144}
145
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800146lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800147 /// The path where keystore stores all its keys.
148 pub static ref DB_PATH: Mutex<PathBuf> = Mutex::new(
149 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800150 /// Runtime database of unwrapped super keys.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800151 pub static ref SUPER_KEY: Arc<SuperKeyManager> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800152 /// Map of KeyMint devices.
Max Bires8e93d2b2021-01-14 13:17:59 -0800153 static ref KEY_MINT_DEVICES: Mutex<DevicesMap> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800154 /// Timestamp service.
155 static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default();
Max Biresb2e1d032021-02-08 21:35:05 -0800156 /// RemotelyProvisionedComponent HAL devices.
157 static ref REMOTELY_PROVISIONED_COMPONENT_DEVICES: Mutex<RemotelyProvisionedDevicesMap> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800158 /// A single on-demand worker thread that handles deferred tasks with two different
159 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800160 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800161 /// Singleton for enforcements.
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000162 pub static ref ENFORCEMENTS: Enforcements = Enforcements::new();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000163 /// LegacyBlobLoader is initialized and exists globally.
164 /// The same directory used by the database is used by the LegacyBlobLoader as well.
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000165 pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
166 &DB_PATH.lock().expect("Could not get the database path for legacy blob loader.")));
167 /// Legacy migrator. Atomically migrates legacy blobs to the database.
168 pub static ref LEGACY_MIGRATOR: Arc<LegacyMigrator> =
169 Arc::new(LegacyMigrator::new(ASYNC_TASK.clone()));
Janis Danisevskisba998992020-12-29 16:08:40 -0800170}
171
172static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
173
174/// Make a new connection to a KeyMint device of the given security level.
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800175/// If no native KeyMint device can be found this function also brings
176/// up the compatibility service and attempts to connect to the legacy wrapper.
Max Bires8e93d2b2021-01-14 13:17:59 -0800177fn connect_keymint(security_level: &SecurityLevel) -> Result<(Asp, KeyMintHardwareInfo)> {
178 let service_name = match *security_level {
Janis Danisevskisba998992020-12-29 16:08:40 -0800179 SecurityLevel::TRUSTED_ENVIRONMENT => format!("{}/default", KEYMINT_SERVICE_NAME),
180 SecurityLevel::STRONGBOX => format!("{}/strongbox", KEYMINT_SERVICE_NAME),
181 _ => {
182 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
183 .context("In connect_keymint.")
184 }
185 };
186
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800187 let keymint = map_binder_status_code(binder::get_interface(&service_name))
188 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")
189 .or_else(|e| {
190 match e.root_cause().downcast_ref::<Error>() {
191 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
192 // This is a no-op if it was called before.
193 keystore2_km_compat::add_keymint_device_service();
194
Stephen Crane221bbb52020-12-16 15:52:10 -0800195 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800196 map_binder_status_code(binder::get_interface("android.security.compat"))
197 .context("In connect_keymint: Trying to connect to compat service.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -0800198 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800199 .map_err(|e| match e {
200 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
201 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
202 }
203 e => e,
204 })
Max Bires8e93d2b2021-01-14 13:17:59 -0800205 .context("In connect_keymint: Trying to get Legacy wrapper.")
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800206 }
207 _ => Err(e),
208 }
209 })?;
Janis Danisevskisba998992020-12-29 16:08:40 -0800210
Max Bires8e93d2b2021-01-14 13:17:59 -0800211 let hw_info = map_km_error(keymint.getHardwareInfo())
212 .context("In connect_keymint: Failed to get hardware info.")?;
213
214 Ok((Asp::new(keymint.as_binder()), hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800215}
216
217/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800218/// by making a new connection. Returns the device, the hardware info and the uuid.
219/// TODO the latter can be removed when the uuid is part of the hardware info.
220pub fn get_keymint_device(
221 security_level: &SecurityLevel,
222) -> Result<(Asp, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800223 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Max Bires8e93d2b2021-01-14 13:17:59 -0800224 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(&security_level) {
225 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800226 } else {
Max Bires8e93d2b2021-01-14 13:17:59 -0800227 let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
228 devices_map.insert(*security_level, dev, hw_info);
229 // Unwrap must succeed because we just inserted it.
230 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
231 }
232}
233
234/// Get a keymint device for the given uuid. This will only access the cache, but will not
235/// attempt to establish a new connection. It is assumed that the cache is already populated
236/// when this is called. This is a fair assumption, because service.rs iterates through all
237/// security levels when it gets instantiated.
238pub fn get_keymint_dev_by_uuid(uuid: &Uuid) -> Result<(Asp, KeyMintHardwareInfo)> {
239 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
240 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
241 Ok((dev, hw_info))
242 } else {
243 Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
Janis Danisevskisba998992020-12-29 16:08:40 -0800244 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800245}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800246
247static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
248
249/// Make a new connection to a secure clock service.
250/// If no native SecureClock device can be found brings up the compatibility service and attempts
251/// to connect to the legacy wrapper.
252fn connect_secureclock() -> Result<Asp> {
253 let secureclock = map_binder_status_code(binder::get_interface(TIME_STAMP_SERVICE_NAME))
254 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
255 .or_else(|e| {
256 match e.root_cause().downcast_ref::<Error>() {
257 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
258 // This is a no-op if it was called before.
259 keystore2_km_compat::add_keymint_device_service();
260
Stephen Crane221bbb52020-12-16 15:52:10 -0800261 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800262 map_binder_status_code(binder::get_interface("android.security.compat"))
263 .context(
264 "In connect_secureclock: Trying to connect to compat service.",
265 )?;
266
267 // Legacy secure clock services were only implemented by TEE.
268 map_binder_status(keystore_compat_service.getSecureClock())
269 .map_err(|e| match e {
270 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
271 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
272 }
273 e => e,
274 })
275 .context("In connect_secureclock: Trying to get Legacy wrapper.")
276 }
277 _ => Err(e),
278 }
279 })?;
280
281 Ok(Asp::new(secureclock.as_binder()))
282}
283
284/// Get the timestamp service that verifies auth token timeliness towards security levels with
285/// different clocks.
286pub fn get_timestamp_service() -> Result<Asp> {
287 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
288 if let Some(dev) = &*ts_device {
289 Ok(dev.clone())
290 } else {
291 let dev = connect_secureclock().context("In get_timestamp_service.")?;
292 *ts_device = Some(dev.clone());
293 Ok(dev)
294 }
295}
Max Biresb2e1d032021-02-08 21:35:05 -0800296
297static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
298 "android.hardware.security.keymint.IRemotelyProvisionedComponent";
299
300fn connect_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp> {
301 let service_name = match *security_level {
302 SecurityLevel::TRUSTED_ENVIRONMENT => {
303 format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME)
304 }
305 SecurityLevel::STRONGBOX => format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME),
306 _ => {
307 // Given the integration of IRemotelyProvisionedComponent with KeyMint, it is reasonable
308 // to return HARDWARE_TYPE_UNAVAILABLE as a Km error if it cannot be found.
309 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
310 .context("In connect_remotely_provisioned_component.");
311 }
312 };
313
314 let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> =
315 map_binder_status_code(binder::get_interface(&service_name))
316 .context(concat!(
317 "In connect_remotely_provisioned_component: Trying to connect to",
318 " RemotelyProvisionedComponent service."
319 ))
320 .map_err(|e| e)?;
321 Ok(Asp::new(rem_prov_hal.as_binder()))
322}
323
324/// Get a remote provisiong component device for the given security level either from the cache or
325/// by making a new connection. Returns the device.
326pub fn get_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp> {
327 let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap();
328 if let Some(dev) = devices_map.dev_by_sec_level(&security_level) {
329 Ok(dev)
330 } else {
331 let dev = connect_remotely_provisioned_component(security_level)
332 .context("In get_remotely_provisioned_component.")?;
333 devices_map.insert(*security_level, dev);
334 // Unwrap must succeed because we just inserted it.
335 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
336 }
337}