1*e1997b9aSAndroid Build Coastguard Worker // Copyright 2020, The Android Open Source Project
2*e1997b9aSAndroid Build Coastguard Worker //
3*e1997b9aSAndroid Build Coastguard Worker // Licensed under the Apache License, Version 2.0 (the "License");
4*e1997b9aSAndroid Build Coastguard Worker // you may not use this file except in compliance with the License.
5*e1997b9aSAndroid Build Coastguard Worker // You may obtain a copy of the License at
6*e1997b9aSAndroid Build Coastguard Worker //
7*e1997b9aSAndroid Build Coastguard Worker // http://www.apache.org/licenses/LICENSE-2.0
8*e1997b9aSAndroid Build Coastguard Worker //
9*e1997b9aSAndroid Build Coastguard Worker // Unless required by applicable law or agreed to in writing, software
10*e1997b9aSAndroid Build Coastguard Worker // distributed under the License is distributed on an "AS IS" BASIS,
11*e1997b9aSAndroid Build Coastguard Worker // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12*e1997b9aSAndroid Build Coastguard Worker // See the License for the specific language governing permissions and
13*e1997b9aSAndroid Build Coastguard Worker // limitations under the License.
14*e1997b9aSAndroid Build Coastguard Worker
15*e1997b9aSAndroid Build Coastguard Worker //! This module implements utility functions used by the Keystore 2.0 service
16*e1997b9aSAndroid Build Coastguard Worker //! implementation.
17*e1997b9aSAndroid Build Coastguard Worker
18*e1997b9aSAndroid Build Coastguard Worker use crate::error::{map_binder_status, map_km_error, Error, ErrorCode};
19*e1997b9aSAndroid Build Coastguard Worker use crate::key_parameter::KeyParameter;
20*e1997b9aSAndroid Build Coastguard Worker use crate::ks_err;
21*e1997b9aSAndroid Build Coastguard Worker use crate::permission;
22*e1997b9aSAndroid Build Coastguard Worker use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
23*e1997b9aSAndroid Build Coastguard Worker pub use crate::watchdog_helper::watchdog;
24*e1997b9aSAndroid Build Coastguard Worker use crate::{
25*e1997b9aSAndroid Build Coastguard Worker database::{KeyType, KeystoreDB},
26*e1997b9aSAndroid Build Coastguard Worker globals::LEGACY_IMPORTER,
27*e1997b9aSAndroid Build Coastguard Worker km_compat,
28*e1997b9aSAndroid Build Coastguard Worker raw_device::KeyMintDevice,
29*e1997b9aSAndroid Build Coastguard Worker };
30*e1997b9aSAndroid Build Coastguard Worker use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
31*e1997b9aSAndroid Build Coastguard Worker Algorithm::Algorithm, IKeyMintDevice::IKeyMintDevice, KeyCharacteristics::KeyCharacteristics,
32*e1997b9aSAndroid Build Coastguard Worker KeyParameter::KeyParameter as KmKeyParameter, KeyParameterValue::KeyParameterValue, Tag::Tag,
33*e1997b9aSAndroid Build Coastguard Worker };
34*e1997b9aSAndroid Build Coastguard Worker use android_os_permissions_aidl::aidl::android::os::IPermissionController;
35*e1997b9aSAndroid Build Coastguard Worker use android_security_apc::aidl::android::security::apc::{
36*e1997b9aSAndroid Build Coastguard Worker IProtectedConfirmation::{FLAG_UI_OPTION_INVERTED, FLAG_UI_OPTION_MAGNIFIED},
37*e1997b9aSAndroid Build Coastguard Worker ResponseCode::ResponseCode as ApcResponseCode,
38*e1997b9aSAndroid Build Coastguard Worker };
39*e1997b9aSAndroid Build Coastguard Worker use android_system_keystore2::aidl::android::system::keystore2::{
40*e1997b9aSAndroid Build Coastguard Worker Authorization::Authorization, Domain::Domain, KeyDescriptor::KeyDescriptor,
41*e1997b9aSAndroid Build Coastguard Worker ResponseCode::ResponseCode,
42*e1997b9aSAndroid Build Coastguard Worker };
43*e1997b9aSAndroid Build Coastguard Worker use anyhow::{Context, Result};
44*e1997b9aSAndroid Build Coastguard Worker use binder::{FromIBinder, StatusCode, Strong, ThreadState};
45*e1997b9aSAndroid Build Coastguard Worker use keystore2_apc_compat::{
46*e1997b9aSAndroid Build Coastguard Worker ApcCompatUiOptions, APC_COMPAT_ERROR_ABORTED, APC_COMPAT_ERROR_CANCELLED,
47*e1997b9aSAndroid Build Coastguard Worker APC_COMPAT_ERROR_IGNORED, APC_COMPAT_ERROR_OK, APC_COMPAT_ERROR_OPERATION_PENDING,
48*e1997b9aSAndroid Build Coastguard Worker APC_COMPAT_ERROR_SYSTEM_ERROR,
49*e1997b9aSAndroid Build Coastguard Worker };
50*e1997b9aSAndroid Build Coastguard Worker use keystore2_crypto::{aes_gcm_decrypt, aes_gcm_encrypt, ZVec};
51*e1997b9aSAndroid Build Coastguard Worker use log::{info, warn};
52*e1997b9aSAndroid Build Coastguard Worker use std::iter::IntoIterator;
53*e1997b9aSAndroid Build Coastguard Worker use std::thread::sleep;
54*e1997b9aSAndroid Build Coastguard Worker use std::time::Duration;
55*e1997b9aSAndroid Build Coastguard Worker
56*e1997b9aSAndroid Build Coastguard Worker #[cfg(test)]
57*e1997b9aSAndroid Build Coastguard Worker mod tests;
58*e1997b9aSAndroid Build Coastguard Worker
59*e1997b9aSAndroid Build Coastguard Worker /// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
60*e1997b9aSAndroid Build Coastguard Worker /// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
61*e1997b9aSAndroid Build Coastguard Worker pub const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
62*e1997b9aSAndroid Build Coastguard Worker
63*e1997b9aSAndroid Build Coastguard Worker /// This function uses its namesake in the permission module and in
64*e1997b9aSAndroid Build Coastguard Worker /// combination with with_calling_sid from the binder crate to check
65*e1997b9aSAndroid Build Coastguard Worker /// if the caller has the given keystore permission.
check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()>66*e1997b9aSAndroid Build Coastguard Worker pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
67*e1997b9aSAndroid Build Coastguard Worker ThreadState::with_calling_sid(|calling_sid| {
68*e1997b9aSAndroid Build Coastguard Worker permission::check_keystore_permission(
69*e1997b9aSAndroid Build Coastguard Worker calling_sid
70*e1997b9aSAndroid Build Coastguard Worker .ok_or_else(Error::sys)
71*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Cannot check permission without calling_sid."))?,
72*e1997b9aSAndroid Build Coastguard Worker perm,
73*e1997b9aSAndroid Build Coastguard Worker )
74*e1997b9aSAndroid Build Coastguard Worker })
75*e1997b9aSAndroid Build Coastguard Worker }
76*e1997b9aSAndroid Build Coastguard Worker
77*e1997b9aSAndroid Build Coastguard Worker /// This function uses its namesake in the permission module and in
78*e1997b9aSAndroid Build Coastguard Worker /// combination with with_calling_sid from the binder crate to check
79*e1997b9aSAndroid Build Coastguard Worker /// if the caller has the given grant permission.
check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()>80*e1997b9aSAndroid Build Coastguard Worker pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
81*e1997b9aSAndroid Build Coastguard Worker ThreadState::with_calling_sid(|calling_sid| {
82*e1997b9aSAndroid Build Coastguard Worker permission::check_grant_permission(
83*e1997b9aSAndroid Build Coastguard Worker ThreadState::get_calling_uid(),
84*e1997b9aSAndroid Build Coastguard Worker calling_sid
85*e1997b9aSAndroid Build Coastguard Worker .ok_or_else(Error::sys)
86*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Cannot check permission without calling_sid."))?,
87*e1997b9aSAndroid Build Coastguard Worker access_vec,
88*e1997b9aSAndroid Build Coastguard Worker key,
89*e1997b9aSAndroid Build Coastguard Worker )
90*e1997b9aSAndroid Build Coastguard Worker })
91*e1997b9aSAndroid Build Coastguard Worker }
92*e1997b9aSAndroid Build Coastguard Worker
93*e1997b9aSAndroid Build Coastguard Worker /// This function uses its namesake in the permission module and in
94*e1997b9aSAndroid Build Coastguard Worker /// combination with with_calling_sid from the binder crate to check
95*e1997b9aSAndroid Build Coastguard Worker /// if the caller has the given key permission.
check_key_permission( perm: KeyPerm, key: &KeyDescriptor, access_vector: &Option<KeyPermSet>, ) -> anyhow::Result<()>96*e1997b9aSAndroid Build Coastguard Worker pub fn check_key_permission(
97*e1997b9aSAndroid Build Coastguard Worker perm: KeyPerm,
98*e1997b9aSAndroid Build Coastguard Worker key: &KeyDescriptor,
99*e1997b9aSAndroid Build Coastguard Worker access_vector: &Option<KeyPermSet>,
100*e1997b9aSAndroid Build Coastguard Worker ) -> anyhow::Result<()> {
101*e1997b9aSAndroid Build Coastguard Worker ThreadState::with_calling_sid(|calling_sid| {
102*e1997b9aSAndroid Build Coastguard Worker permission::check_key_permission(
103*e1997b9aSAndroid Build Coastguard Worker ThreadState::get_calling_uid(),
104*e1997b9aSAndroid Build Coastguard Worker calling_sid
105*e1997b9aSAndroid Build Coastguard Worker .ok_or_else(Error::sys)
106*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Cannot check permission without calling_sid."))?,
107*e1997b9aSAndroid Build Coastguard Worker perm,
108*e1997b9aSAndroid Build Coastguard Worker key,
109*e1997b9aSAndroid Build Coastguard Worker access_vector,
110*e1997b9aSAndroid Build Coastguard Worker )
111*e1997b9aSAndroid Build Coastguard Worker })
112*e1997b9aSAndroid Build Coastguard Worker }
113*e1997b9aSAndroid Build Coastguard Worker
114*e1997b9aSAndroid Build Coastguard Worker /// This function checks whether a given tag corresponds to the access of device identifiers.
is_device_id_attestation_tag(tag: Tag) -> bool115*e1997b9aSAndroid Build Coastguard Worker pub fn is_device_id_attestation_tag(tag: Tag) -> bool {
116*e1997b9aSAndroid Build Coastguard Worker matches!(
117*e1997b9aSAndroid Build Coastguard Worker tag,
118*e1997b9aSAndroid Build Coastguard Worker Tag::ATTESTATION_ID_IMEI
119*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_MEID
120*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_SERIAL
121*e1997b9aSAndroid Build Coastguard Worker | Tag::DEVICE_UNIQUE_ATTESTATION
122*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_SECOND_IMEI
123*e1997b9aSAndroid Build Coastguard Worker )
124*e1997b9aSAndroid Build Coastguard Worker }
125*e1997b9aSAndroid Build Coastguard Worker
126*e1997b9aSAndroid Build Coastguard Worker /// This function checks whether the calling app has the Android permissions needed to attest device
127*e1997b9aSAndroid Build Coastguard Worker /// identifiers. It throws an error if the permissions cannot be verified or if the caller doesn't
128*e1997b9aSAndroid Build Coastguard Worker /// have the right permissions. Otherwise it returns silently.
check_device_attestation_permissions() -> anyhow::Result<()>129*e1997b9aSAndroid Build Coastguard Worker pub fn check_device_attestation_permissions() -> anyhow::Result<()> {
130*e1997b9aSAndroid Build Coastguard Worker check_android_permission(
131*e1997b9aSAndroid Build Coastguard Worker "android.permission.READ_PRIVILEGED_PHONE_STATE",
132*e1997b9aSAndroid Build Coastguard Worker Error::Km(ErrorCode::CANNOT_ATTEST_IDS),
133*e1997b9aSAndroid Build Coastguard Worker )
134*e1997b9aSAndroid Build Coastguard Worker }
135*e1997b9aSAndroid Build Coastguard Worker
136*e1997b9aSAndroid Build Coastguard Worker /// This function checks whether the calling app has the Android permissions needed to attest the
137*e1997b9aSAndroid Build Coastguard Worker /// device-unique identifier. It throws an error if the permissions cannot be verified or if the
138*e1997b9aSAndroid Build Coastguard Worker /// caller doesn't have the right permissions. Otherwise it returns silently.
check_unique_id_attestation_permissions() -> anyhow::Result<()>139*e1997b9aSAndroid Build Coastguard Worker pub fn check_unique_id_attestation_permissions() -> anyhow::Result<()> {
140*e1997b9aSAndroid Build Coastguard Worker check_android_permission(
141*e1997b9aSAndroid Build Coastguard Worker "android.permission.REQUEST_UNIQUE_ID_ATTESTATION",
142*e1997b9aSAndroid Build Coastguard Worker Error::Km(ErrorCode::CANNOT_ATTEST_IDS),
143*e1997b9aSAndroid Build Coastguard Worker )
144*e1997b9aSAndroid Build Coastguard Worker }
145*e1997b9aSAndroid Build Coastguard Worker
146*e1997b9aSAndroid Build Coastguard Worker /// This function checks whether the calling app has the Android permissions needed to manage
147*e1997b9aSAndroid Build Coastguard Worker /// users. Only callers that can manage users are allowed to get a list of apps affected
148*e1997b9aSAndroid Build Coastguard Worker /// by a user's SID changing.
149*e1997b9aSAndroid Build Coastguard Worker /// It throws an error if the permissions cannot be verified or if the caller doesn't
150*e1997b9aSAndroid Build Coastguard Worker /// have the right permissions. Otherwise it returns silently.
check_get_app_uids_affected_by_sid_permissions() -> anyhow::Result<()>151*e1997b9aSAndroid Build Coastguard Worker pub fn check_get_app_uids_affected_by_sid_permissions() -> anyhow::Result<()> {
152*e1997b9aSAndroid Build Coastguard Worker check_android_permission(
153*e1997b9aSAndroid Build Coastguard Worker "android.permission.MANAGE_USERS",
154*e1997b9aSAndroid Build Coastguard Worker Error::Km(ErrorCode::CANNOT_ATTEST_IDS),
155*e1997b9aSAndroid Build Coastguard Worker )
156*e1997b9aSAndroid Build Coastguard Worker }
157*e1997b9aSAndroid Build Coastguard Worker
158*e1997b9aSAndroid Build Coastguard Worker /// This function checks whether the calling app has the Android permission needed to dump
159*e1997b9aSAndroid Build Coastguard Worker /// Keystore state to logcat.
check_dump_permission() -> anyhow::Result<()>160*e1997b9aSAndroid Build Coastguard Worker pub fn check_dump_permission() -> anyhow::Result<()> {
161*e1997b9aSAndroid Build Coastguard Worker check_android_permission("android.permission.DUMP", Error::Rc(ResponseCode::PERMISSION_DENIED))
162*e1997b9aSAndroid Build Coastguard Worker }
163*e1997b9aSAndroid Build Coastguard Worker
check_android_permission(permission: &str, err: Error) -> anyhow::Result<()>164*e1997b9aSAndroid Build Coastguard Worker fn check_android_permission(permission: &str, err: Error) -> anyhow::Result<()> {
165*e1997b9aSAndroid Build Coastguard Worker let permission_controller: Strong<dyn IPermissionController::IPermissionController> =
166*e1997b9aSAndroid Build Coastguard Worker binder::get_interface("permission")?;
167*e1997b9aSAndroid Build Coastguard Worker
168*e1997b9aSAndroid Build Coastguard Worker let binder_result = {
169*e1997b9aSAndroid Build Coastguard Worker let _wp = watchdog::watch("check_android_permission: calling checkPermission");
170*e1997b9aSAndroid Build Coastguard Worker permission_controller.checkPermission(
171*e1997b9aSAndroid Build Coastguard Worker permission,
172*e1997b9aSAndroid Build Coastguard Worker ThreadState::get_calling_pid(),
173*e1997b9aSAndroid Build Coastguard Worker ThreadState::get_calling_uid() as i32,
174*e1997b9aSAndroid Build Coastguard Worker )
175*e1997b9aSAndroid Build Coastguard Worker };
176*e1997b9aSAndroid Build Coastguard Worker let has_permissions =
177*e1997b9aSAndroid Build Coastguard Worker map_binder_status(binder_result).context(ks_err!("checkPermission failed"))?;
178*e1997b9aSAndroid Build Coastguard Worker match has_permissions {
179*e1997b9aSAndroid Build Coastguard Worker true => Ok(()),
180*e1997b9aSAndroid Build Coastguard Worker false => Err(err).context(ks_err!("caller does not have the '{permission}' permission")),
181*e1997b9aSAndroid Build Coastguard Worker }
182*e1997b9aSAndroid Build Coastguard Worker }
183*e1997b9aSAndroid Build Coastguard Worker
184*e1997b9aSAndroid Build Coastguard Worker /// Converts a set of key characteristics as returned from KeyMint into the internal
185*e1997b9aSAndroid Build Coastguard Worker /// representation of the keystore service.
key_characteristics_to_internal( key_characteristics: Vec<KeyCharacteristics>, ) -> Vec<KeyParameter>186*e1997b9aSAndroid Build Coastguard Worker pub fn key_characteristics_to_internal(
187*e1997b9aSAndroid Build Coastguard Worker key_characteristics: Vec<KeyCharacteristics>,
188*e1997b9aSAndroid Build Coastguard Worker ) -> Vec<KeyParameter> {
189*e1997b9aSAndroid Build Coastguard Worker key_characteristics
190*e1997b9aSAndroid Build Coastguard Worker .into_iter()
191*e1997b9aSAndroid Build Coastguard Worker .flat_map(|aidl_key_char| {
192*e1997b9aSAndroid Build Coastguard Worker let sec_level = aidl_key_char.securityLevel;
193*e1997b9aSAndroid Build Coastguard Worker aidl_key_char
194*e1997b9aSAndroid Build Coastguard Worker .authorizations
195*e1997b9aSAndroid Build Coastguard Worker .into_iter()
196*e1997b9aSAndroid Build Coastguard Worker .map(move |aidl_kp| KeyParameter::new(aidl_kp.into(), sec_level))
197*e1997b9aSAndroid Build Coastguard Worker })
198*e1997b9aSAndroid Build Coastguard Worker .collect()
199*e1997b9aSAndroid Build Coastguard Worker }
200*e1997b9aSAndroid Build Coastguard Worker
201*e1997b9aSAndroid Build Coastguard Worker /// Import a keyblob that is of the format used by the software C++ KeyMint implementation. After
202*e1997b9aSAndroid Build Coastguard Worker /// successful import, invoke both the `new_blob_handler` and `km_op` closures. On success a tuple
203*e1997b9aSAndroid Build Coastguard Worker /// of the `km_op`s result and the optional upgraded blob is returned.
import_keyblob_and_perform_op<T, KmOp, NewBlobHandler>( km_dev: &dyn IKeyMintDevice, inner_keyblob: &[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<()>,204*e1997b9aSAndroid Build Coastguard Worker fn import_keyblob_and_perform_op<T, KmOp, NewBlobHandler>(
205*e1997b9aSAndroid Build Coastguard Worker km_dev: &dyn IKeyMintDevice,
206*e1997b9aSAndroid Build Coastguard Worker inner_keyblob: &[u8],
207*e1997b9aSAndroid Build Coastguard Worker upgrade_params: &[KmKeyParameter],
208*e1997b9aSAndroid Build Coastguard Worker km_op: KmOp,
209*e1997b9aSAndroid Build Coastguard Worker new_blob_handler: NewBlobHandler,
210*e1997b9aSAndroid Build Coastguard Worker ) -> Result<(T, Option<Vec<u8>>)>
211*e1997b9aSAndroid Build Coastguard Worker where
212*e1997b9aSAndroid Build Coastguard Worker KmOp: Fn(&[u8]) -> Result<T, Error>,
213*e1997b9aSAndroid Build Coastguard Worker NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
214*e1997b9aSAndroid Build Coastguard Worker {
215*e1997b9aSAndroid Build Coastguard Worker let (format, key_material, mut chars) =
216*e1997b9aSAndroid Build Coastguard Worker crate::sw_keyblob::export_key(inner_keyblob, upgrade_params)?;
217*e1997b9aSAndroid Build Coastguard Worker log::debug!(
218*e1997b9aSAndroid Build Coastguard Worker "importing {:?} key material (len={}) with original chars={:?}",
219*e1997b9aSAndroid Build Coastguard Worker format,
220*e1997b9aSAndroid Build Coastguard Worker key_material.len(),
221*e1997b9aSAndroid Build Coastguard Worker chars
222*e1997b9aSAndroid Build Coastguard Worker );
223*e1997b9aSAndroid Build Coastguard Worker let asymmetric = chars.iter().any(|kp| {
224*e1997b9aSAndroid Build Coastguard Worker kp.tag == Tag::ALGORITHM
225*e1997b9aSAndroid Build Coastguard Worker && (kp.value == KeyParameterValue::Algorithm(Algorithm::RSA)
226*e1997b9aSAndroid Build Coastguard Worker || (kp.value == KeyParameterValue::Algorithm(Algorithm::EC)))
227*e1997b9aSAndroid Build Coastguard Worker });
228*e1997b9aSAndroid Build Coastguard Worker
229*e1997b9aSAndroid Build Coastguard Worker // Combine the characteristics of the previous keyblob with the upgrade parameters (which might
230*e1997b9aSAndroid Build Coastguard Worker // include special things like APPLICATION_ID / APPLICATION_DATA).
231*e1997b9aSAndroid Build Coastguard Worker chars.extend_from_slice(upgrade_params);
232*e1997b9aSAndroid Build Coastguard Worker
233*e1997b9aSAndroid Build Coastguard Worker // Now filter out values from the existing keyblob that shouldn't be set on import, either
234*e1997b9aSAndroid Build Coastguard Worker // because they are per-operation parameter or because they are auto-added by KeyMint itself.
235*e1997b9aSAndroid Build Coastguard Worker let mut import_params: Vec<KmKeyParameter> = chars
236*e1997b9aSAndroid Build Coastguard Worker .into_iter()
237*e1997b9aSAndroid Build Coastguard Worker .filter(|kp| {
238*e1997b9aSAndroid Build Coastguard Worker !matches!(
239*e1997b9aSAndroid Build Coastguard Worker kp.tag,
240*e1997b9aSAndroid Build Coastguard Worker Tag::ORIGIN
241*e1997b9aSAndroid Build Coastguard Worker | Tag::ROOT_OF_TRUST
242*e1997b9aSAndroid Build Coastguard Worker | Tag::OS_VERSION
243*e1997b9aSAndroid Build Coastguard Worker | Tag::OS_PATCHLEVEL
244*e1997b9aSAndroid Build Coastguard Worker | Tag::UNIQUE_ID
245*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_CHALLENGE
246*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_APPLICATION_ID
247*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_BRAND
248*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_DEVICE
249*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_PRODUCT
250*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_SERIAL
251*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_IMEI
252*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_MEID
253*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_MANUFACTURER
254*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_MODEL
255*e1997b9aSAndroid Build Coastguard Worker | Tag::VENDOR_PATCHLEVEL
256*e1997b9aSAndroid Build Coastguard Worker | Tag::BOOT_PATCHLEVEL
257*e1997b9aSAndroid Build Coastguard Worker | Tag::DEVICE_UNIQUE_ATTESTATION
258*e1997b9aSAndroid Build Coastguard Worker | Tag::ATTESTATION_ID_SECOND_IMEI
259*e1997b9aSAndroid Build Coastguard Worker | Tag::NONCE
260*e1997b9aSAndroid Build Coastguard Worker | Tag::MAC_LENGTH
261*e1997b9aSAndroid Build Coastguard Worker | Tag::CERTIFICATE_SERIAL
262*e1997b9aSAndroid Build Coastguard Worker | Tag::CERTIFICATE_SUBJECT
263*e1997b9aSAndroid Build Coastguard Worker | Tag::CERTIFICATE_NOT_BEFORE
264*e1997b9aSAndroid Build Coastguard Worker | Tag::CERTIFICATE_NOT_AFTER
265*e1997b9aSAndroid Build Coastguard Worker )
266*e1997b9aSAndroid Build Coastguard Worker })
267*e1997b9aSAndroid Build Coastguard Worker .collect();
268*e1997b9aSAndroid Build Coastguard Worker
269*e1997b9aSAndroid Build Coastguard Worker // Now that any previous values have been removed, add any additional parameters that needed for
270*e1997b9aSAndroid Build Coastguard Worker // import. In particular, if we are generating/importing an asymmetric key, we need to make sure
271*e1997b9aSAndroid Build Coastguard Worker // that NOT_BEFORE and NOT_AFTER are present.
272*e1997b9aSAndroid Build Coastguard Worker if asymmetric {
273*e1997b9aSAndroid Build Coastguard Worker import_params.push(KmKeyParameter {
274*e1997b9aSAndroid Build Coastguard Worker tag: Tag::CERTIFICATE_NOT_BEFORE,
275*e1997b9aSAndroid Build Coastguard Worker value: KeyParameterValue::DateTime(0),
276*e1997b9aSAndroid Build Coastguard Worker });
277*e1997b9aSAndroid Build Coastguard Worker import_params.push(KmKeyParameter {
278*e1997b9aSAndroid Build Coastguard Worker tag: Tag::CERTIFICATE_NOT_AFTER,
279*e1997b9aSAndroid Build Coastguard Worker value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
280*e1997b9aSAndroid Build Coastguard Worker });
281*e1997b9aSAndroid Build Coastguard Worker }
282*e1997b9aSAndroid Build Coastguard Worker log::debug!("import parameters={import_params:?}");
283*e1997b9aSAndroid Build Coastguard Worker
284*e1997b9aSAndroid Build Coastguard Worker let creation_result = {
285*e1997b9aSAndroid Build Coastguard Worker let _wp = watchdog::watch(
286*e1997b9aSAndroid Build Coastguard Worker "utils::import_keyblob_and_perform_op: calling IKeyMintDevice::importKey",
287*e1997b9aSAndroid Build Coastguard Worker );
288*e1997b9aSAndroid Build Coastguard Worker map_km_error(km_dev.importKey(&import_params, format, &key_material, None))
289*e1997b9aSAndroid Build Coastguard Worker }
290*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Upgrade failed."))?;
291*e1997b9aSAndroid Build Coastguard Worker
292*e1997b9aSAndroid Build Coastguard Worker // Note that the importKey operation will produce key characteristics that may be different
293*e1997b9aSAndroid Build Coastguard Worker // than are already stored in Keystore's SQL database. In particular, the KeyMint
294*e1997b9aSAndroid Build Coastguard Worker // implementation will now mark the key as `Origin::IMPORTED` not `Origin::GENERATED`, and
295*e1997b9aSAndroid Build Coastguard Worker // the security level for characteristics will now be `TRUSTED_ENVIRONMENT` not `SOFTWARE`.
296*e1997b9aSAndroid Build Coastguard Worker //
297*e1997b9aSAndroid Build Coastguard Worker // However, the DB metadata still accurately reflects the original origin of the key, and
298*e1997b9aSAndroid Build Coastguard Worker // so we leave the values as-is (and so any `KeyInfo` retrieved in the Java layer will get the
299*e1997b9aSAndroid Build Coastguard Worker // same results before and after import).
300*e1997b9aSAndroid Build Coastguard Worker //
301*e1997b9aSAndroid Build Coastguard Worker // Note that this also applies to the `USAGE_COUNT_LIMIT` parameter -- if the key has already
302*e1997b9aSAndroid Build Coastguard Worker // been used, then the DB version of the parameter will be (and will continue to be) lower
303*e1997b9aSAndroid Build Coastguard Worker // than the original count bound to the keyblob. This means that Keystore's policing of
304*e1997b9aSAndroid Build Coastguard Worker // usage counts will continue where it left off.
305*e1997b9aSAndroid Build Coastguard Worker
306*e1997b9aSAndroid Build Coastguard Worker new_blob_handler(&creation_result.keyBlob).context(ks_err!("calling new_blob_handler."))?;
307*e1997b9aSAndroid Build Coastguard Worker
308*e1997b9aSAndroid Build Coastguard Worker km_op(&creation_result.keyBlob)
309*e1997b9aSAndroid Build Coastguard Worker .map(|v| (v, Some(creation_result.keyBlob)))
310*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Calling km_op after upgrade."))
311*e1997b9aSAndroid Build Coastguard Worker }
312*e1997b9aSAndroid Build Coastguard Worker
313*e1997b9aSAndroid Build Coastguard Worker /// Upgrade a keyblob then invoke both the `new_blob_handler` and the `km_op` closures. On success
314*e1997b9aSAndroid Build Coastguard Worker /// a tuple of the `km_op`s result and the optional upgraded blob is returned.
upgrade_keyblob_and_perform_op<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<()>,315*e1997b9aSAndroid Build Coastguard Worker fn upgrade_keyblob_and_perform_op<T, KmOp, NewBlobHandler>(
316*e1997b9aSAndroid Build Coastguard Worker km_dev: &dyn IKeyMintDevice,
317*e1997b9aSAndroid Build Coastguard Worker key_blob: &[u8],
318*e1997b9aSAndroid Build Coastguard Worker upgrade_params: &[KmKeyParameter],
319*e1997b9aSAndroid Build Coastguard Worker km_op: KmOp,
320*e1997b9aSAndroid Build Coastguard Worker new_blob_handler: NewBlobHandler,
321*e1997b9aSAndroid Build Coastguard Worker ) -> Result<(T, Option<Vec<u8>>)>
322*e1997b9aSAndroid Build Coastguard Worker where
323*e1997b9aSAndroid Build Coastguard Worker KmOp: Fn(&[u8]) -> Result<T, Error>,
324*e1997b9aSAndroid Build Coastguard Worker NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
325*e1997b9aSAndroid Build Coastguard Worker {
326*e1997b9aSAndroid Build Coastguard Worker let upgraded_blob = {
327*e1997b9aSAndroid Build Coastguard Worker let _wp = watchdog::watch(
328*e1997b9aSAndroid Build Coastguard Worker "utils::upgrade_keyblob_and_perform_op: calling IKeyMintDevice::upgradeKey.",
329*e1997b9aSAndroid Build Coastguard Worker );
330*e1997b9aSAndroid Build Coastguard Worker map_km_error(km_dev.upgradeKey(key_blob, upgrade_params))
331*e1997b9aSAndroid Build Coastguard Worker }
332*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Upgrade failed."))?;
333*e1997b9aSAndroid Build Coastguard Worker
334*e1997b9aSAndroid Build Coastguard Worker new_blob_handler(&upgraded_blob).context(ks_err!("calling new_blob_handler."))?;
335*e1997b9aSAndroid Build Coastguard Worker
336*e1997b9aSAndroid Build Coastguard Worker km_op(&upgraded_blob)
337*e1997b9aSAndroid Build Coastguard Worker .map(|v| (v, Some(upgraded_blob)))
338*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Calling km_op after upgrade."))
339*e1997b9aSAndroid Build Coastguard Worker }
340*e1997b9aSAndroid Build Coastguard Worker
341*e1997b9aSAndroid Build Coastguard Worker /// This function can be used to upgrade key blobs on demand. The return value of
342*e1997b9aSAndroid Build Coastguard Worker /// `km_op` is inspected and if ErrorCode::KEY_REQUIRES_UPGRADE is encountered,
343*e1997b9aSAndroid Build Coastguard Worker /// an attempt is made to upgrade the key blob. On success `new_blob_handler` is called
344*e1997b9aSAndroid Build Coastguard Worker /// with the upgraded blob as argument. Then `km_op` is called a second time with the
345*e1997b9aSAndroid Build Coastguard Worker /// upgraded blob as argument. On success a tuple of the `km_op`s result and the
346*e1997b9aSAndroid Build Coastguard Worker /// optional upgraded blob is returned.
upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>( km_dev: &dyn IKeyMintDevice, km_dev_version: i32, 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<()>,347*e1997b9aSAndroid Build Coastguard Worker pub fn upgrade_keyblob_if_required_with<T, KmOp, NewBlobHandler>(
348*e1997b9aSAndroid Build Coastguard Worker km_dev: &dyn IKeyMintDevice,
349*e1997b9aSAndroid Build Coastguard Worker km_dev_version: i32,
350*e1997b9aSAndroid Build Coastguard Worker key_blob: &[u8],
351*e1997b9aSAndroid Build Coastguard Worker upgrade_params: &[KmKeyParameter],
352*e1997b9aSAndroid Build Coastguard Worker km_op: KmOp,
353*e1997b9aSAndroid Build Coastguard Worker new_blob_handler: NewBlobHandler,
354*e1997b9aSAndroid Build Coastguard Worker ) -> Result<(T, Option<Vec<u8>>)>
355*e1997b9aSAndroid Build Coastguard Worker where
356*e1997b9aSAndroid Build Coastguard Worker KmOp: Fn(&[u8]) -> Result<T, Error>,
357*e1997b9aSAndroid Build Coastguard Worker NewBlobHandler: FnOnce(&[u8]) -> Result<()>,
358*e1997b9aSAndroid Build Coastguard Worker {
359*e1997b9aSAndroid Build Coastguard Worker match km_op(key_blob) {
360*e1997b9aSAndroid Build Coastguard Worker Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => upgrade_keyblob_and_perform_op(
361*e1997b9aSAndroid Build Coastguard Worker km_dev,
362*e1997b9aSAndroid Build Coastguard Worker key_blob,
363*e1997b9aSAndroid Build Coastguard Worker upgrade_params,
364*e1997b9aSAndroid Build Coastguard Worker km_op,
365*e1997b9aSAndroid Build Coastguard Worker new_blob_handler,
366*e1997b9aSAndroid Build Coastguard Worker ),
367*e1997b9aSAndroid Build Coastguard Worker Err(Error::Km(ErrorCode::INVALID_KEY_BLOB))
368*e1997b9aSAndroid Build Coastguard Worker if km_dev_version >= KeyMintDevice::KEY_MINT_V1 =>
369*e1997b9aSAndroid Build Coastguard Worker {
370*e1997b9aSAndroid Build Coastguard Worker // A KeyMint (not Keymaster via km_compat) device says that this is an invalid keyblob.
371*e1997b9aSAndroid Build Coastguard Worker //
372*e1997b9aSAndroid Build Coastguard Worker // This may be because the keyblob was created before an Android upgrade, and as part of
373*e1997b9aSAndroid Build Coastguard Worker // the device upgrade the underlying Keymaster/KeyMint implementation has been upgraded.
374*e1997b9aSAndroid Build Coastguard Worker //
375*e1997b9aSAndroid Build Coastguard Worker // If that's the case, there are three possible scenarios:
376*e1997b9aSAndroid Build Coastguard Worker if key_blob.starts_with(km_compat::KEYMASTER_BLOB_HW_PREFIX) {
377*e1997b9aSAndroid Build Coastguard Worker // 1) The keyblob was created in hardware by the km_compat C++ code, using a prior
378*e1997b9aSAndroid Build Coastguard Worker // Keymaster implementation, and wrapped.
379*e1997b9aSAndroid Build Coastguard Worker //
380*e1997b9aSAndroid Build Coastguard Worker // In this case, the keyblob will have the km_compat magic prefix, including the
381*e1997b9aSAndroid Build Coastguard Worker // marker that indicates that this was a hardware-backed key.
382*e1997b9aSAndroid Build Coastguard Worker //
383*e1997b9aSAndroid Build Coastguard Worker // The inner keyblob should still be recognized by the hardware implementation, so
384*e1997b9aSAndroid Build Coastguard Worker // strip the prefix and attempt a key upgrade.
385*e1997b9aSAndroid Build Coastguard Worker log::info!(
386*e1997b9aSAndroid Build Coastguard Worker "found apparent km_compat(Keymaster) HW blob, attempt strip-and-upgrade"
387*e1997b9aSAndroid Build Coastguard Worker );
388*e1997b9aSAndroid Build Coastguard Worker let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_HW_PREFIX.len()..];
389*e1997b9aSAndroid Build Coastguard Worker upgrade_keyblob_and_perform_op(
390*e1997b9aSAndroid Build Coastguard Worker km_dev,
391*e1997b9aSAndroid Build Coastguard Worker inner_keyblob,
392*e1997b9aSAndroid Build Coastguard Worker upgrade_params,
393*e1997b9aSAndroid Build Coastguard Worker km_op,
394*e1997b9aSAndroid Build Coastguard Worker new_blob_handler,
395*e1997b9aSAndroid Build Coastguard Worker )
396*e1997b9aSAndroid Build Coastguard Worker } else if keystore2_flags::import_previously_emulated_keys()
397*e1997b9aSAndroid Build Coastguard Worker && key_blob.starts_with(km_compat::KEYMASTER_BLOB_SW_PREFIX)
398*e1997b9aSAndroid Build Coastguard Worker {
399*e1997b9aSAndroid Build Coastguard Worker // 2) The keyblob was created in software by the km_compat C++ code because a prior
400*e1997b9aSAndroid Build Coastguard Worker // Keymaster implementation did not support ECDH (which was only added in KeyMint).
401*e1997b9aSAndroid Build Coastguard Worker //
402*e1997b9aSAndroid Build Coastguard Worker // In this case, the keyblob with have the km_compat magic prefix, but with the
403*e1997b9aSAndroid Build Coastguard Worker // marker that indicates that this was a software-emulated key.
404*e1997b9aSAndroid Build Coastguard Worker //
405*e1997b9aSAndroid Build Coastguard Worker // The inner keyblob should be in the format produced by the C++ reference
406*e1997b9aSAndroid Build Coastguard Worker // implementation of KeyMint. Extract the key material and import it into the
407*e1997b9aSAndroid Build Coastguard Worker // current KeyMint device.
408*e1997b9aSAndroid Build Coastguard Worker log::info!("found apparent km_compat(Keymaster) SW blob, attempt strip-and-import");
409*e1997b9aSAndroid Build Coastguard Worker let inner_keyblob = &key_blob[km_compat::KEYMASTER_BLOB_SW_PREFIX.len()..];
410*e1997b9aSAndroid Build Coastguard Worker import_keyblob_and_perform_op(
411*e1997b9aSAndroid Build Coastguard Worker km_dev,
412*e1997b9aSAndroid Build Coastguard Worker inner_keyblob,
413*e1997b9aSAndroid Build Coastguard Worker upgrade_params,
414*e1997b9aSAndroid Build Coastguard Worker km_op,
415*e1997b9aSAndroid Build Coastguard Worker new_blob_handler,
416*e1997b9aSAndroid Build Coastguard Worker )
417*e1997b9aSAndroid Build Coastguard Worker } else if let (true, km_compat::KeyBlob::Wrapped(inner_keyblob)) = (
418*e1997b9aSAndroid Build Coastguard Worker keystore2_flags::import_previously_emulated_keys(),
419*e1997b9aSAndroid Build Coastguard Worker km_compat::unwrap_keyblob(key_blob),
420*e1997b9aSAndroid Build Coastguard Worker ) {
421*e1997b9aSAndroid Build Coastguard Worker // 3) The keyblob was created in software by km_compat.rs because a prior KeyMint
422*e1997b9aSAndroid Build Coastguard Worker // implementation did not support a feature present in the current KeyMint spec.
423*e1997b9aSAndroid Build Coastguard Worker // (For example, a curve 25519 key created when the device only supported KeyMint
424*e1997b9aSAndroid Build Coastguard Worker // v1).
425*e1997b9aSAndroid Build Coastguard Worker //
426*e1997b9aSAndroid Build Coastguard Worker // In this case, the keyblob with have the km_compat.rs wrapper around it to
427*e1997b9aSAndroid Build Coastguard Worker // indicate that this was a software-emulated key.
428*e1997b9aSAndroid Build Coastguard Worker //
429*e1997b9aSAndroid Build Coastguard Worker // The inner keyblob should be in the format produced by the C++ reference
430*e1997b9aSAndroid Build Coastguard Worker // implementation of KeyMint. Extract the key material and import it into the
431*e1997b9aSAndroid Build Coastguard Worker // current KeyMint device.
432*e1997b9aSAndroid Build Coastguard Worker log::info!(
433*e1997b9aSAndroid Build Coastguard Worker "found apparent km_compat.rs(KeyMint) SW blob, attempt strip-and-import"
434*e1997b9aSAndroid Build Coastguard Worker );
435*e1997b9aSAndroid Build Coastguard Worker import_keyblob_and_perform_op(
436*e1997b9aSAndroid Build Coastguard Worker km_dev,
437*e1997b9aSAndroid Build Coastguard Worker inner_keyblob,
438*e1997b9aSAndroid Build Coastguard Worker upgrade_params,
439*e1997b9aSAndroid Build Coastguard Worker km_op,
440*e1997b9aSAndroid Build Coastguard Worker new_blob_handler,
441*e1997b9aSAndroid Build Coastguard Worker )
442*e1997b9aSAndroid Build Coastguard Worker } else {
443*e1997b9aSAndroid Build Coastguard Worker Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)).context(ks_err!("Calling km_op"))
444*e1997b9aSAndroid Build Coastguard Worker }
445*e1997b9aSAndroid Build Coastguard Worker }
446*e1997b9aSAndroid Build Coastguard Worker r => r.map(|v| (v, None)).context(ks_err!("Calling km_op.")),
447*e1997b9aSAndroid Build Coastguard Worker }
448*e1997b9aSAndroid Build Coastguard Worker }
449*e1997b9aSAndroid Build Coastguard Worker
450*e1997b9aSAndroid Build Coastguard Worker /// Converts a set of key characteristics from the internal representation into a set of
451*e1997b9aSAndroid Build Coastguard Worker /// 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>452*e1997b9aSAndroid Build Coastguard Worker pub fn key_parameters_to_authorizations(
453*e1997b9aSAndroid Build Coastguard Worker parameters: Vec<crate::key_parameter::KeyParameter>,
454*e1997b9aSAndroid Build Coastguard Worker ) -> Vec<Authorization> {
455*e1997b9aSAndroid Build Coastguard Worker parameters.into_iter().map(|p| p.into_authorization()).collect()
456*e1997b9aSAndroid Build Coastguard Worker }
457*e1997b9aSAndroid Build Coastguard Worker
458*e1997b9aSAndroid Build Coastguard Worker #[allow(clippy::unnecessary_cast)]
459*e1997b9aSAndroid Build Coastguard Worker /// This returns the current time (in milliseconds) as an instance of a monotonic clock,
460*e1997b9aSAndroid Build Coastguard Worker /// by invoking the system call since Rust does not support getting monotonic time instance
461*e1997b9aSAndroid Build Coastguard Worker /// as an integer.
get_current_time_in_milliseconds() -> i64462*e1997b9aSAndroid Build Coastguard Worker pub fn get_current_time_in_milliseconds() -> i64 {
463*e1997b9aSAndroid Build Coastguard Worker let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
464*e1997b9aSAndroid Build Coastguard Worker // SAFETY: The pointer is valid because it comes from a reference, and clock_gettime doesn't
465*e1997b9aSAndroid Build Coastguard Worker // retain it beyond the call.
466*e1997b9aSAndroid Build Coastguard Worker unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut current_time) };
467*e1997b9aSAndroid Build Coastguard Worker current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
468*e1997b9aSAndroid Build Coastguard Worker }
469*e1997b9aSAndroid Build Coastguard Worker
470*e1997b9aSAndroid Build Coastguard Worker /// Converts a response code as returned by the Android Protected Confirmation HIDL compatibility
471*e1997b9aSAndroid Build Coastguard Worker /// module (keystore2_apc_compat) into a ResponseCode as defined by the APC AIDL
472*e1997b9aSAndroid Build Coastguard Worker /// (android.security.apc) spec.
compat_2_response_code(rc: u32) -> ApcResponseCode473*e1997b9aSAndroid Build Coastguard Worker pub fn compat_2_response_code(rc: u32) -> ApcResponseCode {
474*e1997b9aSAndroid Build Coastguard Worker match rc {
475*e1997b9aSAndroid Build Coastguard Worker APC_COMPAT_ERROR_OK => ApcResponseCode::OK,
476*e1997b9aSAndroid Build Coastguard Worker APC_COMPAT_ERROR_CANCELLED => ApcResponseCode::CANCELLED,
477*e1997b9aSAndroid Build Coastguard Worker APC_COMPAT_ERROR_ABORTED => ApcResponseCode::ABORTED,
478*e1997b9aSAndroid Build Coastguard Worker APC_COMPAT_ERROR_OPERATION_PENDING => ApcResponseCode::OPERATION_PENDING,
479*e1997b9aSAndroid Build Coastguard Worker APC_COMPAT_ERROR_IGNORED => ApcResponseCode::IGNORED,
480*e1997b9aSAndroid Build Coastguard Worker APC_COMPAT_ERROR_SYSTEM_ERROR => ApcResponseCode::SYSTEM_ERROR,
481*e1997b9aSAndroid Build Coastguard Worker _ => ApcResponseCode::SYSTEM_ERROR,
482*e1997b9aSAndroid Build Coastguard Worker }
483*e1997b9aSAndroid Build Coastguard Worker }
484*e1997b9aSAndroid Build Coastguard Worker
485*e1997b9aSAndroid Build Coastguard Worker /// Converts the UI Options flags as defined by the APC AIDL (android.security.apc) spec into
486*e1997b9aSAndroid Build Coastguard Worker /// UI Options flags as defined by the Android Protected Confirmation HIDL compatibility
487*e1997b9aSAndroid Build Coastguard Worker /// module (keystore2_apc_compat).
ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions488*e1997b9aSAndroid Build Coastguard Worker pub fn ui_opts_2_compat(opt: i32) -> ApcCompatUiOptions {
489*e1997b9aSAndroid Build Coastguard Worker ApcCompatUiOptions {
490*e1997b9aSAndroid Build Coastguard Worker inverted: (opt & FLAG_UI_OPTION_INVERTED) != 0,
491*e1997b9aSAndroid Build Coastguard Worker magnified: (opt & FLAG_UI_OPTION_MAGNIFIED) != 0,
492*e1997b9aSAndroid Build Coastguard Worker }
493*e1997b9aSAndroid Build Coastguard Worker }
494*e1997b9aSAndroid Build Coastguard Worker
495*e1997b9aSAndroid Build Coastguard Worker /// AID offset for uid space partitioning.
496*e1997b9aSAndroid Build Coastguard Worker pub const AID_USER_OFFSET: u32 = rustutils::users::AID_USER_OFFSET;
497*e1997b9aSAndroid Build Coastguard Worker
498*e1997b9aSAndroid Build Coastguard Worker /// AID of the keystore process itself, used for keys that
499*e1997b9aSAndroid Build Coastguard Worker /// keystore generates for its own use.
500*e1997b9aSAndroid Build Coastguard Worker pub const AID_KEYSTORE: u32 = rustutils::users::AID_KEYSTORE;
501*e1997b9aSAndroid Build Coastguard Worker
502*e1997b9aSAndroid Build Coastguard Worker /// Extracts the android user from the given uid.
uid_to_android_user(uid: u32) -> u32503*e1997b9aSAndroid Build Coastguard Worker pub fn uid_to_android_user(uid: u32) -> u32 {
504*e1997b9aSAndroid Build Coastguard Worker rustutils::users::multiuser_get_user_id(uid)
505*e1997b9aSAndroid Build Coastguard Worker }
506*e1997b9aSAndroid Build Coastguard Worker
507*e1997b9aSAndroid Build Coastguard Worker /// Merges and filters two lists of key descriptors. The first input list, legacy_descriptors,
508*e1997b9aSAndroid Build Coastguard Worker /// is assumed to not be sorted or filtered. As such, all key descriptors in that list whose
509*e1997b9aSAndroid Build Coastguard Worker /// alias is less than, or equal to, start_past_alias (if provided) will be removed.
510*e1997b9aSAndroid Build Coastguard Worker /// This list will then be merged with the second list, db_descriptors. The db_descriptors list
511*e1997b9aSAndroid Build Coastguard Worker /// is assumed to be sorted and filtered so the output list will be sorted prior to returning.
512*e1997b9aSAndroid Build Coastguard Worker /// The returned value is a list of KeyDescriptor objects whose alias is greater than
513*e1997b9aSAndroid Build Coastguard Worker /// start_past_alias, sorted and de-duplicated.
merge_and_filter_key_entry_lists( legacy_descriptors: &[KeyDescriptor], db_descriptors: &[KeyDescriptor], start_past_alias: Option<&str>, ) -> Vec<KeyDescriptor>514*e1997b9aSAndroid Build Coastguard Worker fn merge_and_filter_key_entry_lists(
515*e1997b9aSAndroid Build Coastguard Worker legacy_descriptors: &[KeyDescriptor],
516*e1997b9aSAndroid Build Coastguard Worker db_descriptors: &[KeyDescriptor],
517*e1997b9aSAndroid Build Coastguard Worker start_past_alias: Option<&str>,
518*e1997b9aSAndroid Build Coastguard Worker ) -> Vec<KeyDescriptor> {
519*e1997b9aSAndroid Build Coastguard Worker let mut result: Vec<KeyDescriptor> =
520*e1997b9aSAndroid Build Coastguard Worker match start_past_alias {
521*e1997b9aSAndroid Build Coastguard Worker Some(past_alias) => legacy_descriptors
522*e1997b9aSAndroid Build Coastguard Worker .iter()
523*e1997b9aSAndroid Build Coastguard Worker .filter(|kd| {
524*e1997b9aSAndroid Build Coastguard Worker if let Some(alias) = &kd.alias {
525*e1997b9aSAndroid Build Coastguard Worker alias.as_str() > past_alias
526*e1997b9aSAndroid Build Coastguard Worker } else {
527*e1997b9aSAndroid Build Coastguard Worker false
528*e1997b9aSAndroid Build Coastguard Worker }
529*e1997b9aSAndroid Build Coastguard Worker })
530*e1997b9aSAndroid Build Coastguard Worker .cloned()
531*e1997b9aSAndroid Build Coastguard Worker .collect(),
532*e1997b9aSAndroid Build Coastguard Worker None => legacy_descriptors.to_vec(),
533*e1997b9aSAndroid Build Coastguard Worker };
534*e1997b9aSAndroid Build Coastguard Worker
535*e1997b9aSAndroid Build Coastguard Worker result.extend_from_slice(db_descriptors);
536*e1997b9aSAndroid Build Coastguard Worker result.sort_unstable();
537*e1997b9aSAndroid Build Coastguard Worker result.dedup();
538*e1997b9aSAndroid Build Coastguard Worker result
539*e1997b9aSAndroid Build Coastguard Worker }
540*e1997b9aSAndroid Build Coastguard Worker
estimate_safe_amount_to_return( domain: Domain, namespace: i64, start_past_alias: Option<&str>, key_descriptors: &[KeyDescriptor], response_size_limit: usize, ) -> usize541*e1997b9aSAndroid Build Coastguard Worker pub(crate) fn estimate_safe_amount_to_return(
542*e1997b9aSAndroid Build Coastguard Worker domain: Domain,
543*e1997b9aSAndroid Build Coastguard Worker namespace: i64,
544*e1997b9aSAndroid Build Coastguard Worker start_past_alias: Option<&str>,
545*e1997b9aSAndroid Build Coastguard Worker key_descriptors: &[KeyDescriptor],
546*e1997b9aSAndroid Build Coastguard Worker response_size_limit: usize,
547*e1997b9aSAndroid Build Coastguard Worker ) -> usize {
548*e1997b9aSAndroid Build Coastguard Worker let mut count = 0;
549*e1997b9aSAndroid Build Coastguard Worker let mut bytes: usize = 0;
550*e1997b9aSAndroid Build Coastguard Worker // Estimate the transaction size to avoid returning more items than what
551*e1997b9aSAndroid Build Coastguard Worker // could fit in a binder transaction.
552*e1997b9aSAndroid Build Coastguard Worker for kd in key_descriptors.iter() {
553*e1997b9aSAndroid Build Coastguard Worker // 4 bytes for the Domain enum
554*e1997b9aSAndroid Build Coastguard Worker // 8 bytes for the Namespace long.
555*e1997b9aSAndroid Build Coastguard Worker bytes += 4 + 8;
556*e1997b9aSAndroid Build Coastguard Worker // Size of the alias string. Includes 4 bytes for length encoding.
557*e1997b9aSAndroid Build Coastguard Worker if let Some(alias) = &kd.alias {
558*e1997b9aSAndroid Build Coastguard Worker bytes += 4 + alias.len();
559*e1997b9aSAndroid Build Coastguard Worker }
560*e1997b9aSAndroid Build Coastguard Worker // Size of the blob. Includes 4 bytes for length encoding.
561*e1997b9aSAndroid Build Coastguard Worker if let Some(blob) = &kd.blob {
562*e1997b9aSAndroid Build Coastguard Worker bytes += 4 + blob.len();
563*e1997b9aSAndroid Build Coastguard Worker }
564*e1997b9aSAndroid Build Coastguard Worker // The binder transaction size limit is 1M. Empirical measurements show
565*e1997b9aSAndroid Build Coastguard Worker // that the binder overhead is 60% (to be confirmed). So break after
566*e1997b9aSAndroid Build Coastguard Worker // 350KB and return a partial list.
567*e1997b9aSAndroid Build Coastguard Worker if bytes > response_size_limit {
568*e1997b9aSAndroid Build Coastguard Worker log::warn!(
569*e1997b9aSAndroid Build Coastguard Worker "{domain:?}:{namespace}: Key descriptors list ({} items after {start_past_alias:?}) \
570*e1997b9aSAndroid Build Coastguard Worker may exceed binder size, returning {count} items est. {bytes} bytes",
571*e1997b9aSAndroid Build Coastguard Worker key_descriptors.len(),
572*e1997b9aSAndroid Build Coastguard Worker );
573*e1997b9aSAndroid Build Coastguard Worker break;
574*e1997b9aSAndroid Build Coastguard Worker }
575*e1997b9aSAndroid Build Coastguard Worker count += 1;
576*e1997b9aSAndroid Build Coastguard Worker }
577*e1997b9aSAndroid Build Coastguard Worker count
578*e1997b9aSAndroid Build Coastguard Worker }
579*e1997b9aSAndroid Build Coastguard Worker
580*e1997b9aSAndroid Build Coastguard Worker /// Estimate for maximum size of a Binder response in bytes.
581*e1997b9aSAndroid Build Coastguard Worker pub(crate) const RESPONSE_SIZE_LIMIT: usize = 358400;
582*e1997b9aSAndroid Build Coastguard Worker
583*e1997b9aSAndroid Build Coastguard Worker /// List all key aliases for a given domain + namespace. whose alias is greater
584*e1997b9aSAndroid Build Coastguard Worker /// than start_past_alias (if provided).
list_key_entries( db: &mut KeystoreDB, domain: Domain, namespace: i64, start_past_alias: Option<&str>, ) -> Result<Vec<KeyDescriptor>>585*e1997b9aSAndroid Build Coastguard Worker pub fn list_key_entries(
586*e1997b9aSAndroid Build Coastguard Worker db: &mut KeystoreDB,
587*e1997b9aSAndroid Build Coastguard Worker domain: Domain,
588*e1997b9aSAndroid Build Coastguard Worker namespace: i64,
589*e1997b9aSAndroid Build Coastguard Worker start_past_alias: Option<&str>,
590*e1997b9aSAndroid Build Coastguard Worker ) -> Result<Vec<KeyDescriptor>> {
591*e1997b9aSAndroid Build Coastguard Worker let legacy_key_descriptors: Vec<KeyDescriptor> = LEGACY_IMPORTER
592*e1997b9aSAndroid Build Coastguard Worker .list_uid(domain, namespace)
593*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Trying to list legacy keys."))?;
594*e1997b9aSAndroid Build Coastguard Worker
595*e1997b9aSAndroid Build Coastguard Worker // The results from the database will be sorted and unique
596*e1997b9aSAndroid Build Coastguard Worker let db_key_descriptors: Vec<KeyDescriptor> = db
597*e1997b9aSAndroid Build Coastguard Worker .list_past_alias(domain, namespace, KeyType::Client, start_past_alias)
598*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Trying to list keystore database past alias."))?;
599*e1997b9aSAndroid Build Coastguard Worker
600*e1997b9aSAndroid Build Coastguard Worker let merged_key_entries = merge_and_filter_key_entry_lists(
601*e1997b9aSAndroid Build Coastguard Worker &legacy_key_descriptors,
602*e1997b9aSAndroid Build Coastguard Worker &db_key_descriptors,
603*e1997b9aSAndroid Build Coastguard Worker start_past_alias,
604*e1997b9aSAndroid Build Coastguard Worker );
605*e1997b9aSAndroid Build Coastguard Worker
606*e1997b9aSAndroid Build Coastguard Worker let safe_amount_to_return = estimate_safe_amount_to_return(
607*e1997b9aSAndroid Build Coastguard Worker domain,
608*e1997b9aSAndroid Build Coastguard Worker namespace,
609*e1997b9aSAndroid Build Coastguard Worker start_past_alias,
610*e1997b9aSAndroid Build Coastguard Worker &merged_key_entries,
611*e1997b9aSAndroid Build Coastguard Worker RESPONSE_SIZE_LIMIT,
612*e1997b9aSAndroid Build Coastguard Worker );
613*e1997b9aSAndroid Build Coastguard Worker Ok(merged_key_entries[..safe_amount_to_return].to_vec())
614*e1997b9aSAndroid Build Coastguard Worker }
615*e1997b9aSAndroid Build Coastguard Worker
616*e1997b9aSAndroid Build Coastguard Worker /// Count all key aliases for a given domain + namespace.
count_key_entries(db: &mut KeystoreDB, domain: Domain, namespace: i64) -> Result<i32>617*e1997b9aSAndroid Build Coastguard Worker pub fn count_key_entries(db: &mut KeystoreDB, domain: Domain, namespace: i64) -> Result<i32> {
618*e1997b9aSAndroid Build Coastguard Worker let legacy_keys = LEGACY_IMPORTER
619*e1997b9aSAndroid Build Coastguard Worker .list_uid(domain, namespace)
620*e1997b9aSAndroid Build Coastguard Worker .context(ks_err!("Trying to list legacy keys."))?;
621*e1997b9aSAndroid Build Coastguard Worker
622*e1997b9aSAndroid Build Coastguard Worker let num_keys_in_db = db.count_keys(domain, namespace, KeyType::Client)?;
623*e1997b9aSAndroid Build Coastguard Worker
624*e1997b9aSAndroid Build Coastguard Worker Ok((legacy_keys.len() + num_keys_in_db) as i32)
625*e1997b9aSAndroid Build Coastguard Worker }
626*e1997b9aSAndroid Build Coastguard Worker
627*e1997b9aSAndroid Build Coastguard Worker /// For params remove sensitive data before returning a string for logging
log_security_safe_params(params: &[KmKeyParameter]) -> Vec<KmKeyParameter>628*e1997b9aSAndroid Build Coastguard Worker pub fn log_security_safe_params(params: &[KmKeyParameter]) -> Vec<KmKeyParameter> {
629*e1997b9aSAndroid Build Coastguard Worker params
630*e1997b9aSAndroid Build Coastguard Worker .iter()
631*e1997b9aSAndroid Build Coastguard Worker .filter(|kp| (kp.tag != Tag::APPLICATION_ID && kp.tag != Tag::APPLICATION_DATA))
632*e1997b9aSAndroid Build Coastguard Worker .cloned()
633*e1997b9aSAndroid Build Coastguard Worker .collect::<Vec<KmKeyParameter>>()
634*e1997b9aSAndroid Build Coastguard Worker }
635*e1997b9aSAndroid Build Coastguard Worker
636*e1997b9aSAndroid Build Coastguard Worker /// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
637*e1997b9aSAndroid Build Coastguard Worker pub trait AesGcm {
638*e1997b9aSAndroid Build Coastguard Worker /// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
639*e1997b9aSAndroid Build Coastguard Worker /// and AES-GCM. The implementation provides the key material and selects
640*e1997b9aSAndroid Build Coastguard Worker /// the implementation variant, e.g., AES128 or AES265.
decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>641*e1997b9aSAndroid Build Coastguard Worker fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>;
642*e1997b9aSAndroid Build Coastguard Worker
643*e1997b9aSAndroid Build Coastguard Worker /// Encrypts `data` and returns the ciphertext, the initialization vector `iv`
644*e1997b9aSAndroid Build Coastguard Worker /// and AEAD tag `tag`. The implementation provides the key material and selects
645*e1997b9aSAndroid Build Coastguard Worker /// the implementation variant, e.g., AES128 or AES265.
encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>646*e1997b9aSAndroid Build Coastguard Worker fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>;
647*e1997b9aSAndroid Build Coastguard Worker }
648*e1997b9aSAndroid Build Coastguard Worker
649*e1997b9aSAndroid Build Coastguard Worker /// Marks an object as AES-GCM key.
650*e1997b9aSAndroid Build Coastguard Worker pub trait AesGcmKey {
651*e1997b9aSAndroid Build Coastguard Worker /// Provides access to the raw key material.
key(&self) -> &[u8]652*e1997b9aSAndroid Build Coastguard Worker fn key(&self) -> &[u8];
653*e1997b9aSAndroid Build Coastguard Worker }
654*e1997b9aSAndroid Build Coastguard Worker
655*e1997b9aSAndroid Build Coastguard Worker impl<T: AesGcmKey> AesGcm for T {
decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec>656*e1997b9aSAndroid Build Coastguard Worker fn decrypt(&self, data: &[u8], iv: &[u8], tag: &[u8]) -> Result<ZVec> {
657*e1997b9aSAndroid Build Coastguard Worker aes_gcm_decrypt(data, iv, tag, self.key()).context(ks_err!("Decryption failed"))
658*e1997b9aSAndroid Build Coastguard Worker }
659*e1997b9aSAndroid Build Coastguard Worker
encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)>660*e1997b9aSAndroid Build Coastguard Worker fn encrypt(&self, plaintext: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
661*e1997b9aSAndroid Build Coastguard Worker aes_gcm_encrypt(plaintext, self.key()).context(ks_err!("Encryption failed."))
662*e1997b9aSAndroid Build Coastguard Worker }
663*e1997b9aSAndroid Build Coastguard Worker }
664*e1997b9aSAndroid Build Coastguard Worker
retry_get_interface<T: FromIBinder + ?Sized>( name: &str, ) -> Result<Strong<T>, StatusCode>665*e1997b9aSAndroid Build Coastguard Worker pub(crate) fn retry_get_interface<T: FromIBinder + ?Sized>(
666*e1997b9aSAndroid Build Coastguard Worker name: &str,
667*e1997b9aSAndroid Build Coastguard Worker ) -> Result<Strong<T>, StatusCode> {
668*e1997b9aSAndroid Build Coastguard Worker let retry_count = if cfg!(early_vm) { 5 } else { 1 };
669*e1997b9aSAndroid Build Coastguard Worker
670*e1997b9aSAndroid Build Coastguard Worker let mut wait_time = Duration::from_secs(5);
671*e1997b9aSAndroid Build Coastguard Worker for i in 1..retry_count {
672*e1997b9aSAndroid Build Coastguard Worker match binder::get_interface(name) {
673*e1997b9aSAndroid Build Coastguard Worker Ok(res) => return Ok(res),
674*e1997b9aSAndroid Build Coastguard Worker Err(e) => {
675*e1997b9aSAndroid Build Coastguard Worker warn!("failed to get interface {name}. Retry {i}/{retry_count}: {e:?}");
676*e1997b9aSAndroid Build Coastguard Worker sleep(wait_time);
677*e1997b9aSAndroid Build Coastguard Worker wait_time *= 2;
678*e1997b9aSAndroid Build Coastguard Worker }
679*e1997b9aSAndroid Build Coastguard Worker }
680*e1997b9aSAndroid Build Coastguard Worker }
681*e1997b9aSAndroid Build Coastguard Worker if retry_count > 1 {
682*e1997b9aSAndroid Build Coastguard Worker info!("{retry_count}-th (last) retry to get interface: {name}");
683*e1997b9aSAndroid Build Coastguard Worker }
684*e1997b9aSAndroid Build Coastguard Worker binder::get_interface(name)
685*e1997b9aSAndroid Build Coastguard Worker }
686