blob: bca27d1c9a229f3e5776e8fbc1fdee9599232cc8 [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
110 let binder_result = permission_controller.checkPermission(
111 "android.permission.READ_PRIVILEGED_PHONE_STATE",
112 ThreadState::get_calling_pid(),
113 ThreadState::get_calling_uid() as i32,
114 );
115 let has_permissions = map_binder_status(binder_result)
116 .context("In check_device_attestation_permissions: checkPermission failed")?;
117 match has_permissions {
118 true => Ok(()),
119 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)).context(concat!(
120 "In check_device_attestation_permissions: ",
121 "caller does not have the permission to attest device IDs"
122 )),
123 }
124}
125
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700126/// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the
127/// same object in multiple threads, but cloning a SpIBinder is not thread safe.
128/// Keystore frequently hands out binder tokens to the security level interface. If this
129/// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a
130/// Mutex.
131#[derive(Debug)]
132pub struct Asp(Mutex<SpIBinder>);
133
134impl Asp {
135 /// Creates a new instance owning a SpIBinder wrapped in a Mutex.
136 pub fn new(i: SpIBinder) -> Self {
137 Self(Mutex::new(i))
138 }
139
140 /// Clones the owned SpIBinder and attempts to convert it into the requested interface.
Stephen Crane221bbb52020-12-16 15:52:10 -0800141 pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<binder::Strong<T>> {
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700142 // We can use unwrap here because we never panic when locked, so the mutex
143 // can never be poisoned.
144 let lock = self.0.lock().unwrap();
145 (*lock)
146 .clone()
147 .into_interface()
148 .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e)))
149 }
150}
Janis Danisevskis04b02832020-10-26 09:21:40 -0700151
Janis Danisevskisba998992020-12-29 16:08:40 -0800152impl Clone for Asp {
153 fn clone(&self) -> Self {
154 let lock = self.0.lock().unwrap();
155 Self(Mutex::new((*lock).clone()))
156 }
157}
158
Janis Danisevskis04b02832020-10-26 09:21:40 -0700159/// Converts a set of key characteristics as returned from KeyMint into the internal
160/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700161pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700162 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700163) -> Vec<crate::key_parameter::KeyParameter> {
164 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700165 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700166 .flat_map(|aidl_key_char| {
167 let sec_level = aidl_key_char.securityLevel;
168 aidl_key_char.authorizations.into_iter().map(move |aidl_kp| {
169 crate::key_parameter::KeyParameter::new(aidl_kp.into(), sec_level)
170 })
171 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700172 .collect()
173}
174
175/// Converts a set of key characteristics from the internal representation into a set of
176/// Authorizations as they are used to convey key characteristics to the clients of keystore.
177pub fn key_parameters_to_authorizations(
178 parameters: Vec<crate::key_parameter::KeyParameter>,
179) -> Vec<Authorization> {
180 parameters.into_iter().map(|p| p.into_authorization()).collect()
181}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000182
183/// This returns the current time (in seconds) as an instance of a monotonic clock, by invoking the
184/// system call since Rust does not support getting monotonic time instance as an integer.
185pub fn get_current_time_in_seconds() -> i64 {
186 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
187 // Following unsafe block includes one system call to get monotonic time.
188 // Therefore, it is not considered harmful.
189 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
190 // It is safe to unwrap here because try_from() returns std::convert::Infallible, which is
191 // defined to be an error that can never happen (i.e. the result is always ok).
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000192 // This suppresses the compiler's complaint about converting tv_sec to i64 in method
193 // get_current_time_in_seconds.
194 #[allow(clippy::useless_conversion)]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000195 i64::try_from(current_time.tv_sec).unwrap()
196}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800197
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800198/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
199/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
200/// (android.security.apc) spec.
201pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
202 match rc {
203 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
204 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
205 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
206 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
207 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
208 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
209 _ => ApcResponseCode::SYSTEM_ERROR,
210 }
211}
212
213/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
214/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
215/// module (keystore2_apc_compat).
216pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
217 ApcCompatUiOptions {
218 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
219 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
220 }
221}
222
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800223/// AID offset for uid space partitioning.
Joel Galensonba41ca32020-12-28 14:14:07 -0800224pub const AID_USER_OFFSET: u32 = cutils_bindgen::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800225
Paul Crowley44c02da2021-04-08 17:04:43 +0000226/// AID of the keystore process itself, used for keys that
227/// keystore generates for its own use.
228pub const AID_KEYSTORE: u32 = cutils_bindgen::AID_KEYSTORE;
229
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800230/// Extracts the android user from the given uid.
231pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galensonba41ca32020-12-28 14:14:07 -0800232 // Safety: No memory access
233 unsafe { cutils_bindgen::multiuser_get_user_id(uid) }
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800234}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100235
236#[cfg(test)]
237mod tests {
238 use super::*;
239 use anyhow::Result;
240
241 #[test]
242 fn check_device_attestation_permissions_test() -> Result<()> {
243 check_device_attestation_permissions().or_else(|error| {
244 match error.root_cause().downcast_ref::<Error>() {
245 // Expected: the context for this test might not be allowed to attest device IDs.
246 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
247 // Other errors are unexpected
248 _ => Err(error),
249 }
250 })
251 }
252}