blob: f7bf1c61f5a5c1f4d157baf614d4d7483f185278 [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;
Max Bires97f96812021-02-23 23:44:57 -080040use crate::remote_provisioning::RemProvState;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000041use crate::super_key::{KeyBlob, SuperKeyManager};
Bram Bonné5d6c5102021-02-24 15:09:18 +010042use crate::utils::{
43 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
44 uid_to_android_user, Asp,
45};
Max Bires8e93d2b2021-01-14 13:17:59 -080046use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080047 database::{
48 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
49 KeyMetaEntry, KeyType, SubComponentType, Uuid,
50 },
51 operation::KeystoreOperation,
52 operation::OperationDb,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080053 permission::KeyPerm,
54};
55use crate::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070056 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
57 utils::key_characteristics_to_internal,
58};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080059use anyhow::{anyhow, Context, Result};
Andrew Walbran808e8602021-03-16 13:58:28 +000060use binder::{IBinderInternal, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070061
62/// Implementation of the IKeystoreSecurityLevel Interface.
63pub struct KeystoreSecurityLevel {
64 security_level: SecurityLevel,
65 keymint: Asp,
Max Bires8e93d2b2021-01-14 13:17:59 -080066 #[allow(dead_code)]
67 hw_info: KeyMintHardwareInfo,
68 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070069 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080070 rem_prov_state: RemProvState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070071}
72
Janis Danisevskis1af91262020-08-10 14:58:08 -070073// Blob of 32 zeroes used as empty masking key.
74static ZERO_BLOB_32: &[u8] = &[0; 32];
75
Janis Danisevskis2c084012021-01-31 22:23:17 -080076// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
77// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
78const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
79
Janis Danisevskis1af91262020-08-10 14:58:08 -070080impl KeystoreSecurityLevel {
81 /// Creates a new security level instance wrapped in a
82 /// BnKeystoreSecurityLevel proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +000083 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070084 /// we need it for checking keystore permissions.
85 pub fn new_native_binder(
86 security_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -080087 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080088 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
89 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070090 let result = BnKeystoreSecurityLevel::new_binder(Self {
91 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080092 keymint: dev,
93 hw_info,
94 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070095 operation_db: OperationDb::new(),
Max Bires97f96812021-02-23 23:44:57 -080096 rem_prov_state: RemProvState::new(security_level, km_uuid),
Janis Danisevskis1af91262020-08-10 14:58:08 -070097 });
98 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -080099 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700100 }
101
102 fn store_new_key(
103 &self,
104 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700105 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000106 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000107 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700108 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700109 let KeyCreationResult {
110 keyBlob: key_blob,
111 keyCharacteristics: key_characteristics,
112 certificateChain: mut certificate_chain,
113 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700114
Max Bires8e93d2b2021-01-14 13:17:59 -0800115 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700116 match certificate_chain.len() {
117 0 => None,
118 _ => Some(certificate_chain.remove(0).encodedCertificate),
119 },
120 match certificate_chain.len() {
121 0 => None,
122 _ => Some(
123 certificate_chain
124 .iter()
125 .map(|c| c.encodedCertificate.iter())
126 .flatten()
127 .copied()
128 .collect(),
129 ),
130 },
131 );
132
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000133 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
134
135 key_parameters.push(KsKeyParam::new(
136 KsKeyParamValue::UserID(user_id as i32),
137 SecurityLevel::SOFTWARE,
138 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700139
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800140 let creation_date = DateTime::now().context("Trying to make creation time.")?;
141
Janis Danisevskis1af91262020-08-10 14:58:08 -0700142 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800143 Domain::BLOB => KeyDescriptor {
144 domain: Domain::BLOB,
145 blob: Some(key_blob.to_vec()),
146 ..Default::default()
147 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700148 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800149 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800150 let mut db = db.borrow_mut();
151
152 let (key_blob, mut blob_metadata) = SUPER_KEY
153 .handle_super_encryption_on_key_init(
154 &mut db,
155 &LEGACY_MIGRATOR,
156 &(key.domain),
157 &key_parameters,
158 flags,
159 user_id,
160 &key_blob,
161 )
162 .context("In store_new_key. Failed to handle super encryption.")?;
163
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800164 let mut key_metadata = KeyMetaData::new();
165 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800166 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800167
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800168 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800169 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800170 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800171 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800172 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800173 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800174 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800175 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800176 )
177 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700178 Ok(KeyDescriptor {
179 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800180 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700181 ..Default::default()
182 })
183 })
184 .context("In store_new_key.")?,
185 };
186
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700187 Ok(KeyMetadata {
188 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700189 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800190 certificate: cert_info.take_cert(),
191 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700192 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800193 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700194 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700195 }
196
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700197 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700198 &self,
199 key: &KeyDescriptor,
200 operation_parameters: &[KeyParameter],
201 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700202 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700203 let caller_uid = ThreadState::get_calling_uid();
204 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
205 // so that we can use it by reference like the blob provided by the key descriptor.
206 // Otherwise, we would have to clone the blob from the key descriptor.
207 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800208 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700209 Domain::BLOB => {
210 check_key_permission(KeyPerm::use_(), key, &None)
211 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800212 if forced {
213 check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
214 "In create_operation: checking forced permission for Domain::BLOB.",
215 )?;
216 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700217 (
218 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700219 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700220 None => {
221 return Err(Error::sys()).context(concat!(
222 "In create_operation: Key blob must be specified when",
223 " using Domain::BLOB."
224 ))
225 }
226 },
227 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000228 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000229 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700230 )
231 }
232 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800233 let (key_id_guard, mut key_entry) = DB
234 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000235 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
236 db.borrow_mut().load_key_entry(
237 &key,
238 KeyType::Client,
239 KeyEntryLoadBits::KM,
240 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800241 |k, av| {
242 check_key_permission(KeyPerm::use_(), k, &av)?;
243 if forced {
244 check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
245 }
246 Ok(())
247 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000248 )
249 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700250 })
251 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800252
253 let (blob, blob_metadata) =
254 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
255 "In create_operation: Successfully loaded key entry, ",
256 "but KM blob was missing."
257 ))?;
258 scoping_blob = blob;
259
Qi Wub9433b52020-12-01 14:52:46 +0800260 (
261 &scoping_blob,
262 Some((key_id_guard.id(), key_entry.into_key_parameters())),
263 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000264 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800265 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700266 }
267 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700268
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700269 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700270 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700271 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800272 |kp| match kp.value {
273 KeyParameterValue::KeyPurpose(p) => Ok(p),
274 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
275 .context("In create_operation: Malformed KeyParameter."),
276 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700277 )?;
278
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800279 let (immediate_hat, mut auth_info) = ENFORCEMENTS
280 .authorize_create(
281 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800282 key_properties.as_ref(),
283 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700284 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800285 )
286 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000287
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800288 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000289
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000290 let km_blob = SUPER_KEY
291 .unwrap_key_if_required(&blob_metadata, km_blob)
292 .context("In create_operation. Failed to handle super encryption.")?;
293
Stephen Crane221bbb52020-12-16 15:52:10 -0800294 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700295 .keymint
296 .get_interface()
297 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700298
Janis Danisevskisaec14592020-11-12 09:41:49 -0800299 let (begin_result, upgraded_blob) = self
300 .upgrade_keyblob_if_required_with(
301 &*km_dev,
302 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700303 &km_blob,
304 &blob_metadata,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700305 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800306 |blob| loop {
307 match map_km_error(km_dev.begin(
308 purpose,
309 blob,
310 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800311 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800312 )) {
313 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800314 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800315 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700316 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800317 v => return v,
318 }
319 },
320 )
321 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700322
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800323 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000324
Janis Danisevskis1af91262020-08-10 14:58:08 -0700325 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000326 Some(km_op) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800327 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000328 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700329 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 -0700330 };
331
Stephen Crane221bbb52020-12-16 15:52:10 -0800332 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700333 KeystoreOperation::new_native_binder(operation)
334 .as_binder()
335 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700336 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700337
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700338 Ok(CreateOperationResponse {
339 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000340 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700341 parameters: match begin_result.params.len() {
342 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700343 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700344 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800345 // An upgraded blob should only be returned if the caller has permission
346 // to use Domain::BLOB keys. If we got to this point, we already checked
347 // that the caller had that permission.
348 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700349 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700350 }
351
Janis Danisevskise766edc2021-02-06 12:16:26 -0800352 fn add_certificate_parameters(
353 uid: u32,
354 params: &[KeyParameter],
355 key: &KeyDescriptor,
356 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800357 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800358 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800359 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
360 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800361 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800362 })?;
363 result.push(KeyParameter {
364 tag: Tag::ATTESTATION_APPLICATION_ID,
365 value: KeyParameterValue::Blob(aaid),
366 });
367 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800368
Janis Danisevskise766edc2021-02-06 12:16:26 -0800369 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
370 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
371 "In add_certificate_parameters: ",
372 "Caller does not have the permission for device unique attestation."
373 ))?;
374 }
375
Bram Bonné5d6c5102021-02-24 15:09:18 +0100376 // If the caller requests any device identifier attestation tag, check that they hold the
377 // correct Android permission.
378 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
379 check_device_attestation_permissions().context(concat!(
380 "In add_certificate_parameters: ",
381 "Caller does not have the permission to attest device identifiers."
382 ))?;
383 }
384
Janis Danisevskis2c084012021-01-31 22:23:17 -0800385 // If we are generating/importing an asymmetric key, we need to make sure
386 // that NOT_BEFORE and NOT_AFTER are present.
387 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
388 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
389 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
390 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
391 result.push(KeyParameter {
392 tag: Tag::CERTIFICATE_NOT_BEFORE,
393 value: KeyParameterValue::DateTime(0),
394 })
395 }
396 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
397 result.push(KeyParameter {
398 tag: Tag::CERTIFICATE_NOT_AFTER,
399 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
400 })
401 }
402 }
403 _ => {}
404 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800405 Ok(result)
406 }
407
Janis Danisevskis1af91262020-08-10 14:58:08 -0700408 fn generate_key(
409 &self,
410 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700411 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700412 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700413 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700414 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700415 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700416 if key.domain != Domain::BLOB && key.alias.is_none() {
417 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
418 .context("In generate_key: Alias must be specified");
419 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000420 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700421
422 let key = match key.domain {
423 Domain::APP => KeyDescriptor {
424 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000425 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700426 alias: key.alias.clone(),
427 blob: None,
428 },
429 _ => key.clone(),
430 };
431
432 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700433 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700434 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700435
436 let attestation_key_info = match (key.domain, attest_key_descriptor) {
437 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800438 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700439 .with(|db| {
440 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800441 &key,
442 caller_uid,
443 attest_key_descriptor,
444 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700445 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800446 &mut db.borrow_mut(),
447 )
448 })
449 .context("In generate_key: Trying to get an attestation key")?,
450 };
Janis Danisevskise766edc2021-02-06 12:16:26 -0800451 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800452 .context("In generate_key: Trying to get aaid.")?;
453
Stephen Crane221bbb52020-12-16 15:52:10 -0800454 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700455
456 let creation_result = match attestation_key_info {
457 Some(AttestationKeyInfo::UserGenerated {
458 key_id_guard,
459 blob,
460 blob_metadata,
461 issuer_subject,
462 }) => self
463 .upgrade_keyblob_if_required_with(
464 &*km_dev,
465 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700466 &KeyBlob::Ref(&blob),
467 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700468 &params,
469 |blob| {
470 let attest_key = Some(AttestationKey {
471 keyBlob: blob.to_vec(),
472 attestKeyParams: vec![],
473 issuerSubjectName: issuer_subject.clone(),
474 });
475 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
476 },
477 )
478 .context("In generate_key: Using user generated attestation key.")
479 .map(|(result, _)| result),
480 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
481 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
482 .context("While generating Key with remote provisioned attestation key.")
483 .map(|mut creation_result| {
484 creation_result.certificateChain.push(attestation_certs);
485 creation_result
486 })
487 }
488 None => map_km_error(km_dev.generateKey(&params, None))
489 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800490 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700491 .context("In generate_key.")?;
492
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000493 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000494 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700495 }
496
497 fn import_key(
498 &self,
499 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700500 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700501 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700502 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700503 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700504 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700505 if key.domain != Domain::BLOB && key.alias.is_none() {
506 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
507 .context("In import_key: Alias must be specified");
508 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000509 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700510
511 let key = match key.domain {
512 Domain::APP => KeyDescriptor {
513 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000514 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700515 alias: key.alias.clone(),
516 blob: None,
517 },
518 _ => key.clone(),
519 };
520
521 // import_key requires the rebind permission.
522 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
523
Janis Danisevskise766edc2021-02-06 12:16:26 -0800524 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800525 .context("In import_key: Trying to get aaid.")?;
526
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 let format = params
528 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700529 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700530 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
531 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800532 .and_then(|p| match &p.value {
533 KeyParameterValue::Algorithm(Algorithm::AES)
534 | KeyParameterValue::Algorithm(Algorithm::HMAC)
535 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
536 KeyParameterValue::Algorithm(Algorithm::RSA)
537 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
538 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
539 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700540 })
541 .context("In import_key.")?;
542
Stephen Crane221bbb52020-12-16 15:52:10 -0800543 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800544 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700545 let creation_result =
546 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
547 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700548
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000549 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000550 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700551 }
552
553 fn import_wrapped_key(
554 &self,
555 key: &KeyDescriptor,
556 wrapping_key: &KeyDescriptor,
557 masking_key: Option<&[u8]>,
558 params: &[KeyParameter],
559 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700560 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800561 let wrapped_data: &[u8] = match key {
562 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
563 | KeyDescriptor {
564 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
565 } => blob,
566 _ => {
567 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
568 concat!(
569 "In import_wrapped_key: Alias and blob must be specified ",
570 "and domain must be APP or SELINUX. {:?}"
571 ),
572 key
573 ))
574 }
575 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700576
Janis Danisevskisaec14592020-11-12 09:41:49 -0800577 if wrapping_key.domain == Domain::BLOB {
578 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
579 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
580 );
581 }
582
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000583 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000584 let user_id = uid_to_android_user(caller_uid);
585
Janis Danisevskis1af91262020-08-10 14:58:08 -0700586 let key = match key.domain {
587 Domain::APP => KeyDescriptor {
588 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000589 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700590 alias: key.alias.clone(),
591 blob: None,
592 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800593 Domain::SELINUX => KeyDescriptor {
594 domain: Domain::SELINUX,
595 nspace: key.nspace,
596 alias: key.alias.clone(),
597 blob: None,
598 },
599 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700600 };
601
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800602 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700603 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
604
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000605 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700606 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000607 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
608 db.borrow_mut().load_key_entry(
609 &wrapping_key,
610 KeyType::Client,
611 KeyEntryLoadBits::KM,
612 caller_uid,
613 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
614 )
615 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700616 })
617 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000618
619 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
620 .take_key_blob_info()
621 .ok_or_else(error::Error::sys)
622 .context("No km_blob after successfully loading key. This should never happen.")?;
623
624 let wrapping_key_blob =
625 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
626 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
627 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700628
Janis Danisevskis1af91262020-08-10 14:58:08 -0700629 // km_dev.importWrappedKey does not return a certificate chain.
630 // TODO Do we assume that all wrapped keys are symmetric?
631 // let certificate_chain: Vec<KmCertificate> = Default::default();
632
633 let pw_sid = authenticators
634 .iter()
635 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700636 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700637 _ => None,
638 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800639 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700640
641 let fp_sid = authenticators
642 .iter()
643 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700644 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700645 _ => None,
646 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800647 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700648
649 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
650
Stephen Crane221bbb52020-12-16 15:52:10 -0800651 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800652 let (creation_result, _) = self
653 .upgrade_keyblob_if_required_with(
654 &*km_dev,
655 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700656 &wrapping_key_blob,
657 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800658 &[],
659 |wrapping_blob| {
660 let creation_result = map_km_error(km_dev.importWrappedKey(
661 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800662 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800663 masking_key,
664 &params,
665 pw_sid,
666 fp_sid,
667 ))?;
668 Ok(creation_result)
669 },
670 )
671 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700672
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000673 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800674 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700675 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800676
Paul Crowley7a658392021-03-18 17:08:20 -0700677 fn store_upgraded_keyblob(
678 key_id_guard: KeyIdGuard,
679 km_uuid: Option<&Uuid>,
680 key_blob: &KeyBlob,
681 upgraded_blob: &[u8],
682 ) -> Result<()> {
683 let (upgraded_blob_to_be_stored, new_blob_metadata) =
684 SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
685 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
686
687 let mut new_blob_metadata = new_blob_metadata.unwrap_or_else(BlobMetaData::new);
688 if let Some(uuid) = km_uuid {
689 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
690 }
691
692 DB.with(|db| {
693 let mut db = db.borrow_mut();
694 db.set_blob(
695 &key_id_guard,
696 SubComponentType::KEY_BLOB,
697 Some(&upgraded_blob_to_be_stored),
698 Some(&new_blob_metadata),
699 )
700 })
701 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
702 }
703
Janis Danisevskisaec14592020-11-12 09:41:49 -0800704 fn upgrade_keyblob_if_required_with<T, F>(
705 &self,
706 km_dev: &dyn IKeyMintDevice,
707 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700708 key_blob: &KeyBlob,
709 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800710 params: &[KeyParameter],
711 f: F,
712 ) -> Result<(T, Option<Vec<u8>>)>
713 where
714 F: Fn(&[u8]) -> Result<T, Error>,
715 {
Paul Crowley7a658392021-03-18 17:08:20 -0700716 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800717 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Paul Crowley7a658392021-03-18 17:08:20 -0700718 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800719 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000720
Paul Crowley7a658392021-03-18 17:08:20 -0700721 if let Some(kid) = key_id_guard {
722 Self::store_upgraded_keyblob(
723 kid,
724 blob_metadata.km_uuid(),
725 key_blob,
726 &upgraded_blob,
727 )
728 .context(
729 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000730 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000731 }
732
Janis Danisevskisaec14592020-11-12 09:41:49 -0800733 match f(&upgraded_blob) {
734 Ok(v) => Ok((v, Some(upgraded_blob))),
735 Err(e) => Err(e).context(concat!(
736 "In upgrade_keyblob_if_required_with: ",
737 "Failed to perform operation on second try."
738 )),
739 }
740 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700741 result => {
742 if let Some(kid) = key_id_guard {
743 if key_blob.force_reencrypt() {
744 Self::store_upgraded_keyblob(
745 kid,
746 blob_metadata.km_uuid(),
747 key_blob,
748 key_blob,
749 )
750 .context(concat!(
751 "In upgrade_keyblob_if_required_with: ",
752 "store_upgraded_keyblob failed in forced reencrypt"
753 ))?;
754 }
755 }
756 result
757 .map(|v| (v, None))
758 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
759 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800760 }
761 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800762
763 fn convert_storage_key_to_ephemeral(&self, storage_key: &KeyDescriptor) -> Result<Vec<u8>> {
764 if storage_key.domain != Domain::BLOB {
765 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
766 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
767 "Key must be of Domain::BLOB"
768 ));
769 }
770 let key_blob = storage_key
771 .blob
772 .as_ref()
773 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
774 .context(
775 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
776 )?;
777
778 // convert_storage_key_to_ephemeral requires the associated permission
779 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
780 .context("In convert_storage_key_to_ephemeral: Check permission")?;
781
782 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
783 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
784 "Getting keymint device interface"
785 ))?;
786 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
787 .context("In keymint device convertStorageKeyToEphemeral")
788 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800789
790 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
791 if key.domain != Domain::BLOB {
792 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
793 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
794 }
795
796 let key_blob = key
797 .blob
798 .as_ref()
799 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
800 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
801
802 check_key_permission(KeyPerm::delete(), key, &None)
803 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
804
805 let km_dev: Strong<dyn IKeyMintDevice> = self
806 .keymint
807 .get_interface()
808 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
809 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
810 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700811}
812
813impl binder::Interface for KeystoreSecurityLevel {}
814
815impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700816 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700817 &self,
818 key: &KeyDescriptor,
819 operation_parameters: &[KeyParameter],
820 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700821 ) -> binder::public_api::Result<CreateOperationResponse> {
822 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700823 }
824 fn generateKey(
825 &self,
826 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700827 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700828 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700829 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700830 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700831 ) -> binder::public_api::Result<KeyMetadata> {
832 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700833 }
834 fn importKey(
835 &self,
836 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700837 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700838 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700839 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700840 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700841 ) -> binder::public_api::Result<KeyMetadata> {
842 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700843 }
844 fn importWrappedKey(
845 &self,
846 key: &KeyDescriptor,
847 wrapping_key: &KeyDescriptor,
848 masking_key: Option<&[u8]>,
849 params: &[KeyParameter],
850 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700851 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700852 map_or_log_err(
853 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700854 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700855 )
856 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800857 fn convertStorageKeyToEphemeral(
858 &self,
859 storage_key: &KeyDescriptor,
860 ) -> binder::public_api::Result<Vec<u8>> {
861 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
862 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800863 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
864 map_or_log_err(self.delete_key(key), Ok)
865 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700866}