blob: 83b6853c614fc1accd9638dcc90a820084971649 [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};
Shawn Willden708744a2020-12-11 13:05:27 +000021use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Bram Bonné5d6c5102021-02-24 15:09:18 +010022 KeyCharacteristics::KeyCharacteristics, Tag::Tag,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070023};
Bram Bonné5d6c5102021-02-24 15:09:18 +010024use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080025use android_security_apc::aidl::android::security::apc::{
26 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
27 ResponseCode::ResponseCode as ApcResponseCode,
28};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070029use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070030 Authorization::Authorization, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070031};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070032use anyhow::Context;
33use binder::{Strong, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080034use keystore2_apc_compat::{
35 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
36 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
37 APC_COMPAT_ERROR_SYSTEM_ERROR,
38};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070039
40/// This function uses its namesake in the permission module and in
41/// combination with with_calling_sid from the binder crate to check
42/// if the caller has the given keystore permission.
43pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
44 ThreadState::with_calling_sid(|calling_sid| {
45 permission::check_keystore_permission(
46 &calling_sid.ok_or_else(Error::sys).context(
47 "In check_keystore_permission: Cannot check permission without calling_sid.",
48 )?,
49 perm,
50 )
51 })
52}
53
54/// This function uses its namesake in the permission module and in
55/// combination with with_calling_sid from the binder crate to check
56/// if the caller has the given grant permission.
57pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
58 ThreadState::with_calling_sid(|calling_sid| {
59 permission::check_grant_permission(
60 &calling_sid.ok_or_else(Error::sys).context(
61 "In check_grant_permission: Cannot check permission without calling_sid.",
62 )?,
63 access_vec,
64 key,
65 )
66 })
67}
68
69/// This function uses its namesake in the permission module and in
70/// combination with with_calling_sid from the binder crate to check
71/// if the caller has the given key permission.
72pub fn check_key_permission(
73 perm: KeyPerm,
74 key: &KeyDescriptor,
75 access_vector: &Option<KeyPermSet>,
76) -> anyhow::Result<()> {
77 ThreadState::with_calling_sid(|calling_sid| {
78 permission::check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -080079 ThreadState::get_calling_uid(),
Janis Danisevskisa75e2082020-10-07 16:44:26 -070080 &calling_sid
81 .ok_or_else(Error::sys)
82 .context("In check_key_permission: Cannot check permission without calling_sid.")?,
83 perm,
84 key,
85 access_vector,
86 )
87 })
88}
89
Bram Bonné5d6c5102021-02-24 15:09:18 +010090/// This function checks whether a given tag corresponds to the access of device identifiers.
91pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -070092 matches!(
93 tag,
94 Tag::ATTESTATION_ID_IMEI
95 | Tag::ATTESTATION_ID_MEID
96 | Tag::ATTESTATION_ID_SERIAL
97 | Tag::DEVICE_UNIQUE_ATTESTATION
98 )
Bram Bonné5d6c5102021-02-24 15:09:18 +010099}
100
101/// This function checks whether the calling app has the Android permissions needed to attest device
102/// identifiers. It throws an error if the permissions cannot be verified, or if the caller doesn't
103/// have the right permissions, and returns silently otherwise.
104pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700105 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
Bram Bonné5d6c5102021-02-24 15:09:18 +0100106 binder::get_interface("permission")?;
107
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700108 let binder_result = {
109 let _wp = watchdog::watch_millis(
110 "In check_device_attestation_permissions: calling checkPermission.",
111 500,
112 );
113 permission_controller.checkPermission(
114 "android.permission.READ_PRIVILEGED_PHONE_STATE",
115 ThreadState::get_calling_pid(),
116 ThreadState::get_calling_uid() as i32,
117 )
118 };
Bram Bonné5d6c5102021-02-24 15:09:18 +0100119 let has_permissions = map_binder_status(binder_result)
120 .context("In check_device_attestation_permissions: checkPermission failed")?;
121 match has_permissions {
122 true => Ok(()),
123 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)).context(concat!(
124 "In check_device_attestation_permissions: ",
125 "caller does not have the permission to attest device IDs"
126 )),
127 }
128}
129
Janis Danisevskis04b02832020-10-26 09:21:40 -0700130/// Converts a set of key characteristics as returned from KeyMint into the internal
131/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700132pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700133 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700134) -> Vec<crate::key_parameter::KeyParameter> {
135 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700136 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700137 .flat_map(|aidl_key_char| {
138 let sec_level = aidl_key_char.securityLevel;
139 aidl_key_char.authorizations.into_iter().map(move |aidl_kp| {
140 crate::key_parameter::KeyParameter::new(aidl_kp.into(), sec_level)
141 })
142 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700143 .collect()
144}
145
146/// Converts a set of key characteristics from the internal representation into a set of
147/// Authorizations as they are used to convey key characteristics to the clients of keystore.
148pub fn key_parameters_to_authorizations(
149 parameters: Vec<crate::key_parameter::KeyParameter>,
150) -> Vec<Authorization> {
151 parameters.into_iter().map(|p| p.into_authorization()).collect()
152}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000153
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000154/// This returns the current time (in milliseconds) as an instance of a monotonic clock,
155/// by invoking the system call since Rust does not support getting monotonic time instance
156/// as an integer.
157pub fn get_current_time_in_milliseconds() -> i64 {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000158 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
159 // Following unsafe block includes one system call to get monotonic time.
160 // Therefore, it is not considered harmful.
161 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000162 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000163}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800164
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800165/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
166/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
167/// (android.security.apc) spec.
168pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
169 match rc {
170 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
171 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
172 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
173 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
174 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
175 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
176 _ => ApcResponseCode::SYSTEM_ERROR,
177 }
178}
179
180/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
181/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
182/// module (keystore2_apc_compat).
183pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
184 ApcCompatUiOptions {
185 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
186 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
187 }
188}
189
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800190/// AID offset for uid space partitioning.
Joel Galensonba41ca32020-12-28 14:14:07 -0800191pub const AID_USER_OFFSET: u32 = cutils_bindgen::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800192
Paul Crowley44c02da2021-04-08 17:04:43 +0000193/// AID of the keystore process itself, used for keys that
194/// keystore generates for its own use.
195pub const AID_KEYSTORE: u32 = cutils_bindgen::AID_KEYSTORE;
196
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800197/// Extracts the android user from the given uid.
198pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galensonba41ca32020-12-28 14:14:07 -0800199 // Safety: No memory access
200 unsafe { cutils_bindgen::multiuser_get_user_id(uid) }
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800201}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100202
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700203/// This module provides helpers for simplified use of the watchdog module.
204#[cfg(feature = "watchdog")]
205pub mod watchdog {
206 pub use crate::watchdog::WatchPoint;
207 use crate::watchdog::Watchdog;
208 use lazy_static::lazy_static;
209 use std::sync::Arc;
210 use std::time::Duration;
211
212 lazy_static! {
213 /// A Watchdog thread, that can be used to create watch points.
214 static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
215 }
216
217 /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
218 pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
219 Watchdog::watch(&WD, id, Duration::from_millis(millis))
220 }
221
222 /// Like `watch_millis` but with a callback that is called every time a report
223 /// is printed about this watch point.
224 pub fn watch_millis_with(
225 id: &'static str,
226 millis: u64,
227 callback: impl Fn() -> String + Send + 'static,
228 ) -> Option<WatchPoint> {
229 Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
230 }
231}
232
233/// This module provides empty/noop implementations of the watch dog utility functions.
234#[cfg(not(feature = "watchdog"))]
235pub mod watchdog {
236 /// Noop watch point.
237 pub struct WatchPoint();
238 /// Sets a Noop watch point.
239 fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
240 None
241 }
242
243 pub fn watch_millis_with(
244 _: &'static str,
245 _: u64,
246 _: impl Fn() -> String + Send + 'static,
247 ) -> Option<WatchPoint> {
248 None
249 }
250}
251
Bram Bonné5d6c5102021-02-24 15:09:18 +0100252#[cfg(test)]
253mod tests {
254 use super::*;
255 use anyhow::Result;
256
257 #[test]
258 fn check_device_attestation_permissions_test() -> Result<()> {
259 check_device_attestation_permissions().or_else(|error| {
260 match error.root_cause().downcast_ref::<Error>() {
261 // Expected: the context for this test might not be allowed to attest device IDs.
262 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
263 // Other errors are unexpected
264 _ => Err(error),
265 }
266 })
267 }
268}