Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1 | // 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 Danisevskis | 34a0cf2 | 2021-03-08 09:19:03 -0800 | [diff] [blame] | 15 | //! This module implements IKeystoreMaintenance AIDL interface. |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 16 | |
Eric Biggers | b5613da | 2024-03-13 19:31:42 +0000 | [diff] [blame] | 17 | use crate::database::{KeyEntryLoadBits, KeyType}; |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 18 | use crate::error::into_logged_binder; |
Satya Tangirala | 5b9e5b1 | 2021-03-09 12:54:21 -0800 | [diff] [blame] | 19 | use crate::error::map_km_error; |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 20 | use crate::error::Error; |
Satya Tangirala | 5b9e5b1 | 2021-03-09 12:54:21 -0800 | [diff] [blame] | 21 | use crate::globals::get_keymint_device; |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 22 | use crate::globals::{DB, LEGACY_IMPORTER, SUPER_KEY, ENCODED_MODULE_INFO}; |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 23 | use crate::ks_err; |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 24 | use crate::permission::{KeyPerm, KeystorePerm}; |
Eric Biggers | 9f7ebeb | 2024-06-20 14:59:32 +0000 | [diff] [blame] | 25 | use crate::super_key::SuperKeyManager; |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 26 | use crate::utils::{ |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame] | 27 | check_dump_permission, check_get_app_uids_affected_by_sid_permissions, check_key_permission, |
Eran Messeri | cfe79f1 | 2024-02-05 17:50:41 +0000 | [diff] [blame] | 28 | check_keystore_permission, uid_to_android_user, watchdog as wd, |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 29 | }; |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 30 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 31 | ErrorCode::ErrorCode, IKeyMintDevice::IKeyMintDevice, KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag, |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 32 | }; |
Eric Biggers | 2f9498a | 2023-10-09 23:16:05 +0000 | [diff] [blame] | 33 | use android_security_maintenance::aidl::android::security::maintenance::IKeystoreMaintenance::{ |
| 34 | BnKeystoreMaintenance, IKeystoreMaintenance, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 35 | }; |
Andrew Walbran | de45c8b | 2021-04-13 14:42:38 +0000 | [diff] [blame] | 36 | use android_security_maintenance::binder::{ |
| 37 | BinderFeatures, Interface, Result as BinderResult, Strong, ThreadState, |
| 38 | }; |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame] | 39 | use android_security_metrics::aidl::android::security::metrics::{ |
| 40 | KeystoreAtomPayload::KeystoreAtomPayload::StorageStats |
| 41 | }; |
Janis Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 42 | use android_system_keystore2::aidl::android::system::keystore2::KeyDescriptor::KeyDescriptor; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 43 | use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode; |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 44 | use anyhow::{anyhow, Context, Result}; |
| 45 | use bssl_crypto::digest; |
| 46 | use der::{DerOrd, Encode, asn1::OctetString, asn1::SetOfVec, Sequence}; |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 47 | use keystore2_crypto::Password; |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 48 | use std::cmp::Ordering; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 49 | |
Janis Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 50 | /// Reexport Domain for the benefit of DeleteListener |
| 51 | pub use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain; |
| 52 | |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 53 | /// Version number of KeyMint V4. |
| 54 | pub const KEYMINT_V4: i32 = 400; |
| 55 | |
| 56 | /// Module information structure for DER-encoding. |
| 57 | #[derive(Sequence, Debug)] |
| 58 | struct ModuleInfo { |
| 59 | name: OctetString, |
| 60 | version: i32, |
| 61 | } |
| 62 | |
| 63 | impl 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 Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 75 | /// The Maintenance module takes a delete listener argument which observes user and namespace |
| 76 | /// deletion events. |
| 77 | pub 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 Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 84 | /// This struct is defined to implement the aforementioned AIDL interface. |
Janis Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 85 | pub struct Maintenance { |
| 86 | delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>, |
| 87 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 88 | |
Janis Danisevskis | 34a0cf2 | 2021-03-08 09:19:03 -0800 | [diff] [blame] | 89 | impl Maintenance { |
Janis Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 90 | /// 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 Walbran | de45c8b | 2021-04-13 14:42:38 +0000 | [diff] [blame] | 94 | Ok(BnKeystoreMaintenance::new_binder( |
Janis Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 95 | Self { delete_listener }, |
Andrew Walbran | de45c8b | 2021-04-13 14:42:38 +0000 | [diff] [blame] | 96 | BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() }, |
| 97 | )) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 98 | } |
| 99 | |
Janis Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 100 | fn add_or_remove_user(&self, user_id: i32) -> Result<()> { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 101 | // Check permission. Function should return if this failed. Therefore having '?' at the end |
| 102 | // is very important. |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 103 | check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?; |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 104 | |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 105 | DB.with(|db| { |
Nathan Huckleberry | 204a044 | 2023-03-30 17:27:47 +0000 | [diff] [blame] | 106 | SUPER_KEY.write().unwrap().remove_user( |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 107 | &mut db.borrow_mut(), |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 108 | &LEGACY_IMPORTER, |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 109 | user_id as u32, |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 110 | ) |
| 111 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 112 | .context(ks_err!("Trying to delete keys from db."))?; |
Janis Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 113 | self.delete_listener |
| 114 | .delete_user(user_id as u32) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 115 | .context(ks_err!("While invoking the delete listener.")) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 116 | } |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 117 | |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 118 | 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 Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 153 | fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> { |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 154 | // Permission check. Must return on error. Do not touch the '?'. |
Janis Danisevskis | a916d99 | 2021-10-19 15:46:09 -0700 | [diff] [blame] | 155 | check_keystore_permission(KeystorePerm::ClearUID).context("In clear_namespace.")?; |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 156 | |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 157 | LEGACY_IMPORTER |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 158 | .bulk_delete_uid(domain, nspace) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 159 | .context(ks_err!("Trying to delete legacy keys."))?; |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 160 | DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 161 | .context(ks_err!("Trying to delete keys from db."))?; |
Janis Danisevskis | 5898d15 | 2021-06-15 08:23:46 -0700 | [diff] [blame] | 162 | self.delete_listener |
| 163 | .delete_namespace(domain, nspace) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 164 | .context(ks_err!("While invoking the delete listener.")) |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 165 | } |
Hasini Gunasinghe | 9ee1841 | 2021-03-11 20:12:44 +0000 | [diff] [blame] | 166 | |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 167 | fn call_with_watchdog<F>( |
| 168 | sec_level: SecurityLevel, |
| 169 | name: &'static str, |
| 170 | op: &F, |
| 171 | min_version: Option<i32>, |
| 172 | ) -> Result<()> |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 173 | where |
Stephen Crane | 23cf724 | 2022-01-19 17:49:46 +0000 | [diff] [blame] | 174 | F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>, |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 175 | { |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 176 | let (km_dev, hw_info, _) = |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 177 | get_keymint_device(&sec_level).context(ks_err!("getting keymint device"))?; |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 178 | |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 179 | 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 Drysdale | c652f6c | 2024-07-18 13:01:23 +0100 | [diff] [blame] | 186 | let _wp = wd::watch_millis_with("Maintenance::call_with_watchdog", 500, (sec_level, name)); |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 187 | map_km_error(op(km_dev)).with_context(|| ks_err!("calling {}", name))?; |
Satya Tangirala | 5b9e5b1 | 2021-03-09 12:54:21 -0800 | [diff] [blame] | 188 | Ok(()) |
| 189 | } |
| 190 | |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 191 | fn call_on_all_security_levels<F>( |
| 192 | name: &'static str, |
| 193 | op: F, |
| 194 | min_version: Option<i32>, |
| 195 | ) -> Result<()> |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 196 | where |
Stephen Crane | 23cf724 | 2022-01-19 17:49:46 +0000 | [diff] [blame] | 197 | F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>, |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 198 | { |
| 199 | let sec_levels = [ |
| 200 | (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"), |
| 201 | (SecurityLevel::STRONGBOX, "STRONGBOX"), |
| 202 | ]; |
James Farrell | d77b97f | 2023-08-15 20:03:38 +0000 | [diff] [blame] | 203 | sec_levels.iter().try_fold((), |_result, (sec_level, sec_level_string)| { |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 204 | let curr_result = Maintenance::call_with_watchdog(*sec_level, name, &op, min_version); |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 205 | match curr_result { |
| 206 | Ok(()) => log::info!( |
| 207 | "Call to {} succeeded for security level {}.", |
| 208 | name, |
| 209 | &sec_level_string |
| 210 | ), |
David Drysdale | ce2b90b | 2024-07-17 15:56:29 +0100 | [diff] [blame] | 211 | 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 Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 226 | } |
James Farrell | d77b97f | 2023-08-15 20:03:38 +0000 | [diff] [blame] | 227 | curr_result |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 228 | }) |
| 229 | } |
| 230 | |
Satya Tangirala | 5b9e5b1 | 2021-03-09 12:54:21 -0800 | [diff] [blame] | 231 | fn early_boot_ended() -> Result<()> { |
Janis Danisevskis | a916d99 | 2021-10-19 15:46:09 -0700 | [diff] [blame] | 232 | check_keystore_permission(KeystorePerm::EarlyBootEnded) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 233 | .context(ks_err!("Checking permission"))?; |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 234 | log::info!("In early_boot_ended."); |
| 235 | |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 236 | if let Err(e) = |
| 237 | DB.with(|db| SuperKeyManager::set_up_boot_level_cache(&SUPER_KEY, &mut db.borrow_mut())) |
| 238 | { |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 239 | log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e); |
| 240 | } |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 241 | |
| 242 | Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded(), None) |
Satya Tangirala | 5b9e5b1 | 2021-03-09 12:54:21 -0800 | [diff] [blame] | 243 | } |
| 244 | |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 245 | fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> { |
John Wu | 889c1cc | 2022-03-14 16:02:56 -0700 | [diff] [blame] | 246 | let calling_uid = ThreadState::get_calling_uid(); |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 247 | |
John Wu | 889c1cc | 2022-03-14 16:02:56 -0700 | [diff] [blame] | 248 | match source.domain { |
| 249 | Domain::SELINUX | Domain::KEY_ID | Domain::APP => (), |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 250 | _ => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 251 | return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)) |
| 252 | .context(ks_err!("Source domain must be one of APP, SELINUX, or KEY_ID.")); |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 253 | } |
| 254 | }; |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 255 | |
John Wu | 889c1cc | 2022-03-14 16:02:56 -0700 | [diff] [blame] | 256 | match destination.domain { |
| 257 | Domain::SELINUX | Domain::APP => (), |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 258 | _ => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 259 | return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)) |
| 260 | .context(ks_err!("Destination domain must be one of APP or SELINUX.")); |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 261 | } |
| 262 | }; |
| 263 | |
John Wu | 889c1cc | 2022-03-14 16:02:56 -0700 | [diff] [blame] | 264 | let user_id = uid_to_android_user(calling_uid); |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 265 | |
Eric Biggers | 673d34a | 2023-10-18 01:54:18 +0000 | [diff] [blame] | 266 | let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id); |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 267 | |
| 268 | DB.with(|db| { |
John Wu | 889c1cc | 2022-03-14 16:02:56 -0700 | [diff] [blame] | 269 | 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 Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 282 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 283 | .context(ks_err!("Failed to load key blob."))?; |
John Wu | 889c1cc | 2022-03-14 16:02:56 -0700 | [diff] [blame] | 284 | { |
| 285 | db.borrow_mut().migrate_key_namespace(key_id_guard, destination, calling_uid, |k| { |
| 286 | check_key_permission(KeyPerm::Rebind, k, &None) |
| 287 | }) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 288 | } |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 289 | }) |
| 290 | } |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 291 | |
| 292 | fn delete_all_keys() -> Result<()> { |
| 293 | // Security critical permission check. This statement must return on fail. |
Janis Danisevskis | a916d99 | 2021-10-19 15:46:09 -0700 | [diff] [blame] | 294 | check_keystore_permission(KeystorePerm::DeleteAllKeys) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 295 | .context(ks_err!("Checking permission"))?; |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 296 | log::info!("In delete_all_keys."); |
| 297 | |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 298 | Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys(), None) |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 299 | } |
Eran Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 300 | |
| 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 Messeri | cfe79f1 | 2024-02-05 17:50:41 +0000 | [diff] [blame] | 306 | // 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 Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 309 | 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 Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame] | 312 | |
| 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 Drysdale | 709c209 | 2024-06-06 16:17:28 +0100 | [diff] [blame] | 354 | // Display database config information. |
| 355 | writeln!(f, "Database configuration:")?; |
| 356 | DB.with(|db| -> std::io::Result<()> { |
| 357 | let pragma_str = |f: &mut dyn std::io::Write, name| -> std::io::Result<()> { |
| 358 | let mut db = db.borrow_mut(); |
| 359 | let value: String = db |
| 360 | .pragma(name) |
| 361 | .unwrap_or_else(|e| format!("unknown value for '{name}', failed: {e:?}")); |
| 362 | writeln!(f, " {name} = {value}") |
| 363 | }; |
| 364 | let pragma_i32 = |f: &mut dyn std::io::Write, name| -> std::io::Result<()> { |
| 365 | let mut db = db.borrow_mut(); |
| 366 | let value: i32 = db.pragma(name).unwrap_or_else(|e| { |
| 367 | log::error!("unknown value for '{name}', failed: {e:?}"); |
| 368 | -1 |
| 369 | }); |
| 370 | writeln!(f, " {name} = {value}") |
| 371 | }; |
| 372 | pragma_i32(f, "auto_vacuum")?; |
| 373 | pragma_str(f, "journal_mode")?; |
| 374 | pragma_i32(f, "journal_size_limit")?; |
| 375 | pragma_i32(f, "synchronous")?; |
| 376 | pragma_i32(f, "schema_version")?; |
| 377 | pragma_i32(f, "user_version")?; |
| 378 | Ok(()) |
| 379 | })?; |
| 380 | writeln!(f)?; |
| 381 | |
David Drysdale | 49811e2 | 2023-05-22 18:51:30 +0100 | [diff] [blame] | 382 | // Display accumulated metrics. |
| 383 | writeln!(f, "Metrics information:")?; |
| 384 | writeln!(f)?; |
| 385 | write!(f, "{:?}", *crate::metrics_store::METRICS_STORE)?; |
| 386 | writeln!(f)?; |
| 387 | |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame] | 388 | // Reminder: any additional information added to the `dump_state()` output needs to be |
| 389 | // careful not to include confidential information (e.g. key material). |
| 390 | |
| 391 | Ok(()) |
| 392 | } |
Karuna Wadhera | ca70449 | 2024-11-20 06:50:29 +0000 | [diff] [blame] | 393 | |
| 394 | #[allow(dead_code)] |
| 395 | fn set_module_info(module_info: Vec<ModuleInfo>) -> Result<()> { |
| 396 | let encoding = Self::encode_module_info(module_info) |
| 397 | .map_err(|e| anyhow!({ e })) |
| 398 | .context(ks_err!("Failed to encode module_info"))?; |
| 399 | let hash = digest::Sha256::hash(&encoding).to_vec(); |
| 400 | |
| 401 | { |
| 402 | let mut saved = ENCODED_MODULE_INFO.write().unwrap(); |
| 403 | if let Some(saved_encoding) = &*saved { |
| 404 | if *saved_encoding == encoding { |
| 405 | log::warn!( |
| 406 | "Module info already set, ignoring repeated attempt to set same info." |
| 407 | ); |
| 408 | return Ok(()); |
| 409 | } |
| 410 | return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!( |
| 411 | "Failed to set module info as it is already set to a different value." |
| 412 | )); |
| 413 | } |
| 414 | *saved = Some(encoding); |
| 415 | } |
| 416 | |
| 417 | let kps = |
| 418 | vec![KeyParameter { tag: Tag::MODULE_HASH, value: KeyParameterValue::Blob(hash) }]; |
| 419 | |
| 420 | Maintenance::call_on_all_security_levels( |
| 421 | "setAdditionalAttestationInfo", |
| 422 | |dev| dev.setAdditionalAttestationInfo(&kps), |
| 423 | Some(KEYMINT_V4), |
| 424 | ) |
| 425 | } |
| 426 | |
| 427 | #[allow(dead_code)] |
| 428 | fn encode_module_info(module_info: Vec<ModuleInfo>) -> Result<Vec<u8>, der::Error> { |
| 429 | SetOfVec::<ModuleInfo>::from_iter(module_info.into_iter())?.to_der() |
| 430 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 431 | } |
| 432 | |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame] | 433 | impl Interface for Maintenance { |
| 434 | fn dump( |
| 435 | &self, |
| 436 | f: &mut dyn std::io::Write, |
| 437 | _args: &[&std::ffi::CStr], |
| 438 | ) -> Result<(), binder::StatusCode> { |
| 439 | if !keystore2_flags::enable_dump() { |
| 440 | log::info!("skipping dump() as flag not enabled"); |
| 441 | return Ok(()); |
| 442 | } |
| 443 | log::info!("dump()"); |
| 444 | let _wp = wd::watch("IKeystoreMaintenance::dump"); |
| 445 | check_dump_permission().map_err(|_e| { |
| 446 | log::error!("dump permission denied"); |
| 447 | binder::StatusCode::PERMISSION_DENIED |
| 448 | })?; |
| 449 | |
| 450 | self.dump_state(f).map_err(|e| { |
| 451 | log::error!("dump_state failed: {e:?}"); |
| 452 | binder::StatusCode::UNKNOWN_ERROR |
| 453 | }) |
| 454 | } |
| 455 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 456 | |
Janis Danisevskis | 34a0cf2 | 2021-03-08 09:19:03 -0800 | [diff] [blame] | 457 | impl IKeystoreMaintenance for Maintenance { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 458 | fn onUserAdded(&self, user_id: i32) -> BinderResult<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 459 | log::info!("onUserAdded(user={user_id})"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 460 | let _wp = wd::watch("IKeystoreMaintenance::onUserAdded"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 461 | self.add_or_remove_user(user_id).map_err(into_logged_binder) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 462 | } |
| 463 | |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 464 | fn initUserSuperKeys( |
| 465 | &self, |
| 466 | user_id: i32, |
| 467 | password: &[u8], |
| 468 | allow_existing: bool, |
| 469 | ) -> BinderResult<()> { |
| 470 | log::info!("initUserSuperKeys(user={user_id}, allow_existing={allow_existing})"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 471 | let _wp = wd::watch("IKeystoreMaintenance::initUserSuperKeys"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 472 | self.init_user_super_keys(user_id, password.into(), allow_existing) |
| 473 | .map_err(into_logged_binder) |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 474 | } |
| 475 | |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 476 | fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 477 | log::info!("onUserRemoved(user={user_id})"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 478 | let _wp = wd::watch("IKeystoreMaintenance::onUserRemoved"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 479 | self.add_or_remove_user(user_id).map_err(into_logged_binder) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 480 | } |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 481 | |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 482 | fn onUserLskfRemoved(&self, user_id: i32) -> BinderResult<()> { |
| 483 | log::info!("onUserLskfRemoved(user={user_id})"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 484 | let _wp = wd::watch("IKeystoreMaintenance::onUserLskfRemoved"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 485 | Self::on_user_lskf_removed(user_id).map_err(into_logged_binder) |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 486 | } |
| 487 | |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 488 | fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 489 | log::info!("clearNamespace({domain:?}, nspace={nspace})"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 490 | let _wp = wd::watch("IKeystoreMaintenance::clearNamespace"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 491 | self.clear_namespace(domain, nspace).map_err(into_logged_binder) |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 492 | } |
Hasini Gunasinghe | 9ee1841 | 2021-03-11 20:12:44 +0000 | [diff] [blame] | 493 | |
Satya Tangirala | 5b9e5b1 | 2021-03-09 12:54:21 -0800 | [diff] [blame] | 494 | fn earlyBootEnded(&self) -> BinderResult<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 495 | log::info!("earlyBootEnded()"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 496 | let _wp = wd::watch("IKeystoreMaintenance::earlyBootEnded"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 497 | Self::early_boot_ended().map_err(into_logged_binder) |
Satya Tangirala | 5b9e5b1 | 2021-03-09 12:54:21 -0800 | [diff] [blame] | 498 | } |
| 499 | |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 500 | fn migrateKeyNamespace( |
| 501 | &self, |
| 502 | source: &KeyDescriptor, |
| 503 | destination: &KeyDescriptor, |
| 504 | ) -> BinderResult<()> { |
David Drysdale | e85523f | 2023-06-19 12:28:53 +0100 | [diff] [blame] | 505 | log::info!("migrateKeyNamespace(src={source:?}, dest={destination:?})"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 506 | let _wp = wd::watch("IKeystoreMaintenance::migrateKeyNamespace"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 507 | Self::migrate_key_namespace(source, destination).map_err(into_logged_binder) |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 508 | } |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 509 | |
| 510 | fn deleteAllKeys(&self) -> BinderResult<()> { |
David Drysdale | ce2b90b | 2024-07-17 15:56:29 +0100 | [diff] [blame] | 511 | log::warn!("deleteAllKeys() invoked, indicating initial setup or post-factory reset"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 512 | let _wp = wd::watch("IKeystoreMaintenance::deleteAllKeys"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 513 | Self::delete_all_keys().map_err(into_logged_binder) |
Paul Crowley | 46c703e | 2021-08-06 15:13:53 -0700 | [diff] [blame] | 514 | } |
Eran Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 515 | |
| 516 | fn getAppUidsAffectedBySid( |
| 517 | &self, |
| 518 | user_id: i32, |
| 519 | secure_user_id: i64, |
| 520 | ) -> BinderResult<std::vec::Vec<i64>> { |
| 521 | log::info!("getAppUidsAffectedBySid(secure_user_id={secure_user_id:?})"); |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 522 | let _wp = wd::watch("IKeystoreMaintenance::getAppUidsAffectedBySid"); |
David Drysdale | db7ddde | 2024-06-07 16:22:49 +0100 | [diff] [blame] | 523 | Self::get_app_uids_affected_by_sid(user_id, secure_user_id).map_err(into_logged_binder) |
Eran Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 524 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 525 | } |