blob: acca942a4d78d0876c5a558f4b14163f6f310aba [file] [log] [blame]
Hasini Gunasingheda895552021-01-27 19:34:37 +00001// 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
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080015//! This module implements IKeystoreMaintenance AIDL interface.
Hasini Gunasingheda895552021-01-27 19:34:37 +000016
Eric Biggersb5613da2024-03-13 19:31:42 +000017use crate::database::{KeyEntryLoadBits, KeyType};
David Drysdaledb7ddde2024-06-07 16:22:49 +010018use crate::error::into_logged_binder;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -080019use crate::error::map_km_error;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070020use crate::error::Error;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -080021use crate::globals::get_keymint_device;
David Drysdale37fcf5b2024-12-11 11:07:56 +000022use crate::globals::{DB, ENCODED_MODULE_INFO, LEGACY_IMPORTER, SUPER_KEY};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000023use crate::ks_err;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070024use crate::permission::{KeyPerm, KeystorePerm};
Eric Biggers9f7ebeb2024-06-20 14:59:32 +000025use crate::super_key::SuperKeyManager;
John Wu16db29e2022-01-13 15:21:43 -080026use crate::utils::{
David Drysdale0fefae32024-09-16 13:32:27 +010027 check_dump_permission, check_get_app_uids_affected_by_sid_permissions, check_key_permission,
Eran Messericfe79f12024-02-05 17:50:41 +000028 check_keystore_permission, uid_to_android_user, watchdog as wd,
John Wu16db29e2022-01-13 15:21:43 -080029};
Paul Crowley46c703e2021-08-06 15:13:53 -070030use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Karuna Wadheraca704492024-11-20 06:50:29 +000031 ErrorCode::ErrorCode, IKeyMintDevice::IKeyMintDevice, KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Paul Crowley46c703e2021-08-06 15:13:53 -070032};
David Drysdale1ce15612024-12-05 18:50:40 +000033use apex_aidl_interface::aidl::android::apex::{
34 IApexService::IApexService,
35};
Eric Biggers2f9498a2023-10-09 23:16:05 +000036use android_security_maintenance::aidl::android::security::maintenance::IKeystoreMaintenance::{
37 BnKeystoreMaintenance, IKeystoreMaintenance,
Hasini Gunasingheda895552021-01-27 19:34:37 +000038};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000039use android_security_maintenance::binder::{
40 BinderFeatures, Interface, Result as BinderResult, Strong, ThreadState,
41};
David Drysdale0fefae32024-09-16 13:32:27 +010042use android_security_metrics::aidl::android::security::metrics::{
43 KeystoreAtomPayload::KeystoreAtomPayload::StorageStats
44};
Janis Danisevskis5898d152021-06-15 08:23:46 -070045use android_system_keystore2::aidl::android::system::keystore2::KeyDescriptor::KeyDescriptor;
Hasini Gunasingheda895552021-01-27 19:34:37 +000046use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Karuna Wadheraca704492024-11-20 06:50:29 +000047use anyhow::{anyhow, Context, Result};
David Drysdale1ce15612024-12-05 18:50:40 +000048use binder::wait_for_interface;
Karuna Wadheraca704492024-11-20 06:50:29 +000049use bssl_crypto::digest;
50use der::{DerOrd, Encode, asn1::OctetString, asn1::SetOfVec, Sequence};
Paul Crowleyf61fee72021-03-17 14:38:44 -070051use keystore2_crypto::Password;
David Drysdale1ce15612024-12-05 18:50:40 +000052use rustutils::system_properties::PropertyWatcher;
Karuna Wadheraca704492024-11-20 06:50:29 +000053use std::cmp::Ordering;
Hasini Gunasingheda895552021-01-27 19:34:37 +000054
Janis Danisevskis5898d152021-06-15 08:23:46 -070055/// Reexport Domain for the benefit of DeleteListener
56pub use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
57
Karuna Wadhera8b319092024-12-11 04:42:45 +000058#[cfg(test)]
59mod tests;
60
Karuna Wadheraca704492024-11-20 06:50:29 +000061/// Version number of KeyMint V4.
62pub const KEYMINT_V4: i32 = 400;
63
64/// Module information structure for DER-encoding.
David Drysdale1ce15612024-12-05 18:50:40 +000065#[derive(Sequence, Debug, PartialEq, Eq)]
Karuna Wadheraca704492024-11-20 06:50:29 +000066struct ModuleInfo {
67 name: OctetString,
David Drysdale1ce15612024-12-05 18:50:40 +000068 version: i64,
Karuna Wadheraca704492024-11-20 06:50:29 +000069}
70
71impl DerOrd for ModuleInfo {
72 // DER mandates "encodings of the component values of a set-of value shall appear in ascending
73 // order". `der_cmp` serves as a proxy for determining that ordering (though why the `der` crate
74 // requires this is unclear). Essentially, we just need to compare the `name` lengths, and then
75 // if those are equal, the `name`s themselves. (No need to consider `version`s since there can't
76 // be more than one `ModuleInfo` with the same `name` in the set-of `ModuleInfo`s.) We rely on
77 // `OctetString`'s `der_cmp` to do the aforementioned comparison.
78 fn der_cmp(&self, other: &Self) -> std::result::Result<Ordering, der::Error> {
79 self.name.der_cmp(&other.name)
80 }
81}
82
Janis Danisevskis5898d152021-06-15 08:23:46 -070083/// The Maintenance module takes a delete listener argument which observes user and namespace
84/// deletion events.
85pub trait DeleteListener {
86 /// Called by the maintenance module when an app/namespace is deleted.
87 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>;
88 /// Called by the maintenance module when a user is deleted.
89 fn delete_user(&self, user_id: u32) -> Result<()>;
90}
91
Hasini Gunasingheda895552021-01-27 19:34:37 +000092/// This struct is defined to implement the aforementioned AIDL interface.
Janis Danisevskis5898d152021-06-15 08:23:46 -070093pub struct Maintenance {
94 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
95}
Hasini Gunasingheda895552021-01-27 19:34:37 +000096
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080097impl Maintenance {
Janis Danisevskis5898d152021-06-15 08:23:46 -070098 /// Create a new instance of Keystore Maintenance service.
99 pub fn new_native_binder(
100 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
101 ) -> Result<Strong<dyn IKeystoreMaintenance>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000102 Ok(BnKeystoreMaintenance::new_binder(
Janis Danisevskis5898d152021-06-15 08:23:46 -0700103 Self { delete_listener },
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000104 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
105 ))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000106 }
107
Janis Danisevskis5898d152021-06-15 08:23:46 -0700108 fn add_or_remove_user(&self, user_id: i32) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000109 // Check permission. Function should return if this failed. Therefore having '?' at the end
110 // is very important.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000111 check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800112
Janis Danisevskiseed69842021-02-18 20:04:10 -0800113 DB.with(|db| {
Nathan Huckleberry204a0442023-03-30 17:27:47 +0000114 SUPER_KEY.write().unwrap().remove_user(
Janis Danisevskiseed69842021-02-18 20:04:10 -0800115 &mut db.borrow_mut(),
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800116 &LEGACY_IMPORTER,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800117 user_id as u32,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800118 )
119 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000120 .context(ks_err!("Trying to delete keys from db."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700121 self.delete_listener
122 .delete_user(user_id as u32)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000123 .context(ks_err!("While invoking the delete listener."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000124 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800125
Eric Biggersb0478cf2023-10-27 03:55:29 +0000126 fn init_user_super_keys(
127 &self,
128 user_id: i32,
129 password: Password,
130 allow_existing: bool,
131 ) -> Result<()> {
132 // Permission check. Must return on error. Do not touch the '?'.
133 check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
134
135 let mut skm = SUPER_KEY.write().unwrap();
136 DB.with(|db| {
137 skm.initialize_user(
138 &mut db.borrow_mut(),
139 &LEGACY_IMPORTER,
140 user_id as u32,
141 &password,
142 allow_existing,
143 )
144 })
145 .context(ks_err!("Failed to initialize user super keys"))
146 }
147
148 // Deletes all auth-bound keys when the user's LSKF is removed.
149 fn on_user_lskf_removed(user_id: i32) -> Result<()> {
150 // Permission check. Must return on error. Do not touch the '?'.
151 check_keystore_permission(KeystorePerm::ChangePassword).context(ks_err!())?;
152
153 LEGACY_IMPORTER
154 .bulk_delete_user(user_id as u32, true)
155 .context(ks_err!("Failed to delete legacy keys."))?;
156
157 DB.with(|db| db.borrow_mut().unbind_auth_bound_keys_for_user(user_id as u32))
158 .context(ks_err!("Failed to delete auth-bound keys."))
159 }
160
Janis Danisevskis5898d152021-06-15 08:23:46 -0700161 fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> {
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800162 // Permission check. Must return on error. Do not touch the '?'.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700163 check_keystore_permission(KeystorePerm::ClearUID).context("In clear_namespace.")?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800164
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800165 LEGACY_IMPORTER
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800166 .bulk_delete_uid(domain, nspace)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000167 .context(ks_err!("Trying to delete legacy keys."))?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800168 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000169 .context(ks_err!("Trying to delete keys from db."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700170 self.delete_listener
171 .delete_namespace(domain, nspace)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000172 .context(ks_err!("While invoking the delete listener."))
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800173 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000174
Karuna Wadheraca704492024-11-20 06:50:29 +0000175 fn call_with_watchdog<F>(
176 sec_level: SecurityLevel,
177 name: &'static str,
178 op: &F,
179 min_version: Option<i32>,
180 ) -> Result<()>
Paul Crowley46c703e2021-08-06 15:13:53 -0700181 where
Stephen Crane23cf7242022-01-19 17:49:46 +0000182 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
Paul Crowley46c703e2021-08-06 15:13:53 -0700183 {
Karuna Wadheraca704492024-11-20 06:50:29 +0000184 let (km_dev, hw_info, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000185 get_keymint_device(&sec_level).context(ks_err!("getting keymint device"))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700186
Karuna Wadheraca704492024-11-20 06:50:29 +0000187 if let Some(min_version) = min_version {
188 if hw_info.versionNumber < min_version {
189 log::info!("skipping {name} for {sec_level:?} since its keymint version {} is less than the minimum required version {min_version}", hw_info.versionNumber);
190 return Ok(());
191 }
192 }
193
David Drysdalec652f6c2024-07-18 13:01:23 +0100194 let _wp = wd::watch_millis_with("Maintenance::call_with_watchdog", 500, (sec_level, name));
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000195 map_km_error(op(km_dev)).with_context(|| ks_err!("calling {}", name))?;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800196 Ok(())
197 }
198
Karuna Wadheraca704492024-11-20 06:50:29 +0000199 fn call_on_all_security_levels<F>(
200 name: &'static str,
201 op: F,
202 min_version: Option<i32>,
203 ) -> Result<()>
Paul Crowley46c703e2021-08-06 15:13:53 -0700204 where
Stephen Crane23cf7242022-01-19 17:49:46 +0000205 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
Paul Crowley46c703e2021-08-06 15:13:53 -0700206 {
207 let sec_levels = [
208 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
209 (SecurityLevel::STRONGBOX, "STRONGBOX"),
210 ];
James Farrelld77b97f2023-08-15 20:03:38 +0000211 sec_levels.iter().try_fold((), |_result, (sec_level, sec_level_string)| {
Karuna Wadheraca704492024-11-20 06:50:29 +0000212 let curr_result = Maintenance::call_with_watchdog(*sec_level, name, &op, min_version);
Paul Crowley46c703e2021-08-06 15:13:53 -0700213 match curr_result {
214 Ok(()) => log::info!(
215 "Call to {} succeeded for security level {}.",
216 name,
217 &sec_level_string
218 ),
David Drysdalece2b90b2024-07-17 15:56:29 +0100219 Err(ref e) => {
220 if *sec_level == SecurityLevel::STRONGBOX
221 && e.downcast_ref::<Error>()
222 == Some(&Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
223 {
224 log::info!("Call to {} failed for StrongBox as it is not available", name,)
225 } else {
226 log::error!(
227 "Call to {} failed for security level {}: {}.",
228 name,
229 &sec_level_string,
230 e
231 )
232 }
233 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700234 }
James Farrelld77b97f2023-08-15 20:03:38 +0000235 curr_result
Paul Crowley46c703e2021-08-06 15:13:53 -0700236 })
237 }
238
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800239 fn early_boot_ended() -> Result<()> {
Janis Danisevskisa916d992021-10-19 15:46:09 -0700240 check_keystore_permission(KeystorePerm::EarlyBootEnded)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000241 .context(ks_err!("Checking permission"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000242 log::info!("In early_boot_ended.");
243
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800244 if let Err(e) =
245 DB.with(|db| SuperKeyManager::set_up_boot_level_cache(&SUPER_KEY, &mut db.borrow_mut()))
246 {
Paul Crowley44c02da2021-04-08 17:04:43 +0000247 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
248 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000249
David Drysdale1ce15612024-12-05 18:50:40 +0000250 if keystore2_flags::attest_modules() {
251 std::thread::spawn(move || {
252 Self::watch_apex_info()
253 .unwrap_or_else(|e| log::error!("watch_apex_info failed: {e:?}"));
254 });
255 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000256 Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded(), None)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800257 }
258
David Drysdale1ce15612024-12-05 18:50:40 +0000259 /// Watch the `apexd.status` system property, and read apex module information once
260 /// it is `activated`.
261 ///
262 /// Blocks waiting for system property changes, so must be run in its own thread.
263 fn watch_apex_info() -> Result<()> {
264 let prop = "apexd.status";
265 log::info!("start monitoring '{prop}' property");
266 let mut w = PropertyWatcher::new(prop).context(ks_err!("PropertyWatcher::new failed"))?;
267 loop {
268 let value = w.read(|_name, value| Ok(value.to_string()));
269 // The status for apexd moves from "starting" to "activated" to "ready"; the apex
270 // info file should be populated for either of the latter two states, so cope with
271 // both in case we miss a state change.
272 log::info!("property '{prop}' is now '{value:?}'");
273 if matches!(value.as_deref(), Ok("activated") | Ok("ready")) {
274 match Self::read_apex_info() {
275 Ok(modules) => {
276 Self::set_module_info(modules)
277 .context(ks_err!("failed to set module info"))?;
278 break;
279 }
280 Err(e) => {
281 log::error!(
282 "failed to read apex info, try again on next state change: {e:?}"
283 );
284 }
285 }
286 }
287
288 log::info!("await a change to '{prop}'...");
289 w.wait(None).context(ks_err!("property wait failed"))?;
290 log::info!("await a change to '{prop}'...notified");
291 }
292 Ok(())
293 }
294
295 fn read_apex_info() -> Result<Vec<ModuleInfo>> {
296 let _wp = wd::watch("read_apex_info via IApexService.getActivePackages()");
297 let apexd: Strong<dyn IApexService> =
298 wait_for_interface("apexservice").context("failed to AIDL connect to apexd")?;
299 let packages = apexd.getActivePackages().context("failed to retrieve active packages")?;
300 packages
301 .into_iter()
302 .map(|pkg| {
303 log::info!("apex modules += {} version {}", pkg.moduleName, pkg.versionCode);
304 let name = OctetString::new(pkg.moduleName.as_bytes()).map_err(|e| {
305 anyhow!("failed to convert '{}' to OCTET_STRING: {e:?}", pkg.moduleName)
306 })?;
307 Ok(ModuleInfo { name, version: pkg.versionCode })
308 })
309 .collect()
310 }
311
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700312 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
John Wu889c1cc2022-03-14 16:02:56 -0700313 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700314
John Wu889c1cc2022-03-14 16:02:56 -0700315 match source.domain {
316 Domain::SELINUX | Domain::KEY_ID | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800317 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000318 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
319 .context(ks_err!("Source domain must be one of APP, SELINUX, or KEY_ID."));
John Wu16db29e2022-01-13 15:21:43 -0800320 }
321 };
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700322
John Wu889c1cc2022-03-14 16:02:56 -0700323 match destination.domain {
324 Domain::SELINUX | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800325 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000326 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
327 .context(ks_err!("Destination domain must be one of APP or SELINUX."));
John Wu16db29e2022-01-13 15:21:43 -0800328 }
329 };
330
John Wu889c1cc2022-03-14 16:02:56 -0700331 let user_id = uid_to_android_user(calling_uid);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800332
Eric Biggers673d34a2023-10-18 01:54:18 +0000333 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800334
335 DB.with(|db| {
John Wu889c1cc2022-03-14 16:02:56 -0700336 let (key_id_guard, _) = LEGACY_IMPORTER
337 .with_try_import(source, calling_uid, super_key, || {
338 db.borrow_mut().load_key_entry(
339 source,
340 KeyType::Client,
341 KeyEntryLoadBits::NONE,
342 calling_uid,
343 |k, av| {
344 check_key_permission(KeyPerm::Use, k, &av)?;
345 check_key_permission(KeyPerm::Delete, k, &av)?;
346 check_key_permission(KeyPerm::Grant, k, &av)
347 },
348 )
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800349 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000350 .context(ks_err!("Failed to load key blob."))?;
John Wu889c1cc2022-03-14 16:02:56 -0700351 {
352 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, calling_uid, |k| {
353 check_key_permission(KeyPerm::Rebind, k, &None)
354 })
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800355 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700356 })
357 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700358
359 fn delete_all_keys() -> Result<()> {
360 // Security critical permission check. This statement must return on fail.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700361 check_keystore_permission(KeystorePerm::DeleteAllKeys)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000362 .context(ks_err!("Checking permission"))?;
Paul Crowley46c703e2021-08-06 15:13:53 -0700363 log::info!("In delete_all_keys.");
364
Karuna Wadheraca704492024-11-20 06:50:29 +0000365 Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys(), None)
Paul Crowley46c703e2021-08-06 15:13:53 -0700366 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000367
368 fn get_app_uids_affected_by_sid(
369 user_id: i32,
370 secure_user_id: i64,
371 ) -> Result<std::vec::Vec<i64>> {
372 // This method is intended to be called by Settings and discloses a list of apps
Eran Messericfe79f12024-02-05 17:50:41 +0000373 // associated with a user, so it requires the "android.permission.MANAGE_USERS"
374 // permission (to avoid leaking list of apps to unauthorized callers).
375 check_get_app_uids_affected_by_sid_permissions().context(ks_err!())?;
Eran Messeri4dc27b52024-01-09 12:43:31 +0000376 DB.with(|db| db.borrow_mut().get_app_uids_affected_by_sid(user_id, secure_user_id))
377 .context(ks_err!("Failed to get app UIDs affected by SID"))
378 }
David Drysdale0fefae32024-09-16 13:32:27 +0100379
380 fn dump_state(&self, f: &mut dyn std::io::Write) -> std::io::Result<()> {
381 writeln!(f, "keystore2 running")?;
382 writeln!(f)?;
383
384 // Display underlying device information
385 for sec_level in &[SecurityLevel::TRUSTED_ENVIRONMENT, SecurityLevel::STRONGBOX] {
386 let Ok((_dev, hw_info, uuid)) = get_keymint_device(sec_level) else { continue };
387
388 writeln!(f, "Device info for {sec_level:?} with {uuid:?}")?;
389 writeln!(f, " HAL version: {}", hw_info.versionNumber)?;
390 writeln!(f, " Implementation name: {}", hw_info.keyMintName)?;
391 writeln!(f, " Implementation author: {}", hw_info.keyMintAuthorName)?;
392 writeln!(f, " Timestamp token required: {}", hw_info.timestampTokenRequired)?;
393 }
394 writeln!(f)?;
395
David Drysdale37fcf5b2024-12-11 11:07:56 +0000396 // Display module attestation information
397 {
398 let info = ENCODED_MODULE_INFO.read().unwrap();
399 if let Some(info) = info.as_ref() {
400 writeln!(f, "Attested module information (DER-encoded):")?;
401 writeln!(f, " {}", hex::encode(info))?;
402 writeln!(f)?;
403 } else {
404 writeln!(f, "Attested module information not set")?;
405 writeln!(f)?;
406 }
407 }
408
David Drysdale0fefae32024-09-16 13:32:27 +0100409 // Display database size information.
410 match crate::metrics_store::pull_storage_stats() {
411 Ok(atoms) => {
412 writeln!(f, "Database size information (in bytes):")?;
413 for atom in atoms {
414 if let StorageStats(stats) = &atom.payload {
415 let stype = format!("{:?}", stats.storage_type);
416 if stats.unused_size == 0 {
417 writeln!(f, " {:<40}: {:>12}", stype, stats.size)?;
418 } else {
419 writeln!(
420 f,
421 " {:<40}: {:>12} (unused {})",
422 stype, stats.size, stats.unused_size
423 )?;
424 }
425 }
426 }
427 }
428 Err(e) => {
429 writeln!(f, "Failed to retrieve storage stats: {e:?}")?;
430 }
431 }
432 writeln!(f)?;
433
David Drysdale709c2092024-06-06 16:17:28 +0100434 // Display database config information.
435 writeln!(f, "Database configuration:")?;
436 DB.with(|db| -> std::io::Result<()> {
437 let pragma_str = |f: &mut dyn std::io::Write, name| -> std::io::Result<()> {
438 let mut db = db.borrow_mut();
439 let value: String = db
440 .pragma(name)
441 .unwrap_or_else(|e| format!("unknown value for '{name}', failed: {e:?}"));
442 writeln!(f, " {name} = {value}")
443 };
444 let pragma_i32 = |f: &mut dyn std::io::Write, name| -> std::io::Result<()> {
445 let mut db = db.borrow_mut();
446 let value: i32 = db.pragma(name).unwrap_or_else(|e| {
447 log::error!("unknown value for '{name}', failed: {e:?}");
448 -1
449 });
450 writeln!(f, " {name} = {value}")
451 };
452 pragma_i32(f, "auto_vacuum")?;
453 pragma_str(f, "journal_mode")?;
454 pragma_i32(f, "journal_size_limit")?;
455 pragma_i32(f, "synchronous")?;
456 pragma_i32(f, "schema_version")?;
457 pragma_i32(f, "user_version")?;
458 Ok(())
459 })?;
460 writeln!(f)?;
461
David Drysdale49811e22023-05-22 18:51:30 +0100462 // Display accumulated metrics.
463 writeln!(f, "Metrics information:")?;
464 writeln!(f)?;
465 write!(f, "{:?}", *crate::metrics_store::METRICS_STORE)?;
466 writeln!(f)?;
467
David Drysdale0fefae32024-09-16 13:32:27 +0100468 // Reminder: any additional information added to the `dump_state()` output needs to be
469 // careful not to include confidential information (e.g. key material).
470
471 Ok(())
472 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000473
Karuna Wadheraca704492024-11-20 06:50:29 +0000474 fn set_module_info(module_info: Vec<ModuleInfo>) -> Result<()> {
David Drysdale1ce15612024-12-05 18:50:40 +0000475 log::info!("set_module_info with {} modules", module_info.len());
Karuna Wadheraca704492024-11-20 06:50:29 +0000476 let encoding = Self::encode_module_info(module_info)
477 .map_err(|e| anyhow!({ e }))
478 .context(ks_err!("Failed to encode module_info"))?;
479 let hash = digest::Sha256::hash(&encoding).to_vec();
480
481 {
482 let mut saved = ENCODED_MODULE_INFO.write().unwrap();
483 if let Some(saved_encoding) = &*saved {
484 if *saved_encoding == encoding {
485 log::warn!(
486 "Module info already set, ignoring repeated attempt to set same info."
487 );
488 return Ok(());
489 }
490 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
491 "Failed to set module info as it is already set to a different value."
492 ));
493 }
494 *saved = Some(encoding);
495 }
496
497 let kps =
498 vec![KeyParameter { tag: Tag::MODULE_HASH, value: KeyParameterValue::Blob(hash) }];
499
500 Maintenance::call_on_all_security_levels(
501 "setAdditionalAttestationInfo",
502 |dev| dev.setAdditionalAttestationInfo(&kps),
503 Some(KEYMINT_V4),
504 )
505 }
506
Karuna Wadheraca704492024-11-20 06:50:29 +0000507 fn encode_module_info(module_info: Vec<ModuleInfo>) -> Result<Vec<u8>, der::Error> {
508 SetOfVec::<ModuleInfo>::from_iter(module_info.into_iter())?.to_der()
509 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000510}
511
David Drysdale0fefae32024-09-16 13:32:27 +0100512impl Interface for Maintenance {
513 fn dump(
514 &self,
515 f: &mut dyn std::io::Write,
516 _args: &[&std::ffi::CStr],
517 ) -> Result<(), binder::StatusCode> {
518 if !keystore2_flags::enable_dump() {
519 log::info!("skipping dump() as flag not enabled");
520 return Ok(());
521 }
522 log::info!("dump()");
523 let _wp = wd::watch("IKeystoreMaintenance::dump");
524 check_dump_permission().map_err(|_e| {
525 log::error!("dump permission denied");
526 binder::StatusCode::PERMISSION_DENIED
527 })?;
528
529 self.dump_state(f).map_err(|e| {
530 log::error!("dump_state failed: {e:?}");
531 binder::StatusCode::UNKNOWN_ERROR
532 })
533 }
534}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000535
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800536impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000537 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100538 log::info!("onUserAdded(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100539 let _wp = wd::watch("IKeystoreMaintenance::onUserAdded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100540 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000541 }
542
Eric Biggersb0478cf2023-10-27 03:55:29 +0000543 fn initUserSuperKeys(
544 &self,
545 user_id: i32,
546 password: &[u8],
547 allow_existing: bool,
548 ) -> BinderResult<()> {
549 log::info!("initUserSuperKeys(user={user_id}, allow_existing={allow_existing})");
David Drysdale541846b2024-05-23 13:16:07 +0100550 let _wp = wd::watch("IKeystoreMaintenance::initUserSuperKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100551 self.init_user_super_keys(user_id, password.into(), allow_existing)
552 .map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000553 }
554
Hasini Gunasingheda895552021-01-27 19:34:37 +0000555 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100556 log::info!("onUserRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100557 let _wp = wd::watch("IKeystoreMaintenance::onUserRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100558 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000559 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800560
Eric Biggersb0478cf2023-10-27 03:55:29 +0000561 fn onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()> {
562 log::info!("onUserLskfRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100563 let _wp = wd::watch("IKeystoreMaintenance::onUserLskfRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100564 Self::on_user_lskf_removed(user_id).map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000565 }
566
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800567 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100568 log::info!("clearNamespace({domain:?}, nspace={nspace})");
David Drysdale541846b2024-05-23 13:16:07 +0100569 let _wp = wd::watch("IKeystoreMaintenance::clearNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100570 self.clear_namespace(domain, nspace).map_err(into_logged_binder)
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800571 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000572
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800573 fn earlyBootEnded(&self) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100574 log::info!("earlyBootEnded()");
David Drysdale541846b2024-05-23 13:16:07 +0100575 let _wp = wd::watch("IKeystoreMaintenance::earlyBootEnded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100576 Self::early_boot_ended().map_err(into_logged_binder)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800577 }
578
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700579 fn migrateKeyNamespace(
580 &self,
581 source: &KeyDescriptor,
582 destination: &KeyDescriptor,
583 ) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100584 log::info!("migrateKeyNamespace(src={source:?}, dest={destination:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100585 let _wp = wd::watch("IKeystoreMaintenance::migrateKeyNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100586 Self::migrate_key_namespace(source, destination).map_err(into_logged_binder)
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700587 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700588
589 fn deleteAllKeys(&self) -> BinderResult<()> {
David Drysdalece2b90b2024-07-17 15:56:29 +0100590 log::warn!("deleteAllKeys() invoked, indicating initial setup or post-factory reset");
David Drysdale541846b2024-05-23 13:16:07 +0100591 let _wp = wd::watch("IKeystoreMaintenance::deleteAllKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100592 Self::delete_all_keys().map_err(into_logged_binder)
Paul Crowley46c703e2021-08-06 15:13:53 -0700593 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000594
595 fn getAppUidsAffectedBySid(
596 &self,
597 user_id: i32,
598 secure_user_id: i64,
599 ) -> BinderResult<std::vec::Vec<i64>> {
600 log::info!("getAppUidsAffectedBySid(secure_user_id={secure_user_id:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100601 let _wp = wd::watch("IKeystoreMaintenance::getAppUidsAffectedBySid");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100602 Self::get_app_uids_affected_by_sid(user_id, secure_user_id).map_err(into_logged_binder)
Eran Messeri4dc27b52024-01-09 12:43:31 +0000603 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000604}