blob: 80aa7c388adf1c3f7b37a3d90e9d561cd8e6faf2 [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};
John Wu16db29e2022-01-13 15:21:43 -080023use crate::{
24 database::{KeyType, KeystoreDB},
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080025 globals::LEGACY_IMPORTER,
David Drysdale5accbaa2023-04-12 18:47:10 +010026 km_compat,
27 raw_device::KeyMintDevice,
John Wu16db29e2022-01-13 15:21:43 -080028};
Shawn Willden708744a2020-12-11 13:05:27 +000029use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080030 IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics,
31 KeyParameter::KeyParameter as KmKeyParameter, Tag::Tag,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070032};
Bram Bonné5d6c5102021-02-24 15:09:18 +010033use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080034use android_security_apc::aidl::android::security::apc::{
35 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
36 ResponseCode::ResponseCode as ApcResponseCode,
37};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070038use android_system_keystore2::aidl::android::system::keystore2::{
John Wu16db29e2022-01-13 15:21:43 -080039 Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070040};
John Wu16db29e2022-01-13 15:21:43 -080041use anyhow::{Context, Result};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070042use binder::{Strong, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080043use keystore2_apc_compat::{
44 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
45 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
46 APC_COMPAT_ERROR_SYSTEM_ERROR,
47};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080048use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec};
49use std::iter::IntoIterator;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070050
51/// This function uses its namesake in the permission module and in
52/// combination with with_calling_sid from the binder crate to check
53/// if the caller has the given keystore permission.
54pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
55 ThreadState::with_calling_sid(|calling_sid| {
56 permission::check_keystore_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000057 calling_sid
58 .ok_or_else(Error::sys)
59 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070060 perm,
61 )
62 })
63}
64
65/// This function uses its namesake in the permission module and in
66/// combination with with_calling_sid from the binder crate to check
67/// if the caller has the given grant permission.
68pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
69 ThreadState::with_calling_sid(|calling_sid| {
70 permission::check_grant_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000071 calling_sid
72 .ok_or_else(Error::sys)
73 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070074 access_vec,
75 key,
76 )
77 })
78}
79
80/// This function uses its namesake in the permission module and in
81/// combination with with_calling_sid from the binder crate to check
82/// if the caller has the given key permission.
83pub fn check_key_permission(
84 perm: KeyPerm,
85 key: &KeyDescriptor,
86 access_vector: &Option<KeyPermSet>,
87) -> anyhow::Result<()> {
88 ThreadState::with_calling_sid(|calling_sid| {
89 permission::check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -080090 ThreadState::get_calling_uid(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -070091 calling_sid
Janis Danisevskisa75e2082020-10-07 16:44:26 -070092 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000093 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070094 perm,
95 key,
96 access_vector,
97 )
98 })
99}
100
Bram Bonné5d6c5102021-02-24 15:09:18 +0100101/// This function checks whether a given tag corresponds to the access of device identifiers.
102pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -0700103 matches!(
104 tag,
105 Tag::ATTESTATION_ID_IMEI
106 | Tag::ATTESTATION_ID_MEID
107 | Tag::ATTESTATION_ID_SERIAL
108 | Tag::DEVICE_UNIQUE_ATTESTATION
Eran Messeri637259c2022-10-31 12:23:36 +0000109 | Tag::ATTESTATION_ID_SECOND_IMEI
Janis Danisevskis83116e52021-04-06 13:36:58 -0700110 )
Bram Bonné5d6c5102021-02-24 15:09:18 +0100111}
112
113/// This function checks whether the calling app has the Android permissions needed to attest device
Seth Moore66d9e902022-03-16 17:20:31 -0700114/// identifiers. It throws an error if the permissions cannot be verified or if the caller doesn't
115/// have the right permissions. Otherwise it returns silently.
Bram Bonné5d6c5102021-02-24 15:09:18 +0100116pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
Seth Moore66d9e902022-03-16 17:20:31 -0700117 check_android_permission("android.permission.READ_PRIVILEGED_PHONE_STATE")
118}
119
120/// This function checks whether the calling app has the Android permissions needed to attest the
121/// device-unique identifier. It throws an error if the permissions cannot be verified or if the
122/// caller doesn't have the right permissions. Otherwise it returns silently.
123pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> {
124 check_android_permission("android.permission.REQUEST_UNIQUE_ID_ATTESTATION")
125}
126
127fn check_android_permission(permission: &str) -> anyhow::Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700128 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
Bram Bonné5d6c5102021-02-24 15:09:18 +0100129 binder::get_interface("permission")?;
130
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700131 let binder_result = {
132 let _wp = watchdog::watch_millis(
133 "In check_device_attestation_permissions: calling checkPermission.",
134 500,
135 );
136 permission_controller.checkPermission(
Seth Moore66d9e902022-03-16 17:20:31 -0700137 permission,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700138 ThreadState::get_calling_pid(),
139 ThreadState::get_calling_uid() as i32,
140 )
141 };
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000142 let has_permissions =
143 map_binder_status(binder_result).context(ks_err!("checkPermission failed"))?;
Bram Bonné5d6c5102021-02-24 15:09:18 +0100144 match has_permissions {
145 true => Ok(()),
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000146 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS))
147 .context(ks_err!("caller does not have the permission to attest device IDs")),
Bram Bonné5d6c5102021-02-24 15:09:18 +0100148 }
149}
150
Janis Danisevskis04b02832020-10-26 09:21:40 -0700151/// Converts a set of key characteristics as returned from KeyMint into the internal
152/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700153pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700154 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800155) -> Vec<KeyParameter> {
Janis Danisevskis04b02832020-10-26 09:21:40 -0700156 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700157 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700158 .flat_map(|aidl_key_char| {
159 let sec_level = aidl_key_char.securityLevel;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800160 aidl_key_char
161 .authorizations
162 .into_iter()
163 .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level))
Shawn Willdendbdac602021-01-12 22:35:16 -0700164 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700165 .collect()
166}
167
David Drysdale5accbaa2023-04-12 18:47:10 +0100168/// Upgrade a keyblob then invoke both the `new_blob_handler` and the `km_op` closures. On success
169/// a tuple of the `km_op`s result and the optional upgraded blob is returned.
170fn upgrade_keyblob_and_perform_op<T, KmOp, NewBlobHandler>(
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800171 km_dev: &dyn IKeyMintDevice,
172 key_blob: &[u8],
173 upgrade_params: &[KmKeyParameter],
174 km_op: KmOp,
175 new_blob_handler: NewBlobHandler,
176) -> Result<(T, Option<Vec<u8>>)>
177where
178 KmOp: Fn(&[u8]) -> Result<T, Error>,
179 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
180{
David Drysdale5accbaa2023-04-12 18:47:10 +0100181 let upgraded_blob = {
182 let _wp = watchdog::watch_millis(
183 "In utils::upgrade_keyblob_and_perform_op: calling upgradeKey.",
184 500,
185 );
186 map_km_error(km_dev.upgradeKey(key_blob, upgrade_params))
187 }
188 .context(ks_err!("Upgrade failed."))?;
189
190 new_blob_handler(&upgraded_blob).context(ks_err!("calling new_blob_handler."))?;
191
192 km_op(&upgraded_blob)
193 .map(|v| (v, Some(upgraded_blob)))
194 .context(ks_err!("Calling km_op after upgrade."))
195}
196
197/// This function can be used to upgrade key blobs on demand. The return value of
198/// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered,
199/// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called
200/// with the upgraded blob as argument. Then `km_op` is called a second time with the
201/// upgraded blob as argument. On success a tuple of the `km_op`s result and the
202/// optional upgraded blob is returned.
203pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>(
204 km_dev: &dyn IKeyMintDevice,
205 km_dev_version: i32,
206 key_blob: &[u8],
207 upgrade_params: &[KmKeyParameter],
208 km_op: KmOp,
209 new_blob_handler: NewBlobHandler,
210) -> Result<(T, Option<Vec<u8>>)>
211where
212 KmOp: Fn(&[u8]) -> Result<T, Error>,
213 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
214{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800215 match km_op(key_blob) {
David Drysdale5accbaa2023-04-12 18:47:10 +0100216 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => upgrade_keyblob_and_perform_op(
217 km_dev,
218 key_blob,
219 upgrade_params,
220 km_op,
221 new_blob_handler,
222 ),
223 // Some devices have been known to upgrade their Keymaster device to be a KeyMint
224 // device with a new release of Android. If this is the case, then any pre-upgrade
225 // keyblobs will have the km_compat prefix attached to them.
226 //
227 // This prefix gets stripped by the km_compat layer when used pre-upgrade, but after
228 // the upgrade the keyblob will be passed as-is to the KeyMint device, which probably
229 // won't expect to see the km_compat prefix.
230 //
231 // So if a keyblob:
232 // a) gets rejected with INVALID_KEY_BLOB
233 // b) when sent to a KeyMint (not km_compat) device
234 // c) and has the km_compat magic prefix
235 // d) and was not a software-emulated key pre-upgrade
236 // then strip the prefix and attempt a key upgrade.
237 Err(Error::Km(ErrorCode::INVALID_KEY_BLOB))
238 if km_dev_version >= KeyMintDevice::KEY_MINT_V1
239 && key_blob.starts_with(km_compat::KEYMASTER_BLOB_HW_PREFIX) =>
240 {
241 log::info!("found apparent km_compat(Keymaster) blob, attempt strip-and-upgrade");
242 let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_HW_PREFIX.len()..];
243 upgrade_keyblob_and_perform_op(
244 km_dev,
245 inner_keyblob,
246 upgrade_params,
247 km_op,
248 new_blob_handler,
249 )
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800250 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000251 r => r.map(|v| (v, None)).context(ks_err!("Calling km_op.")),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800252 }
253}
254
Janis Danisevskis04b02832020-10-26 09:21:40 -0700255/// Converts a set of key characteristics from the internal representation into a set of
256/// Authorizations as they are used to convey key characteristics to the clients of keystore.
257pub fn key_parameters_to_authorizations(
258 parameters: Vec<crate::key_parameter::KeyParameter>,
259) -> Vec<Authorization> {
260 parameters.into_iter().map(|p| p.into_authorization()).collect()
261}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000262
Charisee03e00842023-01-25 01:41:23 +0000263#[allow(clippy::unnecessary_cast)]
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000264/// This returns the current time (in milliseconds) as an instance of a monotonic clock,
265/// by invoking the system call since Rust does not support getting monotonic time instance
266/// as an integer.
267pub fn get_current_time_in_milliseconds() -> i64 {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000268 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
Andrew Walbrana47698a2023-07-21 17:23:56 +0100269 // SAFETY: The pointer is valid because it comes from a reference, and clock_gettime doesn't
270 // retain it beyond the call.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000271 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000272 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000273}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800274
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800275/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
276/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
277/// (android.security.apc) spec.
278pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
279 match rc {
280 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
281 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
282 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
283 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
284 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
285 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
286 _ => ApcResponseCode::SYSTEM_ERROR,
287 }
288}
289
290/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
291/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
292/// module (keystore2_apc_compat).
293pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
294 ApcCompatUiOptions {
295 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
296 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
297 }
298}
299
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800300/// AID offset for uid space partitioning.
Joel Galenson81a50f22021-07-29 15:39:10 -0700301pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800302
Paul Crowley44c02da2021-04-08 17:04:43 +0000303/// AID of the keystore process itself, used for keys that
304/// keystore generates for its own use.
Joel Galenson81a50f22021-07-29 15:39:10 -0700305pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
Paul Crowley44c02da2021-04-08 17:04:43 +0000306
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800307/// Extracts the android user from the given uid.
308pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galenson81a50f22021-07-29 15:39:10 -0700309 rustutils::users::multiuser_get_user_id(uid)
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800310}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100311
Eran Messeri24f31972023-01-25 17:00:33 +0000312/// Merges and filters two lists of key descriptors. The first input list, legacy_descriptors,
313/// is assumed to not be sorted or filtered. As such, all key descriptors in that list whose
314/// alias is less than, or equal to, start_past_alias (if provided) will be removed.
315/// This list will then be merged with the second list, db_descriptors. The db_descriptors list
316/// is assumed to be sorted and filtered so the output list will be sorted prior to returning.
317/// The returned value is a list of KeyDescriptor objects whose alias is greater than
318/// start_past_alias, sorted and de-duplicated.
319fn merge_and_filter_key_entry_lists(
320 legacy_descriptors: &[KeyDescriptor],
321 db_descriptors: &[KeyDescriptor],
322 start_past_alias: Option<&str>,
323) -> Vec<KeyDescriptor> {
324 let mut result: Vec<KeyDescriptor> =
325 match start_past_alias {
326 Some(past_alias) => legacy_descriptors
327 .iter()
328 .filter(|kd| {
329 if let Some(alias) = &kd.alias {
330 alias.as_str() > past_alias
331 } else {
332 false
333 }
334 })
335 .cloned()
336 .collect(),
337 None => legacy_descriptors.to_vec(),
338 };
339
340 result.extend_from_slice(db_descriptors);
John Wu16db29e2022-01-13 15:21:43 -0800341 result.sort_unstable();
342 result.dedup();
Eran Messeri24f31972023-01-25 17:00:33 +0000343 result
344}
Eran Messeri6e1213f2023-01-10 14:38:31 +0000345
Eran Messeri24f31972023-01-25 17:00:33 +0000346fn estimate_safe_amount_to_return(
347 key_descriptors: &[KeyDescriptor],
348 response_size_limit: usize,
349) -> usize {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000350 let mut items_to_return = 0;
351 let mut returned_bytes: usize = 0;
Eran Messeri6e1213f2023-01-10 14:38:31 +0000352 // Estimate the transaction size to avoid returning more items than what
353 // could fit in a binder transaction.
Eran Messeri24f31972023-01-25 17:00:33 +0000354 for kd in key_descriptors.iter() {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000355 // 4 bytes for the Domain enum
356 // 8 bytes for the Namespace long.
357 returned_bytes += 4 + 8;
358 // Size of the alias string. Includes 4 bytes for length encoding.
359 if let Some(alias) = &kd.alias {
360 returned_bytes += 4 + alias.len();
361 }
362 // Size of the blob. Includes 4 bytes for length encoding.
363 if let Some(blob) = &kd.blob {
364 returned_bytes += 4 + blob.len();
365 }
366 // The binder transaction size limit is 1M. Empirical measurements show
367 // that the binder overhead is 60% (to be confirmed). So break after
368 // 350KB and return a partial list.
Eran Messeri24f31972023-01-25 17:00:33 +0000369 if returned_bytes > response_size_limit {
Eran Messeri6e1213f2023-01-10 14:38:31 +0000370 log::warn!(
371 "Key descriptors list ({} items) may exceed binder \
372 size, returning {} items est {} bytes.",
Eran Messeri24f31972023-01-25 17:00:33 +0000373 key_descriptors.len(),
Eran Messeri6e1213f2023-01-10 14:38:31 +0000374 items_to_return,
375 returned_bytes
376 );
377 break;
378 }
379 items_to_return += 1;
380 }
Eran Messeri24f31972023-01-25 17:00:33 +0000381 items_to_return
382}
383
384/// List all key aliases for a given domain + namespace. whose alias is greater
385/// than start_past_alias (if provided).
386pub fn list_key_entries(
387 db: &mut KeystoreDB,
388 domain: Domain,
389 namespace: i64,
390 start_past_alias: Option<&str>,
391) -> Result<Vec<KeyDescriptor>> {
392 let legacy_key_descriptors: Vec<KeyDescriptor> = LEGACY_IMPORTER
393 .list_uid(domain, namespace)
394 .context(ks_err!("Trying to list legacy keys."))?;
395
396 // The results from the database will be sorted and unique
397 let db_key_descriptors: Vec<KeyDescriptor> = db
398 .list_past_alias(domain, namespace, KeyType::Client, start_past_alias)
399 .context(ks_err!("Trying to list keystore database past alias."))?;
400
401 let merged_key_entries = merge_and_filter_key_entry_lists(
402 &legacy_key_descriptors,
403 &db_key_descriptors,
404 start_past_alias,
405 );
406
407 const RESPONSE_SIZE_LIMIT: usize = 358400;
408 let safe_amount_to_return =
409 estimate_safe_amount_to_return(&merged_key_entries, RESPONSE_SIZE_LIMIT);
410 Ok(merged_key_entries[..safe_amount_to_return].to_vec())
411}
412
413/// Count all key aliases for a given domain + namespace.
414pub fn count_key_entries(db: &mut KeystoreDB, domain: Domain, namespace: i64) -> Result<i32> {
415 let legacy_keys = LEGACY_IMPORTER
416 .list_uid(domain, namespace)
417 .context(ks_err!("Trying to list legacy keys."))?;
418
419 let num_keys_in_db = db.count_keys(domain, namespace, KeyType::Client)?;
420
421 Ok((legacy_keys.len() + num_keys_in_db) as i32)
John Wu16db29e2022-01-13 15:21:43 -0800422}
423
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700424/// This module provides helpers for simplified use of the watchdog module.
425#[cfg(feature = "watchdog")]
426pub mod watchdog {
427 pub use crate::watchdog::WatchPoint;
428 use crate::watchdog::Watchdog;
429 use lazy_static::lazy_static;
430 use std::sync::Arc;
431 use std::time::Duration;
432
433 lazy_static! {
434 /// A Watchdog thread, that can be used to create watch points.
435 static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
436 }
437
438 /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
439 pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
440 Watchdog::watch(&WD, id, Duration::from_millis(millis))
441 }
442
443 /// Like `watch_millis` but with a callback that is called every time a report
444 /// is printed about this watch point.
445 pub fn watch_millis_with(
446 id: &'static str,
447 millis: u64,
448 callback: impl Fn() -> String + Send + 'static,
449 ) -> Option<WatchPoint> {
450 Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
451 }
452}
453
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800454/// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
455pub trait AesGcm {
456 /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
457 /// and AES-GCM. The implementation provides the key material and selects
458 /// the implementation variant, e.g., AES128 or AES265.
459 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>;
460
461 /// Encrypts `data` and returns the ciphertext, the initialization vector `iv`
462 /// and AEAD tag `tag`. The implementation provides the key material and selects
463 /// the implementation variant, e.g., AES128 or AES265.
464 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>;
465}
466
467/// Marks an object as AES-GCM key.
468pub trait AesGcmKey {
469 /// Provides access to the raw key material.
470 fn key(&self) -> &[u8];
471}
472
473impl<T: AesGcmKey> AesGcm for T {
474 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000475 aes_gcm_decrypt(data, iv, tag, self.key()).context(ks_err!("Decryption failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800476 }
477
478 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000479 aes_gcm_encrypt(plaintext, self.key()).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800480 }
481}
482
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700483/// This module provides empty/noop implementations of the watch dog utility functions.
484#[cfg(not(feature = "watchdog"))]
485pub mod watchdog {
486 /// Noop watch point.
487 pub struct WatchPoint();
488 /// Sets a Noop watch point.
489 fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
490 None
491 }
492
493 pub fn watch_millis_with(
494 _: &'static str,
495 _: u64,
496 _: impl Fn() -> String + Send + 'static,
497 ) -> Option<WatchPoint> {
498 None
499 }
500}
501
Bram Bonné5d6c5102021-02-24 15:09:18 +0100502#[cfg(test)]
503mod tests {
504 use super::*;
505 use anyhow::Result;
506
507 #[test]
508 fn check_device_attestation_permissions_test() -> Result<()> {
509 check_device_attestation_permissions().or_else(|error| {
510 match error.root_cause().downcast_ref::<Error>() {
511 // Expected: the context for this test might not be allowed to attest device IDs.
512 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
513 // Other errors are unexpected
514 _ => Err(error),
515 }
516 })
517 }
Eran Messeri24f31972023-01-25 17:00:33 +0000518
519 fn create_key_descriptors_from_aliases(key_aliases: &[&str]) -> Vec<KeyDescriptor> {
520 key_aliases
521 .iter()
522 .map(|key_alias| KeyDescriptor {
523 domain: Domain::APP,
524 nspace: 0,
525 alias: Some(key_alias.to_string()),
526 blob: None,
527 })
528 .collect::<Vec<KeyDescriptor>>()
529 }
530
531 fn aliases_from_key_descriptors(key_descriptors: &[KeyDescriptor]) -> Vec<String> {
532 key_descriptors
533 .iter()
534 .map(
535 |kd| {
536 if let Some(alias) = &kd.alias {
537 String::from(alias)
538 } else {
539 String::from("")
540 }
541 },
542 )
543 .collect::<Vec<String>>()
544 }
545
546 #[test]
547 fn test_safe_amount_to_return() -> Result<()> {
548 let key_aliases = vec!["key1", "key2", "key3"];
549 let key_descriptors = create_key_descriptors_from_aliases(&key_aliases);
550
551 assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 20), 1);
552 assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 50), 2);
553 assert_eq!(estimate_safe_amount_to_return(&key_descriptors, 100), 3);
554 Ok(())
555 }
556
557 #[test]
558 fn test_merge_and_sort_lists_without_filtering() -> Result<()> {
559 let legacy_key_aliases = vec!["key_c", "key_a", "key_b"];
560 let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases);
561 let db_key_aliases = vec!["key_a", "key_d"];
562 let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases);
563 let result =
564 merge_and_filter_key_entry_lists(&legacy_key_descriptors, &db_key_descriptors, None);
565 assert_eq!(aliases_from_key_descriptors(&result), vec!["key_a", "key_b", "key_c", "key_d"]);
566 Ok(())
567 }
568
569 #[test]
570 fn test_merge_and_sort_lists_with_filtering() -> Result<()> {
571 let legacy_key_aliases = vec!["key_f", "key_a", "key_e", "key_b"];
572 let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases);
573 let db_key_aliases = vec!["key_c", "key_g"];
574 let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases);
575 let result = merge_and_filter_key_entry_lists(
576 &legacy_key_descriptors,
577 &db_key_descriptors,
578 Some("key_b"),
579 );
580 assert_eq!(aliases_from_key_descriptors(&result), vec!["key_c", "key_e", "key_f", "key_g"]);
581 Ok(())
582 }
583
584 #[test]
585 fn test_merge_and_sort_lists_with_filtering_and_dups() -> Result<()> {
586 let legacy_key_aliases = vec!["key_f", "key_a", "key_e", "key_b"];
587 let legacy_key_descriptors = create_key_descriptors_from_aliases(&legacy_key_aliases);
588 let db_key_aliases = vec!["key_d", "key_e", "key_g"];
589 let db_key_descriptors = create_key_descriptors_from_aliases(&db_key_aliases);
590 let result = merge_and_filter_key_entry_lists(
591 &legacy_key_descriptors,
592 &db_key_descriptors,
593 Some("key_c"),
594 );
595 assert_eq!(aliases_from_key_descriptors(&result), vec!["key_d", "key_e", "key_f", "key_g"]);
596 Ok(())
597 }
Bram Bonné5d6c5102021-02-24 15:09:18 +0100598}