blob: 3c79eed173475a8d20be11f5881b126fd1b05e7d [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::async_task::AsyncTask;
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +000020use crate::background_task_handler::BackgroundTaskHandler;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000021use crate::enforcements::Enforcements;
Janis Danisevskis93927dd2020-12-23 12:23:08 -080022use crate::gc::Gc;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080023use crate::super_key::SuperKeyManager;
Janis Danisevskisba998992020-12-29 16:08:40 -080024use crate::utils::Asp;
25use 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.");
53 log::info!("Calling cleanup leftovers.");
54 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
55 if n != 0 {
56 log::info!(
57 concat!(
58 "Cleaned up {} failed entries. ",
59 "This indicates keystore crashed during key generation."
60 ),
61 n
62 );
63 }
64 Gc::notify_gc();
65 });
66 db
67}
Janis Danisevskisa75e2082020-10-07 16:44:26 -070068
69thread_local! {
70 /// Database connections are not thread safe, but connecting to the
71 /// same database multiple times is safe as long as each connection is
72 /// used by only one thread. So we store one database connection per
73 /// thread in this thread local key.
74 pub static DB: RefCell<KeystoreDB> =
Janis Danisevskis93927dd2020-12-23 12:23:08 -080075 RefCell::new(create_thread_local_db());
Janis Danisevskisa75e2082020-10-07 16:44:26 -070076}
Janis Danisevskisb42fc182020-12-15 08:41:27 -080077
78lazy_static! {
79 /// Runtime database of unwrapped super keys.
80 pub static ref SUPER_KEY: SuperKeyManager = Default::default();
Janis Danisevskisba998992020-12-29 16:08:40 -080081 /// Map of KeyMint devices.
82 static ref KEY_MINT_DEVICES: Mutex<HashMap<SecurityLevel, Asp>> = Default::default();
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080083 /// Timestamp service.
84 static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default();
Janis Danisevskis93927dd2020-12-23 12:23:08 -080085 /// A single on-demand worker thread that handles deferred tasks with two different
86 /// priorities.
87 pub static ref ASYNC_TASK: AsyncTask = Default::default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000088 /// Singeleton for enforcements.
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000089 pub static ref ENFORCEMENTS: Enforcements = Enforcements::new();
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +000090 /// Background task handler is initialized and exists globally.
91 /// The other modules (e.g. enforcements) communicate with it via a channel initialized during
92 /// keystore startup.
93 pub static ref BACKGROUND_TASK_HANDLER: BackgroundTaskHandler = BackgroundTaskHandler::new();
Janis Danisevskisba998992020-12-29 16:08:40 -080094}
95
96static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
97
98/// Make a new connection to a KeyMint device of the given security level.
Janis Danisevskis8c6378e2021-01-01 09:30:37 -080099/// If no native KeyMint device can be found this function also brings
100/// up the compatibility service and attempts to connect to the legacy wrapper.
Janis Danisevskisba998992020-12-29 16:08:40 -0800101fn connect_keymint(security_level: SecurityLevel) -> Result<Asp> {
102 let service_name = match security_level {
103 SecurityLevel::TRUSTED_ENVIRONMENT => format!("{}/default", KEYMINT_SERVICE_NAME),
104 SecurityLevel::STRONGBOX => format!("{}/strongbox", KEYMINT_SERVICE_NAME),
105 _ => {
106 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
107 .context("In connect_keymint.")
108 }
109 };
110
Janis Danisevskis8c6378e2021-01-01 09:30:37 -0800111 let keymint = map_binder_status_code(binder::get_interface(&service_name))
112 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")
113 .or_else(|e| {
114 match e.root_cause().downcast_ref::<Error>() {
115 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
116 // This is a no-op if it was called before.
117 keystore2_km_compat::add_keymint_device_service();
118
119 let keystore_compat_service: Box<dyn IKeystoreCompatService> =
120 map_binder_status_code(binder::get_interface("android.security.compat"))
121 .context("In connect_keymint: Trying to connect to compat service.")?;
122 map_binder_status(keystore_compat_service.getKeyMintDevice(security_level))
123 .map_err(|e| match e {
124 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
125 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
126 }
127 e => e,
128 })
129 .context("In connext_keymint: Trying to get Legacy wrapper.")
130 }
131 _ => Err(e),
132 }
133 })?;
Janis Danisevskisba998992020-12-29 16:08:40 -0800134
135 Ok(Asp::new(keymint.as_binder()))
136}
137
138/// Get a keymint device for the given security level either from our cache or
139/// by making a new connection.
140pub fn get_keymint_device(security_level: SecurityLevel) -> Result<Asp> {
141 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
142 if let Some(dev) = devices_map.get(&security_level) {
143 Ok(dev.clone())
144 } else {
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800145 let dev = connect_keymint(security_level).context("In get_keymint_device.")?;
Janis Danisevskisba998992020-12-29 16:08:40 -0800146 devices_map.insert(security_level, dev.clone());
147 Ok(dev)
148 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800149}
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800150
151static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
152
153/// Make a new connection to a secure clock service.
154/// If no native SecureClock device can be found brings up the compatibility service and attempts
155/// to connect to the legacy wrapper.
156fn connect_secureclock() -> Result<Asp> {
157 let secureclock = map_binder_status_code(binder::get_interface(TIME_STAMP_SERVICE_NAME))
158 .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
159 .or_else(|e| {
160 match e.root_cause().downcast_ref::<Error>() {
161 Some(Error::BinderTransaction(StatusCode::NAME_NOT_FOUND)) => {
162 // This is a no-op if it was called before.
163 keystore2_km_compat::add_keymint_device_service();
164
165 let keystore_compat_service: Box<dyn IKeystoreCompatService> =
166 map_binder_status_code(binder::get_interface("android.security.compat"))
167 .context(
168 "In connect_secureclock: Trying to connect to compat service.",
169 )?;
170
171 // Legacy secure clock services were only implemented by TEE.
172 map_binder_status(keystore_compat_service.getSecureClock())
173 .map_err(|e| match e {
174 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
175 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
176 }
177 e => e,
178 })
179 .context("In connect_secureclock: Trying to get Legacy wrapper.")
180 }
181 _ => Err(e),
182 }
183 })?;
184
185 Ok(Asp::new(secureclock.as_binder()))
186}
187
188/// Get the timestamp service that verifies auth token timeliness towards security levels with
189/// different clocks.
190pub fn get_timestamp_service() -> Result<Asp> {
191 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
192 if let Some(dev) = &*ts_device {
193 Ok(dev.clone())
194 } else {
195 let dev = connect_secureclock().context("In get_timestamp_service.")?;
196 *ts_device = Some(dev.clone());
197 Ok(dev)
198 }
199}