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