blob: b928fb0946c1a2ff98155d57076b6dadb3ae2efd [file] [log] [blame]
Janis Danisevskis1af91262020-08-10 14:58:08 -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
Janis Danisevskis1af91262020-08-10 14:58:08 -070015//! This crate implements the IKeystoreSecurityLevel interface.
16
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070017use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
Pavel Grafovf45034a2021-05-12 22:35:45 +010018use crate::audit_log::{
19 log_key_deleted, log_key_generated, log_key_imported, log_key_integrity_violation,
20};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080021use crate::database::{BlobInfo, CertificateInfo, KeyIdGuard};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070022use crate::error::{self, map_km_error, map_or_log_err, Error, ErrorCode};
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080023use crate::globals::{DB, ENFORCEMENTS, LEGACY_IMPORTER, SUPER_KEY};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070024use crate::key_parameter::KeyParameter as KsKeyParam;
25use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000026use crate::ks_err;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000027use crate::metrics_store::log_key_creation_event_stats;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070028use crate::remote_provisioning::RemProvState;
Tri Vob5e43d12022-12-21 08:54:14 -080029use crate::rkpd_client::store_rkpd_attestation_key;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070030use crate::super_key::{KeyBlob, SuperKeyManager};
31use crate::utils::{
Seth Moore66d9e902022-03-16 17:20:31 -070032 check_device_attestation_permissions, check_key_permission,
33 check_unique_id_attestation_permissions, is_device_id_attestation_tag,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070034 key_characteristics_to_internal, uid_to_android_user, watchdog as wd,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070035};
36use crate::{
37 database::{
38 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
39 KeyMetaEntry, KeyType, SubComponentType, Uuid,
40 },
41 operation::KeystoreOperation,
42 operation::LoggingInfo,
43 operation::OperationDb,
44 permission::KeyPerm,
45};
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070046use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
Shawn Willden708744a2020-12-11 13:05:27 +000047use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070048 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070049 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
50 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080051 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
52 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070053};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000054use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070055use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070056 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
Janis Danisevskisb2434d02021-04-20 12:49:27 -070057 Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
58 IKeystoreOperation::IKeystoreOperation, IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070059 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000060 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, ResponseCode::ResponseCode,
Janis Danisevskis1af91262020-08-10 14:58:08 -070061};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080062use anyhow::{anyhow, Context, Result};
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000063use std::convert::TryInto;
64use std::time::SystemTime;
Janis Danisevskis1af91262020-08-10 14:58:08 -070065
66/// Implementation of the IKeystoreSecurityLevel Interface.
67pub struct KeystoreSecurityLevel {
68 security_level: SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070069 keymint: Strong<dyn IKeyMintDevice>,
Max Bires8e93d2b2021-01-14 13:17:59 -080070 hw_info: KeyMintHardwareInfo,
71 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070072 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080073 rem_prov_state: RemProvState,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070074 id_rotation_state: IdRotationState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070075}
76
Janis Danisevskis1af91262020-08-10 14:58:08 -070077// Blob of 32 zeroes used as empty masking key.
78static ZERO_BLOB_32: &[u8] = &[0; 32];
79
Janis Danisevskis2c084012021-01-31 22:23:17 -080080// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
81// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
82const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
83
Janis Danisevskis1af91262020-08-10 14:58:08 -070084impl KeystoreSecurityLevel {
85 /// Creates a new security level instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +000086 /// BnKeystoreSecurityLevel proxy object. It also enables
87 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070088 /// we need it for checking keystore permissions.
89 pub fn new_native_binder(
90 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070091 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080092 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080093 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000094 .context(ks_err!("KeystoreSecurityLevel::new_native_binder."))?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000095 let result = BnKeystoreSecurityLevel::new_binder(
96 Self {
97 security_level,
98 keymint: dev,
99 hw_info,
100 km_uuid,
101 operation_db: OperationDb::new(),
102 rem_prov_state: RemProvState::new(security_level, km_uuid),
103 id_rotation_state,
104 },
105 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
106 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800107 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700108 }
109
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700110 fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
111 let sec_level = self.security_level;
112 wd::watch_millis_with(id, millis, move || format!("SecurityLevel {:?}", sec_level))
113 }
114
Janis Danisevskis1af91262020-08-10 14:58:08 -0700115 fn store_new_key(
116 &self,
117 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700118 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000119 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000120 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700121 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700122 let KeyCreationResult {
123 keyBlob: key_blob,
124 keyCharacteristics: key_characteristics,
125 certificateChain: mut certificate_chain,
126 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700127
Max Bires8e93d2b2021-01-14 13:17:59 -0800128 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700129 match certificate_chain.len() {
130 0 => None,
131 _ => Some(certificate_chain.remove(0).encodedCertificate),
132 },
133 match certificate_chain.len() {
134 0 => None,
135 _ => Some(
136 certificate_chain
137 .iter()
Chariseea1e1c482022-02-26 01:26:35 +0000138 .flat_map(|c| c.encodedCertificate.iter())
Shawn Willdendbdac602021-01-12 22:35:16 -0700139 .copied()
140 .collect(),
141 ),
142 },
143 );
144
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000145 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
146
147 key_parameters.push(KsKeyParam::new(
148 KsKeyParamValue::UserID(user_id as i32),
149 SecurityLevel::SOFTWARE,
150 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700151
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000152 let creation_date = DateTime::now().context(ks_err!("Trying to make creation time."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800153
Janis Danisevskis1af91262020-08-10 14:58:08 -0700154 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800155 Domain::BLOB => KeyDescriptor {
156 domain: Domain::BLOB,
157 blob: Some(key_blob.to_vec()),
158 ..Default::default()
159 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700160 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800161 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800162 let mut db = db.borrow_mut();
163
164 let (key_blob, mut blob_metadata) = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800165 .read()
166 .unwrap()
Satya Tangirala60671e32021-03-04 16:12:19 -0800167 .handle_super_encryption_on_key_init(
168 &mut db,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800169 &LEGACY_IMPORTER,
Satya Tangirala60671e32021-03-04 16:12:19 -0800170 &(key.domain),
171 &key_parameters,
172 flags,
173 user_id,
174 &key_blob,
175 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000176 .context(ks_err!("Failed to handle super encryption."))?;
Satya Tangirala60671e32021-03-04 16:12:19 -0800177
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800178 let mut key_metadata = KeyMetaData::new();
179 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800180 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800181
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800182 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800183 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800184 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700185 KeyType::Client,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800186 &key_parameters,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800187 &BlobInfo::new(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800188 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800189 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800190 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800191 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000192 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700193 Ok(KeyDescriptor {
194 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800195 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700196 ..Default::default()
197 })
198 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000199 .context(ks_err!())?,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700200 };
201
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700202 Ok(KeyMetadata {
203 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700204 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800205 certificate: cert_info.take_cert(),
206 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700207 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800208 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700209 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700210 }
211
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700212 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700213 &self,
214 key: &KeyDescriptor,
215 operation_parameters: &[KeyParameter],
216 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700217 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700218 let caller_uid = ThreadState::get_calling_uid();
219 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
220 // so that we can use it by reference like the blob provided by the key descriptor.
221 // Otherwise, we would have to clone the blob from the key descriptor.
222 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800223 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700224 Domain::BLOB => {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700225 check_key_permission(KeyPerm::Use, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000226 .context(ks_err!("checking use permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800227 if forced {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000228 check_key_permission(KeyPerm::ReqForcedOp, key, &None)
229 .context(ks_err!("checking forced permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800230 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700231 (
232 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700233 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700234 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000235 return Err(Error::sys()).context(ks_err!(
236 "Key blob must be specified when \
237 using Domain::BLOB."
238 ));
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700239 }
240 },
241 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000242 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000243 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700244 )
245 }
246 _ => {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800247 let super_key = SUPER_KEY
248 .read()
249 .unwrap()
250 .get_per_boot_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800251 let (key_id_guard, mut key_entry) = DB
252 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800253 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000254 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700255 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000256 KeyType::Client,
257 KeyEntryLoadBits::KM,
258 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800259 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700260 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800261 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700262 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800263 }
264 Ok(())
265 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000266 )
267 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700268 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000269 .context(ks_err!("Failed to load key blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800270
271 let (blob, blob_metadata) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000272 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(ks_err!(
273 "Successfully loaded key entry, \
274 but KM blob was missing."
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800275 ))?;
276 scoping_blob = blob;
277
Qi Wub9433b52020-12-01 14:52:46 +0800278 (
279 &scoping_blob,
280 Some((key_id_guard.id(), key_entry.into_key_parameters())),
281 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000282 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800283 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700284 }
285 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700286
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700287 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700288 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000289 .context(ks_err!("No operation purpose specified.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800290 |kp| match kp.value {
291 KeyParameterValue::KeyPurpose(p) => Ok(p),
292 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000293 .context(ks_err!("Malformed KeyParameter.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800294 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700295 )?;
296
Satya Tangirala2642ff92021-04-15 01:57:00 -0700297 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
298 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
299 let op_params: Vec<KeyParameter> =
300 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
301 let operation_parameters = op_params.as_slice();
302
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800303 let (immediate_hat, mut auth_info) = ENFORCEMENTS
304 .authorize_create(
305 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800306 key_properties.as_ref(),
307 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700308 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800309 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000310 .context(ks_err!())?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000311
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000312 let km_blob = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800313 .read()
314 .unwrap()
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000315 .unwrap_key_if_required(&blob_metadata, km_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000316 .context(ks_err!("Failed to handle super encryption."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000317
Janis Danisevskisaec14592020-11-12 09:41:49 -0800318 let (begin_result, upgraded_blob) = self
319 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700320 &*self.keymint,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800321 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700322 &km_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800323 blob_metadata.km_uuid().copied(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700324 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800325 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700326 match map_km_error({
327 let _wp = self.watch_millis(
328 "In KeystoreSecurityLevel::create_operation: calling begin",
329 500,
330 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700331 self.keymint.begin(
332 purpose,
333 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700334 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700335 immediate_hat.as_ref(),
336 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700337 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800338 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800339 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800340 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700341 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100342 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
343 if let Some((key_id, _)) = key_properties {
344 if let Ok(Some(key)) =
345 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
346 {
347 log_key_integrity_violation(&key);
348 } else {
349 log::error!("Failed to load key descriptor for audit log");
350 }
351 }
352 return v;
353 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800354 v => return v,
355 }
356 },
357 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000358 .context(ks_err!("Failed to begin operation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700359
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800360 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000361
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000362 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
363
Janis Danisevskis1af91262020-08-10 14:58:08 -0700364 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700365 Some(km_op) => self.operation_db.create_operation(
366 km_op,
367 caller_uid,
368 auth_info,
369 forced,
370 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
371 ),
372 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000373 return Err(Error::sys()).context(ks_err!(
374 "Begin operation returned successfully, \
375 but did not return a valid operation."
376 ));
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700377 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700378 };
379
Stephen Crane23cf7242022-01-19 17:49:46 +0000380 let op_binder: binder::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700381 KeystoreOperation::new_native_binder(operation)
382 .as_binder()
383 .into_interface()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000384 .context(ks_err!("Failed to create IKeystoreOperation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700385
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700386 Ok(CreateOperationResponse {
387 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000388 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700389 parameters: match begin_result.params.len() {
390 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700391 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700392 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800393 // An upgraded blob should only be returned if the caller has permission
394 // to use Domain::BLOB keys. If we got to this point, we already checked
395 // that the caller had that permission.
396 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700397 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700398 }
399
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000400 fn add_required_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700401 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800402 uid: u32,
403 params: &[KeyParameter],
404 key: &KeyDescriptor,
405 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800406 let mut result = params.to_vec();
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000407
408 // Unconditionally add the CREATION_DATETIME tag and prevent callers from
409 // specifying it.
410 if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000411 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
412 "KeystoreSecurityLevel::add_required_parameters: \
413 Specifying Tag::CREATION_DATETIME is not allowed."
414 ));
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000415 }
416
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800417 // Add CREATION_DATETIME only if the backend version Keymint V1 (100) or newer.
418 if self.hw_info.versionNumber >= 100 {
419 result.push(KeyParameter {
420 tag: Tag::CREATION_DATETIME,
421 value: KeyParameterValue::DateTime(
422 SystemTime::now()
423 .duration_since(SystemTime::UNIX_EPOCH)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000424 .context(ks_err!(
425 "KeystoreSecurityLevel::add_required_parameters: \
426 Failed to get epoch time."
427 ))?
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800428 .as_millis()
429 .try_into()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000430 .context(ks_err!(
431 "KeystoreSecurityLevel::add_required_parameters: \
432 Failed to convert epoch time."
433 ))?,
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800434 ),
435 });
436 }
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000437
Janis Danisevskis2c084012021-01-31 22:23:17 -0800438 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800439 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700440 let aaid = {
441 let _wp = self.watch_millis(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000442 "In KeystoreSecurityLevel::add_required_parameters calling: get_aaid",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700443 500,
444 );
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000445 keystore2_aaid::get_aaid(uid)
446 .map_err(|e| anyhow!(ks_err!("get_aaid returned status {}.", e)))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700447 }?;
448
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800449 result.push(KeyParameter {
450 tag: Tag::ATTESTATION_APPLICATION_ID,
451 value: KeyParameterValue::Blob(aaid),
452 });
453 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800454
Janis Danisevskise766edc2021-02-06 12:16:26 -0800455 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Seth Moore66d9e902022-03-16 17:20:31 -0700456 if check_key_permission(KeyPerm::GenUniqueId, key, &None).is_err()
457 && check_unique_id_attestation_permissions().is_err()
458 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000459 return Err(Error::perm()).context(ks_err!(
460 "Caller does not have the permission to generate a unique ID"
461 ));
Seth Moore66d9e902022-03-16 17:20:31 -0700462 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000463 if self
464 .id_rotation_state
465 .had_factory_reset_since_id_rotation()
466 .context(ks_err!("Call to had_factory_reset_since_id_rotation failed."))?
467 {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000468 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700469 tag: Tag::RESET_SINCE_ID_ROTATION,
470 value: KeyParameterValue::BoolValue(true),
471 })
472 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800473 }
474
Bram Bonné5d6c5102021-02-24 15:09:18 +0100475 // If the caller requests any device identifier attestation tag, check that they hold the
476 // correct Android permission.
477 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000478 check_device_attestation_permissions().context(ks_err!(
Bram Bonné5d6c5102021-02-24 15:09:18 +0100479 "Caller does not have the permission to attest device identifiers."
480 ))?;
481 }
482
Janis Danisevskis2c084012021-01-31 22:23:17 -0800483 // If we are generating/importing an asymmetric key, we need to make sure
484 // that NOT_BEFORE and NOT_AFTER are present.
485 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
486 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
487 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
488 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
489 result.push(KeyParameter {
490 tag: Tag::CERTIFICATE_NOT_BEFORE,
491 value: KeyParameterValue::DateTime(0),
492 })
493 }
494 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
495 result.push(KeyParameter {
496 tag: Tag::CERTIFICATE_NOT_AFTER,
497 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
498 })
499 }
500 }
501 _ => {}
502 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800503 Ok(result)
504 }
505
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 fn generate_key(
507 &self,
508 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700509 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700510 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700511 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700512 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700513 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700514 if key.domain != Domain::BLOB && key.alias.is_none() {
515 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000516 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700517 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000518 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519
520 let key = match key.domain {
521 Domain::APP => KeyDescriptor {
522 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000523 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700524 alias: key.alias.clone(),
525 blob: None,
526 },
527 _ => key.clone(),
528 };
529
530 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700531 // Must return on error for security reasons.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000532 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700533
534 let attestation_key_info = match (key.domain, attest_key_descriptor) {
535 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800536 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700537 .with(|db| {
538 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800539 &key,
540 caller_uid,
541 attest_key_descriptor,
542 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700543 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800544 &mut db.borrow_mut(),
545 )
546 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000547 .context(ks_err!("Trying to get an attestation key"))?,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800548 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700549 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000550 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000551 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800552
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700553 let creation_result = match attestation_key_info {
554 Some(AttestationKeyInfo::UserGenerated {
555 key_id_guard,
556 blob,
557 blob_metadata,
558 issuer_subject,
559 }) => self
560 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700561 &*self.keymint,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700562 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700563 &KeyBlob::Ref(&blob),
Max Bires55620ff2022-02-11 13:34:15 -0800564 blob_metadata.km_uuid().copied(),
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700565 &params,
566 |blob| {
567 let attest_key = Some(AttestationKey {
568 keyBlob: blob.to_vec(),
569 attestKeyParams: vec![],
570 issuerSubjectName: issuer_subject.clone(),
571 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700572 map_km_error({
573 let _wp = self.watch_millis(
574 concat!(
575 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
576 "calling generate_key."
577 ),
578 5000, // Generate can take a little longer.
579 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700580 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700581 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700582 },
583 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000584 .context(ks_err!("Using user generated attestation key."))
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700585 .map(|(result, _)| result),
Max Bires55620ff2022-02-11 13:34:15 -0800586 Some(AttestationKeyInfo::RemoteProvisioned {
587 key_id_guard,
588 attestation_key,
589 attestation_certs,
590 }) => self
591 .upgrade_keyblob_if_required_with(
592 &*self.keymint,
593 Some(key_id_guard),
594 &KeyBlob::Ref(&attestation_key.keyBlob),
595 Some(self.rem_prov_state.get_uuid()),
596 &[],
597 |blob| {
598 map_km_error({
599 let _wp = self.watch_millis(
600 concat!(
601 "In KeystoreSecurityLevel::generate_key (RemoteProvisioned): ",
602 "calling generate_key.",
603 ),
604 5000, // Generate can take a little longer.
605 );
606 let dynamic_attest_key = Some(AttestationKey {
607 keyBlob: blob.to_vec(),
608 attestKeyParams: vec![],
609 issuerSubjectName: attestation_key.issuerSubjectName.clone(),
610 });
611 self.keymint.generateKey(&params, dynamic_attest_key.as_ref())
612 })
613 },
614 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700615 .context("While generating Key with remote provisioned attestation key.")
Max Bires55620ff2022-02-11 13:34:15 -0800616 .map(|(mut result, _)| {
617 result.certificateChain.push(attestation_certs);
618 result
619 }),
Tri Vob5e43d12022-12-21 08:54:14 -0800620 Some(AttestationKeyInfo::RkpdProvisioned { attestation_key, attestation_certs }) => {
621 self.upgrade_rkpd_keyblob_if_required_with(&attestation_key.keyBlob, &[], |blob| {
622 map_km_error({
623 let _wp = self.watch_millis(
624 concat!(
625 "In KeystoreSecurityLevel::generate_key (RkpdProvisioned): ",
626 "calling generate_key.",
627 ),
628 5000, // Generate can take a little longer.
629 );
630 let dynamic_attest_key = Some(AttestationKey {
631 keyBlob: blob.to_vec(),
632 attestKeyParams: vec![],
633 issuerSubjectName: attestation_key.issuerSubjectName.clone(),
634 });
635 self.keymint.generateKey(&params, dynamic_attest_key.as_ref())
636 })
637 })
638 .context("While generating Key with remote provisioned attestation key.")
639 .map(|(mut result, _)| {
640 result.certificateChain.push(attestation_certs);
641 result
642 })
643 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700644 None => map_km_error({
645 let _wp = self.watch_millis(
646 concat!(
647 "In KeystoreSecurityLevel::generate_key (No attestation): ",
648 "calling generate_key.",
649 ),
650 5000, // Generate can take a little longer.
651 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700652 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700653 })
654 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800655 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000656 .context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700657
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000658 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000659 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700660 }
661
662 fn import_key(
663 &self,
664 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700665 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700666 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700667 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700668 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700669 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700670 if key.domain != Domain::BLOB && key.alias.is_none() {
671 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000672 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700673 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000674 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700675
676 let key = match key.domain {
677 Domain::APP => KeyDescriptor {
678 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000679 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700680 alias: key.alias.clone(),
681 blob: None,
682 },
683 _ => key.clone(),
684 };
685
686 // import_key requires the rebind permission.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700687 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700688
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700689 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000690 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000691 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800692
Janis Danisevskis1af91262020-08-10 14:58:08 -0700693 let format = params
694 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700695 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700696 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
697 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800698 .and_then(|p| match &p.value {
699 KeyParameterValue::Algorithm(Algorithm::AES)
700 | KeyParameterValue::Algorithm(Algorithm::HMAC)
701 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
702 KeyParameterValue::Algorithm(Algorithm::RSA)
703 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
704 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000705 .context(ks_err!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700706 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000707 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700708
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700709 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700710 let creation_result = map_km_error({
711 let _wp =
712 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
713 km_dev.importKey(&params, format, key_data, None /* attestKey */)
714 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000715 .context(ks_err!("Trying to call importKey"))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700716
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000717 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000718 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700719 }
720
721 fn import_wrapped_key(
722 &self,
723 key: &KeyDescriptor,
724 wrapping_key: &KeyDescriptor,
725 masking_key: Option<&[u8]>,
726 params: &[KeyParameter],
727 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700728 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800729 let wrapped_data: &[u8] = match key {
730 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
731 | KeyDescriptor {
732 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
733 } => blob,
734 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000735 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(ks_err!(
736 "Alias and blob must be specified and domain must be APP or SELINUX. {:?}",
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800737 key
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000738 ));
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800739 }
740 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700741
Janis Danisevskisaec14592020-11-12 09:41:49 -0800742 if wrapping_key.domain == Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000743 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
744 .context(ks_err!("Import wrapped key not supported for self managed blobs."));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800745 }
746
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000747 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000748 let user_id = uid_to_android_user(caller_uid);
749
Janis Danisevskis1af91262020-08-10 14:58:08 -0700750 let key = match key.domain {
751 Domain::APP => KeyDescriptor {
752 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000753 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700754 alias: key.alias.clone(),
755 blob: None,
756 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800757 Domain::SELINUX => KeyDescriptor {
758 domain: Domain::SELINUX,
759 nspace: key.nspace,
760 alias: key.alias.clone(),
761 blob: None,
762 },
763 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700764 };
765
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800766 // Import_wrapped_key requires the rebind permission for the new key.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000767 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700768
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800769 let super_key = SUPER_KEY.read().unwrap().get_per_boot_key_by_user_id(user_id);
770
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000771 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700772 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800773 LEGACY_IMPORTER.with_try_import(&key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000774 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700775 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000776 KeyType::Client,
777 KeyEntryLoadBits::KM,
778 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700779 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000780 )
781 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700782 })
783 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000784
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000785 let (wrapping_key_blob, wrapping_blob_metadata) =
786 wrapping_key_entry.take_key_blob_info().ok_or_else(error::Error::sys).context(
787 ks_err!("No km_blob after successfully loading key. This should never happen."),
788 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000789
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800790 let wrapping_key_blob = SUPER_KEY
791 .read()
792 .unwrap()
793 .unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000794 .context(ks_err!("Failed to handle super encryption for wrapping key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700795
Janis Danisevskis1af91262020-08-10 14:58:08 -0700796 // km_dev.importWrappedKey does not return a certificate chain.
797 // TODO Do we assume that all wrapped keys are symmetric?
798 // let certificate_chain: Vec<KmCertificate> = Default::default();
799
800 let pw_sid = authenticators
801 .iter()
802 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700803 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700804 _ => None,
805 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800806 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700807
808 let fp_sid = authenticators
809 .iter()
810 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700811 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700812 _ => None,
813 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800814 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700815
816 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
817
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800818 let (creation_result, _) = self
819 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700820 &*self.keymint,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800821 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700822 &wrapping_key_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800823 wrapping_blob_metadata.km_uuid().copied(),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800824 &[],
825 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700826 let _wp = self.watch_millis(
827 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
828 500,
829 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700830 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800831 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800832 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800833 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700834 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800835 pw_sid,
836 fp_sid,
837 ))?;
838 Ok(creation_result)
839 },
840 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000841 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700842
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000843 self.store_new_key(key, creation_result, user_id, None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000844 .context(ks_err!("Trying to store the new key."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700845 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800846
Paul Crowley7a658392021-03-18 17:08:20 -0700847 fn store_upgraded_keyblob(
848 key_id_guard: KeyIdGuard,
Max Bires55620ff2022-02-11 13:34:15 -0800849 km_uuid: Option<Uuid>,
Paul Crowley7a658392021-03-18 17:08:20 -0700850 key_blob: &KeyBlob,
851 upgraded_blob: &[u8],
852 ) -> Result<()> {
853 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700854 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000855 .context(ks_err!("Failed to handle super encryption."))?;
Paul Crowley7a658392021-03-18 17:08:20 -0700856
Paul Crowley44c02da2021-04-08 17:04:43 +0000857 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700858 if let Some(uuid) = km_uuid {
Max Bires55620ff2022-02-11 13:34:15 -0800859 new_blob_metadata.add(BlobMetaEntry::KmUuid(uuid));
Paul Crowley7a658392021-03-18 17:08:20 -0700860 }
861
862 DB.with(|db| {
863 let mut db = db.borrow_mut();
864 db.set_blob(
865 &key_id_guard,
866 SubComponentType::KEY_BLOB,
867 Some(&upgraded_blob_to_be_stored),
868 Some(&new_blob_metadata),
869 )
870 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000871 .context(ks_err!("Failed to insert upgraded blob into the database."))
Paul Crowley7a658392021-03-18 17:08:20 -0700872 }
873
Janis Danisevskisaec14592020-11-12 09:41:49 -0800874 fn upgrade_keyblob_if_required_with<T, F>(
875 &self,
876 km_dev: &dyn IKeyMintDevice,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800877 mut key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700878 key_blob: &KeyBlob,
Max Bires55620ff2022-02-11 13:34:15 -0800879 km_uuid: Option<Uuid>,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800880 params: &[KeyParameter],
881 f: F,
882 ) -> Result<(T, Option<Vec<u8>>)>
883 where
884 F: Fn(&[u8]) -> Result<T, Error>,
885 {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800886 let (v, upgraded_blob) = crate::utils::upgrade_keyblob_if_required_with(
887 km_dev,
888 key_blob,
889 params,
890 f,
891 |upgraded_blob| {
892 if key_id_guard.is_some() {
893 // Unwrap cannot panic, because the is_some was true.
894 let kid = key_id_guard.take().unwrap();
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000895 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, upgraded_blob)
896 .context(ks_err!("store_upgraded_keyblob failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800897 } else {
898 Ok(())
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000899 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800900 },
901 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000902 .context(ks_err!())?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000903
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800904 // If no upgrade was needed, use the opportunity to reencrypt the blob if required
905 // and if the a key_id_guard is held. Note: key_id_guard can only be Some if no
906 // upgrade was performed above and if one was given in the first place.
907 if key_blob.force_reencrypt() {
908 if let Some(kid) = key_id_guard {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000909 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, key_blob)
910 .context(ks_err!("store_upgraded_keyblob failed in forced reencrypt"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700911 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800912 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800913 Ok((v, upgraded_blob))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800914 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800915
Tri Vob5e43d12022-12-21 08:54:14 -0800916 fn upgrade_rkpd_keyblob_if_required_with<T, F>(
917 &self,
918 key_blob: &[u8],
919 params: &[KeyParameter],
920 f: F,
921 ) -> Result<(T, Option<Vec<u8>>)>
922 where
923 F: Fn(&[u8]) -> Result<T, Error>,
924 {
925 crate::utils::upgrade_keyblob_if_required_with(
926 &*self.keymint,
927 key_blob,
928 params,
929 f,
930 |upgraded_blob| {
931 store_rkpd_attestation_key(&self.security_level, key_blob, upgraded_blob)
932 .context(ks_err!("Failed store_rkpd_attestation_key()."))
933 },
934 )
935 .context(ks_err!())
936 }
937
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700938 fn convert_storage_key_to_ephemeral(
939 &self,
940 storage_key: &KeyDescriptor,
941 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800942 if storage_key.domain != Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000943 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
944 .context(ks_err!("Key must be of Domain::BLOB"));
Satya Tangirala3361b612021-03-08 14:36:11 -0800945 }
946 let key_blob = storage_key
947 .blob
948 .as_ref()
949 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000950 .context(ks_err!("No key blob specified"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800951
952 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700953 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000954 .context(ks_err!("Check permission"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800955
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700956 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700957 match {
958 let _wp = self.watch_millis(
959 concat!(
960 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
961 "calling convertStorageKeyToEphemeral (1)"
962 ),
963 500,
964 );
965 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
966 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700967 Ok(result) => {
968 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
969 }
970 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700971 let upgraded_blob = {
972 let _wp = self.watch_millis(
973 "In convert_storage_key_to_ephemeral: calling upgradeKey",
974 500,
975 );
976 map_km_error(km_dev.upgradeKey(key_blob, &[]))
977 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000978 .context(ks_err!("Failed to upgrade key blob."))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700979 let ephemeral_key = {
980 let _wp = self.watch_millis(
981 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
982 500,
983 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700984 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700985 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000986 .context(ks_err!(
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700987 "Failed to retrieve ephemeral key (after upgrade)."
988 ))?;
989 Ok(EphemeralStorageKeyResponse {
990 ephemeralKey: ephemeral_key,
991 upgradedBlob: Some(upgraded_blob),
992 })
993 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000994 Err(e) => Err(e).context(ks_err!("Failed to retrieve ephemeral key.")),
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700995 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800996 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800997
998 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
999 if key.domain != Domain::BLOB {
1000 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001001 .context(ks_err!("delete_key: Key must be of Domain::BLOB"));
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001002 }
1003
1004 let key_blob = key
1005 .blob
1006 .as_ref()
1007 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001008 .context(ks_err!("delete_key: No key blob specified"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001009
Janis Danisevskis39d57e72021-10-19 16:56:20 -07001010 check_key_permission(KeyPerm::Delete, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001011 .context(ks_err!("delete_key: Checking delete permissions"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001012
Janis Danisevskis5f3a0572021-06-18 11:26:42 -07001013 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -07001014 {
1015 let _wp =
1016 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001017 map_km_error(km_dev.deleteKey(key_blob)).context(ks_err!("keymint device deleteKey"))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -07001018 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001019 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001020}
1021
1022impl binder::Interface for KeystoreSecurityLevel {}
1023
1024impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001025 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -07001026 &self,
1027 key: &KeyDescriptor,
1028 operation_parameters: &[KeyParameter],
1029 forced: bool,
Stephen Crane23cf7242022-01-19 17:49:46 +00001030 ) -> binder::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001031 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001032 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001033 }
1034 fn generateKey(
1035 &self,
1036 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001037 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001038 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001039 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001040 entropy: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001041 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001042 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1043 // time than other operations
1044 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001045 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001046 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001047 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001048 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001049 }
1050 fn importKey(
1051 &self,
1052 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001053 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001054 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001055 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001056 key_data: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001057 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001058 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001059 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001060 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001061 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001062 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001063 }
1064 fn importWrappedKey(
1065 &self,
1066 key: &KeyDescriptor,
1067 wrapping_key: &KeyDescriptor,
1068 masking_key: Option<&[u8]>,
1069 params: &[KeyParameter],
1070 authenticators: &[AuthenticatorSpec],
Stephen Crane23cf7242022-01-19 17:49:46 +00001071 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001072 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001073 let result =
1074 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001075 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001076 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001077 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001078 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001079 fn convertStorageKeyToEphemeral(
1080 &self,
1081 storage_key: &KeyDescriptor,
Stephen Crane23cf7242022-01-19 17:49:46 +00001082 ) -> binder::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001083 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001084 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1085 }
Stephen Crane23cf7242022-01-19 17:49:46 +00001086 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001087 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001088 let result = self.delete_key(key);
1089 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1090 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001091 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001092}