blob: 50d697ee28f98ff78071ddaedf60ab91fc08484f [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,
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000329 LoggingInfo::new(self.security_level, purpose, op_params,
330 upgraded_blob.is_some()))
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000331 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700332 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 -0700333 };
334
Stephen Crane221bbb52020-12-16 15:52:10 -0800335 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700336 KeystoreOperation::new_native_binder(operation)
337 .as_binder()
338 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700339 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700340
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700341 Ok(CreateOperationResponse {
342 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000343 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700344 parameters: match begin_result.params.len() {
345 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700346 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700347 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800348 // An upgraded blob should only be returned if the caller has permission
349 // to use Domain::BLOB keys. If we got to this point, we already checked
350 // that the caller had that permission.
351 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700352 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700353 }
354
Janis Danisevskise766edc2021-02-06 12:16:26 -0800355 fn add_certificate_parameters(
356 uid: u32,
357 params: &[KeyParameter],
358 key: &KeyDescriptor,
359 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800360 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800361 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800362 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
363 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800364 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800365 })?;
366 result.push(KeyParameter {
367 tag: Tag::ATTESTATION_APPLICATION_ID,
368 value: KeyParameterValue::Blob(aaid),
369 });
370 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800371
Janis Danisevskise766edc2021-02-06 12:16:26 -0800372 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
373 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
374 "In add_certificate_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700375 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800376 ))?;
377 }
378
Bram Bonné5d6c5102021-02-24 15:09:18 +0100379 // If the caller requests any device identifier attestation tag, check that they hold the
380 // correct Android permission.
381 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
382 check_device_attestation_permissions().context(concat!(
383 "In add_certificate_parameters: ",
384 "Caller does not have the permission to attest device identifiers."
385 ))?;
386 }
387
Janis Danisevskis2c084012021-01-31 22:23:17 -0800388 // If we are generating/importing an asymmetric key, we need to make sure
389 // that NOT_BEFORE and NOT_AFTER are present.
390 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
391 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
392 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
393 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
394 result.push(KeyParameter {
395 tag: Tag::CERTIFICATE_NOT_BEFORE,
396 value: KeyParameterValue::DateTime(0),
397 })
398 }
399 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
400 result.push(KeyParameter {
401 tag: Tag::CERTIFICATE_NOT_AFTER,
402 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
403 })
404 }
405 }
406 _ => {}
407 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800408 Ok(result)
409 }
410
Janis Danisevskis1af91262020-08-10 14:58:08 -0700411 fn generate_key(
412 &self,
413 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700414 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700415 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700416 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700417 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700418 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700419 if key.domain != Domain::BLOB && key.alias.is_none() {
420 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
421 .context("In generate_key: Alias must be specified");
422 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000423 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700424
425 let key = match key.domain {
426 Domain::APP => KeyDescriptor {
427 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000428 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700429 alias: key.alias.clone(),
430 blob: None,
431 },
432 _ => key.clone(),
433 };
434
435 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700436 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700437 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700438
439 let attestation_key_info = match (key.domain, attest_key_descriptor) {
440 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800441 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700442 .with(|db| {
443 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800444 &key,
445 caller_uid,
446 attest_key_descriptor,
447 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700448 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800449 &mut db.borrow_mut(),
450 )
451 })
452 .context("In generate_key: Trying to get an attestation key")?,
453 };
Janis Danisevskise766edc2021-02-06 12:16:26 -0800454 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800455 .context("In generate_key: Trying to get aaid.")?;
456
Stephen Crane221bbb52020-12-16 15:52:10 -0800457 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700458
459 let creation_result = match attestation_key_info {
460 Some(AttestationKeyInfo::UserGenerated {
461 key_id_guard,
462 blob,
463 blob_metadata,
464 issuer_subject,
465 }) => self
466 .upgrade_keyblob_if_required_with(
467 &*km_dev,
468 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700469 &KeyBlob::Ref(&blob),
470 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700471 &params,
472 |blob| {
473 let attest_key = Some(AttestationKey {
474 keyBlob: blob.to_vec(),
475 attestKeyParams: vec![],
476 issuerSubjectName: issuer_subject.clone(),
477 });
478 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
479 },
480 )
481 .context("In generate_key: Using user generated attestation key.")
482 .map(|(result, _)| result),
483 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
484 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
485 .context("While generating Key with remote provisioned attestation key.")
486 .map(|mut creation_result| {
487 creation_result.certificateChain.push(attestation_certs);
488 creation_result
489 })
490 }
491 None => map_km_error(km_dev.generateKey(&params, None))
492 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800493 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700494 .context("In generate_key.")?;
495
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000496 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000497 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700498 }
499
500 fn import_key(
501 &self,
502 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700503 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700504 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700505 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700507 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700508 if key.domain != Domain::BLOB && key.alias.is_none() {
509 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
510 .context("In import_key: Alias must be specified");
511 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000512 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700513
514 let key = match key.domain {
515 Domain::APP => KeyDescriptor {
516 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000517 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700518 alias: key.alias.clone(),
519 blob: None,
520 },
521 _ => key.clone(),
522 };
523
524 // import_key requires the rebind permission.
525 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
526
Janis Danisevskise766edc2021-02-06 12:16:26 -0800527 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800528 .context("In import_key: Trying to get aaid.")?;
529
Janis Danisevskis1af91262020-08-10 14:58:08 -0700530 let format = params
531 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700532 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700533 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
534 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800535 .and_then(|p| match &p.value {
536 KeyParameterValue::Algorithm(Algorithm::AES)
537 | KeyParameterValue::Algorithm(Algorithm::HMAC)
538 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
539 KeyParameterValue::Algorithm(Algorithm::RSA)
540 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
541 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
542 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700543 })
544 .context("In import_key.")?;
545
Stephen Crane221bbb52020-12-16 15:52:10 -0800546 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800547 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700548 let creation_result =
549 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
550 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700551
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000552 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000553 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700554 }
555
556 fn import_wrapped_key(
557 &self,
558 key: &KeyDescriptor,
559 wrapping_key: &KeyDescriptor,
560 masking_key: Option<&[u8]>,
561 params: &[KeyParameter],
562 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700563 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800564 let wrapped_data: &[u8] = match key {
565 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
566 | KeyDescriptor {
567 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
568 } => blob,
569 _ => {
570 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
571 concat!(
572 "In import_wrapped_key: Alias and blob must be specified ",
573 "and domain must be APP or SELINUX. {:?}"
574 ),
575 key
576 ))
577 }
578 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700579
Janis Danisevskisaec14592020-11-12 09:41:49 -0800580 if wrapping_key.domain == Domain::BLOB {
581 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
582 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
583 );
584 }
585
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000586 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000587 let user_id = uid_to_android_user(caller_uid);
588
Janis Danisevskis1af91262020-08-10 14:58:08 -0700589 let key = match key.domain {
590 Domain::APP => KeyDescriptor {
591 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000592 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700593 alias: key.alias.clone(),
594 blob: None,
595 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800596 Domain::SELINUX => KeyDescriptor {
597 domain: Domain::SELINUX,
598 nspace: key.nspace,
599 alias: key.alias.clone(),
600 blob: None,
601 },
602 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700603 };
604
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800605 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700606 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
607
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000608 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700609 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000610 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
611 db.borrow_mut().load_key_entry(
612 &wrapping_key,
613 KeyType::Client,
614 KeyEntryLoadBits::KM,
615 caller_uid,
616 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
617 )
618 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700619 })
620 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000621
622 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
623 .take_key_blob_info()
624 .ok_or_else(error::Error::sys)
625 .context("No km_blob after successfully loading key. This should never happen.")?;
626
627 let wrapping_key_blob =
628 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
629 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
630 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631
Janis Danisevskis1af91262020-08-10 14:58:08 -0700632 // km_dev.importWrappedKey does not return a certificate chain.
633 // TODO Do we assume that all wrapped keys are symmetric?
634 // let certificate_chain: Vec<KmCertificate> = Default::default();
635
636 let pw_sid = authenticators
637 .iter()
638 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700639 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700640 _ => None,
641 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800642 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700643
644 let fp_sid = authenticators
645 .iter()
646 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700647 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700648 _ => None,
649 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800650 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700651
652 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
653
Stephen Crane221bbb52020-12-16 15:52:10 -0800654 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800655 let (creation_result, _) = self
656 .upgrade_keyblob_if_required_with(
657 &*km_dev,
658 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700659 &wrapping_key_blob,
660 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800661 &[],
662 |wrapping_blob| {
663 let creation_result = map_km_error(km_dev.importWrappedKey(
664 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800665 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800666 masking_key,
667 &params,
668 pw_sid,
669 fp_sid,
670 ))?;
671 Ok(creation_result)
672 },
673 )
674 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700675
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000676 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800677 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700678 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800679
Paul Crowley7a658392021-03-18 17:08:20 -0700680 fn store_upgraded_keyblob(
681 key_id_guard: KeyIdGuard,
682 km_uuid: Option<&Uuid>,
683 key_blob: &KeyBlob,
684 upgraded_blob: &[u8],
685 ) -> Result<()> {
686 let (upgraded_blob_to_be_stored, new_blob_metadata) =
687 SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
688 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
689
690 let mut new_blob_metadata = new_blob_metadata.unwrap_or_else(BlobMetaData::new);
691 if let Some(uuid) = km_uuid {
692 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
693 }
694
695 DB.with(|db| {
696 let mut db = db.borrow_mut();
697 db.set_blob(
698 &key_id_guard,
699 SubComponentType::KEY_BLOB,
700 Some(&upgraded_blob_to_be_stored),
701 Some(&new_blob_metadata),
702 )
703 })
704 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
705 }
706
Janis Danisevskisaec14592020-11-12 09:41:49 -0800707 fn upgrade_keyblob_if_required_with<T, F>(
708 &self,
709 km_dev: &dyn IKeyMintDevice,
710 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700711 key_blob: &KeyBlob,
712 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800713 params: &[KeyParameter],
714 f: F,
715 ) -> Result<(T, Option<Vec<u8>>)>
716 where
717 F: Fn(&[u8]) -> Result<T, Error>,
718 {
Paul Crowley7a658392021-03-18 17:08:20 -0700719 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800720 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Paul Crowley7a658392021-03-18 17:08:20 -0700721 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800722 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000723
Paul Crowley7a658392021-03-18 17:08:20 -0700724 if let Some(kid) = key_id_guard {
725 Self::store_upgraded_keyblob(
726 kid,
727 blob_metadata.km_uuid(),
728 key_blob,
729 &upgraded_blob,
730 )
731 .context(
732 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000733 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000734 }
735
Janis Danisevskisaec14592020-11-12 09:41:49 -0800736 match f(&upgraded_blob) {
737 Ok(v) => Ok((v, Some(upgraded_blob))),
738 Err(e) => Err(e).context(concat!(
739 "In upgrade_keyblob_if_required_with: ",
740 "Failed to perform operation on second try."
741 )),
742 }
743 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700744 result => {
745 if let Some(kid) = key_id_guard {
746 if key_blob.force_reencrypt() {
747 Self::store_upgraded_keyblob(
748 kid,
749 blob_metadata.km_uuid(),
750 key_blob,
751 key_blob,
752 )
753 .context(concat!(
754 "In upgrade_keyblob_if_required_with: ",
755 "store_upgraded_keyblob failed in forced reencrypt"
756 ))?;
757 }
758 }
759 result
760 .map(|v| (v, None))
761 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
762 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800763 }
764 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800765
766 fn convert_storage_key_to_ephemeral(&self, storage_key: &KeyDescriptor) -> Result<Vec<u8>> {
767 if storage_key.domain != Domain::BLOB {
768 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
769 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
770 "Key must be of Domain::BLOB"
771 ));
772 }
773 let key_blob = storage_key
774 .blob
775 .as_ref()
776 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
777 .context(
778 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
779 )?;
780
781 // convert_storage_key_to_ephemeral requires the associated permission
782 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
783 .context("In convert_storage_key_to_ephemeral: Check permission")?;
784
785 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
786 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
787 "Getting keymint device interface"
788 ))?;
789 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
790 .context("In keymint device convertStorageKeyToEphemeral")
791 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800792
793 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
794 if key.domain != Domain::BLOB {
795 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
796 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
797 }
798
799 let key_blob = key
800 .blob
801 .as_ref()
802 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
803 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
804
805 check_key_permission(KeyPerm::delete(), key, &None)
806 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
807
808 let km_dev: Strong<dyn IKeyMintDevice> = self
809 .keymint
810 .get_interface()
811 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
812 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
813 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700814}
815
816impl binder::Interface for KeystoreSecurityLevel {}
817
818impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700819 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700820 &self,
821 key: &KeyDescriptor,
822 operation_parameters: &[KeyParameter],
823 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700824 ) -> binder::public_api::Result<CreateOperationResponse> {
825 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700826 }
827 fn generateKey(
828 &self,
829 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700830 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700831 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700832 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700833 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700834 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000835 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000836 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000837 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700838 }
839 fn importKey(
840 &self,
841 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700842 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700843 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700844 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700845 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700846 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000847 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000848 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000849 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700850 }
851 fn importWrappedKey(
852 &self,
853 key: &KeyDescriptor,
854 wrapping_key: &KeyDescriptor,
855 masking_key: Option<&[u8]>,
856 params: &[KeyParameter],
857 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700858 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000859 let result =
860 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000861 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000862 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700863 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800864 fn convertStorageKeyToEphemeral(
865 &self,
866 storage_key: &KeyDescriptor,
867 ) -> binder::public_api::Result<Vec<u8>> {
868 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
869 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800870 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
871 map_or_log_err(self.delete_key(key), Ok)
872 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700873}