blob: a312c4b8ae4fc2c42404eb6603e25e20022261f6 [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;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070020use crate::permission;
21use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
John Wu16db29e2022-01-13 15:21:43 -080022use crate::{
23 database::{KeyType, KeystoreDB},
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080024 globals::LEGACY_IMPORTER,
John Wu16db29e2022-01-13 15:21:43 -080025};
Shawn Willden708744a2020-12-11 13:05:27 +000026use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080027 IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics,
28 KeyParameter::KeyParameter as KmKeyParameter, Tag::Tag,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070029};
Bram Bonné5d6c5102021-02-24 15:09:18 +010030use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080031use android_security_apc::aidl::android::security::apc::{
32 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
33 ResponseCode::ResponseCode as ApcResponseCode,
34};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070035use android_system_keystore2::aidl::android::system::keystore2::{
John Wu16db29e2022-01-13 15:21:43 -080036 Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070037};
John Wu16db29e2022-01-13 15:21:43 -080038use anyhow::{Context, Result};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070039use binder::{Strong, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080040use keystore2_apc_compat::{
41 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
42 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
43 APC_COMPAT_ERROR_SYSTEM_ERROR,
44};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080045use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec};
46use std::iter::IntoIterator;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070047
48/// This function uses its namesake in the permission module and in
49/// combination with with_calling_sid from the binder crate to check
50/// if the caller has the given keystore permission.
51pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
52 ThreadState::with_calling_sid(|calling_sid| {
53 permission::check_keystore_permission(
Chris Wailesd5aaaef2021-07-27 16:04:33 -070054 calling_sid.ok_or_else(Error::sys).context(
Janis Danisevskisa75e2082020-10-07 16:44:26 -070055 "In check_keystore_permission: Cannot check permission without calling_sid.",
56 )?,
57 perm,
58 )
59 })
60}
61
62/// This function uses its namesake in the permission module and in
63/// combination with with_calling_sid from the binder crate to check
64/// if the caller has the given grant permission.
65pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
66 ThreadState::with_calling_sid(|calling_sid| {
67 permission::check_grant_permission(
Chris Wailesd5aaaef2021-07-27 16:04:33 -070068 calling_sid.ok_or_else(Error::sys).context(
Janis Danisevskisa75e2082020-10-07 16:44:26 -070069 "In check_grant_permission: Cannot check permission without calling_sid.",
70 )?,
71 access_vec,
72 key,
73 )
74 })
75}
76
77/// This function uses its namesake in the permission module and in
78/// combination with with_calling_sid from the binder crate to check
79/// if the caller has the given key permission.
80pub fn check_key_permission(
81 perm: KeyPerm,
82 key: &KeyDescriptor,
83 access_vector: &Option<KeyPermSet>,
84) -> anyhow::Result<()> {
85 ThreadState::with_calling_sid(|calling_sid| {
86 permission::check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -080087 ThreadState::get_calling_uid(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -070088 calling_sid
Janis Danisevskisa75e2082020-10-07 16:44:26 -070089 .ok_or_else(Error::sys)
90 .context("In check_key_permission: Cannot check permission without calling_sid.")?,
91 perm,
92 key,
93 access_vector,
94 )
95 })
96}
97
Bram Bonné5d6c5102021-02-24 15:09:18 +010098/// This function checks whether a given tag corresponds to the access of device identifiers.
99pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -0700100 matches!(
101 tag,
102 Tag::ATTESTATION_ID_IMEI
103 | Tag::ATTESTATION_ID_MEID
104 | Tag::ATTESTATION_ID_SERIAL
105 | Tag::DEVICE_UNIQUE_ATTESTATION
106 )
Bram Bonné5d6c5102021-02-24 15:09:18 +0100107}
108
109/// This function checks whether the calling app has the Android permissions needed to attest device
110/// identifiers. It throws an error if the permissions cannot be verified, or if the caller doesn't
111/// have the right permissions, and returns silently otherwise.
112pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700113 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
Bram Bonné5d6c5102021-02-24 15:09:18 +0100114 binder::get_interface("permission")?;
115
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700116 let binder_result = {
117 let _wp = watchdog::watch_millis(
118 "In check_device_attestation_permissions: calling checkPermission.",
119 500,
120 );
121 permission_controller.checkPermission(
122 "android.permission.READ_PRIVILEGED_PHONE_STATE",
123 ThreadState::get_calling_pid(),
124 ThreadState::get_calling_uid() as i32,
125 )
126 };
Bram Bonné5d6c5102021-02-24 15:09:18 +0100127 let has_permissions = map_binder_status(binder_result)
128 .context("In check_device_attestation_permissions: checkPermission failed")?;
129 match has_permissions {
130 true => Ok(()),
131 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)).context(concat!(
132 "In check_device_attestation_permissions: ",
133 "caller does not have the permission to attest device IDs"
134 )),
135 }
136}
137
Janis Danisevskis04b02832020-10-26 09:21:40 -0700138/// Converts a set of key characteristics as returned from KeyMint into the internal
139/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700140pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700141 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800142) -> Vec<KeyParameter> {
Janis Danisevskis04b02832020-10-26 09:21:40 -0700143 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700144 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700145 .flat_map(|aidl_key_char| {
146 let sec_level = aidl_key_char.securityLevel;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800147 aidl_key_char
148 .authorizations
149 .into_iter()
150 .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level))
Shawn Willdendbdac602021-01-12 22:35:16 -0700151 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700152 .collect()
153}
154
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800155/// This function can be used to upgrade key blobs on demand. The return value of
156/// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered,
157/// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called
158/// with the upgraded blob as argument. Then `km_op` is called a second time with the
159/// upgraded blob as argument. On success a tuple of the `km_op`s result and the
160/// optional upgraded blob is returned.
161pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>(
162 km_dev: &dyn IKeyMintDevice,
163 key_blob: &[u8],
164 upgrade_params: &[KmKeyParameter],
165 km_op: KmOp,
166 new_blob_handler: NewBlobHandler,
167) -> Result<(T, Option<Vec<u8>>)>
168where
169 KmOp: Fn(&[u8]) -> Result<T, Error>,
170 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
171{
172 match km_op(key_blob) {
173 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
174 let upgraded_blob = {
175 let _wp = watchdog::watch_millis(
176 "In utils::upgrade_keyblob_if_required_with: calling upgradeKey.",
177 500,
178 );
179 map_km_error(km_dev.upgradeKey(key_blob, upgrade_params))
180 }
181 .context("In utils::upgrade_keyblob_if_required_with: Upgrade failed.")?;
182
183 new_blob_handler(&upgraded_blob)
184 .context("In utils::upgrade_keyblob_if_required_with: calling new_blob_handler.")?;
185
186 km_op(&upgraded_blob)
187 .map(|v| (v, Some(upgraded_blob)))
188 .context("In utils::upgrade_keyblob_if_required_with: Calling km_op after upgrade.")
189 }
190 r => r
191 .map(|v| (v, None))
192 .context("In utils::upgrade_keyblob_if_required_with: Calling km_op."),
193 }
194}
195
Janis Danisevskis04b02832020-10-26 09:21:40 -0700196/// Converts a set of key characteristics from the internal representation into a set of
197/// Authorizations as they are used to convey key characteristics to the clients of keystore.
198pub fn key_parameters_to_authorizations(
199 parameters: Vec<crate::key_parameter::KeyParameter>,
200) -> Vec<Authorization> {
201 parameters.into_iter().map(|p| p.into_authorization()).collect()
202}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000203
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000204/// This returns the current time (in milliseconds) as an instance of a monotonic clock,
205/// by invoking the system call since Rust does not support getting monotonic time instance
206/// as an integer.
207pub fn get_current_time_in_milliseconds() -> i64 {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000208 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
209 // Following unsafe block includes one system call to get monotonic time.
210 // Therefore, it is not considered harmful.
211 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000212 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000213}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800214
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800215/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
216/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
217/// (android.security.apc) spec.
218pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
219 match rc {
220 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
221 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
222 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
223 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
224 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
225 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
226 _ => ApcResponseCode::SYSTEM_ERROR,
227 }
228}
229
230/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
231/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
232/// module (keystore2_apc_compat).
233pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
234 ApcCompatUiOptions {
235 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
236 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
237 }
238}
239
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800240/// AID offset for uid space partitioning.
Joel Galenson81a50f22021-07-29 15:39:10 -0700241pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800242
Paul Crowley44c02da2021-04-08 17:04:43 +0000243/// AID of the keystore process itself, used for keys that
244/// keystore generates for its own use.
Joel Galenson81a50f22021-07-29 15:39:10 -0700245pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
Paul Crowley44c02da2021-04-08 17:04:43 +0000246
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800247/// Extracts the android user from the given uid.
248pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galenson81a50f22021-07-29 15:39:10 -0700249 rustutils::users::multiuser_get_user_id(uid)
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800250}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100251
John Wu16db29e2022-01-13 15:21:43 -0800252/// List all key aliases for a given domain + namespace.
253pub fn list_key_entries(
254 db: &mut KeystoreDB,
255 domain: Domain,
256 namespace: i64,
257) -> Result<Vec<KeyDescriptor>> {
258 let mut result = Vec::new();
259 result.append(
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800260 &mut LEGACY_IMPORTER
John Wu16db29e2022-01-13 15:21:43 -0800261 .list_uid(domain, namespace)
262 .context("In list_key_entries: Trying to list legacy keys.")?,
263 );
264 result.append(
265 &mut db
266 .list(domain, namespace, KeyType::Client)
267 .context("In list_key_entries: Trying to list keystore database.")?,
268 );
269 result.sort_unstable();
270 result.dedup();
271 Ok(result)
272}
273
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700274/// This module provides helpers for simplified use of the watchdog module.
275#[cfg(feature = "watchdog")]
276pub mod watchdog {
277 pub use crate::watchdog::WatchPoint;
278 use crate::watchdog::Watchdog;
279 use lazy_static::lazy_static;
280 use std::sync::Arc;
281 use std::time::Duration;
282
283 lazy_static! {
284 /// A Watchdog thread, that can be used to create watch points.
285 static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
286 }
287
288 /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
289 pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
290 Watchdog::watch(&WD, id, Duration::from_millis(millis))
291 }
292
293 /// Like `watch_millis` but with a callback that is called every time a report
294 /// is printed about this watch point.
295 pub fn watch_millis_with(
296 id: &'static str,
297 millis: u64,
298 callback: impl Fn() -> String + Send + 'static,
299 ) -> Option<WatchPoint> {
300 Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
301 }
302}
303
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800304/// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
305pub trait AesGcm {
306 /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
307 /// and AES-GCM. The implementation provides the key material and selects
308 /// the implementation variant, e.g., AES128 or AES265.
309 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>;
310
311 /// Encrypts `data` and returns the ciphertext, the initialization vector `iv`
312 /// and AEAD tag `tag`. The implementation provides the key material and selects
313 /// the implementation variant, e.g., AES128 or AES265.
314 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>;
315}
316
317/// Marks an object as AES-GCM key.
318pub trait AesGcmKey {
319 /// Provides access to the raw key material.
320 fn key(&self) -> &[u8];
321}
322
323impl<T: AesGcmKey> AesGcm for T {
324 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
325 aes_gcm_decrypt(data, iv, tag, self.key())
326 .context("In AesGcm<T>::decrypt: Decryption failed")
327 }
328
329 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
330 aes_gcm_encrypt(plaintext, self.key()).context("In AesGcm<T>::encrypt: Encryption failed.")
331 }
332}
333
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700334/// This module provides empty/noop implementations of the watch dog utility functions.
335#[cfg(not(feature = "watchdog"))]
336pub mod watchdog {
337 /// Noop watch point.
338 pub struct WatchPoint();
339 /// Sets a Noop watch point.
340 fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
341 None
342 }
343
344 pub fn watch_millis_with(
345 _: &'static str,
346 _: u64,
347 _: impl Fn() -> String + Send + 'static,
348 ) -> Option<WatchPoint> {
349 None
350 }
351}
352
Bram Bonné5d6c5102021-02-24 15:09:18 +0100353#[cfg(test)]
354mod tests {
355 use super::*;
356 use anyhow::Result;
357
358 #[test]
359 fn check_device_attestation_permissions_test() -> Result<()> {
360 check_device_attestation_permissions().or_else(|error| {
361 match error.root_cause().downcast_ref::<Error>() {
362 // Expected: the context for this test might not be allowed to attest device IDs.
363 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
364 // Other errors are unexpected
365 _ => Err(error),
366 }
367 })
368 }
369}