blob: d0972d147527bb32c6fc2e4f830120c9baef772f [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 Danisevskisba998992020-12-29 16:08:40 -080053use 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
296 fn generate_key(
297 &self,
298 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700299 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700300 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700301 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700302 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700303 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700304 if key.domain != Domain::BLOB && key.alias.is_none() {
305 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
306 .context("In generate_key: Alias must be specified");
307 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000308 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700309
310 let key = match key.domain {
311 Domain::APP => KeyDescriptor {
312 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000313 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700314 alias: key.alias.clone(),
315 blob: None,
316 },
317 _ => key.clone(),
318 };
319
320 // generate_key requires the rebind permission.
321 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
322
323 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800324 map_km_error(km_dev.addRngEntropy(entropy))
325 .context("In generate_key: Trying to add entropy.")?;
326 let creation_result = map_km_error(km_dev.generateKey(&params))
327 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000329 let user_id = uid_to_android_user(caller_uid);
330 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700331 }
332
333 fn import_key(
334 &self,
335 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700336 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700337 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700338 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700339 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700340 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700341 if key.domain != Domain::BLOB && key.alias.is_none() {
342 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
343 .context("In import_key: Alias must be specified");
344 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000345 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700346
347 let key = match key.domain {
348 Domain::APP => KeyDescriptor {
349 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000350 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700351 alias: key.alias.clone(),
352 blob: None,
353 },
354 _ => key.clone(),
355 };
356
357 // import_key requires the rebind permission.
358 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
359
Janis Danisevskis1af91262020-08-10 14:58:08 -0700360 let format = params
361 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700362 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700363 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
364 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800365 .and_then(|p| match &p.value {
366 KeyParameterValue::Algorithm(Algorithm::AES)
367 | KeyParameterValue::Algorithm(Algorithm::HMAC)
368 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
369 KeyParameterValue::Algorithm(Algorithm::RSA)
370 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
371 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
372 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700373 })
374 .context("In import_key.")?;
375
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800376 let km_dev: Box<dyn IKeyMintDevice> =
377 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
378 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))
379 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700380
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000381 let user_id = uid_to_android_user(caller_uid);
382 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700383 }
384
385 fn import_wrapped_key(
386 &self,
387 key: &KeyDescriptor,
388 wrapping_key: &KeyDescriptor,
389 masking_key: Option<&[u8]>,
390 params: &[KeyParameter],
391 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700392 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700393 if key.domain != Domain::BLOB && key.alias.is_none() {
394 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
395 .context("In import_wrapped_key: Alias must be specified.");
396 }
397
Janis Danisevskisaec14592020-11-12 09:41:49 -0800398 if wrapping_key.domain == Domain::BLOB {
399 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
400 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
401 );
402 }
403
Janis Danisevskis1af91262020-08-10 14:58:08 -0700404 let wrapped_data = match &key.blob {
405 Some(d) => d,
406 None => {
407 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
408 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
409 )
410 }
411 };
412
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000413 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700414 let key = match key.domain {
415 Domain::APP => KeyDescriptor {
416 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000417 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700418 alias: key.alias.clone(),
419 blob: None,
420 },
421 _ => key.clone(),
422 };
423
424 // import_wrapped_key requires the rebind permission for the new key.
425 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
426
Janis Danisevskisaec14592020-11-12 09:41:49 -0800427 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700428 .with(|db| {
429 db.borrow_mut().load_key_entry(
430 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800431 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700432 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000433 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700434 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
435 )
436 })
437 .context("Failed to load wrapping key.")?;
438 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
439 Some(blob) => blob,
440 None => {
441 return Err(error::Error::sys()).context(concat!(
442 "No km_blob after successfully loading key.",
443 " This should never happen."
444 ))
445 }
446 };
447
Janis Danisevskis1af91262020-08-10 14:58:08 -0700448 // km_dev.importWrappedKey does not return a certificate chain.
449 // TODO Do we assume that all wrapped keys are symmetric?
450 // let certificate_chain: Vec<KmCertificate> = Default::default();
451
452 let pw_sid = authenticators
453 .iter()
454 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700455 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700456 _ => None,
457 })
458 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
459 .context("A password authenticator SID must be specified.")?;
460
461 let fp_sid = authenticators
462 .iter()
463 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700464 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700465 _ => None,
466 })
467 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
468 .context("A fingerprint authenticator SID must be specified.")?;
469
470 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
471
472 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800473 let (creation_result, _) = self
474 .upgrade_keyblob_if_required_with(
475 &*km_dev,
476 Some(wrapping_key_id_guard),
477 wrapping_key_blob,
478 &[],
479 |wrapping_blob| {
480 let creation_result = map_km_error(km_dev.importWrappedKey(
481 wrapped_data,
482 wrapping_key_blob,
483 masking_key,
484 &params,
485 pw_sid,
486 fp_sid,
487 ))?;
488 Ok(creation_result)
489 },
490 )
491 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700492
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000493 let user_id = uid_to_android_user(caller_uid);
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800494 self.store_new_key(key, creation_result, user_id)
495 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700496 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800497
498 fn upgrade_keyblob_if_required_with<T, F>(
499 &self,
500 km_dev: &dyn IKeyMintDevice,
501 key_id_guard: Option<KeyIdGuard>,
502 blob: &[u8],
503 params: &[KeyParameter],
504 f: F,
505 ) -> Result<(T, Option<Vec<u8>>)>
506 where
507 F: Fn(&[u8]) -> Result<T, Error>,
508 {
509 match f(blob) {
510 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
511 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
512 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
513 key_id_guard.map_or(Ok(()), |key_id_guard| {
514 DB.with(|db| {
515 db.borrow_mut().insert_blob(
516 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800517 SubComponentType::KEY_BLOB,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800518 &upgraded_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800519 )
520 })
521 .context(concat!(
522 "In upgrade_keyblob_if_required_with: ",
523 "Failed to insert upgraded blob into the database.",
524 ))
525 })?;
526 match f(&upgraded_blob) {
527 Ok(v) => Ok((v, Some(upgraded_blob))),
528 Err(e) => Err(e).context(concat!(
529 "In upgrade_keyblob_if_required_with: ",
530 "Failed to perform operation on second try."
531 )),
532 }
533 }
534 Err(e) => {
535 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
536 }
537 Ok(v) => Ok((v, None)),
538 }
539 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700540}
541
542impl binder::Interface for KeystoreSecurityLevel {}
543
544impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700545 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700546 &self,
547 key: &KeyDescriptor,
548 operation_parameters: &[KeyParameter],
549 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700550 ) -> binder::public_api::Result<CreateOperationResponse> {
551 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700552 }
553 fn generateKey(
554 &self,
555 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700556 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700557 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700558 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700559 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700560 ) -> binder::public_api::Result<KeyMetadata> {
561 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700562 }
563 fn importKey(
564 &self,
565 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700566 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700567 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700568 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700570 ) -> binder::public_api::Result<KeyMetadata> {
571 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700572 }
573 fn importWrappedKey(
574 &self,
575 key: &KeyDescriptor,
576 wrapping_key: &KeyDescriptor,
577 masking_key: Option<&[u8]>,
578 params: &[KeyParameter],
579 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700580 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700581 map_or_log_err(
582 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700583 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700584 )
585 }
586}