blob: 1d0608ea49fb5c1ed2dbb580fb6a57401dc26cbe [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
15#![allow(unused_variables)]
16
17//! This crate implements the IKeystoreSecurityLevel interface.
18
Shawn Willden708744a2020-12-11 13:05:27 +000019use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Shawn Willdendbdac602021-01-12 22:35:16 -070020 Algorithm::Algorithm, HardwareAuthenticatorType::HardwareAuthenticatorType,
21 IKeyMintDevice::IKeyMintDevice, KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
22 KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel,
23 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 Danisevskisa53c9cf2020-10-26 11:52:33 -070030 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070031};
32
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070033use crate::utils::{check_key_permission, Asp};
Janis Danisevskisaec14592020-11-12 09:41:49 -080034use crate::{database::KeyIdGuard, globals::DB};
Janis Danisevskis1af91262020-08-10 14:58:08 -070035use crate::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080036 database::{DateTime, KeyMetaData, KeyMetaEntry, KeyType},
37 permission::KeyPerm,
38};
39use crate::{
Janis Danisevskis1af91262020-08-10 14:58:08 -070040 database::{KeyEntry, KeyEntryLoadBits, SubComponentType},
41 operation::KeystoreOperation,
42 operation::OperationDb,
43};
Janis Danisevskis04b02832020-10-26 09:21:40 -070044use crate::{
45 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
46 utils::key_characteristics_to_internal,
47};
Janis Danisevskisba998992020-12-29 16:08:40 -080048use anyhow::{Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -070049use binder::{IBinder, Interface, ThreadState};
50
51/// Implementation of the IKeystoreSecurityLevel Interface.
52pub struct KeystoreSecurityLevel {
53 security_level: SecurityLevel,
54 keymint: Asp,
55 operation_db: OperationDb,
56}
57
Janis Danisevskis1af91262020-08-10 14:58:08 -070058// Blob of 32 zeroes used as empty masking key.
59static ZERO_BLOB_32: &[u8] = &[0; 32];
60
61impl KeystoreSecurityLevel {
62 /// Creates a new security level instance wrapped in a
63 /// BnKeystoreSecurityLevel proxy object. It also
64 /// calls `IBinder::set_requesting_sid` on the new interface, because
65 /// we need it for checking keystore permissions.
66 pub fn new_native_binder(
67 security_level: SecurityLevel,
68 ) -> Result<impl IKeystoreSecurityLevel + Send> {
Janis Danisevskis1af91262020-08-10 14:58:08 -070069 let result = BnKeystoreSecurityLevel::new_binder(Self {
70 security_level,
Janis Danisevskisba998992020-12-29 16:08:40 -080071 keymint: crate::globals::get_keymint_device(security_level)
72 .context("In KeystoreSecurityLevel::new_native_binder.")?,
Janis Danisevskis1af91262020-08-10 14:58:08 -070073 operation_db: OperationDb::new(),
74 });
75 result.as_binder().set_requesting_sid(true);
76 Ok(result)
77 }
78
79 fn store_new_key(
80 &self,
81 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -070082 creation_result: KeyCreationResult,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070083 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -070084 let KeyCreationResult {
85 keyBlob: key_blob,
86 keyCharacteristics: key_characteristics,
87 certificateChain: mut certificate_chain,
88 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -070089
Shawn Willdendbdac602021-01-12 22:35:16 -070090 let (cert, cert_chain): (Option<Vec<u8>>, Option<Vec<u8>>) = (
91 match certificate_chain.len() {
92 0 => None,
93 _ => Some(certificate_chain.remove(0).encodedCertificate),
94 },
95 match certificate_chain.len() {
96 0 => None,
97 _ => Some(
98 certificate_chain
99 .iter()
100 .map(|c| c.encodedCertificate.iter())
101 .flatten()
102 .copied()
103 .collect(),
104 ),
105 },
106 );
107
108 let key_parameters = key_characteristics_to_internal(key_characteristics);
Janis Danisevskis04b02832020-10-26 09:21:40 -0700109
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800110 let creation_date = DateTime::now().context("Trying to make creation time.")?;
111
Janis Danisevskis1af91262020-08-10 14:58:08 -0700112 let key = match key.domain {
113 Domain::BLOB => {
Shawn Willdendbdac602021-01-12 22:35:16 -0700114 KeyDescriptor { domain: Domain::BLOB, blob: Some(key_blob), ..Default::default() }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700115 }
116 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800117 .with::<_, Result<KeyDescriptor>>(|db| {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800118 let mut metadata = KeyMetaData::new();
119 metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800120
121 let mut db = db.borrow_mut();
122 let key_id = db
123 .store_new_key(
124 key,
125 &key_parameters,
Shawn Willdendbdac602021-01-12 22:35:16 -0700126 &key_blob,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800127 cert.as_deref(),
128 cert_chain.as_deref(),
129 &metadata,
130 )
131 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700132 Ok(KeyDescriptor {
133 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800134 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700135 ..Default::default()
136 })
137 })
138 .context("In store_new_key.")?,
139 };
140
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700141 Ok(KeyMetadata {
142 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700143 keySecurityLevel: self.security_level,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700144 certificate: cert,
145 certificateChain: cert_chain,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700146 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800147 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700148 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700149 }
150
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700151 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700152 &self,
153 key: &KeyDescriptor,
154 operation_parameters: &[KeyParameter],
155 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700156 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700157 let caller_uid = ThreadState::get_calling_uid();
158 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
159 // so that we can use it by reference like the blob provided by the key descriptor.
160 // Otherwise, we would have to clone the blob from the key descriptor.
161 let scoping_blob: Vec<u8>;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800162 let (km_blob, key_id_guard) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700163 Domain::BLOB => {
164 check_key_permission(KeyPerm::use_(), key, &None)
165 .context("In create_operation: checking use permission for Domain::BLOB.")?;
166 (
167 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700168 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700169 None => {
170 return Err(Error::sys()).context(concat!(
171 "In create_operation: Key blob must be specified when",
172 " using Domain::BLOB."
173 ))
174 }
175 },
176 None,
177 )
178 }
179 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800180 let (key_id_guard, mut key_entry) = DB
181 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700182 db.borrow_mut().load_key_entry(
183 key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800184 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700185 KeyEntryLoadBits::KM,
186 caller_uid,
187 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
188 )
189 })
190 .context("In create_operation: Failed to load key blob.")?;
191 scoping_blob = match key_entry.take_km_blob() {
192 Some(blob) => blob,
193 None => {
194 return Err(Error::sys()).context(concat!(
195 "In create_operation: Successfully loaded key entry,",
196 " but KM blob was missing."
197 ))
198 }
199 };
Janis Danisevskisaec14592020-11-12 09:41:49 -0800200 (&scoping_blob, Some(key_id_guard))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700201 }
202 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700203
204 // TODO Authorize begin operation.
205 // Check if we need an authorization token.
206 // Lookup authorization token and request VerificationToken if required.
207
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700208 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700209 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700210 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800211 |kp| match kp.value {
212 KeyParameterValue::KeyPurpose(p) => Ok(p),
213 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
214 .context("In create_operation: Malformed KeyParameter."),
215 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700216 )?;
217
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700218 let km_dev: Box<dyn IKeyMintDevice> = self
219 .keymint
220 .get_interface()
221 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700222
Janis Danisevskisaec14592020-11-12 09:41:49 -0800223 let (begin_result, upgraded_blob) = self
224 .upgrade_keyblob_if_required_with(
225 &*km_dev,
226 key_id_guard,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700227 &km_blob,
228 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800229 |blob| loop {
230 match map_km_error(km_dev.begin(
231 purpose,
232 blob,
233 &operation_parameters,
234 &Default::default(),
235 )) {
236 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
237 self.operation_db.prune(caller_uid)?;
238 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700239 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800240 v => return v,
241 }
242 },
243 )
244 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700245
246 let operation = match begin_result.operation {
247 Some(km_op) => self.operation_db.create_operation(km_op, caller_uid),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700248 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 -0700249 };
250
251 let op_binder: Box<dyn IKeystoreOperation> =
252 KeystoreOperation::new_native_binder(operation)
253 .as_binder()
254 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700255 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700256
257 // TODO we need to the enforcement module to determine if we need to return the challenge.
258 // We return None for now because we don't support auth bound keys yet.
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700259 Ok(CreateOperationResponse {
260 iOperation: Some(op_binder),
261 operationChallenge: None,
262 parameters: match begin_result.params.len() {
263 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700264 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700265 },
266 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700267 }
268
269 fn generate_key(
270 &self,
271 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700272 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700273 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700274 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700275 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700276 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700277 if key.domain != Domain::BLOB && key.alias.is_none() {
278 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
279 .context("In generate_key: Alias must be specified");
280 }
281
282 let key = match key.domain {
283 Domain::APP => KeyDescriptor {
284 domain: key.domain,
285 nspace: ThreadState::get_calling_uid() as i64,
286 alias: key.alias.clone(),
287 blob: None,
288 },
289 _ => key.clone(),
290 };
291
292 // generate_key requires the rebind permission.
293 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
294
295 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
296 map_km_error(km_dev.addRngEntropy(entropy))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700297 let creation_result = map_km_error(km_dev.generateKey(&params))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700298
Shawn Willdendbdac602021-01-12 22:35:16 -0700299 self.store_new_key(key, creation_result).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700300 }
301
302 fn import_key(
303 &self,
304 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700305 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700306 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700307 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700308 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700309 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700310 if key.domain != Domain::BLOB && key.alias.is_none() {
311 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
312 .context("In import_key: Alias must be specified");
313 }
314
315 let key = match key.domain {
316 Domain::APP => KeyDescriptor {
317 domain: key.domain,
318 nspace: ThreadState::get_calling_uid() as i64,
319 alias: key.alias.clone(),
320 blob: None,
321 },
322 _ => key.clone(),
323 };
324
325 // import_key requires the rebind permission.
326 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
327
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328 let format = params
329 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700330 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700331 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
332 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800333 .and_then(|p| match &p.value {
334 KeyParameterValue::Algorithm(Algorithm::AES)
335 | KeyParameterValue::Algorithm(Algorithm::HMAC)
336 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
337 KeyParameterValue::Algorithm(Algorithm::RSA)
338 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
339 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
340 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700341 })
342 .context("In import_key.")?;
343
344 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700345 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700346
Shawn Willdendbdac602021-01-12 22:35:16 -0700347 self.store_new_key(key, creation_result).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700348 }
349
350 fn import_wrapped_key(
351 &self,
352 key: &KeyDescriptor,
353 wrapping_key: &KeyDescriptor,
354 masking_key: Option<&[u8]>,
355 params: &[KeyParameter],
356 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700357 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700358 if key.domain != Domain::BLOB && key.alias.is_none() {
359 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
360 .context("In import_wrapped_key: Alias must be specified.");
361 }
362
Janis Danisevskisaec14592020-11-12 09:41:49 -0800363 if wrapping_key.domain == Domain::BLOB {
364 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
365 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
366 );
367 }
368
Janis Danisevskis1af91262020-08-10 14:58:08 -0700369 let wrapped_data = match &key.blob {
370 Some(d) => d,
371 None => {
372 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
373 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
374 )
375 }
376 };
377
378 let key = match key.domain {
379 Domain::APP => KeyDescriptor {
380 domain: key.domain,
381 nspace: ThreadState::get_calling_uid() as i64,
382 alias: key.alias.clone(),
383 blob: None,
384 },
385 _ => key.clone(),
386 };
387
388 // import_wrapped_key requires the rebind permission for the new key.
389 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
390
Janis Danisevskisaec14592020-11-12 09:41:49 -0800391 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700392 .with(|db| {
393 db.borrow_mut().load_key_entry(
394 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800395 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700396 KeyEntryLoadBits::KM,
397 ThreadState::get_calling_uid(),
398 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
399 )
400 })
401 .context("Failed to load wrapping key.")?;
402 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
403 Some(blob) => blob,
404 None => {
405 return Err(error::Error::sys()).context(concat!(
406 "No km_blob after successfully loading key.",
407 " This should never happen."
408 ))
409 }
410 };
411
Janis Danisevskis1af91262020-08-10 14:58:08 -0700412 // km_dev.importWrappedKey does not return a certificate chain.
413 // TODO Do we assume that all wrapped keys are symmetric?
414 // let certificate_chain: Vec<KmCertificate> = Default::default();
415
416 let pw_sid = authenticators
417 .iter()
418 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700419 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700420 _ => None,
421 })
422 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
423 .context("A password authenticator SID must be specified.")?;
424
425 let fp_sid = authenticators
426 .iter()
427 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700428 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700429 _ => None,
430 })
431 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
432 .context("A fingerprint authenticator SID must be specified.")?;
433
434 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
435
436 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700437 let (creation_result, _) = self.upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800438 &*km_dev,
439 Some(wrapping_key_id_guard),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700440 wrapping_key_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800441 &[],
442 |wrapping_blob| {
Shawn Willdendbdac602021-01-12 22:35:16 -0700443 let creation_result = map_km_error(km_dev.importWrappedKey(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800444 wrapped_data,
445 wrapping_key_blob,
446 masking_key,
447 &params,
448 pw_sid,
449 fp_sid,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800450 ))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700451 Ok(creation_result)
Janis Danisevskisaec14592020-11-12 09:41:49 -0800452 },
453 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700454
Shawn Willdendbdac602021-01-12 22:35:16 -0700455 self.store_new_key(key, creation_result).context("In import_wrapped_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700456 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800457
458 fn upgrade_keyblob_if_required_with<T, F>(
459 &self,
460 km_dev: &dyn IKeyMintDevice,
461 key_id_guard: Option<KeyIdGuard>,
462 blob: &[u8],
463 params: &[KeyParameter],
464 f: F,
465 ) -> Result<(T, Option<Vec<u8>>)>
466 where
467 F: Fn(&[u8]) -> Result<T, Error>,
468 {
469 match f(blob) {
470 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
471 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
472 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
473 key_id_guard.map_or(Ok(()), |key_id_guard| {
474 DB.with(|db| {
475 db.borrow_mut().insert_blob(
476 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800477 SubComponentType::KEY_BLOB,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800478 &upgraded_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800479 )
480 })
481 .context(concat!(
482 "In upgrade_keyblob_if_required_with: ",
483 "Failed to insert upgraded blob into the database.",
484 ))
485 })?;
486 match f(&upgraded_blob) {
487 Ok(v) => Ok((v, Some(upgraded_blob))),
488 Err(e) => Err(e).context(concat!(
489 "In upgrade_keyblob_if_required_with: ",
490 "Failed to perform operation on second try."
491 )),
492 }
493 }
494 Err(e) => {
495 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
496 }
497 Ok(v) => Ok((v, None)),
498 }
499 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700500}
501
502impl binder::Interface for KeystoreSecurityLevel {}
503
504impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700505 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 &self,
507 key: &KeyDescriptor,
508 operation_parameters: &[KeyParameter],
509 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700510 ) -> binder::public_api::Result<CreateOperationResponse> {
511 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700512 }
513 fn generateKey(
514 &self,
515 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700516 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700517 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700518 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700520 ) -> binder::public_api::Result<KeyMetadata> {
521 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700522 }
523 fn importKey(
524 &self,
525 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700526 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700528 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700529 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700530 ) -> binder::public_api::Result<KeyMetadata> {
531 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700532 }
533 fn importWrappedKey(
534 &self,
535 key: &KeyDescriptor,
536 wrapping_key: &KeyDescriptor,
537 masking_key: Option<&[u8]>,
538 params: &[KeyParameter],
539 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700540 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700541 map_or_log_err(
542 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700543 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700544 )
545 }
546}