blob: d8787bdded7823de919159ecd5623dbb732f4e54 [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()?;
324 map_km_error(km_dev.addRngEntropy(entropy))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700325 let creation_result = map_km_error(km_dev.generateKey(&params))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700326
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000327 let user_id = uid_to_android_user(caller_uid);
328 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700329 }
330
331 fn import_key(
332 &self,
333 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700334 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700335 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700336 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700337 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700338 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700339 if key.domain != Domain::BLOB && key.alias.is_none() {
340 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
341 .context("In import_key: Alias must be specified");
342 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000343 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700344
345 let key = match key.domain {
346 Domain::APP => KeyDescriptor {
347 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000348 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700349 alias: key.alias.clone(),
350 blob: None,
351 },
352 _ => key.clone(),
353 };
354
355 // import_key requires the rebind permission.
356 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
357
Janis Danisevskis1af91262020-08-10 14:58:08 -0700358 let format = params
359 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700360 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
362 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800363 .and_then(|p| match &p.value {
364 KeyParameterValue::Algorithm(Algorithm::AES)
365 | KeyParameterValue::Algorithm(Algorithm::HMAC)
366 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
367 KeyParameterValue::Algorithm(Algorithm::RSA)
368 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
369 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
370 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700371 })
372 .context("In import_key.")?;
373
374 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700375 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700376
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000377 let user_id = uid_to_android_user(caller_uid);
378 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700379 }
380
381 fn import_wrapped_key(
382 &self,
383 key: &KeyDescriptor,
384 wrapping_key: &KeyDescriptor,
385 masking_key: Option<&[u8]>,
386 params: &[KeyParameter],
387 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700388 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700389 if key.domain != Domain::BLOB && key.alias.is_none() {
390 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
391 .context("In import_wrapped_key: Alias must be specified.");
392 }
393
Janis Danisevskisaec14592020-11-12 09:41:49 -0800394 if wrapping_key.domain == Domain::BLOB {
395 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
396 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
397 );
398 }
399
Janis Danisevskis1af91262020-08-10 14:58:08 -0700400 let wrapped_data = match &key.blob {
401 Some(d) => d,
402 None => {
403 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
404 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
405 )
406 }
407 };
408
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000409 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700410 let key = match key.domain {
411 Domain::APP => KeyDescriptor {
412 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000413 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700414 alias: key.alias.clone(),
415 blob: None,
416 },
417 _ => key.clone(),
418 };
419
420 // import_wrapped_key requires the rebind permission for the new key.
421 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
422
Janis Danisevskisaec14592020-11-12 09:41:49 -0800423 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700424 .with(|db| {
425 db.borrow_mut().load_key_entry(
426 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800427 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700428 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000429 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700430 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
431 )
432 })
433 .context("Failed to load wrapping key.")?;
434 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
435 Some(blob) => blob,
436 None => {
437 return Err(error::Error::sys()).context(concat!(
438 "No km_blob after successfully loading key.",
439 " This should never happen."
440 ))
441 }
442 };
443
Janis Danisevskis1af91262020-08-10 14:58:08 -0700444 // km_dev.importWrappedKey does not return a certificate chain.
445 // TODO Do we assume that all wrapped keys are symmetric?
446 // let certificate_chain: Vec<KmCertificate> = Default::default();
447
448 let pw_sid = authenticators
449 .iter()
450 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700451 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700452 _ => None,
453 })
454 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
455 .context("A password authenticator SID must be specified.")?;
456
457 let fp_sid = authenticators
458 .iter()
459 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700460 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700461 _ => None,
462 })
463 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
464 .context("A fingerprint authenticator SID must be specified.")?;
465
466 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
467
468 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700469 let (creation_result, _) = self.upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800470 &*km_dev,
471 Some(wrapping_key_id_guard),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700472 wrapping_key_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800473 &[],
474 |wrapping_blob| {
Shawn Willdendbdac602021-01-12 22:35:16 -0700475 let creation_result = map_km_error(km_dev.importWrappedKey(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800476 wrapped_data,
477 wrapping_key_blob,
478 masking_key,
479 &params,
480 pw_sid,
481 fp_sid,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800482 ))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700483 Ok(creation_result)
Janis Danisevskisaec14592020-11-12 09:41:49 -0800484 },
485 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700486
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000487 let user_id = uid_to_android_user(caller_uid);
488 self.store_new_key(key, creation_result, user_id).context("In import_wrapped_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700489 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800490
491 fn upgrade_keyblob_if_required_with<T, F>(
492 &self,
493 km_dev: &dyn IKeyMintDevice,
494 key_id_guard: Option<KeyIdGuard>,
495 blob: &[u8],
496 params: &[KeyParameter],
497 f: F,
498 ) -> Result<(T, Option<Vec<u8>>)>
499 where
500 F: Fn(&[u8]) -> Result<T, Error>,
501 {
502 match f(blob) {
503 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
504 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
505 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
506 key_id_guard.map_or(Ok(()), |key_id_guard| {
507 DB.with(|db| {
508 db.borrow_mut().insert_blob(
509 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800510 SubComponentType::KEY_BLOB,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800511 &upgraded_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800512 )
513 })
514 .context(concat!(
515 "In upgrade_keyblob_if_required_with: ",
516 "Failed to insert upgraded blob into the database.",
517 ))
518 })?;
519 match f(&upgraded_blob) {
520 Ok(v) => Ok((v, Some(upgraded_blob))),
521 Err(e) => Err(e).context(concat!(
522 "In upgrade_keyblob_if_required_with: ",
523 "Failed to perform operation on second try."
524 )),
525 }
526 }
527 Err(e) => {
528 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
529 }
530 Ok(v) => Ok((v, None)),
531 }
532 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700533}
534
535impl binder::Interface for KeystoreSecurityLevel {}
536
537impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700538 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700539 &self,
540 key: &KeyDescriptor,
541 operation_parameters: &[KeyParameter],
542 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700543 ) -> binder::public_api::Result<CreateOperationResponse> {
544 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700545 }
546 fn generateKey(
547 &self,
548 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700549 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700550 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700551 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700552 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700553 ) -> binder::public_api::Result<KeyMetadata> {
554 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700555 }
556 fn importKey(
557 &self,
558 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700559 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700560 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700561 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700562 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700563 ) -> binder::public_api::Result<KeyMetadata> {
564 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700565 }
566 fn importWrappedKey(
567 &self,
568 key: &KeyDescriptor,
569 wrapping_key: &KeyDescriptor,
570 masking_key: Option<&[u8]>,
571 params: &[KeyParameter],
572 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700573 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700574 map_or_log_err(
575 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700576 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700577 )
578 }
579}