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