blob: 66a7e508bdaa7730c4edd2aea1c0f15f4806b40e [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 Danisevskisa75e2082020-10-07 16:44:26 -070018use crate::permission;
19use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
Janis Danisevskis04b02832020-10-26 09:21:40 -070020use crate::{error::Error, key_parameter::KeyParameterValue};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070021use android_hardware_keymint::aidl::android::hardware::keymint::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070022 KeyCharacteristics::KeyCharacteristics, KeyParameter::KeyParameter as KmParam,
23 SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070024};
25use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070026 Authorization::Authorization, KeyDescriptor::KeyDescriptor, KeyParameter::KeyParameter,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070027};
28use anyhow::{anyhow, Context};
29use binder::{FromIBinder, SpIBinder, ThreadState};
30use std::sync::Mutex;
31
32/// This function uses its namesake in the permission module and in
33/// combination with with_calling_sid from the binder crate to check
34/// if the caller has the given keystore permission.
35pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
36 ThreadState::with_calling_sid(|calling_sid| {
37 permission::check_keystore_permission(
38 &calling_sid.ok_or_else(Error::sys).context(
39 "In check_keystore_permission: Cannot check permission without calling_sid.",
40 )?,
41 perm,
42 )
43 })
44}
45
46/// This function uses its namesake in the permission module and in
47/// combination with with_calling_sid from the binder crate to check
48/// if the caller has the given grant permission.
49pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
50 ThreadState::with_calling_sid(|calling_sid| {
51 permission::check_grant_permission(
52 &calling_sid.ok_or_else(Error::sys).context(
53 "In check_grant_permission: Cannot check permission without calling_sid.",
54 )?,
55 access_vec,
56 key,
57 )
58 })
59}
60
61/// This function uses its namesake in the permission module and in
62/// combination with with_calling_sid from the binder crate to check
63/// if the caller has the given key permission.
64pub fn check_key_permission(
65 perm: KeyPerm,
66 key: &KeyDescriptor,
67 access_vector: &Option<KeyPermSet>,
68) -> anyhow::Result<()> {
69 ThreadState::with_calling_sid(|calling_sid| {
70 permission::check_key_permission(
71 &calling_sid
72 .ok_or_else(Error::sys)
73 .context("In check_key_permission: Cannot check permission without calling_sid.")?,
74 perm,
75 key,
76 access_vector,
77 )
78 })
79}
80
81/// This function converts a `KeyParameter` from the keystore2 AIDL
82/// bindings into a `KeyParameter` from the keymint AIDL bindings.
83/// TODO This is a temporary workaround until the keymint AIDL spec
84/// lands.
85pub fn keyparam_ks_to_km(p: &KeyParameter) -> KmParam {
86 KmParam {
87 tag: Tag(p.tag),
88 boolValue: p.boolValue,
89 integer: p.integer,
90 longInteger: p.longInteger,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070091 blob: match &p.blob {
92 Some(b) => b.clone(),
93 None => vec![],
94 },
95 }
96}
97
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070098/// This function converts a `KeyParameter` from the keymint AIDL
99/// bindings into a `KeyParameter` from the keystore2 AIDL bindings.
100/// TODO This is a temporary workaround until the keymint AIDL spec
101/// lands.
102pub fn keyparam_km_to_ks(p: &KmParam) -> KeyParameter {
103 KeyParameter {
104 tag: p.tag.0,
105 boolValue: p.boolValue,
106 integer: p.integer,
107 longInteger: p.longInteger,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700108 blob: match p.blob.len() {
109 0 => None,
110 _ => Some(p.blob.clone()),
111 },
112 }
113}
114
Janis Danisevskisa75e2082020-10-07 16:44:26 -0700115/// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the
116/// same object in multiple threads, but cloning a SpIBinder is not thread safe.
117/// Keystore frequently hands out binder tokens to the security level interface. If this
118/// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a
119/// Mutex.
120#[derive(Debug)]
121pub struct Asp(Mutex<SpIBinder>);
122
123impl Asp {
124 /// Creates a new instance owning a SpIBinder wrapped in a Mutex.
125 pub fn new(i: SpIBinder) -> Self {
126 Self(Mutex::new(i))
127 }
128
129 /// Clones the owned SpIBinder and attempts to convert it into the requested interface.
130 pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<Box<T>> {
131 // We can use unwrap here because we never panic when locked, so the mutex
132 // can never be poisoned.
133 let lock = self.0.lock().unwrap();
134 (*lock)
135 .clone()
136 .into_interface()
137 .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e)))
138 }
139}
Janis Danisevskis04b02832020-10-26 09:21:40 -0700140
141/// Converts a set of key characteristics as returned from KeyMint into the internal
142/// representation of the keystore service.
143/// The parameter `hw_security_level` indicates which security level shall be used for
144/// parameters found in the hardware enforced parameter list.
145pub fn key_characteristics_to_internal(
146 key_characteristics: KeyCharacteristics,
147 hw_security_level: SecurityLevel,
148) -> Vec<crate::key_parameter::KeyParameter> {
149 key_characteristics
150 .hardwareEnforced
151 .into_iter()
152 .map(|aidl_kp| {
153 crate::key_parameter::KeyParameter::new(
154 KeyParameterValue::convert_from_wire(aidl_kp),
155 hw_security_level,
156 )
157 })
158 .chain(key_characteristics.softwareEnforced.into_iter().map(|aidl_kp| {
159 crate::key_parameter::KeyParameter::new(
160 KeyParameterValue::convert_from_wire(aidl_kp),
161 SecurityLevel::SOFTWARE,
162 )
163 }))
164 .collect()
165}
166
167/// Converts a set of key characteristics from the internal representation into a set of
168/// Authorizations as they are used to convey key characteristics to the clients of keystore.
169pub fn key_parameters_to_authorizations(
170 parameters: Vec<crate::key_parameter::KeyParameter>,
171) -> Vec<Authorization> {
172 parameters.into_iter().map(|p| p.into_authorization()).collect()
173}