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