blob: 7f41ae849559e3f6511cabe7906d427e916fefe2 [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 Danisevskis5ed8c532021-01-11 14:19:42 -080020 Algorithm::Algorithm, HardwareAuthenticatorType::HardwareAuthenticatorType,
21 IKeyMintDevice::IKeyMintDevice, KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
22 KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel,
23 Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070024};
25use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070026 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
27 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
28 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070029 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080030 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070031};
32
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000033use crate::globals::ENFORCEMENTS;
34use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000035use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
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,
Hasini Gunasinghea020b532021-01-07 21:42:35 +000050 utils::uid_to_android_user,
Janis Danisevskis04b02832020-10-26 09:21:40 -070051};
Janis Danisevskisba998992020-12-29 16:08:40 -080052use anyhow::{Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -070053use binder::{IBinder, Interface, ThreadState};
54
55/// Implementation of the IKeystoreSecurityLevel Interface.
56pub struct KeystoreSecurityLevel {
57 security_level: SecurityLevel,
58 keymint: Asp,
59 operation_db: OperationDb,
60}
61
Janis Danisevskis1af91262020-08-10 14:58:08 -070062// Blob of 32 zeroes used as empty masking key.
63static ZERO_BLOB_32: &[u8] = &[0; 32];
64
65impl KeystoreSecurityLevel {
66 /// Creates a new security level instance wrapped in a
67 /// BnKeystoreSecurityLevel proxy object. It also
68 /// calls `IBinder::set_requesting_sid` on the new interface, because
69 /// we need it for checking keystore permissions.
70 pub fn new_native_binder(
71 security_level: SecurityLevel,
72 ) -> Result<impl IKeystoreSecurityLevel + Send> {
Janis Danisevskis1af91262020-08-10 14:58:08 -070073 let result = BnKeystoreSecurityLevel::new_binder(Self {
74 security_level,
Janis Danisevskisba998992020-12-29 16:08:40 -080075 keymint: crate::globals::get_keymint_device(security_level)
76 .context("In KeystoreSecurityLevel::new_native_binder.")?,
Janis Danisevskis1af91262020-08-10 14:58:08 -070077 operation_db: OperationDb::new(),
78 });
79 result.as_binder().set_requesting_sid(true);
80 Ok(result)
81 }
82
83 fn store_new_key(
84 &self,
85 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -070086 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +000087 user_id: u32,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070088 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -070089 let KeyCreationResult {
90 keyBlob: key_blob,
91 keyCharacteristics: key_characteristics,
92 certificateChain: mut certificate_chain,
93 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -070094
Shawn Willdendbdac602021-01-12 22:35:16 -070095 let (cert, cert_chain): (Option<Vec<u8>>, Option<Vec<u8>>) = (
96 match certificate_chain.len() {
97 0 => None,
98 _ => Some(certificate_chain.remove(0).encodedCertificate),
99 },
100 match certificate_chain.len() {
101 0 => None,
102 _ => Some(
103 certificate_chain
104 .iter()
105 .map(|c| c.encodedCertificate.iter())
106 .flatten()
107 .copied()
108 .collect(),
109 ),
110 },
111 );
112
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000113 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
114
115 key_parameters.push(KsKeyParam::new(
116 KsKeyParamValue::UserID(user_id as i32),
117 SecurityLevel::SOFTWARE,
118 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700119
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800120 let creation_date = DateTime::now().context("Trying to make creation time.")?;
121
Janis Danisevskis1af91262020-08-10 14:58:08 -0700122 let key = match key.domain {
123 Domain::BLOB => {
Shawn Willdendbdac602021-01-12 22:35:16 -0700124 KeyDescriptor { domain: Domain::BLOB, blob: Some(key_blob), ..Default::default() }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700125 }
126 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800127 .with::<_, Result<KeyDescriptor>>(|db| {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800128 let mut metadata = KeyMetaData::new();
129 metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800130
131 let mut db = db.borrow_mut();
132 let key_id = db
133 .store_new_key(
134 key,
135 &key_parameters,
Shawn Willdendbdac602021-01-12 22:35:16 -0700136 &key_blob,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800137 cert.as_deref(),
138 cert_chain.as_deref(),
139 &metadata,
140 )
141 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700142 Ok(KeyDescriptor {
143 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800144 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700145 ..Default::default()
146 })
147 })
148 .context("In store_new_key.")?,
149 };
150
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700151 Ok(KeyMetadata {
152 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700153 keySecurityLevel: self.security_level,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700154 certificate: cert,
155 certificateChain: cert_chain,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700156 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800157 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700158 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700159 }
160
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700161 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700162 &self,
163 key: &KeyDescriptor,
164 operation_parameters: &[KeyParameter],
165 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700166 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700167 let caller_uid = ThreadState::get_calling_uid();
168 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
169 // so that we can use it by reference like the blob provided by the key descriptor.
170 // Otherwise, we would have to clone the blob from the key descriptor.
171 let scoping_blob: Vec<u8>;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000172 let (km_blob, key_id_guard, key_parameters) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700173 Domain::BLOB => {
174 check_key_permission(KeyPerm::use_(), key, &None)
175 .context("In create_operation: checking use permission for Domain::BLOB.")?;
176 (
177 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700178 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700179 None => {
180 return Err(Error::sys()).context(concat!(
181 "In create_operation: Key blob must be specified when",
182 " using Domain::BLOB."
183 ))
184 }
185 },
186 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000187 None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700188 )
189 }
190 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800191 let (key_id_guard, mut key_entry) = DB
192 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700193 db.borrow_mut().load_key_entry(
194 key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800195 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700196 KeyEntryLoadBits::KM,
197 caller_uid,
198 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
199 )
200 })
201 .context("In create_operation: Failed to load key blob.")?;
202 scoping_blob = match key_entry.take_km_blob() {
203 Some(blob) => blob,
204 None => {
205 return Err(Error::sys()).context(concat!(
206 "In create_operation: Successfully loaded key entry,",
207 " but KM blob was missing."
208 ))
209 }
210 };
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000211 (&scoping_blob, Some(key_id_guard), Some(key_entry.into_key_parameters()))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700212 }
213 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700214
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700215 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700216 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700217 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800218 |kp| match kp.value {
219 KeyParameterValue::KeyPurpose(p) => Ok(p),
220 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
221 .context("In create_operation: Malformed KeyParameter."),
222 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700223 )?;
224
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800225 let (immediate_hat, mut auth_info) = ENFORCEMENTS
226 .authorize_create(
227 purpose,
228 key_parameters.as_deref(),
229 operation_parameters,
230 // TODO b/178222844 Replace this with the configuration returned by
231 // KeyMintDevice::getHardwareInfo.
232 // For now we assume that strongbox implementations need secure timestamps.
233 self.security_level == SecurityLevel::STRONGBOX,
234 )
235 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000236
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800237 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000238
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700239 let km_dev: Box<dyn IKeyMintDevice> = self
240 .keymint
241 .get_interface()
242 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700243
Janis Danisevskisaec14592020-11-12 09:41:49 -0800244 let (begin_result, upgraded_blob) = self
245 .upgrade_keyblob_if_required_with(
246 &*km_dev,
247 key_id_guard,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700248 &km_blob,
249 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800250 |blob| loop {
251 match map_km_error(km_dev.begin(
252 purpose,
253 blob,
254 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800255 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800256 )) {
257 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
258 self.operation_db.prune(caller_uid)?;
259 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700260 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800261 v => return v,
262 }
263 },
264 )
265 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700266
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800267 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000268
Janis Danisevskis1af91262020-08-10 14:58:08 -0700269 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000270 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800271 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000272 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700273 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 -0700274 };
275
276 let op_binder: Box<dyn IKeystoreOperation> =
277 KeystoreOperation::new_native_binder(operation)
278 .as_binder()
279 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700280 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700281
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700282 Ok(CreateOperationResponse {
283 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000284 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700285 parameters: match begin_result.params.len() {
286 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700287 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700288 },
289 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700290 }
291
292 fn generate_key(
293 &self,
294 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700295 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700296 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700297 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700298 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700299 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700300 if key.domain != Domain::BLOB && key.alias.is_none() {
301 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
302 .context("In generate_key: Alias must be specified");
303 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000304 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700305
306 let key = match key.domain {
307 Domain::APP => KeyDescriptor {
308 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000309 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700310 alias: key.alias.clone(),
311 blob: None,
312 },
313 _ => key.clone(),
314 };
315
316 // generate_key requires the rebind permission.
317 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
318
319 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
320 map_km_error(km_dev.addRngEntropy(entropy))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700321 let creation_result = map_km_error(km_dev.generateKey(&params))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700322
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000323 let user_id = uid_to_android_user(caller_uid);
324 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700325 }
326
327 fn import_key(
328 &self,
329 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700330 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700331 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700332 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700333 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700334 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700335 if key.domain != Domain::BLOB && key.alias.is_none() {
336 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
337 .context("In import_key: Alias must be specified");
338 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000339 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700340
341 let key = match key.domain {
342 Domain::APP => KeyDescriptor {
343 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000344 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700345 alias: key.alias.clone(),
346 blob: None,
347 },
348 _ => key.clone(),
349 };
350
351 // import_key requires the rebind permission.
352 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
353
Janis Danisevskis1af91262020-08-10 14:58:08 -0700354 let format = params
355 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700356 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700357 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
358 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800359 .and_then(|p| match &p.value {
360 KeyParameterValue::Algorithm(Algorithm::AES)
361 | KeyParameterValue::Algorithm(Algorithm::HMAC)
362 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
363 KeyParameterValue::Algorithm(Algorithm::RSA)
364 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
365 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
366 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700367 })
368 .context("In import_key.")?;
369
370 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700371 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700372
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000373 let user_id = uid_to_android_user(caller_uid);
374 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700375 }
376
377 fn import_wrapped_key(
378 &self,
379 key: &KeyDescriptor,
380 wrapping_key: &KeyDescriptor,
381 masking_key: Option<&[u8]>,
382 params: &[KeyParameter],
383 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700384 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700385 if key.domain != Domain::BLOB && key.alias.is_none() {
386 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
387 .context("In import_wrapped_key: Alias must be specified.");
388 }
389
Janis Danisevskisaec14592020-11-12 09:41:49 -0800390 if wrapping_key.domain == Domain::BLOB {
391 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
392 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
393 );
394 }
395
Janis Danisevskis1af91262020-08-10 14:58:08 -0700396 let wrapped_data = match &key.blob {
397 Some(d) => d,
398 None => {
399 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
400 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
401 )
402 }
403 };
404
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000405 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700406 let key = match key.domain {
407 Domain::APP => KeyDescriptor {
408 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000409 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700410 alias: key.alias.clone(),
411 blob: None,
412 },
413 _ => key.clone(),
414 };
415
416 // import_wrapped_key requires the rebind permission for the new key.
417 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
418
Janis Danisevskisaec14592020-11-12 09:41:49 -0800419 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700420 .with(|db| {
421 db.borrow_mut().load_key_entry(
422 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800423 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700424 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000425 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700426 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
427 )
428 })
429 .context("Failed to load wrapping key.")?;
430 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
431 Some(blob) => blob,
432 None => {
433 return Err(error::Error::sys()).context(concat!(
434 "No km_blob after successfully loading key.",
435 " This should never happen."
436 ))
437 }
438 };
439
Janis Danisevskis1af91262020-08-10 14:58:08 -0700440 // km_dev.importWrappedKey does not return a certificate chain.
441 // TODO Do we assume that all wrapped keys are symmetric?
442 // let certificate_chain: Vec<KmCertificate> = Default::default();
443
444 let pw_sid = authenticators
445 .iter()
446 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700447 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700448 _ => None,
449 })
450 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
451 .context("A password authenticator SID must be specified.")?;
452
453 let fp_sid = authenticators
454 .iter()
455 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700456 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700457 _ => None,
458 })
459 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
460 .context("A fingerprint authenticator SID must be specified.")?;
461
462 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
463
464 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700465 let (creation_result, _) = self.upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800466 &*km_dev,
467 Some(wrapping_key_id_guard),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700468 wrapping_key_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800469 &[],
470 |wrapping_blob| {
Shawn Willdendbdac602021-01-12 22:35:16 -0700471 let creation_result = map_km_error(km_dev.importWrappedKey(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800472 wrapped_data,
473 wrapping_key_blob,
474 masking_key,
475 &params,
476 pw_sid,
477 fp_sid,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800478 ))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700479 Ok(creation_result)
Janis Danisevskisaec14592020-11-12 09:41:49 -0800480 },
481 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700482
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000483 let user_id = uid_to_android_user(caller_uid);
484 self.store_new_key(key, creation_result, user_id).context("In import_wrapped_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700485 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800486
487 fn upgrade_keyblob_if_required_with<T, F>(
488 &self,
489 km_dev: &dyn IKeyMintDevice,
490 key_id_guard: Option<KeyIdGuard>,
491 blob: &[u8],
492 params: &[KeyParameter],
493 f: F,
494 ) -> Result<(T, Option<Vec<u8>>)>
495 where
496 F: Fn(&[u8]) -> Result<T, Error>,
497 {
498 match f(blob) {
499 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
500 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
501 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
502 key_id_guard.map_or(Ok(()), |key_id_guard| {
503 DB.with(|db| {
504 db.borrow_mut().insert_blob(
505 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800506 SubComponentType::KEY_BLOB,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800507 &upgraded_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800508 )
509 })
510 .context(concat!(
511 "In upgrade_keyblob_if_required_with: ",
512 "Failed to insert upgraded blob into the database.",
513 ))
514 })?;
515 match f(&upgraded_blob) {
516 Ok(v) => Ok((v, Some(upgraded_blob))),
517 Err(e) => Err(e).context(concat!(
518 "In upgrade_keyblob_if_required_with: ",
519 "Failed to perform operation on second try."
520 )),
521 }
522 }
523 Err(e) => {
524 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
525 }
526 Ok(v) => Ok((v, None)),
527 }
528 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700529}
530
531impl binder::Interface for KeystoreSecurityLevel {}
532
533impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700534 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700535 &self,
536 key: &KeyDescriptor,
537 operation_parameters: &[KeyParameter],
538 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700539 ) -> binder::public_api::Result<CreateOperationResponse> {
540 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700541 }
542 fn generateKey(
543 &self,
544 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700545 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700546 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700547 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700548 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700549 ) -> binder::public_api::Result<KeyMetadata> {
550 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700551 }
552 fn importKey(
553 &self,
554 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700555 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700556 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700557 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700558 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700559 ) -> binder::public_api::Result<KeyMetadata> {
560 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700561 }
562 fn importWrappedKey(
563 &self,
564 key: &KeyDescriptor,
565 wrapping_key: &KeyDescriptor,
566 masking_key: Option<&[u8]>,
567 params: &[KeyParameter],
568 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700569 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700570 map_or_log_err(
571 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700572 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700573 )
574 }
575}