blob: 44811724306ecc4c6681a0bdaca084099f5ae1b7 [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,
John Wu16db29e2022-01-13 15:21:43 -080026};
Shawn Willden708744a2020-12-11 13:05:27 +000027use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080028 IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics,
29 KeyParameter::KeyParameter as KmKeyParameter, Tag::Tag,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070030};
Bram Bonné5d6c5102021-02-24 15:09:18 +010031use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080032use android_security_apc::aidl::android::security::apc::{
33 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
34 ResponseCode::ResponseCode as ApcResponseCode,
35};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070036use android_system_keystore2::aidl::android::system::keystore2::{
John Wu16db29e2022-01-13 15:21:43 -080037 Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070038};
John Wu16db29e2022-01-13 15:21:43 -080039use anyhow::{Context, Result};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070040use binder::{Strong, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080041use keystore2_apc_compat::{
42 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
43 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
44 APC_COMPAT_ERROR_SYSTEM_ERROR,
45};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080046use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec};
47use std::iter::IntoIterator;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070048
49/// This function uses its namesake in the permission module and in
50/// combination with with_calling_sid from the binder crate to check
51/// if the caller has the given keystore permission.
52pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
53 ThreadState::with_calling_sid(|calling_sid| {
54 permission::check_keystore_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000055 calling_sid
56 .ok_or_else(Error::sys)
57 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070058 perm,
59 )
60 })
61}
62
63/// This function uses its namesake in the permission module and in
64/// combination with with_calling_sid from the binder crate to check
65/// if the caller has the given grant permission.
66pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
67 ThreadState::with_calling_sid(|calling_sid| {
68 permission::check_grant_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000069 calling_sid
70 .ok_or_else(Error::sys)
71 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070072 access_vec,
73 key,
74 )
75 })
76}
77
78/// This function uses its namesake in the permission module and in
79/// combination with with_calling_sid from the binder crate to check
80/// if the caller has the given key permission.
81pub fn check_key_permission(
82 perm: KeyPerm,
83 key: &KeyDescriptor,
84 access_vector: &Option<KeyPermSet>,
85) -> anyhow::Result<()> {
86 ThreadState::with_calling_sid(|calling_sid| {
87 permission::check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -080088 ThreadState::get_calling_uid(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -070089 calling_sid
Janis Danisevskisa75e2082020-10-07 16:44:26 -070090 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000091 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070092 perm,
93 key,
94 access_vector,
95 )
96 })
97}
98
Bram Bonné5d6c5102021-02-24 15:09:18 +010099/// This function checks whether a given tag corresponds to the access of device identifiers.
100pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -0700101 matches!(
102 tag,
103 Tag::ATTESTATION_ID_IMEI
104 | Tag::ATTESTATION_ID_MEID
105 | Tag::ATTESTATION_ID_SERIAL
106 | Tag::DEVICE_UNIQUE_ATTESTATION
Eran Messeri637259c2022-10-31 12:23:36 +0000107 | Tag::ATTESTATION_ID_SECOND_IMEI
Janis Danisevskis83116e52021-04-06 13:36:58 -0700108 )
Bram Bonné5d6c5102021-02-24 15:09:18 +0100109}
110
111/// This function checks whether the calling app has the Android permissions needed to attest device
Seth Moore66d9e902022-03-16 17:20:31 -0700112/// identifiers. It throws an error if the permissions cannot be verified or if the caller doesn't
113/// have the right permissions. Otherwise it returns silently.
Bram Bonné5d6c5102021-02-24 15:09:18 +0100114pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
Seth Moore66d9e902022-03-16 17:20:31 -0700115 check_android_permission("android.permission.READ_PRIVILEGED_PHONE_STATE")
116}
117
118/// This function checks whether the calling app has the Android permissions needed to attest the
119/// device-unique identifier. It throws an error if the permissions cannot be verified or if the
120/// caller doesn't have the right permissions. Otherwise it returns silently.
121pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> {
122 check_android_permission("android.permission.REQUEST_UNIQUE_ID_ATTESTATION")
123}
124
125fn check_android_permission(permission: &str) -> anyhow::Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700126 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
Bram Bonné5d6c5102021-02-24 15:09:18 +0100127 binder::get_interface("permission")?;
128
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700129 let binder_result = {
130 let _wp = watchdog::watch_millis(
131 "In check_device_attestation_permissions: calling checkPermission.",
132 500,
133 );
134 permission_controller.checkPermission(
Seth Moore66d9e902022-03-16 17:20:31 -0700135 permission,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700136 ThreadState::get_calling_pid(),
137 ThreadState::get_calling_uid() as i32,
138 )
139 };
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000140 let has_permissions =
141 map_binder_status(binder_result).context(ks_err!("checkPermission failed"))?;
Bram Bonné5d6c5102021-02-24 15:09:18 +0100142 match has_permissions {
143 true => Ok(()),
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000144 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS))
145 .context(ks_err!("caller does not have the permission to attest device IDs")),
Bram Bonné5d6c5102021-02-24 15:09:18 +0100146 }
147}
148
Janis Danisevskis04b02832020-10-26 09:21:40 -0700149/// Converts a set of key characteristics as returned from KeyMint into the internal
150/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700151pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700152 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800153) -> Vec<KeyParameter> {
Janis Danisevskis04b02832020-10-26 09:21:40 -0700154 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700155 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700156 .flat_map(|aidl_key_char| {
157 let sec_level = aidl_key_char.securityLevel;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800158 aidl_key_char
159 .authorizations
160 .into_iter()
161 .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level))
Shawn Willdendbdac602021-01-12 22:35:16 -0700162 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700163 .collect()
164}
165
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800166/// This function can be used to upgrade key blobs on demand. The return value of
167/// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered,
168/// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called
169/// with the upgraded blob as argument. Then `km_op` is called a second time with the
170/// upgraded blob as argument. On success a tuple of the `km_op`s result and the
171/// optional upgraded blob is returned.
172pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>(
173 km_dev: &dyn IKeyMintDevice,
174 key_blob: &[u8],
175 upgrade_params: &[KmKeyParameter],
176 km_op: KmOp,
177 new_blob_handler: NewBlobHandler,
178) -> Result<(T, Option<Vec<u8>>)>
179where
180 KmOp: Fn(&[u8]) -> Result<T, Error>,
181 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
182{
183 match km_op(key_blob) {
184 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
185 let upgraded_blob = {
186 let _wp = watchdog::watch_millis(
187 "In utils::upgrade_keyblob_if_required_with: calling upgradeKey.",
188 500,
189 );
190 map_km_error(km_dev.upgradeKey(key_blob, upgrade_params))
191 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000192 .context(ks_err!("Upgrade failed."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800193
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000194 new_blob_handler(&upgraded_blob).context(ks_err!("calling new_blob_handler."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800195
196 km_op(&upgraded_blob)
197 .map(|v| (v, Some(upgraded_blob)))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000198 .context(ks_err!("Calling km_op after upgrade."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800199 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000200 r => r.map(|v| (v, None)).context(ks_err!("Calling km_op.")),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800201 }
202}
203
Janis Danisevskis04b02832020-10-26 09:21:40 -0700204/// Converts a set of key characteristics from the internal representation into a set of
205/// Authorizations as they are used to convey key characteristics to the clients of keystore.
206pub fn key_parameters_to_authorizations(
207 parameters: Vec<crate::key_parameter::KeyParameter>,
208) -> Vec<Authorization> {
209 parameters.into_iter().map(|p| p.into_authorization()).collect()
210}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000211
Charisee03e00842023-01-25 01:41:23 +0000212#[allow(clippy::unnecessary_cast)]
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000213/// This returns the current time (in milliseconds) as an instance of a monotonic clock,
214/// by invoking the system call since Rust does not support getting monotonic time instance
215/// as an integer.
216pub fn get_current_time_in_milliseconds() -> i64 {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000217 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
218 // Following unsafe block includes one system call to get monotonic time.
219 // Therefore, it is not considered harmful.
220 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000221 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000222}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800223
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800224/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
225/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
226/// (android.security.apc) spec.
227pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
228 match rc {
229 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
230 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
231 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
232 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
233 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
234 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
235 _ => ApcResponseCode::SYSTEM_ERROR,
236 }
237}
238
239/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
240/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
241/// module (keystore2_apc_compat).
242pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
243 ApcCompatUiOptions {
244 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
245 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
246 }
247}
248
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800249/// AID offset for uid space partitioning.
Joel Galenson81a50f22021-07-29 15:39:10 -0700250pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800251
Paul Crowley44c02da2021-04-08 17:04:43 +0000252/// AID of the keystore process itself, used for keys that
253/// keystore generates for its own use.
Joel Galenson81a50f22021-07-29 15:39:10 -0700254pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
Paul Crowley44c02da2021-04-08 17:04:43 +0000255
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800256/// Extracts the android user from the given uid.
257pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galenson81a50f22021-07-29 15:39:10 -0700258 rustutils::users::multiuser_get_user_id(uid)
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800259}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100260
John Wu16db29e2022-01-13 15:21:43 -0800261/// List all key aliases for a given domain + namespace.
262pub fn list_key_entries(
263 db: &mut KeystoreDB,
264 domain: Domain,
265 namespace: i64,
266) -> Result<Vec<KeyDescriptor>> {
267 let mut result = Vec::new();
268 result.append(
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800269 &mut LEGACY_IMPORTER
John Wu16db29e2022-01-13 15:21:43 -0800270 .list_uid(domain, namespace)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000271 .context(ks_err!("Trying to list legacy keys."))?,
John Wu16db29e2022-01-13 15:21:43 -0800272 );
273 result.append(
274 &mut db
275 .list(domain, namespace, KeyType::Client)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000276 .context(ks_err!("Trying to list keystore database."))?,
John Wu16db29e2022-01-13 15:21:43 -0800277 );
278 result.sort_unstable();
279 result.dedup();
280 Ok(result)
281}
282
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700283/// This module provides helpers for simplified use of the watchdog module.
284#[cfg(feature = "watchdog")]
285pub mod watchdog {
286 pub use crate::watchdog::WatchPoint;
287 use crate::watchdog::Watchdog;
288 use lazy_static::lazy_static;
289 use std::sync::Arc;
290 use std::time::Duration;
291
292 lazy_static! {
293 /// A Watchdog thread, that can be used to create watch points.
294 static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
295 }
296
297 /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
298 pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
299 Watchdog::watch(&WD, id, Duration::from_millis(millis))
300 }
301
302 /// Like `watch_millis` but with a callback that is called every time a report
303 /// is printed about this watch point.
304 pub fn watch_millis_with(
305 id: &'static str,
306 millis: u64,
307 callback: impl Fn() -> String + Send + 'static,
308 ) -> Option<WatchPoint> {
309 Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
310 }
311}
312
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800313/// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
314pub trait AesGcm {
315 /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
316 /// and AES-GCM. The implementation provides the key material and selects
317 /// the implementation variant, e.g., AES128 or AES265.
318 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>;
319
320 /// Encrypts `data` and returns the ciphertext, the initialization vector `iv`
321 /// and AEAD tag `tag`. The implementation provides the key material and selects
322 /// the implementation variant, e.g., AES128 or AES265.
323 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>;
324}
325
326/// Marks an object as AES-GCM key.
327pub trait AesGcmKey {
328 /// Provides access to the raw key material.
329 fn key(&self) -> &[u8];
330}
331
332impl<T: AesGcmKey> AesGcm for T {
333 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000334 aes_gcm_decrypt(data, iv, tag, self.key()).context(ks_err!("Decryption failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800335 }
336
337 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000338 aes_gcm_encrypt(plaintext, self.key()).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800339 }
340}
341
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700342/// This module provides empty/noop implementations of the watch dog utility functions.
343#[cfg(not(feature = "watchdog"))]
344pub mod watchdog {
345 /// Noop watch point.
346 pub struct WatchPoint();
347 /// Sets a Noop watch point.
348 fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
349 None
350 }
351
352 pub fn watch_millis_with(
353 _: &'static str,
354 _: u64,
355 _: impl Fn() -> String + Send + 'static,
356 ) -> Option<WatchPoint> {
357 None
358 }
359}
360
Bram Bonné5d6c5102021-02-24 15:09:18 +0100361#[cfg(test)]
362mod tests {
363 use super::*;
364 use anyhow::Result;
365
366 #[test]
367 fn check_device_attestation_permissions_test() -> Result<()> {
368 check_device_attestation_permissions().or_else(|error| {
369 match error.root_cause().downcast_ref::<Error>() {
370 // Expected: the context for this test might not be allowed to attest device IDs.
371 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
372 // Other errors are unexpected
373 _ => Err(error),
374 }
375 })
376 }
377}