blob: 117b48c907b21516931b6f1e7997653ba4544d06 [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,
Janis Danisevskisb2434d02021-04-20 12:49:27 -070027 Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
28 IKeystoreOperation::IKeystoreOperation, 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
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800296 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000297
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000298 let km_blob = SUPER_KEY
299 .unwrap_key_if_required(&blob_metadata, km_blob)
300 .context("In create_operation. Failed to handle super encryption.")?;
301
Stephen Crane221bbb52020-12-16 15:52:10 -0800302 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700303 .keymint
304 .get_interface()
305 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700306
Janis Danisevskisaec14592020-11-12 09:41:49 -0800307 let (begin_result, upgraded_blob) = self
308 .upgrade_keyblob_if_required_with(
309 &*km_dev,
310 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700311 &km_blob,
312 &blob_metadata,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700313 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800314 |blob| loop {
315 match map_km_error(km_dev.begin(
316 purpose,
317 blob,
318 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800319 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800320 )) {
321 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800322 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800323 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700324 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800325 v => return v,
326 }
327 },
328 )
329 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700330
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800331 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000332
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000333 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
334
Janis Danisevskis1af91262020-08-10 14:58:08 -0700335 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000336 Some(km_op) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000337 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced,
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000338 LoggingInfo::new(self.security_level, purpose, op_params,
339 upgraded_blob.is_some()))
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000340 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700341 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 -0700342 };
343
Stephen Crane221bbb52020-12-16 15:52:10 -0800344 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700345 KeystoreOperation::new_native_binder(operation)
346 .as_binder()
347 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700348 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700349
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700350 Ok(CreateOperationResponse {
351 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000352 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700353 parameters: match begin_result.params.len() {
354 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700355 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700356 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800357 // An upgraded blob should only be returned if the caller has permission
358 // to use Domain::BLOB keys. If we got to this point, we already checked
359 // that the caller had that permission.
360 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700361 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700362 }
363
Janis Danisevskise766edc2021-02-06 12:16:26 -0800364 fn add_certificate_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700365 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800366 uid: u32,
367 params: &[KeyParameter],
368 key: &KeyDescriptor,
369 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800370 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800371 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800372 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
373 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800374 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800375 })?;
376 result.push(KeyParameter {
377 tag: Tag::ATTESTATION_APPLICATION_ID,
378 value: KeyParameterValue::Blob(aaid),
379 });
380 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800381
Janis Danisevskise766edc2021-02-06 12:16:26 -0800382 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
383 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
384 "In add_certificate_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700385 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800386 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700387 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
388 "In add_certificate_parameters: Call to had_factory_reset_since_id_rotation failed."
389 )? {
390 result.push(KeyParameter{
391 tag: Tag::RESET_SINCE_ID_ROTATION,
392 value: KeyParameterValue::BoolValue(true),
393 })
394 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800395 }
396
Bram Bonné5d6c5102021-02-24 15:09:18 +0100397 // If the caller requests any device identifier attestation tag, check that they hold the
398 // correct Android permission.
399 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
400 check_device_attestation_permissions().context(concat!(
401 "In add_certificate_parameters: ",
402 "Caller does not have the permission to attest device identifiers."
403 ))?;
404 }
405
Janis Danisevskis2c084012021-01-31 22:23:17 -0800406 // If we are generating/importing an asymmetric key, we need to make sure
407 // that NOT_BEFORE and NOT_AFTER are present.
408 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
409 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
410 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
411 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
412 result.push(KeyParameter {
413 tag: Tag::CERTIFICATE_NOT_BEFORE,
414 value: KeyParameterValue::DateTime(0),
415 })
416 }
417 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
418 result.push(KeyParameter {
419 tag: Tag::CERTIFICATE_NOT_AFTER,
420 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
421 })
422 }
423 }
424 _ => {}
425 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800426 Ok(result)
427 }
428
Janis Danisevskis1af91262020-08-10 14:58:08 -0700429 fn generate_key(
430 &self,
431 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700432 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700433 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700434 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700435 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700436 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700437 if key.domain != Domain::BLOB && key.alias.is_none() {
438 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
439 .context("In generate_key: Alias must be specified");
440 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000441 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700442
443 let key = match key.domain {
444 Domain::APP => KeyDescriptor {
445 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000446 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700447 alias: key.alias.clone(),
448 blob: None,
449 },
450 _ => key.clone(),
451 };
452
453 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700454 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700455 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700456
457 let attestation_key_info = match (key.domain, attest_key_descriptor) {
458 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800459 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700460 .with(|db| {
461 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800462 &key,
463 caller_uid,
464 attest_key_descriptor,
465 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700466 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800467 &mut db.borrow_mut(),
468 )
469 })
470 .context("In generate_key: Trying to get an attestation key")?,
471 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700472 let params = self
473 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800474 .context("In generate_key: Trying to get aaid.")?;
475
Stephen Crane221bbb52020-12-16 15:52:10 -0800476 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700477
478 let creation_result = match attestation_key_info {
479 Some(AttestationKeyInfo::UserGenerated {
480 key_id_guard,
481 blob,
482 blob_metadata,
483 issuer_subject,
484 }) => self
485 .upgrade_keyblob_if_required_with(
486 &*km_dev,
487 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700488 &KeyBlob::Ref(&blob),
489 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700490 &params,
491 |blob| {
492 let attest_key = Some(AttestationKey {
493 keyBlob: blob.to_vec(),
494 attestKeyParams: vec![],
495 issuerSubjectName: issuer_subject.clone(),
496 });
497 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
498 },
499 )
500 .context("In generate_key: Using user generated attestation key.")
501 .map(|(result, _)| result),
502 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
503 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
504 .context("While generating Key with remote provisioned attestation key.")
505 .map(|mut creation_result| {
506 creation_result.certificateChain.push(attestation_certs);
507 creation_result
508 })
509 }
510 None => map_km_error(km_dev.generateKey(&params, None))
511 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800512 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700513 .context("In generate_key.")?;
514
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000515 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000516 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700517 }
518
519 fn import_key(
520 &self,
521 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700522 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700523 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700524 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700525 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700526 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 if key.domain != Domain::BLOB && key.alias.is_none() {
528 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
529 .context("In import_key: Alias must be specified");
530 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000531 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700532
533 let key = match key.domain {
534 Domain::APP => KeyDescriptor {
535 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000536 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700537 alias: key.alias.clone(),
538 blob: None,
539 },
540 _ => key.clone(),
541 };
542
543 // import_key requires the rebind permission.
544 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
545
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700546 let params = self
547 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800548 .context("In import_key: Trying to get aaid.")?;
549
Janis Danisevskis1af91262020-08-10 14:58:08 -0700550 let format = params
551 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700552 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700553 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
554 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800555 .and_then(|p| match &p.value {
556 KeyParameterValue::Algorithm(Algorithm::AES)
557 | KeyParameterValue::Algorithm(Algorithm::HMAC)
558 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
559 KeyParameterValue::Algorithm(Algorithm::RSA)
560 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
561 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
562 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700563 })
564 .context("In import_key.")?;
565
Stephen Crane221bbb52020-12-16 15:52:10 -0800566 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800567 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700568 let creation_result =
569 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
570 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700571
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000572 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000573 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700574 }
575
576 fn import_wrapped_key(
577 &self,
578 key: &KeyDescriptor,
579 wrapping_key: &KeyDescriptor,
580 masking_key: Option<&[u8]>,
581 params: &[KeyParameter],
582 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700583 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800584 let wrapped_data: &[u8] = match key {
585 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
586 | KeyDescriptor {
587 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
588 } => blob,
589 _ => {
590 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
591 concat!(
592 "In import_wrapped_key: Alias and blob must be specified ",
593 "and domain must be APP or SELINUX. {:?}"
594 ),
595 key
596 ))
597 }
598 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700599
Janis Danisevskisaec14592020-11-12 09:41:49 -0800600 if wrapping_key.domain == Domain::BLOB {
601 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
602 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
603 );
604 }
605
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000606 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000607 let user_id = uid_to_android_user(caller_uid);
608
Janis Danisevskis1af91262020-08-10 14:58:08 -0700609 let key = match key.domain {
610 Domain::APP => KeyDescriptor {
611 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000612 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700613 alias: key.alias.clone(),
614 blob: None,
615 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800616 Domain::SELINUX => KeyDescriptor {
617 domain: Domain::SELINUX,
618 nspace: key.nspace,
619 alias: key.alias.clone(),
620 blob: None,
621 },
622 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700623 };
624
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800625 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700626 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
627
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000628 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700629 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000630 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
631 db.borrow_mut().load_key_entry(
632 &wrapping_key,
633 KeyType::Client,
634 KeyEntryLoadBits::KM,
635 caller_uid,
636 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
637 )
638 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700639 })
640 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000641
642 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
643 .take_key_blob_info()
644 .ok_or_else(error::Error::sys)
645 .context("No km_blob after successfully loading key. This should never happen.")?;
646
647 let wrapping_key_blob =
648 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
649 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
650 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700651
Janis Danisevskis1af91262020-08-10 14:58:08 -0700652 // km_dev.importWrappedKey does not return a certificate chain.
653 // TODO Do we assume that all wrapped keys are symmetric?
654 // let certificate_chain: Vec<KmCertificate> = Default::default();
655
656 let pw_sid = authenticators
657 .iter()
658 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700659 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700660 _ => None,
661 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800662 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700663
664 let fp_sid = authenticators
665 .iter()
666 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700667 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700668 _ => None,
669 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800670 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700671
672 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
673
Stephen Crane221bbb52020-12-16 15:52:10 -0800674 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800675 let (creation_result, _) = self
676 .upgrade_keyblob_if_required_with(
677 &*km_dev,
678 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700679 &wrapping_key_blob,
680 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800681 &[],
682 |wrapping_blob| {
683 let creation_result = map_km_error(km_dev.importWrappedKey(
684 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800685 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800686 masking_key,
687 &params,
688 pw_sid,
689 fp_sid,
690 ))?;
691 Ok(creation_result)
692 },
693 )
694 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700695
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000696 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800697 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700698 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800699
Paul Crowley7a658392021-03-18 17:08:20 -0700700 fn store_upgraded_keyblob(
701 key_id_guard: KeyIdGuard,
702 km_uuid: Option<&Uuid>,
703 key_blob: &KeyBlob,
704 upgraded_blob: &[u8],
705 ) -> Result<()> {
706 let (upgraded_blob_to_be_stored, new_blob_metadata) =
707 SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
708 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
709
Paul Crowley44c02da2021-04-08 17:04:43 +0000710 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700711 if let Some(uuid) = km_uuid {
712 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
713 }
714
715 DB.with(|db| {
716 let mut db = db.borrow_mut();
717 db.set_blob(
718 &key_id_guard,
719 SubComponentType::KEY_BLOB,
720 Some(&upgraded_blob_to_be_stored),
721 Some(&new_blob_metadata),
722 )
723 })
724 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
725 }
726
Janis Danisevskisaec14592020-11-12 09:41:49 -0800727 fn upgrade_keyblob_if_required_with<T, F>(
728 &self,
729 km_dev: &dyn IKeyMintDevice,
730 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700731 key_blob: &KeyBlob,
732 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800733 params: &[KeyParameter],
734 f: F,
735 ) -> Result<(T, Option<Vec<u8>>)>
736 where
737 F: Fn(&[u8]) -> Result<T, Error>,
738 {
Paul Crowley7a658392021-03-18 17:08:20 -0700739 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800740 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Paul Crowley7a658392021-03-18 17:08:20 -0700741 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800742 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000743
Paul Crowley7a658392021-03-18 17:08:20 -0700744 if let Some(kid) = key_id_guard {
745 Self::store_upgraded_keyblob(
746 kid,
747 blob_metadata.km_uuid(),
748 key_blob,
749 &upgraded_blob,
750 )
751 .context(
752 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000753 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000754 }
755
Janis Danisevskisaec14592020-11-12 09:41:49 -0800756 match f(&upgraded_blob) {
757 Ok(v) => Ok((v, Some(upgraded_blob))),
758 Err(e) => Err(e).context(concat!(
759 "In upgrade_keyblob_if_required_with: ",
760 "Failed to perform operation on second try."
761 )),
762 }
763 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700764 result => {
765 if let Some(kid) = key_id_guard {
766 if key_blob.force_reencrypt() {
767 Self::store_upgraded_keyblob(
768 kid,
769 blob_metadata.km_uuid(),
770 key_blob,
771 key_blob,
772 )
773 .context(concat!(
774 "In upgrade_keyblob_if_required_with: ",
775 "store_upgraded_keyblob failed in forced reencrypt"
776 ))?;
777 }
778 }
779 result
780 .map(|v| (v, None))
781 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
782 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800783 }
784 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800785
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700786 fn convert_storage_key_to_ephemeral(
787 &self,
788 storage_key: &KeyDescriptor,
789 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800790 if storage_key.domain != Domain::BLOB {
791 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
792 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
793 "Key must be of Domain::BLOB"
794 ));
795 }
796 let key_blob = storage_key
797 .blob
798 .as_ref()
799 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
800 .context(
801 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
802 )?;
803
804 // convert_storage_key_to_ephemeral requires the associated permission
805 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
806 .context("In convert_storage_key_to_ephemeral: Check permission")?;
807
808 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
809 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
810 "Getting keymint device interface"
811 ))?;
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700812 match map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob)) {
813 Ok(result) => {
814 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
815 }
816 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
817 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, &[]))
818 .context("In convert_storage_key_to_ephemeral: Failed to upgrade key blob.")?;
819 let ephemeral_key = map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
820 .context(concat!(
821 "In convert_storage_key_to_ephemeral: ",
822 "Failed to retrieve ephemeral key (after upgrade)."
823 ))?;
824 Ok(EphemeralStorageKeyResponse {
825 ephemeralKey: ephemeral_key,
826 upgradedBlob: Some(upgraded_blob),
827 })
828 }
829 Err(e) => Err(e)
830 .context("In convert_storage_key_to_ephemeral: Failed to retrieve ephemeral key."),
831 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800832 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800833
834 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
835 if key.domain != Domain::BLOB {
836 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
837 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
838 }
839
840 let key_blob = key
841 .blob
842 .as_ref()
843 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
844 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
845
846 check_key_permission(KeyPerm::delete(), key, &None)
847 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
848
849 let km_dev: Strong<dyn IKeyMintDevice> = self
850 .keymint
851 .get_interface()
852 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
853 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
854 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700855}
856
857impl binder::Interface for KeystoreSecurityLevel {}
858
859impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700860 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700861 &self,
862 key: &KeyDescriptor,
863 operation_parameters: &[KeyParameter],
864 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700865 ) -> binder::public_api::Result<CreateOperationResponse> {
866 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700867 }
868 fn generateKey(
869 &self,
870 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700871 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700872 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700873 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700874 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700875 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000876 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000877 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000878 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700879 }
880 fn importKey(
881 &self,
882 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700883 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700884 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700885 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700886 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700887 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000888 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000889 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000890 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700891 }
892 fn importWrappedKey(
893 &self,
894 key: &KeyDescriptor,
895 wrapping_key: &KeyDescriptor,
896 masking_key: Option<&[u8]>,
897 params: &[KeyParameter],
898 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700899 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000900 let result =
901 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000902 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000903 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700904 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800905 fn convertStorageKeyToEphemeral(
906 &self,
907 storage_key: &KeyDescriptor,
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700908 ) -> binder::public_api::Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800909 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
910 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800911 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
912 map_or_log_err(self.delete_key(key), Ok)
913 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700914}