blob: c234ad36bb87d5d3f032c035c2d97fbdef9c189a [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 Danisevskis7e8b4622021-02-13 10:01:59 -080017use crate::globals::get_keymint_device;
Shawn Willden708744a2020-12-11 13:05:27 +000018use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070019 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070020 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
21 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080022 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
23 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070024};
25use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070026 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
27 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
28 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070029 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080030 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070031};
32
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070033use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
34use crate::database::{CertificateInfo, KeyIdGuard};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000035use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000036use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000037use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Max Bires97f96812021-02-23 23:44:57 -080038use crate::remote_provisioning::RemProvState;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000039use crate::super_key::{KeyBlob, SuperKeyManager};
Bram Bonné5d6c5102021-02-24 15:09:18 +010040use crate::utils::{
41 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
42 uid_to_android_user, Asp,
43};
Max Bires8e93d2b2021-01-14 13:17:59 -080044use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080045 database::{
46 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
47 KeyMetaEntry, KeyType, SubComponentType, Uuid,
48 },
49 operation::KeystoreOperation,
50 operation::OperationDb,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080051 permission::KeyPerm,
52};
53use crate::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070054 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
55 utils::key_characteristics_to_internal,
56};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080057use anyhow::{anyhow, Context, Result};
Andrew Walbran808e8602021-03-16 13:58:28 +000058use binder::{IBinderInternal, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070059
60/// Implementation of the IKeystoreSecurityLevel Interface.
61pub struct KeystoreSecurityLevel {
62 security_level: SecurityLevel,
63 keymint: Asp,
Max Bires8e93d2b2021-01-14 13:17:59 -080064 hw_info: KeyMintHardwareInfo,
65 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070066 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080067 rem_prov_state: RemProvState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070068}
69
Janis Danisevskis1af91262020-08-10 14:58:08 -070070// Blob of 32 zeroes used as empty masking key.
71static ZERO_BLOB_32: &[u8] = &[0; 32];
72
Janis Danisevskis2c084012021-01-31 22:23:17 -080073// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
74// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
75const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
76
Janis Danisevskis1af91262020-08-10 14:58:08 -070077impl KeystoreSecurityLevel {
78 /// Creates a new security level instance wrapped in a
79 /// BnKeystoreSecurityLevel proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +000080 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070081 /// we need it for checking keystore permissions.
82 pub fn new_native_binder(
83 security_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -080084 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080085 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
86 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070087 let result = BnKeystoreSecurityLevel::new_binder(Self {
88 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080089 keymint: dev,
90 hw_info,
91 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070092 operation_db: OperationDb::new(),
Max Bires97f96812021-02-23 23:44:57 -080093 rem_prov_state: RemProvState::new(security_level, km_uuid),
Janis Danisevskis1af91262020-08-10 14:58:08 -070094 });
95 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -080096 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -070097 }
98
99 fn store_new_key(
100 &self,
101 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700102 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000103 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000104 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700105 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700106 let KeyCreationResult {
107 keyBlob: key_blob,
108 keyCharacteristics: key_characteristics,
109 certificateChain: mut certificate_chain,
110 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700111
Max Bires8e93d2b2021-01-14 13:17:59 -0800112 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700113 match certificate_chain.len() {
114 0 => None,
115 _ => Some(certificate_chain.remove(0).encodedCertificate),
116 },
117 match certificate_chain.len() {
118 0 => None,
119 _ => Some(
120 certificate_chain
121 .iter()
122 .map(|c| c.encodedCertificate.iter())
123 .flatten()
124 .copied()
125 .collect(),
126 ),
127 },
128 );
129
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000130 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
131
132 key_parameters.push(KsKeyParam::new(
133 KsKeyParamValue::UserID(user_id as i32),
134 SecurityLevel::SOFTWARE,
135 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700136
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800137 let creation_date = DateTime::now().context("Trying to make creation time.")?;
138
Janis Danisevskis1af91262020-08-10 14:58:08 -0700139 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800140 Domain::BLOB => KeyDescriptor {
141 domain: Domain::BLOB,
142 blob: Some(key_blob.to_vec()),
143 ..Default::default()
144 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700145 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800146 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800147 let mut db = db.borrow_mut();
148
149 let (key_blob, mut blob_metadata) = SUPER_KEY
150 .handle_super_encryption_on_key_init(
151 &mut db,
152 &LEGACY_MIGRATOR,
153 &(key.domain),
154 &key_parameters,
155 flags,
156 user_id,
157 &key_blob,
158 )
159 .context("In store_new_key. Failed to handle super encryption.")?;
160
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800161 let mut key_metadata = KeyMetaData::new();
162 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800163 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800164
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800165 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800166 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800167 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800168 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800169 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800170 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800171 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800172 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800173 )
174 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700175 Ok(KeyDescriptor {
176 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800177 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700178 ..Default::default()
179 })
180 })
181 .context("In store_new_key.")?,
182 };
183
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700184 Ok(KeyMetadata {
185 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700186 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800187 certificate: cert_info.take_cert(),
188 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700189 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800190 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700191 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700192 }
193
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700194 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700195 &self,
196 key: &KeyDescriptor,
197 operation_parameters: &[KeyParameter],
198 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700199 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700200 let caller_uid = ThreadState::get_calling_uid();
201 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
202 // so that we can use it by reference like the blob provided by the key descriptor.
203 // Otherwise, we would have to clone the blob from the key descriptor.
204 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800205 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700206 Domain::BLOB => {
207 check_key_permission(KeyPerm::use_(), key, &None)
208 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800209 if forced {
210 check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
211 "In create_operation: checking forced permission for Domain::BLOB.",
212 )?;
213 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700214 (
215 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700216 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700217 None => {
218 return Err(Error::sys()).context(concat!(
219 "In create_operation: Key blob must be specified when",
220 " using Domain::BLOB."
221 ))
222 }
223 },
224 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000225 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000226 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700227 )
228 }
229 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800230 let (key_id_guard, mut key_entry) = DB
231 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000232 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
233 db.borrow_mut().load_key_entry(
234 &key,
235 KeyType::Client,
236 KeyEntryLoadBits::KM,
237 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800238 |k, av| {
239 check_key_permission(KeyPerm::use_(), k, &av)?;
240 if forced {
241 check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
242 }
243 Ok(())
244 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000245 )
246 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700247 })
248 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800249
250 let (blob, blob_metadata) =
251 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
252 "In create_operation: Successfully loaded key entry, ",
253 "but KM blob was missing."
254 ))?;
255 scoping_blob = blob;
256
Qi Wub9433b52020-12-01 14:52:46 +0800257 (
258 &scoping_blob,
259 Some((key_id_guard.id(), key_entry.into_key_parameters())),
260 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000261 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800262 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700263 }
264 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700265
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700266 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700267 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700268 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800269 |kp| match kp.value {
270 KeyParameterValue::KeyPurpose(p) => Ok(p),
271 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
272 .context("In create_operation: Malformed KeyParameter."),
273 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700274 )?;
275
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800276 let (immediate_hat, mut auth_info) = ENFORCEMENTS
277 .authorize_create(
278 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800279 key_properties.as_ref(),
280 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700281 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800282 )
283 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000284
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800285 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000286
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000287 let km_blob = SUPER_KEY
288 .unwrap_key_if_required(&blob_metadata, km_blob)
289 .context("In create_operation. Failed to handle super encryption.")?;
290
Stephen Crane221bbb52020-12-16 15:52:10 -0800291 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700292 .keymint
293 .get_interface()
294 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700295
Janis Danisevskisaec14592020-11-12 09:41:49 -0800296 let (begin_result, upgraded_blob) = self
297 .upgrade_keyblob_if_required_with(
298 &*km_dev,
299 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700300 &km_blob,
301 &blob_metadata,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700302 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800303 |blob| loop {
304 match map_km_error(km_dev.begin(
305 purpose,
306 blob,
307 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800308 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800309 )) {
310 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800311 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800312 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700313 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800314 v => return v,
315 }
316 },
317 )
318 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700319
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800320 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000321
Janis Danisevskis1af91262020-08-10 14:58:08 -0700322 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000323 Some(km_op) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800324 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000325 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700326 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 -0700327 };
328
Stephen Crane221bbb52020-12-16 15:52:10 -0800329 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700330 KeystoreOperation::new_native_binder(operation)
331 .as_binder()
332 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700333 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700334
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700335 Ok(CreateOperationResponse {
336 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000337 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700338 parameters: match begin_result.params.len() {
339 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700340 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700341 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800342 // An upgraded blob should only be returned if the caller has permission
343 // to use Domain::BLOB keys. If we got to this point, we already checked
344 // that the caller had that permission.
345 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700346 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700347 }
348
Janis Danisevskise766edc2021-02-06 12:16:26 -0800349 fn add_certificate_parameters(
350 uid: u32,
351 params: &[KeyParameter],
352 key: &KeyDescriptor,
353 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800354 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800355 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800356 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
357 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800358 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800359 })?;
360 result.push(KeyParameter {
361 tag: Tag::ATTESTATION_APPLICATION_ID,
362 value: KeyParameterValue::Blob(aaid),
363 });
364 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800365
Janis Danisevskise766edc2021-02-06 12:16:26 -0800366 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
367 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
368 "In add_certificate_parameters: ",
369 "Caller does not have the permission for device unique attestation."
370 ))?;
371 }
372
Bram Bonné5d6c5102021-02-24 15:09:18 +0100373 // If the caller requests any device identifier attestation tag, check that they hold the
374 // correct Android permission.
375 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
376 check_device_attestation_permissions().context(concat!(
377 "In add_certificate_parameters: ",
378 "Caller does not have the permission to attest device identifiers."
379 ))?;
380 }
381
Janis Danisevskis2c084012021-01-31 22:23:17 -0800382 // If we are generating/importing an asymmetric key, we need to make sure
383 // that NOT_BEFORE and NOT_AFTER are present.
384 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
385 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
386 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
387 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
388 result.push(KeyParameter {
389 tag: Tag::CERTIFICATE_NOT_BEFORE,
390 value: KeyParameterValue::DateTime(0),
391 })
392 }
393 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
394 result.push(KeyParameter {
395 tag: Tag::CERTIFICATE_NOT_AFTER,
396 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
397 })
398 }
399 }
400 _ => {}
401 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800402 Ok(result)
403 }
404
Janis Danisevskis1af91262020-08-10 14:58:08 -0700405 fn generate_key(
406 &self,
407 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700408 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700409 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700410 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700411 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700412 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700413 if key.domain != Domain::BLOB && key.alias.is_none() {
414 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
415 .context("In generate_key: Alias must be specified");
416 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000417 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700418
419 let key = match key.domain {
420 Domain::APP => KeyDescriptor {
421 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000422 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700423 alias: key.alias.clone(),
424 blob: None,
425 },
426 _ => key.clone(),
427 };
428
429 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700430 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700431 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700432
433 let attestation_key_info = match (key.domain, attest_key_descriptor) {
434 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800435 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700436 .with(|db| {
437 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800438 &key,
439 caller_uid,
440 attest_key_descriptor,
441 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700442 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800443 &mut db.borrow_mut(),
444 )
445 })
446 .context("In generate_key: Trying to get an attestation key")?,
447 };
Janis Danisevskise766edc2021-02-06 12:16:26 -0800448 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800449 .context("In generate_key: Trying to get aaid.")?;
450
Stephen Crane221bbb52020-12-16 15:52:10 -0800451 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700452
453 let creation_result = match attestation_key_info {
454 Some(AttestationKeyInfo::UserGenerated {
455 key_id_guard,
456 blob,
457 blob_metadata,
458 issuer_subject,
459 }) => self
460 .upgrade_keyblob_if_required_with(
461 &*km_dev,
462 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700463 &KeyBlob::Ref(&blob),
464 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700465 &params,
466 |blob| {
467 let attest_key = Some(AttestationKey {
468 keyBlob: blob.to_vec(),
469 attestKeyParams: vec![],
470 issuerSubjectName: issuer_subject.clone(),
471 });
472 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
473 },
474 )
475 .context("In generate_key: Using user generated attestation key.")
476 .map(|(result, _)| result),
477 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
478 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
479 .context("While generating Key with remote provisioned attestation key.")
480 .map(|mut creation_result| {
481 creation_result.certificateChain.push(attestation_certs);
482 creation_result
483 })
484 }
485 None => map_km_error(km_dev.generateKey(&params, None))
486 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800487 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700488 .context("In generate_key.")?;
489
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000490 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000491 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700492 }
493
494 fn import_key(
495 &self,
496 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700497 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700498 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700499 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700500 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700501 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700502 if key.domain != Domain::BLOB && key.alias.is_none() {
503 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
504 .context("In import_key: Alias must be specified");
505 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000506 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700507
508 let key = match key.domain {
509 Domain::APP => KeyDescriptor {
510 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000511 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700512 alias: key.alias.clone(),
513 blob: None,
514 },
515 _ => key.clone(),
516 };
517
518 // import_key requires the rebind permission.
519 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
520
Janis Danisevskise766edc2021-02-06 12:16:26 -0800521 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800522 .context("In import_key: Trying to get aaid.")?;
523
Janis Danisevskis1af91262020-08-10 14:58:08 -0700524 let format = params
525 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700526 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
528 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800529 .and_then(|p| match &p.value {
530 KeyParameterValue::Algorithm(Algorithm::AES)
531 | KeyParameterValue::Algorithm(Algorithm::HMAC)
532 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
533 KeyParameterValue::Algorithm(Algorithm::RSA)
534 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
535 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
536 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700537 })
538 .context("In import_key.")?;
539
Stephen Crane221bbb52020-12-16 15:52:10 -0800540 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800541 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700542 let creation_result =
543 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
544 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700545
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000546 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000547 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700548 }
549
550 fn import_wrapped_key(
551 &self,
552 key: &KeyDescriptor,
553 wrapping_key: &KeyDescriptor,
554 masking_key: Option<&[u8]>,
555 params: &[KeyParameter],
556 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700557 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800558 let wrapped_data: &[u8] = match key {
559 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
560 | KeyDescriptor {
561 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
562 } => blob,
563 _ => {
564 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
565 concat!(
566 "In import_wrapped_key: Alias and blob must be specified ",
567 "and domain must be APP or SELINUX. {:?}"
568 ),
569 key
570 ))
571 }
572 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700573
Janis Danisevskisaec14592020-11-12 09:41:49 -0800574 if wrapping_key.domain == Domain::BLOB {
575 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
576 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
577 );
578 }
579
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000580 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000581 let user_id = uid_to_android_user(caller_uid);
582
Janis Danisevskis1af91262020-08-10 14:58:08 -0700583 let key = match key.domain {
584 Domain::APP => KeyDescriptor {
585 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000586 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700587 alias: key.alias.clone(),
588 blob: None,
589 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800590 Domain::SELINUX => KeyDescriptor {
591 domain: Domain::SELINUX,
592 nspace: key.nspace,
593 alias: key.alias.clone(),
594 blob: None,
595 },
596 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700597 };
598
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800599 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700600 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
601
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000602 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700603 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000604 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
605 db.borrow_mut().load_key_entry(
606 &wrapping_key,
607 KeyType::Client,
608 KeyEntryLoadBits::KM,
609 caller_uid,
610 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
611 )
612 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700613 })
614 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000615
616 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
617 .take_key_blob_info()
618 .ok_or_else(error::Error::sys)
619 .context("No km_blob after successfully loading key. This should never happen.")?;
620
621 let wrapping_key_blob =
622 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
623 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
624 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700625
Janis Danisevskis1af91262020-08-10 14:58:08 -0700626 // km_dev.importWrappedKey does not return a certificate chain.
627 // TODO Do we assume that all wrapped keys are symmetric?
628 // let certificate_chain: Vec<KmCertificate> = Default::default();
629
630 let pw_sid = authenticators
631 .iter()
632 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700633 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700634 _ => None,
635 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800636 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700637
638 let fp_sid = authenticators
639 .iter()
640 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700641 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700642 _ => None,
643 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800644 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700645
646 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
647
Stephen Crane221bbb52020-12-16 15:52:10 -0800648 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800649 let (creation_result, _) = self
650 .upgrade_keyblob_if_required_with(
651 &*km_dev,
652 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700653 &wrapping_key_blob,
654 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800655 &[],
656 |wrapping_blob| {
657 let creation_result = map_km_error(km_dev.importWrappedKey(
658 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800659 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800660 masking_key,
661 &params,
662 pw_sid,
663 fp_sid,
664 ))?;
665 Ok(creation_result)
666 },
667 )
668 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700669
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000670 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800671 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700672 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800673
Paul Crowley7a658392021-03-18 17:08:20 -0700674 fn store_upgraded_keyblob(
675 key_id_guard: KeyIdGuard,
676 km_uuid: Option<&Uuid>,
677 key_blob: &KeyBlob,
678 upgraded_blob: &[u8],
679 ) -> Result<()> {
680 let (upgraded_blob_to_be_stored, new_blob_metadata) =
681 SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
682 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
683
684 let mut new_blob_metadata = new_blob_metadata.unwrap_or_else(BlobMetaData::new);
685 if let Some(uuid) = km_uuid {
686 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
687 }
688
689 DB.with(|db| {
690 let mut db = db.borrow_mut();
691 db.set_blob(
692 &key_id_guard,
693 SubComponentType::KEY_BLOB,
694 Some(&upgraded_blob_to_be_stored),
695 Some(&new_blob_metadata),
696 )
697 })
698 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
699 }
700
Janis Danisevskisaec14592020-11-12 09:41:49 -0800701 fn upgrade_keyblob_if_required_with<T, F>(
702 &self,
703 km_dev: &dyn IKeyMintDevice,
704 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700705 key_blob: &KeyBlob,
706 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800707 params: &[KeyParameter],
708 f: F,
709 ) -> Result<(T, Option<Vec<u8>>)>
710 where
711 F: Fn(&[u8]) -> Result<T, Error>,
712 {
Paul Crowley7a658392021-03-18 17:08:20 -0700713 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800714 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Paul Crowley7a658392021-03-18 17:08:20 -0700715 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800716 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000717
Paul Crowley7a658392021-03-18 17:08:20 -0700718 if let Some(kid) = key_id_guard {
719 Self::store_upgraded_keyblob(
720 kid,
721 blob_metadata.km_uuid(),
722 key_blob,
723 &upgraded_blob,
724 )
725 .context(
726 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000727 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000728 }
729
Janis Danisevskisaec14592020-11-12 09:41:49 -0800730 match f(&upgraded_blob) {
731 Ok(v) => Ok((v, Some(upgraded_blob))),
732 Err(e) => Err(e).context(concat!(
733 "In upgrade_keyblob_if_required_with: ",
734 "Failed to perform operation on second try."
735 )),
736 }
737 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700738 result => {
739 if let Some(kid) = key_id_guard {
740 if key_blob.force_reencrypt() {
741 Self::store_upgraded_keyblob(
742 kid,
743 blob_metadata.km_uuid(),
744 key_blob,
745 key_blob,
746 )
747 .context(concat!(
748 "In upgrade_keyblob_if_required_with: ",
749 "store_upgraded_keyblob failed in forced reencrypt"
750 ))?;
751 }
752 }
753 result
754 .map(|v| (v, None))
755 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
756 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800757 }
758 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800759
760 fn convert_storage_key_to_ephemeral(&self, storage_key: &KeyDescriptor) -> Result<Vec<u8>> {
761 if storage_key.domain != Domain::BLOB {
762 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
763 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
764 "Key must be of Domain::BLOB"
765 ));
766 }
767 let key_blob = storage_key
768 .blob
769 .as_ref()
770 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
771 .context(
772 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
773 )?;
774
775 // convert_storage_key_to_ephemeral requires the associated permission
776 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
777 .context("In convert_storage_key_to_ephemeral: Check permission")?;
778
779 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
780 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
781 "Getting keymint device interface"
782 ))?;
783 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
784 .context("In keymint device convertStorageKeyToEphemeral")
785 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800786
787 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
788 if key.domain != Domain::BLOB {
789 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
790 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
791 }
792
793 let key_blob = key
794 .blob
795 .as_ref()
796 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
797 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
798
799 check_key_permission(KeyPerm::delete(), key, &None)
800 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
801
802 let km_dev: Strong<dyn IKeyMintDevice> = self
803 .keymint
804 .get_interface()
805 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
806 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
807 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700808}
809
810impl binder::Interface for KeystoreSecurityLevel {}
811
812impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700813 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700814 &self,
815 key: &KeyDescriptor,
816 operation_parameters: &[KeyParameter],
817 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700818 ) -> binder::public_api::Result<CreateOperationResponse> {
819 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700820 }
821 fn generateKey(
822 &self,
823 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700824 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700825 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700826 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700827 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700828 ) -> binder::public_api::Result<KeyMetadata> {
829 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700830 }
831 fn importKey(
832 &self,
833 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700834 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700835 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700836 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700837 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700838 ) -> binder::public_api::Result<KeyMetadata> {
839 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700840 }
841 fn importWrappedKey(
842 &self,
843 key: &KeyDescriptor,
844 wrapping_key: &KeyDescriptor,
845 masking_key: Option<&[u8]>,
846 params: &[KeyParameter],
847 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700848 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700849 map_or_log_err(
850 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700851 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700852 )
853 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800854 fn convertStorageKeyToEphemeral(
855 &self,
856 storage_key: &KeyDescriptor,
857 ) -> binder::public_api::Result<Vec<u8>> {
858 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
859 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800860 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
861 map_or_log_err(self.delete_key(key), Ok)
862 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700863}