blob: 54b5b445832c3271e38a417d1bb84510a95bba27 [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;
Karuna Wadheraca704492024-11-20 06:50:29 +000022use crate::globals::{DB, LEGACY_IMPORTER, SUPER_KEY, ENCODED_MODULE_INFO};
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};
Eric Biggers2f9498a2023-10-09 23:16:05 +000033use android_security_maintenance::aidl::android::security::maintenance::IKeystoreMaintenance::{
34 BnKeystoreMaintenance, IKeystoreMaintenance,
Hasini Gunasingheda895552021-01-27 19:34:37 +000035};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000036use android_security_maintenance::binder::{
37 BinderFeatures, Interface, Result as BinderResult, Strong, ThreadState,
38};
David Drysdale0fefae32024-09-16 13:32:27 +010039use android_security_metrics::aidl::android::security::metrics::{
40 KeystoreAtomPayload::KeystoreAtomPayload::StorageStats
41};
Janis Danisevskis5898d152021-06-15 08:23:46 -070042use android_system_keystore2::aidl::android::system::keystore2::KeyDescriptor::KeyDescriptor;
Hasini Gunasingheda895552021-01-27 19:34:37 +000043use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Karuna Wadheraca704492024-11-20 06:50:29 +000044use anyhow::{anyhow, Context, Result};
45use bssl_crypto::digest;
46use der::{DerOrd, Encode, asn1::OctetString, asn1::SetOfVec, Sequence};
Paul Crowleyf61fee72021-03-17 14:38:44 -070047use keystore2_crypto::Password;
Karuna Wadheraca704492024-11-20 06:50:29 +000048use std::cmp::Ordering;
Hasini Gunasingheda895552021-01-27 19:34:37 +000049
Janis Danisevskis5898d152021-06-15 08:23:46 -070050/// Reexport Domain for the benefit of DeleteListener
51pub use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
52
Karuna Wadhera8b319092024-12-11 04:42:45 +000053#[cfg(test)]
54mod tests;
55
Karuna Wadheraca704492024-11-20 06:50:29 +000056/// Version number of KeyMint V4.
57pub const KEYMINT_V4: i32 = 400;
58
59/// Module information structure for DER-encoding.
60#[derive(Sequence, Debug)]
61struct ModuleInfo {
62 name: OctetString,
63 version: i32,
64}
65
66impl DerOrd for ModuleInfo {
67 // DER mandates "encodings of the component values of a set-of value shall appear in ascending
68 // order". `der_cmp` serves as a proxy for determining that ordering (though why the `der` crate
69 // requires this is unclear). Essentially, we just need to compare the `name` lengths, and then
70 // if those are equal, the `name`s themselves. (No need to consider `version`s since there can't
71 // be more than one `ModuleInfo` with the same `name` in the set-of `ModuleInfo`s.) We rely on
72 // `OctetString`'s `der_cmp` to do the aforementioned comparison.
73 fn der_cmp(&self, other: &Self) -> std::result::Result<Ordering, der::Error> {
74 self.name.der_cmp(&other.name)
75 }
76}
77
Janis Danisevskis5898d152021-06-15 08:23:46 -070078/// The Maintenance module takes a delete listener argument which observes user and namespace
79/// deletion events.
80pub trait DeleteListener {
81 /// Called by the maintenance module when an app/namespace is deleted.
82 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>;
83 /// Called by the maintenance module when a user is deleted.
84 fn delete_user(&self, user_id: u32) -> Result<()>;
85}
86
Hasini Gunasingheda895552021-01-27 19:34:37 +000087/// This struct is defined to implement the aforementioned AIDL interface.
Janis Danisevskis5898d152021-06-15 08:23:46 -070088pub struct Maintenance {
89 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
90}
Hasini Gunasingheda895552021-01-27 19:34:37 +000091
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080092impl Maintenance {
Janis Danisevskis5898d152021-06-15 08:23:46 -070093 /// Create a new instance of Keystore Maintenance service.
94 pub fn new_native_binder(
95 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
96 ) -> Result<Strong<dyn IKeystoreMaintenance>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +000097 Ok(BnKeystoreMaintenance::new_binder(
Janis Danisevskis5898d152021-06-15 08:23:46 -070098 Self { delete_listener },
Andrew Walbrande45c8b2021-04-13 14:42:38 +000099 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
100 ))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000101 }
102
Janis Danisevskis5898d152021-06-15 08:23:46 -0700103 fn add_or_remove_user(&self, user_id: i32) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000104 // Check permission. Function should return if this failed. Therefore having '?' at the end
105 // is very important.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000106 check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800107
Janis Danisevskiseed69842021-02-18 20:04:10 -0800108 DB.with(|db| {
Nathan Huckleberry204a0442023-03-30 17:27:47 +0000109 SUPER_KEY.write().unwrap().remove_user(
Janis Danisevskiseed69842021-02-18 20:04:10 -0800110 &mut db.borrow_mut(),
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800111 &LEGACY_IMPORTER,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800112 user_id as u32,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800113 )
114 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000115 .context(ks_err!("Trying to delete keys from db."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700116 self.delete_listener
117 .delete_user(user_id as u32)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000118 .context(ks_err!("While invoking the delete listener."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000119 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800120
Eric Biggersb0478cf2023-10-27 03:55:29 +0000121 fn init_user_super_keys(
122 &self,
123 user_id: i32,
124 password: Password,
125 allow_existing: bool,
126 ) -> Result<()> {
127 // Permission check. Must return on error. Do not touch the '?'.
128 check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
129
130 let mut skm = SUPER_KEY.write().unwrap();
131 DB.with(|db| {
132 skm.initialize_user(
133 &mut db.borrow_mut(),
134 &LEGACY_IMPORTER,
135 user_id as u32,
136 &password,
137 allow_existing,
138 )
139 })
140 .context(ks_err!("Failed to initialize user super keys"))
141 }
142
143 // Deletes all auth-bound keys when the user's LSKF is removed.
144 fn on_user_lskf_removed(user_id: i32) -> Result<()> {
145 // Permission check. Must return on error. Do not touch the '?'.
146 check_keystore_permission(KeystorePerm::ChangePassword).context(ks_err!())?;
147
148 LEGACY_IMPORTER
149 .bulk_delete_user(user_id as u32, true)
150 .context(ks_err!("Failed to delete legacy keys."))?;
151
152 DB.with(|db| db.borrow_mut().unbind_auth_bound_keys_for_user(user_id as u32))
153 .context(ks_err!("Failed to delete auth-bound keys."))
154 }
155
Janis Danisevskis5898d152021-06-15 08:23:46 -0700156 fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> {
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800157 // Permission check. Must return on error. Do not touch the '?'.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700158 check_keystore_permission(KeystorePerm::ClearUID).context("In clear_namespace.")?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800159
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800160 LEGACY_IMPORTER
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800161 .bulk_delete_uid(domain, nspace)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000162 .context(ks_err!("Trying to delete legacy keys."))?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800163 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000164 .context(ks_err!("Trying to delete keys from db."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700165 self.delete_listener
166 .delete_namespace(domain, nspace)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000167 .context(ks_err!("While invoking the delete listener."))
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800168 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000169
Karuna Wadheraca704492024-11-20 06:50:29 +0000170 fn call_with_watchdog<F>(
171 sec_level: SecurityLevel,
172 name: &'static str,
173 op: &F,
174 min_version: Option<i32>,
175 ) -> Result<()>
Paul Crowley46c703e2021-08-06 15:13:53 -0700176 where
Stephen Crane23cf7242022-01-19 17:49:46 +0000177 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
Paul Crowley46c703e2021-08-06 15:13:53 -0700178 {
Karuna Wadheraca704492024-11-20 06:50:29 +0000179 let (km_dev, hw_info, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000180 get_keymint_device(&sec_level).context(ks_err!("getting keymint device"))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700181
Karuna Wadheraca704492024-11-20 06:50:29 +0000182 if let Some(min_version) = min_version {
183 if hw_info.versionNumber < min_version {
184 log::info!("skipping {name} for {sec_level:?} since its keymint version {} is less than the minimum required version {min_version}", hw_info.versionNumber);
185 return Ok(());
186 }
187 }
188
David Drysdalec652f6c2024-07-18 13:01:23 +0100189 let _wp = wd::watch_millis_with("Maintenance::call_with_watchdog", 500, (sec_level, name));
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000190 map_km_error(op(km_dev)).with_context(|| ks_err!("calling {}", name))?;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800191 Ok(())
192 }
193
Karuna Wadheraca704492024-11-20 06:50:29 +0000194 fn call_on_all_security_levels<F>(
195 name: &'static str,
196 op: F,
197 min_version: Option<i32>,
198 ) -> Result<()>
Paul Crowley46c703e2021-08-06 15:13:53 -0700199 where
Stephen Crane23cf7242022-01-19 17:49:46 +0000200 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
Paul Crowley46c703e2021-08-06 15:13:53 -0700201 {
202 let sec_levels = [
203 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
204 (SecurityLevel::STRONGBOX, "STRONGBOX"),
205 ];
James Farrelld77b97f2023-08-15 20:03:38 +0000206 sec_levels.iter().try_fold((), |_result, (sec_level, sec_level_string)| {
Karuna Wadheraca704492024-11-20 06:50:29 +0000207 let curr_result = Maintenance::call_with_watchdog(*sec_level, name, &op, min_version);
Paul Crowley46c703e2021-08-06 15:13:53 -0700208 match curr_result {
209 Ok(()) => log::info!(
210 "Call to {} succeeded for security level {}.",
211 name,
212 &sec_level_string
213 ),
David Drysdalece2b90b2024-07-17 15:56:29 +0100214 Err(ref e) => {
215 if *sec_level == SecurityLevel::STRONGBOX
216 && e.downcast_ref::<Error>()
217 == Some(&Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
218 {
219 log::info!("Call to {} failed for StrongBox as it is not available", name,)
220 } else {
221 log::error!(
222 "Call to {} failed for security level {}: {}.",
223 name,
224 &sec_level_string,
225 e
226 )
227 }
228 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700229 }
James Farrelld77b97f2023-08-15 20:03:38 +0000230 curr_result
Paul Crowley46c703e2021-08-06 15:13:53 -0700231 })
232 }
233
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800234 fn early_boot_ended() -> Result<()> {
Janis Danisevskisa916d992021-10-19 15:46:09 -0700235 check_keystore_permission(KeystorePerm::EarlyBootEnded)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000236 .context(ks_err!("Checking permission"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000237 log::info!("In early_boot_ended.");
238
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800239 if let Err(e) =
240 DB.with(|db| SuperKeyManager::set_up_boot_level_cache(&SUPER_KEY, &mut db.borrow_mut()))
241 {
Paul Crowley44c02da2021-04-08 17:04:43 +0000242 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
243 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000244
245 Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded(), None)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800246 }
247
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700248 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
John Wu889c1cc2022-03-14 16:02:56 -0700249 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700250
John Wu889c1cc2022-03-14 16:02:56 -0700251 match source.domain {
252 Domain::SELINUX | Domain::KEY_ID | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800253 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000254 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
255 .context(ks_err!("Source domain must be one of APP, SELINUX, or KEY_ID."));
John Wu16db29e2022-01-13 15:21:43 -0800256 }
257 };
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700258
John Wu889c1cc2022-03-14 16:02:56 -0700259 match destination.domain {
260 Domain::SELINUX | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800261 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000262 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
263 .context(ks_err!("Destination domain must be one of APP or SELINUX."));
John Wu16db29e2022-01-13 15:21:43 -0800264 }
265 };
266
John Wu889c1cc2022-03-14 16:02:56 -0700267 let user_id = uid_to_android_user(calling_uid);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800268
Eric Biggers673d34a2023-10-18 01:54:18 +0000269 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800270
271 DB.with(|db| {
John Wu889c1cc2022-03-14 16:02:56 -0700272 let (key_id_guard, _) = LEGACY_IMPORTER
273 .with_try_import(source, calling_uid, super_key, || {
274 db.borrow_mut().load_key_entry(
275 source,
276 KeyType::Client,
277 KeyEntryLoadBits::NONE,
278 calling_uid,
279 |k, av| {
280 check_key_permission(KeyPerm::Use, k, &av)?;
281 check_key_permission(KeyPerm::Delete, k, &av)?;
282 check_key_permission(KeyPerm::Grant, k, &av)
283 },
284 )
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800285 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000286 .context(ks_err!("Failed to load key blob."))?;
John Wu889c1cc2022-03-14 16:02:56 -0700287 {
288 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, calling_uid, |k| {
289 check_key_permission(KeyPerm::Rebind, k, &None)
290 })
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800291 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700292 })
293 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700294
295 fn delete_all_keys() -> Result<()> {
296 // Security critical permission check. This statement must return on fail.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700297 check_keystore_permission(KeystorePerm::DeleteAllKeys)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000298 .context(ks_err!("Checking permission"))?;
Paul Crowley46c703e2021-08-06 15:13:53 -0700299 log::info!("In delete_all_keys.");
300
Karuna Wadheraca704492024-11-20 06:50:29 +0000301 Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys(), None)
Paul Crowley46c703e2021-08-06 15:13:53 -0700302 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000303
304 fn get_app_uids_affected_by_sid(
305 user_id: i32,
306 secure_user_id: i64,
307 ) -> Result<std::vec::Vec<i64>> {
308 // This method is intended to be called by Settings and discloses a list of apps
Eran Messericfe79f12024-02-05 17:50:41 +0000309 // associated with a user, so it requires the "android.permission.MANAGE_USERS"
310 // permission (to avoid leaking list of apps to unauthorized callers).
311 check_get_app_uids_affected_by_sid_permissions().context(ks_err!())?;
Eran Messeri4dc27b52024-01-09 12:43:31 +0000312 DB.with(|db| db.borrow_mut().get_app_uids_affected_by_sid(user_id, secure_user_id))
313 .context(ks_err!("Failed to get app UIDs affected by SID"))
314 }
David Drysdale0fefae32024-09-16 13:32:27 +0100315
316 fn dump_state(&self, f: &mut dyn std::io::Write) -> std::io::Result<()> {
317 writeln!(f, "keystore2 running")?;
318 writeln!(f)?;
319
320 // Display underlying device information
321 for sec_level in &[SecurityLevel::TRUSTED_ENVIRONMENT, SecurityLevel::STRONGBOX] {
322 let Ok((_dev, hw_info, uuid)) = get_keymint_device(sec_level) else { continue };
323
324 writeln!(f, "Device info for {sec_level:?} with {uuid:?}")?;
325 writeln!(f, " HAL version: {}", hw_info.versionNumber)?;
326 writeln!(f, " Implementation name: {}", hw_info.keyMintName)?;
327 writeln!(f, " Implementation author: {}", hw_info.keyMintAuthorName)?;
328 writeln!(f, " Timestamp token required: {}", hw_info.timestampTokenRequired)?;
329 }
330 writeln!(f)?;
331
332 // Display database size information.
333 match crate::metrics_store::pull_storage_stats() {
334 Ok(atoms) => {
335 writeln!(f, "Database size information (in bytes):")?;
336 for atom in atoms {
337 if let StorageStats(stats) = &atom.payload {
338 let stype = format!("{:?}", stats.storage_type);
339 if stats.unused_size == 0 {
340 writeln!(f, " {:<40}: {:>12}", stype, stats.size)?;
341 } else {
342 writeln!(
343 f,
344 " {:<40}: {:>12} (unused {})",
345 stype, stats.size, stats.unused_size
346 )?;
347 }
348 }
349 }
350 }
351 Err(e) => {
352 writeln!(f, "Failed to retrieve storage stats: {e:?}")?;
353 }
354 }
355 writeln!(f)?;
356
David Drysdale709c2092024-06-06 16:17:28 +0100357 // Display database config information.
358 writeln!(f, "Database configuration:")?;
359 DB.with(|db| -> std::io::Result<()> {
360 let pragma_str = |f: &mut dyn std::io::Write, name| -> std::io::Result<()> {
361 let mut db = db.borrow_mut();
362 let value: String = db
363 .pragma(name)
364 .unwrap_or_else(|e| format!("unknown value for '{name}', failed: {e:?}"));
365 writeln!(f, " {name} = {value}")
366 };
367 let pragma_i32 = |f: &mut dyn std::io::Write, name| -> std::io::Result<()> {
368 let mut db = db.borrow_mut();
369 let value: i32 = db.pragma(name).unwrap_or_else(|e| {
370 log::error!("unknown value for '{name}', failed: {e:?}");
371 -1
372 });
373 writeln!(f, " {name} = {value}")
374 };
375 pragma_i32(f, "auto_vacuum")?;
376 pragma_str(f, "journal_mode")?;
377 pragma_i32(f, "journal_size_limit")?;
378 pragma_i32(f, "synchronous")?;
379 pragma_i32(f, "schema_version")?;
380 pragma_i32(f, "user_version")?;
381 Ok(())
382 })?;
383 writeln!(f)?;
384
David Drysdale49811e22023-05-22 18:51:30 +0100385 // Display accumulated metrics.
386 writeln!(f, "Metrics information:")?;
387 writeln!(f)?;
388 write!(f, "{:?}", *crate::metrics_store::METRICS_STORE)?;
389 writeln!(f)?;
390
David Drysdale0fefae32024-09-16 13:32:27 +0100391 // Reminder: any additional information added to the `dump_state()` output needs to be
392 // careful not to include confidential information (e.g. key material).
393
394 Ok(())
395 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000396
397 #[allow(dead_code)]
398 fn set_module_info(module_info: Vec<ModuleInfo>) -> Result<()> {
399 let encoding = Self::encode_module_info(module_info)
400 .map_err(|e| anyhow!({ e }))
401 .context(ks_err!("Failed to encode module_info"))?;
402 let hash = digest::Sha256::hash(&encoding).to_vec();
403
404 {
405 let mut saved = ENCODED_MODULE_INFO.write().unwrap();
406 if let Some(saved_encoding) = &*saved {
407 if *saved_encoding == encoding {
408 log::warn!(
409 "Module info already set, ignoring repeated attempt to set same info."
410 );
411 return Ok(());
412 }
413 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
414 "Failed to set module info as it is already set to a different value."
415 ));
416 }
417 *saved = Some(encoding);
418 }
419
420 let kps =
421 vec![KeyParameter { tag: Tag::MODULE_HASH, value: KeyParameterValue::Blob(hash) }];
422
423 Maintenance::call_on_all_security_levels(
424 "setAdditionalAttestationInfo",
425 |dev| dev.setAdditionalAttestationInfo(&kps),
426 Some(KEYMINT_V4),
427 )
428 }
429
430 #[allow(dead_code)]
431 fn encode_module_info(module_info: Vec<ModuleInfo>) -> Result<Vec<u8>, der::Error> {
432 SetOfVec::<ModuleInfo>::from_iter(module_info.into_iter())?.to_der()
433 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000434}
435
David Drysdale0fefae32024-09-16 13:32:27 +0100436impl Interface for Maintenance {
437 fn dump(
438 &self,
439 f: &mut dyn std::io::Write,
440 _args: &[&std::ffi::CStr],
441 ) -> Result<(), binder::StatusCode> {
442 if !keystore2_flags::enable_dump() {
443 log::info!("skipping dump() as flag not enabled");
444 return Ok(());
445 }
446 log::info!("dump()");
447 let _wp = wd::watch("IKeystoreMaintenance::dump");
448 check_dump_permission().map_err(|_e| {
449 log::error!("dump permission denied");
450 binder::StatusCode::PERMISSION_DENIED
451 })?;
452
453 self.dump_state(f).map_err(|e| {
454 log::error!("dump_state failed: {e:?}");
455 binder::StatusCode::UNKNOWN_ERROR
456 })
457 }
458}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000459
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800460impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000461 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100462 log::info!("onUserAdded(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100463 let _wp = wd::watch("IKeystoreMaintenance::onUserAdded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100464 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000465 }
466
Eric Biggersb0478cf2023-10-27 03:55:29 +0000467 fn initUserSuperKeys(
468 &self,
469 user_id: i32,
470 password: &[u8],
471 allow_existing: bool,
472 ) -> BinderResult<()> {
473 log::info!("initUserSuperKeys(user={user_id}, allow_existing={allow_existing})");
David Drysdale541846b2024-05-23 13:16:07 +0100474 let _wp = wd::watch("IKeystoreMaintenance::initUserSuperKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100475 self.init_user_super_keys(user_id, password.into(), allow_existing)
476 .map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000477 }
478
Hasini Gunasingheda895552021-01-27 19:34:37 +0000479 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100480 log::info!("onUserRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100481 let _wp = wd::watch("IKeystoreMaintenance::onUserRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100482 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000483 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800484
Eric Biggersb0478cf2023-10-27 03:55:29 +0000485 fn onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()> {
486 log::info!("onUserLskfRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100487 let _wp = wd::watch("IKeystoreMaintenance::onUserLskfRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100488 Self::on_user_lskf_removed(user_id).map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000489 }
490
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800491 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100492 log::info!("clearNamespace({domain:?}, nspace={nspace})");
David Drysdale541846b2024-05-23 13:16:07 +0100493 let _wp = wd::watch("IKeystoreMaintenance::clearNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100494 self.clear_namespace(domain, nspace).map_err(into_logged_binder)
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800495 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000496
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800497 fn earlyBootEnded(&self) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100498 log::info!("earlyBootEnded()");
David Drysdale541846b2024-05-23 13:16:07 +0100499 let _wp = wd::watch("IKeystoreMaintenance::earlyBootEnded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100500 Self::early_boot_ended().map_err(into_logged_binder)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800501 }
502
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700503 fn migrateKeyNamespace(
504 &self,
505 source: &KeyDescriptor,
506 destination: &KeyDescriptor,
507 ) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100508 log::info!("migrateKeyNamespace(src={source:?}, dest={destination:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100509 let _wp = wd::watch("IKeystoreMaintenance::migrateKeyNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100510 Self::migrate_key_namespace(source, destination).map_err(into_logged_binder)
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700511 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700512
513 fn deleteAllKeys(&self) -> BinderResult<()> {
David Drysdalece2b90b2024-07-17 15:56:29 +0100514 log::warn!("deleteAllKeys() invoked, indicating initial setup or post-factory reset");
David Drysdale541846b2024-05-23 13:16:07 +0100515 let _wp = wd::watch("IKeystoreMaintenance::deleteAllKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100516 Self::delete_all_keys().map_err(into_logged_binder)
Paul Crowley46c703e2021-08-06 15:13:53 -0700517 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000518
519 fn getAppUidsAffectedBySid(
520 &self,
521 user_id: i32,
522 secure_user_id: i64,
523 ) -> BinderResult<std::vec::Vec<i64>> {
524 log::info!("getAppUidsAffectedBySid(secure_user_id={secure_user_id:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100525 let _wp = wd::watch("IKeystoreMaintenance::getAppUidsAffectedBySid");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100526 Self::get_app_uids_affected_by_sid(user_id, secure_user_id).map_err(into_logged_binder)
Eran Messeri4dc27b52024-01-09 12:43:31 +0000527 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000528}