| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 1 | // 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é | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 18 | use crate::error::{map_binder_status, Error, ErrorCode}; | 
| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 19 | use crate::permission; | 
|  | 20 | use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm}; | 
| Shawn Willden | 708744a | 2020-12-11 13:05:27 +0000 | [diff] [blame] | 21 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ | 
| Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 22 | KeyCharacteristics::KeyCharacteristics, Tag::Tag, | 
| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 23 | }; | 
| Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 24 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; | 
| Janis Danisevskis | 7a1cf38 | 2020-11-20 11:22:14 -0800 | [diff] [blame] | 25 | use android_security_apc::aidl::android::security::apc::{ | 
|  | 26 | IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED}, | 
|  | 27 | ResponseCode::ResponseCode as ApcResponseCode, | 
|  | 28 | }; | 
| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 29 | use android_system_keystore2::aidl::android::system::keystore2::{ | 
| Janis Danisevskis | a53c9cf | 2020-10-26 11:52:33 -0700 | [diff] [blame] | 30 | Authorization::Authorization, KeyDescriptor::KeyDescriptor, | 
| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 31 | }; | 
|  | 32 | use anyhow::{anyhow, Context}; | 
|  | 33 | use binder::{FromIBinder, SpIBinder, ThreadState}; | 
| Janis Danisevskis | 7a1cf38 | 2020-11-20 11:22:14 -0800 | [diff] [blame] | 34 | use 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 Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 39 | use std::convert::TryFrom; | 
| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 40 | use 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. | 
|  | 45 | pub 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. | 
|  | 59 | pub 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. | 
|  | 74 | pub 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 Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 81 | ThreadState::get_calling_uid(), | 
| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 82 | &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é | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 92 | /// This function checks whether a given tag corresponds to the access of device identifiers. | 
|  | 93 | pub fn is_device_id_attestation_tag(tag: Tag) -> bool { | 
| Janis Danisevskis | 83116e5 | 2021-04-06 13:36:58 -0700 | [diff] [blame] | 94 | matches!( | 
|  | 95 | tag, | 
|  | 96 | Tag::ATTESTATION_ID_IMEI | 
|  | 97 | | Tag::ATTESTATION_ID_MEID | 
|  | 98 | | Tag::ATTESTATION_ID_SERIAL | 
|  | 99 | | Tag::DEVICE_UNIQUE_ATTESTATION | 
|  | 100 | ) | 
| Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 101 | } | 
|  | 102 |  | 
|  | 103 | /// This function checks whether the calling app has the Android permissions needed to attest device | 
|  | 104 | /// identifiers. It throws an error if the permissions cannot be verified, or if the caller doesn't | 
|  | 105 | /// have the right permissions, and returns silently otherwise. | 
|  | 106 | pub fn check_device_attestation_permissions() -> anyhow::Result<()> { | 
|  | 107 | let permission_controller: binder::Strong<dyn IPermissionController::IPermissionController> = | 
|  | 108 | binder::get_interface("permission")?; | 
|  | 109 |  | 
|  | 110 | let binder_result = permission_controller.checkPermission( | 
|  | 111 | "android.permission.READ_PRIVILEGED_PHONE_STATE", | 
|  | 112 | ThreadState::get_calling_pid(), | 
|  | 113 | ThreadState::get_calling_uid() as i32, | 
|  | 114 | ); | 
|  | 115 | let has_permissions = map_binder_status(binder_result) | 
|  | 116 | .context("In check_device_attestation_permissions: checkPermission failed")?; | 
|  | 117 | match has_permissions { | 
|  | 118 | true => Ok(()), | 
|  | 119 | false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)).context(concat!( | 
|  | 120 | "In check_device_attestation_permissions: ", | 
|  | 121 | "caller does not have the permission to attest device IDs" | 
|  | 122 | )), | 
|  | 123 | } | 
|  | 124 | } | 
|  | 125 |  | 
| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 126 | /// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the | 
|  | 127 | /// same object in multiple threads, but cloning a SpIBinder is not thread safe. | 
|  | 128 | /// Keystore frequently hands out binder tokens to the security level interface. If this | 
|  | 129 | /// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a | 
|  | 130 | /// Mutex. | 
|  | 131 | #[derive(Debug)] | 
|  | 132 | pub struct Asp(Mutex<SpIBinder>); | 
|  | 133 |  | 
|  | 134 | impl Asp { | 
|  | 135 | /// Creates a new instance owning a SpIBinder wrapped in a Mutex. | 
|  | 136 | pub fn new(i: SpIBinder) -> Self { | 
|  | 137 | Self(Mutex::new(i)) | 
|  | 138 | } | 
|  | 139 |  | 
|  | 140 | /// Clones the owned SpIBinder and attempts to convert it into the requested interface. | 
| Stephen Crane | 221bbb5 | 2020-12-16 15:52:10 -0800 | [diff] [blame] | 141 | pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<binder::Strong<T>> { | 
| Janis Danisevskis | a75e208 | 2020-10-07 16:44:26 -0700 | [diff] [blame] | 142 | // We can use unwrap here because we never panic when locked, so the mutex | 
|  | 143 | // can never be poisoned. | 
|  | 144 | let lock = self.0.lock().unwrap(); | 
|  | 145 | (*lock) | 
|  | 146 | .clone() | 
|  | 147 | .into_interface() | 
|  | 148 | .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e))) | 
|  | 149 | } | 
|  | 150 | } | 
| Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 151 |  | 
| Janis Danisevskis | ba99899 | 2020-12-29 16:08:40 -0800 | [diff] [blame] | 152 | impl Clone for Asp { | 
|  | 153 | fn clone(&self) -> Self { | 
|  | 154 | let lock = self.0.lock().unwrap(); | 
|  | 155 | Self(Mutex::new((*lock).clone())) | 
|  | 156 | } | 
|  | 157 | } | 
|  | 158 |  | 
| Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 159 | /// Converts a set of key characteristics as returned from KeyMint into the internal | 
|  | 160 | /// representation of the keystore service. | 
| Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 161 | pub fn key_characteristics_to_internal( | 
| Shawn Willden | dbdac60 | 2021-01-12 22:35:16 -0700 | [diff] [blame] | 162 | key_characteristics: Vec<KeyCharacteristics>, | 
| Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 163 | ) -> Vec<crate::key_parameter::KeyParameter> { | 
|  | 164 | key_characteristics | 
| Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 165 | .into_iter() | 
| Shawn Willden | dbdac60 | 2021-01-12 22:35:16 -0700 | [diff] [blame] | 166 | .flat_map(|aidl_key_char| { | 
|  | 167 | let sec_level = aidl_key_char.securityLevel; | 
|  | 168 | aidl_key_char.authorizations.into_iter().map(move |aidl_kp| { | 
|  | 169 | crate::key_parameter::KeyParameter::new(aidl_kp.into(), sec_level) | 
|  | 170 | }) | 
|  | 171 | }) | 
| Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 172 | .collect() | 
|  | 173 | } | 
|  | 174 |  | 
|  | 175 | /// Converts a set of key characteristics from the internal representation into a set of | 
|  | 176 | /// Authorizations as they are used to convey key characteristics to the clients of keystore. | 
|  | 177 | pub fn key_parameters_to_authorizations( | 
|  | 178 | parameters: Vec<crate::key_parameter::KeyParameter>, | 
|  | 179 | ) -> Vec<Authorization> { | 
|  | 180 | parameters.into_iter().map(|p| p.into_authorization()).collect() | 
|  | 181 | } | 
| Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 182 |  | 
|  | 183 | /// This returns the current time (in seconds) as an instance of a monotonic clock, by invoking the | 
|  | 184 | /// system call since Rust does not support getting monotonic time instance as an integer. | 
|  | 185 | pub fn get_current_time_in_seconds() -> i64 { | 
|  | 186 | let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 }; | 
|  | 187 | // Following unsafe block includes one system call to get monotonic time. | 
|  | 188 | // Therefore, it is not considered harmful. | 
|  | 189 | unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) }; | 
|  | 190 | // It is safe to unwrap here because try_from() returns std::convert::Infallible, which is | 
|  | 191 | // defined to be an error that can never happen (i.e. the result is always ok). | 
| Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 192 | // This suppresses the compiler's complaint about converting tv_sec to i64 in method | 
|  | 193 | // get_current_time_in_seconds. | 
|  | 194 | #[allow(clippy::useless_conversion)] | 
| Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 195 | i64::try_from(current_time.tv_sec).unwrap() | 
|  | 196 | } | 
| Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 197 |  | 
| Janis Danisevskis | 7a1cf38 | 2020-11-20 11:22:14 -0800 | [diff] [blame] | 198 | /// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility | 
|  | 199 | /// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL | 
|  | 200 | /// (android.security.apc) spec. | 
|  | 201 | pub fn compat_2_response_code(rc: u32) -> ApcResponseCode { | 
|  | 202 | match rc { | 
|  | 203 | APC_COMPAT_ERROR_OK => ApcResponseCode::OK, | 
|  | 204 | APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED, | 
|  | 205 | APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED, | 
|  | 206 | APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING, | 
|  | 207 | APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED, | 
|  | 208 | APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR, | 
|  | 209 | _ => ApcResponseCode::SYSTEM_ERROR, | 
|  | 210 | } | 
|  | 211 | } | 
|  | 212 |  | 
|  | 213 | /// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into | 
|  | 214 | /// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility | 
|  | 215 | /// module (keystore2_apc_compat). | 
|  | 216 | pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions { | 
|  | 217 | ApcCompatUiOptions { | 
|  | 218 | inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0, | 
|  | 219 | magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0, | 
|  | 220 | } | 
|  | 221 | } | 
|  | 222 |  | 
| Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 223 | /// AID offset for uid space partitioning. | 
| Joel Galenson | ba41ca3 | 2020-12-28 14:14:07 -0800 | [diff] [blame] | 224 | pub const AID_USER_OFFSET: u32 = cutils_bindgen::AID_USER_OFFSET; | 
| Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 225 |  | 
|  | 226 | /// Extracts the android user from the given uid. | 
|  | 227 | pub fn uid_to_android_user(uid: u32) -> u32 { | 
| Joel Galenson | ba41ca3 | 2020-12-28 14:14:07 -0800 | [diff] [blame] | 228 | // Safety: No memory access | 
|  | 229 | unsafe { cutils_bindgen::multiuser_get_user_id(uid) } | 
| Janis Danisevskis | cd1fb3a | 2020-12-01 09:20:09 -0800 | [diff] [blame] | 230 | } | 
| Bram Bonné | 5d6c510 | 2021-02-24 15:09:18 +0100 | [diff] [blame] | 231 |  | 
|  | 232 | #[cfg(test)] | 
|  | 233 | mod tests { | 
|  | 234 | use super::*; | 
|  | 235 | use anyhow::Result; | 
|  | 236 |  | 
|  | 237 | #[test] | 
|  | 238 | fn check_device_attestation_permissions_test() -> Result<()> { | 
|  | 239 | check_device_attestation_permissions().or_else(|error| { | 
|  | 240 | match error.root_cause().downcast_ref::<Error>() { | 
|  | 241 | // Expected: the context for this test might not be allowed to attest device IDs. | 
|  | 242 | Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()), | 
|  | 243 | // Other errors are unexpected | 
|  | 244 | _ => Err(error), | 
|  | 245 | } | 
|  | 246 | }) | 
|  | 247 | } | 
|  | 248 | } |