blob: eab9b4d25c2061558ff20d3e208de1fd20261f72 [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
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000015// This suppresses the compiler's complaint about converting tv_sec to i64 in method
16// get_current_time_in_seconds.
17#![allow(clippy::useless_conversion)]
18
Janis Danisevskisa75e2082020-10-07 16:44:26 -070019//! This module implements utility functions used by the Keystore 2.0 service
20//! implementation.
21
Janis Danisevskise6efb242020-12-19 13:58:01 -080022use crate::error::Error;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070023use crate::permission;
24use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
Shawn Willden708744a2020-12-11 13:05:27 +000025use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070026 KeyCharacteristics::KeyCharacteristics, SecurityLevel::SecurityLevel,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070027};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080028use android_security_apc::aidl::android::security::apc::{
29 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
30 ResponseCode::ResponseCode as ApcResponseCode,
31};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070032use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070033 Authorization::Authorization, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070034};
35use anyhow::{anyhow, Context};
36use binder::{FromIBinder, SpIBinder, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080037use keystore2_apc_compat::{
38 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
39 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
40 APC_COMPAT_ERROR_SYSTEM_ERROR,
41};
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000042use std::convert::TryFrom;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070043use std::sync::Mutex;
44
45/// This function uses its namesake in the permission module and in
46/// combination with with_calling_sid from the binder crate to check
47/// if the caller has the given keystore permission.
48pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
49 ThreadState::with_calling_sid(|calling_sid| {
50 permission::check_keystore_permission(
51 &calling_sid.ok_or_else(Error::sys).context(
52 "In check_keystore_permission: Cannot check permission without calling_sid.",
53 )?,
54 perm,
55 )
56 })
57}
58
59/// This function uses its namesake in the permission module and in
60/// combination with with_calling_sid from the binder crate to check
61/// if the caller has the given grant permission.
62pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
63 ThreadState::with_calling_sid(|calling_sid| {
64 permission::check_grant_permission(
65 &calling_sid.ok_or_else(Error::sys).context(
66 "In check_grant_permission: Cannot check permission without calling_sid.",
67 )?,
68 access_vec,
69 key,
70 )
71 })
72}
73
74/// This function uses its namesake in the permission module and in
75/// combination with with_calling_sid from the binder crate to check
76/// if the caller has the given key permission.
77pub fn check_key_permission(
78 perm: KeyPerm,
79 key: &KeyDescriptor,
80 access_vector: &Option<KeyPermSet>,
81) -> anyhow::Result<()> {
82 ThreadState::with_calling_sid(|calling_sid| {
83 permission::check_key_permission(
84 &calling_sid
85 .ok_or_else(Error::sys)
86 .context("In check_key_permission: Cannot check permission without calling_sid.")?,
87 perm,
88 key,
89 access_vector,
90 )
91 })
92}
93
Janis Danisevskisa75e2082020-10-07 16:44:26 -070094/// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the
95/// same object in multiple threads, but cloning a SpIBinder is not thread safe.
96/// Keystore frequently hands out binder tokens to the security level interface. If this
97/// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a
98/// Mutex.
99#[derive(Debug)]
100pub struct Asp(Mutex<SpIBinder>);
101
102impl Asp {
103 /// Creates a new instance owning a SpIBinder wrapped in a Mutex.
104 pub fn new(i: SpIBinder) -> Self {
105 Self(Mutex::new(i))
106 }
107
108 /// Clones the owned SpIBinder and attempts to convert it into the requested interface.
109 pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<Box<T>> {
110 // We can use unwrap here because we never panic when locked, so the mutex
111 // can never be poisoned.
112 let lock = self.0.lock().unwrap();
113 (*lock)
114 .clone()
115 .into_interface()
116 .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e)))
117 }
118}
Janis Danisevskis04b02832020-10-26 09:21:40 -0700119
120/// Converts a set of key characteristics as returned from KeyMint into the internal
121/// representation of the keystore service.
122/// The parameter `hw_security_level` indicates which security level shall be used for
123/// parameters found in the hardware enforced parameter list.
124pub fn key_characteristics_to_internal(
125 key_characteristics: KeyCharacteristics,
126 hw_security_level: SecurityLevel,
127) -> Vec<crate::key_parameter::KeyParameter> {
128 key_characteristics
129 .hardwareEnforced
130 .into_iter()
Janis Danisevskise6efb242020-12-19 13:58:01 -0800131 .map(|aidl_kp| crate::key_parameter::KeyParameter::new(aidl_kp.into(), hw_security_level))
Janis Danisevskis04b02832020-10-26 09:21:40 -0700132 .chain(key_characteristics.softwareEnforced.into_iter().map(|aidl_kp| {
Janis Danisevskise6efb242020-12-19 13:58:01 -0800133 crate::key_parameter::KeyParameter::new(aidl_kp.into(), SecurityLevel::SOFTWARE)
Janis Danisevskis04b02832020-10-26 09:21:40 -0700134 }))
135 .collect()
136}
137
138/// Converts a set of key characteristics from the internal representation into a set of
139/// Authorizations as they are used to convey key characteristics to the clients of keystore.
140pub fn key_parameters_to_authorizations(
141 parameters: Vec<crate::key_parameter::KeyParameter>,
142) -> Vec<Authorization> {
143 parameters.into_iter().map(|p| p.into_authorization()).collect()
144}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000145
146/// This returns the current time (in seconds) as an instance of a monotonic clock, by invoking the
147/// system call since Rust does not support getting monotonic time instance as an integer.
148pub fn get_current_time_in_seconds() -> i64 {
149 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
150 // Following unsafe block includes one system call to get monotonic time.
151 // Therefore, it is not considered harmful.
152 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
153 // It is safe to unwrap here because try_from() returns std::convert::Infallible, which is
154 // defined to be an error that can never happen (i.e. the result is always ok).
155 i64::try_from(current_time.tv_sec).unwrap()
156}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800157
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800158/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
159/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
160/// (android.security.apc) spec.
161pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
162 match rc {
163 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
164 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
165 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
166 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
167 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
168 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
169 _ => ApcResponseCode::SYSTEM_ERROR,
170 }
171}
172
173/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
174/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
175/// module (keystore2_apc_compat).
176pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
177 ApcCompatUiOptions {
178 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
179 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
180 }
181}
182
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800183/// AID offset for uid space partitioning.
184/// TODO: Replace with bindgen generated from libcutils. b/175619259
185pub const AID_USER_OFFSET: u32 = 100000;
186
187/// Extracts the android user from the given uid.
188pub fn uid_to_android_user(uid: u32) -> u32 {
189 uid / AID_USER_OFFSET
190}