blob: c488a18719d0f3bdabf0e2fc11dfd52336aee23e [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 Danisevskisb42fc182020-12-15 08:41:27 -080021use crate::super_key::SuperKeyManager;
Janis Danisevskisba998992020-12-29 16:08:40 -080022use crate::utils::Asp;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080023use crate::{async_task::AsyncTask, database::MonotonicRawTime};
Janis Danisevskisba998992020-12-29 16:08:40 -080024use crate::{
25 database::KeystoreDB,
Max Bires8e93d2b2021-01-14 13:17:59 -080026 database::Uuid,
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080027 error::{map_binder_status, map_binder_status_code, Error, ErrorCode},
Janis Danisevskisba998992020-12-29 16:08:40 -080028};
Max Bires8e93d2b2021-01-14 13:17:59 -080029use crate::{enforcements::Enforcements, error::map_km_error};
30use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
31 KeyMintHardwareInfo::KeyMintHardwareInfo, SecurityLevel::SecurityLevel,
32};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080033use android_hardware_security_keymint::binder::StatusCode;
34use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080035use anyhow::{Context, Result};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080036use lazy_static::lazy_static;
Janis Danisevskisba998992020-12-29 16:08:40 -080037use std::collections::HashMap;
38use std::sync::Mutex;
Janis Danisevskis93927dd2020-12-23 12:23:08 -080039use std::{cell::RefCell, sync::Once};
40
41static DB_INIT: Once = Once::new();
42
43/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
44/// the thread local DB field. It should never be called directly. The first time this is called
45/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
46/// documentation of cleanup_leftovers for more details.
47fn create_thread_local_db() -> KeystoreDB {
48 let mut db = KeystoreDB::new(
49 // Keystore changes to the database directory on startup
50 // (see keystore2_main.rs).
51 &std::env::current_dir().expect("Could not get the current working directory."),
52 )
53 .expect("Failed to open database.");
54 DB_INIT.call_once(|| {
55 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080056 db.insert_last_off_body(MonotonicRawTime::now())
57 .expect("Could not initialize database with last off body.");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080058 log::info!("Calling cleanup leftovers.");
59 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
60 if n != 0 {
61 log::info!(
62 concat!(
63 "Cleaned up {} failed entries. ",
64 "This indicates keystore crashed during key generation."
65 ),
66 n
67 );
68 }
69 Gc::notify_gc();
70 });
71 db
72}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070073
74thread_local! {
75 /// Database connections are not thread safe, but connecting to the
76 /// same database multiple times is safe as long as each connection is
77 /// used by only one thread. So we store one database connection per
78 /// thread in this thread local key.
79 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080080 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070081}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080082
Max Bires8e93d2b2021-01-14 13:17:59 -080083#[derive(Default)]
84struct DevicesMap {
85 devices_by_uuid: HashMap<Uuid, (Asp, KeyMintHardwareInfo)>,
86 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
87}
88
89impl DevicesMap {
90 fn dev_by_sec_level(
91 &self,
92 sec_level: &SecurityLevel,
93 ) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
94 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
95 }
96
97 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
98 self.devices_by_uuid
99 .get(uuid)
100 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
101 }
102
103 /// The requested security level and the security level of the actual implementation may
104 /// differ. So we map the requested security level to the uuid of the implementation
105 /// so that there cannot be any confusion as to which KeyMint instance is requested.
106 fn insert(&mut self, sec_level: SecurityLevel, dev: Asp, hw_info: KeyMintHardwareInfo) {
107 // For now we use the reported security level of the KM instance as UUID.
108 // TODO update this section once UUID was added to the KM hardware info.
109 let uuid: Uuid = sec_level.into();
110 self.devices_by_uuid.insert(uuid, (dev, hw_info));
111 self.uuid_by_sec_level.insert(sec_level, uuid);
112 }
113}
114
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800115lazy_static! {
116 /// Runtime database of unwrapped super keys.
117 pub static ref SUPER_KEY: SuperKeyManager = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800118 /// Map of KeyMint devices.
Max Bires8e93d2b2021-01-14 13:17:59 -0800119 static ref KEY_MINT_DEVICES: Mutex<DevicesMap> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800120 /// Timestamp service.
121 static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800122 /// A single on-demand worker thread that handles deferred tasks with two different
123 /// priorities.
124 pub static ref ASYNC_TASK: AsyncTask = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800125 /// Singleton for enforcements.
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000126 pub static ref ENFORCEMENTS: Enforcements = Enforcements::new();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000127 /// LegacyBlobLoader is initialized and exists globally.
128 /// The same directory used by the database is used by the LegacyBlobLoader as well.
129 pub static ref LEGACY_BLOB_LOADER: LegacyBlobLoader = LegacyBlobLoader::new(
130 &std::env::current_dir().expect("Could not get the current working directory."));
Janis Danisevskisba998992020-12-29 16:08:40 -0800131}
132
133static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
134
135/// Make a new connection to a KeyMint device of the given security level.
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800136/// If no native KeyMint device can be found this function also brings
137/// up the compatibility service and attempts to connect to the legacy wrapper.
Max Bires8e93d2b2021-01-14 13:17:59 -0800138fn connect_keymint(security_level: &SecurityLevel) -> Result<(Asp, KeyMintHardwareInfo)> {
139 let service_name = match *security_level {
Janis Danisevskisba998992020-12-29 16:08:40 -0800140 SecurityLevel::TRUSTED_ENVIRONMENT => format!("{}/default", KEYMINT_SERVICE_NAME),
141 SecurityLevel::STRONGBOX => format!("{}/strongbox", KEYMINT_SERVICE_NAME),
142 _ => {
143 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
144 .context("In connect_keymint.")
145 }
146 };
147
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800148 let keymint = map_binder_status_code(binder::get_interface(&service_name))
149 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")
150 .or_else(|e| {
151 match e.root_cause().downcast_ref::<Error>() {
152 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
153 // This is a no-op if it was called before.
154 keystore2_km_compat::add_keymint_device_service();
155
156 let keystore_compat_service: Box<dyn IKeystoreCompatService> =
157 map_binder_status_code(binder::get_interface("android.security.compat"))
158 .context("In connect_keymint: Trying to connect to compat service.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -0800159 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800160 .map_err(|e| match e {
161 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
162 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
163 }
164 e => e,
165 })
Max Bires8e93d2b2021-01-14 13:17:59 -0800166 .context("In connect_keymint: Trying to get Legacy wrapper.")
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800167 }
168 _ => Err(e),
169 }
170 })?;
Janis Danisevskisba998992020-12-29 16:08:40 -0800171
Max Bires8e93d2b2021-01-14 13:17:59 -0800172 let hw_info = map_km_error(keymint.getHardwareInfo())
173 .context("In connect_keymint: Failed to get hardware info.")?;
174
175 Ok((Asp::new(keymint.as_binder()), hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800176}
177
178/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800179/// by making a new connection. Returns the device, the hardware info and the uuid.
180/// TODO the latter can be removed when the uuid is part of the hardware info.
181pub fn get_keymint_device(
182 security_level: &SecurityLevel,
183) -> Result<(Asp, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800184 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Max Bires8e93d2b2021-01-14 13:17:59 -0800185 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(&security_level) {
186 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800187 } else {
Max Bires8e93d2b2021-01-14 13:17:59 -0800188 let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
189 devices_map.insert(*security_level, dev, hw_info);
190 // Unwrap must succeed because we just inserted it.
191 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
192 }
193}
194
195/// Get a keymint device for the given uuid. This will only access the cache, but will not
196/// attempt to establish a new connection. It is assumed that the cache is already populated
197/// when this is called. This is a fair assumption, because service.rs iterates through all
198/// security levels when it gets instantiated.
199pub fn get_keymint_dev_by_uuid(uuid: &Uuid) -> Result<(Asp, KeyMintHardwareInfo)> {
200 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
201 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
202 Ok((dev, hw_info))
203 } else {
204 Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
Janis Danisevskisba998992020-12-29 16:08:40 -0800205 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800206}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800207
208static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
209
210/// Make a new connection to a secure clock service.
211/// If no native SecureClock device can be found brings up the compatibility service and attempts
212/// to connect to the legacy wrapper.
213fn connect_secureclock() -> Result<Asp> {
214 let secureclock = map_binder_status_code(binder::get_interface(TIME_STAMP_SERVICE_NAME))
215 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
216 .or_else(|e| {
217 match e.root_cause().downcast_ref::<Error>() {
218 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
219 // This is a no-op if it was called before.
220 keystore2_km_compat::add_keymint_device_service();
221
222 let keystore_compat_service: Box<dyn IKeystoreCompatService> =
223 map_binder_status_code(binder::get_interface("android.security.compat"))
224 .context(
225 "In connect_secureclock: Trying to connect to compat service.",
226 )?;
227
228 // Legacy secure clock services were only implemented by TEE.
229 map_binder_status(keystore_compat_service.getSecureClock())
230 .map_err(|e| match e {
231 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
232 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
233 }
234 e => e,
235 })
236 .context("In connect_secureclock: Trying to get Legacy wrapper.")
237 }
238 _ => Err(e),
239 }
240 })?;
241
242 Ok(Asp::new(secureclock.as_binder()))
243}
244
245/// Get the timestamp service that verifies auth token timeliness towards security levels with
246/// different clocks.
247pub fn get_timestamp_service() -> Result<Asp> {
248 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
249 if let Some(dev) = &*ts_device {
250 Ok(dev.clone())
251 } else {
252 let dev = connect_secureclock().context("In get_timestamp_service.")?;
253 *ts_device = Some(dev.clone());
254 Ok(dev)
255 }
256}