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::{ |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 31 | IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics, |
| 32 | KeyParameter::KeyParameter as KmKeyParameter, 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, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 41 | }; |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 42 | use anyhow::{Context, Result}; |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 43 | use binder::{Strong, ThreadState}; |
Janis Danisevskis | 7a1cf38 | 2020-11-20 11:22:14 -0800 | [diff] [blame] | 44 | use keystore2_apc_compat::{ |
| 45 | ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED, |
| 46 | APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING, |
| 47 | APC_COMPAT_ERROR_SYSTEM_ERROR, |
| 48 | }; |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 49 | use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec}; |
| 50 | use std::iter::IntoIterator; |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 51 | |
| 52 | /// This function uses its namesake in the permission module and in |
| 53 | /// combination with with_calling_sid from the binder crate to check |
| 54 | /// if the caller has the given keystore permission. |
| 55 | pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> { |
| 56 | ThreadState::with_calling_sid(|calling_sid| { |
| 57 | permission::check_keystore_permission( |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 58 | calling_sid |
| 59 | .ok_or_else(Error::sys) |
| 60 | .context(ks_err!("Cannot check permission without calling_sid."))?, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 61 | perm, |
| 62 | ) |
| 63 | }) |
| 64 | } |
| 65 | |
| 66 | /// This function uses its namesake in the permission module and in |
| 67 | /// combination with with_calling_sid from the binder crate to check |
| 68 | /// if the caller has the given grant permission. |
| 69 | pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> { |
| 70 | ThreadState::with_calling_sid(|calling_sid| { |
| 71 | permission::check_grant_permission( |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 72 | calling_sid |
| 73 | .ok_or_else(Error::sys) |
| 74 | .context(ks_err!("Cannot check permission without calling_sid."))?, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 75 | access_vec, |
| 76 | key, |
| 77 | ) |
| 78 | }) |
| 79 | } |
| 80 | |
| 81 | /// This function uses its namesake in the permission module and in |
| 82 | /// combination with with_calling_sid from the binder crate to check |
| 83 | /// if the caller has the given key permission. |
| 84 | pub fn check_key_permission( |
| 85 | perm: KeyPerm, |
| 86 | key: &KeyDescriptor, |
| 87 | access_vector: &Option<KeyPermSet>, |
| 88 | ) -> anyhow::Result<()> { |
| 89 | ThreadState::with_calling_sid(|calling_sid| { |
| 90 | permission::check_key_permission( |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 91 | ThreadState::get_calling_uid(), |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 92 | calling_sid |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 93 | .ok_or_else(Error::sys) |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 94 | .context(ks_err!("Cannot check permission without calling_sid."))?, |
Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 95 | perm, |
| 96 | key, |
| 97 | access_vector, |
| 98 | ) |
| 99 | }) |
| 100 | } |
| 101 | |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 102 | /// This function checks whether a given tag corresponds to the access of device identifiers. |
| 103 | pub fn is_device_id_attestation_tag(tag: Tag) -> bool { |
Janis Danisevskis | 83116e5 | 2021-04-06 13:36:58 -0700 | [diff] [blame] | 104 | matches!( |
| 105 | tag, |
| 106 | Tag::ATTESTATION_ID_IMEI |
| 107 | | Tag::ATTESTATION_ID_MEID |
| 108 | | Tag::ATTESTATION_ID_SERIAL |
| 109 | | Tag::DEVICE_UNIQUE_ATTESTATION |
Eran Messeri | 637259c | 2022-10-31 12:23:36 +0000 | [diff] [blame] | 110 | | Tag::ATTESTATION_ID_SECOND_IMEI |
Janis Danisevskis | 83116e5 | 2021-04-06 13:36:58 -0700 | [diff] [blame] | 111 | ) |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 112 | } |
| 113 | |
| 114 | /// 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] | 115 | /// identifiers. It throws an error if the permissions cannot be verified or if the caller doesn't |
| 116 | /// have the right permissions. Otherwise it returns silently. |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 117 | pub fn check_device_attestation_permissions() -> anyhow::Result<()> { |
Seth Moore | 66d9e90 | 2022-03-16 17:20:31 -0700 | [diff] [blame] | 118 | check_android_permission("android.permission.READ_PRIVILEGED_PHONE_STATE") |
| 119 | } |
| 120 | |
| 121 | /// This function checks whether the calling app has the Android permissions needed to attest the |
| 122 | /// device-unique identifier. It throws an error if the permissions cannot be verified or if the |
| 123 | /// caller doesn't have the right permissions. Otherwise it returns silently. |
| 124 | pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> { |
| 125 | check_android_permission("android.permission.REQUEST_UNIQUE_ID_ATTESTATION") |
| 126 | } |
| 127 | |
| 128 | fn check_android_permission(permission: &str) -> anyhow::Result<()> { |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 129 | let permission_controller: Strong<dyn IPermissionController::IPermissionController> = |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 130 | binder::get_interface("permission")?; |
| 131 | |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 132 | let binder_result = { |
| 133 | let _wp = watchdog::watch_millis( |
| 134 | "In check_device_attestation_permissions: calling checkPermission.", |
| 135 | 500, |
| 136 | ); |
| 137 | permission_controller.checkPermission( |
Seth Moore | 66d9e90 | 2022-03-16 17:20:31 -0700 | [diff] [blame] | 138 | permission, |
Janis Danisevskis | 2ee014b | 2021-05-05 14:29:08 -0700 | [diff] [blame] | 139 | ThreadState::get_calling_pid(), |
| 140 | ThreadState::get_calling_uid() as i32, |
| 141 | ) |
| 142 | }; |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 143 | let has_permissions = |
| 144 | map_binder_status(binder_result).context(ks_err!("checkPermission failed"))?; |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 145 | match has_permissions { |
| 146 | true => Ok(()), |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 147 | false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) |
| 148 | .context(ks_err!("caller does not have the permission to attest device IDs")), |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 149 | } |
| 150 | } |
| 151 | |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 152 | /// Converts a set of key characteristics as returned from KeyMint into the internal |
| 153 | /// representation of the keystore service. |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 154 | pub fn key_characteristics_to_internal( |
Shawn Willden | dbdac60 | 2021-01-12 22:35:16 -0700 | [diff] [blame] | 155 | key_characteristics: Vec<KeyCharacteristics>, |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 156 | ) -> Vec<KeyParameter> { |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 157 | key_characteristics |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 158 | .into_iter() |
Shawn Willden | dbdac60 | 2021-01-12 22:35:16 -0700 | [diff] [blame] | 159 | .flat_map(|aidl_key_char| { |
| 160 | let sec_level = aidl_key_char.securityLevel; |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 161 | aidl_key_char |
| 162 | .authorizations |
| 163 | .into_iter() |
| 164 | .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level)) |
Shawn Willden | dbdac60 | 2021-01-12 22:35:16 -0700 | [diff] [blame] | 165 | }) |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 166 | .collect() |
| 167 | } |
| 168 | |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 169 | /// Upgrade a keyblob then invoke both the `new_blob_handler` and the `km_op` closures. On success |
| 170 | /// a tuple of the `km_op`s result and the optional upgraded blob is returned. |
| 171 | fn upgrade_keyblob_and_perform_op<T, KmOp, NewBlobHandler>( |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 172 | km_dev: &dyn IKeyMintDevice, |
| 173 | key_blob: &[u8], |
| 174 | upgrade_params: &[KmKeyParameter], |
| 175 | km_op: KmOp, |
| 176 | new_blob_handler: NewBlobHandler, |
| 177 | ) -> Result<(T, Option<Vec<u8>>)> |
| 178 | where |
| 179 | KmOp: Fn(&[u8]) -> Result<T, Error>, |
| 180 | NewBlobHandler: FnOnce(&[u8]) -> Result<()>, |
| 181 | { |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 182 | let upgraded_blob = { |
| 183 | let _wp = watchdog::watch_millis( |
| 184 | "In utils::upgrade_keyblob_and_perform_op: calling upgradeKey.", |
| 185 | 500, |
| 186 | ); |
| 187 | map_km_error(km_dev.upgradeKey(key_blob, upgrade_params)) |
| 188 | } |
| 189 | .context(ks_err!("Upgrade failed."))?; |
| 190 | |
| 191 | new_blob_handler(&upgraded_blob).context(ks_err!("calling new_blob_handler."))?; |
| 192 | |
| 193 | km_op(&upgraded_blob) |
| 194 | .map(|v| (v, Some(upgraded_blob))) |
| 195 | .context(ks_err!("Calling km_op after upgrade.")) |
| 196 | } |
| 197 | |
| 198 | /// This function can be used to upgrade key blobs on demand. The return value of |
| 199 | /// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered, |
| 200 | /// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called |
| 201 | /// with the upgraded blob as argument. Then `km_op` is called a second time with the |
| 202 | /// upgraded blob as argument. On success a tuple of the `km_op`s result and the |
| 203 | /// optional upgraded blob is returned. |
| 204 | pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>( |
| 205 | km_dev: &dyn IKeyMintDevice, |
| 206 | km_dev_version: i32, |
| 207 | key_blob: &[u8], |
| 208 | upgrade_params: &[KmKeyParameter], |
| 209 | km_op: KmOp, |
| 210 | new_blob_handler: NewBlobHandler, |
| 211 | ) -> Result<(T, Option<Vec<u8>>)> |
| 212 | where |
| 213 | KmOp: Fn(&[u8]) -> Result<T, Error>, |
| 214 | NewBlobHandler: FnOnce(&[u8]) -> Result<()>, |
| 215 | { |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 216 | match km_op(key_blob) { |
David Drysdale | 5accbaa | 2023-04-12 18:47:10 +0100 | [diff] [blame] | 217 | Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => upgrade_keyblob_and_perform_op( |
| 218 | km_dev, |
| 219 | key_blob, |
| 220 | upgrade_params, |
| 221 | km_op, |
| 222 | new_blob_handler, |
| 223 | ), |
| 224 | // Some devices have been known to upgrade their Keymaster device to be a KeyMint |
| 225 | // device with a new release of Android. If this is the case, then any pre-upgrade |
| 226 | // keyblobs will have the km_compat prefix attached to them. |
| 227 | // |
| 228 | // This prefix gets stripped by the km_compat layer when used pre-upgrade, but after |
| 229 | // the upgrade the keyblob will be passed as-is to the KeyMint device, which probably |
| 230 | // won't expect to see the km_compat prefix. |
| 231 | // |
| 232 | // So if a keyblob: |
| 233 | // a) gets rejected with INVALID_KEY_BLOB |
| 234 | // b) when sent to a KeyMint (not km_compat) device |
| 235 | // c) and has the km_compat magic prefix |
| 236 | // d) and was not a software-emulated key pre-upgrade |
| 237 | // then strip the prefix and attempt a key upgrade. |
| 238 | Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) |
| 239 | if km_dev_version >= KeyMintDevice::KEY_MINT_V1 |
| 240 | && key_blob.starts_with(km_compat::KEYMASTER_BLOB_HW_PREFIX) => |
| 241 | { |
| 242 | log::info!("found apparent km_compat(Keymaster) blob, attempt strip-and-upgrade"); |
| 243 | let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_HW_PREFIX.len()..]; |
| 244 | upgrade_keyblob_and_perform_op( |
| 245 | km_dev, |
| 246 | inner_keyblob, |
| 247 | upgrade_params, |
| 248 | km_op, |
| 249 | new_blob_handler, |
| 250 | ) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 251 | } |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 252 | r => r.map(|v| (v, None)).context(ks_err!("Calling km_op.")), |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 253 | } |
| 254 | } |
| 255 | |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 256 | /// Converts a set of key characteristics from the internal representation into a set of |
| 257 | /// Authorizations as they are used to convey key characteristics to the clients of keystore. |
| 258 | pub fn key_parameters_to_authorizations( |
| 259 | parameters: Vec<crate::key_parameter::KeyParameter>, |
| 260 | ) -> Vec<Authorization> { |
| 261 | parameters.into_iter().map(|p| p.into_authorization()).collect() |
| 262 | } |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 263 | |
Charisee | 03e0084 | 2023-01-25 01:41:23 +0000 | [diff] [blame] | 264 | #[allow(clippy::unnecessary_cast)] |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 265 | /// This returns the current time (in milliseconds) as an instance of a monotonic clock, |
| 266 | /// by invoking the system call since Rust does not support getting monotonic time instance |
| 267 | /// as an integer. |
| 268 | pub fn get_current_time_in_milliseconds() -> i64 { |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 269 | let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 }; |
Andrew Walbran | a47698a | 2023-07-21 17:23:56 +0100 | [diff] [blame] | 270 | // SAFETY: The pointer is valid because it comes from a reference, and clock_gettime doesn't |
| 271 | // retain it beyond the call. |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 272 | unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) }; |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 273 | 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] | 274 | } |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 275 | |
Janis Danisevskis | 7a1cf38 | 2020-11-20 11:22:14 -0800 | [diff] [blame] | 276 | /// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility |
| 277 | /// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL |
| 278 | /// (android.security.apc) spec. |
| 279 | pub fn compat_2_response_code(rc: u32) -> ApcResponseCode { |
| 280 | match rc { |
| 281 | APC_COMPAT_ERROR_OK => ApcResponseCode::OK, |
| 282 | APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED, |
| 283 | APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED, |
| 284 | APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING, |
| 285 | APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED, |
| 286 | APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR, |
| 287 | _ => ApcResponseCode::SYSTEM_ERROR, |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | /// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into |
| 292 | /// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility |
| 293 | /// module (keystore2_apc_compat). |
| 294 | pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions { |
| 295 | ApcCompatUiOptions { |
| 296 | inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0, |
| 297 | magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0, |
| 298 | } |
| 299 | } |
| 300 | |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 301 | /// AID offset for uid space partitioning. |
Joel Galenson | 81a50f2 | 2021-07-29 15:39:10 -0700 | [diff] [blame] | 302 | pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET; |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 303 | |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 304 | /// AID of the keystore process itself, used for keys that |
| 305 | /// keystore generates for its own use. |
Joel Galenson | 81a50f2 | 2021-07-29 15:39:10 -0700 | [diff] [blame] | 306 | pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE; |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 307 | |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 308 | /// Extracts the android user from the given uid. |
| 309 | pub fn uid_to_android_user(uid: u32) -> u32 { |
Joel Galenson | 81a50f2 | 2021-07-29 15:39:10 -0700 | [diff] [blame] | 310 | rustutils::users::multiuser_get_user_id(uid) |
Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 311 | } |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 312 | |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 313 | /// Merges and filters two lists of key descriptors. The first input list, legacy_descriptors, |
| 314 | /// is assumed to not be sorted or filtered. As such, all key descriptors in that list whose |
| 315 | /// alias is less than, or equal to, start_past_alias (if provided) will be removed. |
| 316 | /// This list will then be merged with the second list, db_descriptors. The db_descriptors list |
| 317 | /// is assumed to be sorted and filtered so the output list will be sorted prior to returning. |
| 318 | /// The returned value is a list of KeyDescriptor objects whose alias is greater than |
| 319 | /// start_past_alias, sorted and de-duplicated. |
| 320 | fn merge_and_filter_key_entry_lists( |
| 321 | legacy_descriptors: &[KeyDescriptor], |
| 322 | db_descriptors: &[KeyDescriptor], |
| 323 | start_past_alias: Option<&str>, |
| 324 | ) -> Vec<KeyDescriptor> { |
| 325 | let mut result: Vec<KeyDescriptor> = |
| 326 | match start_past_alias { |
| 327 | Some(past_alias) => legacy_descriptors |
| 328 | .iter() |
| 329 | .filter(|kd| { |
| 330 | if let Some(alias) = &kd.alias { |
| 331 | alias.as_str() > past_alias |
| 332 | } else { |
| 333 | false |
| 334 | } |
| 335 | }) |
| 336 | .cloned() |
| 337 | .collect(), |
| 338 | None => legacy_descriptors.to_vec(), |
| 339 | }; |
| 340 | |
| 341 | result.extend_from_slice(db_descriptors); |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 342 | result.sort_unstable(); |
| 343 | result.dedup(); |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 344 | result |
| 345 | } |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 346 | |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 347 | fn estimate_safe_amount_to_return( |
| 348 | key_descriptors: &[KeyDescriptor], |
| 349 | response_size_limit: usize, |
| 350 | ) -> usize { |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 351 | let mut items_to_return = 0; |
| 352 | let mut returned_bytes: usize = 0; |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 353 | // Estimate the transaction size to avoid returning more items than what |
| 354 | // could fit in a binder transaction. |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 355 | for kd in key_descriptors.iter() { |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 356 | // 4 bytes for the Domain enum |
| 357 | // 8 bytes for the Namespace long. |
| 358 | returned_bytes += 4 + 8; |
| 359 | // Size of the alias string. Includes 4 bytes for length encoding. |
| 360 | if let Some(alias) = &kd.alias { |
| 361 | returned_bytes += 4 + alias.len(); |
| 362 | } |
| 363 | // Size of the blob. Includes 4 bytes for length encoding. |
| 364 | if let Some(blob) = &kd.blob { |
| 365 | returned_bytes += 4 + blob.len(); |
| 366 | } |
| 367 | // The binder transaction size limit is 1M. Empirical measurements show |
| 368 | // that the binder overhead is 60% (to be confirmed). So break after |
| 369 | // 350KB and return a partial list. |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 370 | if returned_bytes > response_size_limit { |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 371 | log::warn!( |
| 372 | "Key descriptors list ({} items) may exceed binder \ |
| 373 | size, returning {} items est {} bytes.", |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 374 | key_descriptors.len(), |
Eran Messeri | 6e1213f | 2023-01-10 14:38:31 +0000 | [diff] [blame] | 375 | items_to_return, |
| 376 | returned_bytes |
| 377 | ); |
| 378 | break; |
| 379 | } |
| 380 | items_to_return += 1; |
| 381 | } |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 382 | items_to_return |
| 383 | } |
| 384 | |
| 385 | /// List all key aliases for a given domain + namespace. whose alias is greater |
| 386 | /// than start_past_alias (if provided). |
| 387 | pub fn list_key_entries( |
| 388 | db: &mut KeystoreDB, |
| 389 | domain: Domain, |
| 390 | namespace: i64, |
| 391 | start_past_alias: Option<&str>, |
| 392 | ) -> Result<Vec<KeyDescriptor>> { |
| 393 | let legacy_key_descriptors: Vec<KeyDescriptor> = LEGACY_IMPORTER |
| 394 | .list_uid(domain, namespace) |
| 395 | .context(ks_err!("Trying to list legacy keys."))?; |
| 396 | |
| 397 | // The results from the database will be sorted and unique |
| 398 | let db_key_descriptors: Vec<KeyDescriptor> = db |
| 399 | .list_past_alias(domain, namespace, KeyType::Client, start_past_alias) |
| 400 | .context(ks_err!("Trying to list keystore database past alias."))?; |
| 401 | |
| 402 | let merged_key_entries = merge_and_filter_key_entry_lists( |
| 403 | &legacy_key_descriptors, |
| 404 | &db_key_descriptors, |
| 405 | start_past_alias, |
| 406 | ); |
| 407 | |
| 408 | const RESPONSE_SIZE_LIMIT: usize = 358400; |
| 409 | let safe_amount_to_return = |
| 410 | estimate_safe_amount_to_return(&merged_key_entries, RESPONSE_SIZE_LIMIT); |
| 411 | Ok(merged_key_entries[..safe_amount_to_return].to_vec()) |
| 412 | } |
| 413 | |
| 414 | /// Count all key aliases for a given domain + namespace. |
| 415 | pub fn count_key_entries(db: &mut KeystoreDB, domain: Domain, namespace: i64) -> Result<i32> { |
| 416 | let legacy_keys = LEGACY_IMPORTER |
| 417 | .list_uid(domain, namespace) |
| 418 | .context(ks_err!("Trying to list legacy keys."))?; |
| 419 | |
| 420 | let num_keys_in_db = db.count_keys(domain, namespace, KeyType::Client)?; |
| 421 | |
| 422 | Ok((legacy_keys.len() + num_keys_in_db) as i32) |
John Wu | 16db29e | 2022-01-13 15:21:43 -0800 | [diff] [blame] | 423 | } |
| 424 | |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 425 | /// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM. |
| 426 | pub trait AesGcm { |
| 427 | /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag` |
| 428 | /// and AES-GCM. The implementation provides the key material and selects |
| 429 | /// the implementation variant, e.g., AES128 or AES265. |
| 430 | fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>; |
| 431 | |
| 432 | /// Encrypts `data` and returns the ciphertext, the initialization vector `iv` |
| 433 | /// and AEAD tag `tag`. The implementation provides the key material and selects |
| 434 | /// the implementation variant, e.g., AES128 or AES265. |
| 435 | fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>; |
| 436 | } |
| 437 | |
| 438 | /// Marks an object as AES-GCM key. |
| 439 | pub trait AesGcmKey { |
| 440 | /// Provides access to the raw key material. |
| 441 | fn key(&self) -> &[u8]; |
| 442 | } |
| 443 | |
| 444 | impl<T: AesGcmKey> AesGcm for T { |
| 445 | fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 446 | 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] | 447 | } |
| 448 | |
| 449 | fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> { |
Shaquille Johnson | aec2eca | 2022-11-30 17:08:05 +0000 | [diff] [blame] | 450 | aes_gcm_encrypt(plaintext, self.key()).context(ks_err!("Encryption failed.")) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 451 | } |
| 452 | } |
| 453 | |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 454 | #[cfg(test)] |
| 455 | mod tests { |
| 456 | use super::*; |
| 457 | use anyhow::Result; |
| 458 | |
| 459 | #[test] |
| 460 | fn check_device_attestation_permissions_test() -> Result<()> { |
| 461 | check_device_attestation_permissions().or_else(|error| { |
| 462 | match error.root_cause().downcast_ref::<Error>() { |
| 463 | // Expected: the context for this test might not be allowed to attest device IDs. |
| 464 | Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()), |
| 465 | // Other errors are unexpected |
| 466 | _ => Err(error), |
| 467 | } |
| 468 | }) |
| 469 | } |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 470 | |
| 471 | fn create_key_descriptors_from_aliases(key_aliases: &[&str]) -> Vec<KeyDescriptor> { |
| 472 | key_aliases |
| 473 | .iter() |
| 474 | .map(|key_alias| KeyDescriptor { |
| 475 | domain: Domain::APP, |
| 476 | nspace: 0, |
| 477 | alias: Some(key_alias.to_string()), |
| 478 | blob: None, |
| 479 | }) |
| 480 | .collect::<Vec<KeyDescriptor>>() |
| 481 | } |
| 482 | |
| 483 | fn aliases_from_key_descriptors(key_descriptors: &[KeyDescriptor]) -> Vec<String> { |
| 484 | key_descriptors |
| 485 | .iter() |
| 486 | .map( |
| 487 | |kd| { |
| 488 | if let Some(alias) = &kd.alias { |
| 489 | String::from(alias) |
| 490 | } else { |
| 491 | String::from("") |
| 492 | } |
| 493 | }, |
| 494 | ) |
| 495 | .collect::<Vec<String>>() |
| 496 | } |
| 497 | |
| 498 | #[test] |
| 499 | fn test_safe_amount_to_return() -> Result<()> { |
| 500 | let key_aliases = vec!["key1", "key2", "key3"]; |
| 501 | let key_descriptors = create_key_descriptors_from_aliases(&key_aliases); |
| 502 | |
| 503 | assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 20), 1); |
| 504 | assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 50), 2); |
| 505 | assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 100), 3); |
| 506 | Ok(()) |
| 507 | } |
| 508 | |
| 509 | #[test] |
| 510 | fn test_merge_and_sort_lists_without_filtering() -> Result<()> { |
| 511 | let legacy_key_aliases = vec!["key_c", "key_a", "key_b"]; |
| 512 | let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases); |
| 513 | let db_key_aliases = vec!["key_a", "key_d"]; |
| 514 | let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases); |
| 515 | let result = |
| 516 | merge_and_filter_key_entry_lists(&legacy_key_descriptors, &db_key_descriptors, None); |
| 517 | assert_eq!(aliases_from_key_descriptors(&result), vec!["key_a", "key_b", "key_c", "key_d"]); |
| 518 | Ok(()) |
| 519 | } |
| 520 | |
| 521 | #[test] |
| 522 | fn test_merge_and_sort_lists_with_filtering() -> Result<()> { |
| 523 | let legacy_key_aliases = vec!["key_f", "key_a", "key_e", "key_b"]; |
| 524 | let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases); |
| 525 | let db_key_aliases = vec!["key_c", "key_g"]; |
| 526 | let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases); |
| 527 | let result = merge_and_filter_key_entry_lists( |
| 528 | &legacy_key_descriptors, |
| 529 | &db_key_descriptors, |
| 530 | Some("key_b"), |
| 531 | ); |
| 532 | assert_eq!(aliases_from_key_descriptors(&result), vec!["key_c", "key_e", "key_f", "key_g"]); |
| 533 | Ok(()) |
| 534 | } |
| 535 | |
| 536 | #[test] |
| 537 | fn test_merge_and_sort_lists_with_filtering_and_dups() -> Result<()> { |
| 538 | let legacy_key_aliases = vec!["key_f", "key_a", "key_e", "key_b"]; |
| 539 | let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases); |
| 540 | let db_key_aliases = vec!["key_d", "key_e", "key_g"]; |
| 541 | let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases); |
| 542 | let result = merge_and_filter_key_entry_lists( |
| 543 | &legacy_key_descriptors, |
| 544 | &db_key_descriptors, |
| 545 | Some("key_c"), |
| 546 | ); |
| 547 | assert_eq!(aliases_from_key_descriptors(&result), vec!["key_d", "key_e", "key_f", "key_g"]); |
| 548 | Ok(()) |
| 549 | } |
Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 550 | } |