blob: fcfa9797b569fca40cc2ca5f3069bb9dc1e3189a [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 Danisevskisf84d0b02022-01-26 14:11:14 -080018use crate::error::{map_binder_status, map_km_error, Error, ErrorCode};
19use crate::key_parameter::KeyParameter;
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000020use crate::ks_err;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070021use crate::permission;
22use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
John Wu16db29e2022-01-13 15:21:43 -080023use crate::{
24 database::{KeyType, KeystoreDB},
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080025 globals::LEGACY_IMPORTER,
John Wu16db29e2022-01-13 15:21:43 -080026};
Shawn Willden708744a2020-12-11 13:05:27 +000027use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080028 IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics,
29 KeyParameter::KeyParameter as KmKeyParameter, Tag::Tag,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070030};
Bram Bonné5d6c5102021-02-24 15:09:18 +010031use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080032use android_security_apc::aidl::android::security::apc::{
33 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
34 ResponseCode::ResponseCode as ApcResponseCode,
35};
Janis Danisevskisa75e2082020-10-07 16:44:26 -070036use android_system_keystore2::aidl::android::system::keystore2::{
John Wu16db29e2022-01-13 15:21:43 -080037 Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070038};
John Wu16db29e2022-01-13 15:21:43 -080039use anyhow::{Context, Result};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070040use binder::{Strong, ThreadState};
Janis Danisevskis7a1cf382020-11-20 11:22:14 -080041use keystore2_apc_compat::{
42 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
43 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
44 APC_COMPAT_ERROR_SYSTEM_ERROR,
45};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080046use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec};
47use std::iter::IntoIterator;
Janis Danisevskisa75e2082020-10-07 16:44:26 -070048
49/// This function uses its namesake in the permission module and in
50/// combination with with_calling_sid from the binder crate to check
51/// if the caller has the given keystore permission.
52pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
53 ThreadState::with_calling_sid(|calling_sid| {
54 permission::check_keystore_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000055 calling_sid
56 .ok_or_else(Error::sys)
57 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070058 perm,
59 )
60 })
61}
62
63/// This function uses its namesake in the permission module and in
64/// combination with with_calling_sid from the binder crate to check
65/// if the caller has the given grant permission.
66pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
67 ThreadState::with_calling_sid(|calling_sid| {
68 permission::check_grant_permission(
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000069 calling_sid
70 .ok_or_else(Error::sys)
71 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070072 access_vec,
73 key,
74 )
75 })
76}
77
78/// This function uses its namesake in the permission module and in
79/// combination with with_calling_sid from the binder crate to check
80/// if the caller has the given key permission.
81pub fn check_key_permission(
82 perm: KeyPerm,
83 key: &KeyDescriptor,
84 access_vector: &Option<KeyPermSet>,
85) -> anyhow::Result<()> {
86 ThreadState::with_calling_sid(|calling_sid| {
87 permission::check_key_permission(
Janis Danisevskis45760022021-01-19 16:34:10 -080088 ThreadState::get_calling_uid(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -070089 calling_sid
Janis Danisevskisa75e2082020-10-07 16:44:26 -070090 .ok_or_else(Error::sys)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000091 .context(ks_err!("Cannot check permission without calling_sid."))?,
Janis Danisevskisa75e2082020-10-07 16:44:26 -070092 perm,
93 key,
94 access_vector,
95 )
96 })
97}
98
Bram Bonné5d6c5102021-02-24 15:09:18 +010099/// This function checks whether a given tag corresponds to the access of device identifiers.
100pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
Janis Danisevskis83116e52021-04-06 13:36:58 -0700101 matches!(
102 tag,
103 Tag::ATTESTATION_ID_IMEI
104 | Tag::ATTESTATION_ID_MEID
105 | Tag::ATTESTATION_ID_SERIAL
106 | Tag::DEVICE_UNIQUE_ATTESTATION
107 )
Bram Bonné5d6c5102021-02-24 15:09:18 +0100108}
109
110/// This function checks whether the calling app has the Android permissions needed to attest device
Seth Moore66d9e902022-03-16 17:20:31 -0700111/// identifiers. It throws an error if the permissions cannot be verified or if the caller doesn't
112/// have the right permissions. Otherwise it returns silently.
Bram Bonné5d6c5102021-02-24 15:09:18 +0100113pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
Seth Moore66d9e902022-03-16 17:20:31 -0700114 check_android_permission("android.permission.READ_PRIVILEGED_PHONE_STATE")
115}
116
117/// This function checks whether the calling app has the Android permissions needed to attest the
118/// device-unique identifier. It throws an error if the permissions cannot be verified or if the
119/// caller doesn't have the right permissions. Otherwise it returns silently.
120pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> {
121 check_android_permission("android.permission.REQUEST_UNIQUE_ID_ATTESTATION")
122}
123
124fn check_android_permission(permission: &str) -> anyhow::Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700125 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
Bram Bonné5d6c5102021-02-24 15:09:18 +0100126 binder::get_interface("permission")?;
127
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700128 let binder_result = {
129 let _wp = watchdog::watch_millis(
130 "In check_device_attestation_permissions: calling checkPermission.",
131 500,
132 );
133 permission_controller.checkPermission(
Seth Moore66d9e902022-03-16 17:20:31 -0700134 permission,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700135 ThreadState::get_calling_pid(),
136 ThreadState::get_calling_uid() as i32,
137 )
138 };
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000139 let has_permissions =
140 map_binder_status(binder_result).context(ks_err!("checkPermission failed"))?;
Bram Bonné5d6c5102021-02-24 15:09:18 +0100141 match has_permissions {
142 true => Ok(()),
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000143 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS))
144 .context(ks_err!("caller does not have the permission to attest device IDs")),
Bram Bonné5d6c5102021-02-24 15:09:18 +0100145 }
146}
147
Janis Danisevskis04b02832020-10-26 09:21:40 -0700148/// Converts a set of key characteristics as returned from KeyMint into the internal
149/// representation of the keystore service.
Janis Danisevskis04b02832020-10-26 09:21:40 -0700150pub fn key_characteristics_to_internal(
Shawn Willdendbdac602021-01-12 22:35:16 -0700151 key_characteristics: Vec<KeyCharacteristics>,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800152) -> Vec<KeyParameter> {
Janis Danisevskis04b02832020-10-26 09:21:40 -0700153 key_characteristics
Janis Danisevskis04b02832020-10-26 09:21:40 -0700154 .into_iter()
Shawn Willdendbdac602021-01-12 22:35:16 -0700155 .flat_map(|aidl_key_char| {
156 let sec_level = aidl_key_char.securityLevel;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800157 aidl_key_char
158 .authorizations
159 .into_iter()
160 .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level))
Shawn Willdendbdac602021-01-12 22:35:16 -0700161 })
Janis Danisevskis04b02832020-10-26 09:21:40 -0700162 .collect()
163}
164
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800165/// This function can be used to upgrade key blobs on demand. The return value of
166/// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered,
167/// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called
168/// with the upgraded blob as argument. Then `km_op` is called a second time with the
169/// upgraded blob as argument. On success a tuple of the `km_op`s result and the
170/// optional upgraded blob is returned.
171pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>(
172 km_dev: &dyn IKeyMintDevice,
173 key_blob: &[u8],
174 upgrade_params: &[KmKeyParameter],
175 km_op: KmOp,
176 new_blob_handler: NewBlobHandler,
177) -> Result<(T, Option<Vec<u8>>)>
178where
179 KmOp: Fn(&[u8]) -> Result<T, Error>,
180 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
181{
182 match km_op(key_blob) {
183 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
184 let upgraded_blob = {
185 let _wp = watchdog::watch_millis(
186 "In utils::upgrade_keyblob_if_required_with: calling upgradeKey.",
187 500,
188 );
189 map_km_error(km_dev.upgradeKey(key_blob, upgrade_params))
190 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000191 .context(ks_err!("Upgrade failed."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800192
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000193 new_blob_handler(&upgraded_blob).context(ks_err!("calling new_blob_handler."))?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800194
195 km_op(&upgraded_blob)
196 .map(|v| (v, Some(upgraded_blob)))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000197 .context(ks_err!("Calling km_op after upgrade."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800198 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000199 r => r.map(|v| (v, None)).context(ks_err!("Calling km_op.")),
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800200 }
201}
202
Janis Danisevskis04b02832020-10-26 09:21:40 -0700203/// Converts a set of key characteristics from the internal representation into a set of
204/// Authorizations as they are used to convey key characteristics to the clients of keystore.
205pub fn key_parameters_to_authorizations(
206 parameters: Vec<crate::key_parameter::KeyParameter>,
207) -> Vec<Authorization> {
208 parameters.into_iter().map(|p| p.into_authorization()).collect()
209}
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000210
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000211/// This returns the current time (in milliseconds) as an instance of a monotonic clock,
212/// by invoking the system call since Rust does not support getting monotonic time instance
213/// as an integer.
214pub fn get_current_time_in_milliseconds() -> i64 {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000215 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
216 // Following unsafe block includes one system call to get monotonic time.
217 // Therefore, it is not considered harmful.
218 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000219 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000220}
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800221
Janis Danisevskis7a1cf382020-11-20 11:22:14 -0800222/// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
223/// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
224/// (android.security.apc) spec.
225pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
226 match rc {
227 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
228 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
229 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
230 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
231 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
232 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
233 _ => ApcResponseCode::SYSTEM_ERROR,
234 }
235}
236
237/// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
238/// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
239/// module (keystore2_apc_compat).
240pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
241 ApcCompatUiOptions {
242 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
243 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
244 }
245}
246
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800247/// AID offset for uid space partitioning.
Joel Galenson81a50f22021-07-29 15:39:10 -0700248pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800249
Paul Crowley44c02da2021-04-08 17:04:43 +0000250/// AID of the keystore process itself, used for keys that
251/// keystore generates for its own use.
Joel Galenson81a50f22021-07-29 15:39:10 -0700252pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
Paul Crowley44c02da2021-04-08 17:04:43 +0000253
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800254/// Extracts the android user from the given uid.
255pub fn uid_to_android_user(uid: u32) -> u32 {
Joel Galenson81a50f22021-07-29 15:39:10 -0700256 rustutils::users::multiuser_get_user_id(uid)
Janis Danisevskiscd1fb3a2020-12-01 09:20:09 -0800257}
Bram Bonné5d6c5102021-02-24 15:09:18 +0100258
John Wu16db29e2022-01-13 15:21:43 -0800259/// List all key aliases for a given domain + namespace.
260pub fn list_key_entries(
261 db: &mut KeystoreDB,
262 domain: Domain,
263 namespace: i64,
264) -> Result<Vec<KeyDescriptor>> {
265 let mut result = Vec::new();
266 result.append(
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800267 &mut LEGACY_IMPORTER
John Wu16db29e2022-01-13 15:21:43 -0800268 .list_uid(domain, namespace)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000269 .context(ks_err!("Trying to list legacy keys."))?,
John Wu16db29e2022-01-13 15:21:43 -0800270 );
271 result.append(
272 &mut db
273 .list(domain, namespace, KeyType::Client)
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000274 .context(ks_err!("Trying to list keystore database."))?,
John Wu16db29e2022-01-13 15:21:43 -0800275 );
276 result.sort_unstable();
277 result.dedup();
278 Ok(result)
279}
280
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700281/// This module provides helpers for simplified use of the watchdog module.
282#[cfg(feature = "watchdog")]
283pub mod watchdog {
284 pub use crate::watchdog::WatchPoint;
285 use crate::watchdog::Watchdog;
286 use lazy_static::lazy_static;
287 use std::sync::Arc;
288 use std::time::Duration;
289
290 lazy_static! {
291 /// A Watchdog thread, that can be used to create watch points.
292 static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
293 }
294
295 /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
296 pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
297 Watchdog::watch(&WD, id, Duration::from_millis(millis))
298 }
299
300 /// Like `watch_millis` but with a callback that is called every time a report
301 /// is printed about this watch point.
302 pub fn watch_millis_with(
303 id: &'static str,
304 millis: u64,
305 callback: impl Fn() -> String + Send + 'static,
306 ) -> Option<WatchPoint> {
307 Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
308 }
309}
310
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800311/// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
312pub trait AesGcm {
313 /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
314 /// and AES-GCM. The implementation provides the key material and selects
315 /// the implementation variant, e.g., AES128 or AES265.
316 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>;
317
318 /// Encrypts `data` and returns the ciphertext, the initialization vector `iv`
319 /// and AEAD tag `tag`. The implementation provides the key material and selects
320 /// the implementation variant, e.g., AES128 or AES265.
321 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>;
322}
323
324/// Marks an object as AES-GCM key.
325pub trait AesGcmKey {
326 /// Provides access to the raw key material.
327 fn key(&self) -> &[u8];
328}
329
330impl<T: AesGcmKey> AesGcm for T {
331 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000332 aes_gcm_decrypt(data, iv, tag, self.key()).context(ks_err!("Decryption failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800333 }
334
335 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000336 aes_gcm_encrypt(plaintext, self.key()).context(ks_err!("Encryption failed."))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800337 }
338}
339
Janis Danisevskis3d5a2142021-05-05 07:31:24 -0700340/// This module provides empty/noop implementations of the watch dog utility functions.
341#[cfg(not(feature = "watchdog"))]
342pub mod watchdog {
343 /// Noop watch point.
344 pub struct WatchPoint();
345 /// Sets a Noop watch point.
346 fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
347 None
348 }
349
350 pub fn watch_millis_with(
351 _: &'static str,
352 _: u64,
353 _: impl Fn() -> String + Send + 'static,
354 ) -> Option<WatchPoint> {
355 None
356 }
357}
358
Bram Bonné5d6c5102021-02-24 15:09:18 +0100359#[cfg(test)]
360mod tests {
361 use super::*;
362 use anyhow::Result;
363
364 #[test]
365 fn check_device_attestation_permissions_test() -> Result<()> {
366 check_device_attestation_permissions().or_else(|error| {
367 match error.root_cause().downcast_ref::<Error>() {
368 // Expected: the context for this test might not be allowed to attest device IDs.
369 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
370 // Other errors are unexpected
371 _ => Err(error),
372 }
373 })
374 }
375}