blob: 274802586f96081be3b5fa8a78b8abcba2263846 [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 {
94 matches!(tag, Tag::ATTESTATION_ID_IMEI | Tag::ATTESTATION_ID_MEID | Tag::ATTESTATION_ID_SERIAL)
95}
96
97/// This function checks whether the calling app has the Android permissions needed to attest device
98/// identifiers. It throws an error if the permissions cannot be verified, or if the caller doesn't
99/// have the right permissions, and returns silently otherwise.
100pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
101 let permission_controller: binder::Strong<dyn IPermissionController::IPermissionController> =
102 binder::get_interface("permission")?;
103
104 let binder_result = permission_controller.checkPermission(
105 "android.permission.READ_PRIVILEGED_PHONE_STATE",
106 ThreadState::get_calling_pid(),
107 ThreadState::get_calling_uid() as i32,
108 );
109 let has_permissions = map_binder_status(binder_result)
110 .context("In check_device_attestation_permissions: checkPermission failed")?;
111 match has_permissions {
112 true => Ok(()),
113 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)).context(concat!(
114 "In check_device_attestation_permissions: ",
115 "caller does not have the permission to attest device IDs"
116 )),
117 }
118}
119
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700120/// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the
121/// same object in multiple threads, but cloning a SpIBinder is not thread safe.
122/// Keystore frequently hands out binder tokens to the security level interface. If this
123/// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a
124/// Mutex.
125#[derive(Debug)]
126pub struct Asp(Mutex<SpIBinder>);
127
128impl Asp {
129 /// Creates a new instance owning a SpIBinder wrapped in a Mutex.
130 pub fn new(i: SpIBinder) -> Self {
131 Self(Mutex::new(i))
132 }
133
134 /// Clones the owned SpIBinder and attempts to convert it into the requested interface.
Stephen Crane221bbb52020-12-16 15:52:10 -0800135 pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<binder::Strong<T>> {
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700136 // We can use unwrap here because we never panic when locked, so the mutex
137 // can never be poisoned.
138 let lock = self.0.lock().unwrap();
139 (*lock)
140 .clone()
141 .into_interface()
142 .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e)))
143 }
144}
Janis Danisevskis04b02832020-10-26 09:21:40 -0700145
Janis Danisevskisba998992020-12-29 16:08:40 -0800146impl Clone for Asp {
147 fn clone(&self) -> Self {
148 let lock = self.0.lock().unwrap();
149 Self(Mutex::new((*lock).clone()))
150 }
151}
152
Janis Danisevskis04b02832020-10-26 09:21:40 -0700153/// Converts a set of key characteristics as returned from KeyMint into the internal
154/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700155pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700156 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700157) -> Vec<crate::key_parameter::KeyParameter> {
158 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700159 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700160 .flat_map(|aidl_key_char| {
161 let sec_level = aidl_key_char.securityLevel;
162 aidl_key_char.authorizations.into_iter().map(move |aidl_kp| {
163 crate::key_parameter::KeyParameter::new(aidl_kp.into(), sec_level)
164 })
165 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700166 .collect()
167}
168
169/// Converts a set of key characteristics from the internal representation into a set of
170/// Authorizations as they are used to convey key characteristics to the clients of keystore.
171pub fn key_parameters_to_authorizations(
172 parameters: Vec<crate::key_parameter::KeyParameter>,
173) -> Vec<Authorization> {
174 parameters.into_iter().map(|p| p.into_authorization()).collect()
175}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000176
177/// This returns the current time (in seconds) as an instance of a monotonic clock, by invoking the
178/// system call since Rust does not support getting monotonic time instance as an integer.
179pub fn get_current_time_in_seconds() -> i64 {
180 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
181 // Following unsafe block includes one system call to get monotonic time.
182 // Therefore, it is not considered harmful.
183 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
184 // It is safe to unwrap here because try_from() returns std::convert::Infallible, which is
185 // defined to be an error that can never happen (i.e. the result is always ok).
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000186 // This suppresses the compiler's complaint about converting tv_sec to i64 in method
187 // get_current_time_in_seconds.
188 #[allow(clippy::useless_conversion)]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000189 i64::try_from(current_time.tv_sec).unwrap()
190}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800191
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800192/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
193/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
194/// (android.security.apc) spec.
195pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
196 match rc {
197 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
198 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
199 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
200 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
201 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
202 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
203 _ => ApcResponseCode::SYSTEM_ERROR,
204 }
205}
206
207/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
208/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
209/// module (keystore2_apc_compat).
210pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
211 ApcCompatUiOptions {
212 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
213 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
214 }
215}
216
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800217/// AID offset for uid space partitioning.
218/// TODO: Replace with bindgen generated from libcutils. b/175619259
219pub const AID_USER_OFFSET: u32 = 100000;
220
221/// Extracts the android user from the given uid.
222pub fn uid_to_android_user(uid: u32) -> u32 {
223 uid / AID_USER_OFFSET
224}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100225
226#[cfg(test)]
227mod tests {
228 use super::*;
229 use anyhow::Result;
230
231 #[test]
232 fn check_device_attestation_permissions_test() -> Result<()> {
233 check_device_attestation_permissions().or_else(|error| {
234 match error.root_cause().downcast_ref::<Error>() {
235 // Expected: the context for this test might not be allowed to attest device IDs.
236 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
237 // Other errors are unexpected
238 _ => Err(error),
239 }
240 })
241 }
242}