blob: c1684867e7c52a9c8480c914b4e890316be20dbe [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 Danisevskisa75e2082020-10-07 16:44:26 -070022use crate::permission;
23use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
Janis Danisevskis04b02832020-10-26 09:21:40 -070024use crate::{error::Error, key_parameter::KeyParameterValue};
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};
28use 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};
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000033use std::convert::TryFrom;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070034use std::sync::Mutex;
35
36/// This function uses its namesake in the permission module and in
37/// combination with with_calling_sid from the binder crate to check
38/// if the caller has the given keystore permission.
39pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
40 ThreadState::with_calling_sid(|calling_sid| {
41 permission::check_keystore_permission(
42 &calling_sid.ok_or_else(Error::sys).context(
43 "In check_keystore_permission: Cannot check permission without calling_sid.",
44 )?,
45 perm,
46 )
47 })
48}
49
50/// This function uses its namesake in the permission module and in
51/// combination with with_calling_sid from the binder crate to check
52/// if the caller has the given grant permission.
53pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
54 ThreadState::with_calling_sid(|calling_sid| {
55 permission::check_grant_permission(
56 &calling_sid.ok_or_else(Error::sys).context(
57 "In check_grant_permission: Cannot check permission without calling_sid.",
58 )?,
59 access_vec,
60 key,
61 )
62 })
63}
64
65/// This function uses its namesake in the permission module and in
66/// combination with with_calling_sid from the binder crate to check
67/// if the caller has the given key permission.
68pub fn check_key_permission(
69 perm: KeyPerm,
70 key: &KeyDescriptor,
71 access_vector: &Option<KeyPermSet>,
72) -> anyhow::Result<()> {
73 ThreadState::with_calling_sid(|calling_sid| {
74 permission::check_key_permission(
75 &calling_sid
76 .ok_or_else(Error::sys)
77 .context("In check_key_permission: Cannot check permission without calling_sid.")?,
78 perm,
79 key,
80 access_vector,
81 )
82 })
83}
84
Janis Danisevskisa75e2082020-10-07 16:44:26 -070085/// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the
86/// same object in multiple threads, but cloning a SpIBinder is not thread safe.
87/// Keystore frequently hands out binder tokens to the security level interface. If this
88/// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a
89/// Mutex.
90#[derive(Debug)]
91pub struct Asp(Mutex<SpIBinder>);
92
93impl Asp {
94 /// Creates a new instance owning a SpIBinder wrapped in a Mutex.
95 pub fn new(i: SpIBinder) -> Self {
96 Self(Mutex::new(i))
97 }
98
99 /// Clones the owned SpIBinder and attempts to convert it into the requested interface.
100 pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<Box<T>> {
101 // We can use unwrap here because we never panic when locked, so the mutex
102 // can never be poisoned.
103 let lock = self.0.lock().unwrap();
104 (*lock)
105 .clone()
106 .into_interface()
107 .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e)))
108 }
109}
Janis Danisevskis04b02832020-10-26 09:21:40 -0700110
111/// Converts a set of key characteristics as returned from KeyMint into the internal
112/// representation of the keystore service.
113/// The parameter `hw_security_level` indicates which security level shall be used for
114/// parameters found in the hardware enforced parameter list.
115pub fn key_characteristics_to_internal(
116 key_characteristics: KeyCharacteristics,
117 hw_security_level: SecurityLevel,
118) -> Vec<crate::key_parameter::KeyParameter> {
119 key_characteristics
120 .hardwareEnforced
121 .into_iter()
122 .map(|aidl_kp| {
123 crate::key_parameter::KeyParameter::new(
124 KeyParameterValue::convert_from_wire(aidl_kp),
125 hw_security_level,
126 )
127 })
128 .chain(key_characteristics.softwareEnforced.into_iter().map(|aidl_kp| {
129 crate::key_parameter::KeyParameter::new(
130 KeyParameterValue::convert_from_wire(aidl_kp),
131 SecurityLevel::SOFTWARE,
132 )
133 }))
134 .collect()
135}
136
137/// Converts a set of key characteristics from the internal representation into a set of
138/// Authorizations as they are used to convey key characteristics to the clients of keystore.
139pub fn key_parameters_to_authorizations(
140 parameters: Vec<crate::key_parameter::KeyParameter>,
141) -> Vec<Authorization> {
142 parameters.into_iter().map(|p| p.into_authorization()).collect()
143}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000144
145/// This returns the current time (in seconds) as an instance of a monotonic clock, by invoking the
146/// system call since Rust does not support getting monotonic time instance as an integer.
147pub fn get_current_time_in_seconds() -> i64 {
148 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
149 // Following unsafe block includes one system call to get monotonic time.
150 // Therefore, it is not considered harmful.
151 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
152 // It is safe to unwrap here because try_from() returns std::convert::Infallible, which is
153 // defined to be an error that can never happen (i.e. the result is always ok).
154 i64::try_from(current_time.tv_sec).unwrap()
155}