blob: 174a22ba5790e2244dc3ce5fc53668ab900e4ce2 [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 Drysdale746e1be2023-07-05 17:39:57 +010052/// 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.
54pub const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
55
Janis Danisevskisa75e2082020-10-07 16:44:26 -070056/// 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.
59pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
60 ThreadState::with_calling_sid(|calling_sid| {
61 permission::check_keystore_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000062 calling_sid
63 .ok_or_else(Error::sys)
64 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070065 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.
73pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
74 ThreadState::with_calling_sid(|calling_sid| {
75 permission::check_grant_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000076 calling_sid
77 .ok_or_else(Error::sys)
78 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070079 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.
88pub 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(
Janis Danisevskis45760022021-01-19 16:34:10 -080095 ThreadState::get_calling_uid(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -070096 calling_sid
Janis Danisevskisa75e2082020-10-07 16:44:26 -070097 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000098 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070099 perm,
100 key,
101 access_vector,
102 )
103 })
104}
105
Bram Bonné5d6c5102021-02-24 15:09:18 +0100106/// This function checks whether a given tag corresponds to the access of device identifiers.
107pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -0700108 matches!(
109 tag,
110 Tag::ATTESTATION_ID_IMEI
111 | Tag::ATTESTATION_ID_MEID
112 | Tag::ATTESTATION_ID_SERIAL
113 | Tag::DEVICE_UNIQUE_ATTESTATION
Eran Messeri637259c2022-10-31 12:23:36 +0000114 | Tag::ATTESTATION_ID_SECOND_IMEI
Janis Danisevskis83116e52021-04-06 13:36:58 -0700115 )
Bram Bonné5d6c5102021-02-24 15:09:18 +0100116}
117
118/// This function checks whether the calling app has the Android permissions needed to attest device
Seth Moore66d9e902022-03-16 17:20:31 -0700119/// 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.
Bram Bonné5d6c5102021-02-24 15:09:18 +0100121pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
Seth Moore66d9e902022-03-16 17:20:31 -0700122 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.
128pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> {
129 check_android_permission("android.permission.REQUEST_UNIQUE_ID_ATTESTATION")
130}
131
132fn check_android_permission(permission: &str) -> anyhow::Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700133 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
Bram Bonné5d6c5102021-02-24 15:09:18 +0100134 binder::get_interface("permission")?;
135
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700136 let binder_result = {
137 let _wp = watchdog::watch_millis(
138 "In check_device_attestation_permissions: calling checkPermission.",
139 500,
140 );
141 permission_controller.checkPermission(
Seth Moore66d9e902022-03-16 17:20:31 -0700142 permission,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700143 ThreadState::get_calling_pid(),
144 ThreadState::get_calling_uid() as i32,
145 )
146 };
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000147 let has_permissions =
148 map_binder_status(binder_result).context(ks_err!("checkPermission failed"))?;
Bram Bonné5d6c5102021-02-24 15:09:18 +0100149 match has_permissions {
150 true => Ok(()),
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000151 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS))
152 .context(ks_err!("caller does not have the permission to attest device IDs")),
Bram Bonné5d6c5102021-02-24 15:09:18 +0100153 }
154}
155
Janis Danisevskis04b02832020-10-26 09:21:40 -0700156/// Converts a set of key characteristics as returned from KeyMint into the internal
157/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700158pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700159 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800160) -> Vec<KeyParameter> {
Janis Danisevskis04b02832020-10-26 09:21:40 -0700161 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700162 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700163 .flat_map(|aidl_key_char| {
164 let sec_level = aidl_key_char.securityLevel;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800165 aidl_key_char
166 .authorizations
167 .into_iter()
168 .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level))
Shawn Willdendbdac602021-01-12 22:35:16 -0700169 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700170 .collect()
171}
172
David Drysdale746e1be2023-07-05 17:39:57 +0100173/// Import a keyblob that is of the format used by the software C++ KeyMint implementation. After
174/// successful import, invoke both the `new_blob_handler` and `km_op` closures. On success a tuple
175/// of the `km_op`s result and the optional upgraded blob is returned.
176fn import_keyblob_and_perform_op<T, KmOp, NewBlobHandler>(
177 km_dev: &dyn IKeyMintDevice,
178 inner_keyblob: &[u8],
179 upgrade_params: &[KmKeyParameter],
180 km_op: KmOp,
181 new_blob_handler: NewBlobHandler,
182) -> Result<(T, Option<Vec<u8>>)>
183where
184 KmOp: Fn(&[u8]) -> Result<T, Error>,
185 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
186{
187 let (format, key_material, mut chars) =
188 crate::sw_keyblob::export_key(inner_keyblob, upgrade_params)?;
189 log::debug!(
190 "importing {:?} key material (len={}) with original chars={:?}",
191 format,
192 key_material.len(),
193 chars
194 );
195 let asymmetric = chars.iter().any(|kp| {
196 kp.tag == Tag::ALGORITHM
197 && (kp.value == KeyParameterValue::Algorithm(Algorithm::RSA)
198 || (kp.value == KeyParameterValue::Algorithm(Algorithm::EC)))
199 });
200
201 // Combine the characteristics of the previous keyblob with the upgrade parameters (which might
202 // include special things like APPLICATION_ID / APPLICATION_DATA).
203 chars.extend_from_slice(upgrade_params);
204
205 // Now filter out values from the existing keyblob that shouldn't be set on import, either
206 // because they are per-operation parameter or because they are auto-added by KeyMint itself.
207 let mut import_params: Vec<KmKeyParameter> = chars
208 .into_iter()
209 .filter(|kp| {
210 !matches!(
211 kp.tag,
212 Tag::ORIGIN
213 | Tag::ROOT_OF_TRUST
214 | Tag::OS_VERSION
215 | Tag::OS_PATCHLEVEL
216 | Tag::UNIQUE_ID
217 | Tag::ATTESTATION_CHALLENGE
218 | Tag::ATTESTATION_APPLICATION_ID
219 | Tag::ATTESTATION_ID_BRAND
220 | Tag::ATTESTATION_ID_DEVICE
221 | Tag::ATTESTATION_ID_PRODUCT
222 | Tag::ATTESTATION_ID_SERIAL
223 | Tag::ATTESTATION_ID_IMEI
224 | Tag::ATTESTATION_ID_MEID
225 | Tag::ATTESTATION_ID_MANUFACTURER
226 | Tag::ATTESTATION_ID_MODEL
227 | Tag::VENDOR_PATCHLEVEL
228 | Tag::BOOT_PATCHLEVEL
229 | Tag::DEVICE_UNIQUE_ATTESTATION
230 | Tag::ATTESTATION_ID_SECOND_IMEI
231 | Tag::NONCE
232 | Tag::MAC_LENGTH
233 | Tag::CERTIFICATE_SERIAL
234 | Tag::CERTIFICATE_SUBJECT
235 | Tag::CERTIFICATE_NOT_BEFORE
236 | Tag::CERTIFICATE_NOT_AFTER
237 )
238 })
239 .collect();
240
241 // Now that any previous values have been removed, add any additional parameters that needed for
242 // import. In particular, if we are generating/importing an asymmetric key, we need to make sure
243 // that NOT_BEFORE and NOT_AFTER are present.
244 if asymmetric {
245 import_params.push(KmKeyParameter {
246 tag: Tag::CERTIFICATE_NOT_BEFORE,
247 value: KeyParameterValue::DateTime(0),
248 });
249 import_params.push(KmKeyParameter {
250 tag: Tag::CERTIFICATE_NOT_AFTER,
251 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
252 });
253 }
254 log::debug!("import parameters={import_params:?}");
255
256 let creation_result = {
257 let _wp = watchdog::watch_millis(
258 "In utils::import_keyblob_and_perform_op: calling importKey.",
259 500,
260 );
261 map_km_error(km_dev.importKey(&import_params, format, &key_material, None))
262 }
263 .context(ks_err!("Upgrade failed."))?;
264
265 // Note that the importKey operation will produce key characteristics that may be different
266 // than are already stored in Keystore's SQL database. In particular, the KeyMint
267 // implementation will now mark the key as `Origin::IMPORTED` not `Origin::GENERATED`, and
268 // the security level for characteristics will now be `TRUSTED_ENVIRONMENT` not `SOFTWARE`.
269 //
270 // However, the DB metadata still accurately reflects the original origin of the key, and
271 // so we leave the values as-is (and so any `KeyInfo` retrieved in the Java layer will get the
272 // same results before and after import).
273 //
274 // Note that this also applies to the `USAGE_COUNT_LIMIT` parameter -- if the key has already
275 // been used, then the DB version of the parameter will be (and will continue to be) lower
276 // than the original count bound to the keyblob. This means that Keystore's policing of
277 // usage counts will continue where it left off.
278
279 new_blob_handler(&creation_result.keyBlob).context(ks_err!("calling new_blob_handler."))?;
280
281 km_op(&creation_result.keyBlob)
282 .map(|v| (v, Some(creation_result.keyBlob)))
283 .context(ks_err!("Calling km_op after upgrade."))
284}
285
David Drysdale5accbaa2023-04-12 18:47:10 +0100286/// Upgrade a keyblob then invoke both the `new_blob_handler` and the `km_op` closures. On success
287/// a tuple of the `km_op`s result and the optional upgraded blob is returned.
288fn upgrade_keyblob_and_perform_op<T, KmOp, NewBlobHandler>(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800289 km_dev: &dyn IKeyMintDevice,
290 key_blob: &[u8],
291 upgrade_params: &[KmKeyParameter],
292 km_op: KmOp,
293 new_blob_handler: NewBlobHandler,
294) -> Result<(T, Option<Vec<u8>>)>
295where
296 KmOp: Fn(&[u8]) -> Result<T, Error>,
297 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
298{
David Drysdale5accbaa2023-04-12 18:47:10 +0100299 let upgraded_blob = {
300 let _wp = watchdog::watch_millis(
301 "In utils::upgrade_keyblob_and_perform_op: calling upgradeKey.",
302 500,
303 );
304 map_km_error(km_dev.upgradeKey(key_blob, upgrade_params))
305 }
306 .context(ks_err!("Upgrade failed."))?;
307
308 new_blob_handler(&upgraded_blob).context(ks_err!("calling new_blob_handler."))?;
309
310 km_op(&upgraded_blob)
311 .map(|v| (v, Some(upgraded_blob)))
312 .context(ks_err!("Calling km_op after upgrade."))
313}
314
315/// This function can be used to upgrade key blobs on demand. The return value of
316/// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered,
317/// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called
318/// with the upgraded blob as argument. Then `km_op` is called a second time with the
319/// upgraded blob as argument. On success a tuple of the `km_op`s result and the
320/// optional upgraded blob is returned.
321pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>(
322 km_dev: &dyn IKeyMintDevice,
323 km_dev_version: i32,
324 key_blob: &[u8],
325 upgrade_params: &[KmKeyParameter],
326 km_op: KmOp,
327 new_blob_handler: NewBlobHandler,
328) -> Result<(T, Option<Vec<u8>>)>
329where
330 KmOp: Fn(&[u8]) -> Result<T, Error>,
331 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
332{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800333 match km_op(key_blob) {
David Drysdale5accbaa2023-04-12 18:47:10 +0100334 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => upgrade_keyblob_and_perform_op(
335 km_dev,
336 key_blob,
337 upgrade_params,
338 km_op,
339 new_blob_handler,
340 ),
David Drysdale5accbaa2023-04-12 18:47:10 +0100341 Err(Error::Km(ErrorCode::INVALID_KEY_BLOB))
David Drysdale746e1be2023-07-05 17:39:57 +0100342 if km_dev_version >= KeyMintDevice::KEY_MINT_V1 =>
David Drysdale5accbaa2023-04-12 18:47:10 +0100343 {
David Drysdale746e1be2023-07-05 17:39:57 +0100344 // A KeyMint (not Keymaster via km_compat) device says that this is an invalid keyblob.
345 //
346 // This may be because the keyblob was created before an Android upgrade, and as part of
347 // the device upgrade the underlying Keymaster/KeyMint implementation has been upgraded.
348 //
349 // If that's the case, there are three possible scenarios:
350 if key_blob.starts_with(km_compat::KEYMASTER_BLOB_HW_PREFIX) {
351 // 1) The keyblob was created in hardware by the km_compat C++ code, using a prior
352 // Keymaster implementation, and wrapped.
353 //
354 // In this case, the keyblob will have the km_compat magic prefix, including the
355 // marker that indicates that this was a hardware-backed key.
356 //
357 // The inner keyblob should still be recognized by the hardware implementation, so
358 // strip the prefix and attempt a key upgrade.
359 log::info!(
360 "found apparent km_compat(Keymaster) HW blob, attempt strip-and-upgrade"
361 );
362 let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_HW_PREFIX.len()..];
363 upgrade_keyblob_and_perform_op(
364 km_dev,
365 inner_keyblob,
366 upgrade_params,
367 km_op,
368 new_blob_handler,
369 )
David Drysdale093811e2023-11-09 08:32:02 +0000370 } else if keystore2_flags::import_previously_emulated_keys()
371 && key_blob.starts_with(km_compat::KEYMASTER_BLOB_SW_PREFIX)
372 {
David Drysdale746e1be2023-07-05 17:39:57 +0100373 // 2) The keyblob was created in software by the km_compat C++ code because a prior
374 // Keymaster implementation did not support ECDH (which was only added in KeyMint).
375 //
376 // In this case, the keyblob with have the km_compat magic prefix, but with the
377 // marker that indicates that this was a software-emulated key.
378 //
379 // The inner keyblob should be in the format produced by the C++ reference
380 // implementation of KeyMint. Extract the key material and import it into the
381 // current KeyMint device.
382 log::info!("found apparent km_compat(Keymaster) SW blob, attempt strip-and-import");
383 let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_SW_PREFIX.len()..];
384 import_keyblob_and_perform_op(
385 km_dev,
386 inner_keyblob,
387 upgrade_params,
388 km_op,
389 new_blob_handler,
390 )
David Drysdale093811e2023-11-09 08:32:02 +0000391 } else if let (true, km_compat::KeyBlob::Wrapped(inner_keyblob)) = (
392 keystore2_flags::import_previously_emulated_keys(),
393 km_compat::unwrap_keyblob(key_blob),
394 ) {
David Drysdale746e1be2023-07-05 17:39:57 +0100395 // 3) The keyblob was created in software by km_compat.rs because a prior KeyMint
396 // implementation did not support a feature present in the current KeyMint spec.
397 // (For example, a curve 25519 key created when the device only supported KeyMint
398 // v1).
399 //
400 // In this case, the keyblob with have the km_compat.rs wrapper around it to
401 // indicate that this was a software-emulated key.
402 //
403 // The inner keyblob should be in the format produced by the C++ reference
404 // implementation of KeyMint. Extract the key material and import it into the
405 // current KeyMint device.
406 log::info!(
407 "found apparent km_compat.rs(KeyMint) SW blob, attempt strip-and-import"
408 );
409 import_keyblob_and_perform_op(
410 km_dev,
411 inner_keyblob,
412 upgrade_params,
413 km_op,
414 new_blob_handler,
415 )
416 } else {
417 Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)).context(ks_err!("Calling km_op"))
418 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800419 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000420 r => r.map(|v| (v, None)).context(ks_err!("Calling km_op.")),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800421 }
422}
423
Janis Danisevskis04b02832020-10-26 09:21:40 -0700424/// Converts a set of key characteristics from the internal representation into a set of
425/// Authorizations as they are used to convey key characteristics to the clients of keystore.
426pub fn key_parameters_to_authorizations(
427 parameters: Vec<crate::key_parameter::KeyParameter>,
428) -> Vec<Authorization> {
429 parameters.into_iter().map(|p| p.into_authorization()).collect()
430}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000431
Charisee03e00842023-01-25 01:41:23 +0000432#[allow(clippy::unnecessary_cast)]
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000433/// This returns the current time (in milliseconds) as an instance of a monotonic clock,
434/// by invoking the system call since Rust does not support getting monotonic time instance
435/// as an integer.
436pub fn get_current_time_in_milliseconds() -> i64 {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000437 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
Andrew Walbrana47698a2023-07-21 17:23:56 +0100438 // SAFETY: The pointer is valid because it comes from a reference, and clock_gettime doesn't
439 // retain it beyond the call.
James Willcox80f7be12023-11-08 17:13:16 +0000440 unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut current_time) };
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000441 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000442}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800443
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800444/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
445/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
446/// (android.security.apc) spec.
447pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
448 match rc {
449 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
450 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
451 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
452 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
453 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
454 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
455 _ => ApcResponseCode::SYSTEM_ERROR,
456 }
457}
458
459/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
460/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
461/// module (keystore2_apc_compat).
462pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
463 ApcCompatUiOptions {
464 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
465 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
466 }
467}
468
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800469/// AID offset for uid space partitioning.
Joel Galenson81a50f22021-07-29 15:39:10 -0700470pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800471
Paul Crowley44c02da2021-04-08 17:04:43 +0000472/// AID of the keystore process itself, used for keys that
473/// keystore generates for its own use.
Joel Galenson81a50f22021-07-29 15:39:10 -0700474pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
Paul Crowley44c02da2021-04-08 17:04:43 +0000475
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800476/// Extracts the android user from the given uid.
477pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galenson81a50f22021-07-29 15:39:10 -0700478 rustutils::users::multiuser_get_user_id(uid)
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800479}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100480
Eran Messeri24f31972023-01-25 17:00:33 +0000481/// Merges and filters two lists of key descriptors. The first input list, legacy_descriptors,
482/// is assumed to not be sorted or filtered. As such, all key descriptors in that list whose
483/// alias is less than, or equal to, start_past_alias (if provided) will be removed.
484/// This list will then be merged with the second list, db_descriptors. The db_descriptors list
485/// is assumed to be sorted and filtered so the output list will be sorted prior to returning.
486/// The returned value is a list of KeyDescriptor objects whose alias is greater than
487/// start_past_alias, sorted and de-duplicated.
488fn merge_and_filter_key_entry_lists(
489 legacy_descriptors: &[KeyDescriptor],
490 db_descriptors: &[KeyDescriptor],
491 start_past_alias: Option<&str>,
492) -> Vec<KeyDescriptor> {
493 let mut result: Vec<KeyDescriptor> =
494 match start_past_alias {
495 Some(past_alias) => legacy_descriptors
496 .iter()
497 .filter(|kd| {
498 if let Some(alias) = &kd.alias {
499 alias.as_str() > past_alias
500 } else {
501 false
502 }
503 })
504 .cloned()
505 .collect(),
506 None => legacy_descriptors.to_vec(),
507 };
508
509 result.extend_from_slice(db_descriptors);
John Wu16db29e2022-01-13 15:21:43 -0800510 result.sort_unstable();
511 result.dedup();
Eran Messeri24f31972023-01-25 17:00:33 +0000512 result
513}
Eran Messeri6e1213f2023-01-10 14:38:31 +0000514
Eran Messeri24f31972023-01-25 17:00:33 +0000515fn estimate_safe_amount_to_return(
516 key_descriptors: &[KeyDescriptor],
517 response_size_limit: usize,
518) -> usize {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000519 let mut items_to_return = 0;
520 let mut returned_bytes: usize = 0;
Eran Messeri6e1213f2023-01-10 14:38:31 +0000521 // Estimate the transaction size to avoid returning more items than what
522 // could fit in a binder transaction.
Eran Messeri24f31972023-01-25 17:00:33 +0000523 for kd in key_descriptors.iter() {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000524 // 4 bytes for the Domain enum
525 // 8 bytes for the Namespace long.
526 returned_bytes += 4 + 8;
527 // Size of the alias string. Includes 4 bytes for length encoding.
528 if let Some(alias) = &kd.alias {
529 returned_bytes += 4 + alias.len();
530 }
531 // Size of the blob. Includes 4 bytes for length encoding.
532 if let Some(blob) = &kd.blob {
533 returned_bytes += 4 + blob.len();
534 }
535 // The binder transaction size limit is 1M. Empirical measurements show
536 // that the binder overhead is 60% (to be confirmed). So break after
537 // 350KB and return a partial list.
Eran Messeri24f31972023-01-25 17:00:33 +0000538 if returned_bytes > response_size_limit {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000539 log::warn!(
540 "Key descriptors list ({} items) may exceed binder \
541 size, returning {} items est {} bytes.",
Eran Messeri24f31972023-01-25 17:00:33 +0000542 key_descriptors.len(),
Eran Messeri6e1213f2023-01-10 14:38:31 +0000543 items_to_return,
544 returned_bytes
545 );
546 break;
547 }
548 items_to_return += 1;
549 }
Eran Messeri24f31972023-01-25 17:00:33 +0000550 items_to_return
551}
552
553/// List all key aliases for a given domain + namespace. whose alias is greater
554/// than start_past_alias (if provided).
555pub fn list_key_entries(
556 db: &mut KeystoreDB,
557 domain: Domain,
558 namespace: i64,
559 start_past_alias: Option<&str>,
560) -> Result<Vec<KeyDescriptor>> {
561 let legacy_key_descriptors: Vec<KeyDescriptor> = LEGACY_IMPORTER
562 .list_uid(domain, namespace)
563 .context(ks_err!("Trying to list legacy keys."))?;
564
565 // The results from the database will be sorted and unique
566 let db_key_descriptors: Vec<KeyDescriptor> = db
567 .list_past_alias(domain, namespace, KeyType::Client, start_past_alias)
568 .context(ks_err!("Trying to list keystore database past alias."))?;
569
570 let merged_key_entries = merge_and_filter_key_entry_lists(
571 &legacy_key_descriptors,
572 &db_key_descriptors,
573 start_past_alias,
574 );
575
576 const RESPONSE_SIZE_LIMIT: usize = 358400;
577 let safe_amount_to_return =
578 estimate_safe_amount_to_return(&merged_key_entries, RESPONSE_SIZE_LIMIT);
579 Ok(merged_key_entries[..safe_amount_to_return].to_vec())
580}
581
582/// Count all key aliases for a given domain + namespace.
583pub fn count_key_entries(db: &mut KeystoreDB, domain: Domain, namespace: i64) -> Result<i32> {
584 let legacy_keys = LEGACY_IMPORTER
585 .list_uid(domain, namespace)
586 .context(ks_err!("Trying to list legacy keys."))?;
587
588 let num_keys_in_db = db.count_keys(domain, namespace, KeyType::Client)?;
589
590 Ok((legacy_keys.len() + num_keys_in_db) as i32)
John Wu16db29e2022-01-13 15:21:43 -0800591}
592
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800593/// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
594pub trait AesGcm {
595 /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
596 /// and AES-GCM. The implementation provides the key material and selects
597 /// the implementation variant, e.g., AES128 or AES265.
598 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>;
599
600 /// Encrypts `data` and returns the ciphertext, the initialization vector `iv`
601 /// and AEAD tag `tag`. The implementation provides the key material and selects
602 /// the implementation variant, e.g., AES128 or AES265.
603 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>;
604}
605
606/// Marks an object as AES-GCM key.
607pub trait AesGcmKey {
608 /// Provides access to the raw key material.
609 fn key(&self) -> &[u8];
610}
611
612impl<T: AesGcmKey> AesGcm for T {
613 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000614 aes_gcm_decrypt(data, iv, tag, self.key()).context(ks_err!("Decryption failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800615 }
616
617 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000618 aes_gcm_encrypt(plaintext, self.key()).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800619 }
620}
621
Bram Bonné5d6c5102021-02-24 15:09:18 +0100622#[cfg(test)]
623mod tests {
624 use super::*;
625 use anyhow::Result;
626
627 #[test]
628 fn check_device_attestation_permissions_test() -> Result<()> {
629 check_device_attestation_permissions().or_else(|error| {
630 match error.root_cause().downcast_ref::<Error>() {
631 // Expected: the context for this test might not be allowed to attest device IDs.
632 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
633 // Other errors are unexpected
634 _ => Err(error),
635 }
636 })
637 }
Eran Messeri24f31972023-01-25 17:00:33 +0000638
639 fn create_key_descriptors_from_aliases(key_aliases: &[&str]) -> Vec<KeyDescriptor> {
640 key_aliases
641 .iter()
642 .map(|key_alias| KeyDescriptor {
643 domain: Domain::APP,
644 nspace: 0,
645 alias: Some(key_alias.to_string()),
646 blob: None,
647 })
648 .collect::<Vec<KeyDescriptor>>()
649 }
650
651 fn aliases_from_key_descriptors(key_descriptors: &[KeyDescriptor]) -> Vec<String> {
652 key_descriptors
653 .iter()
654 .map(
655 |kd| {
656 if let Some(alias) = &kd.alias {
657 String::from(alias)
658 } else {
659 String::from("")
660 }
661 },
662 )
663 .collect::<Vec<String>>()
664 }
665
666 #[test]
667 fn test_safe_amount_to_return() -> Result<()> {
668 let key_aliases = vec!["key1", "key2", "key3"];
669 let key_descriptors = create_key_descriptors_from_aliases(&key_aliases);
670
671 assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 20), 1);
672 assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 50), 2);
673 assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 100), 3);
674 Ok(())
675 }
676
677 #[test]
678 fn test_merge_and_sort_lists_without_filtering() -> Result<()> {
679 let legacy_key_aliases = vec!["key_c", "key_a", "key_b"];
680 let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases);
681 let db_key_aliases = vec!["key_a", "key_d"];
682 let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases);
683 let result =
684 merge_and_filter_key_entry_lists(&legacy_key_descriptors, &db_key_descriptors, None);
685 assert_eq!(aliases_from_key_descriptors(&result), vec!["key_a", "key_b", "key_c", "key_d"]);
686 Ok(())
687 }
688
689 #[test]
690 fn test_merge_and_sort_lists_with_filtering() -> Result<()> {
691 let legacy_key_aliases = vec!["key_f", "key_a", "key_e", "key_b"];
692 let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases);
693 let db_key_aliases = vec!["key_c", "key_g"];
694 let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases);
695 let result = merge_and_filter_key_entry_lists(
696 &legacy_key_descriptors,
697 &db_key_descriptors,
698 Some("key_b"),
699 );
700 assert_eq!(aliases_from_key_descriptors(&result), vec!["key_c", "key_e", "key_f", "key_g"]);
701 Ok(())
702 }
703
704 #[test]
705 fn test_merge_and_sort_lists_with_filtering_and_dups() -> Result<()> {
706 let legacy_key_aliases = vec!["key_f", "key_a", "key_e", "key_b"];
707 let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases);
708 let db_key_aliases = vec!["key_d", "key_e", "key_g"];
709 let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases);
710 let result = merge_and_filter_key_entry_lists(
711 &legacy_key_descriptors,
712 &db_key_descriptors,
713 Some("key_c"),
714 );
715 assert_eq!(aliases_from_key_descriptors(&result), vec!["key_d", "key_e", "key_f", "key_g"]);
716 Ok(())
717 }
Bram Bonné5d6c5102021-02-24 15:09:18 +0100718}