blob: a0f5ee8a5151b0489cec53dc5bf1ce2e86b5a4d7 [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 {
Karuna Wadhera1dc2c462024-12-28 00:34:13 +0000224 log::info!("Call to {} failed for StrongBox as it is not available", name);
225 return Ok(());
David Drysdalece2b90b2024-07-17 15:56:29 +0100226 } else {
227 log::error!(
228 "Call to {} failed for security level {}: {}.",
229 name,
230 &sec_level_string,
231 e
232 )
233 }
234 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700235 }
James Farrelld77b97f2023-08-15 20:03:38 +0000236 curr_result
Paul Crowley46c703e2021-08-06 15:13:53 -0700237 })
238 }
239
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800240 fn early_boot_ended() -> Result<()> {
Janis Danisevskisa916d992021-10-19 15:46:09 -0700241 check_keystore_permission(KeystorePerm::EarlyBootEnded)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000242 .context(ks_err!("Checking permission"))?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000243 log::info!("In early_boot_ended.");
244
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800245 if let Err(e) =
246 DB.with(|db| SuperKeyManager::set_up_boot_level_cache(&SUPER_KEY, &mut db.borrow_mut()))
247 {
Paul Crowley44c02da2021-04-08 17:04:43 +0000248 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
249 }
Karuna Wadherafd8b9eb2025-03-19 17:56:35 +0000250 Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded(), None)
251 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000252
Karuna Wadherafd8b9eb2025-03-19 17:56:35 +0000253 /// Spawns a thread to send module info if it hasn't already been sent. The thread first waits
254 /// for the apex info to be available.
255 /// (Module info would have already been sent in the case of a Keystore restart.)
256 ///
257 /// # Panics
258 ///
259 /// This method, and methods it calls, panic on failure, because a failure to populate module
260 /// information will block the boot process from completing. In this method, this happens if:
261 /// - the `apexd.status` property is unable to be monitored
262 /// - the `keystore.module_hash.sent` property cannot be updated
263 pub fn check_send_module_info() {
264 if rustutils::system_properties::read_bool("keystore.module_hash.sent", false)
265 .unwrap_or(false)
266 {
267 log::info!("Module info has already been sent.");
268 return;
269 }
David Drysdale1ce15612024-12-05 18:50:40 +0000270 if keystore2_flags::attest_modules() {
271 std::thread::spawn(move || {
Karuna Wadherafd8b9eb2025-03-19 17:56:35 +0000272 // Wait for apex info to be available before populating.
273 Self::watch_apex_info().unwrap_or_else(|e| {
274 log::error!("failed to monitor apexd.status property: {e:?}");
275 panic!("Terminating due to inaccessibility of apexd.status property, blocking boot: {e:?}");
276 });
David Drysdale1ce15612024-12-05 18:50:40 +0000277 });
Karuna Wadhera1dc2c462024-12-28 00:34:13 +0000278 } else {
279 rustutils::system_properties::write("keystore.module_hash.sent", "true")
Karuna Wadherafd8b9eb2025-03-19 17:56:35 +0000280 .unwrap_or_else(|e| {
281 log::error!("Failed to set keystore.module_hash.sent to true; this will therefore block boot: {e:?}");
282 panic!("Crashing Keystore because it failed to set keystore.module_hash.sent to true (which blocks boot).");
283 }
284 );
David Drysdale1ce15612024-12-05 18:50:40 +0000285 }
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800286 }
287
David Drysdale1ce15612024-12-05 18:50:40 +0000288 /// Watch the `apexd.status` system property, and read apex module information once
289 /// it is `activated`.
290 ///
291 /// Blocks waiting for system property changes, so must be run in its own thread.
292 fn watch_apex_info() -> Result<()> {
Karuna Wadhera1dc2c462024-12-28 00:34:13 +0000293 let apex_prop = "apexd.status";
294 log::info!("start monitoring '{apex_prop}' property");
295 let mut w =
296 PropertyWatcher::new(apex_prop).context(ks_err!("PropertyWatcher::new failed"))?;
David Drysdale1ce15612024-12-05 18:50:40 +0000297 loop {
298 let value = w.read(|_name, value| Ok(value.to_string()));
Karuna Wadhera1dc2c462024-12-28 00:34:13 +0000299 log::info!("property '{apex_prop}' is now '{value:?}'");
300 if matches!(value.as_deref(), Ok("activated")) {
Karuna Wadherafd8b9eb2025-03-19 17:56:35 +0000301 Self::read_and_set_module_info();
302 return Ok(());
David Drysdale1ce15612024-12-05 18:50:40 +0000303 }
Karuna Wadhera1dc2c462024-12-28 00:34:13 +0000304 log::info!("await a change to '{apex_prop}'...");
David Drysdale1ce15612024-12-05 18:50:40 +0000305 w.wait(None).context(ks_err!("property wait failed"))?;
Karuna Wadhera1dc2c462024-12-28 00:34:13 +0000306 log::info!("await a change to '{apex_prop}'...notified");
David Drysdale1ce15612024-12-05 18:50:40 +0000307 }
Karuna Wadherafd8b9eb2025-03-19 17:56:35 +0000308 }
309
310 /// Read apex information (which is assumed to be present) and propagate module
311 /// information to KeyMint instances.
312 ///
313 /// # Panics
314 ///
315 /// This method panics on failure, because a failure to populate module information
316 /// will block the boot process from completing. This happens if:
317 /// - apex information is not available (precondition)
318 /// - KeyMint instances fail to accept module information
319 /// - the `keystore.module_hash.sent` property cannot be updated
320 fn read_and_set_module_info() {
321 let modules = Self::read_apex_info().unwrap_or_else(|e| {
322 log::error!("failed to read apex info: {e:?}");
323 panic!("Terminating due to unavailability of apex info, blocking boot: {e:?}");
324 });
325 Self::set_module_info(modules).unwrap_or_else(|e| {
326 log::error!("failed to set module info: {e:?}");
327 panic!("Terminating due to KeyMint not accepting module info, blocking boot: {e:?}");
328 });
329 rustutils::system_properties::write("keystore.module_hash.sent", "true").unwrap_or_else(|e| {
330 log::error!("failed to set keystore.module_hash.sent property: {e:?}");
331 panic!("Terminating due to failure to set keystore.module_hash.sent property, blocking boot: {e:?}");
332 });
David Drysdale1ce15612024-12-05 18:50:40 +0000333 }
334
335 fn read_apex_info() -> Result<Vec<ModuleInfo>> {
336 let _wp = wd::watch("read_apex_info via IApexService.getActivePackages()");
337 let apexd: Strong<dyn IApexService> =
338 wait_for_interface("apexservice").context("failed to AIDL connect to apexd")?;
339 let packages = apexd.getActivePackages().context("failed to retrieve active packages")?;
340 packages
341 .into_iter()
342 .map(|pkg| {
343 log::info!("apex modules += {} version {}", pkg.moduleName, pkg.versionCode);
344 let name = OctetString::new(pkg.moduleName.as_bytes()).map_err(|e| {
345 anyhow!("failed to convert '{}' to OCTET_STRING: {e:?}", pkg.moduleName)
346 })?;
347 Ok(ModuleInfo { name, version: pkg.versionCode })
348 })
349 .collect()
350 }
351
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700352 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
John Wu889c1cc2022-03-14 16:02:56 -0700353 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700354
John Wu889c1cc2022-03-14 16:02:56 -0700355 match source.domain {
356 Domain::SELINUX | Domain::KEY_ID | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800357 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000358 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
359 .context(ks_err!("Source domain must be one of APP, SELINUX, or KEY_ID."));
John Wu16db29e2022-01-13 15:21:43 -0800360 }
361 };
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700362
John Wu889c1cc2022-03-14 16:02:56 -0700363 match destination.domain {
364 Domain::SELINUX | Domain::APP => (),
John Wu16db29e2022-01-13 15:21:43 -0800365 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000366 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
367 .context(ks_err!("Destination domain must be one of APP or SELINUX."));
John Wu16db29e2022-01-13 15:21:43 -0800368 }
369 };
370
John Wu889c1cc2022-03-14 16:02:56 -0700371 let user_id = uid_to_android_user(calling_uid);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800372
Eric Biggers673d34a2023-10-18 01:54:18 +0000373 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800374
375 DB.with(|db| {
John Wu889c1cc2022-03-14 16:02:56 -0700376 let (key_id_guard, _) = LEGACY_IMPORTER
377 .with_try_import(source, calling_uid, super_key, || {
378 db.borrow_mut().load_key_entry(
379 source,
380 KeyType::Client,
381 KeyEntryLoadBits::NONE,
382 calling_uid,
383 |k, av| {
384 check_key_permission(KeyPerm::Use, k, &av)?;
385 check_key_permission(KeyPerm::Delete, k, &av)?;
386 check_key_permission(KeyPerm::Grant, k, &av)
387 },
388 )
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800389 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000390 .context(ks_err!("Failed to load key blob."))?;
John Wu889c1cc2022-03-14 16:02:56 -0700391 {
392 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, calling_uid, |k| {
393 check_key_permission(KeyPerm::Rebind, k, &None)
394 })
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800395 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700396 })
397 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700398
399 fn delete_all_keys() -> Result<()> {
400 // Security critical permission check. This statement must return on fail.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700401 check_keystore_permission(KeystorePerm::DeleteAllKeys)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000402 .context(ks_err!("Checking permission"))?;
Paul Crowley46c703e2021-08-06 15:13:53 -0700403 log::info!("In delete_all_keys.");
404
Karuna Wadheraca704492024-11-20 06:50:29 +0000405 Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys(), None)
Paul Crowley46c703e2021-08-06 15:13:53 -0700406 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000407
408 fn get_app_uids_affected_by_sid(
409 user_id: i32,
410 secure_user_id: i64,
411 ) -> Result<std::vec::Vec<i64>> {
412 // This method is intended to be called by Settings and discloses a list of apps
Eran Messericfe79f12024-02-05 17:50:41 +0000413 // associated with a user, so it requires the "android.permission.MANAGE_USERS"
414 // permission (to avoid leaking list of apps to unauthorized callers).
415 check_get_app_uids_affected_by_sid_permissions().context(ks_err!())?;
Eran Messeri4dc27b52024-01-09 12:43:31 +0000416 DB.with(|db| db.borrow_mut().get_app_uids_affected_by_sid(user_id, secure_user_id))
417 .context(ks_err!("Failed to get app UIDs affected by SID"))
418 }
David Drysdale0fefae32024-09-16 13:32:27 +0100419
420 fn dump_state(&self, f: &mut dyn std::io::Write) -> std::io::Result<()> {
421 writeln!(f, "keystore2 running")?;
422 writeln!(f)?;
423
David Drysdale72173862025-03-17 18:06:24 +0000424 // Display underlying device information.
425 //
426 // Note that this chunk of output is parsed in a GTS test, so do not change the format
427 // without checking that the test still works.
David Drysdale0fefae32024-09-16 13:32:27 +0100428 for sec_level in &[SecurityLevel::TRUSTED_ENVIRONMENT, SecurityLevel::STRONGBOX] {
429 let Ok((_dev, hw_info, uuid)) = get_keymint_device(sec_level) else { continue };
430
431 writeln!(f, "Device info for {sec_level:?} with {uuid:?}")?;
432 writeln!(f, " HAL version: {}", hw_info.versionNumber)?;
433 writeln!(f, " Implementation name: {}", hw_info.keyMintName)?;
434 writeln!(f, " Implementation author: {}", hw_info.keyMintAuthorName)?;
435 writeln!(f, " Timestamp token required: {}", hw_info.timestampTokenRequired)?;
436 }
437 writeln!(f)?;
438
David Drysdale37fcf5b2024-12-11 11:07:56 +0000439 // Display module attestation information
440 {
441 let info = ENCODED_MODULE_INFO.read().unwrap();
442 if let Some(info) = info.as_ref() {
443 writeln!(f, "Attested module information (DER-encoded):")?;
444 writeln!(f, " {}", hex::encode(info))?;
445 writeln!(f)?;
446 } else {
447 writeln!(f, "Attested module information not set")?;
448 writeln!(f)?;
449 }
450 }
451
David Drysdale0fefae32024-09-16 13:32:27 +0100452 // Display database size information.
453 match crate::metrics_store::pull_storage_stats() {
454 Ok(atoms) => {
455 writeln!(f, "Database size information (in bytes):")?;
456 for atom in atoms {
457 if let StorageStats(stats) = &atom.payload {
458 let stype = format!("{:?}", stats.storage_type);
459 if stats.unused_size == 0 {
460 writeln!(f, " {:<40}: {:>12}", stype, stats.size)?;
461 } else {
462 writeln!(
463 f,
464 " {:<40}: {:>12} (unused {})",
465 stype, stats.size, stats.unused_size
466 )?;
467 }
468 }
469 }
470 }
471 Err(e) => {
472 writeln!(f, "Failed to retrieve storage stats: {e:?}")?;
473 }
474 }
475 writeln!(f)?;
476
David Drysdale709c2092024-06-06 16:17:28 +0100477 // Display database config information.
478 writeln!(f, "Database configuration:")?;
479 DB.with(|db| -> std::io::Result<()> {
480 let pragma_str = |f: &mut dyn std::io::Write, name| -> std::io::Result<()> {
481 let mut db = db.borrow_mut();
482 let value: String = db
483 .pragma(name)
484 .unwrap_or_else(|e| format!("unknown value for '{name}', failed: {e:?}"));
485 writeln!(f, " {name} = {value}")
486 };
487 let pragma_i32 = |f: &mut dyn std::io::Write, name| -> std::io::Result<()> {
488 let mut db = db.borrow_mut();
489 let value: i32 = db.pragma(name).unwrap_or_else(|e| {
490 log::error!("unknown value for '{name}', failed: {e:?}");
491 -1
492 });
493 writeln!(f, " {name} = {value}")
494 };
495 pragma_i32(f, "auto_vacuum")?;
496 pragma_str(f, "journal_mode")?;
497 pragma_i32(f, "journal_size_limit")?;
498 pragma_i32(f, "synchronous")?;
499 pragma_i32(f, "schema_version")?;
500 pragma_i32(f, "user_version")?;
501 Ok(())
502 })?;
503 writeln!(f)?;
504
David Drysdale49811e22023-05-22 18:51:30 +0100505 // Display accumulated metrics.
506 writeln!(f, "Metrics information:")?;
507 writeln!(f)?;
508 write!(f, "{:?}", *crate::metrics_store::METRICS_STORE)?;
509 writeln!(f)?;
510
David Drysdale0fefae32024-09-16 13:32:27 +0100511 // Reminder: any additional information added to the `dump_state()` output needs to be
512 // careful not to include confidential information (e.g. key material).
513
514 Ok(())
515 }
Karuna Wadheraca704492024-11-20 06:50:29 +0000516
Karuna Wadheraca704492024-11-20 06:50:29 +0000517 fn set_module_info(module_info: Vec<ModuleInfo>) -> Result<()> {
David Drysdale1ce15612024-12-05 18:50:40 +0000518 log::info!("set_module_info with {} modules", module_info.len());
Karuna Wadheraca704492024-11-20 06:50:29 +0000519 let encoding = Self::encode_module_info(module_info)
520 .map_err(|e| anyhow!({ e }))
521 .context(ks_err!("Failed to encode module_info"))?;
522 let hash = digest::Sha256::hash(&encoding).to_vec();
523
524 {
525 let mut saved = ENCODED_MODULE_INFO.write().unwrap();
526 if let Some(saved_encoding) = &*saved {
527 if *saved_encoding == encoding {
528 log::warn!(
529 "Module info already set, ignoring repeated attempt to set same info."
530 );
531 return Ok(());
532 }
533 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
534 "Failed to set module info as it is already set to a different value."
535 ));
536 }
537 *saved = Some(encoding);
538 }
539
540 let kps =
541 vec![KeyParameter { tag: Tag::MODULE_HASH, value: KeyParameterValue::Blob(hash) }];
542
543 Maintenance::call_on_all_security_levels(
544 "setAdditionalAttestationInfo",
545 |dev| dev.setAdditionalAttestationInfo(&kps),
546 Some(KEYMINT_V4),
547 )
548 }
549
Karuna Wadheraca704492024-11-20 06:50:29 +0000550 fn encode_module_info(module_info: Vec<ModuleInfo>) -> Result<Vec<u8>, der::Error> {
551 SetOfVec::<ModuleInfo>::from_iter(module_info.into_iter())?.to_der()
552 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000553}
554
David Drysdale0fefae32024-09-16 13:32:27 +0100555impl Interface for Maintenance {
556 fn dump(
557 &self,
558 f: &mut dyn std::io::Write,
559 _args: &[&std::ffi::CStr],
560 ) -> Result<(), binder::StatusCode> {
David Drysdale0fefae32024-09-16 13:32:27 +0100561 log::info!("dump()");
562 let _wp = wd::watch("IKeystoreMaintenance::dump");
563 check_dump_permission().map_err(|_e| {
564 log::error!("dump permission denied");
565 binder::StatusCode::PERMISSION_DENIED
566 })?;
567
568 self.dump_state(f).map_err(|e| {
569 log::error!("dump_state failed: {e:?}");
570 binder::StatusCode::UNKNOWN_ERROR
571 })
572 }
573}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000574
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800575impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000576 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100577 log::info!("onUserAdded(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100578 let _wp = wd::watch("IKeystoreMaintenance::onUserAdded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100579 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000580 }
581
Eric Biggersb0478cf2023-10-27 03:55:29 +0000582 fn initUserSuperKeys(
583 &self,
584 user_id: i32,
585 password: &[u8],
586 allow_existing: bool,
587 ) -> BinderResult<()> {
588 log::info!("initUserSuperKeys(user={user_id}, allow_existing={allow_existing})");
David Drysdale541846b2024-05-23 13:16:07 +0100589 let _wp = wd::watch("IKeystoreMaintenance::initUserSuperKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100590 self.init_user_super_keys(user_id, password.into(), allow_existing)
591 .map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000592 }
593
Hasini Gunasingheda895552021-01-27 19:34:37 +0000594 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100595 log::info!("onUserRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100596 let _wp = wd::watch("IKeystoreMaintenance::onUserRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100597 self.add_or_remove_user(user_id).map_err(into_logged_binder)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000598 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800599
Eric Biggersb0478cf2023-10-27 03:55:29 +0000600 fn onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()> {
601 log::info!("onUserLskfRemoved(user={user_id})");
David Drysdale541846b2024-05-23 13:16:07 +0100602 let _wp = wd::watch("IKeystoreMaintenance::onUserLskfRemoved");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100603 Self::on_user_lskf_removed(user_id).map_err(into_logged_binder)
Eric Biggersb0478cf2023-10-27 03:55:29 +0000604 }
605
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800606 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100607 log::info!("clearNamespace({domain:?}, nspace={nspace})");
David Drysdale541846b2024-05-23 13:16:07 +0100608 let _wp = wd::watch("IKeystoreMaintenance::clearNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100609 self.clear_namespace(domain, nspace).map_err(into_logged_binder)
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800610 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000611
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800612 fn earlyBootEnded(&self) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100613 log::info!("earlyBootEnded()");
David Drysdale541846b2024-05-23 13:16:07 +0100614 let _wp = wd::watch("IKeystoreMaintenance::earlyBootEnded");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100615 Self::early_boot_ended().map_err(into_logged_binder)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800616 }
617
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700618 fn migrateKeyNamespace(
619 &self,
620 source: &KeyDescriptor,
621 destination: &KeyDescriptor,
622 ) -> BinderResult<()> {
David Drysdalee85523f2023-06-19 12:28:53 +0100623 log::info!("migrateKeyNamespace(src={source:?}, dest={destination:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100624 let _wp = wd::watch("IKeystoreMaintenance::migrateKeyNamespace");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100625 Self::migrate_key_namespace(source, destination).map_err(into_logged_binder)
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700626 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700627
628 fn deleteAllKeys(&self) -> BinderResult<()> {
David Drysdalece2b90b2024-07-17 15:56:29 +0100629 log::warn!("deleteAllKeys() invoked, indicating initial setup or post-factory reset");
David Drysdale541846b2024-05-23 13:16:07 +0100630 let _wp = wd::watch("IKeystoreMaintenance::deleteAllKeys");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100631 Self::delete_all_keys().map_err(into_logged_binder)
Paul Crowley46c703e2021-08-06 15:13:53 -0700632 }
Eran Messeri4dc27b52024-01-09 12:43:31 +0000633
634 fn getAppUidsAffectedBySid(
635 &self,
636 user_id: i32,
637 secure_user_id: i64,
638 ) -> BinderResult<std::vec::Vec<i64>> {
639 log::info!("getAppUidsAffectedBySid(secure_user_id={secure_user_id:?})");
David Drysdale541846b2024-05-23 13:16:07 +0100640 let _wp = wd::watch("IKeystoreMaintenance::getAppUidsAffectedBySid");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100641 Self::get_app_uids_affected_by_sid(user_id, secure_user_id).map_err(into_logged_binder)
Eran Messeri4dc27b52024-01-09 12:43:31 +0000642 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000643}