blob: 079e92acf2f772887b450c2fe1324574f32a5283 [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::{
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000020 Algorithm::Algorithm, HardwareAuthToken::HardwareAuthToken,
21 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
22 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat, KeyParameter::KeyParameter,
23 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070024};
25use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070026 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
27 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
28 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070029 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000030 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, OperationChallenge::OperationChallenge,
Janis Danisevskis1af91262020-08-10 14:58:08 -070031};
32
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000033use crate::auth_token_handler::AuthTokenHandler;
34use crate::globals::ENFORCEMENTS;
35use crate::key_parameter::KeyParameter as KsKeyParam;
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070036use crate::utils::{check_key_permission, Asp};
Janis Danisevskisaec14592020-11-12 09:41:49 -080037use crate::{database::KeyIdGuard, globals::DB};
Janis Danisevskis1af91262020-08-10 14:58:08 -070038use crate::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080039 database::{DateTime, KeyMetaData, KeyMetaEntry, KeyType},
40 permission::KeyPerm,
41};
42use crate::{
Janis Danisevskis1af91262020-08-10 14:58:08 -070043 database::{KeyEntry, KeyEntryLoadBits, SubComponentType},
44 operation::KeystoreOperation,
45 operation::OperationDb,
46};
Janis Danisevskis04b02832020-10-26 09:21:40 -070047use crate::{
48 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
49 utils::key_characteristics_to_internal,
50};
Janis Danisevskisba998992020-12-29 16:08:40 -080051use anyhow::{Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -070052use binder::{IBinder, Interface, ThreadState};
53
54/// Implementation of the IKeystoreSecurityLevel Interface.
55pub struct KeystoreSecurityLevel {
56 security_level: SecurityLevel,
57 keymint: Asp,
58 operation_db: OperationDb,
59}
60
Janis Danisevskis1af91262020-08-10 14:58:08 -070061// Blob of 32 zeroes used as empty masking key.
62static ZERO_BLOB_32: &[u8] = &[0; 32];
63
64impl KeystoreSecurityLevel {
65 /// Creates a new security level instance wrapped in a
66 /// BnKeystoreSecurityLevel proxy object. It also
67 /// calls `IBinder::set_requesting_sid` on the new interface, because
68 /// we need it for checking keystore permissions.
69 pub fn new_native_binder(
70 security_level: SecurityLevel,
71 ) -> Result<impl IKeystoreSecurityLevel + Send> {
Janis Danisevskis1af91262020-08-10 14:58:08 -070072 let result = BnKeystoreSecurityLevel::new_binder(Self {
73 security_level,
Janis Danisevskisba998992020-12-29 16:08:40 -080074 keymint: crate::globals::get_keymint_device(security_level)
75 .context("In KeystoreSecurityLevel::new_native_binder.")?,
Janis Danisevskis1af91262020-08-10 14:58:08 -070076 operation_db: OperationDb::new(),
77 });
78 result.as_binder().set_requesting_sid(true);
79 Ok(result)
80 }
81
82 fn store_new_key(
83 &self,
84 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -070085 creation_result: KeyCreationResult,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070086 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -070087 let KeyCreationResult {
88 keyBlob: key_blob,
89 keyCharacteristics: key_characteristics,
90 certificateChain: mut certificate_chain,
91 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -070092
Shawn Willdendbdac602021-01-12 22:35:16 -070093 let (cert, cert_chain): (Option<Vec<u8>>, Option<Vec<u8>>) = (
94 match certificate_chain.len() {
95 0 => None,
96 _ => Some(certificate_chain.remove(0).encodedCertificate),
97 },
98 match certificate_chain.len() {
99 0 => None,
100 _ => Some(
101 certificate_chain
102 .iter()
103 .map(|c| c.encodedCertificate.iter())
104 .flatten()
105 .copied()
106 .collect(),
107 ),
108 },
109 );
110
111 let key_parameters = key_characteristics_to_internal(key_characteristics);
Janis Danisevskis04b02832020-10-26 09:21:40 -0700112
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800113 let creation_date = DateTime::now().context("Trying to make creation time.")?;
114
Janis Danisevskis1af91262020-08-10 14:58:08 -0700115 let key = match key.domain {
116 Domain::BLOB => {
Shawn Willdendbdac602021-01-12 22:35:16 -0700117 KeyDescriptor { domain: Domain::BLOB, blob: Some(key_blob), ..Default::default() }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700118 }
119 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800120 .with::<_, Result<KeyDescriptor>>(|db| {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800121 let mut metadata = KeyMetaData::new();
122 metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800123
124 let mut db = db.borrow_mut();
125 let key_id = db
126 .store_new_key(
127 key,
128 &key_parameters,
Shawn Willdendbdac602021-01-12 22:35:16 -0700129 &key_blob,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800130 cert.as_deref(),
131 cert_chain.as_deref(),
132 &metadata,
133 )
134 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700135 Ok(KeyDescriptor {
136 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800137 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700138 ..Default::default()
139 })
140 })
141 .context("In store_new_key.")?,
142 };
143
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700144 Ok(KeyMetadata {
145 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700146 keySecurityLevel: self.security_level,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700147 certificate: cert,
148 certificateChain: cert_chain,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700149 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800150 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700151 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700152 }
153
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700154 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700155 &self,
156 key: &KeyDescriptor,
157 operation_parameters: &[KeyParameter],
158 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700159 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700160 let caller_uid = ThreadState::get_calling_uid();
161 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
162 // so that we can use it by reference like the blob provided by the key descriptor.
163 // Otherwise, we would have to clone the blob from the key descriptor.
164 let scoping_blob: Vec<u8>;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000165 let (km_blob, key_id_guard, key_parameters) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700166 Domain::BLOB => {
167 check_key_permission(KeyPerm::use_(), key, &None)
168 .context("In create_operation: checking use permission for Domain::BLOB.")?;
169 (
170 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700171 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700172 None => {
173 return Err(Error::sys()).context(concat!(
174 "In create_operation: Key blob must be specified when",
175 " using Domain::BLOB."
176 ))
177 }
178 },
179 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000180 None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700181 )
182 }
183 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800184 let (key_id_guard, mut key_entry) = DB
185 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700186 db.borrow_mut().load_key_entry(
187 key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800188 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700189 KeyEntryLoadBits::KM,
190 caller_uid,
191 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
192 )
193 })
194 .context("In create_operation: Failed to load key blob.")?;
195 scoping_blob = match key_entry.take_km_blob() {
196 Some(blob) => blob,
197 None => {
198 return Err(Error::sys()).context(concat!(
199 "In create_operation: Successfully loaded key entry,",
200 " but KM blob was missing."
201 ))
202 }
203 };
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000204 (&scoping_blob, Some(key_id_guard), Some(key_entry.into_key_parameters()))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700205 }
206 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700207
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
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000218 let mut auth_token_for_km: &HardwareAuthToken = &Default::default();
219 let mut auth_token_handler = AuthTokenHandler::NoAuthRequired;
220
221 // keystore performs authorizations only if the key parameters are loaded above
222 if let Some(ref key_params) = key_parameters {
223 // Note: although currently only one operation parameter is checked in authorizing the
224 // operation, the whole operation_parameter vector is converted into the internal
225 // representation of key parameter because we might need to sanitize operation
226 // parameters (b/175792701)
227 let mut op_params: Vec<KsKeyParam> = Vec::new();
228 for op_param in operation_parameters.iter() {
229 op_params.push(KsKeyParam::new(op_param.into(), self.security_level));
230 }
231 // authorize the operation, and receive an AuthTokenHandler, if authorized, else
232 // propagate the error
233 auth_token_handler = ENFORCEMENTS
234 .authorize_create(
235 purpose,
236 key_params.as_slice(),
237 op_params.as_slice(),
238 self.security_level,
239 )
240 .context("In create_operation.")?;
241 // if an auth token was found, pass it to keymint
242 if let Some(auth_token) = auth_token_handler.get_auth_token() {
243 auth_token_for_km = auth_token;
244 }
245 }
246
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700247 let km_dev: Box<dyn IKeyMintDevice> = self
248 .keymint
249 .get_interface()
250 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700251
Janis Danisevskisaec14592020-11-12 09:41:49 -0800252 let (begin_result, upgraded_blob) = self
253 .upgrade_keyblob_if_required_with(
254 &*km_dev,
255 key_id_guard,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700256 &km_blob,
257 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800258 |blob| loop {
259 match map_km_error(km_dev.begin(
260 purpose,
261 blob,
262 &operation_parameters,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000263 auth_token_for_km,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800264 )) {
265 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
266 self.operation_db.prune(caller_uid)?;
267 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700268 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800269 v => return v,
270 }
271 },
272 )
273 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700274
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000275 let mut operation_challenge: Option<OperationChallenge> = None;
276
277 // take actions based on the authorization decision (if any) received via auth token handler
278 match auth_token_handler {
279 AuthTokenHandler::OpAuthRequired => {
280 operation_challenge =
281 Some(OperationChallenge { challenge: begin_result.challenge });
282 ENFORCEMENTS.insert_to_op_auth_map(begin_result.challenge);
283 }
284 AuthTokenHandler::VerificationRequired(auth_token) => {
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000285 //request a verification token, given the auth token and the challenge
286 auth_token_handler = ENFORCEMENTS
287 .request_verification_token(
288 auth_token,
289 OperationChallenge { challenge: begin_result.challenge },
290 )
291 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000292 }
293 _ => {}
294 }
295
Janis Danisevskis1af91262020-08-10 14:58:08 -0700296 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000297 Some(km_op) => {
298 let mut op_challenge_copy: Option<OperationChallenge> = None;
299 if let Some(ref op_challenge) = operation_challenge {
300 op_challenge_copy = Some(OperationChallenge{challenge: op_challenge.challenge});
301 }
302 self.operation_db.create_operation(km_op, caller_uid,
303 auth_token_handler, key_parameters, op_challenge_copy)
304 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700305 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 -0700306 };
307
308 let op_binder: Box<dyn IKeystoreOperation> =
309 KeystoreOperation::new_native_binder(operation)
310 .as_binder()
311 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700312 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700313
314 // TODO we need to the enforcement module to determine if we need to return the challenge.
315 // We return None for now because we don't support auth bound keys yet.
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700316 Ok(CreateOperationResponse {
317 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000318 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700319 parameters: match begin_result.params.len() {
320 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700321 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700322 },
323 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700324 }
325
326 fn generate_key(
327 &self,
328 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700329 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700330 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700331 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700332 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700333 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700334 if key.domain != Domain::BLOB && key.alias.is_none() {
335 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
336 .context("In generate_key: Alias must be specified");
337 }
338
339 let key = match key.domain {
340 Domain::APP => KeyDescriptor {
341 domain: key.domain,
342 nspace: ThreadState::get_calling_uid() as i64,
343 alias: key.alias.clone(),
344 blob: None,
345 },
346 _ => key.clone(),
347 };
348
349 // generate_key requires the rebind permission.
350 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
351
352 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
353 map_km_error(km_dev.addRngEntropy(entropy))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700354 let creation_result = map_km_error(km_dev.generateKey(&params))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700355
Shawn Willdendbdac602021-01-12 22:35:16 -0700356 self.store_new_key(key, creation_result).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700357 }
358
359 fn import_key(
360 &self,
361 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700362 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700363 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700364 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700365 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700366 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700367 if key.domain != Domain::BLOB && key.alias.is_none() {
368 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
369 .context("In import_key: Alias must be specified");
370 }
371
372 let key = match key.domain {
373 Domain::APP => KeyDescriptor {
374 domain: key.domain,
375 nspace: ThreadState::get_calling_uid() as i64,
376 alias: key.alias.clone(),
377 blob: None,
378 },
379 _ => key.clone(),
380 };
381
382 // import_key requires the rebind permission.
383 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
384
Janis Danisevskis1af91262020-08-10 14:58:08 -0700385 let format = params
386 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700387 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700388 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
389 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800390 .and_then(|p| match &p.value {
391 KeyParameterValue::Algorithm(Algorithm::AES)
392 | KeyParameterValue::Algorithm(Algorithm::HMAC)
393 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
394 KeyParameterValue::Algorithm(Algorithm::RSA)
395 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
396 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
397 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700398 })
399 .context("In import_key.")?;
400
401 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700402 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700403
Shawn Willdendbdac602021-01-12 22:35:16 -0700404 self.store_new_key(key, creation_result).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700405 }
406
407 fn import_wrapped_key(
408 &self,
409 key: &KeyDescriptor,
410 wrapping_key: &KeyDescriptor,
411 masking_key: Option<&[u8]>,
412 params: &[KeyParameter],
413 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700414 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700415 if key.domain != Domain::BLOB && key.alias.is_none() {
416 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
417 .context("In import_wrapped_key: Alias must be specified.");
418 }
419
Janis Danisevskisaec14592020-11-12 09:41:49 -0800420 if wrapping_key.domain == Domain::BLOB {
421 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
422 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
423 );
424 }
425
Janis Danisevskis1af91262020-08-10 14:58:08 -0700426 let wrapped_data = match &key.blob {
427 Some(d) => d,
428 None => {
429 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
430 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
431 )
432 }
433 };
434
435 let key = match key.domain {
436 Domain::APP => KeyDescriptor {
437 domain: key.domain,
438 nspace: ThreadState::get_calling_uid() as i64,
439 alias: key.alias.clone(),
440 blob: None,
441 },
442 _ => key.clone(),
443 };
444
445 // import_wrapped_key requires the rebind permission for the new key.
446 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
447
Janis Danisevskisaec14592020-11-12 09:41:49 -0800448 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700449 .with(|db| {
450 db.borrow_mut().load_key_entry(
451 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800452 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700453 KeyEntryLoadBits::KM,
454 ThreadState::get_calling_uid(),
455 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
456 )
457 })
458 .context("Failed to load wrapping key.")?;
459 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
460 Some(blob) => blob,
461 None => {
462 return Err(error::Error::sys()).context(concat!(
463 "No km_blob after successfully loading key.",
464 " This should never happen."
465 ))
466 }
467 };
468
Janis Danisevskis1af91262020-08-10 14:58:08 -0700469 // km_dev.importWrappedKey does not return a certificate chain.
470 // TODO Do we assume that all wrapped keys are symmetric?
471 // let certificate_chain: Vec<KmCertificate> = Default::default();
472
473 let pw_sid = authenticators
474 .iter()
475 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700476 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700477 _ => None,
478 })
479 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
480 .context("A password authenticator SID must be specified.")?;
481
482 let fp_sid = authenticators
483 .iter()
484 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700485 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700486 _ => None,
487 })
488 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
489 .context("A fingerprint authenticator SID must be specified.")?;
490
491 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
492
493 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700494 let (creation_result, _) = self.upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800495 &*km_dev,
496 Some(wrapping_key_id_guard),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700497 wrapping_key_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800498 &[],
499 |wrapping_blob| {
Shawn Willdendbdac602021-01-12 22:35:16 -0700500 let creation_result = map_km_error(km_dev.importWrappedKey(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800501 wrapped_data,
502 wrapping_key_blob,
503 masking_key,
504 &params,
505 pw_sid,
506 fp_sid,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800507 ))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700508 Ok(creation_result)
Janis Danisevskisaec14592020-11-12 09:41:49 -0800509 },
510 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700511
Shawn Willdendbdac602021-01-12 22:35:16 -0700512 self.store_new_key(key, creation_result).context("In import_wrapped_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700513 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800514
515 fn upgrade_keyblob_if_required_with<T, F>(
516 &self,
517 km_dev: &dyn IKeyMintDevice,
518 key_id_guard: Option<KeyIdGuard>,
519 blob: &[u8],
520 params: &[KeyParameter],
521 f: F,
522 ) -> Result<(T, Option<Vec<u8>>)>
523 where
524 F: Fn(&[u8]) -> Result<T, Error>,
525 {
526 match f(blob) {
527 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
528 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
529 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
530 key_id_guard.map_or(Ok(()), |key_id_guard| {
531 DB.with(|db| {
532 db.borrow_mut().insert_blob(
533 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800534 SubComponentType::KEY_BLOB,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800535 &upgraded_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800536 )
537 })
538 .context(concat!(
539 "In upgrade_keyblob_if_required_with: ",
540 "Failed to insert upgraded blob into the database.",
541 ))
542 })?;
543 match f(&upgraded_blob) {
544 Ok(v) => Ok((v, Some(upgraded_blob))),
545 Err(e) => Err(e).context(concat!(
546 "In upgrade_keyblob_if_required_with: ",
547 "Failed to perform operation on second try."
548 )),
549 }
550 }
551 Err(e) => {
552 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
553 }
554 Ok(v) => Ok((v, None)),
555 }
556 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700557}
558
559impl binder::Interface for KeystoreSecurityLevel {}
560
561impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700562 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700563 &self,
564 key: &KeyDescriptor,
565 operation_parameters: &[KeyParameter],
566 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700567 ) -> binder::public_api::Result<CreateOperationResponse> {
568 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569 }
570 fn generateKey(
571 &self,
572 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700573 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700574 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700575 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700576 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700577 ) -> binder::public_api::Result<KeyMetadata> {
578 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700579 }
580 fn importKey(
581 &self,
582 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700583 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700584 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700585 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700586 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700587 ) -> binder::public_api::Result<KeyMetadata> {
588 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700589 }
590 fn importWrappedKey(
591 &self,
592 key: &KeyDescriptor,
593 wrapping_key: &KeyDescriptor,
594 masking_key: Option<&[u8]>,
595 params: &[KeyParameter],
596 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700597 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700598 map_or_log_err(
599 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700600 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700601 )
602 }
603}