blob: 8530a2ebed3384b0f441790093627e0a3c1b7fcd [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};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000025use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070026use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070027 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
28 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
29 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070030 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080031 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070032};
33
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070034use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
35use crate::database::{CertificateInfo, KeyIdGuard};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000036use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000037use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000038use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Hasini Gunasingheb7142972021-02-20 03:11:27 +000039use crate::metrics::log_key_creation_event_stats;
Max Bires97f96812021-02-23 23:44:57 -080040use crate::remote_provisioning::RemProvState;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000041use crate::super_key::{KeyBlob, SuperKeyManager};
Bram Bonné5d6c5102021-02-24 15:09:18 +010042use crate::utils::{
43 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
44 uid_to_android_user, Asp,
45};
Max Bires8e93d2b2021-01-14 13:17:59 -080046use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080047 database::{
48 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
49 KeyMetaEntry, KeyType, SubComponentType, Uuid,
50 },
51 operation::KeystoreOperation,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +000052 operation::LoggingInfo,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080053 operation::OperationDb,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080054 permission::KeyPerm,
55};
56use crate::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070057 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
58 utils::key_characteristics_to_internal,
59};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080060use anyhow::{anyhow, Context, Result};
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
Andrew Walbrande45c8b2021-04-13 14:42:38 +000082 /// BnKeystoreSecurityLevel proxy object. It also enables
83 /// `BinderFeatures::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.")?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000091 let result = BnKeystoreSecurityLevel::new_binder(
92 Self {
93 security_level,
94 keymint: dev,
95 hw_info,
96 km_uuid,
97 operation_db: OperationDb::new(),
98 rem_prov_state: RemProvState::new(security_level, km_uuid),
99 id_rotation_state,
100 },
101 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
102 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800103 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700104 }
105
106 fn store_new_key(
107 &self,
108 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700109 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000110 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000111 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700112 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700113 let KeyCreationResult {
114 keyBlob: key_blob,
115 keyCharacteristics: key_characteristics,
116 certificateChain: mut certificate_chain,
117 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700118
Max Bires8e93d2b2021-01-14 13:17:59 -0800119 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700120 match certificate_chain.len() {
121 0 => None,
122 _ => Some(certificate_chain.remove(0).encodedCertificate),
123 },
124 match certificate_chain.len() {
125 0 => None,
126 _ => Some(
127 certificate_chain
128 .iter()
129 .map(|c| c.encodedCertificate.iter())
130 .flatten()
131 .copied()
132 .collect(),
133 ),
134 },
135 );
136
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000137 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
138
139 key_parameters.push(KsKeyParam::new(
140 KsKeyParamValue::UserID(user_id as i32),
141 SecurityLevel::SOFTWARE,
142 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700143
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800144 let creation_date = DateTime::now().context("Trying to make creation time.")?;
145
Janis Danisevskis1af91262020-08-10 14:58:08 -0700146 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800147 Domain::BLOB => KeyDescriptor {
148 domain: Domain::BLOB,
149 blob: Some(key_blob.to_vec()),
150 ..Default::default()
151 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700152 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800153 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800154 let mut db = db.borrow_mut();
155
156 let (key_blob, mut blob_metadata) = SUPER_KEY
157 .handle_super_encryption_on_key_init(
158 &mut db,
159 &LEGACY_MIGRATOR,
160 &(key.domain),
161 &key_parameters,
162 flags,
163 user_id,
164 &key_blob,
165 )
166 .context("In store_new_key. Failed to handle super encryption.")?;
167
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800168 let mut key_metadata = KeyMetaData::new();
169 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800171
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800172 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800173 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800174 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800175 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800177 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800178 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800179 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800180 )
181 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700182 Ok(KeyDescriptor {
183 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800184 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700185 ..Default::default()
186 })
187 })
188 .context("In store_new_key.")?,
189 };
190
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700191 Ok(KeyMetadata {
192 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700193 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800194 certificate: cert_info.take_cert(),
195 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700196 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800197 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700198 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700199 }
200
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700201 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700202 &self,
203 key: &KeyDescriptor,
204 operation_parameters: &[KeyParameter],
205 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700206 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700207 let caller_uid = ThreadState::get_calling_uid();
208 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
209 // so that we can use it by reference like the blob provided by the key descriptor.
210 // Otherwise, we would have to clone the blob from the key descriptor.
211 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800212 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700213 Domain::BLOB => {
214 check_key_permission(KeyPerm::use_(), key, &None)
215 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800216 if forced {
217 check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
218 "In create_operation: checking forced permission for Domain::BLOB.",
219 )?;
220 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700221 (
222 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700223 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700224 None => {
225 return Err(Error::sys()).context(concat!(
226 "In create_operation: Key blob must be specified when",
227 " using Domain::BLOB."
228 ))
229 }
230 },
231 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000232 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000233 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700234 )
235 }
236 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800237 let (key_id_guard, mut key_entry) = DB
238 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000239 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
240 db.borrow_mut().load_key_entry(
241 &key,
242 KeyType::Client,
243 KeyEntryLoadBits::KM,
244 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800245 |k, av| {
246 check_key_permission(KeyPerm::use_(), k, &av)?;
247 if forced {
248 check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
249 }
250 Ok(())
251 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000252 )
253 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700254 })
255 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800256
257 let (blob, blob_metadata) =
258 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
259 "In create_operation: Successfully loaded key entry, ",
260 "but KM blob was missing."
261 ))?;
262 scoping_blob = blob;
263
Qi Wub9433b52020-12-01 14:52:46 +0800264 (
265 &scoping_blob,
266 Some((key_id_guard.id(), key_entry.into_key_parameters())),
267 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000268 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800269 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700270 }
271 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700272
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700273 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700274 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700275 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800276 |kp| match kp.value {
277 KeyParameterValue::KeyPurpose(p) => Ok(p),
278 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
279 .context("In create_operation: Malformed KeyParameter."),
280 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700281 )?;
282
Satya Tangirala2642ff92021-04-15 01:57:00 -0700283 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
284 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
285 let op_params: Vec<KeyParameter> =
286 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
287 let operation_parameters = op_params.as_slice();
288
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800289 let (immediate_hat, mut auth_info) = ENFORCEMENTS
290 .authorize_create(
291 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800292 key_properties.as_ref(),
293 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700294 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800295 )
296 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000297
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800298 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000299
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000300 let km_blob = SUPER_KEY
301 .unwrap_key_if_required(&blob_metadata, km_blob)
302 .context("In create_operation. Failed to handle super encryption.")?;
303
Stephen Crane221bbb52020-12-16 15:52:10 -0800304 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700305 .keymint
306 .get_interface()
307 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700308
Janis Danisevskisaec14592020-11-12 09:41:49 -0800309 let (begin_result, upgraded_blob) = self
310 .upgrade_keyblob_if_required_with(
311 &*km_dev,
312 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700313 &km_blob,
314 &blob_metadata,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700315 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800316 |blob| loop {
317 match map_km_error(km_dev.begin(
318 purpose,
319 blob,
320 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800321 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800322 )) {
323 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800324 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800325 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700326 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800327 v => return v,
328 }
329 },
330 )
331 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700332
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800333 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000334
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000335 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
336
Janis Danisevskis1af91262020-08-10 14:58:08 -0700337 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000338 Some(km_op) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000339 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced,
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000340 LoggingInfo::new(self.security_level, purpose, op_params,
341 upgraded_blob.is_some()))
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000342 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700343 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 -0700344 };
345
Stephen Crane221bbb52020-12-16 15:52:10 -0800346 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700347 KeystoreOperation::new_native_binder(operation)
348 .as_binder()
349 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700350 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700351
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700352 Ok(CreateOperationResponse {
353 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000354 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700355 parameters: match begin_result.params.len() {
356 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700357 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700358 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800359 // An upgraded blob should only be returned if the caller has permission
360 // to use Domain::BLOB keys. If we got to this point, we already checked
361 // that the caller had that permission.
362 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700363 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700364 }
365
Janis Danisevskise766edc2021-02-06 12:16:26 -0800366 fn add_certificate_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700367 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800368 uid: u32,
369 params: &[KeyParameter],
370 key: &KeyDescriptor,
371 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800372 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800373 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800374 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
375 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800376 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800377 })?;
378 result.push(KeyParameter {
379 tag: Tag::ATTESTATION_APPLICATION_ID,
380 value: KeyParameterValue::Blob(aaid),
381 });
382 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800383
Janis Danisevskise766edc2021-02-06 12:16:26 -0800384 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
385 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
386 "In add_certificate_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700387 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800388 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700389 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
390 "In add_certificate_parameters: Call to had_factory_reset_since_id_rotation failed."
391 )? {
392 result.push(KeyParameter{
393 tag: Tag::RESET_SINCE_ID_ROTATION,
394 value: KeyParameterValue::BoolValue(true),
395 })
396 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800397 }
398
Bram Bonné5d6c5102021-02-24 15:09:18 +0100399 // If the caller requests any device identifier attestation tag, check that they hold the
400 // correct Android permission.
401 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
402 check_device_attestation_permissions().context(concat!(
403 "In add_certificate_parameters: ",
404 "Caller does not have the permission to attest device identifiers."
405 ))?;
406 }
407
Janis Danisevskis2c084012021-01-31 22:23:17 -0800408 // If we are generating/importing an asymmetric key, we need to make sure
409 // that NOT_BEFORE and NOT_AFTER are present.
410 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
411 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
412 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
413 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
414 result.push(KeyParameter {
415 tag: Tag::CERTIFICATE_NOT_BEFORE,
416 value: KeyParameterValue::DateTime(0),
417 })
418 }
419 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
420 result.push(KeyParameter {
421 tag: Tag::CERTIFICATE_NOT_AFTER,
422 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
423 })
424 }
425 }
426 _ => {}
427 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800428 Ok(result)
429 }
430
Janis Danisevskis1af91262020-08-10 14:58:08 -0700431 fn generate_key(
432 &self,
433 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700434 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700435 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700436 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700437 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700438 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700439 if key.domain != Domain::BLOB && key.alias.is_none() {
440 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
441 .context("In generate_key: Alias must be specified");
442 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000443 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700444
445 let key = match key.domain {
446 Domain::APP => KeyDescriptor {
447 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000448 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700449 alias: key.alias.clone(),
450 blob: None,
451 },
452 _ => key.clone(),
453 };
454
455 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700456 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700457 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700458
459 let attestation_key_info = match (key.domain, attest_key_descriptor) {
460 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800461 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700462 .with(|db| {
463 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800464 &key,
465 caller_uid,
466 attest_key_descriptor,
467 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700468 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800469 &mut db.borrow_mut(),
470 )
471 })
472 .context("In generate_key: Trying to get an attestation key")?,
473 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700474 let params = self
475 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800476 .context("In generate_key: Trying to get aaid.")?;
477
Stephen Crane221bbb52020-12-16 15:52:10 -0800478 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700479
480 let creation_result = match attestation_key_info {
481 Some(AttestationKeyInfo::UserGenerated {
482 key_id_guard,
483 blob,
484 blob_metadata,
485 issuer_subject,
486 }) => self
487 .upgrade_keyblob_if_required_with(
488 &*km_dev,
489 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700490 &KeyBlob::Ref(&blob),
491 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700492 &params,
493 |blob| {
494 let attest_key = Some(AttestationKey {
495 keyBlob: blob.to_vec(),
496 attestKeyParams: vec![],
497 issuerSubjectName: issuer_subject.clone(),
498 });
499 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
500 },
501 )
502 .context("In generate_key: Using user generated attestation key.")
503 .map(|(result, _)| result),
504 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
505 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
506 .context("While generating Key with remote provisioned attestation key.")
507 .map(|mut creation_result| {
508 creation_result.certificateChain.push(attestation_certs);
509 creation_result
510 })
511 }
512 None => map_km_error(km_dev.generateKey(&params, None))
513 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800514 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700515 .context("In generate_key.")?;
516
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000517 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000518 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519 }
520
521 fn import_key(
522 &self,
523 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700524 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700525 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700526 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700528 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700529 if key.domain != Domain::BLOB && key.alias.is_none() {
530 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
531 .context("In import_key: Alias must be specified");
532 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000533 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700534
535 let key = match key.domain {
536 Domain::APP => KeyDescriptor {
537 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000538 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700539 alias: key.alias.clone(),
540 blob: None,
541 },
542 _ => key.clone(),
543 };
544
545 // import_key requires the rebind permission.
546 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
547
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700548 let params = self
549 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800550 .context("In import_key: Trying to get aaid.")?;
551
Janis Danisevskis1af91262020-08-10 14:58:08 -0700552 let format = params
553 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700554 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700555 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
556 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800557 .and_then(|p| match &p.value {
558 KeyParameterValue::Algorithm(Algorithm::AES)
559 | KeyParameterValue::Algorithm(Algorithm::HMAC)
560 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
561 KeyParameterValue::Algorithm(Algorithm::RSA)
562 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
563 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
564 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700565 })
566 .context("In import_key.")?;
567
Stephen Crane221bbb52020-12-16 15:52:10 -0800568 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800569 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700570 let creation_result =
571 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
572 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700573
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000574 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000575 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700576 }
577
578 fn import_wrapped_key(
579 &self,
580 key: &KeyDescriptor,
581 wrapping_key: &KeyDescriptor,
582 masking_key: Option<&[u8]>,
583 params: &[KeyParameter],
584 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700585 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800586 let wrapped_data: &[u8] = match key {
587 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
588 | KeyDescriptor {
589 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
590 } => blob,
591 _ => {
592 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
593 concat!(
594 "In import_wrapped_key: Alias and blob must be specified ",
595 "and domain must be APP or SELINUX. {:?}"
596 ),
597 key
598 ))
599 }
600 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700601
Janis Danisevskisaec14592020-11-12 09:41:49 -0800602 if wrapping_key.domain == Domain::BLOB {
603 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
604 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
605 );
606 }
607
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000608 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000609 let user_id = uid_to_android_user(caller_uid);
610
Janis Danisevskis1af91262020-08-10 14:58:08 -0700611 let key = match key.domain {
612 Domain::APP => KeyDescriptor {
613 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000614 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700615 alias: key.alias.clone(),
616 blob: None,
617 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800618 Domain::SELINUX => KeyDescriptor {
619 domain: Domain::SELINUX,
620 nspace: key.nspace,
621 alias: key.alias.clone(),
622 blob: None,
623 },
624 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700625 };
626
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800627 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700628 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
629
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000630 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000632 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
633 db.borrow_mut().load_key_entry(
634 &wrapping_key,
635 KeyType::Client,
636 KeyEntryLoadBits::KM,
637 caller_uid,
638 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
639 )
640 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700641 })
642 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000643
644 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
645 .take_key_blob_info()
646 .ok_or_else(error::Error::sys)
647 .context("No km_blob after successfully loading key. This should never happen.")?;
648
649 let wrapping_key_blob =
650 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
651 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
652 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700653
Janis Danisevskis1af91262020-08-10 14:58:08 -0700654 // km_dev.importWrappedKey does not return a certificate chain.
655 // TODO Do we assume that all wrapped keys are symmetric?
656 // let certificate_chain: Vec<KmCertificate> = Default::default();
657
658 let pw_sid = authenticators
659 .iter()
660 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700661 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700662 _ => None,
663 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800664 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700665
666 let fp_sid = authenticators
667 .iter()
668 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700669 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700670 _ => None,
671 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800672 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700673
674 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
675
Stephen Crane221bbb52020-12-16 15:52:10 -0800676 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800677 let (creation_result, _) = self
678 .upgrade_keyblob_if_required_with(
679 &*km_dev,
680 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700681 &wrapping_key_blob,
682 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800683 &[],
684 |wrapping_blob| {
685 let creation_result = map_km_error(km_dev.importWrappedKey(
686 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800687 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800688 masking_key,
689 &params,
690 pw_sid,
691 fp_sid,
692 ))?;
693 Ok(creation_result)
694 },
695 )
696 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700697
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000698 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800699 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700700 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800701
Paul Crowley7a658392021-03-18 17:08:20 -0700702 fn store_upgraded_keyblob(
703 key_id_guard: KeyIdGuard,
704 km_uuid: Option<&Uuid>,
705 key_blob: &KeyBlob,
706 upgraded_blob: &[u8],
707 ) -> Result<()> {
708 let (upgraded_blob_to_be_stored, new_blob_metadata) =
709 SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
710 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
711
Paul Crowley44c02da2021-04-08 17:04:43 +0000712 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700713 if let Some(uuid) = km_uuid {
714 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
715 }
716
717 DB.with(|db| {
718 let mut db = db.borrow_mut();
719 db.set_blob(
720 &key_id_guard,
721 SubComponentType::KEY_BLOB,
722 Some(&upgraded_blob_to_be_stored),
723 Some(&new_blob_metadata),
724 )
725 })
726 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
727 }
728
Janis Danisevskisaec14592020-11-12 09:41:49 -0800729 fn upgrade_keyblob_if_required_with<T, F>(
730 &self,
731 km_dev: &dyn IKeyMintDevice,
732 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700733 key_blob: &KeyBlob,
734 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800735 params: &[KeyParameter],
736 f: F,
737 ) -> Result<(T, Option<Vec<u8>>)>
738 where
739 F: Fn(&[u8]) -> Result<T, Error>,
740 {
Paul Crowley7a658392021-03-18 17:08:20 -0700741 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800742 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Paul Crowley7a658392021-03-18 17:08:20 -0700743 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800744 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000745
Paul Crowley7a658392021-03-18 17:08:20 -0700746 if let Some(kid) = key_id_guard {
747 Self::store_upgraded_keyblob(
748 kid,
749 blob_metadata.km_uuid(),
750 key_blob,
751 &upgraded_blob,
752 )
753 .context(
754 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000755 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000756 }
757
Janis Danisevskisaec14592020-11-12 09:41:49 -0800758 match f(&upgraded_blob) {
759 Ok(v) => Ok((v, Some(upgraded_blob))),
760 Err(e) => Err(e).context(concat!(
761 "In upgrade_keyblob_if_required_with: ",
762 "Failed to perform operation on second try."
763 )),
764 }
765 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700766 result => {
767 if let Some(kid) = key_id_guard {
768 if key_blob.force_reencrypt() {
769 Self::store_upgraded_keyblob(
770 kid,
771 blob_metadata.km_uuid(),
772 key_blob,
773 key_blob,
774 )
775 .context(concat!(
776 "In upgrade_keyblob_if_required_with: ",
777 "store_upgraded_keyblob failed in forced reencrypt"
778 ))?;
779 }
780 }
781 result
782 .map(|v| (v, None))
783 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
784 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800785 }
786 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800787
788 fn convert_storage_key_to_ephemeral(&self, storage_key: &KeyDescriptor) -> Result<Vec<u8>> {
789 if storage_key.domain != Domain::BLOB {
790 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
791 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
792 "Key must be of Domain::BLOB"
793 ));
794 }
795 let key_blob = storage_key
796 .blob
797 .as_ref()
798 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
799 .context(
800 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
801 )?;
802
803 // convert_storage_key_to_ephemeral requires the associated permission
804 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
805 .context("In convert_storage_key_to_ephemeral: Check permission")?;
806
807 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
808 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
809 "Getting keymint device interface"
810 ))?;
811 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
812 .context("In keymint device convertStorageKeyToEphemeral")
813 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800814
815 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
816 if key.domain != Domain::BLOB {
817 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
818 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
819 }
820
821 let key_blob = key
822 .blob
823 .as_ref()
824 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
825 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
826
827 check_key_permission(KeyPerm::delete(), key, &None)
828 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
829
830 let km_dev: Strong<dyn IKeyMintDevice> = self
831 .keymint
832 .get_interface()
833 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
834 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
835 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700836}
837
838impl binder::Interface for KeystoreSecurityLevel {}
839
840impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700841 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700842 &self,
843 key: &KeyDescriptor,
844 operation_parameters: &[KeyParameter],
845 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700846 ) -> binder::public_api::Result<CreateOperationResponse> {
847 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700848 }
849 fn generateKey(
850 &self,
851 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700852 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700853 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700854 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700855 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700856 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000857 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000858 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000859 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700860 }
861 fn importKey(
862 &self,
863 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700864 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700865 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700866 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700867 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700868 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000869 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000870 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000871 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700872 }
873 fn importWrappedKey(
874 &self,
875 key: &KeyDescriptor,
876 wrapping_key: &KeyDescriptor,
877 masking_key: Option<&[u8]>,
878 params: &[KeyParameter],
879 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700880 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000881 let result =
882 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000883 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000884 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700885 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800886 fn convertStorageKeyToEphemeral(
887 &self,
888 storage_key: &KeyDescriptor,
889 ) -> binder::public_api::Result<Vec<u8>> {
890 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
891 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800892 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
893 map_or_log_err(self.delete_key(key), Ok)
894 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700895}