blob: ec6c4d75eac6a4936b966205188f69984dd08440 [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;
Hasini Gunasingheb7142972021-02-20 03:11:27 +000038use crate::metrics::log_key_creation_event_stats;
Max Bires97f96812021-02-23 23:44:57 -080039use crate::remote_provisioning::RemProvState;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000040use crate::super_key::{KeyBlob, SuperKeyManager};
Bram Bonné5d6c5102021-02-24 15:09:18 +010041use crate::utils::{
42 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
43 uid_to_android_user, Asp,
44};
Max Bires8e93d2b2021-01-14 13:17:59 -080045use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080046 database::{
47 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
48 KeyMetaEntry, KeyType, SubComponentType, Uuid,
49 },
50 operation::KeystoreOperation,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +000051 operation::LoggingInfo,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080052 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 hw_info: KeyMintHardwareInfo,
67 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070068 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080069 rem_prov_state: RemProvState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070070}
71
Janis Danisevskis1af91262020-08-10 14:58:08 -070072// Blob of 32 zeroes used as empty masking key.
73static ZERO_BLOB_32: &[u8] = &[0; 32];
74
Janis Danisevskis2c084012021-01-31 22:23:17 -080075// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
76// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
77const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
78
Janis Danisevskis1af91262020-08-10 14:58:08 -070079impl KeystoreSecurityLevel {
80 /// Creates a new security level instance wrapped in a
81 /// BnKeystoreSecurityLevel proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +000082 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070083 /// we need it for checking keystore permissions.
84 pub fn new_native_binder(
85 security_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -080086 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080087 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
88 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070089 let result = BnKeystoreSecurityLevel::new_binder(Self {
90 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080091 keymint: dev,
92 hw_info,
93 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070094 operation_db: OperationDb::new(),
Max Bires97f96812021-02-23 23:44:57 -080095 rem_prov_state: RemProvState::new(security_level, km_uuid),
Janis Danisevskis1af91262020-08-10 14:58:08 -070096 });
97 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -080098 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -070099 }
100
101 fn store_new_key(
102 &self,
103 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700104 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000105 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000106 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700107 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700108 let KeyCreationResult {
109 keyBlob: key_blob,
110 keyCharacteristics: key_characteristics,
111 certificateChain: mut certificate_chain,
112 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700113
Max Bires8e93d2b2021-01-14 13:17:59 -0800114 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700115 match certificate_chain.len() {
116 0 => None,
117 _ => Some(certificate_chain.remove(0).encodedCertificate),
118 },
119 match certificate_chain.len() {
120 0 => None,
121 _ => Some(
122 certificate_chain
123 .iter()
124 .map(|c| c.encodedCertificate.iter())
125 .flatten()
126 .copied()
127 .collect(),
128 ),
129 },
130 );
131
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000132 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
133
134 key_parameters.push(KsKeyParam::new(
135 KsKeyParamValue::UserID(user_id as i32),
136 SecurityLevel::SOFTWARE,
137 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700138
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800139 let creation_date = DateTime::now().context("Trying to make creation time.")?;
140
Janis Danisevskis1af91262020-08-10 14:58:08 -0700141 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800142 Domain::BLOB => KeyDescriptor {
143 domain: Domain::BLOB,
144 blob: Some(key_blob.to_vec()),
145 ..Default::default()
146 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700147 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800148 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800149 let mut db = db.borrow_mut();
150
151 let (key_blob, mut blob_metadata) = SUPER_KEY
152 .handle_super_encryption_on_key_init(
153 &mut db,
154 &LEGACY_MIGRATOR,
155 &(key.domain),
156 &key_parameters,
157 flags,
158 user_id,
159 &key_blob,
160 )
161 .context("In store_new_key. Failed to handle super encryption.")?;
162
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800163 let mut key_metadata = KeyMetaData::new();
164 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800165 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800166
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800167 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800168 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800169 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800170 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800171 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800172 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800173 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800174 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800175 )
176 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700177 Ok(KeyDescriptor {
178 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800179 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700180 ..Default::default()
181 })
182 })
183 .context("In store_new_key.")?,
184 };
185
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700186 Ok(KeyMetadata {
187 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700188 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800189 certificate: cert_info.take_cert(),
190 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700191 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800192 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700193 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700194 }
195
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700196 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700197 &self,
198 key: &KeyDescriptor,
199 operation_parameters: &[KeyParameter],
200 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700201 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700202 let caller_uid = ThreadState::get_calling_uid();
203 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
204 // so that we can use it by reference like the blob provided by the key descriptor.
205 // Otherwise, we would have to clone the blob from the key descriptor.
206 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800207 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700208 Domain::BLOB => {
209 check_key_permission(KeyPerm::use_(), key, &None)
210 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800211 if forced {
212 check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
213 "In create_operation: checking forced permission for Domain::BLOB.",
214 )?;
215 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700216 (
217 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700218 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700219 None => {
220 return Err(Error::sys()).context(concat!(
221 "In create_operation: Key blob must be specified when",
222 " using Domain::BLOB."
223 ))
224 }
225 },
226 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000227 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000228 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700229 )
230 }
231 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800232 let (key_id_guard, mut key_entry) = DB
233 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000234 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
235 db.borrow_mut().load_key_entry(
236 &key,
237 KeyType::Client,
238 KeyEntryLoadBits::KM,
239 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800240 |k, av| {
241 check_key_permission(KeyPerm::use_(), k, &av)?;
242 if forced {
243 check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
244 }
245 Ok(())
246 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000247 )
248 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700249 })
250 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800251
252 let (blob, blob_metadata) =
253 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
254 "In create_operation: Successfully loaded key entry, ",
255 "but KM blob was missing."
256 ))?;
257 scoping_blob = blob;
258
Qi Wub9433b52020-12-01 14:52:46 +0800259 (
260 &scoping_blob,
261 Some((key_id_guard.id(), key_entry.into_key_parameters())),
262 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000263 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800264 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700265 }
266 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700267
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700268 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700269 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700270 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800271 |kp| match kp.value {
272 KeyParameterValue::KeyPurpose(p) => Ok(p),
273 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
274 .context("In create_operation: Malformed KeyParameter."),
275 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700276 )?;
277
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800278 let (immediate_hat, mut auth_info) = ENFORCEMENTS
279 .authorize_create(
280 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800281 key_properties.as_ref(),
282 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700283 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800284 )
285 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000286
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800287 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000288
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000289 let km_blob = SUPER_KEY
290 .unwrap_key_if_required(&blob_metadata, km_blob)
291 .context("In create_operation. Failed to handle super encryption.")?;
292
Stephen Crane221bbb52020-12-16 15:52:10 -0800293 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700294 .keymint
295 .get_interface()
296 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700297
Janis Danisevskisaec14592020-11-12 09:41:49 -0800298 let (begin_result, upgraded_blob) = self
299 .upgrade_keyblob_if_required_with(
300 &*km_dev,
301 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700302 &km_blob,
303 &blob_metadata,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700304 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800305 |blob| loop {
306 match map_km_error(km_dev.begin(
307 purpose,
308 blob,
309 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800310 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800311 )) {
312 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800313 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800314 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700315 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800316 v => return v,
317 }
318 },
319 )
320 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700321
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800322 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000323
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000324 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
325
Janis Danisevskis1af91262020-08-10 14:58:08 -0700326 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000327 Some(km_op) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000328 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced,
329 LoggingInfo::new(purpose, op_params, upgraded_blob.is_some()))
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000330 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700331 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 -0700332 };
333
Stephen Crane221bbb52020-12-16 15:52:10 -0800334 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700335 KeystoreOperation::new_native_binder(operation)
336 .as_binder()
337 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700338 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700339
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700340 Ok(CreateOperationResponse {
341 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000342 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700343 parameters: match begin_result.params.len() {
344 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700345 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700346 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800347 // An upgraded blob should only be returned if the caller has permission
348 // to use Domain::BLOB keys. If we got to this point, we already checked
349 // that the caller had that permission.
350 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700351 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700352 }
353
Janis Danisevskise766edc2021-02-06 12:16:26 -0800354 fn add_certificate_parameters(
355 uid: u32,
356 params: &[KeyParameter],
357 key: &KeyDescriptor,
358 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800359 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800360 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800361 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
362 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800363 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800364 })?;
365 result.push(KeyParameter {
366 tag: Tag::ATTESTATION_APPLICATION_ID,
367 value: KeyParameterValue::Blob(aaid),
368 });
369 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800370
Janis Danisevskise766edc2021-02-06 12:16:26 -0800371 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
372 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
373 "In add_certificate_parameters: ",
374 "Caller does not have the permission for device unique attestation."
375 ))?;
376 }
377
Bram Bonné5d6c5102021-02-24 15:09:18 +0100378 // If the caller requests any device identifier attestation tag, check that they hold the
379 // correct Android permission.
380 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
381 check_device_attestation_permissions().context(concat!(
382 "In add_certificate_parameters: ",
383 "Caller does not have the permission to attest device identifiers."
384 ))?;
385 }
386
Janis Danisevskis2c084012021-01-31 22:23:17 -0800387 // If we are generating/importing an asymmetric key, we need to make sure
388 // that NOT_BEFORE and NOT_AFTER are present.
389 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
390 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
391 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
392 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
393 result.push(KeyParameter {
394 tag: Tag::CERTIFICATE_NOT_BEFORE,
395 value: KeyParameterValue::DateTime(0),
396 })
397 }
398 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
399 result.push(KeyParameter {
400 tag: Tag::CERTIFICATE_NOT_AFTER,
401 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
402 })
403 }
404 }
405 _ => {}
406 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800407 Ok(result)
408 }
409
Janis Danisevskis1af91262020-08-10 14:58:08 -0700410 fn generate_key(
411 &self,
412 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700413 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700414 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700415 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700416 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700417 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700418 if key.domain != Domain::BLOB && key.alias.is_none() {
419 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
420 .context("In generate_key: Alias must be specified");
421 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000422 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700423
424 let key = match key.domain {
425 Domain::APP => KeyDescriptor {
426 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000427 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700428 alias: key.alias.clone(),
429 blob: None,
430 },
431 _ => key.clone(),
432 };
433
434 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700435 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700436 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700437
438 let attestation_key_info = match (key.domain, attest_key_descriptor) {
439 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800440 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700441 .with(|db| {
442 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800443 &key,
444 caller_uid,
445 attest_key_descriptor,
446 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700447 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800448 &mut db.borrow_mut(),
449 )
450 })
451 .context("In generate_key: Trying to get an attestation key")?,
452 };
Janis Danisevskise766edc2021-02-06 12:16:26 -0800453 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800454 .context("In generate_key: Trying to get aaid.")?;
455
Stephen Crane221bbb52020-12-16 15:52:10 -0800456 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700457
458 let creation_result = match attestation_key_info {
459 Some(AttestationKeyInfo::UserGenerated {
460 key_id_guard,
461 blob,
462 blob_metadata,
463 issuer_subject,
464 }) => self
465 .upgrade_keyblob_if_required_with(
466 &*km_dev,
467 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700468 &KeyBlob::Ref(&blob),
469 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700470 &params,
471 |blob| {
472 let attest_key = Some(AttestationKey {
473 keyBlob: blob.to_vec(),
474 attestKeyParams: vec![],
475 issuerSubjectName: issuer_subject.clone(),
476 });
477 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
478 },
479 )
480 .context("In generate_key: Using user generated attestation key.")
481 .map(|(result, _)| result),
482 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
483 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
484 .context("While generating Key with remote provisioned attestation key.")
485 .map(|mut creation_result| {
486 creation_result.certificateChain.push(attestation_certs);
487 creation_result
488 })
489 }
490 None => map_km_error(km_dev.generateKey(&params, None))
491 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800492 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700493 .context("In generate_key.")?;
494
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000495 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000496 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700497 }
498
499 fn import_key(
500 &self,
501 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700502 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700503 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700504 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700505 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700506 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700507 if key.domain != Domain::BLOB && key.alias.is_none() {
508 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
509 .context("In import_key: Alias must be specified");
510 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000511 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700512
513 let key = match key.domain {
514 Domain::APP => KeyDescriptor {
515 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000516 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700517 alias: key.alias.clone(),
518 blob: None,
519 },
520 _ => key.clone(),
521 };
522
523 // import_key requires the rebind permission.
524 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
525
Janis Danisevskise766edc2021-02-06 12:16:26 -0800526 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800527 .context("In import_key: Trying to get aaid.")?;
528
Janis Danisevskis1af91262020-08-10 14:58:08 -0700529 let format = params
530 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700531 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700532 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
533 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800534 .and_then(|p| match &p.value {
535 KeyParameterValue::Algorithm(Algorithm::AES)
536 | KeyParameterValue::Algorithm(Algorithm::HMAC)
537 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
538 KeyParameterValue::Algorithm(Algorithm::RSA)
539 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
540 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
541 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700542 })
543 .context("In import_key.")?;
544
Stephen Crane221bbb52020-12-16 15:52:10 -0800545 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800546 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700547 let creation_result =
548 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
549 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700550
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000551 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000552 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700553 }
554
555 fn import_wrapped_key(
556 &self,
557 key: &KeyDescriptor,
558 wrapping_key: &KeyDescriptor,
559 masking_key: Option<&[u8]>,
560 params: &[KeyParameter],
561 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700562 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800563 let wrapped_data: &[u8] = match key {
564 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
565 | KeyDescriptor {
566 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
567 } => blob,
568 _ => {
569 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
570 concat!(
571 "In import_wrapped_key: Alias and blob must be specified ",
572 "and domain must be APP or SELINUX. {:?}"
573 ),
574 key
575 ))
576 }
577 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700578
Janis Danisevskisaec14592020-11-12 09:41:49 -0800579 if wrapping_key.domain == Domain::BLOB {
580 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
581 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
582 );
583 }
584
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000585 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000586 let user_id = uid_to_android_user(caller_uid);
587
Janis Danisevskis1af91262020-08-10 14:58:08 -0700588 let key = match key.domain {
589 Domain::APP => KeyDescriptor {
590 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000591 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700592 alias: key.alias.clone(),
593 blob: None,
594 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800595 Domain::SELINUX => KeyDescriptor {
596 domain: Domain::SELINUX,
597 nspace: key.nspace,
598 alias: key.alias.clone(),
599 blob: None,
600 },
601 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700602 };
603
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800604 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700605 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
606
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000607 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700608 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000609 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
610 db.borrow_mut().load_key_entry(
611 &wrapping_key,
612 KeyType::Client,
613 KeyEntryLoadBits::KM,
614 caller_uid,
615 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
616 )
617 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700618 })
619 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000620
621 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
622 .take_key_blob_info()
623 .ok_or_else(error::Error::sys)
624 .context("No km_blob after successfully loading key. This should never happen.")?;
625
626 let wrapping_key_blob =
627 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
628 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
629 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700630
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631 // km_dev.importWrappedKey does not return a certificate chain.
632 // TODO Do we assume that all wrapped keys are symmetric?
633 // let certificate_chain: Vec<KmCertificate> = Default::default();
634
635 let pw_sid = authenticators
636 .iter()
637 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700638 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700639 _ => None,
640 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800641 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700642
643 let fp_sid = authenticators
644 .iter()
645 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700646 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700647 _ => None,
648 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800649 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700650
651 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
652
Stephen Crane221bbb52020-12-16 15:52:10 -0800653 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800654 let (creation_result, _) = self
655 .upgrade_keyblob_if_required_with(
656 &*km_dev,
657 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700658 &wrapping_key_blob,
659 &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
Paul Crowley7a658392021-03-18 17:08:20 -0700679 fn store_upgraded_keyblob(
680 key_id_guard: KeyIdGuard,
681 km_uuid: Option<&Uuid>,
682 key_blob: &KeyBlob,
683 upgraded_blob: &[u8],
684 ) -> Result<()> {
685 let (upgraded_blob_to_be_stored, new_blob_metadata) =
686 SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
687 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
688
689 let mut new_blob_metadata = new_blob_metadata.unwrap_or_else(BlobMetaData::new);
690 if let Some(uuid) = km_uuid {
691 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
692 }
693
694 DB.with(|db| {
695 let mut db = db.borrow_mut();
696 db.set_blob(
697 &key_id_guard,
698 SubComponentType::KEY_BLOB,
699 Some(&upgraded_blob_to_be_stored),
700 Some(&new_blob_metadata),
701 )
702 })
703 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
704 }
705
Janis Danisevskisaec14592020-11-12 09:41:49 -0800706 fn upgrade_keyblob_if_required_with<T, F>(
707 &self,
708 km_dev: &dyn IKeyMintDevice,
709 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700710 key_blob: &KeyBlob,
711 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800712 params: &[KeyParameter],
713 f: F,
714 ) -> Result<(T, Option<Vec<u8>>)>
715 where
716 F: Fn(&[u8]) -> Result<T, Error>,
717 {
Paul Crowley7a658392021-03-18 17:08:20 -0700718 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800719 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Paul Crowley7a658392021-03-18 17:08:20 -0700720 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800721 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000722
Paul Crowley7a658392021-03-18 17:08:20 -0700723 if let Some(kid) = key_id_guard {
724 Self::store_upgraded_keyblob(
725 kid,
726 blob_metadata.km_uuid(),
727 key_blob,
728 &upgraded_blob,
729 )
730 .context(
731 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000732 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000733 }
734
Janis Danisevskisaec14592020-11-12 09:41:49 -0800735 match f(&upgraded_blob) {
736 Ok(v) => Ok((v, Some(upgraded_blob))),
737 Err(e) => Err(e).context(concat!(
738 "In upgrade_keyblob_if_required_with: ",
739 "Failed to perform operation on second try."
740 )),
741 }
742 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700743 result => {
744 if let Some(kid) = key_id_guard {
745 if key_blob.force_reencrypt() {
746 Self::store_upgraded_keyblob(
747 kid,
748 blob_metadata.km_uuid(),
749 key_blob,
750 key_blob,
751 )
752 .context(concat!(
753 "In upgrade_keyblob_if_required_with: ",
754 "store_upgraded_keyblob failed in forced reencrypt"
755 ))?;
756 }
757 }
758 result
759 .map(|v| (v, None))
760 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
761 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800762 }
763 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800764
765 fn convert_storage_key_to_ephemeral(&self, storage_key: &KeyDescriptor) -> Result<Vec<u8>> {
766 if storage_key.domain != Domain::BLOB {
767 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
768 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
769 "Key must be of Domain::BLOB"
770 ));
771 }
772 let key_blob = storage_key
773 .blob
774 .as_ref()
775 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
776 .context(
777 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
778 )?;
779
780 // convert_storage_key_to_ephemeral requires the associated permission
781 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
782 .context("In convert_storage_key_to_ephemeral: Check permission")?;
783
784 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
785 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
786 "Getting keymint device interface"
787 ))?;
788 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
789 .context("In keymint device convertStorageKeyToEphemeral")
790 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800791
792 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
793 if key.domain != Domain::BLOB {
794 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
795 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
796 }
797
798 let key_blob = key
799 .blob
800 .as_ref()
801 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
802 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
803
804 check_key_permission(KeyPerm::delete(), key, &None)
805 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
806
807 let km_dev: Strong<dyn IKeyMintDevice> = self
808 .keymint
809 .get_interface()
810 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
811 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
812 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700813}
814
815impl binder::Interface for KeystoreSecurityLevel {}
816
817impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700818 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700819 &self,
820 key: &KeyDescriptor,
821 operation_parameters: &[KeyParameter],
822 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700823 ) -> binder::public_api::Result<CreateOperationResponse> {
824 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700825 }
826 fn generateKey(
827 &self,
828 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700829 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700830 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700831 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700832 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700833 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000834 let result = self.generate_key(key, attestation_key, params, flags, entropy);
835 log_key_creation_event_stats(params, &result);
836 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700837 }
838 fn importKey(
839 &self,
840 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700841 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700842 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700843 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700844 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700845 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000846 let result = self.import_key(key, attestation_key, params, flags, key_data);
847 log_key_creation_event_stats(params, &result);
848 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700849 }
850 fn importWrappedKey(
851 &self,
852 key: &KeyDescriptor,
853 wrapping_key: &KeyDescriptor,
854 masking_key: Option<&[u8]>,
855 params: &[KeyParameter],
856 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700857 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000858 let result =
859 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
860 log_key_creation_event_stats(params, &result);
861 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700862 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800863 fn convertStorageKeyToEphemeral(
864 &self,
865 storage_key: &KeyDescriptor,
866 ) -> binder::public_api::Result<Vec<u8>> {
867 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
868 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800869 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
870 map_or_log_err(self.delete_key(key), Ok)
871 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700872}