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