blob: 16cc34f7423fb773ad0e4cb6086b37a1f9e24fbd [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 Wadheraca704492024-11-20 06:50:29 +000058/// Version number of KeyMint V4.
59pub const KEYMINT_V4: i32 = 400;
60
61/// Module information structure for DER-encoding.
David Drysdale1ce15612024-12-05 18:50:40 +000062#[derive(Sequence, Debug, PartialEq, Eq)]
Karuna Wadheraca704492024-11-20 06:50:29 +000063struct ModuleInfo {
64 name: OctetString,
David Drysdale1ce15612024-12-05 18:50:40 +000065 version: i64,
Karuna Wadheraca704492024-11-20 06:50:29 +000066}
67
68impl DerOrd for ModuleInfo {
69 // DER mandates "encodings of the component values of a set-of value shall appear in ascending
70 // order". `der_cmp` serves as a proxy for determining that ordering (though why the `der` crate
71 // requires this is unclear). Essentially, we just need to compare the `name` lengths, and then
72 // if those are equal, the `name`s themselves. (No need to consider `version`s since there can't
73 // be more than one `ModuleInfo` with the same `name` in the set-of `ModuleInfo`s.) We rely on
74 // `OctetString`'s `der_cmp` to do the aforementioned comparison.
75 fn der_cmp(&self, other: &Self) -> std::result::Result<Ordering, der::Error> {
76 self.name.der_cmp(&other.name)
77 }
78}
79
Janis Danisevskis5898d152021-06-15 08:23:46 -070080/// The Maintenance module takes a delete listener argument which observes user and namespace
81/// deletion events.
82pub trait DeleteListener {
83 /// Called by the maintenance module when an app/namespace is deleted.
84 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>;
85 /// Called by the maintenance module when a user is deleted.
86 fn delete_user(&self, user_id: u32) -> Result<()>;
87}
88
Hasini Gunasingheda895552021-01-27 19:34:37 +000089/// This struct is defined to implement the aforementioned AIDL interface.
Janis Danisevskis5898d152021-06-15 08:23:46 -070090pub struct Maintenance {
91 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
92}
Hasini Gunasingheda895552021-01-27 19:34:37 +000093
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080094impl Maintenance {
Janis Danisevskis5898d152021-06-15 08:23:46 -070095 /// Create a new instance of Keystore Maintenance service.
96 pub fn new_native_binder(
97 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
98 ) -> Result<Strong<dyn IKeystoreMaintenance>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +000099 Ok(BnKeystoreMaintenance::new_binder(
Janis Danisevskis5898d152021-06-15 08:23:46 -0700100 Self { delete_listener },
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000101 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
102 ))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000103 }
104
Janis Danisevskis5898d152021-06-15 08:23:46 -0700105 fn add_or_remove_user(&self, user_id: i32) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000106 // Check permission. Function should return if this failed. Therefore having '?' at the end
107 // is very important.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000108 check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800109
Janis Danisevskiseed69842021-02-18 20:04:10 -0800110 DB.with(|db| {
Nathan Huckleberry204a0442023-03-30 17:27:47 +0000111 SUPER_KEY.write().unwrap().remove_user(
Janis Danisevskiseed69842021-02-18 20:04:10 -0800112 &mut db.borrow_mut(),
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800113 &LEGACY_IMPORTER,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800114 user_id as u32,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800115 )
116 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000117 .context(ks_err!("Trying to delete keys from db."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700118 self.delete_listener
119 .delete_user(user_id as u32)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000120 .context(ks_err!("While invoking the delete listener."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000121 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800122
Eric Biggersb0478cf2023-10-27 03:55:29 +0000123 fn init_user_super_keys(
124 &self,
125 user_id: i32,
126 password: Password,
127 allow_existing: bool,
128 ) -> Result<()> {
129 // Permission check. Must return on error. Do not touch the '?'.
130 check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
131
132 let mut skm = SUPER_KEY.write().unwrap();
133 DB.with(|db| {
134 skm.initialize_user(
135 &mut db.borrow_mut(),
136 &LEGACY_IMPORTER,
137 user_id as u32,
138 &password,
139 allow_existing,
140 )
141 })
142 .context(ks_err!("Failed to initialize user super keys"))
143 }
144
145 // Deletes all auth-bound keys when the user's LSKF is removed.
146 fn on_user_lskf_removed(user_id: i32) -> Result<()> {
147 // Permission check. Must return on error. Do not touch the '?'.
148 check_keystore_permission(KeystorePerm::ChangePassword).context(ks_err!())?;
149
150 LEGACY_IMPORTER
151 .bulk_delete_user(user_id as u32, true)
152 .context(ks_err!("Failed to delete legacy keys."))?;
153
154 DB.with(|db| db.borrow_mut().unbind_auth_bound_keys_for_user(user_id as u32))
155 .context(ks_err!("Failed to delete auth-bound keys."))
156 }
157
Janis Danisevskis5898d152021-06-15 08:23:46 -0700158 fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> {
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800159 // Permission check. Must return on error. Do not touch the '?'.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700160 check_keystore_permission(KeystorePerm::ClearUID).context("In clear_namespace.")?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800161
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800162 LEGACY_IMPORTER
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800163 .bulk_delete_uid(domain, nspace)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000164 .context(ks_err!("Trying to delete legacy keys."))?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800165 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000166 .context(ks_err!("Trying to delete keys from db."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700167 self.delete_listener
168 .delete_namespace(domain, nspace)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000169 .context(ks_err!("While invoking the delete listener."))
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800170 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000171
Karuna Wadheraca704492024-11-20 06:50:29 +0000172 fn call_with_watchdog<F>(
173 sec_level: SecurityLevel,
174 name: &'static str,
175 op: &F,
176 min_version: Option<i32>,
177 ) -> Result<()>
Paul Crowley46c703e2021-08-06 15:13:53 -0700178 where
Stephen Crane23cf7242022-01-19 17:49:46 +0000179 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
Paul Crowley46c703e2021-08-06 15:13:53 -0700180 {
Karuna Wadheraca704492024-11-20 06:50:29 +0000181 let (km_dev, hw_info, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000182 get_keymint_device(&sec_level).context(ks_err!("getting keymint device"))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700183
Karuna Wadheraca704492024-11-20 06:50:29 +0000184 if let Some(min_version) = min_version {
185 if hw_info.versionNumber < min_version {
186 log::info!("skipping {name} for {sec_level:?} since its keymint version {} is less than the minimum required version {min_version}", hw_info.versionNumber);
187 return Ok(());
188 }
189 }
190
David Drysdalec652f6c2024-07-18 13:01:23 +0100191 let _wp = wd::watch_millis_with("Maintenance::call_with_watchdog", 500, (sec_level, name));
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000192 map_km_error(op(km_dev)).with_context(|| ks_err!("calling {}", name))?;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800193 Ok(())
194 }
195
Karuna Wadheraca704492024-11-20 06:50:29 +0000196 fn call_on_all_security_levels<F>(
197 name: &'static str,
198 op: F,
199 min_version: Option<i32>,
200 ) -> Result<()>
Paul Crowley46c703e2021-08-06 15:13:53 -0700201 where
Stephen Crane23cf7242022-01-19 17:49:46 +0000202 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
Paul Crowley46c703e2021-08-06 15:13:53 -0700203 {
204 let sec_levels = [
205 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
206 (SecurityLevel::STRONGBOX, "STRONGBOX"),
207 ];
James Farrelld77b97f2023-08-15 20:03:38 +0000208 sec_levels.iter().try_fold((), |_result, (sec_level, sec_level_string)| {
Karuna Wadheraca704492024-11-20 06:50:29 +0000209 let curr_result = Maintenance::call_with_watchdog(*sec_level, name, &op, min_version);
Paul Crowley46c703e2021-08-06 15:13:53 -0700210 match curr_result {
211 Ok(()) => log::info!(
212 "Call to {} succeeded for security level {}.",
213 name,
214 &sec_level_string
215 ),
David Drysdalece2b90b2024-07-17 15:56:29 +0100216 Err(ref e) => {
217 if *sec_level == SecurityLevel::STRONGBOX
218 && e.downcast_ref::<Error>()
219 == Some(&Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
220 {
221 log::info!("Call to {} failed for StrongBox as it is not available", name,)
222 } else {
223 log::error!(
224 "Call to {} failed for security level {}: {}.",
225 name,
226 &sec_level_string,
227 e
228 )
229 }
230 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700231 }
James Farrelld77b97f2023-08-15 20:03:38 +0000232 curr_result
Paul Crowley46c703e2021-08-06 15:13:53 -0700233 })
234 }
235
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800236 fn early_boot_ended() -> Result<()> {
Janis Danisevskisa916d992021-10-19 15:46:09 -0700237 check_keystore_permission(KeystorePerm::EarlyBootEnded)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000238 .context(ks_err!("Checking permission"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000239 log::info!("In early_boot_ended.");
240
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800241 if let Err(e) =
242 DB.with(|db| SuperKeyManager::set_up_boot_level_cache(&SUPER_KEY, &mut db.borrow_mut()))
243 {
Paul Crowley44c02da2021-04-08 17:04:43 +0000244 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
245 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000246
David Drysdale1ce15612024-12-05 18:50:40 +0000247 if keystore2_flags::attest_modules() {
248 std::thread::spawn(move || {
249 Self::watch_apex_info()
250 .unwrap_or_else(|e| log::error!("watch_apex_info failed: {e:?}"));
251 });
252 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000253 Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded(), None)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800254 }
255
David Drysdale1ce15612024-12-05 18:50:40 +0000256 /// Watch the `apexd.status` system property, and read apex module information once
257 /// it is `activated`.
258 ///
259 /// Blocks waiting for system property changes, so must be run in its own thread.
260 fn watch_apex_info() -> Result<()> {
261 let prop = "apexd.status";
262 log::info!("start monitoring '{prop}' property");
263 let mut w = PropertyWatcher::new(prop).context(ks_err!("PropertyWatcher::new failed"))?;
264 loop {
265 let value = w.read(|_name, value| Ok(value.to_string()));
266 // The status for apexd moves from "starting" to "activated" to "ready"; the apex
267 // info file should be populated for either of the latter two states, so cope with
268 // both in case we miss a state change.
269 log::info!("property '{prop}' is now '{value:?}'");
270 if matches!(value.as_deref(), Ok("activated") | Ok("ready")) {
271 match Self::read_apex_info() {
272 Ok(modules) => {
273 Self::set_module_info(modules)
274 .context(ks_err!("failed to set module info"))?;
275 break;
276 }
277 Err(e) => {
278 log::error!(
279 "failed to read apex info, try again on next state change: {e:?}"
280 );
281 }
282 }
283 }
284
285 log::info!("await a change to '{prop}'...");
286 w.wait(None).context(ks_err!("property wait failed"))?;
287 log::info!("await a change to '{prop}'...notified");
288 }
289 Ok(())
290 }
291
292 fn read_apex_info() -> Result<Vec<ModuleInfo>> {
293 let _wp = wd::watch("read_apex_info via IApexService.getActivePackages()");
294 let apexd: Strong<dyn IApexService> =
295 wait_for_interface("apexservice").context("failed to AIDL connect to apexd")?;
296 let packages = apexd.getActivePackages().context("failed to retrieve active packages")?;
297 packages
298 .into_iter()
299 .map(|pkg| {
300 log::info!("apex modules += {} version {}", pkg.moduleName, pkg.versionCode);
301 let name = OctetString::new(pkg.moduleName.as_bytes()).map_err(|e| {
302 anyhow!("failed to convert '{}' to OCTET_STRING: {e:?}", pkg.moduleName)
303 })?;
304 Ok(ModuleInfo { name, version: pkg.versionCode })
305 })
306 .collect()
307 }
308
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700309 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
John Wu889c1cc2022-03-14 16:02:56 -0700310 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700311
John Wu889c1cc2022-03-14 16:02:56 -0700312 match source.domain {
313 Domain::SELINUX | Domain::KEY_ID | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800314 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000315 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
316 .context(ks_err!("Source domain must be one of APP, SELINUX, or KEY_ID."));
John Wu16db29e2022-01-13 15:21:43 -0800317 }
318 };
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700319
John Wu889c1cc2022-03-14 16:02:56 -0700320 match destination.domain {
321 Domain::SELINUX | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800322 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000323 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
324 .context(ks_err!("Destination domain must be one of APP or SELINUX."));
John Wu16db29e2022-01-13 15:21:43 -0800325 }
326 };
327
John Wu889c1cc2022-03-14 16:02:56 -0700328 let user_id = uid_to_android_user(calling_uid);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800329
Eric Biggers673d34a2023-10-18 01:54:18 +0000330 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800331
332 DB.with(|db| {
John Wu889c1cc2022-03-14 16:02:56 -0700333 let (key_id_guard, _) = LEGACY_IMPORTER
334 .with_try_import(source, calling_uid, super_key, || {
335 db.borrow_mut().load_key_entry(
336 source,
337 KeyType::Client,
338 KeyEntryLoadBits::NONE,
339 calling_uid,
340 |k, av| {
341 check_key_permission(KeyPerm::Use, k, &av)?;
342 check_key_permission(KeyPerm::Delete, k, &av)?;
343 check_key_permission(KeyPerm::Grant, k, &av)
344 },
345 )
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800346 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000347 .context(ks_err!("Failed to load key blob."))?;
John Wu889c1cc2022-03-14 16:02:56 -0700348 {
349 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, calling_uid, |k| {
350 check_key_permission(KeyPerm::Rebind, k, &None)
351 })
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800352 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700353 })
354 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700355
356 fn delete_all_keys() -> Result<()> {
357 // Security critical permission check. This statement must return on fail.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700358 check_keystore_permission(KeystorePerm::DeleteAllKeys)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000359 .context(ks_err!("Checking permission"))?;
Paul Crowley46c703e2021-08-06 15:13:53 -0700360 log::info!("In delete_all_keys.");
361
Karuna Wadheraca704492024-11-20 06:50:29 +0000362 Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys(), None)
Paul Crowley46c703e2021-08-06 15:13:53 -0700363 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000364
365 fn get_app_uids_affected_by_sid(
366 user_id: i32,
367 secure_user_id: i64,
368 ) -> Result<std::vec::Vec<i64>> {
369 // This method is intended to be called by Settings and discloses a list of apps
Eran Messericfe79f12024-02-05 17:50:41 +0000370 // associated with a user, so it requires the "android.permission.MANAGE_USERS"
371 // permission (to avoid leaking list of apps to unauthorized callers).
372 check_get_app_uids_affected_by_sid_permissions().context(ks_err!())?;
Eran Messeri4dc27b52024-01-09 12:43:31 +0000373 DB.with(|db| db.borrow_mut().get_app_uids_affected_by_sid(user_id, secure_user_id))
374 .context(ks_err!("Failed to get app UIDs affected by SID"))
375 }
David Drysdale0fefae32024-09-16 13:32:27 +0100376
377 fn dump_state(&self, f: &mut dyn std::io::Write) -> std::io::Result<()> {
378 writeln!(f, "keystore2 running")?;
379 writeln!(f)?;
380
381 // Display underlying device information
382 for sec_level in &[SecurityLevel::TRUSTED_ENVIRONMENT, SecurityLevel::STRONGBOX] {
383 let Ok((_dev, hw_info, uuid)) = get_keymint_device(sec_level) else { continue };
384
385 writeln!(f, "Device info for {sec_level:?} with {uuid:?}")?;
386 writeln!(f, " HAL version: {}", hw_info.versionNumber)?;
387 writeln!(f, " Implementation name: {}", hw_info.keyMintName)?;
388 writeln!(f, " Implementation author: {}", hw_info.keyMintAuthorName)?;
389 writeln!(f, " Timestamp token required: {}", hw_info.timestampTokenRequired)?;
390 }
391 writeln!(f)?;
392
David Drysdale37fcf5b2024-12-11 11:07:56 +0000393 // Display module attestation information
394 {
395 let info = ENCODED_MODULE_INFO.read().unwrap();
396 if let Some(info) = info.as_ref() {
397 writeln!(f, "Attested module information (DER-encoded):")?;
398 writeln!(f, " {}", hex::encode(info))?;
399 writeln!(f)?;
400 } else {
401 writeln!(f, "Attested module information not set")?;
402 writeln!(f)?;
403 }
404 }
405
David Drysdale0fefae32024-09-16 13:32:27 +0100406 // Display database size information.
407 match crate::metrics_store::pull_storage_stats() {
408 Ok(atoms) => {
409 writeln!(f, "Database size information (in bytes):")?;
410 for atom in atoms {
411 if let StorageStats(stats) = &atom.payload {
412 let stype = format!("{:?}", stats.storage_type);
413 if stats.unused_size == 0 {
414 writeln!(f, " {:<40}: {:>12}", stype, stats.size)?;
415 } else {
416 writeln!(
417 f,
418 " {:<40}: {:>12} (unused {})",
419 stype, stats.size, stats.unused_size
420 )?;
421 }
422 }
423 }
424 }
425 Err(e) => {
426 writeln!(f, "Failed to retrieve storage stats: {e:?}")?;
427 }
428 }
429 writeln!(f)?;
430
David Drysdale49811e22023-05-22 18:51:30 +0100431 // Display accumulated metrics.
432 writeln!(f, "Metrics information:")?;
433 writeln!(f)?;
434 write!(f, "{:?}", *crate::metrics_store::METRICS_STORE)?;
435 writeln!(f)?;
436
David Drysdale0fefae32024-09-16 13:32:27 +0100437 // Reminder: any additional information added to the `dump_state()` output needs to be
438 // careful not to include confidential information (e.g. key material).
439
440 Ok(())
441 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000442
Karuna Wadheraca704492024-11-20 06:50:29 +0000443 fn set_module_info(module_info: Vec<ModuleInfo>) -> Result<()> {
David Drysdale1ce15612024-12-05 18:50:40 +0000444 log::info!("set_module_info with {} modules", module_info.len());
Karuna Wadheraca704492024-11-20 06:50:29 +0000445 let encoding = Self::encode_module_info(module_info)
446 .map_err(|e| anyhow!({ e }))
447 .context(ks_err!("Failed to encode module_info"))?;
448 let hash = digest::Sha256::hash(&encoding).to_vec();
449
450 {
451 let mut saved = ENCODED_MODULE_INFO.write().unwrap();
452 if let Some(saved_encoding) = &*saved {
453 if *saved_encoding == encoding {
454 log::warn!(
455 "Module info already set, ignoring repeated attempt to set same info."
456 );
457 return Ok(());
458 }
459 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
460 "Failed to set module info as it is already set to a different value."
461 ));
462 }
463 *saved = Some(encoding);
464 }
465
466 let kps =
467 vec![KeyParameter { tag: Tag::MODULE_HASH, value: KeyParameterValue::Blob(hash) }];
468
469 Maintenance::call_on_all_security_levels(
470 "setAdditionalAttestationInfo",
471 |dev| dev.setAdditionalAttestationInfo(&kps),
472 Some(KEYMINT_V4),
473 )
474 }
475
Karuna Wadheraca704492024-11-20 06:50:29 +0000476 fn encode_module_info(module_info: Vec<ModuleInfo>) -> Result<Vec<u8>, der::Error> {
477 SetOfVec::<ModuleInfo>::from_iter(module_info.into_iter())?.to_der()
478 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000479}
480
David Drysdale0fefae32024-09-16 13:32:27 +0100481impl Interface for Maintenance {
482 fn dump(
483 &self,
484 f: &mut dyn std::io::Write,
485 _args: &[&std::ffi::CStr],
486 ) -> Result<(), binder::StatusCode> {
487 if !keystore2_flags::enable_dump() {
488 log::info!("skipping dump() as flag not enabled");
489 return Ok(());
490 }
491 log::info!("dump()");
492 let _wp = wd::watch("IKeystoreMaintenance::dump");
493 check_dump_permission().map_err(|_e| {
494 log::error!("dump permission denied");
495 binder::StatusCode::PERMISSION_DENIED
496 })?;
497
498 self.dump_state(f).map_err(|e| {
499 log::error!("dump_state failed: {e:?}");
500 binder::StatusCode::UNKNOWN_ERROR
501 })
502 }
503}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000504
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800505impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000506 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100507 log::info!("onUserAdded(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100508 let _wp = wd::watch("IKeystoreMaintenance::onUserAdded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100509 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000510 }
511
Eric Biggersb0478cf2023-10-27 03:55:29 +0000512 fn initUserSuperKeys(
513 &self,
514 user_id: i32,
515 password: &[u8],
516 allow_existing: bool,
517 ) -> BinderResult<()> {
518 log::info!("initUserSuperKeys(user={user_id}, allow_existing={allow_existing})");
David Drysdale541846b2024-05-23 13:16:07 +0100519 let _wp = wd::watch("IKeystoreMaintenance::initUserSuperKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100520 self.init_user_super_keys(user_id, password.into(), allow_existing)
521 .map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000522 }
523
Hasini Gunasingheda895552021-01-27 19:34:37 +0000524 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100525 log::info!("onUserRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100526 let _wp = wd::watch("IKeystoreMaintenance::onUserRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100527 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000528 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800529
Eric Biggersb0478cf2023-10-27 03:55:29 +0000530 fn onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()> {
531 log::info!("onUserLskfRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100532 let _wp = wd::watch("IKeystoreMaintenance::onUserLskfRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100533 Self::on_user_lskf_removed(user_id).map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000534 }
535
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800536 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100537 log::info!("clearNamespace({domain:?}, nspace={nspace})");
David Drysdale541846b2024-05-23 13:16:07 +0100538 let _wp = wd::watch("IKeystoreMaintenance::clearNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100539 self.clear_namespace(domain, nspace).map_err(into_logged_binder)
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800540 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000541
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800542 fn earlyBootEnded(&self) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100543 log::info!("earlyBootEnded()");
David Drysdale541846b2024-05-23 13:16:07 +0100544 let _wp = wd::watch("IKeystoreMaintenance::earlyBootEnded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100545 Self::early_boot_ended().map_err(into_logged_binder)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800546 }
547
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700548 fn migrateKeyNamespace(
549 &self,
550 source: &KeyDescriptor,
551 destination: &KeyDescriptor,
552 ) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100553 log::info!("migrateKeyNamespace(src={source:?}, dest={destination:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100554 let _wp = wd::watch("IKeystoreMaintenance::migrateKeyNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100555 Self::migrate_key_namespace(source, destination).map_err(into_logged_binder)
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700556 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700557
558 fn deleteAllKeys(&self) -> BinderResult<()> {
David Drysdalece2b90b2024-07-17 15:56:29 +0100559 log::warn!("deleteAllKeys() invoked, indicating initial setup or post-factory reset");
David Drysdale541846b2024-05-23 13:16:07 +0100560 let _wp = wd::watch("IKeystoreMaintenance::deleteAllKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100561 Self::delete_all_keys().map_err(into_logged_binder)
Paul Crowley46c703e2021-08-06 15:13:53 -0700562 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000563
564 fn getAppUidsAffectedBySid(
565 &self,
566 user_id: i32,
567 secure_user_id: i64,
568 ) -> BinderResult<std::vec::Vec<i64>> {
569 log::info!("getAppUidsAffectedBySid(secure_user_id={secure_user_id:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100570 let _wp = wd::watch("IKeystoreMaintenance::getAppUidsAffectedBySid");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100571 Self::get_app_uids_affected_by_sid(user_id, secure_user_id).map_err(into_logged_binder)
Eran Messeri4dc27b52024-01-09 12:43:31 +0000572 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000573}