blob: e4af00984aa61c453610c421e287f0c1356f3542 [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 Danisevskis5cb52dc2021-04-07 16:31:18 -070017use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
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 Danisevskis5cb52dc2021-04-07 16:31:18 -070070 id_rotation_state: IdRotationState,
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,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070087 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080088 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080089 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
90 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070091 let result = BnKeystoreSecurityLevel::new_binder(Self {
92 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080093 keymint: dev,
94 hw_info,
95 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070096 operation_db: OperationDb::new(),
Max Bires97f96812021-02-23 23:44:57 -080097 rem_prov_state: RemProvState::new(security_level, km_uuid),
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070098 id_rotation_state,
Janis Danisevskis1af91262020-08-10 14:58:08 -070099 });
100 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -0800101 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700102 }
103
104 fn store_new_key(
105 &self,
106 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700107 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000108 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000109 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700110 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700111 let KeyCreationResult {
112 keyBlob: key_blob,
113 keyCharacteristics: key_characteristics,
114 certificateChain: mut certificate_chain,
115 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700116
Max Bires8e93d2b2021-01-14 13:17:59 -0800117 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700118 match certificate_chain.len() {
119 0 => None,
120 _ => Some(certificate_chain.remove(0).encodedCertificate),
121 },
122 match certificate_chain.len() {
123 0 => None,
124 _ => Some(
125 certificate_chain
126 .iter()
127 .map(|c| c.encodedCertificate.iter())
128 .flatten()
129 .copied()
130 .collect(),
131 ),
132 },
133 );
134
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000135 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
136
137 key_parameters.push(KsKeyParam::new(
138 KsKeyParamValue::UserID(user_id as i32),
139 SecurityLevel::SOFTWARE,
140 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700141
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800142 let creation_date = DateTime::now().context("Trying to make creation time.")?;
143
Janis Danisevskis1af91262020-08-10 14:58:08 -0700144 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800145 Domain::BLOB => KeyDescriptor {
146 domain: Domain::BLOB,
147 blob: Some(key_blob.to_vec()),
148 ..Default::default()
149 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700150 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800151 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800152 let mut db = db.borrow_mut();
153
154 let (key_blob, mut blob_metadata) = SUPER_KEY
155 .handle_super_encryption_on_key_init(
156 &mut db,
157 &LEGACY_MIGRATOR,
158 &(key.domain),
159 &key_parameters,
160 flags,
161 user_id,
162 &key_blob,
163 )
164 .context("In store_new_key. Failed to handle super encryption.")?;
165
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800166 let mut key_metadata = KeyMetaData::new();
167 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800168 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800171 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800172 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800173 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800174 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800175 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800177 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800178 )
179 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700180 Ok(KeyDescriptor {
181 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800182 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700183 ..Default::default()
184 })
185 })
186 .context("In store_new_key.")?,
187 };
188
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700189 Ok(KeyMetadata {
190 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700191 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800192 certificate: cert_info.take_cert(),
193 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700194 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800195 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700196 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700197 }
198
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700199 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700200 &self,
201 key: &KeyDescriptor,
202 operation_parameters: &[KeyParameter],
203 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700204 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700205 let caller_uid = ThreadState::get_calling_uid();
206 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
207 // so that we can use it by reference like the blob provided by the key descriptor.
208 // Otherwise, we would have to clone the blob from the key descriptor.
209 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800210 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700211 Domain::BLOB => {
212 check_key_permission(KeyPerm::use_(), key, &None)
213 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800214 if forced {
215 check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
216 "In create_operation: checking forced permission for Domain::BLOB.",
217 )?;
218 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700219 (
220 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700221 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700222 None => {
223 return Err(Error::sys()).context(concat!(
224 "In create_operation: Key blob must be specified when",
225 " using Domain::BLOB."
226 ))
227 }
228 },
229 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000230 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000231 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700232 )
233 }
234 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800235 let (key_id_guard, mut key_entry) = DB
236 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000237 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
238 db.borrow_mut().load_key_entry(
239 &key,
240 KeyType::Client,
241 KeyEntryLoadBits::KM,
242 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800243 |k, av| {
244 check_key_permission(KeyPerm::use_(), k, &av)?;
245 if forced {
246 check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
247 }
248 Ok(())
249 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000250 )
251 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700252 })
253 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800254
255 let (blob, blob_metadata) =
256 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
257 "In create_operation: Successfully loaded key entry, ",
258 "but KM blob was missing."
259 ))?;
260 scoping_blob = blob;
261
Qi Wub9433b52020-12-01 14:52:46 +0800262 (
263 &scoping_blob,
264 Some((key_id_guard.id(), key_entry.into_key_parameters())),
265 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000266 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800267 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700268 }
269 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700270
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700271 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700272 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700273 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800274 |kp| match kp.value {
275 KeyParameterValue::KeyPurpose(p) => Ok(p),
276 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
277 .context("In create_operation: Malformed KeyParameter."),
278 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700279 )?;
280
Satya Tangirala2642ff92021-04-15 01:57:00 -0700281 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
282 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
283 let op_params: Vec<KeyParameter> =
284 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
285 let operation_parameters = op_params.as_slice();
286
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800287 let (immediate_hat, mut auth_info) = ENFORCEMENTS
288 .authorize_create(
289 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800290 key_properties.as_ref(),
291 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700292 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800293 )
294 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000295
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000296 let km_blob = SUPER_KEY
297 .unwrap_key_if_required(&blob_metadata, km_blob)
298 .context("In create_operation. Failed to handle super encryption.")?;
299
Stephen Crane221bbb52020-12-16 15:52:10 -0800300 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700301 .keymint
302 .get_interface()
303 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700304
Janis Danisevskisaec14592020-11-12 09:41:49 -0800305 let (begin_result, upgraded_blob) = self
306 .upgrade_keyblob_if_required_with(
307 &*km_dev,
308 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700309 &km_blob,
310 &blob_metadata,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700311 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800312 |blob| loop {
313 match map_km_error(km_dev.begin(
314 purpose,
315 blob,
316 &operation_parameters,
David Drysdalef5c1ab02021-04-19 19:08:14 +0100317 immediate_hat.as_ref(),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800318 )) {
319 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800320 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800321 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700322 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800323 v => return v,
324 }
325 },
326 )
327 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800329 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000330
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000331 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
332
Janis Danisevskis1af91262020-08-10 14:58:08 -0700333 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000334 Some(km_op) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000335 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced,
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000336 LoggingInfo::new(self.security_level, purpose, op_params,
337 upgraded_blob.is_some()))
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000338 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700339 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 -0700340 };
341
Stephen Crane221bbb52020-12-16 15:52:10 -0800342 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700343 KeystoreOperation::new_native_binder(operation)
344 .as_binder()
345 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700346 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700347
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700348 Ok(CreateOperationResponse {
349 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000350 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700351 parameters: match begin_result.params.len() {
352 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700353 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700354 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800355 // An upgraded blob should only be returned if the caller has permission
356 // to use Domain::BLOB keys. If we got to this point, we already checked
357 // that the caller had that permission.
358 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700359 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700360 }
361
Janis Danisevskise766edc2021-02-06 12:16:26 -0800362 fn add_certificate_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700363 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800364 uid: u32,
365 params: &[KeyParameter],
366 key: &KeyDescriptor,
367 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800368 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800369 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800370 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
371 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800372 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800373 })?;
374 result.push(KeyParameter {
375 tag: Tag::ATTESTATION_APPLICATION_ID,
376 value: KeyParameterValue::Blob(aaid),
377 });
378 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800379
Janis Danisevskise766edc2021-02-06 12:16:26 -0800380 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
381 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
382 "In add_certificate_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700383 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800384 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700385 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
386 "In add_certificate_parameters: Call to had_factory_reset_since_id_rotation failed."
387 )? {
388 result.push(KeyParameter{
389 tag: Tag::RESET_SINCE_ID_ROTATION,
390 value: KeyParameterValue::BoolValue(true),
391 })
392 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800393 }
394
Bram Bonné5d6c5102021-02-24 15:09:18 +0100395 // If the caller requests any device identifier attestation tag, check that they hold the
396 // correct Android permission.
397 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
398 check_device_attestation_permissions().context(concat!(
399 "In add_certificate_parameters: ",
400 "Caller does not have the permission to attest device identifiers."
401 ))?;
402 }
403
Janis Danisevskis2c084012021-01-31 22:23:17 -0800404 // If we are generating/importing an asymmetric key, we need to make sure
405 // that NOT_BEFORE and NOT_AFTER are present.
406 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
407 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
408 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
409 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
410 result.push(KeyParameter {
411 tag: Tag::CERTIFICATE_NOT_BEFORE,
412 value: KeyParameterValue::DateTime(0),
413 })
414 }
415 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
416 result.push(KeyParameter {
417 tag: Tag::CERTIFICATE_NOT_AFTER,
418 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
419 })
420 }
421 }
422 _ => {}
423 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800424 Ok(result)
425 }
426
Janis Danisevskis1af91262020-08-10 14:58:08 -0700427 fn generate_key(
428 &self,
429 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700430 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700431 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700432 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700433 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700434 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700435 if key.domain != Domain::BLOB && key.alias.is_none() {
436 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
437 .context("In generate_key: Alias must be specified");
438 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000439 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700440
441 let key = match key.domain {
442 Domain::APP => KeyDescriptor {
443 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000444 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700445 alias: key.alias.clone(),
446 blob: None,
447 },
448 _ => key.clone(),
449 };
450
451 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700452 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700453 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700454
455 let attestation_key_info = match (key.domain, attest_key_descriptor) {
456 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800457 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700458 .with(|db| {
459 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800460 &key,
461 caller_uid,
462 attest_key_descriptor,
463 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700464 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800465 &mut db.borrow_mut(),
466 )
467 })
468 .context("In generate_key: Trying to get an attestation key")?,
469 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700470 let params = self
471 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800472 .context("In generate_key: Trying to get aaid.")?;
473
Stephen Crane221bbb52020-12-16 15:52:10 -0800474 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700475
476 let creation_result = match attestation_key_info {
477 Some(AttestationKeyInfo::UserGenerated {
478 key_id_guard,
479 blob,
480 blob_metadata,
481 issuer_subject,
482 }) => self
483 .upgrade_keyblob_if_required_with(
484 &*km_dev,
485 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700486 &KeyBlob::Ref(&blob),
487 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700488 &params,
489 |blob| {
490 let attest_key = Some(AttestationKey {
491 keyBlob: blob.to_vec(),
492 attestKeyParams: vec![],
493 issuerSubjectName: issuer_subject.clone(),
494 });
495 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
496 },
497 )
498 .context("In generate_key: Using user generated attestation key.")
499 .map(|(result, _)| result),
500 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
501 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
502 .context("While generating Key with remote provisioned attestation key.")
503 .map(|mut creation_result| {
504 creation_result.certificateChain.push(attestation_certs);
505 creation_result
506 })
507 }
508 None => map_km_error(km_dev.generateKey(&params, None))
509 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800510 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700511 .context("In generate_key.")?;
512
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000513 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000514 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700515 }
516
517 fn import_key(
518 &self,
519 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700520 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700521 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700522 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700523 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700524 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700525 if key.domain != Domain::BLOB && key.alias.is_none() {
526 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
527 .context("In import_key: Alias must be specified");
528 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000529 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700530
531 let key = match key.domain {
532 Domain::APP => KeyDescriptor {
533 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000534 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700535 alias: key.alias.clone(),
536 blob: None,
537 },
538 _ => key.clone(),
539 };
540
541 // import_key requires the rebind permission.
542 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
543
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700544 let params = self
545 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800546 .context("In import_key: Trying to get aaid.")?;
547
Janis Danisevskis1af91262020-08-10 14:58:08 -0700548 let format = params
549 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700550 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700551 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
552 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800553 .and_then(|p| match &p.value {
554 KeyParameterValue::Algorithm(Algorithm::AES)
555 | KeyParameterValue::Algorithm(Algorithm::HMAC)
556 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
557 KeyParameterValue::Algorithm(Algorithm::RSA)
558 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
559 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
560 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700561 })
562 .context("In import_key.")?;
563
Stephen Crane221bbb52020-12-16 15:52:10 -0800564 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800565 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700566 let creation_result =
567 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
568 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000570 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000571 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700572 }
573
574 fn import_wrapped_key(
575 &self,
576 key: &KeyDescriptor,
577 wrapping_key: &KeyDescriptor,
578 masking_key: Option<&[u8]>,
579 params: &[KeyParameter],
580 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700581 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800582 let wrapped_data: &[u8] = match key {
583 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
584 | KeyDescriptor {
585 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
586 } => blob,
587 _ => {
588 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
589 concat!(
590 "In import_wrapped_key: Alias and blob must be specified ",
591 "and domain must be APP or SELINUX. {:?}"
592 ),
593 key
594 ))
595 }
596 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700597
Janis Danisevskisaec14592020-11-12 09:41:49 -0800598 if wrapping_key.domain == Domain::BLOB {
599 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
600 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
601 );
602 }
603
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000604 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000605 let user_id = uid_to_android_user(caller_uid);
606
Janis Danisevskis1af91262020-08-10 14:58:08 -0700607 let key = match key.domain {
608 Domain::APP => KeyDescriptor {
609 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000610 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700611 alias: key.alias.clone(),
612 blob: None,
613 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800614 Domain::SELINUX => KeyDescriptor {
615 domain: Domain::SELINUX,
616 nspace: key.nspace,
617 alias: key.alias.clone(),
618 blob: None,
619 },
620 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700621 };
622
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800623 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700624 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
625
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000626 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700627 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000628 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
629 db.borrow_mut().load_key_entry(
630 &wrapping_key,
631 KeyType::Client,
632 KeyEntryLoadBits::KM,
633 caller_uid,
634 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
635 )
636 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700637 })
638 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000639
640 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
641 .take_key_blob_info()
642 .ok_or_else(error::Error::sys)
643 .context("No km_blob after successfully loading key. This should never happen.")?;
644
645 let wrapping_key_blob =
646 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
647 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
648 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700649
Janis Danisevskis1af91262020-08-10 14:58:08 -0700650 // km_dev.importWrappedKey does not return a certificate chain.
651 // TODO Do we assume that all wrapped keys are symmetric?
652 // let certificate_chain: Vec<KmCertificate> = Default::default();
653
654 let pw_sid = authenticators
655 .iter()
656 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700657 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700658 _ => None,
659 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800660 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700661
662 let fp_sid = authenticators
663 .iter()
664 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700665 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700666 _ => None,
667 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800668 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700669
670 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
671
Stephen Crane221bbb52020-12-16 15:52:10 -0800672 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800673 let (creation_result, _) = self
674 .upgrade_keyblob_if_required_with(
675 &*km_dev,
676 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700677 &wrapping_key_blob,
678 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800679 &[],
680 |wrapping_blob| {
681 let creation_result = map_km_error(km_dev.importWrappedKey(
682 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800683 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800684 masking_key,
685 &params,
686 pw_sid,
687 fp_sid,
688 ))?;
689 Ok(creation_result)
690 },
691 )
692 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700693
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000694 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800695 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700696 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800697
Paul Crowley7a658392021-03-18 17:08:20 -0700698 fn store_upgraded_keyblob(
699 key_id_guard: KeyIdGuard,
700 km_uuid: Option<&Uuid>,
701 key_blob: &KeyBlob,
702 upgraded_blob: &[u8],
703 ) -> Result<()> {
704 let (upgraded_blob_to_be_stored, new_blob_metadata) =
705 SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
706 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
707
Paul Crowley44c02da2021-04-08 17:04:43 +0000708 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700709 if let Some(uuid) = km_uuid {
710 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
711 }
712
713 DB.with(|db| {
714 let mut db = db.borrow_mut();
715 db.set_blob(
716 &key_id_guard,
717 SubComponentType::KEY_BLOB,
718 Some(&upgraded_blob_to_be_stored),
719 Some(&new_blob_metadata),
720 )
721 })
722 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
723 }
724
Janis Danisevskisaec14592020-11-12 09:41:49 -0800725 fn upgrade_keyblob_if_required_with<T, F>(
726 &self,
727 km_dev: &dyn IKeyMintDevice,
728 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700729 key_blob: &KeyBlob,
730 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800731 params: &[KeyParameter],
732 f: F,
733 ) -> Result<(T, Option<Vec<u8>>)>
734 where
735 F: Fn(&[u8]) -> Result<T, Error>,
736 {
Paul Crowley7a658392021-03-18 17:08:20 -0700737 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800738 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Paul Crowley7a658392021-03-18 17:08:20 -0700739 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800740 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000741
Paul Crowley7a658392021-03-18 17:08:20 -0700742 if let Some(kid) = key_id_guard {
743 Self::store_upgraded_keyblob(
744 kid,
745 blob_metadata.km_uuid(),
746 key_blob,
747 &upgraded_blob,
748 )
749 .context(
750 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000751 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000752 }
753
Janis Danisevskisaec14592020-11-12 09:41:49 -0800754 match f(&upgraded_blob) {
755 Ok(v) => Ok((v, Some(upgraded_blob))),
756 Err(e) => Err(e).context(concat!(
757 "In upgrade_keyblob_if_required_with: ",
758 "Failed to perform operation on second try."
759 )),
760 }
761 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700762 result => {
763 if let Some(kid) = key_id_guard {
764 if key_blob.force_reencrypt() {
765 Self::store_upgraded_keyblob(
766 kid,
767 blob_metadata.km_uuid(),
768 key_blob,
769 key_blob,
770 )
771 .context(concat!(
772 "In upgrade_keyblob_if_required_with: ",
773 "store_upgraded_keyblob failed in forced reencrypt"
774 ))?;
775 }
776 }
777 result
778 .map(|v| (v, None))
779 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
780 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800781 }
782 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800783
784 fn convert_storage_key_to_ephemeral(&self, storage_key: &KeyDescriptor) -> Result<Vec<u8>> {
785 if storage_key.domain != Domain::BLOB {
786 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
787 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
788 "Key must be of Domain::BLOB"
789 ));
790 }
791 let key_blob = storage_key
792 .blob
793 .as_ref()
794 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
795 .context(
796 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
797 )?;
798
799 // convert_storage_key_to_ephemeral requires the associated permission
800 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
801 .context("In convert_storage_key_to_ephemeral: Check permission")?;
802
803 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
804 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
805 "Getting keymint device interface"
806 ))?;
807 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
808 .context("In keymint device convertStorageKeyToEphemeral")
809 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800810
811 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
812 if key.domain != Domain::BLOB {
813 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
814 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
815 }
816
817 let key_blob = key
818 .blob
819 .as_ref()
820 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
821 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
822
823 check_key_permission(KeyPerm::delete(), key, &None)
824 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
825
826 let km_dev: Strong<dyn IKeyMintDevice> = self
827 .keymint
828 .get_interface()
829 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
830 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
831 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700832}
833
834impl binder::Interface for KeystoreSecurityLevel {}
835
836impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700837 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700838 &self,
839 key: &KeyDescriptor,
840 operation_parameters: &[KeyParameter],
841 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700842 ) -> binder::public_api::Result<CreateOperationResponse> {
843 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700844 }
845 fn generateKey(
846 &self,
847 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700848 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700849 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700850 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700851 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700852 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000853 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000854 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000855 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700856 }
857 fn importKey(
858 &self,
859 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700860 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700861 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700862 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700863 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700864 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000865 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000866 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000867 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700868 }
869 fn importWrappedKey(
870 &self,
871 key: &KeyDescriptor,
872 wrapping_key: &KeyDescriptor,
873 masking_key: Option<&[u8]>,
874 params: &[KeyParameter],
875 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700876 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000877 let result =
878 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000879 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000880 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700881 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800882 fn convertStorageKeyToEphemeral(
883 &self,
884 storage_key: &KeyDescriptor,
885 ) -> binder::public_api::Result<Vec<u8>> {
886 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
887 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800888 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
889 map_or_log_err(self.delete_key(key), Ok)
890 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700891}