blob: 4636906b2d5976a64158e5d6698a2f685b61e57a [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
15#![allow(unused_variables)]
16
17//! This crate implements the IKeystoreSecurityLevel interface.
18
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080019use crate::globals::get_keymint_device;
Shawn Willden708744a2020-12-11 13:05:27 +000020use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070021 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070022 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
23 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080024 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
25 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070026};
27use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070028 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
29 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
30 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070031 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080032 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070033};
34
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070035use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
36use crate::database::{CertificateInfo, KeyIdGuard};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000037use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000038use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000039use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Hasini Gunasingheb7142972021-02-20 03:11:27 +000040use crate::metrics::log_key_creation_event_stats;
Max Bires97f96812021-02-23 23:44:57 -080041use crate::remote_provisioning::RemProvState;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000042use crate::super_key::{KeyBlob, SuperKeyManager};
Bram Bonné5d6c5102021-02-24 15:09:18 +010043use crate::utils::{
44 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
45 uid_to_android_user, Asp,
46};
Max Bires8e93d2b2021-01-14 13:17:59 -080047use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080048 database::{
49 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
50 KeyMetaEntry, KeyType, SubComponentType, Uuid,
51 },
52 operation::KeystoreOperation,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +000053 operation::LoggingInfo,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054 operation::OperationDb,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080055 permission::KeyPerm,
56};
57use crate::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070058 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
59 utils::key_characteristics_to_internal,
60};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080061use anyhow::{anyhow, Context, Result};
Andrew Walbran808e8602021-03-16 13:58:28 +000062use binder::{IBinderInternal, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070063
64/// Implementation of the IKeystoreSecurityLevel Interface.
65pub struct KeystoreSecurityLevel {
66 security_level: SecurityLevel,
67 keymint: Asp,
Max Bires8e93d2b2021-01-14 13:17:59 -080068 #[allow(dead_code)]
69 hw_info: KeyMintHardwareInfo,
70 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070071 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080072 rem_prov_state: RemProvState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070073}
74
Janis Danisevskis1af91262020-08-10 14:58:08 -070075// Blob of 32 zeroes used as empty masking key.
76static ZERO_BLOB_32: &[u8] = &[0; 32];
77
Janis Danisevskis2c084012021-01-31 22:23:17 -080078// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
79// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
80const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
81
Janis Danisevskis1af91262020-08-10 14:58:08 -070082impl KeystoreSecurityLevel {
83 /// Creates a new security level instance wrapped in a
84 /// BnKeystoreSecurityLevel proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +000085 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070086 /// we need it for checking keystore permissions.
87 pub fn new_native_binder(
88 security_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -080089 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080090 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
91 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070092 let result = BnKeystoreSecurityLevel::new_binder(Self {
93 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080094 keymint: dev,
95 hw_info,
96 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070097 operation_db: OperationDb::new(),
Max Bires97f96812021-02-23 23:44:57 -080098 rem_prov_state: RemProvState::new(security_level, km_uuid),
Janis Danisevskis1af91262020-08-10 14:58:08 -070099 });
100 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -0800101 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700102 }
103
104 fn store_new_key(
105 &self,
106 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700107 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000108 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000109 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700110 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700111 let KeyCreationResult {
112 keyBlob: key_blob,
113 keyCharacteristics: key_characteristics,
114 certificateChain: mut certificate_chain,
115 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700116
Max Bires8e93d2b2021-01-14 13:17:59 -0800117 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700118 match certificate_chain.len() {
119 0 => None,
120 _ => Some(certificate_chain.remove(0).encodedCertificate),
121 },
122 match certificate_chain.len() {
123 0 => None,
124 _ => Some(
125 certificate_chain
126 .iter()
127 .map(|c| c.encodedCertificate.iter())
128 .flatten()
129 .copied()
130 .collect(),
131 ),
132 },
133 );
134
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000135 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
136
137 key_parameters.push(KsKeyParam::new(
138 KsKeyParamValue::UserID(user_id as i32),
139 SecurityLevel::SOFTWARE,
140 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700141
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800142 let creation_date = DateTime::now().context("Trying to make creation time.")?;
143
Janis Danisevskis1af91262020-08-10 14:58:08 -0700144 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800145 Domain::BLOB => KeyDescriptor {
146 domain: Domain::BLOB,
147 blob: Some(key_blob.to_vec()),
148 ..Default::default()
149 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700150 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800151 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800152 let mut db = db.borrow_mut();
153
154 let (key_blob, mut blob_metadata) = SUPER_KEY
155 .handle_super_encryption_on_key_init(
156 &mut db,
157 &LEGACY_MIGRATOR,
158 &(key.domain),
159 &key_parameters,
160 flags,
161 user_id,
162 &key_blob,
163 )
164 .context("In store_new_key. Failed to handle super encryption.")?;
165
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800166 let mut key_metadata = KeyMetaData::new();
167 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800168 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800171 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800172 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800173 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800174 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800175 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800177 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800178 )
179 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700180 Ok(KeyDescriptor {
181 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800182 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700183 ..Default::default()
184 })
185 })
186 .context("In store_new_key.")?,
187 };
188
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700189 Ok(KeyMetadata {
190 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700191 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800192 certificate: cert_info.take_cert(),
193 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700194 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800195 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700196 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700197 }
198
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700199 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700200 &self,
201 key: &KeyDescriptor,
202 operation_parameters: &[KeyParameter],
203 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700204 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700205 let caller_uid = ThreadState::get_calling_uid();
206 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
207 // so that we can use it by reference like the blob provided by the key descriptor.
208 // Otherwise, we would have to clone the blob from the key descriptor.
209 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800210 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700211 Domain::BLOB => {
212 check_key_permission(KeyPerm::use_(), key, &None)
213 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800214 if forced {
215 check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
216 "In create_operation: checking forced permission for Domain::BLOB.",
217 )?;
218 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700219 (
220 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700221 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700222 None => {
223 return Err(Error::sys()).context(concat!(
224 "In create_operation: Key blob must be specified when",
225 " using Domain::BLOB."
226 ))
227 }
228 },
229 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000230 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000231 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700232 )
233 }
234 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800235 let (key_id_guard, mut key_entry) = DB
236 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000237 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
238 db.borrow_mut().load_key_entry(
239 &key,
240 KeyType::Client,
241 KeyEntryLoadBits::KM,
242 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800243 |k, av| {
244 check_key_permission(KeyPerm::use_(), k, &av)?;
245 if forced {
246 check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
247 }
248 Ok(())
249 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000250 )
251 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700252 })
253 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800254
255 let (blob, blob_metadata) =
256 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
257 "In create_operation: Successfully loaded key entry, ",
258 "but KM blob was missing."
259 ))?;
260 scoping_blob = blob;
261
Qi Wub9433b52020-12-01 14:52:46 +0800262 (
263 &scoping_blob,
264 Some((key_id_guard.id(), key_entry.into_key_parameters())),
265 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000266 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800267 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700268 }
269 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700270
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700271 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700272 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700273 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800274 |kp| match kp.value {
275 KeyParameterValue::KeyPurpose(p) => Ok(p),
276 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
277 .context("In create_operation: Malformed KeyParameter."),
278 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700279 )?;
280
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800281 let (immediate_hat, mut auth_info) = ENFORCEMENTS
282 .authorize_create(
283 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800284 key_properties.as_ref(),
285 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700286 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800287 )
288 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000289
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800290 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000291
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000292 let km_blob = SUPER_KEY
293 .unwrap_key_if_required(&blob_metadata, km_blob)
294 .context("In create_operation. Failed to handle super encryption.")?;
295
Stephen Crane221bbb52020-12-16 15:52:10 -0800296 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700297 .keymint
298 .get_interface()
299 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700300
Janis Danisevskisaec14592020-11-12 09:41:49 -0800301 let (begin_result, upgraded_blob) = self
302 .upgrade_keyblob_if_required_with(
303 &*km_dev,
304 key_id_guard,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000305 &(&km_blob, &blob_metadata),
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700306 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800307 |blob| loop {
308 match map_km_error(km_dev.begin(
309 purpose,
310 blob,
311 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800312 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800313 )) {
314 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800315 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800316 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700317 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800318 v => return v,
319 }
320 },
321 )
322 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700323
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800324 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000325
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000326 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
327
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000329 Some(km_op) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000330 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced,
331 LoggingInfo::new(purpose, op_params, upgraded_blob.is_some()))
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000332 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700333 None => return Err(Error::sys()).context("In create_operation: Begin operation returned successfully, but did not return a valid operation."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700334 };
335
Stephen Crane221bbb52020-12-16 15:52:10 -0800336 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700337 KeystoreOperation::new_native_binder(operation)
338 .as_binder()
339 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700340 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700341
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700342 Ok(CreateOperationResponse {
343 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000344 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700345 parameters: match begin_result.params.len() {
346 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700347 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700348 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800349 // An upgraded blob should only be returned if the caller has permission
350 // to use Domain::BLOB keys. If we got to this point, we already checked
351 // that the caller had that permission.
352 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700353 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700354 }
355
Janis Danisevskise766edc2021-02-06 12:16:26 -0800356 fn add_certificate_parameters(
357 uid: u32,
358 params: &[KeyParameter],
359 key: &KeyDescriptor,
360 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800361 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800362 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800363 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
364 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800365 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800366 })?;
367 result.push(KeyParameter {
368 tag: Tag::ATTESTATION_APPLICATION_ID,
369 value: KeyParameterValue::Blob(aaid),
370 });
371 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800372
Janis Danisevskise766edc2021-02-06 12:16:26 -0800373 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
374 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
375 "In add_certificate_parameters: ",
376 "Caller does not have the permission for device unique attestation."
377 ))?;
378 }
379
Bram Bonné5d6c5102021-02-24 15:09:18 +0100380 // If the caller requests any device identifier attestation tag, check that they hold the
381 // correct Android permission.
382 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
383 check_device_attestation_permissions().context(concat!(
384 "In add_certificate_parameters: ",
385 "Caller does not have the permission to attest device identifiers."
386 ))?;
387 }
388
Janis Danisevskis2c084012021-01-31 22:23:17 -0800389 // If we are generating/importing an asymmetric key, we need to make sure
390 // that NOT_BEFORE and NOT_AFTER are present.
391 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
392 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
393 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
394 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
395 result.push(KeyParameter {
396 tag: Tag::CERTIFICATE_NOT_BEFORE,
397 value: KeyParameterValue::DateTime(0),
398 })
399 }
400 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
401 result.push(KeyParameter {
402 tag: Tag::CERTIFICATE_NOT_AFTER,
403 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
404 })
405 }
406 }
407 _ => {}
408 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800409 Ok(result)
410 }
411
Janis Danisevskis1af91262020-08-10 14:58:08 -0700412 fn generate_key(
413 &self,
414 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700415 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700416 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700417 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700418 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700419 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700420 if key.domain != Domain::BLOB && key.alias.is_none() {
421 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
422 .context("In generate_key: Alias must be specified");
423 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000424 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700425
426 let key = match key.domain {
427 Domain::APP => KeyDescriptor {
428 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000429 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700430 alias: key.alias.clone(),
431 blob: None,
432 },
433 _ => key.clone(),
434 };
435
436 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700437 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700438 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700439
440 let attestation_key_info = match (key.domain, attest_key_descriptor) {
441 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800442 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700443 .with(|db| {
444 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800445 &key,
446 caller_uid,
447 attest_key_descriptor,
448 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700449 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800450 &mut db.borrow_mut(),
451 )
452 })
453 .context("In generate_key: Trying to get an attestation key")?,
454 };
Janis Danisevskise766edc2021-02-06 12:16:26 -0800455 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800456 .context("In generate_key: Trying to get aaid.")?;
457
Stephen Crane221bbb52020-12-16 15:52:10 -0800458 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700459
460 let creation_result = match attestation_key_info {
461 Some(AttestationKeyInfo::UserGenerated {
462 key_id_guard,
463 blob,
464 blob_metadata,
465 issuer_subject,
466 }) => self
467 .upgrade_keyblob_if_required_with(
468 &*km_dev,
469 Some(key_id_guard),
470 &(&KeyBlob::Ref(&blob), &blob_metadata),
471 &params,
472 |blob| {
473 let attest_key = Some(AttestationKey {
474 keyBlob: blob.to_vec(),
475 attestKeyParams: vec![],
476 issuerSubjectName: issuer_subject.clone(),
477 });
478 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
479 },
480 )
481 .context("In generate_key: Using user generated attestation key.")
482 .map(|(result, _)| result),
483 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
484 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
485 .context("While generating Key with remote provisioned attestation key.")
486 .map(|mut creation_result| {
487 creation_result.certificateChain.push(attestation_certs);
488 creation_result
489 })
490 }
491 None => map_km_error(km_dev.generateKey(&params, None))
492 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800493 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700494 .context("In generate_key.")?;
495
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000496 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000497 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700498 }
499
500 fn import_key(
501 &self,
502 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700503 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700504 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700505 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700507 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700508 if key.domain != Domain::BLOB && key.alias.is_none() {
509 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
510 .context("In import_key: Alias must be specified");
511 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000512 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700513
514 let key = match key.domain {
515 Domain::APP => KeyDescriptor {
516 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000517 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700518 alias: key.alias.clone(),
519 blob: None,
520 },
521 _ => key.clone(),
522 };
523
524 // import_key requires the rebind permission.
525 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
526
Janis Danisevskise766edc2021-02-06 12:16:26 -0800527 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800528 .context("In import_key: Trying to get aaid.")?;
529
Janis Danisevskis1af91262020-08-10 14:58:08 -0700530 let format = params
531 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700532 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700533 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
534 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800535 .and_then(|p| match &p.value {
536 KeyParameterValue::Algorithm(Algorithm::AES)
537 | KeyParameterValue::Algorithm(Algorithm::HMAC)
538 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
539 KeyParameterValue::Algorithm(Algorithm::RSA)
540 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
541 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
542 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700543 })
544 .context("In import_key.")?;
545
Stephen Crane221bbb52020-12-16 15:52:10 -0800546 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800547 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700548 let creation_result =
549 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
550 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700551
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000552 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000553 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700554 }
555
556 fn import_wrapped_key(
557 &self,
558 key: &KeyDescriptor,
559 wrapping_key: &KeyDescriptor,
560 masking_key: Option<&[u8]>,
561 params: &[KeyParameter],
562 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700563 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800564 let wrapped_data: &[u8] = match key {
565 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
566 | KeyDescriptor {
567 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
568 } => blob,
569 _ => {
570 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
571 concat!(
572 "In import_wrapped_key: Alias and blob must be specified ",
573 "and domain must be APP or SELINUX. {:?}"
574 ),
575 key
576 ))
577 }
578 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700579
Janis Danisevskisaec14592020-11-12 09:41:49 -0800580 if wrapping_key.domain == Domain::BLOB {
581 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
582 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
583 );
584 }
585
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000586 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000587 let user_id = uid_to_android_user(caller_uid);
588
Janis Danisevskis1af91262020-08-10 14:58:08 -0700589 let key = match key.domain {
590 Domain::APP => KeyDescriptor {
591 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000592 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700593 alias: key.alias.clone(),
594 blob: None,
595 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800596 Domain::SELINUX => KeyDescriptor {
597 domain: Domain::SELINUX,
598 nspace: key.nspace,
599 alias: key.alias.clone(),
600 blob: None,
601 },
602 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700603 };
604
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800605 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700606 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
607
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000608 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700609 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000610 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
611 db.borrow_mut().load_key_entry(
612 &wrapping_key,
613 KeyType::Client,
614 KeyEntryLoadBits::KM,
615 caller_uid,
616 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
617 )
618 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700619 })
620 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000621
622 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
623 .take_key_blob_info()
624 .ok_or_else(error::Error::sys)
625 .context("No km_blob after successfully loading key. This should never happen.")?;
626
627 let wrapping_key_blob =
628 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
629 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
630 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631
Janis Danisevskis1af91262020-08-10 14:58:08 -0700632 // km_dev.importWrappedKey does not return a certificate chain.
633 // TODO Do we assume that all wrapped keys are symmetric?
634 // let certificate_chain: Vec<KmCertificate> = Default::default();
635
636 let pw_sid = authenticators
637 .iter()
638 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700639 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700640 _ => None,
641 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800642 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700643
644 let fp_sid = authenticators
645 .iter()
646 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700647 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700648 _ => None,
649 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800650 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700651
652 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
653
Stephen Crane221bbb52020-12-16 15:52:10 -0800654 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800655 let (creation_result, _) = self
656 .upgrade_keyblob_if_required_with(
657 &*km_dev,
658 Some(wrapping_key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000659 &(&wrapping_key_blob, &wrapping_blob_metadata),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800660 &[],
661 |wrapping_blob| {
662 let creation_result = map_km_error(km_dev.importWrappedKey(
663 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800664 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800665 masking_key,
666 &params,
667 pw_sid,
668 fp_sid,
669 ))?;
670 Ok(creation_result)
671 },
672 )
673 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700674
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000675 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800676 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700677 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800678
679 fn upgrade_keyblob_if_required_with<T, F>(
680 &self,
681 km_dev: &dyn IKeyMintDevice,
682 key_id_guard: Option<KeyIdGuard>,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000683 blob_info: &(&KeyBlob, &BlobMetaData),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800684 params: &[KeyParameter],
685 f: F,
686 ) -> Result<(T, Option<Vec<u8>>)>
687 where
688 F: Fn(&[u8]) -> Result<T, Error>,
689 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800690 match f(blob_info.0) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800691 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800692 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob_info.0, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800693 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000694
695 let (upgraded_blob_to_be_stored, blob_metadata) =
696 SuperKeyManager::reencrypt_on_upgrade_if_required(blob_info.0, &upgraded_blob)
697 .context(
698 "In upgrade_keyblob_if_required_with: Failed to handle super encryption.",
699 )?;
700
701 let mut blob_metadata = blob_metadata.unwrap_or_else(BlobMetaData::new);
702 if let Some(uuid) = blob_info.1.km_uuid() {
703 blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
704 }
705
Janis Danisevskisaec14592020-11-12 09:41:49 -0800706 key_id_guard.map_or(Ok(()), |key_id_guard| {
707 DB.with(|db| {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000708 let mut db = db.borrow_mut();
709 db.set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800710 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800711 SubComponentType::KEY_BLOB,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000712 Some(&upgraded_blob_to_be_stored),
713 Some(&blob_metadata),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800714 )
715 })
716 .context(concat!(
717 "In upgrade_keyblob_if_required_with: ",
718 "Failed to insert upgraded blob into the database.",
719 ))
720 })?;
721 match f(&upgraded_blob) {
722 Ok(v) => Ok((v, Some(upgraded_blob))),
723 Err(e) => Err(e).context(concat!(
724 "In upgrade_keyblob_if_required_with: ",
725 "Failed to perform operation on second try."
726 )),
727 }
728 }
729 Err(e) => {
730 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
731 }
732 Ok(v) => Ok((v, None)),
733 }
734 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800735
736 fn convert_storage_key_to_ephemeral(&self, storage_key: &KeyDescriptor) -> Result<Vec<u8>> {
737 if storage_key.domain != Domain::BLOB {
738 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
739 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
740 "Key must be of Domain::BLOB"
741 ));
742 }
743 let key_blob = storage_key
744 .blob
745 .as_ref()
746 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
747 .context(
748 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
749 )?;
750
751 // convert_storage_key_to_ephemeral requires the associated permission
752 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
753 .context("In convert_storage_key_to_ephemeral: Check permission")?;
754
755 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
756 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
757 "Getting keymint device interface"
758 ))?;
759 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
760 .context("In keymint device convertStorageKeyToEphemeral")
761 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800762
763 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
764 if key.domain != Domain::BLOB {
765 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
766 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
767 }
768
769 let key_blob = key
770 .blob
771 .as_ref()
772 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
773 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
774
775 check_key_permission(KeyPerm::delete(), key, &None)
776 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
777
778 let km_dev: Strong<dyn IKeyMintDevice> = self
779 .keymint
780 .get_interface()
781 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
782 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
783 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700784}
785
786impl binder::Interface for KeystoreSecurityLevel {}
787
788impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700789 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700790 &self,
791 key: &KeyDescriptor,
792 operation_parameters: &[KeyParameter],
793 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700794 ) -> binder::public_api::Result<CreateOperationResponse> {
795 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700796 }
797 fn generateKey(
798 &self,
799 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700800 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700801 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700802 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700803 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700804 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000805 let result = self.generate_key(key, attestation_key, params, flags, entropy);
806 log_key_creation_event_stats(params, &result);
807 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700808 }
809 fn importKey(
810 &self,
811 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700812 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700813 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700814 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700815 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700816 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000817 let result = self.import_key(key, attestation_key, params, flags, key_data);
818 log_key_creation_event_stats(params, &result);
819 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700820 }
821 fn importWrappedKey(
822 &self,
823 key: &KeyDescriptor,
824 wrapping_key: &KeyDescriptor,
825 masking_key: Option<&[u8]>,
826 params: &[KeyParameter],
827 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700828 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000829 let result =
830 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
831 log_key_creation_event_stats(params, &result);
832 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700833 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800834 fn convertStorageKeyToEphemeral(
835 &self,
836 storage_key: &KeyDescriptor,
837 ) -> binder::public_api::Result<Vec<u8>> {
838 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
839 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800840 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
841 map_or_log_err(self.delete_key(key), Ok)
842 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700843}