1 // 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
19 use crate::async_task::AsyncTask;
20 use crate::gc::Gc;
21 use crate::km_compat::{BacklevelKeyMintWrapper, KeyMintV1};
22 use crate::ks_err;
23 use crate::legacy_blob::LegacyBlobLoader;
24 use crate::legacy_importer::LegacyImporter;
25 use crate::super_key::SuperKeyManager;
26 use crate::utils::{retry_get_interface, watchdog as wd};
27 use crate::{
28 database::KeystoreDB,
29 database::Uuid,
30 error::{map_binder_status, map_binder_status_code, Error, ErrorCode},
31 };
32 use crate::{enforcements::Enforcements, error::map_km_error};
33 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
34 IKeyMintDevice::BpKeyMintDevice, IKeyMintDevice::IKeyMintDevice,
35 KeyMintHardwareInfo::KeyMintHardwareInfo, SecurityLevel::SecurityLevel,
36 };
37 use android_hardware_security_keymint::binder::{StatusCode, Strong};
38 use android_hardware_security_rkp::aidl::android::hardware::security::keymint::{
39 IRemotelyProvisionedComponent::BpRemotelyProvisionedComponent,
40 IRemotelyProvisionedComponent::IRemotelyProvisionedComponent,
41 };
42 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
43 ISecureClock::BpSecureClock, ISecureClock::ISecureClock,
44 };
45 use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
46 use anyhow::{Context, Result};
47 use binder::FromIBinder;
48 use binder::{get_declared_instances, is_declared};
49 use std::sync::{Arc, LazyLock, Mutex, RwLock};
50 use std::{cell::RefCell, sync::Once};
51 use std::{collections::HashMap, path::Path, path::PathBuf};
52
53 static DB_INIT: Once = Once::new();
54
55 /// Open a connection to the Keystore 2.0 database. This is called during the initialization of
56 /// the thread local DB field. It should never be called directly. The first time this is called
57 /// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
58 /// documentation of cleanup_leftovers for more details. The function also constructs a blob
59 /// garbage collector. The initializing closure constructs another database connection without
60 /// a gc. Although one GC is created for each thread local database connection, this closure
61 /// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
62 /// database connection is created for the garbage collector worker.
create_thread_local_db() -> KeystoreDB63 pub fn create_thread_local_db() -> KeystoreDB {
64 let db_path = DB_PATH.read().expect("Could not get the database directory");
65
66 let result = KeystoreDB::new(&db_path, Some(GC.clone()));
67 let mut db = match result {
68 Ok(db) => db,
69 Err(e) => {
70 log::error!("Failed to open Keystore database at {db_path:?}: {e:?}");
71 log::error!("Has /data been mounted correctly?");
72 panic!("Failed to open database for Keystore, cannot continue: {e:?}")
73 }
74 };
75
76 DB_INIT.call_once(|| {
77 log::info!("Touching Keystore 2.0 database for this first time since boot.");
78 log::info!("Calling cleanup leftovers.");
79 let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup");
80 if n != 0 {
81 log::info!(
82 "Cleaned up {n} failed entries, indicating keystore crash on key generation"
83 );
84 }
85 });
86 db
87 }
88
89 thread_local! {
90 /// Database connections are not thread safe, but connecting to the
91 /// same database multiple times is safe as long as each connection is
92 /// used by only one thread. So we store one database connection per
93 /// thread in this thread local key.
94 pub static DB: RefCell<KeystoreDB> = RefCell::new(create_thread_local_db());
95 }
96
97 struct DevicesMap<T: FromIBinder + ?Sized> {
98 devices_by_uuid: HashMap<Uuid, (Strong<T>, KeyMintHardwareInfo)>,
99 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
100 }
101
102 impl<T: FromIBinder + ?Sized> DevicesMap<T> {
dev_by_sec_level( &self, sec_level: &SecurityLevel, ) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)>103 fn dev_by_sec_level(
104 &self,
105 sec_level: &SecurityLevel,
106 ) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
107 self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
108 }
109
dev_by_uuid(&self, uuid: &Uuid) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)>110 fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Strong<T>, KeyMintHardwareInfo, Uuid)> {
111 self.devices_by_uuid
112 .get(uuid)
113 .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
114 }
115
devices(&self) -> Vec<Strong<T>>116 fn devices(&self) -> Vec<Strong<T>> {
117 self.devices_by_uuid.values().map(|(dev, _)| dev.clone()).collect()
118 }
119
120 /// The requested security level and the security level of the actual implementation may
121 /// differ. So we map the requested security level to the uuid of the implementation
122 /// so that there cannot be any confusion as to which KeyMint instance is requested.
insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>, hw_info: KeyMintHardwareInfo)123 fn insert(&mut self, sec_level: SecurityLevel, dev: Strong<T>, hw_info: KeyMintHardwareInfo) {
124 // For now we use the reported security level of the KM instance as UUID.
125 // TODO update this section once UUID was added to the KM hardware info.
126 let uuid: Uuid = sec_level.into();
127 self.devices_by_uuid.insert(uuid, (dev, hw_info));
128 self.uuid_by_sec_level.insert(sec_level, uuid);
129 }
130 }
131
132 impl<T: FromIBinder + ?Sized> Default for DevicesMap<T> {
default() -> Self133 fn default() -> Self {
134 Self {
135 devices_by_uuid: HashMap::<Uuid, (Strong<T>, KeyMintHardwareInfo)>::new(),
136 uuid_by_sec_level: Default::default(),
137 }
138 }
139 }
140
141 /// The path where keystore stores all its keys.
142 pub static DB_PATH: LazyLock<RwLock<PathBuf>> =
143 LazyLock::new(|| RwLock::new(Path::new("/data/misc/keystore").to_path_buf()));
144 /// Runtime database of unwrapped super keys.
145 pub static SUPER_KEY: LazyLock<Arc<RwLock<SuperKeyManager>>> = LazyLock::new(Default::default);
146 /// Map of KeyMint devices.
147 static KEY_MINT_DEVICES: LazyLock<Mutex<DevicesMap<dyn IKeyMintDevice>>> =
148 LazyLock::new(Default::default);
149 /// Timestamp service.
150 static TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Mutex::new(None);
151 /// A single on-demand worker thread that handles deferred tasks with two different
152 /// priorities.
153 pub static ASYNC_TASK: LazyLock<Arc<AsyncTask>> = LazyLock::new(Default::default);
154 /// Singleton for enforcements.
155 pub static ENFORCEMENTS: LazyLock<Enforcements> = LazyLock::new(Default::default);
156 /// LegacyBlobLoader is initialized and exists globally.
157 /// The same directory used by the database is used by the LegacyBlobLoader as well.
158 pub static LEGACY_BLOB_LOADER: LazyLock<Arc<LegacyBlobLoader>> = LazyLock::new(|| {
159 Arc::new(LegacyBlobLoader::new(
160 &DB_PATH.read().expect("Could not determine database path for legacy blob loader"),
161 ))
162 });
163 /// Legacy migrator. Atomically migrates legacy blobs to the database.
164 pub static LEGACY_IMPORTER: LazyLock<Arc<LegacyImporter>> =
165 LazyLock::new(|| Arc::new(LegacyImporter::new(Arc::new(Default::default()))));
166 /// Background thread which handles logging via statsd and logd
167 pub static LOGS_HANDLER: LazyLock<Arc<AsyncTask>> = LazyLock::new(Default::default);
168 /// DER-encoded module information returned by `getSupplementaryAttestationInfo(Tag.MODULE_HASH)`.
169 pub static ENCODED_MODULE_INFO: RwLock<Option<Vec<u8>>> = RwLock::new(None);
170
171 static GC: LazyLock<Arc<Gc>> = LazyLock::new(|| {
172 Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
173 (
174 Box::new(|uuid, blob| {
175 let km_dev = get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?;
176 let _wp = wd::watch("invalidate key closure: calling IKeyMintDevice::deleteKey");
177 map_km_error(km_dev.deleteKey(blob))
178 .context(ks_err!("Trying to invalidate key blob."))
179 }),
180 KeystoreDB::new(
181 &DB_PATH.read().expect("Could not determine database path for GC"),
182 None,
183 )
184 .expect("Failed to open database"),
185 SUPER_KEY.clone(),
186 )
187 }))
188 });
189
190 /// Determine the service name for a KeyMint device of the given security level
191 /// gotten by binder service from the device and determining what services
192 /// are available.
keymint_service_name(security_level: &SecurityLevel) -> Result<Option<String>>193 fn keymint_service_name(security_level: &SecurityLevel) -> Result<Option<String>> {
194 let keymint_descriptor: &str = <BpKeyMintDevice as IKeyMintDevice>::get_descriptor();
195 let keymint_instances = get_declared_instances(keymint_descriptor).unwrap();
196
197 let service_name = match *security_level {
198 SecurityLevel::TRUSTED_ENVIRONMENT => {
199 if keymint_instances.iter().any(|instance| *instance == "default") {
200 Some(format!("{}/default", keymint_descriptor))
201 } else {
202 None
203 }
204 }
205 SecurityLevel::STRONGBOX => {
206 if keymint_instances.iter().any(|instance| *instance == "strongbox") {
207 Some(format!("{}/strongbox", keymint_descriptor))
208 } else {
209 None
210 }
211 }
212 _ => {
213 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!(
214 "Trying to find keymint for security level: {:?}",
215 security_level
216 ));
217 }
218 };
219
220 Ok(service_name)
221 }
222
223 /// Make a new connection to a KeyMint device of the given security level.
224 /// If no native KeyMint device can be found this function also brings
225 /// up the compatibility service and attempts to connect to the legacy wrapper.
connect_keymint( security_level: &SecurityLevel, ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)>226 fn connect_keymint(
227 security_level: &SecurityLevel,
228 ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
229 // Show the keymint interface that is registered in the binder
230 // service and use the security level to get the service name.
231 let service_name = keymint_service_name(security_level)
232 .context(ks_err!("Get service name from binder service"))?;
233
234 let (keymint, hal_version) = if let Some(service_name) = service_name {
235 let km: Strong<dyn IKeyMintDevice> =
236 if SecurityLevel::TRUSTED_ENVIRONMENT == *security_level {
237 map_binder_status_code(retry_get_interface(&service_name))
238 } else {
239 map_binder_status_code(binder::get_interface(&service_name))
240 }
241 .context(ks_err!("Trying to connect to genuine KeyMint service."))?;
242 // Map the HAL version code for KeyMint to be <AIDL version> * 100, so
243 // - V1 is 100
244 // - V2 is 200
245 // - V3 is 300
246 // etc.
247 let km_version = km.getInterfaceVersion()?;
248 (km, Some(km_version * 100))
249 } else {
250 // This is a no-op if it was called before.
251 keystore2_km_compat::add_keymint_device_service();
252
253 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
254 map_binder_status_code(binder::get_interface("android.security.compat"))
255 .context(ks_err!("Trying to connect to compat service."))?;
256 (
257 map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
258 .map_err(|e| match e {
259 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
260 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
261 }
262 e => e,
263 })
264 .context(ks_err!(
265 "Trying to get Legacy wrapper. Attempt to get keystore \
266 compat service for security level {:?}",
267 *security_level
268 ))?,
269 None,
270 )
271 };
272
273 // If the KeyMint device is back-level, use a wrapper that intercepts and
274 // emulates things that are not supported by the hardware.
275 let keymint = match hal_version {
276 Some(400) | Some(300) | Some(200) => {
277 // KeyMint v2+: use as-is (we don't have any software emulation of v3 or v4-specific KeyMint features).
278 log::info!(
279 "KeyMint device is current version ({:?}) for security level: {:?}",
280 hal_version,
281 security_level
282 );
283 keymint
284 }
285 Some(100) => {
286 // KeyMint v1: perform software emulation.
287 log::info!(
288 "Add emulation wrapper around {:?} device for security level: {:?}",
289 hal_version,
290 security_level
291 );
292 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
293 .context(ks_err!("Trying to create V1 compatibility wrapper."))?
294 }
295 None => {
296 // Compatibility wrapper around a KeyMaster device: this roughly
297 // behaves like KeyMint V1 (e.g. it includes AGREE_KEY support,
298 // albeit in software.)
299 log::info!(
300 "Add emulation wrapper around Keymaster device for security level: {:?}",
301 security_level
302 );
303 BacklevelKeyMintWrapper::wrap(KeyMintV1::new(*security_level), keymint)
304 .context(ks_err!("Trying to create km_compat V1 compatibility wrapper ."))?
305 }
306 _ => {
307 return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)).context(ks_err!(
308 "unexpected hal_version {:?} for security level: {:?}",
309 hal_version,
310 security_level
311 ));
312 }
313 };
314
315 let wp = wd::watch("connect_keymint: calling IKeyMintDevice::getHardwareInfo()");
316 let mut hw_info =
317 map_km_error(keymint.getHardwareInfo()).context(ks_err!("Failed to get hardware info."))?;
318 drop(wp);
319
320 // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
321 // 10 * <major> + <minor>, e.g., KM 3.0 = 30. So 30, 40, and 41 are the only viable values.
322 //
323 // For KeyMint the returned versionNumber is implementation defined and thus completely
324 // meaningless to Keystore 2.0. So set the versionNumber field that is returned to
325 // the rest of the code to be the <AIDL version> * 100, so KeyMint V1 is 100, KeyMint V2 is 200
326 // and so on.
327 //
328 // This ensures that versionNumber value across KeyMaster and KeyMint is monotonically
329 // increasing (and so comparisons like `versionNumber >= KEY_MINT_1` are valid).
330 if let Some(hal_version) = hal_version {
331 hw_info.versionNumber = hal_version;
332 }
333
334 Ok((keymint, hw_info))
335 }
336
337 /// Get a keymint device for the given security level either from our cache or
338 /// by making a new connection. Returns the device, the hardware info and the uuid.
339 /// TODO the latter can be removed when the uuid is part of the hardware info.
get_keymint_device( security_level: &SecurityLevel, ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)>340 pub fn get_keymint_device(
341 security_level: &SecurityLevel,
342 ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo, Uuid)> {
343 let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
344 if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(security_level) {
345 Ok((dev, hw_info, uuid))
346 } else {
347 let (dev, hw_info) =
348 connect_keymint(security_level).context(ks_err!("Cannot connect to Keymint"))?;
349 devices_map.insert(*security_level, dev, hw_info);
350 // Unwrap must succeed because we just inserted it.
351 Ok(devices_map.dev_by_sec_level(security_level).unwrap())
352 }
353 }
354
355 /// Get a keymint device for the given uuid. This will only access the cache, but will not
356 /// attempt to establish a new connection. It is assumed that the cache is already populated
357 /// when this is called. This is a fair assumption, because service.rs iterates through all
358 /// security levels when it gets instantiated.
get_keymint_dev_by_uuid( uuid: &Uuid, ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)>359 pub fn get_keymint_dev_by_uuid(
360 uuid: &Uuid,
361 ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
362 let devices_map = KEY_MINT_DEVICES.lock().unwrap();
363 if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
364 Ok((dev, hw_info))
365 } else {
366 Err(Error::sys()).context(ks_err!("No KeyMint instance found."))
367 }
368 }
369
370 /// Return all known keymint devices.
get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>>371 pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
372 KEY_MINT_DEVICES.lock().unwrap().devices()
373 }
374
375 /// Make a new connection to a secure clock service.
376 /// If no native SecureClock device can be found brings up the compatibility service and attempts
377 /// to connect to the legacy wrapper.
connect_secureclock() -> Result<Strong<dyn ISecureClock>>378 fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> {
379 let secure_clock_descriptor: &str = <BpSecureClock as ISecureClock>::get_descriptor();
380 let secureclock_instances = get_declared_instances(secure_clock_descriptor).unwrap();
381
382 let secure_clock_available =
383 secureclock_instances.iter().any(|instance| *instance == "default");
384
385 let default_time_stamp_service_name = format!("{}/default", secure_clock_descriptor);
386
387 let secureclock = if secure_clock_available {
388 map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
389 .context(ks_err!("Trying to connect to genuine secure clock service."))
390 } else {
391 // This is a no-op if it was called before.
392 keystore2_km_compat::add_keymint_device_service();
393
394 let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
395 map_binder_status_code(binder::get_interface("android.security.compat"))
396 .context(ks_err!("Trying to connect to compat service."))?;
397
398 // Legacy secure clock services were only implemented by TEE.
399 map_binder_status(keystore_compat_service.getSecureClock())
400 .map_err(|e| match e {
401 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
402 Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
403 }
404 e => e,
405 })
406 .context(ks_err!("Failed attempt to get legacy secure clock."))
407 }?;
408
409 Ok(secureclock)
410 }
411
412 /// Get the timestamp service that verifies auth token timeliness towards security levels with
413 /// different clocks.
get_timestamp_service() -> Result<Strong<dyn ISecureClock>>414 pub fn get_timestamp_service() -> Result<Strong<dyn ISecureClock>> {
415 let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
416 if let Some(dev) = &*ts_device {
417 Ok(dev.clone())
418 } else {
419 let dev = connect_secureclock().context(ks_err!())?;
420 *ts_device = Some(dev.clone());
421 Ok(dev)
422 }
423 }
424
425 /// Get the service name of a remotely provisioned component corresponding to given security level.
get_remotely_provisioned_component_name(security_level: &SecurityLevel) -> Result<String>426 pub fn get_remotely_provisioned_component_name(security_level: &SecurityLevel) -> Result<String> {
427 let remote_prov_descriptor: &str =
428 <BpRemotelyProvisionedComponent as IRemotelyProvisionedComponent>::get_descriptor();
429
430 match *security_level {
431 SecurityLevel::TRUSTED_ENVIRONMENT => {
432 let instance = format!("{}/default", remote_prov_descriptor);
433 if is_declared(&instance)? {
434 Some(instance)
435 } else {
436 None
437 }
438 }
439 SecurityLevel::STRONGBOX => {
440 let instance = format!("{}/strongbox", remote_prov_descriptor);
441 if is_declared(&instance)? {
442 Some(instance)
443 } else {
444 None
445 }
446 }
447 _ => None,
448 }
449 .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
450 .context(ks_err!("Failed to get rpc for sec level {:?}", *security_level))
451 }
452