blob: 994b2c85e2a7537425a85e386dd1620c21e6515c [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;
Qi Wub9433b52020-12-01 14:52:46 +080037use crate::utils::{check_key_permission, uid_to_android_user, 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,
51};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080052use anyhow::{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();
Janis Danisevskis4507f3b2021-01-13 16:34:39 -0800132 let (need_gc, key_id) = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800133 .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 Danisevskis4507f3b2021-01-13 16:34:39 -0800142 if need_gc {
143 Gc::notify_gc();
144 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700145 Ok(KeyDescriptor {
146 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800147 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700148 ..Default::default()
149 })
150 })
151 .context("In store_new_key.")?,
152 };
153
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700154 Ok(KeyMetadata {
155 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700156 keySecurityLevel: self.security_level,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700157 certificate: cert,
158 certificateChain: cert_chain,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700159 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800160 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700161 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700162 }
163
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700164 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700165 &self,
166 key: &KeyDescriptor,
167 operation_parameters: &[KeyParameter],
168 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700169 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700170 let caller_uid = ThreadState::get_calling_uid();
171 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
172 // so that we can use it by reference like the blob provided by the key descriptor.
173 // Otherwise, we would have to clone the blob from the key descriptor.
174 let scoping_blob: Vec<u8>;
Qi Wub9433b52020-12-01 14:52:46 +0800175 let (km_blob, key_properties, key_id_guard) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700176 Domain::BLOB => {
177 check_key_permission(KeyPerm::use_(), key, &None)
178 .context("In create_operation: checking use permission for Domain::BLOB.")?;
179 (
180 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700181 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700182 None => {
183 return Err(Error::sys()).context(concat!(
184 "In create_operation: Key blob must be specified when",
185 " using Domain::BLOB."
186 ))
187 }
188 },
189 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000190 None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700191 )
192 }
193 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800194 let (key_id_guard, mut key_entry) = DB
195 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700196 db.borrow_mut().load_key_entry(
197 key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800198 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700199 KeyEntryLoadBits::KM,
200 caller_uid,
201 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
202 )
203 })
204 .context("In create_operation: Failed to load key blob.")?;
205 scoping_blob = match key_entry.take_km_blob() {
206 Some(blob) => blob,
207 None => {
208 return Err(Error::sys()).context(concat!(
209 "In create_operation: Successfully loaded key entry,",
210 " but KM blob was missing."
211 ))
212 }
213 };
Qi Wub9433b52020-12-01 14:52:46 +0800214 (
215 &scoping_blob,
216 Some((key_id_guard.id(), key_entry.into_key_parameters())),
217 Some(key_id_guard),
218 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700219 }
220 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700221
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700222 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700223 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700224 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800225 |kp| match kp.value {
226 KeyParameterValue::KeyPurpose(p) => Ok(p),
227 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
228 .context("In create_operation: Malformed KeyParameter."),
229 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700230 )?;
231
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800232 let (immediate_hat, mut auth_info) = ENFORCEMENTS
233 .authorize_create(
234 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800235 key_properties.as_ref(),
236 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800237 // TODO b/178222844 Replace this with the configuration returned by
238 // KeyMintDevice::getHardwareInfo.
239 // For now we assume that strongbox implementations need secure timestamps.
240 self.security_level == SecurityLevel::STRONGBOX,
241 )
242 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000243
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800244 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000245
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700246 let km_dev: Box<dyn IKeyMintDevice> = self
247 .keymint
248 .get_interface()
249 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700250
Janis Danisevskisaec14592020-11-12 09:41:49 -0800251 let (begin_result, upgraded_blob) = self
252 .upgrade_keyblob_if_required_with(
253 &*km_dev,
254 key_id_guard,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700255 &km_blob,
256 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800257 |blob| loop {
258 match map_km_error(km_dev.begin(
259 purpose,
260 blob,
261 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800262 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800263 )) {
264 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
265 self.operation_db.prune(caller_uid)?;
266 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700267 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800268 v => return v,
269 }
270 },
271 )
272 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700273
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800274 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000275
Janis Danisevskis1af91262020-08-10 14:58:08 -0700276 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000277 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800278 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000279 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700280 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 -0700281 };
282
283 let op_binder: Box<dyn IKeystoreOperation> =
284 KeystoreOperation::new_native_binder(operation)
285 .as_binder()
286 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700287 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700288
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700289 Ok(CreateOperationResponse {
290 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000291 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700292 parameters: match begin_result.params.len() {
293 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700294 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700295 },
296 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700297 }
298
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800299 fn add_attestation_parameters(uid: u32, params: &[KeyParameter]) -> Result<Vec<KeyParameter>> {
300 let mut result = params.to_vec();
301 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
302 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
303 anyhow!(format!("In add_attestation_parameters: get_aaid returned status {}.", e))
304 })?;
305 result.push(KeyParameter {
306 tag: Tag::ATTESTATION_APPLICATION_ID,
307 value: KeyParameterValue::Blob(aaid),
308 });
309 }
310 Ok(result)
311 }
312
Janis Danisevskis1af91262020-08-10 14:58:08 -0700313 fn generate_key(
314 &self,
315 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700316 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700317 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700318 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700319 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700320 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700321 if key.domain != Domain::BLOB && key.alias.is_none() {
322 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
323 .context("In generate_key: Alias must be specified");
324 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000325 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700326
327 let key = match key.domain {
328 Domain::APP => KeyDescriptor {
329 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000330 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700331 alias: key.alias.clone(),
332 blob: None,
333 },
334 _ => key.clone(),
335 };
336
337 // generate_key requires the rebind permission.
338 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
339
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800340 let params = Self::add_attestation_parameters(caller_uid, params)
341 .context("In generate_key: Trying to get aaid.")?;
342
Janis Danisevskis1af91262020-08-10 14:58:08 -0700343 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800344 map_km_error(km_dev.addRngEntropy(entropy))
345 .context("In generate_key: Trying to add entropy.")?;
346 let creation_result = map_km_error(km_dev.generateKey(&params))
347 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700348
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000349 let user_id = uid_to_android_user(caller_uid);
350 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700351 }
352
353 fn import_key(
354 &self,
355 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700356 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700357 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700358 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700359 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700360 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361 if key.domain != Domain::BLOB && key.alias.is_none() {
362 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
363 .context("In import_key: Alias must be specified");
364 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000365 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700366
367 let key = match key.domain {
368 Domain::APP => KeyDescriptor {
369 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000370 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700371 alias: key.alias.clone(),
372 blob: None,
373 },
374 _ => key.clone(),
375 };
376
377 // import_key requires the rebind permission.
378 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
379
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800380 let params = Self::add_attestation_parameters(caller_uid, params)
381 .context("In import_key: Trying to get aaid.")?;
382
Janis Danisevskis1af91262020-08-10 14:58:08 -0700383 let format = params
384 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700385 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700386 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
387 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800388 .and_then(|p| match &p.value {
389 KeyParameterValue::Algorithm(Algorithm::AES)
390 | KeyParameterValue::Algorithm(Algorithm::HMAC)
391 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
392 KeyParameterValue::Algorithm(Algorithm::RSA)
393 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
394 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
395 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700396 })
397 .context("In import_key.")?;
398
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800399 let km_dev: Box<dyn IKeyMintDevice> =
400 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
401 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))
402 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700403
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000404 let user_id = uid_to_android_user(caller_uid);
405 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700406 }
407
408 fn import_wrapped_key(
409 &self,
410 key: &KeyDescriptor,
411 wrapping_key: &KeyDescriptor,
412 masking_key: Option<&[u8]>,
413 params: &[KeyParameter],
414 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700415 ) -> Result<KeyMetadata> {
Janis Danisevskis5d27fbb2021-01-21 16:36:18 -0800416 if !(key.domain == Domain::BLOB && key.alias.is_some()) {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700417 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
418 .context("In import_wrapped_key: Alias must be specified.");
419 }
420
Janis Danisevskisaec14592020-11-12 09:41:49 -0800421 if wrapping_key.domain == Domain::BLOB {
422 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
423 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
424 );
425 }
426
Janis Danisevskis1af91262020-08-10 14:58:08 -0700427 let wrapped_data = match &key.blob {
428 Some(d) => d,
429 None => {
430 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
431 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
432 )
433 }
434 };
435
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000436 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700437 let key = match key.domain {
438 Domain::APP => KeyDescriptor {
439 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000440 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700441 alias: key.alias.clone(),
442 blob: None,
443 },
444 _ => key.clone(),
445 };
446
447 // import_wrapped_key requires the rebind permission for the new key.
448 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
449
Janis Danisevskisaec14592020-11-12 09:41:49 -0800450 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700451 .with(|db| {
452 db.borrow_mut().load_key_entry(
453 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800454 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700455 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000456 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700457 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
458 )
459 })
460 .context("Failed to load wrapping key.")?;
461 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
462 Some(blob) => blob,
463 None => {
464 return Err(error::Error::sys()).context(concat!(
465 "No km_blob after successfully loading key.",
466 " This should never happen."
467 ))
468 }
469 };
470
Janis Danisevskis1af91262020-08-10 14:58:08 -0700471 // km_dev.importWrappedKey does not return a certificate chain.
472 // TODO Do we assume that all wrapped keys are symmetric?
473 // let certificate_chain: Vec<KmCertificate> = Default::default();
474
475 let pw_sid = authenticators
476 .iter()
477 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700478 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700479 _ => None,
480 })
481 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
482 .context("A password authenticator SID must be specified.")?;
483
484 let fp_sid = authenticators
485 .iter()
486 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700487 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700488 _ => None,
489 })
490 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
491 .context("A fingerprint authenticator SID must be specified.")?;
492
493 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
494
495 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800496 let (creation_result, _) = self
497 .upgrade_keyblob_if_required_with(
498 &*km_dev,
499 Some(wrapping_key_id_guard),
500 wrapping_key_blob,
501 &[],
502 |wrapping_blob| {
503 let creation_result = map_km_error(km_dev.importWrappedKey(
504 wrapped_data,
505 wrapping_key_blob,
506 masking_key,
507 &params,
508 pw_sid,
509 fp_sid,
510 ))?;
511 Ok(creation_result)
512 },
513 )
514 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700515
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000516 let user_id = uid_to_android_user(caller_uid);
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800517 self.store_new_key(key, creation_result, user_id)
518 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800520
521 fn upgrade_keyblob_if_required_with<T, F>(
522 &self,
523 km_dev: &dyn IKeyMintDevice,
524 key_id_guard: Option<KeyIdGuard>,
525 blob: &[u8],
526 params: &[KeyParameter],
527 f: F,
528 ) -> Result<(T, Option<Vec<u8>>)>
529 where
530 F: Fn(&[u8]) -> Result<T, Error>,
531 {
532 match f(blob) {
533 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
534 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
535 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
536 key_id_guard.map_or(Ok(()), |key_id_guard| {
537 DB.with(|db| {
Janis Danisevskis377d1002021-01-27 19:07:48 -0800538 db.borrow_mut().set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800539 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800540 SubComponentType::KEY_BLOB,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800541 Some(&upgraded_blob),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800542 )
543 })
544 .context(concat!(
545 "In upgrade_keyblob_if_required_with: ",
546 "Failed to insert upgraded blob into the database.",
547 ))
548 })?;
549 match f(&upgraded_blob) {
550 Ok(v) => Ok((v, Some(upgraded_blob))),
551 Err(e) => Err(e).context(concat!(
552 "In upgrade_keyblob_if_required_with: ",
553 "Failed to perform operation on second try."
554 )),
555 }
556 }
557 Err(e) => {
558 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
559 }
560 Ok(v) => Ok((v, None)),
561 }
562 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700563}
564
565impl binder::Interface for KeystoreSecurityLevel {}
566
567impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700568 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569 &self,
570 key: &KeyDescriptor,
571 operation_parameters: &[KeyParameter],
572 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700573 ) -> binder::public_api::Result<CreateOperationResponse> {
574 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700575 }
576 fn generateKey(
577 &self,
578 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700579 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700580 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700581 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700582 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700583 ) -> binder::public_api::Result<KeyMetadata> {
584 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700585 }
586 fn importKey(
587 &self,
588 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700589 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700590 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700591 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700592 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700593 ) -> binder::public_api::Result<KeyMetadata> {
594 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700595 }
596 fn importWrappedKey(
597 &self,
598 key: &KeyDescriptor,
599 wrapping_key: &KeyDescriptor,
600 masking_key: Option<&[u8]>,
601 params: &[KeyParameter],
602 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700603 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700604 map_or_log_err(
605 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700606 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700607 )
608 }
609}