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