• 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_migrator::LegacyMigrator;
22 use crate::super_key::SuperKeyManager;
23 use crate::utils::watchdog as wd;
24 use crate::utils::Asp;
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::{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_keymint::binder::{StatusCode, Strong};
37 use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
38 use anyhow::{Context, Result};
39 use binder::FromIBinder;
40 use keystore2_vintf::get_aidl_instances;
41 use lazy_static::lazy_static;
42 use std::sync::{Arc, Mutex, RwLock};
43 use std::{cell::RefCell, sync::Once};
44 use std::{collections::HashMap, path::Path, path::PathBuf};
45 
46 static DB_INIT: Once = Once::new();
47 
48 /// Open a connection to the Keystore 2.0 database. This is called during the initialization of
49 /// the thread local DB field. It should never be called directly. The first time this is called
50 /// we also call KeystoreDB::cleanup_leftovers to restore the key lifecycle invariant. See the
51 /// documentation of cleanup_leftovers for more details. The function also constructs a blob
52 /// garbage collector. The initializing closure constructs another database connection without
53 /// a gc. Although one GC is created for each thread local database connection, this closure
54 /// is run only once, as long as the ASYNC_TASK instance is the same. So only one additional
55 /// database connection is created for the garbage collector worker.
create_thread_local_db() -> KeystoreDB56 pub fn create_thread_local_db() -> KeystoreDB {
57     let db_path = DB_PATH.read().expect("Could not get the database directory.");
58 
59     let mut db = KeystoreDB::new(&db_path, Some(GC.clone())).expect("Failed to open database.");
60 
61     DB_INIT.call_once(|| {
62         log::info!("Touching Keystore 2.0 database for this first time since boot.");
63         db.insert_last_off_body(MonotonicRawTime::now());
64         log::info!("Calling cleanup leftovers.");
65         let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
66         if n != 0 {
67             log::info!(
68                 concat!(
69                     "Cleaned up {} failed entries. ",
70                     "This indicates keystore crashed during key generation."
71                 ),
72                 n
73             );
74         }
75     });
76     db
77 }
78 
79 thread_local! {
80     /// Database connections are not thread safe, but connecting to the
81     /// same database multiple times is safe as long as each connection is
82     /// used by only one thread. So we store one database connection per
83     /// thread in this thread local key.
84     pub static DB: RefCell<KeystoreDB> =
85             RefCell::new(create_thread_local_db());
86 }
87 
88 #[derive(Default)]
89 struct DevicesMap {
90     devices_by_uuid: HashMap<Uuid, (Asp, KeyMintHardwareInfo)>,
91     uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
92 }
93 
94 impl DevicesMap {
dev_by_sec_level( &self, sec_level: &SecurityLevel, ) -> Option<(Asp, KeyMintHardwareInfo, Uuid)>95     fn dev_by_sec_level(
96         &self,
97         sec_level: &SecurityLevel,
98     ) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
99         self.uuid_by_sec_level.get(sec_level).and_then(|uuid| self.dev_by_uuid(uuid))
100     }
101 
dev_by_uuid(&self, uuid: &Uuid) -> Option<(Asp, KeyMintHardwareInfo, Uuid)>102     fn dev_by_uuid(&self, uuid: &Uuid) -> Option<(Asp, KeyMintHardwareInfo, Uuid)> {
103         self.devices_by_uuid
104             .get(uuid)
105             .map(|(dev, hw_info)| ((*dev).clone(), (*hw_info).clone(), *uuid))
106     }
107 
devices<T: FromIBinder + ?Sized>(&self) -> Vec<Strong<T>>108     fn devices<T: FromIBinder + ?Sized>(&self) -> Vec<Strong<T>> {
109         self.devices_by_uuid.values().filter_map(|(asp, _)| asp.get_interface::<T>().ok()).collect()
110     }
111 
112     /// The requested security level and the security level of the actual implementation may
113     /// differ. So we map the requested security level to the uuid of the implementation
114     /// so that there cannot be any confusion as to which KeyMint instance is requested.
insert(&mut self, sec_level: SecurityLevel, dev: Asp, hw_info: KeyMintHardwareInfo)115     fn insert(&mut self, sec_level: SecurityLevel, dev: Asp, hw_info: KeyMintHardwareInfo) {
116         // For now we use the reported security level of the KM instance as UUID.
117         // TODO update this section once UUID was added to the KM hardware info.
118         let uuid: Uuid = sec_level.into();
119         self.devices_by_uuid.insert(uuid, (dev, hw_info));
120         self.uuid_by_sec_level.insert(sec_level, uuid);
121     }
122 }
123 
124 #[derive(Default)]
125 struct RemotelyProvisionedDevicesMap {
126     devices_by_sec_level: HashMap<SecurityLevel, Asp>,
127 }
128 
129 impl RemotelyProvisionedDevicesMap {
dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Asp>130     fn dev_by_sec_level(&self, sec_level: &SecurityLevel) -> Option<Asp> {
131         self.devices_by_sec_level.get(sec_level).map(|dev| (*dev).clone())
132     }
133 
insert(&mut self, sec_level: SecurityLevel, dev: Asp)134     fn insert(&mut self, sec_level: SecurityLevel, dev: Asp) {
135         self.devices_by_sec_level.insert(sec_level, dev);
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<SuperKeyManager> = Default::default();
145     /// Map of KeyMint devices.
146     static ref KEY_MINT_DEVICES: Mutex<DevicesMap> = Default::default();
147     /// Timestamp service.
148     static ref TIME_STAMP_DEVICE: Mutex<Option<Asp>> = Default::default();
149     /// RemotelyProvisionedComponent HAL devices.
150     static ref REMOTELY_PROVISIONED_COMPONENT_DEVICES: Mutex<RemotelyProvisionedDevicesMap> = Default::default();
151     /// A single on-demand worker thread that handles deferred tasks with two different
152     /// priorities.
153     pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
154     /// Singleton for enforcements.
155     pub static ref ENFORCEMENTS: Enforcements = 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 ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
159         &DB_PATH.read().expect("Could not get the database path for legacy blob loader.")));
160     /// Legacy migrator. Atomically migrates legacy blobs to the database.
161     pub static ref LEGACY_MIGRATOR: Arc<LegacyMigrator> =
162         Arc::new(LegacyMigrator::new(Arc::new(Default::default())));
163     /// Background thread which handles logging via statsd and logd
164     pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
165 
166     static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
167         (
168             Box::new(|uuid, blob| {
169                 let km_dev: Strong<dyn IKeyMintDevice> =
170                     get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?.get_interface()?;
171                 let _wp = wd::watch_millis("In invalidate key closure: calling deleteKey", 500);
172                 map_km_error(km_dev.deleteKey(&*blob))
173                     .context("In invalidate key closure: Trying to invalidate key blob.")
174             }),
175             KeystoreDB::new(&DB_PATH.read().expect("Could not get the database directory."), None)
176                 .expect("Failed to open database."),
177             SUPER_KEY.clone(),
178         )
179     }));
180 }
181 
182 static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
183 
184 /// Make a new connection to a KeyMint device of the given security level.
185 /// If no native KeyMint device can be found this function also brings
186 /// up the compatibility service and attempts to connect to the legacy wrapper.
connect_keymint(security_level: &SecurityLevel) -> Result<(Asp, KeyMintHardwareInfo)>187 fn connect_keymint(security_level: &SecurityLevel) -> Result<(Asp, KeyMintHardwareInfo)> {
188     let keymint_instances =
189         get_aidl_instances("android.hardware.security.keymint", 1, "IKeyMintDevice");
190 
191     let service_name = match *security_level {
192         SecurityLevel::TRUSTED_ENVIRONMENT => {
193             if keymint_instances.as_vec()?.iter().any(|instance| *instance == "default") {
194                 Some(format!("{}/default", KEYMINT_SERVICE_NAME))
195             } else {
196                 None
197             }
198         }
199         SecurityLevel::STRONGBOX => {
200             if keymint_instances.as_vec()?.iter().any(|instance| *instance == "strongbox") {
201                 Some(format!("{}/strongbox", KEYMINT_SERVICE_NAME))
202             } else {
203                 None
204             }
205         }
206         _ => {
207             return Err(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
208                 .context("In connect_keymint.")
209         }
210     };
211 
212     let (keymint, hal_version) = if let Some(service_name) = service_name {
213         (
214             map_binder_status_code(binder::get_interface(&service_name))
215                 .context("In connect_keymint: Trying to connect to genuine KeyMint service.")?,
216             Some(100i32), // The HAL version code for KeyMint V1 is 100.
217         )
218     } else {
219         // This is a no-op if it was called before.
220         keystore2_km_compat::add_keymint_device_service();
221 
222         let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
223             map_binder_status_code(binder::get_interface("android.security.compat"))
224                 .context("In connect_keymint: Trying to connect to compat service.")?;
225         (
226             map_binder_status(keystore_compat_service.getKeyMintDevice(*security_level))
227                 .map_err(|e| match e {
228                     Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
229                         Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
230                     }
231                     e => e,
232                 })
233                 .context("In connect_keymint: Trying to get Legacy wrapper.")?,
234             None,
235         )
236     };
237 
238     let wp = wd::watch_millis("In connect_keymint: calling getHardwareInfo()", 500);
239     let mut hw_info = map_km_error(keymint.getHardwareInfo())
240         .context("In connect_keymint: Failed to get hardware info.")?;
241     drop(wp);
242 
243     // The legacy wrapper sets hw_info.versionNumber to the underlying HAL version like so:
244     // 10 * <major> + <minor>, e.g., KM 3.0 = 30. So 30, 40, and 41 are the only viable values.
245     // For KeyMint the versionNumber is implementation defined and thus completely meaningless
246     // to Keystore 2.0. So at this point the versionNumber field is set to the HAL version, so
247     // that higher levels have a meaningful guide as to which feature set to expect from the
248     // implementation. As of this writing the only meaningful version number is 100 for KeyMint V1,
249     // and future AIDL versions should follow the pattern <AIDL version> * 100.
250     if let Some(hal_version) = hal_version {
251         hw_info.versionNumber = hal_version;
252     }
253 
254     Ok((Asp::new(keymint.as_binder()), hw_info))
255 }
256 
257 /// Get a keymint device for the given security level either from our cache or
258 /// by making a new connection. Returns the device, the hardware info and the uuid.
259 /// TODO the latter can be removed when the uuid is part of the hardware info.
get_keymint_device( security_level: &SecurityLevel, ) -> Result<(Asp, KeyMintHardwareInfo, Uuid)>260 pub fn get_keymint_device(
261     security_level: &SecurityLevel,
262 ) -> Result<(Asp, KeyMintHardwareInfo, Uuid)> {
263     let mut devices_map = KEY_MINT_DEVICES.lock().unwrap();
264     if let Some((dev, hw_info, uuid)) = devices_map.dev_by_sec_level(&security_level) {
265         Ok((dev, hw_info, uuid))
266     } else {
267         let (dev, hw_info) = connect_keymint(security_level).context("In get_keymint_device.")?;
268         devices_map.insert(*security_level, dev, hw_info);
269         // Unwrap must succeed because we just inserted it.
270         Ok(devices_map.dev_by_sec_level(security_level).unwrap())
271     }
272 }
273 
274 /// Get a keymint device for the given uuid. This will only access the cache, but will not
275 /// attempt to establish a new connection. It is assumed that the cache is already populated
276 /// when this is called. This is a fair assumption, because service.rs iterates through all
277 /// security levels when it gets instantiated.
get_keymint_dev_by_uuid(uuid: &Uuid) -> Result<(Asp, KeyMintHardwareInfo)>278 pub fn get_keymint_dev_by_uuid(uuid: &Uuid) -> Result<(Asp, KeyMintHardwareInfo)> {
279     let devices_map = KEY_MINT_DEVICES.lock().unwrap();
280     if let Some((dev, hw_info, _)) = devices_map.dev_by_uuid(uuid) {
281         Ok((dev, hw_info))
282     } else {
283         Err(Error::sys()).context("In get_keymint_dev_by_uuid: No KeyMint instance found.")
284     }
285 }
286 
287 /// Return all known keymint devices.
get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>>288 pub fn get_keymint_devices() -> Vec<Strong<dyn IKeyMintDevice>> {
289     KEY_MINT_DEVICES.lock().unwrap().devices()
290 }
291 
292 static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
293 
294 /// Make a new connection to a secure clock service.
295 /// If no native SecureClock device can be found brings up the compatibility service and attempts
296 /// to connect to the legacy wrapper.
connect_secureclock() -> Result<Asp>297 fn connect_secureclock() -> Result<Asp> {
298     let secureclock_instances =
299         get_aidl_instances("android.hardware.security.secureclock", 1, "ISecureClock");
300 
301     let secure_clock_available =
302         secureclock_instances.as_vec()?.iter().any(|instance| *instance == "default");
303 
304     let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
305 
306     let secureclock = if secure_clock_available {
307         map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
308             .context("In connect_secureclock: Trying to connect to genuine secure clock service.")
309     } else {
310         // This is a no-op if it was called before.
311         keystore2_km_compat::add_keymint_device_service();
312 
313         let keystore_compat_service: Strong<dyn IKeystoreCompatService> =
314             map_binder_status_code(binder::get_interface("android.security.compat"))
315                 .context("In connect_secureclock: Trying to connect to compat service.")?;
316 
317         // Legacy secure clock services were only implemented by TEE.
318         map_binder_status(keystore_compat_service.getSecureClock())
319             .map_err(|e| match e {
320                 Error::BinderTransaction(StatusCode::NAME_NOT_FOUND) => {
321                     Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE)
322                 }
323                 e => e,
324             })
325             .context("In connect_secureclock: Trying to get Legacy wrapper.")
326     }?;
327 
328     Ok(Asp::new(secureclock.as_binder()))
329 }
330 
331 /// Get the timestamp service that verifies auth token timeliness towards security levels with
332 /// different clocks.
get_timestamp_service() -> Result<Asp>333 pub fn get_timestamp_service() -> Result<Asp> {
334     let mut ts_device = TIME_STAMP_DEVICE.lock().unwrap();
335     if let Some(dev) = &*ts_device {
336         Ok(dev.clone())
337     } else {
338         let dev = connect_secureclock().context("In get_timestamp_service.")?;
339         *ts_device = Some(dev.clone());
340         Ok(dev)
341     }
342 }
343 
344 static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
345     "android.hardware.security.keymint.IRemotelyProvisionedComponent";
346 
connect_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp>347 fn connect_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp> {
348     let remotely_prov_instances =
349         get_aidl_instances("android.hardware.security.keymint", 1, "IRemotelyProvisionedComponent");
350 
351     let service_name = match *security_level {
352         SecurityLevel::TRUSTED_ENVIRONMENT => {
353             if remotely_prov_instances.as_vec()?.iter().any(|instance| *instance == "default") {
354                 Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
355             } else {
356                 None
357             }
358         }
359         SecurityLevel::STRONGBOX => {
360             if remotely_prov_instances.as_vec()?.iter().any(|instance| *instance == "strongbox") {
361                 Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
362             } else {
363                 None
364             }
365         }
366         _ => None,
367     }
368     .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
369     .context("In connect_remotely_provisioned_component.")?;
370 
371     let rem_prov_hal: Strong<dyn IRemotelyProvisionedComponent> =
372         map_binder_status_code(binder::get_interface(&service_name))
373             .context(concat!(
374                 "In connect_remotely_provisioned_component: Trying to connect to",
375                 " RemotelyProvisionedComponent service."
376             ))
377             .map_err(|e| e)?;
378     Ok(Asp::new(rem_prov_hal.as_binder()))
379 }
380 
381 /// Get a remote provisiong component device for the given security level either from the cache or
382 /// by making a new connection. Returns the device.
get_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp>383 pub fn get_remotely_provisioned_component(security_level: &SecurityLevel) -> Result<Asp> {
384     let mut devices_map = REMOTELY_PROVISIONED_COMPONENT_DEVICES.lock().unwrap();
385     if let Some(dev) = devices_map.dev_by_sec_level(&security_level) {
386         Ok(dev)
387     } else {
388         let dev = connect_remotely_provisioned_component(security_level)
389             .context("In get_remotely_provisioned_component.")?;
390         devices_map.insert(*security_level, dev);
391         // Unwrap must succeed because we just inserted it.
392         Ok(devices_map.dev_by_sec_level(security_level).unwrap())
393     }
394 }
395