blob: 82e6700628f42b63cd90d83bcf825ded026b1a07 [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
Bram Bonné5d6c5102021-02-24 15:09:18 +010018use crate::error::{map_binder_status, Error, ErrorCode};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070019use crate::permission;
20use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
John Wu16db29e2022-01-13 15:21:43 -080021use crate::{
22 database::{KeyType, KeystoreDB},
23 globals::LEGACY_MIGRATOR,
24};
Shawn Willden708744a2020-12-11 13:05:27 +000025use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Bram Bonné5d6c5102021-02-24 15:09:18 +010026 KeyCharacteristics::KeyCharacteristics, Tag::Tag,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070027};
Bram Bonné5d6c5102021-02-24 15:09:18 +010028use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080029use android_security_apc::aidl::android::security::apc::{
30 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
31 ResponseCode::ResponseCode as ApcResponseCode,
32};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070033use android_system_keystore2::aidl::android::system::keystore2::{
John Wu16db29e2022-01-13 15:21:43 -080034 Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070035};
John Wu16db29e2022-01-13 15:21:43 -080036use anyhow::{Context, Result};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070037use binder::{Strong, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080038use keystore2_apc_compat::{
39 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
40 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
41 APC_COMPAT_ERROR_SYSTEM_ERROR,
42};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070043
44/// This function uses its namesake in the permission module and in
45/// combination with with_calling_sid from the binder crate to check
46/// if the caller has the given keystore permission.
47pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
48 ThreadState::with_calling_sid(|calling_sid| {
49 permission::check_keystore_permission(
Chris Wailesd5aaaef2021-07-27 16:04:33 -070050 calling_sid.ok_or_else(Error::sys).context(
Janis Danisevskisa75e2082020-10-07 16:44:26 -070051 "In check_keystore_permission: Cannot check permission without calling_sid.",
52 )?,
53 perm,
54 )
55 })
56}
57
58/// This function uses its namesake in the permission module and in
59/// combination with with_calling_sid from the binder crate to check
60/// if the caller has the given grant permission.
61pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
62 ThreadState::with_calling_sid(|calling_sid| {
63 permission::check_grant_permission(
Chris Wailesd5aaaef2021-07-27 16:04:33 -070064 calling_sid.ok_or_else(Error::sys).context(
Janis Danisevskisa75e2082020-10-07 16:44:26 -070065 "In check_grant_permission: Cannot check permission without calling_sid.",
66 )?,
67 access_vec,
68 key,
69 )
70 })
71}
72
73/// This function uses its namesake in the permission module and in
74/// combination with with_calling_sid from the binder crate to check
75/// if the caller has the given key permission.
76pub fn check_key_permission(
77 perm: KeyPerm,
78 key: &KeyDescriptor,
79 access_vector: &Option<KeyPermSet>,
80) -> anyhow::Result<()> {
81 ThreadState::with_calling_sid(|calling_sid| {
82 permission::check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -080083 ThreadState::get_calling_uid(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -070084 calling_sid
Janis Danisevskisa75e2082020-10-07 16:44:26 -070085 .ok_or_else(Error::sys)
86 .context("In check_key_permission: Cannot check permission without calling_sid.")?,
87 perm,
88 key,
89 access_vector,
90 )
91 })
92}
93
Bram Bonné5d6c5102021-02-24 15:09:18 +010094/// This function checks whether a given tag corresponds to the access of device identifiers.
95pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -070096 matches!(
97 tag,
98 Tag::ATTESTATION_ID_IMEI
99 | Tag::ATTESTATION_ID_MEID
100 | Tag::ATTESTATION_ID_SERIAL
101 | Tag::DEVICE_UNIQUE_ATTESTATION
102 )
Bram Bonné5d6c5102021-02-24 15:09:18 +0100103}
104
105/// This function checks whether the calling app has the Android permissions needed to attest device
106/// identifiers. It throws an error if the permissions cannot be verified, or if the caller doesn't
107/// have the right permissions, and returns silently otherwise.
108pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700109 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
Bram Bonné5d6c5102021-02-24 15:09:18 +0100110 binder::get_interface("permission")?;
111
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700112 let binder_result = {
113 let _wp = watchdog::watch_millis(
114 "In check_device_attestation_permissions: calling checkPermission.",
115 500,
116 );
117 permission_controller.checkPermission(
118 "android.permission.READ_PRIVILEGED_PHONE_STATE",
119 ThreadState::get_calling_pid(),
120 ThreadState::get_calling_uid() as i32,
121 )
122 };
Bram Bonné5d6c5102021-02-24 15:09:18 +0100123 let has_permissions = map_binder_status(binder_result)
124 .context("In check_device_attestation_permissions: checkPermission failed")?;
125 match has_permissions {
126 true => Ok(()),
127 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)).context(concat!(
128 "In check_device_attestation_permissions: ",
129 "caller does not have the permission to attest device IDs"
130 )),
131 }
132}
133
Janis Danisevskis04b02832020-10-26 09:21:40 -0700134/// Converts a set of key characteristics as returned from KeyMint into the internal
135/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700136pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700137 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700138) -> Vec<crate::key_parameter::KeyParameter> {
139 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700140 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700141 .flat_map(|aidl_key_char| {
142 let sec_level = aidl_key_char.securityLevel;
143 aidl_key_char.authorizations.into_iter().map(move |aidl_kp| {
144 crate::key_parameter::KeyParameter::new(aidl_kp.into(), sec_level)
145 })
146 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700147 .collect()
148}
149
150/// Converts a set of key characteristics from the internal representation into a set of
151/// Authorizations as they are used to convey key characteristics to the clients of keystore.
152pub fn key_parameters_to_authorizations(
153 parameters: Vec<crate::key_parameter::KeyParameter>,
154) -> Vec<Authorization> {
155 parameters.into_iter().map(|p| p.into_authorization()).collect()
156}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000157
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000158/// This returns the current time (in milliseconds) as an instance of a monotonic clock,
159/// by invoking the system call since Rust does not support getting monotonic time instance
160/// as an integer.
161pub fn get_current_time_in_milliseconds() -> i64 {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000162 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
163 // Following unsafe block includes one system call to get monotonic time.
164 // Therefore, it is not considered harmful.
165 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000166 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000167}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800168
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800169/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
170/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
171/// (android.security.apc) spec.
172pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
173 match rc {
174 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
175 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
176 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
177 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
178 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
179 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
180 _ => ApcResponseCode::SYSTEM_ERROR,
181 }
182}
183
184/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
185/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
186/// module (keystore2_apc_compat).
187pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
188 ApcCompatUiOptions {
189 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
190 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
191 }
192}
193
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800194/// AID offset for uid space partitioning.
Joel Galenson81a50f22021-07-29 15:39:10 -0700195pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800196
Paul Crowley44c02da2021-04-08 17:04:43 +0000197/// AID of the keystore process itself, used for keys that
198/// keystore generates for its own use.
Joel Galenson81a50f22021-07-29 15:39:10 -0700199pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
Paul Crowley44c02da2021-04-08 17:04:43 +0000200
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800201/// Extracts the android user from the given uid.
202pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galenson81a50f22021-07-29 15:39:10 -0700203 rustutils::users::multiuser_get_user_id(uid)
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800204}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100205
John Wu16db29e2022-01-13 15:21:43 -0800206/// List all key aliases for a given domain + namespace.
207pub fn list_key_entries(
208 db: &mut KeystoreDB,
209 domain: Domain,
210 namespace: i64,
211) -> Result<Vec<KeyDescriptor>> {
212 let mut result = Vec::new();
213 result.append(
214 &mut LEGACY_MIGRATOR
215 .list_uid(domain, namespace)
216 .context("In list_key_entries: Trying to list legacy keys.")?,
217 );
218 result.append(
219 &mut db
220 .list(domain, namespace, KeyType::Client)
221 .context("In list_key_entries: Trying to list keystore database.")?,
222 );
223 result.sort_unstable();
224 result.dedup();
225 Ok(result)
226}
227
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700228/// This module provides helpers for simplified use of the watchdog module.
229#[cfg(feature = "watchdog")]
230pub mod watchdog {
231 pub use crate::watchdog::WatchPoint;
232 use crate::watchdog::Watchdog;
233 use lazy_static::lazy_static;
234 use std::sync::Arc;
235 use std::time::Duration;
236
237 lazy_static! {
238 /// A Watchdog thread, that can be used to create watch points.
239 static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
240 }
241
242 /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
243 pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
244 Watchdog::watch(&WD, id, Duration::from_millis(millis))
245 }
246
247 /// Like `watch_millis` but with a callback that is called every time a report
248 /// is printed about this watch point.
249 pub fn watch_millis_with(
250 id: &'static str,
251 millis: u64,
252 callback: impl Fn() -> String + Send + 'static,
253 ) -> Option<WatchPoint> {
254 Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
255 }
256}
257
258/// This module provides empty/noop implementations of the watch dog utility functions.
259#[cfg(not(feature = "watchdog"))]
260pub mod watchdog {
261 /// Noop watch point.
262 pub struct WatchPoint();
263 /// Sets a Noop watch point.
264 fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
265 None
266 }
267
268 pub fn watch_millis_with(
269 _: &'static str,
270 _: u64,
271 _: impl Fn() -> String + Send + 'static,
272 ) -> Option<WatchPoint> {
273 None
274 }
275}
276
Bram Bonné5d6c5102021-02-24 15:09:18 +0100277#[cfg(test)]
278mod tests {
279 use super::*;
280 use anyhow::Result;
281
282 #[test]
283 fn check_device_attestation_permissions_test() -> Result<()> {
284 check_device_attestation_permissions().or_else(|error| {
285 match error.root_cause().downcast_ref::<Error>() {
286 // Expected: the context for this test might not be allowed to attest device IDs.
287 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
288 // Other errors are unexpected
289 _ => Err(error),
290 }
291 })
292 }
293}