blob: 50ec26c2252d6ad5a4bfaf9853ec99253505358e [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
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000019use crate::enforcements::Enforcements;
Janis Danisevskis93927dd2020-12-23 12:23:08 -080020use crate::gc::Gc;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000021use crate::legacy_blob::LegacyBlobLoader;
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,
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};
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080029use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
30use android_hardware_security_keymint::binder::StatusCode;
31use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
Janis Danisevskisba998992020-12-29 16:08:40 -080032use anyhow::{Context, Result};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080033use lazy_static::lazy_static;
Janis Danisevskisba998992020-12-29 16:08:40 -080034use std::collections::HashMap;
35use std::sync::Mutex;
Janis Danisevskis93927dd2020-12-23 12:23:08 -080036use std::{cell::RefCell, sync::Once};
37
38static DB_INIT: Once = Once::new();
39
40/// Open a connection to the Keystore 2.0 database. This is called during the initialization of
41/// the thread local DB field. It should never be called directly. The first time this is called
42/// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
43/// documentation of cleanup_leftovers for more details.
44fn create_thread_local_db() -> KeystoreDB {
45 let mut db = KeystoreDB::new(
46 // Keystore changes to the database directory on startup
47 // (see keystore2_main.rs).
48 &std::env::current_dir().expect("Could not get the current working directory."),
49 )
50 .expect("Failed to open database.");
51 DB_INIT.call_once(|| {
52 log::info!("Touching Keystore 2.0 database for this first time since boot.");
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080053 db.insert_last_off_body(MonotonicRawTime::now())
54 .expect("Could not initialize database with last off body.");
Janis Danisevskis93927dd2020-12-23 12:23:08 -080055 log::info!("Calling cleanup leftovers.");
56 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
57 if n != 0 {
58 log::info!(
59 concat!(
60 "Cleaned up {} failed entries. ",
61 "This indicates keystore crashed during key generation."
62 ),
63 n
64 );
65 }
66 Gc::notify_gc();
67 });
68 db
69}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070070
71thread_local! {
72 /// Database connections are not thread safe, but connecting to the
73 /// same database multiple times is safe as long as each connection is
74 /// used by only one thread. So we store one database connection per
75 /// thread in this thread local key.
76 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080077 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070078}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080079
80lazy_static! {
81 /// Runtime database of unwrapped super keys.
82 pub static ref SUPER_KEY: SuperKeyManager = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -080083 /// Map of KeyMint devices.
84 static ref KEY_MINT_DEVICES: Mutex<HashMap<SecurityLevel, Asp>> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080085 /// Timestamp service.
86 static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -080087 /// A single on-demand worker thread that handles deferred tasks with two different
88 /// priorities.
89 pub static ref ASYNC_TASK: AsyncTask = Default::default();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080090 /// Singleton for enforcements.
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000091 pub static ref ENFORCEMENTS: Enforcements = Enforcements::new();
Hasini Gunasinghea020b532021-01-07 21:42:35 +000092 /// LegacyBlobLoader is initialized and exists globally.
93 /// The same directory used by the database is used by the LegacyBlobLoader as well.
94 pub static ref LEGACY_BLOB_LOADER: LegacyBlobLoader = LegacyBlobLoader::new(
95 &std::env::current_dir().expect("Could not get the current working directory."));
Janis Danisevskisba998992020-12-29 16:08:40 -080096}
97
98static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
99
100/// Make a new connection to a KeyMint device of the given security level.
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800101/// If no native KeyMint device can be found this function also brings
102/// up the compatibility service and attempts to connect to the legacy wrapper.
Janis Danisevskisba998992020-12-29 16:08:40 -0800103fn connect_keymint(security_level: SecurityLevel) -> Result<Asp> {
104 let service_name = match security_level {
105 SecurityLevel::TRUSTED_ENVIRONMENT => format!("{}/default", KEYMINT_SERVICE_NAME),
106 SecurityLevel::STRONGBOX => format!("{}/strongbox", KEYMINT_SERVICE_NAME),
107 _ => {
108 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
109 .context("In connect_keymint.")
110 }
111 };
112
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800113 let keymint = map_binder_status_code(binder::get_interface(&service_name))
114 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")
115 .or_else(|e| {
116 match e.root_cause().downcast_ref::<Error>() {
117 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
118 // This is a no-op if it was called before.
119 keystore2_km_compat::add_keymint_device_service();
120
121 let keystore_compat_service: Box<dyn IKeystoreCompatService> =
122 map_binder_status_code(binder::get_interface("android.security.compat"))
123 .context("In connect_keymint: Trying to connect to compat service.")?;
124 map_binder_status(keystore_compat_service.getKeyMintDevice(security_level))
125 .map_err(|e| match e {
126 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
127 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
128 }
129 e => e,
130 })
131 .context("In connext_keymint: Trying to get Legacy wrapper.")
132 }
133 _ => Err(e),
134 }
135 })?;
Janis Danisevskisba998992020-12-29 16:08:40 -0800136
137 Ok(Asp::new(keymint.as_binder()))
138}
139
140/// Get a keymint device for the given security level either from our cache or
141/// by making a new connection.
142pub fn get_keymint_device(security_level: SecurityLevel) -> Result<Asp> {
143 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
144 if let Some(dev) = devices_map.get(&security_level) {
145 Ok(dev.clone())
146 } else {
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800147 let dev = connect_keymint(security_level).context("In get_keymint_device.")?;
Janis Danisevskisba998992020-12-29 16:08:40 -0800148 devices_map.insert(security_level, dev.clone());
149 Ok(dev)
150 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800151}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800152
153static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
154
155/// Make a new connection to a secure clock service.
156/// If no native SecureClock device can be found brings up the compatibility service and attempts
157/// to connect to the legacy wrapper.
158fn connect_secureclock() -> Result<Asp> {
159 let secureclock = map_binder_status_code(binder::get_interface(TIME_STAMP_SERVICE_NAME))
160 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
161 .or_else(|e| {
162 match e.root_cause().downcast_ref::<Error>() {
163 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
164 // This is a no-op if it was called before.
165 keystore2_km_compat::add_keymint_device_service();
166
167 let keystore_compat_service: Box<dyn IKeystoreCompatService> =
168 map_binder_status_code(binder::get_interface("android.security.compat"))
169 .context(
170 "In connect_secureclock: Trying to connect to compat service.",
171 )?;
172
173 // Legacy secure clock services were only implemented by TEE.
174 map_binder_status(keystore_compat_service.getSecureClock())
175 .map_err(|e| match e {
176 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
177 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
178 }
179 e => e,
180 })
181 .context("In connect_secureclock: Trying to get Legacy wrapper.")
182 }
183 _ => Err(e),
184 }
185 })?;
186
187 Ok(Asp::new(secureclock.as_binder()))
188}
189
190/// Get the timestamp service that verifies auth token timeliness towards security levels with
191/// different clocks.
192pub fn get_timestamp_service() -> Result<Asp> {
193 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
194 if let Some(dev) = &*ts_device {
195 Ok(dev.clone())
196 } else {
197 let dev = connect_secureclock().context("In get_timestamp_service.")?;
198 *ts_device = Some(dev.clone());
199 Ok(dev)
200 }
201}