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