blob: 3037a03829306a8f46c6d1a46bdae47b3940214d [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::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080031 IKeyMintDevice::IKeyMintDevice, KeyMintHardwareInfo::KeyMintHardwareInfo,
32 SecurityLevel::SecurityLevel,
Max Bires8e93d2b2021-01-14 13:17:59 -080033};
Stephen Crane221bbb52020-12-16 15:52:10 -080034use android_hardware_security_keymint::binder::{StatusCode, Strong};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080035use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080036use anyhow::{Context, Result};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080037use lazy_static::lazy_static;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080038use std::sync::{Arc, Mutex};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080039use std::{cell::RefCell, sync::Once};
Janis Danisevskis3f2955c2021-02-02 21:53:35 -080040use std::{collections::HashMap, path::Path, path::PathBuf};
Janis Danisevskis93927dd2020-12-23 12:23:08 -080041
42static DB_INIT: Once = Once::new();
43
44/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
45/// the thread local DB field. It should never be called directly. The first time this is called
46/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080047/// documentation of cleanup_leftovers for more details. The function also constructs a blob
48/// garbage collector. The initializing closure constructs another database connection without
49/// a gc. Although one GC is created for each thread local database connection, this closure
50/// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
51/// database connection is created for the garbage collector worker.
Janis Danisevskis93927dd2020-12-23 12:23:08 -080052fn create_thread_local_db() -> KeystoreDB {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080053 let gc = Gc::new_init_with(ASYNC_TASK.clone(), || {
54 (
55 Box::new(|uuid, blob| {
56 let km_dev: Strong<dyn IKeyMintDevice> =
57 get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?.get_interface()?;
58 map_km_error(km_dev.deleteKey(&*blob))
59 .context("In invalidate key closure: Trying to invalidate key blob.")
60 }),
61 KeystoreDB::new(&DB_PATH.lock().expect("Could not get the database directory."), None)
62 .expect("Failed to open database."),
63 )
64 });
65
66 let mut db =
67 KeystoreDB::new(&DB_PATH.lock().expect("Could not get the database directory."), Some(gc))
68 .expect("Failed to open database.");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080069 DB_INIT.call_once(|| {
70 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080071 db.insert_last_off_body(MonotonicRawTime::now())
72 .expect("Could not initialize database with last off body.");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080073 log::info!("Calling cleanup leftovers.");
74 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
75 if n != 0 {
76 log::info!(
77 concat!(
78 "Cleaned up {} failed entries. ",
79 "This indicates keystore crashed during key generation."
80 ),
81 n
82 );
83 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -080084 });
85 db
86}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070087
88thread_local! {
89 /// Database connections are not thread safe, but connecting to the
90 /// same database multiple times is safe as long as each connection is
91 /// used by only one thread. So we store one database connection per
92 /// thread in this thread local key.
93 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080094 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070095}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080096
Max Bires8e93d2b2021-01-14 13:17:59 -080097#[derive(Default)]
98struct DevicesMap {
99 devices_by_uuid: HashMap<Uuid, (Asp, KeyMintHardwareInfo)>,
100 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
101}
102
103impl DevicesMap {
104 fn dev_by_sec_level(
105 &self,
106 sec_level: &SecurityLevel,
107 ) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
108 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
109 }
110
111 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
112 self.devices_by_uuid
113 .get(uuid)
114 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
115 }
116
117 /// The requested security level and the security level of the actual implementation may
118 /// differ. So we map the requested security level to the uuid of the implementation
119 /// so that there cannot be any confusion as to which KeyMint instance is requested.
120 fn insert(&mut self, sec_level: SecurityLevel, dev: Asp, hw_info: KeyMintHardwareInfo) {
121 // For now we use the reported security level of the KM instance as UUID.
122 // TODO update this section once UUID was added to the KM hardware info.
123 let uuid: Uuid = sec_level.into();
124 self.devices_by_uuid.insert(uuid, (dev, hw_info));
125 self.uuid_by_sec_level.insert(sec_level, uuid);
126 }
127}
128
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800129lazy_static! {
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800130 /// The path where keystore stores all its keys.
131 pub static ref DB_PATH: Mutex<PathBuf> = Mutex::new(
132 Path::new("/data/misc/keystore").to_path_buf());
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800133 /// Runtime database of unwrapped super keys.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800134 pub static ref SUPER_KEY: Arc<SuperKeyManager> = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -0800135 /// Map of KeyMint devices.
Max Bires8e93d2b2021-01-14 13:17:59 -0800136 static ref KEY_MINT_DEVICES: Mutex<DevicesMap> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800137 /// Timestamp service.
138 static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800139 /// A single on-demand worker thread that handles deferred tasks with two different
140 /// priorities.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800141 pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800142 /// Singleton for enforcements.
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000143 pub static ref ENFORCEMENTS: Enforcements = Enforcements::new();
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000144 /// LegacyBlobLoader is initialized and exists globally.
145 /// The same directory used by the database is used by the LegacyBlobLoader as well.
146 pub static ref LEGACY_BLOB_LOADER: LegacyBlobLoader = LegacyBlobLoader::new(
Janis Danisevskis3f2955c2021-02-02 21:53:35 -0800147 &DB_PATH.lock().expect("Could not get the database path for legacy blob loader."));
Janis Danisevskisba998992020-12-29 16:08:40 -0800148}
149
150static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
151
152/// Make a new connection to a KeyMint device of the given security level.
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800153/// If no native KeyMint device can be found this function also brings
154/// up the compatibility service and attempts to connect to the legacy wrapper.
Max Bires8e93d2b2021-01-14 13:17:59 -0800155fn connect_keymint(security_level: &SecurityLevel) -> Result<(Asp, KeyMintHardwareInfo)> {
156 let service_name = match *security_level {
Janis Danisevskisba998992020-12-29 16:08:40 -0800157 SecurityLevel::TRUSTED_ENVIRONMENT => format!("{}/default", KEYMINT_SERVICE_NAME),
158 SecurityLevel::STRONGBOX => format!("{}/strongbox", KEYMINT_SERVICE_NAME),
159 _ => {
160 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
161 .context("In connect_keymint.")
162 }
163 };
164
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800165 let keymint = map_binder_status_code(binder::get_interface(&service_name))
166 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")
167 .or_else(|e| {
168 match e.root_cause().downcast_ref::<Error>() {
169 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
170 // This is a no-op if it was called before.
171 keystore2_km_compat::add_keymint_device_service();
172
Stephen Crane221bbb52020-12-16 15:52:10 -0800173 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800174 map_binder_status_code(binder::get_interface("android.security.compat"))
175 .context("In connect_keymint: Trying to connect to compat service.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -0800176 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800177 .map_err(|e| match e {
178 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
179 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
180 }
181 e => e,
182 })
Max Bires8e93d2b2021-01-14 13:17:59 -0800183 .context("In connect_keymint: Trying to get Legacy wrapper.")
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800184 }
185 _ => Err(e),
186 }
187 })?;
Janis Danisevskisba998992020-12-29 16:08:40 -0800188
Max Bires8e93d2b2021-01-14 13:17:59 -0800189 let hw_info = map_km_error(keymint.getHardwareInfo())
190 .context("In connect_keymint: Failed to get hardware info.")?;
191
192 Ok((Asp::new(keymint.as_binder()), hw_info))
Janis Danisevskisba998992020-12-29 16:08:40 -0800193}
194
195/// Get a keymint device for the given security level either from our cache or
Max Bires8e93d2b2021-01-14 13:17:59 -0800196/// by making a new connection. Returns the device, the hardware info and the uuid.
197/// TODO the latter can be removed when the uuid is part of the hardware info.
198pub fn get_keymint_device(
199 security_level: &SecurityLevel,
200) -> Result<(Asp, KeyMintHardwareInfo, Uuid)> {
Janis Danisevskisba998992020-12-29 16:08:40 -0800201 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
Max Bires8e93d2b2021-01-14 13:17:59 -0800202 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(&security_level) {
203 Ok((dev, hw_info, uuid))
Janis Danisevskisba998992020-12-29 16:08:40 -0800204 } else {
Max Bires8e93d2b2021-01-14 13:17:59 -0800205 let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
206 devices_map.insert(*security_level, dev, hw_info);
207 // Unwrap must succeed because we just inserted it.
208 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
209 }
210}
211
212/// Get a keymint device for the given uuid. This will only access the cache, but will not
213/// attempt to establish a new connection. It is assumed that the cache is already populated
214/// when this is called. This is a fair assumption, because service.rs iterates through all
215/// security levels when it gets instantiated.
216pub fn get_keymint_dev_by_uuid(uuid: &Uuid) -> Result<(Asp, KeyMintHardwareInfo)> {
217 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
218 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
219 Ok((dev, hw_info))
220 } else {
221 Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
Janis Danisevskisba998992020-12-29 16:08:40 -0800222 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800223}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800224
225static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
226
227/// Make a new connection to a secure clock service.
228/// If no native SecureClock device can be found brings up the compatibility service and attempts
229/// to connect to the legacy wrapper.
230fn connect_secureclock() -> Result<Asp> {
231 let secureclock = map_binder_status_code(binder::get_interface(TIME_STAMP_SERVICE_NAME))
232 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
233 .or_else(|e| {
234 match e.root_cause().downcast_ref::<Error>() {
235 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
236 // This is a no-op if it was called before.
237 keystore2_km_compat::add_keymint_device_service();
238
Stephen Crane221bbb52020-12-16 15:52:10 -0800239 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800240 map_binder_status_code(binder::get_interface("android.security.compat"))
241 .context(
242 "In connect_secureclock: Trying to connect to compat service.",
243 )?;
244
245 // Legacy secure clock services were only implemented by TEE.
246 map_binder_status(keystore_compat_service.getSecureClock())
247 .map_err(|e| match e {
248 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
249 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
250 }
251 e => e,
252 })
253 .context("In connect_secureclock: Trying to get Legacy wrapper.")
254 }
255 _ => Err(e),
256 }
257 })?;
258
259 Ok(Asp::new(secureclock.as_binder()))
260}
261
262/// Get the timestamp service that verifies auth token timeliness towards security levels with
263/// different clocks.
264pub fn get_timestamp_service() -> Result<Asp> {
265 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
266 if let Some(dev) = &*ts_device {
267 Ok(dev.clone())
268 } else {
269 let dev = connect_secureclock().context("In get_timestamp_service.")?;
270 *ts_device = Some(dev.clone());
271 Ok(dev)
272 }
273}