blob: 34f07e0f945eaec4457af2e12f980ef0be0a0d8a [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
Janis Danisevskis4507f3b2021-01-13 16:34:39 -080019use crate::gc::Gc;
Shawn Willden708744a2020-12-11 13:05:27 +000020use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080021 Algorithm::Algorithm, HardwareAuthenticatorType::HardwareAuthenticatorType,
22 IKeyMintDevice::IKeyMintDevice, KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
23 KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel,
24 Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070025};
26use 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
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000034use crate::globals::ENFORCEMENTS;
35use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000036use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070037use crate::utils::{check_key_permission, Asp};
Janis Danisevskisaec14592020-11-12 09:41:49 -080038use crate::{database::KeyIdGuard, globals::DB};
Janis Danisevskis1af91262020-08-10 14:58:08 -070039use crate::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080040 database::{DateTime, KeyMetaData, KeyMetaEntry, KeyType},
41 permission::KeyPerm,
42};
43use crate::{
Janis Danisevskis1af91262020-08-10 14:58:08 -070044 database::{KeyEntry, KeyEntryLoadBits, SubComponentType},
45 operation::KeystoreOperation,
46 operation::OperationDb,
47};
Janis Danisevskis04b02832020-10-26 09:21:40 -070048use crate::{
49 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
50 utils::key_characteristics_to_internal,
Hasini Gunasinghea020b532021-01-07 21:42:35 +000051 utils::uid_to_android_user,
Janis Danisevskis04b02832020-10-26 09:21:40 -070052};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080053use anyhow::{anyhow, Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -070054use binder::{IBinder, Interface, ThreadState};
55
56/// Implementation of the IKeystoreSecurityLevel Interface.
57pub struct KeystoreSecurityLevel {
58 security_level: SecurityLevel,
59 keymint: Asp,
60 operation_db: OperationDb,
61}
62
Janis Danisevskis1af91262020-08-10 14:58:08 -070063// Blob of 32 zeroes used as empty masking key.
64static ZERO_BLOB_32: &[u8] = &[0; 32];
65
66impl KeystoreSecurityLevel {
67 /// Creates a new security level instance wrapped in a
68 /// BnKeystoreSecurityLevel proxy object. It also
69 /// calls `IBinder::set_requesting_sid` on the new interface, because
70 /// we need it for checking keystore permissions.
71 pub fn new_native_binder(
72 security_level: SecurityLevel,
73 ) -> Result<impl IKeystoreSecurityLevel + Send> {
Janis Danisevskis1af91262020-08-10 14:58:08 -070074 let result = BnKeystoreSecurityLevel::new_binder(Self {
75 security_level,
Janis Danisevskisba998992020-12-29 16:08:40 -080076 keymint: crate::globals::get_keymint_device(security_level)
77 .context("In KeystoreSecurityLevel::new_native_binder.")?,
Janis Danisevskis1af91262020-08-10 14:58:08 -070078 operation_db: OperationDb::new(),
79 });
80 result.as_binder().set_requesting_sid(true);
81 Ok(result)
82 }
83
84 fn store_new_key(
85 &self,
86 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -070087 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +000088 user_id: u32,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070089 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -070090 let KeyCreationResult {
91 keyBlob: key_blob,
92 keyCharacteristics: key_characteristics,
93 certificateChain: mut certificate_chain,
94 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -070095
Shawn Willdendbdac602021-01-12 22:35:16 -070096 let (cert, cert_chain): (Option<Vec<u8>>, Option<Vec<u8>>) = (
97 match certificate_chain.len() {
98 0 => None,
99 _ => Some(certificate_chain.remove(0).encodedCertificate),
100 },
101 match certificate_chain.len() {
102 0 => None,
103 _ => Some(
104 certificate_chain
105 .iter()
106 .map(|c| c.encodedCertificate.iter())
107 .flatten()
108 .copied()
109 .collect(),
110 ),
111 },
112 );
113
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000114 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
115
116 key_parameters.push(KsKeyParam::new(
117 KsKeyParamValue::UserID(user_id as i32),
118 SecurityLevel::SOFTWARE,
119 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700120
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800121 let creation_date = DateTime::now().context("Trying to make creation time.")?;
122
Janis Danisevskis1af91262020-08-10 14:58:08 -0700123 let key = match key.domain {
124 Domain::BLOB => {
Shawn Willdendbdac602021-01-12 22:35:16 -0700125 KeyDescriptor { domain: Domain::BLOB, blob: Some(key_blob), ..Default::default() }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700126 }
127 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800128 .with::<_, Result<KeyDescriptor>>(|db| {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800129 let mut metadata = KeyMetaData::new();
130 metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800131
132 let mut db = db.borrow_mut();
Janis Danisevskis4507f3b2021-01-13 16:34:39 -0800133 let (need_gc, key_id) = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800134 .store_new_key(
135 key,
136 &key_parameters,
Shawn Willdendbdac602021-01-12 22:35:16 -0700137 &key_blob,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800138 cert.as_deref(),
139 cert_chain.as_deref(),
140 &metadata,
141 )
142 .context("In store_new_key.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -0800143 if need_gc {
144 Gc::notify_gc();
145 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700146 Ok(KeyDescriptor {
147 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800148 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700149 ..Default::default()
150 })
151 })
152 .context("In store_new_key.")?,
153 };
154
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700155 Ok(KeyMetadata {
156 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700157 keySecurityLevel: self.security_level,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700158 certificate: cert,
159 certificateChain: cert_chain,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700160 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800161 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700162 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700163 }
164
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700165 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700166 &self,
167 key: &KeyDescriptor,
168 operation_parameters: &[KeyParameter],
169 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700170 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700171 let caller_uid = ThreadState::get_calling_uid();
172 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
173 // so that we can use it by reference like the blob provided by the key descriptor.
174 // Otherwise, we would have to clone the blob from the key descriptor.
175 let scoping_blob: Vec<u8>;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000176 let (km_blob, key_id_guard, key_parameters) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700177 Domain::BLOB => {
178 check_key_permission(KeyPerm::use_(), key, &None)
179 .context("In create_operation: checking use permission for Domain::BLOB.")?;
180 (
181 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700182 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700183 None => {
184 return Err(Error::sys()).context(concat!(
185 "In create_operation: Key blob must be specified when",
186 " using Domain::BLOB."
187 ))
188 }
189 },
190 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000191 None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700192 )
193 }
194 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800195 let (key_id_guard, mut key_entry) = DB
196 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700197 db.borrow_mut().load_key_entry(
198 key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800199 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700200 KeyEntryLoadBits::KM,
201 caller_uid,
202 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
203 )
204 })
205 .context("In create_operation: Failed to load key blob.")?;
206 scoping_blob = match key_entry.take_km_blob() {
207 Some(blob) => blob,
208 None => {
209 return Err(Error::sys()).context(concat!(
210 "In create_operation: Successfully loaded key entry,",
211 " but KM blob was missing."
212 ))
213 }
214 };
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000215 (&scoping_blob, Some(key_id_guard), Some(key_entry.into_key_parameters()))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700216 }
217 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700218
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700219 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700220 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700221 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800222 |kp| match kp.value {
223 KeyParameterValue::KeyPurpose(p) => Ok(p),
224 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
225 .context("In create_operation: Malformed KeyParameter."),
226 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700227 )?;
228
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800229 let (immediate_hat, mut auth_info) = ENFORCEMENTS
230 .authorize_create(
231 purpose,
232 key_parameters.as_deref(),
233 operation_parameters,
234 // TODO b/178222844 Replace this with the configuration returned by
235 // KeyMintDevice::getHardwareInfo.
236 // For now we assume that strongbox implementations need secure timestamps.
237 self.security_level == SecurityLevel::STRONGBOX,
238 )
239 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000240
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800241 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000242
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700243 let km_dev: Box<dyn IKeyMintDevice> = self
244 .keymint
245 .get_interface()
246 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700247
Janis Danisevskisaec14592020-11-12 09:41:49 -0800248 let (begin_result, upgraded_blob) = self
249 .upgrade_keyblob_if_required_with(
250 &*km_dev,
251 key_id_guard,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700252 &km_blob,
253 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800254 |blob| loop {
255 match map_km_error(km_dev.begin(
256 purpose,
257 blob,
258 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800259 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800260 )) {
261 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
262 self.operation_db.prune(caller_uid)?;
263 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700264 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800265 v => return v,
266 }
267 },
268 )
269 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700270
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800271 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000272
Janis Danisevskis1af91262020-08-10 14:58:08 -0700273 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000274 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800275 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000276 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700277 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 -0700278 };
279
280 let op_binder: Box<dyn IKeystoreOperation> =
281 KeystoreOperation::new_native_binder(operation)
282 .as_binder()
283 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700284 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700285
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700286 Ok(CreateOperationResponse {
287 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000288 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700289 parameters: match begin_result.params.len() {
290 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700291 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700292 },
293 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700294 }
295
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800296 fn add_attestation_parameters(uid: u32, params: &[KeyParameter]) -> Result<Vec<KeyParameter>> {
297 let mut result = params.to_vec();
298 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
299 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
300 anyhow!(format!("In add_attestation_parameters: get_aaid returned status {}.", e))
301 })?;
302 result.push(KeyParameter {
303 tag: Tag::ATTESTATION_APPLICATION_ID,
304 value: KeyParameterValue::Blob(aaid),
305 });
306 }
307 Ok(result)
308 }
309
Janis Danisevskis1af91262020-08-10 14:58:08 -0700310 fn generate_key(
311 &self,
312 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700313 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700314 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700315 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700316 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700317 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700318 if key.domain != Domain::BLOB && key.alias.is_none() {
319 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
320 .context("In generate_key: Alias must be specified");
321 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000322 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700323
324 let key = match key.domain {
325 Domain::APP => KeyDescriptor {
326 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000327 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328 alias: key.alias.clone(),
329 blob: None,
330 },
331 _ => key.clone(),
332 };
333
334 // generate_key requires the rebind permission.
335 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
336
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800337 let params = Self::add_attestation_parameters(caller_uid, params)
338 .context("In generate_key: Trying to get aaid.")?;
339
Janis Danisevskis1af91262020-08-10 14:58:08 -0700340 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
341 map_km_error(km_dev.addRngEntropy(entropy))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700342 let creation_result = map_km_error(km_dev.generateKey(&params))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700343
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000344 let user_id = uid_to_android_user(caller_uid);
345 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700346 }
347
348 fn import_key(
349 &self,
350 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700351 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700352 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700353 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700354 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700355 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700356 if key.domain != Domain::BLOB && key.alias.is_none() {
357 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
358 .context("In import_key: Alias must be specified");
359 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000360 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361
362 let key = match key.domain {
363 Domain::APP => KeyDescriptor {
364 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000365 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700366 alias: key.alias.clone(),
367 blob: None,
368 },
369 _ => key.clone(),
370 };
371
372 // import_key requires the rebind permission.
373 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
374
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800375 let params = Self::add_attestation_parameters(caller_uid, params)
376 .context("In import_key: Trying to get aaid.")?;
377
Janis Danisevskis1af91262020-08-10 14:58:08 -0700378 let format = params
379 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700380 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700381 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
382 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800383 .and_then(|p| match &p.value {
384 KeyParameterValue::Algorithm(Algorithm::AES)
385 | KeyParameterValue::Algorithm(Algorithm::HMAC)
386 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
387 KeyParameterValue::Algorithm(Algorithm::RSA)
388 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
389 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
390 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700391 })
392 .context("In import_key.")?;
393
394 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700395 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700396
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000397 let user_id = uid_to_android_user(caller_uid);
398 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700399 }
400
401 fn import_wrapped_key(
402 &self,
403 key: &KeyDescriptor,
404 wrapping_key: &KeyDescriptor,
405 masking_key: Option<&[u8]>,
406 params: &[KeyParameter],
407 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700408 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700409 if key.domain != Domain::BLOB && key.alias.is_none() {
410 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
411 .context("In import_wrapped_key: Alias must be specified.");
412 }
413
Janis Danisevskisaec14592020-11-12 09:41:49 -0800414 if wrapping_key.domain == Domain::BLOB {
415 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
416 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
417 );
418 }
419
Janis Danisevskis1af91262020-08-10 14:58:08 -0700420 let wrapped_data = match &key.blob {
421 Some(d) => d,
422 None => {
423 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
424 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
425 )
426 }
427 };
428
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000429 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700430 let key = match key.domain {
431 Domain::APP => KeyDescriptor {
432 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000433 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700434 alias: key.alias.clone(),
435 blob: None,
436 },
437 _ => key.clone(),
438 };
439
440 // import_wrapped_key requires the rebind permission for the new key.
441 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
442
Janis Danisevskisaec14592020-11-12 09:41:49 -0800443 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700444 .with(|db| {
445 db.borrow_mut().load_key_entry(
446 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800447 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700448 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000449 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700450 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
451 )
452 })
453 .context("Failed to load wrapping key.")?;
454 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
455 Some(blob) => blob,
456 None => {
457 return Err(error::Error::sys()).context(concat!(
458 "No km_blob after successfully loading key.",
459 " This should never happen."
460 ))
461 }
462 };
463
Janis Danisevskis1af91262020-08-10 14:58:08 -0700464 // km_dev.importWrappedKey does not return a certificate chain.
465 // TODO Do we assume that all wrapped keys are symmetric?
466 // let certificate_chain: Vec<KmCertificate> = Default::default();
467
468 let pw_sid = authenticators
469 .iter()
470 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700471 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700472 _ => None,
473 })
474 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
475 .context("A password authenticator SID must be specified.")?;
476
477 let fp_sid = authenticators
478 .iter()
479 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700480 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700481 _ => None,
482 })
483 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
484 .context("A fingerprint authenticator SID must be specified.")?;
485
486 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
487
488 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700489 let (creation_result, _) = self.upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800490 &*km_dev,
491 Some(wrapping_key_id_guard),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700492 wrapping_key_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800493 &[],
494 |wrapping_blob| {
Shawn Willdendbdac602021-01-12 22:35:16 -0700495 let creation_result = map_km_error(km_dev.importWrappedKey(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800496 wrapped_data,
497 wrapping_key_blob,
498 masking_key,
499 &params,
500 pw_sid,
501 fp_sid,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800502 ))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700503 Ok(creation_result)
Janis Danisevskisaec14592020-11-12 09:41:49 -0800504 },
505 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000507 let user_id = uid_to_android_user(caller_uid);
508 self.store_new_key(key, creation_result, user_id).context("In import_wrapped_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700509 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800510
511 fn upgrade_keyblob_if_required_with<T, F>(
512 &self,
513 km_dev: &dyn IKeyMintDevice,
514 key_id_guard: Option<KeyIdGuard>,
515 blob: &[u8],
516 params: &[KeyParameter],
517 f: F,
518 ) -> Result<(T, Option<Vec<u8>>)>
519 where
520 F: Fn(&[u8]) -> Result<T, Error>,
521 {
522 match f(blob) {
523 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
524 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
525 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
526 key_id_guard.map_or(Ok(()), |key_id_guard| {
527 DB.with(|db| {
528 db.borrow_mut().insert_blob(
529 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800530 SubComponentType::KEY_BLOB,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800531 &upgraded_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800532 )
533 })
534 .context(concat!(
535 "In upgrade_keyblob_if_required_with: ",
536 "Failed to insert upgraded blob into the database.",
537 ))
538 })?;
539 match f(&upgraded_blob) {
540 Ok(v) => Ok((v, Some(upgraded_blob))),
541 Err(e) => Err(e).context(concat!(
542 "In upgrade_keyblob_if_required_with: ",
543 "Failed to perform operation on second try."
544 )),
545 }
546 }
547 Err(e) => {
548 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
549 }
550 Ok(v) => Ok((v, None)),
551 }
552 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700553}
554
555impl binder::Interface for KeystoreSecurityLevel {}
556
557impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700558 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700559 &self,
560 key: &KeyDescriptor,
561 operation_parameters: &[KeyParameter],
562 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700563 ) -> binder::public_api::Result<CreateOperationResponse> {
564 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700565 }
566 fn generateKey(
567 &self,
568 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700569 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700570 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700571 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700572 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700573 ) -> binder::public_api::Result<KeyMetadata> {
574 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700575 }
576 fn importKey(
577 &self,
578 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700579 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700580 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700581 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700582 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700583 ) -> binder::public_api::Result<KeyMetadata> {
584 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700585 }
586 fn importWrappedKey(
587 &self,
588 key: &KeyDescriptor,
589 wrapping_key: &KeyDescriptor,
590 masking_key: Option<&[u8]>,
591 params: &[KeyParameter],
592 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700593 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700594 map_or_log_err(
595 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700596 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700597 )
598 }
599}