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
18 use crate::error::{map_binder_status, map_km_error, Error, ErrorCode};
19 use crate::key_parameter::KeyParameter;
20 use crate::permission;
21 use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
22 use crate::{
23 database::{KeyType, KeystoreDB},
24 globals::LEGACY_IMPORTER,
25 };
26 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
27 IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics,
28 KeyParameter::KeyParameter as KmKeyParameter, Tag::Tag,
29 };
30 use android_os_permissions_aidl::aidl::android::os::IPermissionController;
31 use android_security_apc::aidl::android::security::apc::{
32 IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
33 ResponseCode::ResponseCode as ApcResponseCode,
34 };
35 use android_system_keystore2::aidl::android::system::keystore2::{
36 Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor,
37 };
38 use anyhow::{Context, Result};
39 use binder::{Strong, ThreadState};
40 use keystore2_apc_compat::{
41 ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
42 APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
43 APC_COMPAT_ERROR_SYSTEM_ERROR,
44 };
45 use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec};
46 use std::iter::IntoIterator;
47
48 /// This function uses its namesake in the permission module and in
49 /// combination with with_calling_sid from the binder crate to check
50 /// if the caller has the given keystore permission.
check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()>51 pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
52 ThreadState::with_calling_sid(|calling_sid| {
53 permission::check_keystore_permission(
54 calling_sid.ok_or_else(Error::sys).context(
55 "In check_keystore_permission: Cannot check permission without calling_sid.",
56 )?,
57 perm,
58 )
59 })
60 }
61
62 /// This function uses its namesake in the permission module and in
63 /// combination with with_calling_sid from the binder crate to check
64 /// if the caller has the given grant permission.
check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()>65 pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
66 ThreadState::with_calling_sid(|calling_sid| {
67 permission::check_grant_permission(
68 calling_sid.ok_or_else(Error::sys).context(
69 "In check_grant_permission: Cannot check permission without calling_sid.",
70 )?,
71 access_vec,
72 key,
73 )
74 })
75 }
76
77 /// This function uses its namesake in the permission module and in
78 /// combination with with_calling_sid from the binder crate to check
79 /// if the caller has the given key permission.
check_key_permission( perm: KeyPerm, key: &KeyDescriptor, access_vector: &Option<KeyPermSet>, ) -> anyhow::Result<()>80 pub fn check_key_permission(
81 perm: KeyPerm,
82 key: &KeyDescriptor,
83 access_vector: &Option<KeyPermSet>,
84 ) -> anyhow::Result<()> {
85 ThreadState::with_calling_sid(|calling_sid| {
86 permission::check_key_permission(
87 ThreadState::get_calling_uid(),
88 calling_sid
89 .ok_or_else(Error::sys)
90 .context("In check_key_permission: Cannot check permission without calling_sid.")?,
91 perm,
92 key,
93 access_vector,
94 )
95 })
96 }
97
98 /// This function checks whether a given tag corresponds to the access of device identifiers.
is_device_id_attestation_tag(tag: Tag) -> bool99 pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
100 matches!(
101 tag,
102 Tag::ATTESTATION_ID_IMEI
103 | Tag::ATTESTATION_ID_MEID
104 | Tag::ATTESTATION_ID_SERIAL
105 | Tag::DEVICE_UNIQUE_ATTESTATION
106 )
107 }
108
109 /// This function checks whether the calling app has the Android permissions needed to attest device
110 /// identifiers. It throws an error if the permissions cannot be verified or if the caller doesn't
111 /// have the right permissions. Otherwise it returns silently.
check_device_attestation_permissions() -> anyhow::Result<()>112 pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
113 check_android_permission("android.permission.READ_PRIVILEGED_PHONE_STATE")
114 }
115
116 /// This function checks whether the calling app has the Android permissions needed to attest the
117 /// device-unique identifier. It throws an error if the permissions cannot be verified or if the
118 /// caller doesn't have the right permissions. Otherwise it returns silently.
check_unique_id_attestation_permissions() -> anyhow::Result<()>119 pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> {
120 check_android_permission("android.permission.REQUEST_UNIQUE_ID_ATTESTATION")
121 }
122
check_android_permission(permission: &str) -> anyhow::Result<()>123 fn check_android_permission(permission: &str) -> anyhow::Result<()> {
124 let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
125 binder::get_interface("permission")?;
126
127 let binder_result = {
128 let _wp = watchdog::watch_millis(
129 "In check_device_attestation_permissions: calling checkPermission.",
130 500,
131 );
132 permission_controller.checkPermission(
133 permission,
134 ThreadState::get_calling_pid(),
135 ThreadState::get_calling_uid() as i32,
136 )
137 };
138 let has_permissions = map_binder_status(binder_result)
139 .context("In check_device_attestation_permissions: checkPermission failed")?;
140 match has_permissions {
141 true => Ok(()),
142 false => Err(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)).context(concat!(
143 "In check_device_attestation_permissions: ",
144 "caller does not have the permission to attest device IDs"
145 )),
146 }
147 }
148
149 /// Converts a set of key characteristics as returned from KeyMint into the internal
150 /// representation of the keystore service.
key_characteristics_to_internal( key_characteristics: Vec<KeyCharacteristics>, ) -> Vec<KeyParameter>151 pub fn key_characteristics_to_internal(
152 key_characteristics: Vec<KeyCharacteristics>,
153 ) -> Vec<KeyParameter> {
154 key_characteristics
155 .into_iter()
156 .flat_map(|aidl_key_char| {
157 let sec_level = aidl_key_char.securityLevel;
158 aidl_key_char
159 .authorizations
160 .into_iter()
161 .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level))
162 })
163 .collect()
164 }
165
166 /// This function can be used to upgrade key blobs on demand. The return value of
167 /// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered,
168 /// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called
169 /// with the upgraded blob as argument. Then `km_op` is called a second time with the
170 /// upgraded blob as argument. On success a tuple of the `km_op`s result and the
171 /// optional upgraded blob is returned.
upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>( km_dev: &dyn IKeyMintDevice, key_blob: &[u8], upgrade_params: &[KmKeyParameter], km_op: KmOp, new_blob_handler: NewBlobHandler, ) -> Result<(T, Option<Vec<u8>>)> where KmOp: Fn(&[u8]) -> Result<T, Error>, NewBlobHandler: FnOnce(&[u8]) -> Result<()>,172 pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>(
173 km_dev: &dyn IKeyMintDevice,
174 key_blob: &[u8],
175 upgrade_params: &[KmKeyParameter],
176 km_op: KmOp,
177 new_blob_handler: NewBlobHandler,
178 ) -> Result<(T, Option<Vec<u8>>)>
179 where
180 KmOp: Fn(&[u8]) -> Result<T, Error>,
181 NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
182 {
183 match km_op(key_blob) {
184 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
185 let upgraded_blob = {
186 let _wp = watchdog::watch_millis(
187 "In utils::upgrade_keyblob_if_required_with: calling upgradeKey.",
188 500,
189 );
190 map_km_error(km_dev.upgradeKey(key_blob, upgrade_params))
191 }
192 .context("In utils::upgrade_keyblob_if_required_with: Upgrade failed.")?;
193
194 new_blob_handler(&upgraded_blob)
195 .context("In utils::upgrade_keyblob_if_required_with: calling new_blob_handler.")?;
196
197 km_op(&upgraded_blob)
198 .map(|v| (v, Some(upgraded_blob)))
199 .context("In utils::upgrade_keyblob_if_required_with: Calling km_op after upgrade.")
200 }
201 r => r
202 .map(|v| (v, None))
203 .context("In utils::upgrade_keyblob_if_required_with: Calling km_op."),
204 }
205 }
206
207 /// Converts a set of key characteristics from the internal representation into a set of
208 /// Authorizations as they are used to convey key characteristics to the clients of keystore.
key_parameters_to_authorizations( parameters: Vec<crate::key_parameter::KeyParameter>, ) -> Vec<Authorization>209 pub fn key_parameters_to_authorizations(
210 parameters: Vec<crate::key_parameter::KeyParameter>,
211 ) -> Vec<Authorization> {
212 parameters.into_iter().map(|p| p.into_authorization()).collect()
213 }
214
215 /// This returns the current time (in milliseconds) as an instance of a monotonic clock,
216 /// by invoking the system call since Rust does not support getting monotonic time instance
217 /// as an integer.
get_current_time_in_milliseconds() -> i64218 pub fn get_current_time_in_milliseconds() -> i64 {
219 let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
220 // Following unsafe block includes one system call to get monotonic time.
221 // Therefore, it is not considered harmful.
222 unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
223 current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
224 }
225
226 /// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
227 /// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
228 /// (android.security.apc) spec.
compat_2_response_code(rc: u32) -> ApcResponseCode229 pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
230 match rc {
231 APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
232 APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
233 APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
234 APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
235 APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
236 APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
237 _ => ApcResponseCode::SYSTEM_ERROR,
238 }
239 }
240
241 /// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
242 /// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
243 /// module (keystore2_apc_compat).
ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions244 pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
245 ApcCompatUiOptions {
246 inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
247 magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
248 }
249 }
250
251 /// AID offset for uid space partitioning.
252 pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
253
254 /// AID of the keystore process itself, used for keys that
255 /// keystore generates for its own use.
256 pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
257
258 /// Extracts the android user from the given uid.
uid_to_android_user(uid: u32) -> u32259 pub fn uid_to_android_user(uid: u32) -> u32 {
260 rustutils::users::multiuser_get_user_id(uid)
261 }
262
263 /// List all key aliases for a given domain + namespace.
list_key_entries( db: &mut KeystoreDB, domain: Domain, namespace: i64, ) -> Result<Vec<KeyDescriptor>>264 pub fn list_key_entries(
265 db: &mut KeystoreDB,
266 domain: Domain,
267 namespace: i64,
268 ) -> Result<Vec<KeyDescriptor>> {
269 let mut result = Vec::new();
270 result.append(
271 &mut LEGACY_IMPORTER
272 .list_uid(domain, namespace)
273 .context("In list_key_entries: Trying to list legacy keys.")?,
274 );
275 result.append(
276 &mut db
277 .list(domain, namespace, KeyType::Client)
278 .context("In list_key_entries: Trying to list keystore database.")?,
279 );
280 result.sort_unstable();
281 result.dedup();
282
283 let mut items_to_return = 0;
284 let mut returned_bytes: usize = 0;
285 const RESPONSE_SIZE_LIMIT: usize = 358400;
286 // Estimate the transaction size to avoid returning more items than what
287 // could fit in a binder transaction.
288 for kd in result.iter() {
289 // 4 bytes for the Domain enum
290 // 8 bytes for the Namespace long.
291 returned_bytes += 4 + 8;
292 // Size of the alias string. Includes 4 bytes for length encoding.
293 if let Some(alias) = &kd.alias {
294 returned_bytes += 4 + alias.len();
295 }
296 // Size of the blob. Includes 4 bytes for length encoding.
297 if let Some(blob) = &kd.blob {
298 returned_bytes += 4 + blob.len();
299 }
300 // The binder transaction size limit is 1M. Empirical measurements show
301 // that the binder overhead is 60% (to be confirmed). So break after
302 // 350KB and return a partial list.
303 if returned_bytes > RESPONSE_SIZE_LIMIT {
304 log::warn!(
305 "Key descriptors list ({} items) may exceed binder \
306 size, returning {} items est {} bytes.",
307 result.len(),
308 items_to_return,
309 returned_bytes
310 );
311 break;
312 }
313 items_to_return += 1;
314 }
315 Ok(result[..items_to_return].to_vec())
316 }
317
318 /// This module provides helpers for simplified use of the watchdog module.
319 #[cfg(feature = "watchdog")]
320 pub mod watchdog {
321 pub use crate::watchdog::WatchPoint;
322 use crate::watchdog::Watchdog;
323 use lazy_static::lazy_static;
324 use std::sync::Arc;
325 use std::time::Duration;
326
327 lazy_static! {
328 /// A Watchdog thread, that can be used to create watch points.
329 static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
330 }
331
332 /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint>333 pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
334 Watchdog::watch(&WD, id, Duration::from_millis(millis))
335 }
336
337 /// Like `watch_millis` but with a callback that is called every time a report
338 /// is printed about this watch point.
watch_millis_with( id: &'static str, millis: u64, callback: impl Fn() -> String + Send + 'static, ) -> Option<WatchPoint>339 pub fn watch_millis_with(
340 id: &'static str,
341 millis: u64,
342 callback: impl Fn() -> String + Send + 'static,
343 ) -> Option<WatchPoint> {
344 Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
345 }
346 }
347
348 /// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
349 pub trait AesGcm {
350 /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
351 /// and AES-GCM. The implementation provides the key material and selects
352 /// the implementation variant, e.g., AES128 or AES265.
decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>353 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>;
354
355 /// Encrypts `data` and returns the ciphertext, the initialization vector `iv`
356 /// and AEAD tag `tag`. The implementation provides the key material and selects
357 /// the implementation variant, e.g., AES128 or AES265.
encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>358 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>;
359 }
360
361 /// Marks an object as AES-GCM key.
362 pub trait AesGcmKey {
363 /// Provides access to the raw key material.
key(&self) -> &[u8]364 fn key(&self) -> &[u8];
365 }
366
367 impl<T: AesGcmKey> AesGcm for T {
decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>368 fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
369 aes_gcm_decrypt(data, iv, tag, self.key())
370 .context("In AesGcm<T>::decrypt: Decryption failed")
371 }
372
encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>373 fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
374 aes_gcm_encrypt(plaintext, self.key()).context("In AesGcm<T>::encrypt: Encryption failed.")
375 }
376 }
377
378 /// This module provides empty/noop implementations of the watch dog utility functions.
379 #[cfg(not(feature = "watchdog"))]
380 pub mod watchdog {
381 /// Noop watch point.
382 pub struct WatchPoint();
383 /// Sets a Noop watch point.
watch_millis(_: &'static str, _: u64) -> Option<WatchPoint>384 fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
385 None
386 }
387
watch_millis_with( _: &'static str, _: u64, _: impl Fn() -> String + Send + 'static, ) -> Option<WatchPoint>388 pub fn watch_millis_with(
389 _: &'static str,
390 _: u64,
391 _: impl Fn() -> String + Send + 'static,
392 ) -> Option<WatchPoint> {
393 None
394 }
395 }
396
397 #[cfg(test)]
398 mod tests {
399 use super::*;
400 use anyhow::Result;
401
402 #[test]
check_device_attestation_permissions_test() -> Result<()>403 fn check_device_attestation_permissions_test() -> Result<()> {
404 check_device_attestation_permissions().or_else(|error| {
405 match error.root_cause().downcast_ref::<Error>() {
406 // Expected: the context for this test might not be allowed to attest device IDs.
407 Some(Error::Km(ErrorCode::CANNOT_ATTEST_IDS)) => Ok(()),
408 // Other errors are unexpected
409 _ => Err(error),
410 }
411 })
412 }
413 }
414