blob: 943f69f9c90b53f7a0846c970ff134060aee207d [file] [log] [blame]
Janis Danisevskis1af91262020-08-10 14:58:08 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![allow(unused_variables)]
16
17//! This crate implements the IKeystoreSecurityLevel interface.
18
Shawn Willden708744a2020-12-11 13:05:27 +000019use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000020 Algorithm::Algorithm, HardwareAuthToken::HardwareAuthToken,
21 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
22 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat, KeyParameter::KeyParameter,
23 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070024};
25use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070026 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
27 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
28 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070029 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000030 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, OperationChallenge::OperationChallenge,
Janis Danisevskis1af91262020-08-10 14:58:08 -070031};
32
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000033use crate::auth_token_handler::AuthTokenHandler;
34use crate::globals::ENFORCEMENTS;
35use crate::key_parameter::KeyParameter as KsKeyParam;
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();
133 let key_id = db
134 .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 Danisevskis1af91262020-08-10 14:58:08 -0700143 Ok(KeyDescriptor {
144 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800145 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700146 ..Default::default()
147 })
148 })
149 .context("In store_new_key.")?,
150 };
151
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700152 Ok(KeyMetadata {
153 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700154 keySecurityLevel: self.security_level,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700155 certificate: cert,
156 certificateChain: cert_chain,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700157 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800158 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700159 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700160 }
161
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700162 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700163 &self,
164 key: &KeyDescriptor,
165 operation_parameters: &[KeyParameter],
166 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700167 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700168 let caller_uid = ThreadState::get_calling_uid();
169 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
170 // so that we can use it by reference like the blob provided by the key descriptor.
171 // Otherwise, we would have to clone the blob from the key descriptor.
172 let scoping_blob: Vec<u8>;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000173 let (km_blob, key_id_guard, key_parameters) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700174 Domain::BLOB => {
175 check_key_permission(KeyPerm::use_(), key, &None)
176 .context("In create_operation: checking use permission for Domain::BLOB.")?;
177 (
178 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700179 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700180 None => {
181 return Err(Error::sys()).context(concat!(
182 "In create_operation: Key blob must be specified when",
183 " using Domain::BLOB."
184 ))
185 }
186 },
187 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000188 None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700189 )
190 }
191 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800192 let (key_id_guard, mut key_entry) = DB
193 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700194 db.borrow_mut().load_key_entry(
195 key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800196 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700197 KeyEntryLoadBits::KM,
198 caller_uid,
199 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
200 )
201 })
202 .context("In create_operation: Failed to load key blob.")?;
203 scoping_blob = match key_entry.take_km_blob() {
204 Some(blob) => blob,
205 None => {
206 return Err(Error::sys()).context(concat!(
207 "In create_operation: Successfully loaded key entry,",
208 " but KM blob was missing."
209 ))
210 }
211 };
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000212 (&scoping_blob, Some(key_id_guard), Some(key_entry.into_key_parameters()))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700213 }
214 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700215
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700216 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700217 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700218 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800219 |kp| match kp.value {
220 KeyParameterValue::KeyPurpose(p) => Ok(p),
221 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
222 .context("In create_operation: Malformed KeyParameter."),
223 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700224 )?;
225
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000226 let mut auth_token_for_km: &HardwareAuthToken = &Default::default();
227 let mut auth_token_handler = AuthTokenHandler::NoAuthRequired;
228
229 // keystore performs authorizations only if the key parameters are loaded above
230 if let Some(ref key_params) = key_parameters {
231 // Note: although currently only one operation parameter is checked in authorizing the
232 // operation, the whole operation_parameter vector is converted into the internal
233 // representation of key parameter because we might need to sanitize operation
234 // parameters (b/175792701)
235 let mut op_params: Vec<KsKeyParam> = Vec::new();
236 for op_param in operation_parameters.iter() {
237 op_params.push(KsKeyParam::new(op_param.into(), self.security_level));
238 }
239 // authorize the operation, and receive an AuthTokenHandler, if authorized, else
240 // propagate the error
241 auth_token_handler = ENFORCEMENTS
242 .authorize_create(
243 purpose,
244 key_params.as_slice(),
245 op_params.as_slice(),
246 self.security_level,
247 )
248 .context("In create_operation.")?;
249 // if an auth token was found, pass it to keymint
250 if let Some(auth_token) = auth_token_handler.get_auth_token() {
251 auth_token_for_km = auth_token;
252 }
253 }
254
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700255 let km_dev: Box<dyn IKeyMintDevice> = self
256 .keymint
257 .get_interface()
258 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700259
Janis Danisevskisaec14592020-11-12 09:41:49 -0800260 let (begin_result, upgraded_blob) = self
261 .upgrade_keyblob_if_required_with(
262 &*km_dev,
263 key_id_guard,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700264 &km_blob,
265 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800266 |blob| loop {
267 match map_km_error(km_dev.begin(
268 purpose,
269 blob,
270 &operation_parameters,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000271 auth_token_for_km,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800272 )) {
273 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
274 self.operation_db.prune(caller_uid)?;
275 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700276 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800277 v => return v,
278 }
279 },
280 )
281 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700282
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000283 let mut operation_challenge: Option<OperationChallenge> = None;
284
285 // take actions based on the authorization decision (if any) received via auth token handler
286 match auth_token_handler {
287 AuthTokenHandler::OpAuthRequired => {
288 operation_challenge =
289 Some(OperationChallenge { challenge: begin_result.challenge });
290 ENFORCEMENTS.insert_to_op_auth_map(begin_result.challenge);
291 }
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800292 AuthTokenHandler::TimestampRequired(auth_token) => {
293 //request a timestamp token, given the auth token and the challenge
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000294 auth_token_handler = ENFORCEMENTS
Janis Danisevskisc3a496b2021-01-05 10:37:22 -0800295 .request_timestamp_token(
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000296 auth_token,
297 OperationChallenge { challenge: begin_result.challenge },
298 )
299 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000300 }
301 _ => {}
302 }
303
Janis Danisevskis1af91262020-08-10 14:58:08 -0700304 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000305 Some(km_op) => {
306 let mut op_challenge_copy: Option<OperationChallenge> = None;
307 if let Some(ref op_challenge) = operation_challenge {
308 op_challenge_copy = Some(OperationChallenge{challenge: op_challenge.challenge});
309 }
310 self.operation_db.create_operation(km_op, caller_uid,
311 auth_token_handler, key_parameters, op_challenge_copy)
312 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700313 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 -0700314 };
315
316 let op_binder: Box<dyn IKeystoreOperation> =
317 KeystoreOperation::new_native_binder(operation)
318 .as_binder()
319 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700320 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700321
322 // TODO we need to the enforcement module to determine if we need to return the challenge.
323 // We return None for now because we don't support auth bound keys yet.
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700324 Ok(CreateOperationResponse {
325 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000326 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700327 parameters: match begin_result.params.len() {
328 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700329 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700330 },
331 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700332 }
333
334 fn generate_key(
335 &self,
336 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700337 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700338 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700339 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700340 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700341 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700342 if key.domain != Domain::BLOB && key.alias.is_none() {
343 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
344 .context("In generate_key: Alias must be specified");
345 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000346 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700347
348 let key = match key.domain {
349 Domain::APP => KeyDescriptor {
350 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000351 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700352 alias: key.alias.clone(),
353 blob: None,
354 },
355 _ => key.clone(),
356 };
357
358 // generate_key requires the rebind permission.
359 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
360
361 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
362 map_km_error(km_dev.addRngEntropy(entropy))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700363 let creation_result = map_km_error(km_dev.generateKey(&params))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700364
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000365 let user_id = uid_to_android_user(caller_uid);
366 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700367 }
368
369 fn import_key(
370 &self,
371 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700372 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700373 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700374 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700375 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700376 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700377 if key.domain != Domain::BLOB && key.alias.is_none() {
378 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
379 .context("In import_key: Alias must be specified");
380 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000381 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700382
383 let key = match key.domain {
384 Domain::APP => KeyDescriptor {
385 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000386 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700387 alias: key.alias.clone(),
388 blob: None,
389 },
390 _ => key.clone(),
391 };
392
393 // import_key requires the rebind permission.
394 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
395
Janis Danisevskis1af91262020-08-10 14:58:08 -0700396 let format = params
397 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700398 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700399 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
400 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800401 .and_then(|p| match &p.value {
402 KeyParameterValue::Algorithm(Algorithm::AES)
403 | KeyParameterValue::Algorithm(Algorithm::HMAC)
404 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
405 KeyParameterValue::Algorithm(Algorithm::RSA)
406 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
407 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
408 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700409 })
410 .context("In import_key.")?;
411
412 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700413 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700414
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000415 let user_id = uid_to_android_user(caller_uid);
416 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700417 }
418
419 fn import_wrapped_key(
420 &self,
421 key: &KeyDescriptor,
422 wrapping_key: &KeyDescriptor,
423 masking_key: Option<&[u8]>,
424 params: &[KeyParameter],
425 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700426 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700427 if key.domain != Domain::BLOB && key.alias.is_none() {
428 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
429 .context("In import_wrapped_key: Alias must be specified.");
430 }
431
Janis Danisevskisaec14592020-11-12 09:41:49 -0800432 if wrapping_key.domain == Domain::BLOB {
433 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
434 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
435 );
436 }
437
Janis Danisevskis1af91262020-08-10 14:58:08 -0700438 let wrapped_data = match &key.blob {
439 Some(d) => d,
440 None => {
441 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
442 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
443 )
444 }
445 };
446
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000447 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700448 let key = match key.domain {
449 Domain::APP => KeyDescriptor {
450 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000451 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700452 alias: key.alias.clone(),
453 blob: None,
454 },
455 _ => key.clone(),
456 };
457
458 // import_wrapped_key requires the rebind permission for the new key.
459 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
460
Janis Danisevskisaec14592020-11-12 09:41:49 -0800461 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700462 .with(|db| {
463 db.borrow_mut().load_key_entry(
464 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800465 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700466 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000467 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700468 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
469 )
470 })
471 .context("Failed to load wrapping key.")?;
472 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
473 Some(blob) => blob,
474 None => {
475 return Err(error::Error::sys()).context(concat!(
476 "No km_blob after successfully loading key.",
477 " This should never happen."
478 ))
479 }
480 };
481
Janis Danisevskis1af91262020-08-10 14:58:08 -0700482 // km_dev.importWrappedKey does not return a certificate chain.
483 // TODO Do we assume that all wrapped keys are symmetric?
484 // let certificate_chain: Vec<KmCertificate> = Default::default();
485
486 let pw_sid = authenticators
487 .iter()
488 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700489 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700490 _ => None,
491 })
492 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
493 .context("A password authenticator SID must be specified.")?;
494
495 let fp_sid = authenticators
496 .iter()
497 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700498 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700499 _ => None,
500 })
501 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
502 .context("A fingerprint authenticator SID must be specified.")?;
503
504 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
505
506 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700507 let (creation_result, _) = self.upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800508 &*km_dev,
509 Some(wrapping_key_id_guard),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700510 wrapping_key_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800511 &[],
512 |wrapping_blob| {
Shawn Willdendbdac602021-01-12 22:35:16 -0700513 let creation_result = map_km_error(km_dev.importWrappedKey(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800514 wrapped_data,
515 wrapping_key_blob,
516 masking_key,
517 &params,
518 pw_sid,
519 fp_sid,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800520 ))?;
Shawn Willdendbdac602021-01-12 22:35:16 -0700521 Ok(creation_result)
Janis Danisevskisaec14592020-11-12 09:41:49 -0800522 },
523 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700524
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000525 let user_id = uid_to_android_user(caller_uid);
526 self.store_new_key(key, creation_result, user_id).context("In import_wrapped_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800528
529 fn upgrade_keyblob_if_required_with<T, F>(
530 &self,
531 km_dev: &dyn IKeyMintDevice,
532 key_id_guard: Option<KeyIdGuard>,
533 blob: &[u8],
534 params: &[KeyParameter],
535 f: F,
536 ) -> Result<(T, Option<Vec<u8>>)>
537 where
538 F: Fn(&[u8]) -> Result<T, Error>,
539 {
540 match f(blob) {
541 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
542 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
543 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
544 key_id_guard.map_or(Ok(()), |key_id_guard| {
545 DB.with(|db| {
546 db.borrow_mut().insert_blob(
547 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800548 SubComponentType::KEY_BLOB,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800549 &upgraded_blob,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800550 )
551 })
552 .context(concat!(
553 "In upgrade_keyblob_if_required_with: ",
554 "Failed to insert upgraded blob into the database.",
555 ))
556 })?;
557 match f(&upgraded_blob) {
558 Ok(v) => Ok((v, Some(upgraded_blob))),
559 Err(e) => Err(e).context(concat!(
560 "In upgrade_keyblob_if_required_with: ",
561 "Failed to perform operation on second try."
562 )),
563 }
564 }
565 Err(e) => {
566 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
567 }
568 Ok(v) => Ok((v, None)),
569 }
570 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700571}
572
573impl binder::Interface for KeystoreSecurityLevel {}
574
575impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700576 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700577 &self,
578 key: &KeyDescriptor,
579 operation_parameters: &[KeyParameter],
580 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700581 ) -> binder::public_api::Result<CreateOperationResponse> {
582 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700583 }
584 fn generateKey(
585 &self,
586 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700587 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700588 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700589 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700590 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700591 ) -> binder::public_api::Result<KeyMetadata> {
592 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700593 }
594 fn importKey(
595 &self,
596 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700597 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700598 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700599 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700600 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700601 ) -> binder::public_api::Result<KeyMetadata> {
602 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700603 }
604 fn importWrappedKey(
605 &self,
606 key: &KeyDescriptor,
607 wrapping_key: &KeyDescriptor,
608 masking_key: Option<&[u8]>,
609 params: &[KeyParameter],
610 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700611 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700612 map_or_log_err(
613 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700614 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700615 )
616 }
617}