blob: 0a545f762a6e477d532e200b339326b995edb722 [file] [log] [blame]
Janis Danisevskisa75e2082020-10-07 16:44:26 -07001// 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 Danisevskisf84d0b02022-01-26 14:11:14 -080018use crate::error::{map_binder_status, map_km_error, Error, ErrorCode};
19use crate::key_parameter::KeyParameter;
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000020use crate::ks_err;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070021use crate::permission;
22use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
Alice Wang83c6aef2023-11-03 17:17:34 +000023pub use crate::watchdog_helper::watchdog;
John Wu16db29e2022-01-13 15:21:43 -080024use crate::{
25 database::{KeyType, KeystoreDB},
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080026 globals::LEGACY_IMPORTER,
David Drysdale5accbaa2023-04-12 18:47:10 +010027 km_compat,
28 raw_device::KeyMintDevice,
John Wu16db29e2022-01-13 15:21:43 -080029};
Shawn Willden708744a2020-12-11 13:05:27 +000030use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
David Drysdale746e1be2023-07-05 17:39:57 +010031 Algorithm::Algorithm, IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics,
32 KeyParameter::KeyParameter as KmKeyParameter, KeyParameterValue::KeyParameterValue, Tag::Tag,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070033};
Bram Bonné5d6c5102021-02-24 15:09:18 +010034use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080035use android_security_apc::aidl::android::security::apc::{
36 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
37 ResponseCode::ResponseCode as ApcResponseCode,
38};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070039use android_system_keystore2::aidl::android::system::keystore2::{
John Wu16db29e2022-01-13 15:21:43 -080040 Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070041};
John Wu16db29e2022-01-13 15:21:43 -080042use anyhow::{Context, Result};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070043use binder::{Strong, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080044use 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 Danisevskisf84d0b02022-01-26 14:11:14 -080049use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec};
50use std::iter::IntoIterator;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070051
David Drysdale2566fb32024-07-09 14:46:37 +010052#[cfg(test)]
53mod tests;
54
David Drysdale746e1be2023-07-05 17:39:57 +010055/// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
56/// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
57pub const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
58
Janis Danisevskisa75e2082020-10-07 16:44:26 -070059/// This function uses its namesake in the permission module and in
60/// combination with with_calling_sid from the binder crate to check
61/// if the caller has the given keystore permission.
62pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
63 ThreadState::with_calling_sid(|calling_sid| {
64 permission::check_keystore_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000065 calling_sid
66 .ok_or_else(Error::sys)
67 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070068 perm,
69 )
70 })
71}
72
73/// This function uses its namesake in the permission module and in
74/// combination with with_calling_sid from the binder crate to check
75/// if the caller has the given grant permission.
76pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
77 ThreadState::with_calling_sid(|calling_sid| {
78 permission::check_grant_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000079 calling_sid
80 .ok_or_else(Error::sys)
81 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070082 access_vec,
83 key,
84 )
85 })
86}
87
88/// This function uses its namesake in the permission module and in
89/// combination with with_calling_sid from the binder crate to check
90/// if the caller has the given key permission.
91pub fn check_key_permission(
92 perm: KeyPerm,
93 key: &KeyDescriptor,
94 access_vector: &Option<KeyPermSet>,
95) -> anyhow::Result<()> {
96 ThreadState::with_calling_sid(|calling_sid| {
97 permission::check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -080098 ThreadState::get_calling_uid(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -070099 calling_sid
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700100 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000101 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700102 perm,
103 key,
104 access_vector,
105 )
106 })
107}
108
Bram Bonné5d6c5102021-02-24 15:09:18 +0100109/// This function checks whether a given tag corresponds to the access of device identifiers.
110pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -0700111 matches!(
112 tag,
113 Tag::ATTESTATION_ID_IMEI
114 | Tag::ATTESTATION_ID_MEID
115 | Tag::ATTESTATION_ID_SERIAL
116 | Tag::DEVICE_UNIQUE_ATTESTATION
Eran Messeri637259c2022-10-31 12:23:36 +0000117 | Tag::ATTESTATION_ID_SECOND_IMEI
Janis Danisevskis83116e52021-04-06 13:36:58 -0700118 )
Bram Bonné5d6c5102021-02-24 15:09:18 +0100119}
120
121/// This function checks whether the calling app has the Android permissions needed to attest device
Seth Moore66d9e902022-03-16 17:20:31 -0700122/// identifiers. It throws an error if the permissions cannot be verified or if the caller doesn't
123/// have the right permissions. Otherwise it returns silently.
Bram Bonné5d6c5102021-02-24 15:09:18 +0100124pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
Seth Moore66d9e902022-03-16 17:20:31 -0700125 check_android_permission("android.permission.READ_PRIVILEGED_PHONE_STATE")
126}
127
128/// This function checks whether the calling app has the Android permissions needed to attest the
129/// device-unique identifier. It throws an error if the permissions cannot be verified or if the
130/// caller doesn't have the right permissions. Otherwise it returns silently.
131pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> {
132 check_android_permission("android.permission.REQUEST_UNIQUE_ID_ATTESTATION")
133}
134
Eran Messericfe79f12024-02-05 17:50:41 +0000135/// This function checks whether the calling app has the Android permissions needed to manage
136/// users. Only callers that can manage users are allowed to get a list of apps affected
137/// by a user's SID changing.
138/// It throws an error if the permissions cannot be verified or if the caller doesn't
139/// have the right permissions. Otherwise it returns silently.
140pub fn check_get_app_uids_affected_by_sid_permissions() -> anyhow::Result<()> {
141 check_android_permission("android.permission.MANAGE_USERS")
142}
143
Seth Moore66d9e902022-03-16 17:20:31 -0700144fn check_android_permission(permission: &str) -> anyhow::Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700145 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
Bram Bonné5d6c5102021-02-24 15:09:18 +0100146 binder::get_interface("permission")?;
147
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700148 let binder_result = {
David Drysdalec652f6c2024-07-18 13:01:23 +0100149 let _wp = watchdog::watch("check_android_permission: calling checkPermission");
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700150 permission_controller.checkPermission(
Seth Moore66d9e902022-03-16 17:20:31 -0700151 permission,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700152 ThreadState::get_calling_pid(),
153 ThreadState::get_calling_uid() as i32,
154 )
155 };
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000156 let has_permissions =
157 map_binder_status(binder_result).context(ks_err!("checkPermission failed"))?;
Bram Bonné5d6c5102021-02-24 15:09:18 +0100158 match has_permissions {
159 true => Ok(()),
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000160 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS))
161 .context(ks_err!("caller does not have the permission to attest device IDs")),
Bram Bonné5d6c5102021-02-24 15:09:18 +0100162 }
163}
164
Janis Danisevskis04b02832020-10-26 09:21:40 -0700165/// Converts a set of key characteristics as returned from KeyMint into the internal
166/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700167pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700168 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800169) -> Vec<KeyParameter> {
Janis Danisevskis04b02832020-10-26 09:21:40 -0700170 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700171 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700172 .flat_map(|aidl_key_char| {
173 let sec_level = aidl_key_char.securityLevel;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800174 aidl_key_char
175 .authorizations
176 .into_iter()
177 .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level))
Shawn Willdendbdac602021-01-12 22:35:16 -0700178 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700179 .collect()
180}
181
David Drysdale746e1be2023-07-05 17:39:57 +0100182/// Import a keyblob that is of the format used by the software C++ KeyMint implementation. After
183/// successful import, invoke both the `new_blob_handler` and `km_op` closures. On success a tuple
184/// of the `km_op`s result and the optional upgraded blob is returned.
185fn import_keyblob_and_perform_op<T, KmOp, NewBlobHandler>(
186 km_dev: &dyn IKeyMintDevice,
187 inner_keyblob: &[u8],
188 upgrade_params: &[KmKeyParameter],
189 km_op: KmOp,
190 new_blob_handler: NewBlobHandler,
191) -> Result<(T, Option<Vec<u8>>)>
192where
193 KmOp: Fn(&[u8]) -> Result<T, Error>,
194 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
195{
196 let (format, key_material, mut chars) =
197 crate::sw_keyblob::export_key(inner_keyblob, upgrade_params)?;
198 log::debug!(
199 "importing {:?} key material (len={}) with original chars={:?}",
200 format,
201 key_material.len(),
202 chars
203 );
204 let asymmetric = chars.iter().any(|kp| {
205 kp.tag == Tag::ALGORITHM
206 && (kp.value == KeyParameterValue::Algorithm(Algorithm::RSA)
207 || (kp.value == KeyParameterValue::Algorithm(Algorithm::EC)))
208 });
209
210 // Combine the characteristics of the previous keyblob with the upgrade parameters (which might
211 // include special things like APPLICATION_ID / APPLICATION_DATA).
212 chars.extend_from_slice(upgrade_params);
213
214 // Now filter out values from the existing keyblob that shouldn't be set on import, either
215 // because they are per-operation parameter or because they are auto-added by KeyMint itself.
216 let mut import_params: Vec<KmKeyParameter> = chars
217 .into_iter()
218 .filter(|kp| {
219 !matches!(
220 kp.tag,
221 Tag::ORIGIN
222 | Tag::ROOT_OF_TRUST
223 | Tag::OS_VERSION
224 | Tag::OS_PATCHLEVEL
225 | Tag::UNIQUE_ID
226 | Tag::ATTESTATION_CHALLENGE
227 | Tag::ATTESTATION_APPLICATION_ID
228 | Tag::ATTESTATION_ID_BRAND
229 | Tag::ATTESTATION_ID_DEVICE
230 | Tag::ATTESTATION_ID_PRODUCT
231 | Tag::ATTESTATION_ID_SERIAL
232 | Tag::ATTESTATION_ID_IMEI
233 | Tag::ATTESTATION_ID_MEID
234 | Tag::ATTESTATION_ID_MANUFACTURER
235 | Tag::ATTESTATION_ID_MODEL
236 | Tag::VENDOR_PATCHLEVEL
237 | Tag::BOOT_PATCHLEVEL
238 | Tag::DEVICE_UNIQUE_ATTESTATION
239 | Tag::ATTESTATION_ID_SECOND_IMEI
240 | Tag::NONCE
241 | Tag::MAC_LENGTH
242 | Tag::CERTIFICATE_SERIAL
243 | Tag::CERTIFICATE_SUBJECT
244 | Tag::CERTIFICATE_NOT_BEFORE
245 | Tag::CERTIFICATE_NOT_AFTER
246 )
247 })
248 .collect();
249
250 // Now that any previous values have been removed, add any additional parameters that needed for
251 // import. In particular, if we are generating/importing an asymmetric key, we need to make sure
252 // that NOT_BEFORE and NOT_AFTER are present.
253 if asymmetric {
254 import_params.push(KmKeyParameter {
255 tag: Tag::CERTIFICATE_NOT_BEFORE,
256 value: KeyParameterValue::DateTime(0),
257 });
258 import_params.push(KmKeyParameter {
259 tag: Tag::CERTIFICATE_NOT_AFTER,
260 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
261 });
262 }
263 log::debug!("import parameters={import_params:?}");
264
265 let creation_result = {
David Drysdalec652f6c2024-07-18 13:01:23 +0100266 let _wp = watchdog::watch(
267 "utils::import_keyblob_and_perform_op: calling IKeyMintDevice::importKey",
268 );
David Drysdale746e1be2023-07-05 17:39:57 +0100269 map_km_error(km_dev.importKey(&import_params, format, &key_material, None))
270 }
271 .context(ks_err!("Upgrade failed."))?;
272
273 // Note that the importKey operation will produce key characteristics that may be different
274 // than are already stored in Keystore's SQL database. In particular, the KeyMint
275 // implementation will now mark the key as `Origin::IMPORTED` not `Origin::GENERATED`, and
276 // the security level for characteristics will now be `TRUSTED_ENVIRONMENT` not `SOFTWARE`.
277 //
278 // However, the DB metadata still accurately reflects the original origin of the key, and
279 // so we leave the values as-is (and so any `KeyInfo` retrieved in the Java layer will get the
280 // same results before and after import).
281 //
282 // Note that this also applies to the `USAGE_COUNT_LIMIT` parameter -- if the key has already
283 // been used, then the DB version of the parameter will be (and will continue to be) lower
284 // than the original count bound to the keyblob. This means that Keystore's policing of
285 // usage counts will continue where it left off.
286
287 new_blob_handler(&creation_result.keyBlob).context(ks_err!("calling new_blob_handler."))?;
288
289 km_op(&creation_result.keyBlob)
290 .map(|v| (v, Some(creation_result.keyBlob)))
291 .context(ks_err!("Calling km_op after upgrade."))
292}
293
David Drysdale5accbaa2023-04-12 18:47:10 +0100294/// Upgrade a keyblob then invoke both the `new_blob_handler` and the `km_op` closures. On success
295/// a tuple of the `km_op`s result and the optional upgraded blob is returned.
296fn upgrade_keyblob_and_perform_op<T, KmOp, NewBlobHandler>(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800297 km_dev: &dyn IKeyMintDevice,
298 key_blob: &[u8],
299 upgrade_params: &[KmKeyParameter],
300 km_op: KmOp,
301 new_blob_handler: NewBlobHandler,
302) -> Result<(T, Option<Vec<u8>>)>
303where
304 KmOp: Fn(&[u8]) -> Result<T, Error>,
305 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
306{
David Drysdale5accbaa2023-04-12 18:47:10 +0100307 let upgraded_blob = {
David Drysdalec652f6c2024-07-18 13:01:23 +0100308 let _wp = watchdog::watch(
309 "utils::upgrade_keyblob_and_perform_op: calling IKeyMintDevice::upgradeKey.",
310 );
David Drysdale5accbaa2023-04-12 18:47:10 +0100311 map_km_error(km_dev.upgradeKey(key_blob, upgrade_params))
312 }
313 .context(ks_err!("Upgrade failed."))?;
314
315 new_blob_handler(&upgraded_blob).context(ks_err!("calling new_blob_handler."))?;
316
317 km_op(&upgraded_blob)
318 .map(|v| (v, Some(upgraded_blob)))
319 .context(ks_err!("Calling km_op after upgrade."))
320}
321
322/// This function can be used to upgrade key blobs on demand. The return value of
323/// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered,
324/// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called
325/// with the upgraded blob as argument. Then `km_op` is called a second time with the
326/// upgraded blob as argument. On success a tuple of the `km_op`s result and the
327/// optional upgraded blob is returned.
328pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>(
329 km_dev: &dyn IKeyMintDevice,
330 km_dev_version: i32,
331 key_blob: &[u8],
332 upgrade_params: &[KmKeyParameter],
333 km_op: KmOp,
334 new_blob_handler: NewBlobHandler,
335) -> Result<(T, Option<Vec<u8>>)>
336where
337 KmOp: Fn(&[u8]) -> Result<T, Error>,
338 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
339{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800340 match km_op(key_blob) {
David Drysdale5accbaa2023-04-12 18:47:10 +0100341 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => upgrade_keyblob_and_perform_op(
342 km_dev,
343 key_blob,
344 upgrade_params,
345 km_op,
346 new_blob_handler,
347 ),
David Drysdale5accbaa2023-04-12 18:47:10 +0100348 Err(Error::Km(ErrorCode::INVALID_KEY_BLOB))
David Drysdale746e1be2023-07-05 17:39:57 +0100349 if km_dev_version >= KeyMintDevice::KEY_MINT_V1 =>
David Drysdale5accbaa2023-04-12 18:47:10 +0100350 {
David Drysdale746e1be2023-07-05 17:39:57 +0100351 // A KeyMint (not Keymaster via km_compat) device says that this is an invalid keyblob.
352 //
353 // This may be because the keyblob was created before an Android upgrade, and as part of
354 // the device upgrade the underlying Keymaster/KeyMint implementation has been upgraded.
355 //
356 // If that's the case, there are three possible scenarios:
357 if key_blob.starts_with(km_compat::KEYMASTER_BLOB_HW_PREFIX) {
358 // 1) The keyblob was created in hardware by the km_compat C++ code, using a prior
359 // Keymaster implementation, and wrapped.
360 //
361 // In this case, the keyblob will have the km_compat magic prefix, including the
362 // marker that indicates that this was a hardware-backed key.
363 //
364 // The inner keyblob should still be recognized by the hardware implementation, so
365 // strip the prefix and attempt a key upgrade.
366 log::info!(
367 "found apparent km_compat(Keymaster) HW blob, attempt strip-and-upgrade"
368 );
369 let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_HW_PREFIX.len()..];
370 upgrade_keyblob_and_perform_op(
371 km_dev,
372 inner_keyblob,
373 upgrade_params,
374 km_op,
375 new_blob_handler,
376 )
David Drysdale093811e2023-11-09 08:32:02 +0000377 } else if keystore2_flags::import_previously_emulated_keys()
378 && key_blob.starts_with(km_compat::KEYMASTER_BLOB_SW_PREFIX)
379 {
David Drysdale746e1be2023-07-05 17:39:57 +0100380 // 2) The keyblob was created in software by the km_compat C++ code because a prior
381 // Keymaster implementation did not support ECDH (which was only added in KeyMint).
382 //
383 // In this case, the keyblob with have the km_compat magic prefix, but with the
384 // marker that indicates that this was a software-emulated key.
385 //
386 // The inner keyblob should be in the format produced by the C++ reference
387 // implementation of KeyMint. Extract the key material and import it into the
388 // current KeyMint device.
389 log::info!("found apparent km_compat(Keymaster) SW blob, attempt strip-and-import");
390 let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_SW_PREFIX.len()..];
391 import_keyblob_and_perform_op(
392 km_dev,
393 inner_keyblob,
394 upgrade_params,
395 km_op,
396 new_blob_handler,
397 )
David Drysdale093811e2023-11-09 08:32:02 +0000398 } else if let (true, km_compat::KeyBlob::Wrapped(inner_keyblob)) = (
399 keystore2_flags::import_previously_emulated_keys(),
400 km_compat::unwrap_keyblob(key_blob),
401 ) {
David Drysdale746e1be2023-07-05 17:39:57 +0100402 // 3) The keyblob was created in software by km_compat.rs because a prior KeyMint
403 // implementation did not support a feature present in the current KeyMint spec.
404 // (For example, a curve 25519 key created when the device only supported KeyMint
405 // v1).
406 //
407 // In this case, the keyblob with have the km_compat.rs wrapper around it to
408 // indicate that this was a software-emulated key.
409 //
410 // The inner keyblob should be in the format produced by the C++ reference
411 // implementation of KeyMint. Extract the key material and import it into the
412 // current KeyMint device.
413 log::info!(
414 "found apparent km_compat.rs(KeyMint) SW blob, attempt strip-and-import"
415 );
416 import_keyblob_and_perform_op(
417 km_dev,
418 inner_keyblob,
419 upgrade_params,
420 km_op,
421 new_blob_handler,
422 )
423 } else {
424 Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)).context(ks_err!("Calling km_op"))
425 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800426 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000427 r => r.map(|v| (v, None)).context(ks_err!("Calling km_op.")),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800428 }
429}
430
Janis Danisevskis04b02832020-10-26 09:21:40 -0700431/// Converts a set of key characteristics from the internal representation into a set of
432/// Authorizations as they are used to convey key characteristics to the clients of keystore.
433pub fn key_parameters_to_authorizations(
434 parameters: Vec<crate::key_parameter::KeyParameter>,
435) -> Vec<Authorization> {
436 parameters.into_iter().map(|p| p.into_authorization()).collect()
437}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000438
Charisee03e00842023-01-25 01:41:23 +0000439#[allow(clippy::unnecessary_cast)]
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000440/// This returns the current time (in milliseconds) as an instance of a monotonic clock,
441/// by invoking the system call since Rust does not support getting monotonic time instance
442/// as an integer.
443pub fn get_current_time_in_milliseconds() -> i64 {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000444 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
Andrew Walbrana47698a2023-07-21 17:23:56 +0100445 // SAFETY: The pointer is valid because it comes from a reference, and clock_gettime doesn't
446 // retain it beyond the call.
James Willcox80f7be12023-11-08 17:13:16 +0000447 unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut current_time) };
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000448 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000449}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800450
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800451/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
452/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
453/// (android.security.apc) spec.
454pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
455 match rc {
456 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
457 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
458 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
459 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
460 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
461 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
462 _ => ApcResponseCode::SYSTEM_ERROR,
463 }
464}
465
466/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
467/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
468/// module (keystore2_apc_compat).
469pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
470 ApcCompatUiOptions {
471 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
472 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
473 }
474}
475
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800476/// AID offset for uid space partitioning.
Joel Galenson81a50f22021-07-29 15:39:10 -0700477pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800478
Paul Crowley44c02da2021-04-08 17:04:43 +0000479/// AID of the keystore process itself, used for keys that
480/// keystore generates for its own use.
Joel Galenson81a50f22021-07-29 15:39:10 -0700481pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
Paul Crowley44c02da2021-04-08 17:04:43 +0000482
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800483/// Extracts the android user from the given uid.
484pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galenson81a50f22021-07-29 15:39:10 -0700485 rustutils::users::multiuser_get_user_id(uid)
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800486}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100487
Eran Messeri24f31972023-01-25 17:00:33 +0000488/// Merges and filters two lists of key descriptors. The first input list, legacy_descriptors,
489/// is assumed to not be sorted or filtered. As such, all key descriptors in that list whose
490/// alias is less than, or equal to, start_past_alias (if provided) will be removed.
491/// This list will then be merged with the second list, db_descriptors. The db_descriptors list
492/// is assumed to be sorted and filtered so the output list will be sorted prior to returning.
493/// The returned value is a list of KeyDescriptor objects whose alias is greater than
494/// start_past_alias, sorted and de-duplicated.
495fn merge_and_filter_key_entry_lists(
496 legacy_descriptors: &[KeyDescriptor],
497 db_descriptors: &[KeyDescriptor],
498 start_past_alias: Option<&str>,
499) -> Vec<KeyDescriptor> {
500 let mut result: Vec<KeyDescriptor> =
501 match start_past_alias {
502 Some(past_alias) => legacy_descriptors
503 .iter()
504 .filter(|kd| {
505 if let Some(alias) = &kd.alias {
506 alias.as_str() > past_alias
507 } else {
508 false
509 }
510 })
511 .cloned()
512 .collect(),
513 None => legacy_descriptors.to_vec(),
514 };
515
516 result.extend_from_slice(db_descriptors);
John Wu16db29e2022-01-13 15:21:43 -0800517 result.sort_unstable();
518 result.dedup();
Eran Messeri24f31972023-01-25 17:00:33 +0000519 result
520}
Eran Messeri6e1213f2023-01-10 14:38:31 +0000521
Eran Messeri24f31972023-01-25 17:00:33 +0000522fn estimate_safe_amount_to_return(
David Drysdale4e5b4c72024-06-28 13:41:27 +0100523 domain: Domain,
524 namespace: i64,
Eran Messeri24f31972023-01-25 17:00:33 +0000525 key_descriptors: &[KeyDescriptor],
526 response_size_limit: usize,
527) -> usize {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000528 let mut items_to_return = 0;
529 let mut returned_bytes: usize = 0;
Eran Messeri6e1213f2023-01-10 14:38:31 +0000530 // Estimate the transaction size to avoid returning more items than what
531 // could fit in a binder transaction.
Eran Messeri24f31972023-01-25 17:00:33 +0000532 for kd in key_descriptors.iter() {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000533 // 4 bytes for the Domain enum
534 // 8 bytes for the Namespace long.
535 returned_bytes += 4 + 8;
536 // Size of the alias string. Includes 4 bytes for length encoding.
537 if let Some(alias) = &kd.alias {
538 returned_bytes += 4 + alias.len();
539 }
540 // Size of the blob. Includes 4 bytes for length encoding.
541 if let Some(blob) = &kd.blob {
542 returned_bytes += 4 + blob.len();
543 }
544 // The binder transaction size limit is 1M. Empirical measurements show
545 // that the binder overhead is 60% (to be confirmed). So break after
546 // 350KB and return a partial list.
Eran Messeri24f31972023-01-25 17:00:33 +0000547 if returned_bytes > response_size_limit {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000548 log::warn!(
David Drysdale4e5b4c72024-06-28 13:41:27 +0100549 "{domain:?}:{namespace}: Key descriptors list ({} items) may exceed binder \
550 size, returning {items_to_return} items est {returned_bytes} bytes.",
Eran Messeri24f31972023-01-25 17:00:33 +0000551 key_descriptors.len(),
Eran Messeri6e1213f2023-01-10 14:38:31 +0000552 );
553 break;
554 }
555 items_to_return += 1;
556 }
Eran Messeri24f31972023-01-25 17:00:33 +0000557 items_to_return
558}
559
Shaquille Johnsona820ef52024-06-20 13:48:23 +0000560/// List all key aliases for a given domain + namespace. whose alias is greater
561/// than start_past_alias (if provided).
Eran Messeri24f31972023-01-25 17:00:33 +0000562pub fn list_key_entries(
563 db: &mut KeystoreDB,
564 domain: Domain,
565 namespace: i64,
566 start_past_alias: Option<&str>,
567) -> Result<Vec<KeyDescriptor>> {
568 let legacy_key_descriptors: Vec<KeyDescriptor> = LEGACY_IMPORTER
569 .list_uid(domain, namespace)
570 .context(ks_err!("Trying to list legacy keys."))?;
571
572 // The results from the database will be sorted and unique
573 let db_key_descriptors: Vec<KeyDescriptor> = db
574 .list_past_alias(domain, namespace, KeyType::Client, start_past_alias)
575 .context(ks_err!("Trying to list keystore database past alias."))?;
576
577 let merged_key_entries = merge_and_filter_key_entry_lists(
578 &legacy_key_descriptors,
579 &db_key_descriptors,
580 start_past_alias,
581 );
582
583 const RESPONSE_SIZE_LIMIT: usize = 358400;
584 let safe_amount_to_return =
David Drysdale4e5b4c72024-06-28 13:41:27 +0100585 estimate_safe_amount_to_return(domain, namespace, &merged_key_entries, RESPONSE_SIZE_LIMIT);
Eran Messeri24f31972023-01-25 17:00:33 +0000586 Ok(merged_key_entries[..safe_amount_to_return].to_vec())
587}
588
589/// Count all key aliases for a given domain + namespace.
590pub fn count_key_entries(db: &mut KeystoreDB, domain: Domain, namespace: i64) -> Result<i32> {
591 let legacy_keys = LEGACY_IMPORTER
592 .list_uid(domain, namespace)
593 .context(ks_err!("Trying to list legacy keys."))?;
594
595 let num_keys_in_db = db.count_keys(domain, namespace, KeyType::Client)?;
596
597 Ok((legacy_keys.len() + num_keys_in_db) as i32)
John Wu16db29e2022-01-13 15:21:43 -0800598}
599
Shaquille Johnson668d2922024-07-02 18:03:47 +0000600/// For params remove sensitive data before returning a string for logging
601pub fn log_security_safe_params(params: &[KmKeyParameter]) -> Vec<KmKeyParameter> {
602 params
603 .iter()
604 .filter(|kp| (kp.tag != Tag::APPLICATION_ID && kp.tag != Tag::APPLICATION_DATA))
605 .cloned()
606 .collect::<Vec<KmKeyParameter>>()
607}
608
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800609/// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
610pub trait AesGcm {
611 /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
612 /// and AES-GCM. The implementation provides the key material and selects
613 /// the implementation variant, e.g., AES128 or AES265.
614 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>;
615
616 /// Encrypts `data` and returns the ciphertext, the initialization vector `iv`
617 /// and AEAD tag `tag`. The implementation provides the key material and selects
618 /// the implementation variant, e.g., AES128 or AES265.
619 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>;
620}
621
622/// Marks an object as AES-GCM key.
623pub trait AesGcmKey {
624 /// Provides access to the raw key material.
625 fn key(&self) -> &[u8];
626}
627
628impl<T: AesGcmKey> AesGcm for T {
629 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000630 aes_gcm_decrypt(data, iv, tag, self.key()).context(ks_err!("Decryption failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800631 }
632
633 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000634 aes_gcm_encrypt(plaintext, self.key()).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800635 }
636}