blob: 1a5045ec5eee5b73d5c4fb6e3d0b379716dcb910 [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 Wadheraca704492024-11-20 06:50:29 +000053/// Version number of KeyMint V4.
54pub const KEYMINT_V4: i32 = 400;
55
56/// Module information structure for DER-encoding.
57#[derive(Sequence, Debug)]
58struct ModuleInfo {
59 name: OctetString,
60 version: i32,
61}
62
63impl 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.
70 fn der_cmp(&self, other: &Self) -> std::result::Result<Ordering, der::Error> {
71 self.name.der_cmp(&other.name)
72 }
73}
74
Janis Danisevskis5898d152021-06-15 08:23:46 -070075/// The Maintenance module takes a delete listener argument which observes user and namespace
76/// deletion events.
77pub trait DeleteListener {
78 /// Called by the maintenance module when an app/namespace is deleted.
79 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>;
80 /// Called by the maintenance module when a user is deleted.
81 fn delete_user(&self, user_id: u32) -> Result<()>;
82}
83
Hasini Gunasingheda895552021-01-27 19:34:37 +000084/// This struct is defined to implement the aforementioned AIDL interface.
Janis Danisevskis5898d152021-06-15 08:23:46 -070085pub struct Maintenance {
86 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
87}
Hasini Gunasingheda895552021-01-27 19:34:37 +000088
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080089impl Maintenance {
Janis Danisevskis5898d152021-06-15 08:23:46 -070090 /// Create a new instance of Keystore Maintenance service.
91 pub fn new_native_binder(
92 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
93 ) -> Result<Strong<dyn IKeystoreMaintenance>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +000094 Ok(BnKeystoreMaintenance::new_binder(
Janis Danisevskis5898d152021-06-15 08:23:46 -070095 Self { delete_listener },
Andrew Walbrande45c8b2021-04-13 14:42:38 +000096 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
97 ))
Hasini Gunasingheda895552021-01-27 19:34:37 +000098 }
99
Janis Danisevskis5898d152021-06-15 08:23:46 -0700100 fn add_or_remove_user(&self, user_id: i32) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000101 // Check permission. Function should return if this failed. Therefore having '?' at the end
102 // is very important.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000103 check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?;
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800104
Janis Danisevskiseed69842021-02-18 20:04:10 -0800105 DB.with(|db| {
Nathan Huckleberry204a0442023-03-30 17:27:47 +0000106 SUPER_KEY.write().unwrap().remove_user(
Janis Danisevskiseed69842021-02-18 20:04:10 -0800107 &mut db.borrow_mut(),
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800108 &LEGACY_IMPORTER,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800109 user_id as u32,
Janis Danisevskiseed69842021-02-18 20:04:10 -0800110 )
111 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000112 .context(ks_err!("Trying to delete keys from db."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700113 self.delete_listener
114 .delete_user(user_id as u32)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000115 .context(ks_err!("While invoking the delete listener."))
Hasini Gunasingheda895552021-01-27 19:34:37 +0000116 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800117
Eric Biggersb0478cf2023-10-27 03:55:29 +0000118 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.
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
Janis Danisevskis5898d152021-06-15 08:23:46 -0700153 fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> {
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800154 // Permission check. Must return on error. Do not touch the '?'.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700155 check_keystore_permission(KeystorePerm::ClearUID).context("In clear_namespace.")?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800156
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800157 LEGACY_IMPORTER
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800158 .bulk_delete_uid(domain, nspace)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000159 .context(ks_err!("Trying to delete legacy keys."))?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800160 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000161 .context(ks_err!("Trying to delete keys from db."))?;
Janis Danisevskis5898d152021-06-15 08:23:46 -0700162 self.delete_listener
163 .delete_namespace(domain, nspace)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000164 .context(ks_err!("While invoking the delete listener."))
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800165 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000166
Karuna Wadheraca704492024-11-20 06:50:29 +0000167 fn call_with_watchdog<F>(
168 sec_level: SecurityLevel,
169 name: &'static str,
170 op: &F,
171 min_version: Option<i32>,
172 ) -> Result<()>
Paul Crowley46c703e2021-08-06 15:13:53 -0700173 where
Stephen Crane23cf7242022-01-19 17:49:46 +0000174 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
Paul Crowley46c703e2021-08-06 15:13:53 -0700175 {
Karuna Wadheraca704492024-11-20 06:50:29 +0000176 let (km_dev, hw_info, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000177 get_keymint_device(&sec_level).context(ks_err!("getting keymint device"))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700178
Karuna Wadheraca704492024-11-20 06:50:29 +0000179 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
David Drysdalec652f6c2024-07-18 13:01:23 +0100186 let _wp = wd::watch_millis_with("Maintenance::call_with_watchdog", 500, (sec_level, name));
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000187 map_km_error(op(km_dev)).with_context(|| ks_err!("calling {}", name))?;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800188 Ok(())
189 }
190
Karuna Wadheraca704492024-11-20 06:50:29 +0000191 fn call_on_all_security_levels<F>(
192 name: &'static str,
193 op: F,
194 min_version: Option<i32>,
195 ) -> Result<()>
Paul Crowley46c703e2021-08-06 15:13:53 -0700196 where
Stephen Crane23cf7242022-01-19 17:49:46 +0000197 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,
Paul Crowley46c703e2021-08-06 15:13:53 -0700198 {
199 let sec_levels = [
200 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
201 (SecurityLevel::STRONGBOX, "STRONGBOX"),
202 ];
James Farrelld77b97f2023-08-15 20:03:38 +0000203 sec_levels.iter().try_fold((), |_result, (sec_level, sec_level_string)| {
Karuna Wadheraca704492024-11-20 06:50:29 +0000204 let curr_result = Maintenance::call_with_watchdog(*sec_level, name, &op, min_version);
Paul Crowley46c703e2021-08-06 15:13:53 -0700205 match curr_result {
206 Ok(()) => log::info!(
207 "Call to {} succeeded for security level {}.",
208 name,
209 &sec_level_string
210 ),
David Drysdalece2b90b2024-07-17 15:56:29 +0100211 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 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700226 }
James Farrelld77b97f2023-08-15 20:03:38 +0000227 curr_result
Paul Crowley46c703e2021-08-06 15:13:53 -0700228 })
229 }
230
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800231 fn early_boot_ended() -> Result<()> {
Janis Danisevskisa916d992021-10-19 15:46:09 -0700232 check_keystore_permission(KeystorePerm::EarlyBootEnded)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000233 .context(ks_err!("Checking permission"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000234 log::info!("In early_boot_ended.");
235
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800236 if let Err(e) =
237 DB.with(|db| SuperKeyManager::set_up_boot_level_cache(&SUPER_KEY, &mut db.borrow_mut()))
238 {
Paul Crowley44c02da2021-04-08 17:04:43 +0000239 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
240 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000241
242 Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded(), None)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800243 }
244
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700245 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
John Wu889c1cc2022-03-14 16:02:56 -0700246 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700247
John Wu889c1cc2022-03-14 16:02:56 -0700248 match source.domain {
249 Domain::SELINUX | Domain::KEY_ID | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800250 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000251 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
252 .context(ks_err!("Source domain must be one of APP, SELINUX, or KEY_ID."));
John Wu16db29e2022-01-13 15:21:43 -0800253 }
254 };
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700255
John Wu889c1cc2022-03-14 16:02:56 -0700256 match destination.domain {
257 Domain::SELINUX | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800258 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000259 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
260 .context(ks_err!("Destination domain must be one of APP or SELINUX."));
John Wu16db29e2022-01-13 15:21:43 -0800261 }
262 };
263
John Wu889c1cc2022-03-14 16:02:56 -0700264 let user_id = uid_to_android_user(calling_uid);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800265
Eric Biggers673d34a2023-10-18 01:54:18 +0000266 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800267
268 DB.with(|db| {
John Wu889c1cc2022-03-14 16:02:56 -0700269 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 )
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800282 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000283 .context(ks_err!("Failed to load key blob."))?;
John Wu889c1cc2022-03-14 16:02:56 -0700284 {
285 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, calling_uid, |k| {
286 check_key_permission(KeyPerm::Rebind, k, &None)
287 })
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800288 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700289 })
290 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700291
292 fn delete_all_keys() -> Result<()> {
293 // Security critical permission check. This statement must return on fail.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700294 check_keystore_permission(KeystorePerm::DeleteAllKeys)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000295 .context(ks_err!("Checking permission"))?;
Paul Crowley46c703e2021-08-06 15:13:53 -0700296 log::info!("In delete_all_keys.");
297
Karuna Wadheraca704492024-11-20 06:50:29 +0000298 Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys(), None)
Paul Crowley46c703e2021-08-06 15:13:53 -0700299 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000300
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
Eran Messericfe79f12024-02-05 17:50:41 +0000306 // 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!())?;
Eran Messeri4dc27b52024-01-09 12:43:31 +0000309 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 }
David Drysdale0fefae32024-09-16 13:32:27 +0100312
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
David Drysdale49811e22023-05-22 18:51:30 +0100354 // Display accumulated metrics.
355 writeln!(f, "Metrics information:")?;
356 writeln!(f)?;
357 write!(f, "{:?}", *crate::metrics_store::METRICS_STORE)?;
358 writeln!(f)?;
359
David Drysdale0fefae32024-09-16 13:32:27 +0100360 // 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 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000365
366 #[allow(dead_code)]
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)]
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 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000403}
404
David Drysdale0fefae32024-09-16 13:32:27 +0100405impl Interface for Maintenance {
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}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000428
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800429impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000430 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100431 log::info!("onUserAdded(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100432 let _wp = wd::watch("IKeystoreMaintenance::onUserAdded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100433 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000434 }
435
Eric Biggersb0478cf2023-10-27 03:55:29 +0000436 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})");
David Drysdale541846b2024-05-23 13:16:07 +0100443 let _wp = wd::watch("IKeystoreMaintenance::initUserSuperKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100444 self.init_user_super_keys(user_id, password.into(), allow_existing)
445 .map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000446 }
447
Hasini Gunasingheda895552021-01-27 19:34:37 +0000448 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100449 log::info!("onUserRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100450 let _wp = wd::watch("IKeystoreMaintenance::onUserRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100451 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000452 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800453
Eric Biggersb0478cf2023-10-27 03:55:29 +0000454 fn onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()> {
455 log::info!("onUserLskfRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100456 let _wp = wd::watch("IKeystoreMaintenance::onUserLskfRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100457 Self::on_user_lskf_removed(user_id).map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000458 }
459
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800460 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100461 log::info!("clearNamespace({domain:?}, nspace={nspace})");
David Drysdale541846b2024-05-23 13:16:07 +0100462 let _wp = wd::watch("IKeystoreMaintenance::clearNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100463 self.clear_namespace(domain, nspace).map_err(into_logged_binder)
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800464 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000465
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800466 fn earlyBootEnded(&self) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100467 log::info!("earlyBootEnded()");
David Drysdale541846b2024-05-23 13:16:07 +0100468 let _wp = wd::watch("IKeystoreMaintenance::earlyBootEnded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100469 Self::early_boot_ended().map_err(into_logged_binder)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800470 }
471
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700472 fn migrateKeyNamespace(
473 &self,
474 source: &KeyDescriptor,
475 destination: &KeyDescriptor,
476 ) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100477 log::info!("migrateKeyNamespace(src={source:?}, dest={destination:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100478 let _wp = wd::watch("IKeystoreMaintenance::migrateKeyNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100479 Self::migrate_key_namespace(source, destination).map_err(into_logged_binder)
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700480 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700481
482 fn deleteAllKeys(&self) -> BinderResult<()> {
David Drysdalece2b90b2024-07-17 15:56:29 +0100483 log::warn!("deleteAllKeys() invoked, indicating initial setup or post-factory reset");
David Drysdale541846b2024-05-23 13:16:07 +0100484 let _wp = wd::watch("IKeystoreMaintenance::deleteAllKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100485 Self::delete_all_keys().map_err(into_logged_binder)
Paul Crowley46c703e2021-08-06 15:13:53 -0700486 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000487
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:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100494 let _wp = wd::watch("IKeystoreMaintenance::getAppUidsAffectedBySid");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100495 Self::get_app_uids_affected_by_sid(user_id, secure_user_id).map_err(into_logged_binder)
Eran Messeri4dc27b52024-01-09 12:43:31 +0000496 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000497}