blob: af59f793b893980ca34420352d013abb724d3f79 [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::{
Janis Danisevskis85d47932020-10-23 16:12:59 -070020 Algorithm::Algorithm, ByteArray::ByteArray, Certificate::Certificate as KmCertificate,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070021 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
22 KeyCharacteristics::KeyCharacteristics, KeyFormat::KeyFormat, KeyParameter::KeyParameter,
Janis Danisevskis398e6be2020-12-17 09:29:25 -080023 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070024};
25use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070026 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
27 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
28 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070029 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis 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,
Janis Danisevskis04b02832020-10-26 09:21:40 -070082 key_characteristics: KeyCharacteristics,
Janis Danisevskis1af91262020-08-10 14:58:08 -070083 km_cert_chain: Option<Vec<KmCertificate>>,
Janis Danisevskis85d47932020-10-23 16:12:59 -070084 blob: ByteArray,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070085 ) -> Result<KeyMetadata> {
86 let (cert, cert_chain): (Option<Vec<u8>>, Option<Vec<u8>>) = match km_cert_chain {
Janis Danisevskis1af91262020-08-10 14:58:08 -070087 Some(mut chain) => (
88 match chain.len() {
89 0 => None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070090 _ => Some(chain.remove(0).encodedCertificate),
Janis Danisevskis1af91262020-08-10 14:58:08 -070091 },
92 match chain.len() {
93 0 => None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070094 _ => Some(
95 chain
Janis Danisevskis1af91262020-08-10 14:58:08 -070096 .iter()
97 .map(|c| c.encodedCertificate.iter())
98 .flatten()
99 .copied()
100 .collect(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700101 ),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700102 },
103 ),
104 None => (None, None),
105 };
106
Janis Danisevskis04b02832020-10-26 09:21:40 -0700107 let key_parameters =
108 key_characteristics_to_internal(key_characteristics, self.security_level);
109
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 => {
Janis Danisevskis85d47932020-10-23 16:12:59 -0700114 KeyDescriptor { domain: Domain::BLOB, blob: Some(blob.data), ..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,
126 &blob.data,
127 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))?;
Janis Danisevskis85d47932020-10-23 16:12:59 -0700297 let mut blob: ByteArray = Default::default();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700298 let mut key_characteristics: KeyCharacteristics = Default::default();
299 let mut certificate_chain: Vec<KmCertificate> = Default::default();
300 map_km_error(km_dev.generateKey(
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700301 &params,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700302 &mut blob,
303 &mut key_characteristics,
304 &mut certificate_chain,
305 ))?;
306
Janis Danisevskis04b02832020-10-26 09:21:40 -0700307 self.store_new_key(key, key_characteristics, Some(certificate_chain), blob)
308 .context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700309 }
310
311 fn import_key(
312 &self,
313 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700314 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700315 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700316 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700317 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700318 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700319 if key.domain != Domain::BLOB && key.alias.is_none() {
320 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
321 .context("In import_key: Alias must be specified");
322 }
323
324 let key = match key.domain {
325 Domain::APP => KeyDescriptor {
326 domain: key.domain,
327 nspace: ThreadState::get_calling_uid() as i64,
328 alias: key.alias.clone(),
329 blob: None,
330 },
331 _ => key.clone(),
332 };
333
334 // import_key requires the rebind permission.
335 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
336
Janis Danisevskis85d47932020-10-23 16:12:59 -0700337 let mut blob: ByteArray = Default::default();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700338 let mut key_characteristics: KeyCharacteristics = Default::default();
339 let mut certificate_chain: Vec<KmCertificate> = Default::default();
340
341 let format = params
342 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700343 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700344 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
345 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800346 .and_then(|p| match &p.value {
347 KeyParameterValue::Algorithm(Algorithm::AES)
348 | KeyParameterValue::Algorithm(Algorithm::HMAC)
349 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
350 KeyParameterValue::Algorithm(Algorithm::RSA)
351 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
352 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
353 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700354 })
355 .context("In import_key.")?;
356
357 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
358 map_km_error(km_dev.importKey(
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700359 &params,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700360 format,
361 key_data,
362 &mut blob,
363 &mut key_characteristics,
364 &mut certificate_chain,
365 ))?;
366
Janis Danisevskis04b02832020-10-26 09:21:40 -0700367 self.store_new_key(key, key_characteristics, Some(certificate_chain), blob)
368 .context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700369 }
370
371 fn import_wrapped_key(
372 &self,
373 key: &KeyDescriptor,
374 wrapping_key: &KeyDescriptor,
375 masking_key: Option<&[u8]>,
376 params: &[KeyParameter],
377 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700378 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700379 if key.domain != Domain::BLOB && key.alias.is_none() {
380 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
381 .context("In import_wrapped_key: Alias must be specified.");
382 }
383
Janis Danisevskisaec14592020-11-12 09:41:49 -0800384 if wrapping_key.domain == Domain::BLOB {
385 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
386 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
387 );
388 }
389
Janis Danisevskis1af91262020-08-10 14:58:08 -0700390 let wrapped_data = match &key.blob {
391 Some(d) => d,
392 None => {
393 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
394 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
395 )
396 }
397 };
398
399 let key = match key.domain {
400 Domain::APP => KeyDescriptor {
401 domain: key.domain,
402 nspace: ThreadState::get_calling_uid() as i64,
403 alias: key.alias.clone(),
404 blob: None,
405 },
406 _ => key.clone(),
407 };
408
409 // import_wrapped_key requires the rebind permission for the new key.
410 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
411
Janis Danisevskisaec14592020-11-12 09:41:49 -0800412 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700413 .with(|db| {
414 db.borrow_mut().load_key_entry(
415 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800416 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700417 KeyEntryLoadBits::KM,
418 ThreadState::get_calling_uid(),
419 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
420 )
421 })
422 .context("Failed to load wrapping key.")?;
423 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
424 Some(blob) => blob,
425 None => {
426 return Err(error::Error::sys()).context(concat!(
427 "No km_blob after successfully loading key.",
428 " This should never happen."
429 ))
430 }
431 };
432
Janis Danisevskis1af91262020-08-10 14:58:08 -0700433 // km_dev.importWrappedKey does not return a certificate chain.
434 // TODO Do we assume that all wrapped keys are symmetric?
435 // let certificate_chain: Vec<KmCertificate> = Default::default();
436
437 let pw_sid = authenticators
438 .iter()
439 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700440 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700441 _ => None,
442 })
443 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
444 .context("A password authenticator SID must be specified.")?;
445
446 let fp_sid = authenticators
447 .iter()
448 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700449 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700450 _ => None,
451 })
452 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
453 .context("A fingerprint authenticator SID must be specified.")?;
454
455 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
456
457 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800458 let ((blob, key_characteristics), _) = self.upgrade_keyblob_if_required_with(
459 &*km_dev,
460 Some(wrapping_key_id_guard),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700461 wrapping_key_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800462 &[],
463 |wrapping_blob| {
464 let mut blob: ByteArray = Default::default();
465 let mut key_characteristics: KeyCharacteristics = Default::default();
466 map_km_error(km_dev.importWrappedKey(
467 wrapped_data,
468 wrapping_key_blob,
469 masking_key,
470 &params,
471 pw_sid,
472 fp_sid,
473 &mut blob,
474 &mut key_characteristics,
475 ))?;
476 Ok((blob, key_characteristics))
477 },
478 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700479
Janis Danisevskis04b02832020-10-26 09:21:40 -0700480 self.store_new_key(key, key_characteristics, None, blob).context("In import_wrapped_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700481 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800482
483 fn upgrade_keyblob_if_required_with<T, F>(
484 &self,
485 km_dev: &dyn IKeyMintDevice,
486 key_id_guard: Option<KeyIdGuard>,
487 blob: &[u8],
488 params: &[KeyParameter],
489 f: F,
490 ) -> Result<(T, Option<Vec<u8>>)>
491 where
492 F: Fn(&[u8]) -> Result<T, Error>,
493 {
494 match f(blob) {
495 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
496 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
497 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
498 key_id_guard.map_or(Ok(()), |key_id_guard| {
499 DB.with(|db| {
500 db.borrow_mut().insert_blob(
501 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800502 SubComponentType::KEY_BLOB,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800503 &upgraded_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800504 )
505 })
506 .context(concat!(
507 "In upgrade_keyblob_if_required_with: ",
508 "Failed to insert upgraded blob into the database.",
509 ))
510 })?;
511 match f(&upgraded_blob) {
512 Ok(v) => Ok((v, Some(upgraded_blob))),
513 Err(e) => Err(e).context(concat!(
514 "In upgrade_keyblob_if_required_with: ",
515 "Failed to perform operation on second try."
516 )),
517 }
518 }
519 Err(e) => {
520 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
521 }
522 Ok(v) => Ok((v, None)),
523 }
524 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700525}
526
527impl binder::Interface for KeystoreSecurityLevel {}
528
529impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700530 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700531 &self,
532 key: &KeyDescriptor,
533 operation_parameters: &[KeyParameter],
534 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700535 ) -> binder::public_api::Result<CreateOperationResponse> {
536 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700537 }
538 fn generateKey(
539 &self,
540 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700541 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700542 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700543 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700544 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700545 ) -> binder::public_api::Result<KeyMetadata> {
546 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700547 }
548 fn importKey(
549 &self,
550 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700551 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700552 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700553 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700554 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700555 ) -> binder::public_api::Result<KeyMetadata> {
556 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700557 }
558 fn importWrappedKey(
559 &self,
560 key: &KeyDescriptor,
561 wrapping_key: &KeyDescriptor,
562 masking_key: Option<&[u8]>,
563 params: &[KeyParameter],
564 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700565 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700566 map_or_log_err(
567 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700568 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569 )
570 }
571}