xref: /aosp_15_r20/system/security/keystore2/src/maintenance.rs (revision e1997b9af69e3155ead6e072d106a0077849ffba)
1 // Copyright 2021, 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 implements IKeystoreMaintenance AIDL interface.
16 
17 use crate::database::{KeyEntryLoadBits, KeyType};
18 use crate::error::into_logged_binder;
19 use crate::error::map_km_error;
20 use crate::error::Error;
21 use crate::globals::get_keymint_device;
22 use crate::globals::{DB, LEGACY_IMPORTER, SUPER_KEY, ENCODED_MODULE_INFO};
23 use crate::ks_err;
24 use crate::permission::{KeyPerm, KeystorePerm};
25 use crate::super_key::SuperKeyManager;
26 use crate::utils::{
27     check_dump_permission, check_get_app_uids_affected_by_sid_permissions, check_key_permission,
28     check_keystore_permission, uid_to_android_user, watchdog as wd,
29 };
30 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
31     ErrorCode::ErrorCode, IKeyMintDevice::IKeyMintDevice, KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
32 };
33 use android_security_maintenance::aidl::android::security::maintenance::IKeystoreMaintenance::{
34     BnKeystoreMaintenance, IKeystoreMaintenance,
35 };
36 use android_security_maintenance::binder::{
37     BinderFeatures, Interface, Result as BinderResult, Strong, ThreadState,
38 };
39 use android_security_metrics::aidl::android::security::metrics::{
40     KeystoreAtomPayload::KeystoreAtomPayload::StorageStats
41 };
42 use android_system_keystore2::aidl::android::system::keystore2::KeyDescriptor::KeyDescriptor;
43 use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
44 use anyhow::{anyhow, Context, Result};
45 use bssl_crypto::digest;
46 use der::{DerOrd, Encode, asn1::OctetString, asn1::SetOfVec, Sequence};
47 use keystore2_crypto::Password;
48 use std::cmp::Ordering;
49 
50 /// Reexport Domain for the benefit of DeleteListener
51 pub use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
52 
53 /// Version number of KeyMint V4.
54 pub const KEYMINT_V4: i32 = 400;
55 
56 /// Module information structure for DER-encoding.
57 #[derive(Sequence, Debug)]
58 struct ModuleInfo {
59     name: OctetString,
60     version: i32,
61 }
62 
63 impl DerOrd for ModuleInfo {
64     // DER mandates "encodings of the component values of a set-of value shall appear in ascending
65     // order". `der_cmp` serves as a proxy for determining that ordering (though why the `der` crate
66     // requires this is unclear). Essentially, we just need to compare the `name` lengths, and then
67     // if those are equal, the `name`s themselves. (No need to consider `version`s since there can't
68     // be more than one `ModuleInfo` with the same `name` in the set-of `ModuleInfo`s.) We rely on
69     // `OctetString`'s `der_cmp` to do the aforementioned comparison.
der_cmp(&self, other: &Self) -> std::result::Result<Ordering, der::Error>70     fn der_cmp(&self, other: &Self) -> std::result::Result<Ordering, der::Error> {
71         self.name.der_cmp(&other.name)
72     }
73 }
74 
75 /// The Maintenance module takes a delete listener argument which observes user and namespace
76 /// deletion events.
77 pub trait DeleteListener {
78     /// Called by the maintenance module when an app/namespace is deleted.
delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>79     fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>;
80     /// Called by the maintenance module when a user is deleted.
delete_user(&self, user_id: u32) -> Result<()>81     fn delete_user(&self, user_id: u32) -> Result<()>;
82 }
83 
84 /// This struct is defined to implement the aforementioned AIDL interface.
85 pub struct Maintenance {
86     delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
87 }
88 
89 impl Maintenance {
90     /// Create a new instance of Keystore Maintenance service.
new_native_binder( delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>, ) -> Result<Strong<dyn IKeystoreMaintenance>>91     pub fn new_native_binder(
92         delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
93     ) -> Result<Strong<dyn IKeystoreMaintenance>> {
94         Ok(BnKeystoreMaintenance::new_binder(
95             Self { delete_listener },
96             BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
97         ))
98     }
99 
add_or_remove_user(&self, user_id: i32) -> Result<()>100     fn add_or_remove_user(&self, user_id: i32) -> Result<()> {
101         // Check permission. Function should return if this failed. Therefore having '?' at the end
102         // is very important.
103         check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
104 
105         DB.with(|db| {
106             SUPER_KEY.write().unwrap().remove_user(
107                 &mut db.borrow_mut(),
108                 &LEGACY_IMPORTER,
109                 user_id as u32,
110             )
111         })
112         .context(ks_err!("Trying to delete keys from db."))?;
113         self.delete_listener
114             .delete_user(user_id as u32)
115             .context(ks_err!("While invoking the delete listener."))
116     }
117 
init_user_super_keys( &self, user_id: i32, password: Password, allow_existing: bool, ) -> Result<()>118     fn init_user_super_keys(
119         &self,
120         user_id: i32,
121         password: Password,
122         allow_existing: bool,
123     ) -> Result<()> {
124         // Permission check. Must return on error. Do not touch the '?'.
125         check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
126 
127         let mut skm = SUPER_KEY.write().unwrap();
128         DB.with(|db| {
129             skm.initialize_user(
130                 &mut db.borrow_mut(),
131                 &LEGACY_IMPORTER,
132                 user_id as u32,
133                 &password,
134                 allow_existing,
135             )
136         })
137         .context(ks_err!("Failed to initialize user super keys"))
138     }
139 
140     // Deletes all auth-bound keys when the user's LSKF is removed.
on_user_lskf_removed(user_id: i32) -> Result<()>141     fn on_user_lskf_removed(user_id: i32) -> Result<()> {
142         // Permission check. Must return on error. Do not touch the '?'.
143         check_keystore_permission(KeystorePerm::ChangePassword).context(ks_err!())?;
144 
145         LEGACY_IMPORTER
146             .bulk_delete_user(user_id as u32, true)
147             .context(ks_err!("Failed to delete legacy keys."))?;
148 
149         DB.with(|db| db.borrow_mut().unbind_auth_bound_keys_for_user(user_id as u32))
150             .context(ks_err!("Failed to delete auth-bound keys."))
151     }
152 
clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()>153     fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> {
154         // Permission check. Must return on error. Do not touch the '?'.
155         check_keystore_permission(KeystorePerm::ClearUID).context("In clear_namespace.")?;
156 
157         LEGACY_IMPORTER
158             .bulk_delete_uid(domain, nspace)
159             .context(ks_err!("Trying to delete legacy keys."))?;
160         DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
161             .context(ks_err!("Trying to delete keys from db."))?;
162         self.delete_listener
163             .delete_namespace(domain, nspace)
164             .context(ks_err!("While invoking the delete listener."))
165     }
166 
call_with_watchdog<F>( sec_level: SecurityLevel, name: &'static str, op: &F, min_version: Option<i32>, ) -> Result<()> where F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,167     fn call_with_watchdog<F>(
168         sec_level: SecurityLevel,
169         name: &'static str,
170         op: &F,
171         min_version: Option<i32>,
172     ) -> Result<()>
173     where
174         F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
175     {
176         let (km_dev, hw_info, _) =
177             get_keymint_device(&sec_level).context(ks_err!("getting keymint device"))?;
178 
179         if let Some(min_version) = min_version {
180             if hw_info.versionNumber < min_version {
181                 log::info!("skipping {name} for {sec_level:?} since its keymint version {} is less than the minimum required version {min_version}", hw_info.versionNumber);
182                 return Ok(());
183             }
184         }
185 
186         let _wp = wd::watch_millis_with("Maintenance::call_with_watchdog", 500, (sec_level, name));
187         map_km_error(op(km_dev)).with_context(|| ks_err!("calling {}", name))?;
188         Ok(())
189     }
190 
call_on_all_security_levels<F>( name: &'static str, op: F, min_version: Option<i32>, ) -> Result<()> where F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,191     fn call_on_all_security_levels<F>(
192         name: &'static str,
193         op: F,
194         min_version: Option<i32>,
195     ) -> Result<()>
196     where
197         F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
198     {
199         let sec_levels = [
200             (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
201             (SecurityLevel::STRONGBOX, "STRONGBOX"),
202         ];
203         sec_levels.iter().try_fold((), |_result, (sec_level, sec_level_string)| {
204             let curr_result = Maintenance::call_with_watchdog(*sec_level, name, &op, min_version);
205             match curr_result {
206                 Ok(()) => log::info!(
207                     "Call to {} succeeded for security level {}.",
208                     name,
209                     &sec_level_string
210                 ),
211                 Err(ref e) => {
212                     if *sec_level == SecurityLevel::STRONGBOX
213                         && e.downcast_ref::<Error>()
214                             == Some(&Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
215                     {
216                         log::info!("Call to {} failed for StrongBox as it is not available", name,)
217                     } else {
218                         log::error!(
219                             "Call to {} failed for security level {}: {}.",
220                             name,
221                             &sec_level_string,
222                             e
223                         )
224                     }
225                 }
226             }
227             curr_result
228         })
229     }
230 
early_boot_ended() -> Result<()>231     fn early_boot_ended() -> Result<()> {
232         check_keystore_permission(KeystorePerm::EarlyBootEnded)
233             .context(ks_err!("Checking permission"))?;
234         log::info!("In early_boot_ended.");
235 
236         if let Err(e) =
237             DB.with(|db| SuperKeyManager::set_up_boot_level_cache(&SUPER_KEY, &mut db.borrow_mut()))
238         {
239             log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
240         }
241 
242         Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded(), None)
243     }
244 
migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()>245     fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
246         let calling_uid = ThreadState::get_calling_uid();
247 
248         match source.domain {
249             Domain::SELINUX | Domain::KEY_ID | Domain::APP => (),
250             _ => {
251                 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
252                     .context(ks_err!("Source domain must be one of APP, SELINUX, or KEY_ID."));
253             }
254         };
255 
256         match destination.domain {
257             Domain::SELINUX | Domain::APP => (),
258             _ => {
259                 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
260                     .context(ks_err!("Destination domain must be one of APP or SELINUX."));
261             }
262         };
263 
264         let user_id = uid_to_android_user(calling_uid);
265 
266         let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
267 
268         DB.with(|db| {
269             let (key_id_guard, _) = LEGACY_IMPORTER
270                 .with_try_import(source, calling_uid, super_key, || {
271                     db.borrow_mut().load_key_entry(
272                         source,
273                         KeyType::Client,
274                         KeyEntryLoadBits::NONE,
275                         calling_uid,
276                         |k, av| {
277                             check_key_permission(KeyPerm::Use, k, &av)?;
278                             check_key_permission(KeyPerm::Delete, k, &av)?;
279                             check_key_permission(KeyPerm::Grant, k, &av)
280                         },
281                     )
282                 })
283                 .context(ks_err!("Failed to load key blob."))?;
284             {
285                 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, calling_uid, |k| {
286                     check_key_permission(KeyPerm::Rebind, k, &None)
287                 })
288             }
289         })
290     }
291 
delete_all_keys() -> Result<()>292     fn delete_all_keys() -> Result<()> {
293         // Security critical permission check. This statement must return on fail.
294         check_keystore_permission(KeystorePerm::DeleteAllKeys)
295             .context(ks_err!("Checking permission"))?;
296         log::info!("In delete_all_keys.");
297 
298         Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys(), None)
299     }
300 
get_app_uids_affected_by_sid( user_id: i32, secure_user_id: i64, ) -> Result<std::vec::Vec<i64>>301     fn get_app_uids_affected_by_sid(
302         user_id: i32,
303         secure_user_id: i64,
304     ) -> Result<std::vec::Vec<i64>> {
305         // This method is intended to be called by Settings and discloses a list of apps
306         // associated with a user, so it requires the "android.permission.MANAGE_USERS"
307         // permission (to avoid leaking list of apps to unauthorized callers).
308         check_get_app_uids_affected_by_sid_permissions().context(ks_err!())?;
309         DB.with(|db| db.borrow_mut().get_app_uids_affected_by_sid(user_id, secure_user_id))
310             .context(ks_err!("Failed to get app UIDs affected by SID"))
311     }
312 
dump_state(&self, f: &mut dyn std::io::Write) -> std::io::Result<()>313     fn dump_state(&self, f: &mut dyn std::io::Write) -> std::io::Result<()> {
314         writeln!(f, "keystore2 running")?;
315         writeln!(f)?;
316 
317         // Display underlying device information
318         for sec_level in &[SecurityLevel::TRUSTED_ENVIRONMENT, SecurityLevel::STRONGBOX] {
319             let Ok((_dev, hw_info, uuid)) = get_keymint_device(sec_level) else { continue };
320 
321             writeln!(f, "Device info for {sec_level:?} with {uuid:?}")?;
322             writeln!(f, "  HAL version:              {}", hw_info.versionNumber)?;
323             writeln!(f, "  Implementation name:      {}", hw_info.keyMintName)?;
324             writeln!(f, "  Implementation author:    {}", hw_info.keyMintAuthorName)?;
325             writeln!(f, "  Timestamp token required: {}", hw_info.timestampTokenRequired)?;
326         }
327         writeln!(f)?;
328 
329         // Display database size information.
330         match crate::metrics_store::pull_storage_stats() {
331             Ok(atoms) => {
332                 writeln!(f, "Database size information (in bytes):")?;
333                 for atom in atoms {
334                     if let StorageStats(stats) = &atom.payload {
335                         let stype = format!("{:?}", stats.storage_type);
336                         if stats.unused_size == 0 {
337                             writeln!(f, "  {:<40}: {:>12}", stype, stats.size)?;
338                         } else {
339                             writeln!(
340                                 f,
341                                 "  {:<40}: {:>12} (unused {})",
342                                 stype, stats.size, stats.unused_size
343                             )?;
344                         }
345                     }
346                 }
347             }
348             Err(e) => {
349                 writeln!(f, "Failed to retrieve storage stats: {e:?}")?;
350             }
351         }
352         writeln!(f)?;
353 
354         // Display accumulated metrics.
355         writeln!(f, "Metrics information:")?;
356         writeln!(f)?;
357         write!(f, "{:?}", *crate::metrics_store::METRICS_STORE)?;
358         writeln!(f)?;
359 
360         // Reminder: any additional information added to the `dump_state()` output needs to be
361         // careful not to include confidential information (e.g. key material).
362 
363         Ok(())
364     }
365 
366     #[allow(dead_code)]
set_module_info(module_info: Vec<ModuleInfo>) -> Result<()>367     fn set_module_info(module_info: Vec<ModuleInfo>) -> Result<()> {
368         let encoding = Self::encode_module_info(module_info)
369             .map_err(|e| anyhow!({ e }))
370             .context(ks_err!("Failed to encode module_info"))?;
371         let hash = digest::Sha256::hash(&encoding).to_vec();
372 
373         {
374             let mut saved = ENCODED_MODULE_INFO.write().unwrap();
375             if let Some(saved_encoding) = &*saved {
376                 if *saved_encoding == encoding {
377                     log::warn!(
378                         "Module info already set, ignoring repeated attempt to set same info."
379                     );
380                     return Ok(());
381                 }
382                 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
383                     "Failed to set module info as it is already set to a different value."
384                 ));
385             }
386             *saved = Some(encoding);
387         }
388 
389         let kps =
390             vec![KeyParameter { tag: Tag::MODULE_HASH, value: KeyParameterValue::Blob(hash) }];
391 
392         Maintenance::call_on_all_security_levels(
393             "setAdditionalAttestationInfo",
394             |dev| dev.setAdditionalAttestationInfo(&kps),
395             Some(KEYMINT_V4),
396         )
397     }
398 
399     #[allow(dead_code)]
encode_module_info(module_info: Vec<ModuleInfo>) -> Result<Vec<u8>, der::Error>400     fn encode_module_info(module_info: Vec<ModuleInfo>) -> Result<Vec<u8>, der::Error> {
401         SetOfVec::<ModuleInfo>::from_iter(module_info.into_iter())?.to_der()
402     }
403 }
404 
405 impl Interface for Maintenance {
dump( &self, f: &mut dyn std::io::Write, _args: &[&std::ffi::CStr], ) -> Result<(), binder::StatusCode>406     fn dump(
407         &self,
408         f: &mut dyn std::io::Write,
409         _args: &[&std::ffi::CStr],
410     ) -> Result<(), binder::StatusCode> {
411         if !keystore2_flags::enable_dump() {
412             log::info!("skipping dump() as flag not enabled");
413             return Ok(());
414         }
415         log::info!("dump()");
416         let _wp = wd::watch("IKeystoreMaintenance::dump");
417         check_dump_permission().map_err(|_e| {
418             log::error!("dump permission denied");
419             binder::StatusCode::PERMISSION_DENIED
420         })?;
421 
422         self.dump_state(f).map_err(|e| {
423             log::error!("dump_state failed: {e:?}");
424             binder::StatusCode::UNKNOWN_ERROR
425         })
426     }
427 }
428 
429 impl IKeystoreMaintenance for Maintenance {
onUserAdded(&self, user_id: i32) -> BinderResult<()>430     fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
431         log::info!("onUserAdded(user={user_id})");
432         let _wp = wd::watch("IKeystoreMaintenance::onUserAdded");
433         self.add_or_remove_user(user_id).map_err(into_logged_binder)
434     }
435 
initUserSuperKeys( &self, user_id: i32, password: &[u8], allow_existing: bool, ) -> BinderResult<()>436     fn initUserSuperKeys(
437         &self,
438         user_id: i32,
439         password: &[u8],
440         allow_existing: bool,
441     ) -> BinderResult<()> {
442         log::info!("initUserSuperKeys(user={user_id}, allow_existing={allow_existing})");
443         let _wp = wd::watch("IKeystoreMaintenance::initUserSuperKeys");
444         self.init_user_super_keys(user_id, password.into(), allow_existing)
445             .map_err(into_logged_binder)
446     }
447 
onUserRemoved(&self, user_id: i32) -> BinderResult<()>448     fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
449         log::info!("onUserRemoved(user={user_id})");
450         let _wp = wd::watch("IKeystoreMaintenance::onUserRemoved");
451         self.add_or_remove_user(user_id).map_err(into_logged_binder)
452     }
453 
onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()>454     fn onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()> {
455         log::info!("onUserLskfRemoved(user={user_id})");
456         let _wp = wd::watch("IKeystoreMaintenance::onUserLskfRemoved");
457         Self::on_user_lskf_removed(user_id).map_err(into_logged_binder)
458     }
459 
clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()>460     fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
461         log::info!("clearNamespace({domain:?}, nspace={nspace})");
462         let _wp = wd::watch("IKeystoreMaintenance::clearNamespace");
463         self.clear_namespace(domain, nspace).map_err(into_logged_binder)
464     }
465 
earlyBootEnded(&self) -> BinderResult<()>466     fn earlyBootEnded(&self) -> BinderResult<()> {
467         log::info!("earlyBootEnded()");
468         let _wp = wd::watch("IKeystoreMaintenance::earlyBootEnded");
469         Self::early_boot_ended().map_err(into_logged_binder)
470     }
471 
migrateKeyNamespace( &self, source: &KeyDescriptor, destination: &KeyDescriptor, ) -> BinderResult<()>472     fn migrateKeyNamespace(
473         &self,
474         source: &KeyDescriptor,
475         destination: &KeyDescriptor,
476     ) -> BinderResult<()> {
477         log::info!("migrateKeyNamespace(src={source:?}, dest={destination:?})");
478         let _wp = wd::watch("IKeystoreMaintenance::migrateKeyNamespace");
479         Self::migrate_key_namespace(source, destination).map_err(into_logged_binder)
480     }
481 
deleteAllKeys(&self) -> BinderResult<()>482     fn deleteAllKeys(&self) -> BinderResult<()> {
483         log::warn!("deleteAllKeys() invoked, indicating initial setup or post-factory reset");
484         let _wp = wd::watch("IKeystoreMaintenance::deleteAllKeys");
485         Self::delete_all_keys().map_err(into_logged_binder)
486     }
487 
getAppUidsAffectedBySid( &self, user_id: i32, secure_user_id: i64, ) -> BinderResult<std::vec::Vec<i64>>488     fn getAppUidsAffectedBySid(
489         &self,
490         user_id: i32,
491         secure_user_id: i64,
492     ) -> BinderResult<std::vec::Vec<i64>> {
493         log::info!("getAppUidsAffectedBySid(secure_user_id={secure_user_id:?})");
494         let _wp = wd::watch("IKeystoreMaintenance::getAppUidsAffectedBySid");
495         Self::get_app_uids_affected_by_sid(user_id, secure_user_id).map_err(into_logged_binder)
496     }
497 }
498