Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 1 | // Copyright 2020, 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 | |
| 15 | //! This module implements utility functions used by the Keystore 2.0 service |
| 16 | //! implementation. |
| 17 | |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 18 | use crate::error::{map_binder_status, map_km_error, Error, ErrorCode}; |
| 19 | use crate::key_parameter::KeyParameter; |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 20 | use crate::ks_err; |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 21 | use crate::permission; |
| 22 | use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm}; |
Alice Wang | 83c6aef | 2023-11-03 17:17:34 +0000 | [diff] [blame] | 23 | pub use crate::watchdog_helper::watchdog; |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 24 | use crate::{ |
| 25 | database::{KeyType, KeystoreDB}, |
Janis Danisevskis | 0ffb8a8 | 2022-02-06 22:37:21 -0800 | [diff] [blame] | 26 | globals::LEGACY_IMPORTER, |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 27 | km_compat, |
| 28 | raw_device::KeyMintDevice, |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 29 | }; |
Shawn Willden | 708744a | 2020-12-11 13:05:27 +0000 | [diff] [blame] | 30 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
David Drysdale | 746e1be | 2023-07-05 17:39:57 +0100 | [diff] [blame] | 31 | Algorithm::Algorithm, IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics, |
| 32 | KeyParameter::KeyParameter as KmKeyParameter, KeyParameterValue::KeyParameterValue, Tag::Tag, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 33 | }; |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 34 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; |
Janis Danisevskis | 7a1cf38 | 2020-11-20 11:22:14 -0800 | [diff] [blame] | 35 | use android_security_apc::aidl::android::security::apc::{ |
| 36 | IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED}, |
| 37 | ResponseCode::ResponseCode as ApcResponseCode, |
| 38 | }; |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 39 | use android_system_keystore2::aidl::android::system::keystore2::{ |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 40 | Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor, |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame^] | 41 | ResponseCode::ResponseCode, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 42 | }; |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 43 | use anyhow::{Context, Result}; |
Alice Wang | 81dbef7 | 2024-07-31 15:13:14 +0000 | [diff] [blame] | 44 | use binder::{FromIBinder, StatusCode, Strong, ThreadState}; |
Janis Danisevskis | 7a1cf38 | 2020-11-20 11:22:14 -0800 | [diff] [blame] | 45 | use keystore2_apc_compat::{ |
| 46 | ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED, |
| 47 | APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING, |
| 48 | APC_COMPAT_ERROR_SYSTEM_ERROR, |
| 49 | }; |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 50 | use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec}; |
Alice Wang | 81dbef7 | 2024-07-31 15:13:14 +0000 | [diff] [blame] | 51 | use log::{info, warn}; |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 52 | use std::iter::IntoIterator; |
Alice Wang | 81dbef7 | 2024-07-31 15:13:14 +0000 | [diff] [blame] | 53 | use std::thread::sleep; |
| 54 | use std::time::Duration; |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 55 | |
David Drysdale | 2566fb3 | 2024-07-09 14:46:37 +0100 | [diff] [blame] | 56 | #[cfg(test)] |
| 57 | mod tests; |
| 58 | |
David Drysdale | 746e1be | 2023-07-05 17:39:57 +0100 | [diff] [blame] | 59 | /// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime |
| 60 | /// 999912312359559, which is 253402300799000 ms from Jan 1, 1970. |
| 61 | pub const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64; |
| 62 | |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 63 | /// This function uses its namesake in the permission module and in |
| 64 | /// combination with with_calling_sid from the binder crate to check |
| 65 | /// if the caller has the given keystore permission. |
| 66 | pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> { |
| 67 | ThreadState::with_calling_sid(|calling_sid| { |
| 68 | permission::check_keystore_permission( |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 69 | calling_sid |
| 70 | .ok_or_else(Error::sys) |
| 71 | .context(ks_err!("Cannot check permission without calling_sid."))?, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 72 | perm, |
| 73 | ) |
| 74 | }) |
| 75 | } |
| 76 | |
| 77 | /// This function uses its namesake in the permission module and in |
| 78 | /// combination with with_calling_sid from the binder crate to check |
| 79 | /// if the caller has the given grant permission. |
| 80 | pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> { |
| 81 | ThreadState::with_calling_sid(|calling_sid| { |
| 82 | permission::check_grant_permission( |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 83 | calling_sid |
| 84 | .ok_or_else(Error::sys) |
| 85 | .context(ks_err!("Cannot check permission without calling_sid."))?, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 86 | access_vec, |
| 87 | key, |
| 88 | ) |
| 89 | }) |
| 90 | } |
| 91 | |
| 92 | /// This function uses its namesake in the permission module and in |
| 93 | /// combination with with_calling_sid from the binder crate to check |
| 94 | /// if the caller has the given key permission. |
| 95 | pub fn check_key_permission( |
| 96 | perm: KeyPerm, |
| 97 | key: &KeyDescriptor, |
| 98 | access_vector: &Option<KeyPermSet>, |
| 99 | ) -> anyhow::Result<()> { |
| 100 | ThreadState::with_calling_sid(|calling_sid| { |
| 101 | permission::check_key_permission( |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 102 | ThreadState::get_calling_uid(), |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 103 | calling_sid |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 104 | .ok_or_else(Error::sys) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 105 | .context(ks_err!("Cannot check permission without calling_sid."))?, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 106 | perm, |
| 107 | key, |
| 108 | access_vector, |
| 109 | ) |
| 110 | }) |
| 111 | } |
| 112 | |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 113 | /// This function checks whether a given tag corresponds to the access of device identifiers. |
| 114 | pub fn is_device_id_attestation_tag(tag: Tag) -> bool { |
Janis Danisevskis | 83116e5 | 2021-04-06 13:36:58 -0700 | [diff] [blame] | 115 | matches!( |
| 116 | tag, |
| 117 | Tag::ATTESTATION_ID_IMEI |
| 118 | | Tag::ATTESTATION_ID_MEID |
| 119 | | Tag::ATTESTATION_ID_SERIAL |
| 120 | | Tag::DEVICE_UNIQUE_ATTESTATION |
Eran Messeri | 637259c | 2022-10-31 12:23:36 +0000 | [diff] [blame] | 121 | | Tag::ATTESTATION_ID_SECOND_IMEI |
Janis Danisevskis | 83116e5 | 2021-04-06 13:36:58 -0700 | [diff] [blame] | 122 | ) |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 123 | } |
| 124 | |
| 125 | /// This function checks whether the calling app has the Android permissions needed to attest device |
Seth Moore | 66d9e90 | 2022-03-16 17:20:31 -0700 | [diff] [blame] | 126 | /// identifiers. It throws an error if the permissions cannot be verified or if the caller doesn't |
| 127 | /// have the right permissions. Otherwise it returns silently. |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 128 | pub fn check_device_attestation_permissions() -> anyhow::Result<()> { |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame^] | 129 | check_android_permission( |
| 130 | "android.permission.READ_PRIVILEGED_PHONE_STATE", |
| 131 | Error::Km(ErrorCode::CANNOT_ATTEST_IDS), |
| 132 | ) |
Seth Moore | 66d9e90 | 2022-03-16 17:20:31 -0700 | [diff] [blame] | 133 | } |
| 134 | |
| 135 | /// This function checks whether the calling app has the Android permissions needed to attest the |
| 136 | /// device-unique identifier. It throws an error if the permissions cannot be verified or if the |
| 137 | /// caller doesn't have the right permissions. Otherwise it returns silently. |
| 138 | pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> { |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame^] | 139 | check_android_permission( |
| 140 | "android.permission.REQUEST_UNIQUE_ID_ATTESTATION", |
| 141 | Error::Km(ErrorCode::CANNOT_ATTEST_IDS), |
| 142 | ) |
Seth Moore | 66d9e90 | 2022-03-16 17:20:31 -0700 | [diff] [blame] | 143 | } |
| 144 | |
Eran Messeri | cfe79f1 | 2024-02-05 17:50:41 +0000 | [diff] [blame] | 145 | /// This function checks whether the calling app has the Android permissions needed to manage |
| 146 | /// users. Only callers that can manage users are allowed to get a list of apps affected |
| 147 | /// by a user's SID changing. |
| 148 | /// It throws an error if the permissions cannot be verified or if the caller doesn't |
| 149 | /// have the right permissions. Otherwise it returns silently. |
| 150 | pub fn check_get_app_uids_affected_by_sid_permissions() -> anyhow::Result<()> { |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame^] | 151 | check_android_permission( |
| 152 | "android.permission.MANAGE_USERS", |
| 153 | Error::Km(ErrorCode::CANNOT_ATTEST_IDS), |
| 154 | ) |
Eran Messeri | cfe79f1 | 2024-02-05 17:50:41 +0000 | [diff] [blame] | 155 | } |
| 156 | |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame^] | 157 | /// This function checks whether the calling app has the Android permission needed to dump |
| 158 | /// Keystore state to logcat. |
| 159 | pub fn check_dump_permission() -> anyhow::Result<()> { |
| 160 | check_android_permission("android.permission.DUMP", Error::Rc(ResponseCode::PERMISSION_DENIED)) |
| 161 | } |
| 162 | |
| 163 | fn check_android_permission(permission: &str, err: Error) -> anyhow::Result<()> { |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 164 | let permission_controller: Strong<dyn IPermissionController::IPermissionController> = |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 165 | binder::get_interface("permission")?; |
| 166 | |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 167 | let binder_result = { |
David Drysdale | c652f6c | 2024-07-18 13:01:23 +0100 | [diff] [blame] | 168 | let _wp = watchdog::watch("check_android_permission: calling checkPermission"); |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 169 | permission_controller.checkPermission( |
Seth Moore | 66d9e90 | 2022-03-16 17:20:31 -0700 | [diff] [blame] | 170 | permission, |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 171 | ThreadState::get_calling_pid(), |
| 172 | ThreadState::get_calling_uid() as i32, |
| 173 | ) |
| 174 | }; |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 175 | let has_permissions = |
| 176 | map_binder_status(binder_result).context(ks_err!("checkPermission failed"))?; |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 177 | match has_permissions { |
| 178 | true => Ok(()), |
David Drysdale | 0fefae3 | 2024-09-16 13:32:27 +0100 | [diff] [blame^] | 179 | false => Err(err).context(ks_err!("caller does not have the '{permission}' permission")), |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 180 | } |
| 181 | } |
| 182 | |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 183 | /// Converts a set of key characteristics as returned from KeyMint into the internal |
| 184 | /// representation of the keystore service. |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 185 | pub fn key_characteristics_to_internal( |
Shawn Willden | dbdac60 | 2021-01-12 22:35:16 -0700 | [diff] [blame] | 186 | key_characteristics: Vec<KeyCharacteristics>, |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 187 | ) -> Vec<KeyParameter> { |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 188 | key_characteristics |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 189 | .into_iter() |
Shawn Willden | dbdac60 | 2021-01-12 22:35:16 -0700 | [diff] [blame] | 190 | .flat_map(|aidl_key_char| { |
| 191 | let sec_level = aidl_key_char.securityLevel; |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 192 | aidl_key_char |
| 193 | .authorizations |
| 194 | .into_iter() |
| 195 | .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level)) |
Shawn Willden | dbdac60 | 2021-01-12 22:35:16 -0700 | [diff] [blame] | 196 | }) |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 197 | .collect() |
| 198 | } |
| 199 | |
David Drysdale | 746e1be | 2023-07-05 17:39:57 +0100 | [diff] [blame] | 200 | /// Import a keyblob that is of the format used by the software C++ KeyMint implementation. After |
| 201 | /// successful import, invoke both the `new_blob_handler` and `km_op` closures. On success a tuple |
| 202 | /// of the `km_op`s result and the optional upgraded blob is returned. |
| 203 | fn import_keyblob_and_perform_op<T, KmOp, NewBlobHandler>( |
| 204 | km_dev: &dyn IKeyMintDevice, |
| 205 | inner_keyblob: &[u8], |
| 206 | upgrade_params: &[KmKeyParameter], |
| 207 | km_op: KmOp, |
| 208 | new_blob_handler: NewBlobHandler, |
| 209 | ) -> Result<(T, Option<Vec<u8>>)> |
| 210 | where |
| 211 | KmOp: Fn(&[u8]) -> Result<T, Error>, |
| 212 | NewBlobHandler: FnOnce(&[u8]) -> Result<()>, |
| 213 | { |
| 214 | let (format, key_material, mut chars) = |
| 215 | crate::sw_keyblob::export_key(inner_keyblob, upgrade_params)?; |
| 216 | log::debug!( |
| 217 | "importing {:?} key material (len={}) with original chars={:?}", |
| 218 | format, |
| 219 | key_material.len(), |
| 220 | chars |
| 221 | ); |
| 222 | let asymmetric = chars.iter().any(|kp| { |
| 223 | kp.tag == Tag::ALGORITHM |
| 224 | && (kp.value == KeyParameterValue::Algorithm(Algorithm::RSA) |
| 225 | || (kp.value == KeyParameterValue::Algorithm(Algorithm::EC))) |
| 226 | }); |
| 227 | |
| 228 | // Combine the characteristics of the previous keyblob with the upgrade parameters (which might |
| 229 | // include special things like APPLICATION_ID / APPLICATION_DATA). |
| 230 | chars.extend_from_slice(upgrade_params); |
| 231 | |
| 232 | // Now filter out values from the existing keyblob that shouldn't be set on import, either |
| 233 | // because they are per-operation parameter or because they are auto-added by KeyMint itself. |
| 234 | let mut import_params: Vec<KmKeyParameter> = chars |
| 235 | .into_iter() |
| 236 | .filter(|kp| { |
| 237 | !matches!( |
| 238 | kp.tag, |
| 239 | Tag::ORIGIN |
| 240 | | Tag::ROOT_OF_TRUST |
| 241 | | Tag::OS_VERSION |
| 242 | | Tag::OS_PATCHLEVEL |
| 243 | | Tag::UNIQUE_ID |
| 244 | | Tag::ATTESTATION_CHALLENGE |
| 245 | | Tag::ATTESTATION_APPLICATION_ID |
| 246 | | Tag::ATTESTATION_ID_BRAND |
| 247 | | Tag::ATTESTATION_ID_DEVICE |
| 248 | | Tag::ATTESTATION_ID_PRODUCT |
| 249 | | Tag::ATTESTATION_ID_SERIAL |
| 250 | | Tag::ATTESTATION_ID_IMEI |
| 251 | | Tag::ATTESTATION_ID_MEID |
| 252 | | Tag::ATTESTATION_ID_MANUFACTURER |
| 253 | | Tag::ATTESTATION_ID_MODEL |
| 254 | | Tag::VENDOR_PATCHLEVEL |
| 255 | | Tag::BOOT_PATCHLEVEL |
| 256 | | Tag::DEVICE_UNIQUE_ATTESTATION |
| 257 | | Tag::ATTESTATION_ID_SECOND_IMEI |
| 258 | | Tag::NONCE |
| 259 | | Tag::MAC_LENGTH |
| 260 | | Tag::CERTIFICATE_SERIAL |
| 261 | | Tag::CERTIFICATE_SUBJECT |
| 262 | | Tag::CERTIFICATE_NOT_BEFORE |
| 263 | | Tag::CERTIFICATE_NOT_AFTER |
| 264 | ) |
| 265 | }) |
| 266 | .collect(); |
| 267 | |
| 268 | // Now that any previous values have been removed, add any additional parameters that needed for |
| 269 | // import. In particular, if we are generating/importing an asymmetric key, we need to make sure |
| 270 | // that NOT_BEFORE and NOT_AFTER are present. |
| 271 | if asymmetric { |
| 272 | import_params.push(KmKeyParameter { |
| 273 | tag: Tag::CERTIFICATE_NOT_BEFORE, |
| 274 | value: KeyParameterValue::DateTime(0), |
| 275 | }); |
| 276 | import_params.push(KmKeyParameter { |
| 277 | tag: Tag::CERTIFICATE_NOT_AFTER, |
| 278 | value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER), |
| 279 | }); |
| 280 | } |
| 281 | log::debug!("import parameters={import_params:?}"); |
| 282 | |
| 283 | let creation_result = { |
David Drysdale | c652f6c | 2024-07-18 13:01:23 +0100 | [diff] [blame] | 284 | let _wp = watchdog::watch( |
| 285 | "utils::import_keyblob_and_perform_op: calling IKeyMintDevice::importKey", |
| 286 | ); |
David Drysdale | 746e1be | 2023-07-05 17:39:57 +0100 | [diff] [blame] | 287 | map_km_error(km_dev.importKey(&import_params, format, &key_material, None)) |
| 288 | } |
| 289 | .context(ks_err!("Upgrade failed."))?; |
| 290 | |
| 291 | // Note that the importKey operation will produce key characteristics that may be different |
| 292 | // than are already stored in Keystore's SQL database. In particular, the KeyMint |
| 293 | // implementation will now mark the key as `Origin::IMPORTED` not `Origin::GENERATED`, and |
| 294 | // the security level for characteristics will now be `TRUSTED_ENVIRONMENT` not `SOFTWARE`. |
| 295 | // |
| 296 | // However, the DB metadata still accurately reflects the original origin of the key, and |
| 297 | // so we leave the values as-is (and so any `KeyInfo` retrieved in the Java layer will get the |
| 298 | // same results before and after import). |
| 299 | // |
| 300 | // Note that this also applies to the `USAGE_COUNT_LIMIT` parameter -- if the key has already |
| 301 | // been used, then the DB version of the parameter will be (and will continue to be) lower |
| 302 | // than the original count bound to the keyblob. This means that Keystore's policing of |
| 303 | // usage counts will continue where it left off. |
| 304 | |
| 305 | new_blob_handler(&creation_result.keyBlob).context(ks_err!("calling new_blob_handler."))?; |
| 306 | |
| 307 | km_op(&creation_result.keyBlob) |
| 308 | .map(|v| (v, Some(creation_result.keyBlob))) |
| 309 | .context(ks_err!("Calling km_op after upgrade.")) |
| 310 | } |
| 311 | |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 312 | /// Upgrade a keyblob then invoke both the `new_blob_handler` and the `km_op` closures. On success |
| 313 | /// a tuple of the `km_op`s result and the optional upgraded blob is returned. |
| 314 | fn upgrade_keyblob_and_perform_op<T, KmOp, NewBlobHandler>( |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 315 | km_dev: &dyn IKeyMintDevice, |
| 316 | key_blob: &[u8], |
| 317 | upgrade_params: &[KmKeyParameter], |
| 318 | km_op: KmOp, |
| 319 | new_blob_handler: NewBlobHandler, |
| 320 | ) -> Result<(T, Option<Vec<u8>>)> |
| 321 | where |
| 322 | KmOp: Fn(&[u8]) -> Result<T, Error>, |
| 323 | NewBlobHandler: FnOnce(&[u8]) -> Result<()>, |
| 324 | { |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 325 | let upgraded_blob = { |
David Drysdale | c652f6c | 2024-07-18 13:01:23 +0100 | [diff] [blame] | 326 | let _wp = watchdog::watch( |
| 327 | "utils::upgrade_keyblob_and_perform_op: calling IKeyMintDevice::upgradeKey.", |
| 328 | ); |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 329 | map_km_error(km_dev.upgradeKey(key_blob, upgrade_params)) |
| 330 | } |
| 331 | .context(ks_err!("Upgrade failed."))?; |
| 332 | |
| 333 | new_blob_handler(&upgraded_blob).context(ks_err!("calling new_blob_handler."))?; |
| 334 | |
| 335 | km_op(&upgraded_blob) |
| 336 | .map(|v| (v, Some(upgraded_blob))) |
| 337 | .context(ks_err!("Calling km_op after upgrade.")) |
| 338 | } |
| 339 | |
| 340 | /// This function can be used to upgrade key blobs on demand. The return value of |
| 341 | /// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered, |
| 342 | /// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called |
| 343 | /// with the upgraded blob as argument. Then `km_op` is called a second time with the |
| 344 | /// upgraded blob as argument. On success a tuple of the `km_op`s result and the |
| 345 | /// optional upgraded blob is returned. |
| 346 | pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>( |
| 347 | km_dev: &dyn IKeyMintDevice, |
| 348 | km_dev_version: i32, |
| 349 | key_blob: &[u8], |
| 350 | upgrade_params: &[KmKeyParameter], |
| 351 | km_op: KmOp, |
| 352 | new_blob_handler: NewBlobHandler, |
| 353 | ) -> Result<(T, Option<Vec<u8>>)> |
| 354 | where |
| 355 | KmOp: Fn(&[u8]) -> Result<T, Error>, |
| 356 | NewBlobHandler: FnOnce(&[u8]) -> Result<()>, |
| 357 | { |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 358 | match km_op(key_blob) { |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 359 | Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => upgrade_keyblob_and_perform_op( |
| 360 | km_dev, |
| 361 | key_blob, |
| 362 | upgrade_params, |
| 363 | km_op, |
| 364 | new_blob_handler, |
| 365 | ), |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 366 | Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) |
David Drysdale | 746e1be | 2023-07-05 17:39:57 +0100 | [diff] [blame] | 367 | if km_dev_version >= KeyMintDevice::KEY_MINT_V1 => |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 368 | { |
David Drysdale | 746e1be | 2023-07-05 17:39:57 +0100 | [diff] [blame] | 369 | // A KeyMint (not Keymaster via km_compat) device says that this is an invalid keyblob. |
| 370 | // |
| 371 | // This may be because the keyblob was created before an Android upgrade, and as part of |
| 372 | // the device upgrade the underlying Keymaster/KeyMint implementation has been upgraded. |
| 373 | // |
| 374 | // If that's the case, there are three possible scenarios: |
| 375 | if key_blob.starts_with(km_compat::KEYMASTER_BLOB_HW_PREFIX) { |
| 376 | // 1) The keyblob was created in hardware by the km_compat C++ code, using a prior |
| 377 | // Keymaster implementation, and wrapped. |
| 378 | // |
| 379 | // In this case, the keyblob will have the km_compat magic prefix, including the |
| 380 | // marker that indicates that this was a hardware-backed key. |
| 381 | // |
| 382 | // The inner keyblob should still be recognized by the hardware implementation, so |
| 383 | // strip the prefix and attempt a key upgrade. |
| 384 | log::info!( |
| 385 | "found apparent km_compat(Keymaster) HW blob, attempt strip-and-upgrade" |
| 386 | ); |
| 387 | let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_HW_PREFIX.len()..]; |
| 388 | upgrade_keyblob_and_perform_op( |
| 389 | km_dev, |
| 390 | inner_keyblob, |
| 391 | upgrade_params, |
| 392 | km_op, |
| 393 | new_blob_handler, |
| 394 | ) |
David Drysdale | 093811e | 2023-11-09 08:32:02 +0000 | [diff] [blame] | 395 | } else if keystore2_flags::import_previously_emulated_keys() |
| 396 | && key_blob.starts_with(km_compat::KEYMASTER_BLOB_SW_PREFIX) |
| 397 | { |
David Drysdale | 746e1be | 2023-07-05 17:39:57 +0100 | [diff] [blame] | 398 | // 2) The keyblob was created in software by the km_compat C++ code because a prior |
| 399 | // Keymaster implementation did not support ECDH (which was only added in KeyMint). |
| 400 | // |
| 401 | // In this case, the keyblob with have the km_compat magic prefix, but with the |
| 402 | // marker that indicates that this was a software-emulated key. |
| 403 | // |
| 404 | // The inner keyblob should be in the format produced by the C++ reference |
| 405 | // implementation of KeyMint. Extract the key material and import it into the |
| 406 | // current KeyMint device. |
| 407 | log::info!("found apparent km_compat(Keymaster) SW blob, attempt strip-and-import"); |
| 408 | let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_SW_PREFIX.len()..]; |
| 409 | import_keyblob_and_perform_op( |
| 410 | km_dev, |
| 411 | inner_keyblob, |
| 412 | upgrade_params, |
| 413 | km_op, |
| 414 | new_blob_handler, |
| 415 | ) |
David Drysdale | 093811e | 2023-11-09 08:32:02 +0000 | [diff] [blame] | 416 | } else if let (true, km_compat::KeyBlob::Wrapped(inner_keyblob)) = ( |
| 417 | keystore2_flags::import_previously_emulated_keys(), |
| 418 | km_compat::unwrap_keyblob(key_blob), |
| 419 | ) { |
David Drysdale | 746e1be | 2023-07-05 17:39:57 +0100 | [diff] [blame] | 420 | // 3) The keyblob was created in software by km_compat.rs because a prior KeyMint |
| 421 | // implementation did not support a feature present in the current KeyMint spec. |
| 422 | // (For example, a curve 25519 key created when the device only supported KeyMint |
| 423 | // v1). |
| 424 | // |
| 425 | // In this case, the keyblob with have the km_compat.rs wrapper around it to |
| 426 | // indicate that this was a software-emulated key. |
| 427 | // |
| 428 | // The inner keyblob should be in the format produced by the C++ reference |
| 429 | // implementation of KeyMint. Extract the key material and import it into the |
| 430 | // current KeyMint device. |
| 431 | log::info!( |
| 432 | "found apparent km_compat.rs(KeyMint) SW blob, attempt strip-and-import" |
| 433 | ); |
| 434 | import_keyblob_and_perform_op( |
| 435 | km_dev, |
| 436 | inner_keyblob, |
| 437 | upgrade_params, |
| 438 | km_op, |
| 439 | new_blob_handler, |
| 440 | ) |
| 441 | } else { |
| 442 | Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)).context(ks_err!("Calling km_op")) |
| 443 | } |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 444 | } |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 445 | r => r.map(|v| (v, None)).context(ks_err!("Calling km_op.")), |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 446 | } |
| 447 | } |
| 448 | |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 449 | /// Converts a set of key characteristics from the internal representation into a set of |
| 450 | /// Authorizations as they are used to convey key characteristics to the clients of keystore. |
| 451 | pub fn key_parameters_to_authorizations( |
| 452 | parameters: Vec<crate::key_parameter::KeyParameter>, |
| 453 | ) -> Vec<Authorization> { |
| 454 | parameters.into_iter().map(|p| p.into_authorization()).collect() |
| 455 | } |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 456 | |
Charisee | 03e0084 | 2023-01-25 01:41:23 +0000 | [diff] [blame] | 457 | #[allow(clippy::unnecessary_cast)] |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 458 | /// This returns the current time (in milliseconds) as an instance of a monotonic clock, |
| 459 | /// by invoking the system call since Rust does not support getting monotonic time instance |
| 460 | /// as an integer. |
| 461 | pub fn get_current_time_in_milliseconds() -> i64 { |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 462 | let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 }; |
Andrew Walbran | a47698a | 2023-07-21 17:23:56 +0100 | [diff] [blame] | 463 | // SAFETY: The pointer is valid because it comes from a reference, and clock_gettime doesn't |
| 464 | // retain it beyond the call. |
James Willcox | 80f7be1 | 2023-11-08 17:13:16 +0000 | [diff] [blame] | 465 | unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut current_time) }; |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 466 | current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000) |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 467 | } |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 468 | |
Janis Danisevskis | 7a1cf38 | 2020-11-20 11:22:14 -0800 | [diff] [blame] | 469 | /// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility |
| 470 | /// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL |
| 471 | /// (android.security.apc) spec. |
| 472 | pub fn compat_2_response_code(rc: u32) -> ApcResponseCode { |
| 473 | match rc { |
| 474 | APC_COMPAT_ERROR_OK => ApcResponseCode::OK, |
| 475 | APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED, |
| 476 | APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED, |
| 477 | APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING, |
| 478 | APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED, |
| 479 | APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR, |
| 480 | _ => ApcResponseCode::SYSTEM_ERROR, |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | /// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into |
| 485 | /// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility |
| 486 | /// module (keystore2_apc_compat). |
| 487 | pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions { |
| 488 | ApcCompatUiOptions { |
| 489 | inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0, |
| 490 | magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0, |
| 491 | } |
| 492 | } |
| 493 | |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 494 | /// AID offset for uid space partitioning. |
Joel Galenson | 81a50f2 | 2021-07-29 15:39:10 -0700 | [diff] [blame] | 495 | pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET; |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 496 | |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 497 | /// AID of the keystore process itself, used for keys that |
| 498 | /// keystore generates for its own use. |
Joel Galenson | 81a50f2 | 2021-07-29 15:39:10 -0700 | [diff] [blame] | 499 | pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE; |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 500 | |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 501 | /// Extracts the android user from the given uid. |
| 502 | pub fn uid_to_android_user(uid: u32) -> u32 { |
Joel Galenson | 81a50f2 | 2021-07-29 15:39:10 -0700 | [diff] [blame] | 503 | rustutils::users::multiuser_get_user_id(uid) |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 504 | } |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 505 | |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 506 | /// Merges and filters two lists of key descriptors. The first input list, legacy_descriptors, |
| 507 | /// is assumed to not be sorted or filtered. As such, all key descriptors in that list whose |
| 508 | /// alias is less than, or equal to, start_past_alias (if provided) will be removed. |
| 509 | /// This list will then be merged with the second list, db_descriptors. The db_descriptors list |
| 510 | /// is assumed to be sorted and filtered so the output list will be sorted prior to returning. |
| 511 | /// The returned value is a list of KeyDescriptor objects whose alias is greater than |
| 512 | /// start_past_alias, sorted and de-duplicated. |
| 513 | fn merge_and_filter_key_entry_lists( |
| 514 | legacy_descriptors: &[KeyDescriptor], |
| 515 | db_descriptors: &[KeyDescriptor], |
| 516 | start_past_alias: Option<&str>, |
| 517 | ) -> Vec<KeyDescriptor> { |
| 518 | let mut result: Vec<KeyDescriptor> = |
| 519 | match start_past_alias { |
| 520 | Some(past_alias) => legacy_descriptors |
| 521 | .iter() |
| 522 | .filter(|kd| { |
| 523 | if let Some(alias) = &kd.alias { |
| 524 | alias.as_str() > past_alias |
| 525 | } else { |
| 526 | false |
| 527 | } |
| 528 | }) |
| 529 | .cloned() |
| 530 | .collect(), |
| 531 | None => legacy_descriptors.to_vec(), |
| 532 | }; |
| 533 | |
| 534 | result.extend_from_slice(db_descriptors); |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 535 | result.sort_unstable(); |
| 536 | result.dedup(); |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 537 | result |
| 538 | } |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 539 | |
David Drysdale | da89743 | 2024-06-24 15:57:35 +0100 | [diff] [blame] | 540 | pub(crate) fn estimate_safe_amount_to_return( |
David Drysdale | 4e5b4c7 | 2024-06-28 13:41:27 +0100 | [diff] [blame] | 541 | domain: Domain, |
| 542 | namespace: i64, |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 543 | key_descriptors: &[KeyDescriptor], |
| 544 | response_size_limit: usize, |
| 545 | ) -> usize { |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 546 | let mut items_to_return = 0; |
| 547 | let mut returned_bytes: usize = 0; |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 548 | // Estimate the transaction size to avoid returning more items than what |
| 549 | // could fit in a binder transaction. |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 550 | for kd in key_descriptors.iter() { |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 551 | // 4 bytes for the Domain enum |
| 552 | // 8 bytes for the Namespace long. |
| 553 | returned_bytes += 4 + 8; |
| 554 | // Size of the alias string. Includes 4 bytes for length encoding. |
| 555 | if let Some(alias) = &kd.alias { |
| 556 | returned_bytes += 4 + alias.len(); |
| 557 | } |
| 558 | // Size of the blob. Includes 4 bytes for length encoding. |
| 559 | if let Some(blob) = &kd.blob { |
| 560 | returned_bytes += 4 + blob.len(); |
| 561 | } |
| 562 | // The binder transaction size limit is 1M. Empirical measurements show |
| 563 | // that the binder overhead is 60% (to be confirmed). So break after |
| 564 | // 350KB and return a partial list. |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 565 | if returned_bytes > response_size_limit { |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 566 | log::warn!( |
David Drysdale | 4e5b4c7 | 2024-06-28 13:41:27 +0100 | [diff] [blame] | 567 | "{domain:?}:{namespace}: Key descriptors list ({} items) may exceed binder \ |
| 568 | size, returning {items_to_return} items est {returned_bytes} bytes.", |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 569 | key_descriptors.len(), |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 570 | ); |
| 571 | break; |
| 572 | } |
| 573 | items_to_return += 1; |
| 574 | } |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 575 | items_to_return |
| 576 | } |
| 577 | |
David Drysdale | da89743 | 2024-06-24 15:57:35 +0100 | [diff] [blame] | 578 | /// Estimate for maximum size of a Binder response in bytes. |
| 579 | pub(crate) const RESPONSE_SIZE_LIMIT: usize = 358400; |
| 580 | |
Shaquille Johnson | a820ef5 | 2024-06-20 13:48:23 +0000 | [diff] [blame] | 581 | /// List all key aliases for a given domain + namespace. whose alias is greater |
| 582 | /// than start_past_alias (if provided). |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 583 | pub fn list_key_entries( |
| 584 | db: &mut KeystoreDB, |
| 585 | domain: Domain, |
| 586 | namespace: i64, |
| 587 | start_past_alias: Option<&str>, |
| 588 | ) -> Result<Vec<KeyDescriptor>> { |
| 589 | let legacy_key_descriptors: Vec<KeyDescriptor> = LEGACY_IMPORTER |
| 590 | .list_uid(domain, namespace) |
| 591 | .context(ks_err!("Trying to list legacy keys."))?; |
| 592 | |
| 593 | // The results from the database will be sorted and unique |
| 594 | let db_key_descriptors: Vec<KeyDescriptor> = db |
| 595 | .list_past_alias(domain, namespace, KeyType::Client, start_past_alias) |
| 596 | .context(ks_err!("Trying to list keystore database past alias."))?; |
| 597 | |
| 598 | let merged_key_entries = merge_and_filter_key_entry_lists( |
| 599 | &legacy_key_descriptors, |
| 600 | &db_key_descriptors, |
| 601 | start_past_alias, |
| 602 | ); |
| 603 | |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 604 | let safe_amount_to_return = |
David Drysdale | 4e5b4c7 | 2024-06-28 13:41:27 +0100 | [diff] [blame] | 605 | estimate_safe_amount_to_return(domain, namespace, &merged_key_entries, RESPONSE_SIZE_LIMIT); |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 606 | Ok(merged_key_entries[..safe_amount_to_return].to_vec()) |
| 607 | } |
| 608 | |
| 609 | /// Count all key aliases for a given domain + namespace. |
| 610 | pub fn count_key_entries(db: &mut KeystoreDB, domain: Domain, namespace: i64) -> Result<i32> { |
| 611 | let legacy_keys = LEGACY_IMPORTER |
| 612 | .list_uid(domain, namespace) |
| 613 | .context(ks_err!("Trying to list legacy keys."))?; |
| 614 | |
| 615 | let num_keys_in_db = db.count_keys(domain, namespace, KeyType::Client)?; |
| 616 | |
| 617 | Ok((legacy_keys.len() + num_keys_in_db) as i32) |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 618 | } |
| 619 | |
Shaquille Johnson | 668d292 | 2024-07-02 18:03:47 +0000 | [diff] [blame] | 620 | /// For params remove sensitive data before returning a string for logging |
| 621 | pub fn log_security_safe_params(params: &[KmKeyParameter]) -> Vec<KmKeyParameter> { |
| 622 | params |
| 623 | .iter() |
| 624 | .filter(|kp| (kp.tag != Tag::APPLICATION_ID && kp.tag != Tag::APPLICATION_DATA)) |
| 625 | .cloned() |
| 626 | .collect::<Vec<KmKeyParameter>>() |
| 627 | } |
| 628 | |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 629 | /// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM. |
| 630 | pub trait AesGcm { |
| 631 | /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag` |
| 632 | /// and AES-GCM. The implementation provides the key material and selects |
| 633 | /// the implementation variant, e.g., AES128 or AES265. |
| 634 | fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>; |
| 635 | |
| 636 | /// Encrypts `data` and returns the ciphertext, the initialization vector `iv` |
| 637 | /// and AEAD tag `tag`. The implementation provides the key material and selects |
| 638 | /// the implementation variant, e.g., AES128 or AES265. |
| 639 | fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>; |
| 640 | } |
| 641 | |
| 642 | /// Marks an object as AES-GCM key. |
| 643 | pub trait AesGcmKey { |
| 644 | /// Provides access to the raw key material. |
| 645 | fn key(&self) -> &[u8]; |
| 646 | } |
| 647 | |
| 648 | impl<T: AesGcmKey> AesGcm for T { |
| 649 | fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 650 | aes_gcm_decrypt(data, iv, tag, self.key()).context(ks_err!("Decryption failed")) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 651 | } |
| 652 | |
| 653 | fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 654 | aes_gcm_encrypt(plaintext, self.key()).context(ks_err!("Encryption failed.")) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 655 | } |
| 656 | } |
Alice Wang | 81dbef7 | 2024-07-31 15:13:14 +0000 | [diff] [blame] | 657 | |
| 658 | pub(crate) fn retry_get_interface<T: FromIBinder + ?Sized>( |
| 659 | name: &str, |
| 660 | ) -> Result<Strong<T>, StatusCode> { |
| 661 | let retry_count = if cfg!(early_vm) { 5 } else { 1 }; |
| 662 | |
| 663 | let mut wait_time = Duration::from_secs(5); |
| 664 | for i in 1..retry_count { |
| 665 | match binder::get_interface(name) { |
| 666 | Ok(res) => return Ok(res), |
| 667 | Err(e) => { |
| 668 | warn!("failed to get interface {name}. Retry {i}/{retry_count}: {e:?}"); |
| 669 | sleep(wait_time); |
| 670 | wait_time *= 2; |
| 671 | } |
| 672 | } |
| 673 | } |
| 674 | if retry_count > 1 { |
| 675 | info!("{retry_count}-th (last) retry to get interface: {name}"); |
| 676 | } |
| 677 | binder::get_interface(name) |
| 678 | } |