blob: 9852aadf85c3ec359fad90dfd6d7a32bec3158b4 [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};
32use anyhow::{anyhow, Context};
33use binder::{FromIBinder, SpIBinder, 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};
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000039use std::convert::TryFrom;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070040use std::sync::Mutex;
41
42/// This function uses its namesake in the permission module and in
43/// combination with with_calling_sid from the binder crate to check
44/// if the caller has the given keystore permission.
45pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
46 ThreadState::with_calling_sid(|calling_sid| {
47 permission::check_keystore_permission(
48 &calling_sid.ok_or_else(Error::sys).context(
49 "In check_keystore_permission: Cannot check permission without calling_sid.",
50 )?,
51 perm,
52 )
53 })
54}
55
56/// This function uses its namesake in the permission module and in
57/// combination with with_calling_sid from the binder crate to check
58/// if the caller has the given grant permission.
59pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
60 ThreadState::with_calling_sid(|calling_sid| {
61 permission::check_grant_permission(
62 &calling_sid.ok_or_else(Error::sys).context(
63 "In check_grant_permission: Cannot check permission without calling_sid.",
64 )?,
65 access_vec,
66 key,
67 )
68 })
69}
70
71/// This function uses its namesake in the permission module and in
72/// combination with with_calling_sid from the binder crate to check
73/// if the caller has the given key permission.
74pub fn check_key_permission(
75 perm: KeyPerm,
76 key: &KeyDescriptor,
77 access_vector: &Option<KeyPermSet>,
78) -> anyhow::Result<()> {
79 ThreadState::with_calling_sid(|calling_sid| {
80 permission::check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -080081 ThreadState::get_calling_uid(),
Janis Danisevskisa75e2082020-10-07 16:44:26 -070082 &calling_sid
83 .ok_or_else(Error::sys)
84 .context("In check_key_permission: Cannot check permission without calling_sid.")?,
85 perm,
86 key,
87 access_vector,
88 )
89 })
90}
91
Bram Bonné5d6c5102021-02-24 15:09:18 +010092/// This function checks whether a given tag corresponds to the access of device identifiers.
93pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -070094 matches!(
95 tag,
96 Tag::ATTESTATION_ID_IMEI
97 | Tag::ATTESTATION_ID_MEID
98 | Tag::ATTESTATION_ID_SERIAL
99 | Tag::DEVICE_UNIQUE_ATTESTATION
100 )
Bram Bonné5d6c5102021-02-24 15:09:18 +0100101}
102
103/// This function checks whether the calling app has the Android permissions needed to attest device
104/// identifiers. It throws an error if the permissions cannot be verified, or if the caller doesn't
105/// have the right permissions, and returns silently otherwise.
106pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
107 let permission_controller: binder::Strong<dyn IPermissionController::IPermissionController> =
108 binder::get_interface("permission")?;
109
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700110 let binder_result = {
111 let _wp = watchdog::watch_millis(
112 "In check_device_attestation_permissions: calling checkPermission.",
113 500,
114 );
115 permission_controller.checkPermission(
116 "android.permission.READ_PRIVILEGED_PHONE_STATE",
117 ThreadState::get_calling_pid(),
118 ThreadState::get_calling_uid() as i32,
119 )
120 };
Bram Bonné5d6c5102021-02-24 15:09:18 +0100121 let has_permissions = map_binder_status(binder_result)
122 .context("In check_device_attestation_permissions: checkPermission failed")?;
123 match has_permissions {
124 true => Ok(()),
125 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)).context(concat!(
126 "In check_device_attestation_permissions: ",
127 "caller does not have the permission to attest device IDs"
128 )),
129 }
130}
131
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700132/// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the
133/// same object in multiple threads, but cloning a SpIBinder is not thread safe.
134/// Keystore frequently hands out binder tokens to the security level interface. If this
135/// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a
136/// Mutex.
137#[derive(Debug)]
138pub struct Asp(Mutex<SpIBinder>);
139
140impl Asp {
141 /// Creates a new instance owning a SpIBinder wrapped in a Mutex.
142 pub fn new(i: SpIBinder) -> Self {
143 Self(Mutex::new(i))
144 }
145
146 /// Clones the owned SpIBinder and attempts to convert it into the requested interface.
Stephen Crane221bbb52020-12-16 15:52:10 -0800147 pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<binder::Strong<T>> {
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700148 // We can use unwrap here because we never panic when locked, so the mutex
149 // can never be poisoned.
150 let lock = self.0.lock().unwrap();
151 (*lock)
152 .clone()
153 .into_interface()
154 .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e)))
155 }
156}
Janis Danisevskis04b02832020-10-26 09:21:40 -0700157
Janis Danisevskisba998992020-12-29 16:08:40 -0800158impl Clone for Asp {
159 fn clone(&self) -> Self {
160 let lock = self.0.lock().unwrap();
161 Self(Mutex::new((*lock).clone()))
162 }
163}
164
Janis Danisevskis04b02832020-10-26 09:21:40 -0700165/// Converts a set of key characteristics as returned from KeyMint into the internal
166/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700167pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700168 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700169) -> Vec<crate::key_parameter::KeyParameter> {
170 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700171 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700172 .flat_map(|aidl_key_char| {
173 let sec_level = aidl_key_char.securityLevel;
174 aidl_key_char.authorizations.into_iter().map(move |aidl_kp| {
175 crate::key_parameter::KeyParameter::new(aidl_kp.into(), sec_level)
176 })
177 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700178 .collect()
179}
180
181/// Converts a set of key characteristics from the internal representation into a set of
182/// Authorizations as they are used to convey key characteristics to the clients of keystore.
183pub fn key_parameters_to_authorizations(
184 parameters: Vec<crate::key_parameter::KeyParameter>,
185) -> Vec<Authorization> {
186 parameters.into_iter().map(|p| p.into_authorization()).collect()
187}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000188
189/// This returns the current time (in seconds) as an instance of a monotonic clock, by invoking the
190/// system call since Rust does not support getting monotonic time instance as an integer.
191pub fn get_current_time_in_seconds() -> i64 {
192 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
193 // Following unsafe block includes one system call to get monotonic time.
194 // Therefore, it is not considered harmful.
195 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
196 // It is safe to unwrap here because try_from() returns std::convert::Infallible, which is
197 // defined to be an error that can never happen (i.e. the result is always ok).
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000198 // This suppresses the compiler's complaint about converting tv_sec to i64 in method
199 // get_current_time_in_seconds.
200 #[allow(clippy::useless_conversion)]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000201 i64::try_from(current_time.tv_sec).unwrap()
202}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800203
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800204/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
205/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
206/// (android.security.apc) spec.
207pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
208 match rc {
209 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
210 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
211 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
212 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
213 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
214 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
215 _ => ApcResponseCode::SYSTEM_ERROR,
216 }
217}
218
219/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
220/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
221/// module (keystore2_apc_compat).
222pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
223 ApcCompatUiOptions {
224 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
225 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
226 }
227}
228
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800229/// AID offset for uid space partitioning.
Joel Galensonba41ca32020-12-28 14:14:07 -0800230pub const AID_USER_OFFSET: u32 = cutils_bindgen::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800231
Paul Crowley44c02da2021-04-08 17:04:43 +0000232/// AID of the keystore process itself, used for keys that
233/// keystore generates for its own use.
234pub const AID_KEYSTORE: u32 = cutils_bindgen::AID_KEYSTORE;
235
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800236/// Extracts the android user from the given uid.
237pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galensonba41ca32020-12-28 14:14:07 -0800238 // Safety: No memory access
239 unsafe { cutils_bindgen::multiuser_get_user_id(uid) }
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800240}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100241
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700242/// This module provides helpers for simplified use of the watchdog module.
243#[cfg(feature = "watchdog")]
244pub mod watchdog {
245 pub use crate::watchdog::WatchPoint;
246 use crate::watchdog::Watchdog;
247 use lazy_static::lazy_static;
248 use std::sync::Arc;
249 use std::time::Duration;
250
251 lazy_static! {
252 /// A Watchdog thread, that can be used to create watch points.
253 static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
254 }
255
256 /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
257 pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
258 Watchdog::watch(&WD, id, Duration::from_millis(millis))
259 }
260
261 /// Like `watch_millis` but with a callback that is called every time a report
262 /// is printed about this watch point.
263 pub fn watch_millis_with(
264 id: &'static str,
265 millis: u64,
266 callback: impl Fn() -> String + Send + 'static,
267 ) -> Option<WatchPoint> {
268 Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
269 }
270}
271
272/// This module provides empty/noop implementations of the watch dog utility functions.
273#[cfg(not(feature = "watchdog"))]
274pub mod watchdog {
275 /// Noop watch point.
276 pub struct WatchPoint();
277 /// Sets a Noop watch point.
278 fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
279 None
280 }
281
282 pub fn watch_millis_with(
283 _: &'static str,
284 _: u64,
285 _: impl Fn() -> String + Send + 'static,
286 ) -> Option<WatchPoint> {
287 None
288 }
289}
290
Bram Bonné5d6c5102021-02-24 15:09:18 +0100291#[cfg(test)]
292mod tests {
293 use super::*;
294 use anyhow::Result;
295
296 #[test]
297 fn check_device_attestation_permissions_test() -> Result<()> {
298 check_device_attestation_permissions().or_else(|error| {
299 match error.root_cause().downcast_ref::<Error>() {
300 // Expected: the context for this test might not be allowed to attest device IDs.
301 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
302 // Other errors are unexpected
303 _ => Err(error),
304 }
305 })
306 }
307}