blob: 8e161b7703f82d89bdab662e9cf9255eba2922e8 [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
Janis Danisevskise6efb242020-12-19 13:58:01 -080018use crate::error::Error;
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::{
Max Bires8e93d2b2021-01-14 13:17:59 -080022 KeyCharacteristics::KeyCharacteristics,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070023};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080024use android_security_apc::aidl::android::security::apc::{
25 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
26 ResponseCode::ResponseCode as ApcResponseCode,
27};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070028use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070029 Authorization::Authorization, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070030};
31use anyhow::{anyhow, Context};
32use binder::{FromIBinder, SpIBinder, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080033use keystore2_apc_compat::{
34 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
35 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
36 APC_COMPAT_ERROR_SYSTEM_ERROR,
37};
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000038use std::convert::TryFrom;
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
Janis Danisevskisa75e2082020-10-07 16:44:26 -070091/// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the
92/// same object in multiple threads, but cloning a SpIBinder is not thread safe.
93/// Keystore frequently hands out binder tokens to the security level interface. If this
94/// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a
95/// Mutex.
96#[derive(Debug)]
97pub struct Asp(Mutex<SpIBinder>);
98
99impl Asp {
100 /// Creates a new instance owning a SpIBinder wrapped in a Mutex.
101 pub fn new(i: SpIBinder) -> Self {
102 Self(Mutex::new(i))
103 }
104
105 /// Clones the owned SpIBinder and attempts to convert it into the requested interface.
Stephen Crane221bbb52020-12-16 15:52:10 -0800106 pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<binder::Strong<T>> {
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700107 // We can use unwrap here because we never panic when locked, so the mutex
108 // can never be poisoned.
109 let lock = self.0.lock().unwrap();
110 (*lock)
111 .clone()
112 .into_interface()
113 .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e)))
114 }
115}
Janis Danisevskis04b02832020-10-26 09:21:40 -0700116
Janis Danisevskisba998992020-12-29 16:08:40 -0800117impl Clone for Asp {
118 fn clone(&self) -> Self {
119 let lock = self.0.lock().unwrap();
120 Self(Mutex::new((*lock).clone()))
121 }
122}
123
Janis Danisevskis04b02832020-10-26 09:21:40 -0700124/// Converts a set of key characteristics as returned from KeyMint into the internal
125/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700126pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700127 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700128) -> Vec<crate::key_parameter::KeyParameter> {
129 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700130 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700131 .flat_map(|aidl_key_char| {
132 let sec_level = aidl_key_char.securityLevel;
133 aidl_key_char.authorizations.into_iter().map(move |aidl_kp| {
134 crate::key_parameter::KeyParameter::new(aidl_kp.into(), sec_level)
135 })
136 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700137 .collect()
138}
139
140/// Converts a set of key characteristics from the internal representation into a set of
141/// Authorizations as they are used to convey key characteristics to the clients of keystore.
142pub fn key_parameters_to_authorizations(
143 parameters: Vec<crate::key_parameter::KeyParameter>,
144) -> Vec<Authorization> {
145 parameters.into_iter().map(|p| p.into_authorization()).collect()
146}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000147
148/// This returns the current time (in seconds) as an instance of a monotonic clock, by invoking the
149/// system call since Rust does not support getting monotonic time instance as an integer.
150pub fn get_current_time_in_seconds() -> i64 {
151 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
152 // Following unsafe block includes one system call to get monotonic time.
153 // Therefore, it is not considered harmful.
154 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
155 // It is safe to unwrap here because try_from() returns std::convert::Infallible, which is
156 // defined to be an error that can never happen (i.e. the result is always ok).
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000157 // This suppresses the compiler's complaint about converting tv_sec to i64 in method
158 // get_current_time_in_seconds.
159 #[allow(clippy::useless_conversion)]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000160 i64::try_from(current_time.tv_sec).unwrap()
161}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800162
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800163/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
164/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
165/// (android.security.apc) spec.
166pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
167 match rc {
168 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
169 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
170 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
171 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
172 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
173 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
174 _ => ApcResponseCode::SYSTEM_ERROR,
175 }
176}
177
178/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
179/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
180/// module (keystore2_apc_compat).
181pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
182 ApcCompatUiOptions {
183 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
184 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
185 }
186}
187
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800188/// AID offset for uid space partitioning.
189/// TODO: Replace with bindgen generated from libcutils. b/175619259
190pub const AID_USER_OFFSET: u32 = 100000;
191
192/// Extracts the android user from the given uid.
193pub fn uid_to_android_user(uid: u32) -> u32 {
194 uid / AID_USER_OFFSET
195}