blob: cc1da981eca5c47db86527bac4efa4bdc0f40578 [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
Max Bires8e93d2b2021-01-14 13:17:59 -080019use crate::{database::Uuid, gc::Gc, globals::get_keymint_device};
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,
Max Bires8e93d2b2021-01-14 13:17:59 -080023 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
24 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, 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};
Max Bires8e93d2b2021-01-14 13:17:59 -080038use crate::{
39 database::{CertificateInfo, KeyIdGuard},
40 globals::DB,
41};
Janis Danisevskis1af91262020-08-10 14:58:08 -070042use crate::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080043 database::{DateTime, KeyMetaData, KeyMetaEntry, KeyType},
44 permission::KeyPerm,
45};
46use crate::{
Janis Danisevskis1af91262020-08-10 14:58:08 -070047 database::{KeyEntry, KeyEntryLoadBits, SubComponentType},
48 operation::KeystoreOperation,
49 operation::OperationDb,
50};
Janis Danisevskis04b02832020-10-26 09:21:40 -070051use crate::{
52 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
53 utils::key_characteristics_to_internal,
54};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080055use anyhow::{anyhow, Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -070056use binder::{IBinder, Interface, ThreadState};
57
58/// Implementation of the IKeystoreSecurityLevel Interface.
59pub struct KeystoreSecurityLevel {
60 security_level: SecurityLevel,
61 keymint: Asp,
Max Bires8e93d2b2021-01-14 13:17:59 -080062 #[allow(dead_code)]
63 hw_info: KeyMintHardwareInfo,
64 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070065 operation_db: OperationDb,
66}
67
Janis Danisevskis1af91262020-08-10 14:58:08 -070068// Blob of 32 zeroes used as empty masking key.
69static ZERO_BLOB_32: &[u8] = &[0; 32];
70
Janis Danisevskis2c084012021-01-31 22:23:17 -080071// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
72// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
73const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
74
Janis Danisevskis1af91262020-08-10 14:58:08 -070075impl KeystoreSecurityLevel {
76 /// Creates a new security level instance wrapped in a
77 /// BnKeystoreSecurityLevel proxy object. It also
78 /// calls `IBinder::set_requesting_sid` on the new interface, because
79 /// we need it for checking keystore permissions.
80 pub fn new_native_binder(
81 security_level: SecurityLevel,
Max Bires8e93d2b2021-01-14 13:17:59 -080082 ) -> Result<(impl IKeystoreSecurityLevel + Send, Uuid)> {
83 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
84 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070085 let result = BnKeystoreSecurityLevel::new_binder(Self {
86 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080087 keymint: dev,
88 hw_info,
89 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070090 operation_db: OperationDb::new(),
91 });
92 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -080093 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -070094 }
95
96 fn store_new_key(
97 &self,
98 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -070099 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000100 user_id: u32,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700101 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700102 let KeyCreationResult {
103 keyBlob: key_blob,
104 keyCharacteristics: key_characteristics,
105 certificateChain: mut certificate_chain,
106 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700107
Max Bires8e93d2b2021-01-14 13:17:59 -0800108 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700109 match certificate_chain.len() {
110 0 => None,
111 _ => Some(certificate_chain.remove(0).encodedCertificate),
112 },
113 match certificate_chain.len() {
114 0 => None,
115 _ => Some(
116 certificate_chain
117 .iter()
118 .map(|c| c.encodedCertificate.iter())
119 .flatten()
120 .copied()
121 .collect(),
122 ),
123 },
124 );
125
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000126 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
127
128 key_parameters.push(KsKeyParam::new(
129 KsKeyParamValue::UserID(user_id as i32),
130 SecurityLevel::SOFTWARE,
131 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700132
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800133 let creation_date = DateTime::now().context("Trying to make creation time.")?;
134
Janis Danisevskis1af91262020-08-10 14:58:08 -0700135 let key = match key.domain {
136 Domain::BLOB => {
Shawn Willdendbdac602021-01-12 22:35:16 -0700137 KeyDescriptor { domain: Domain::BLOB, blob: Some(key_blob), ..Default::default() }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700138 }
139 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800140 .with::<_, Result<KeyDescriptor>>(|db| {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800141 let mut metadata = KeyMetaData::new();
142 metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800143
144 let mut db = db.borrow_mut();
Janis Danisevskis4507f3b2021-01-13 16:34:39 -0800145 let (need_gc, key_id) = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800146 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800147 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800148 &key_parameters,
Shawn Willdendbdac602021-01-12 22:35:16 -0700149 &key_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -0800150 &cert_info,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800151 &metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800152 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800153 )
154 .context("In store_new_key.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -0800155 if need_gc {
156 Gc::notify_gc();
157 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700158 Ok(KeyDescriptor {
159 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800160 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700161 ..Default::default()
162 })
163 })
164 .context("In store_new_key.")?,
165 };
166
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700167 Ok(KeyMetadata {
168 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700169 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800170 certificate: cert_info.take_cert(),
171 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700172 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800173 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700174 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700175 }
176
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700177 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700178 &self,
179 key: &KeyDescriptor,
180 operation_parameters: &[KeyParameter],
181 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700182 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700183 let caller_uid = ThreadState::get_calling_uid();
184 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
185 // so that we can use it by reference like the blob provided by the key descriptor.
186 // Otherwise, we would have to clone the blob from the key descriptor.
187 let scoping_blob: Vec<u8>;
Qi Wub9433b52020-12-01 14:52:46 +0800188 let (km_blob, key_properties, key_id_guard) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700189 Domain::BLOB => {
190 check_key_permission(KeyPerm::use_(), key, &None)
191 .context("In create_operation: checking use permission for Domain::BLOB.")?;
192 (
193 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700194 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700195 None => {
196 return Err(Error::sys()).context(concat!(
197 "In create_operation: Key blob must be specified when",
198 " using Domain::BLOB."
199 ))
200 }
201 },
202 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000203 None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700204 )
205 }
206 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800207 let (key_id_guard, mut key_entry) = DB
208 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700209 db.borrow_mut().load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800210 &key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800211 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700212 KeyEntryLoadBits::KM,
213 caller_uid,
214 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
215 )
216 })
217 .context("In create_operation: Failed to load key blob.")?;
218 scoping_blob = match key_entry.take_km_blob() {
219 Some(blob) => blob,
220 None => {
221 return Err(Error::sys()).context(concat!(
222 "In create_operation: Successfully loaded key entry,",
223 " but KM blob was missing."
224 ))
225 }
226 };
Qi Wub9433b52020-12-01 14:52:46 +0800227 (
228 &scoping_blob,
229 Some((key_id_guard.id(), key_entry.into_key_parameters())),
230 Some(key_id_guard),
231 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700232 }
233 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700234
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700235 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700236 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700237 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800238 |kp| match kp.value {
239 KeyParameterValue::KeyPurpose(p) => Ok(p),
240 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
241 .context("In create_operation: Malformed KeyParameter."),
242 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700243 )?;
244
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800245 let (immediate_hat, mut auth_info) = ENFORCEMENTS
246 .authorize_create(
247 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800248 key_properties.as_ref(),
249 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800250 // TODO b/178222844 Replace this with the configuration returned by
251 // KeyMintDevice::getHardwareInfo.
252 // For now we assume that strongbox implementations need secure timestamps.
253 self.security_level == SecurityLevel::STRONGBOX,
254 )
255 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000256
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800257 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000258
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700259 let km_dev: Box<dyn IKeyMintDevice> = self
260 .keymint
261 .get_interface()
262 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700263
Janis Danisevskisaec14592020-11-12 09:41:49 -0800264 let (begin_result, upgraded_blob) = self
265 .upgrade_keyblob_if_required_with(
266 &*km_dev,
267 key_id_guard,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700268 &km_blob,
269 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800270 |blob| loop {
271 match map_km_error(km_dev.begin(
272 purpose,
273 blob,
274 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800275 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800276 )) {
277 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
278 self.operation_db.prune(caller_uid)?;
279 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700280 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800281 v => return v,
282 }
283 },
284 )
285 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700286
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800287 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000288
Janis Danisevskis1af91262020-08-10 14:58:08 -0700289 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000290 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800291 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000292 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700293 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 -0700294 };
295
296 let op_binder: Box<dyn IKeystoreOperation> =
297 KeystoreOperation::new_native_binder(operation)
298 .as_binder()
299 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700300 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700301
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700302 Ok(CreateOperationResponse {
303 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000304 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700305 parameters: match begin_result.params.len() {
306 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700307 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700308 },
309 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700310 }
311
Janis Danisevskis2c084012021-01-31 22:23:17 -0800312 fn add_certificate_parameters(uid: u32, params: &[KeyParameter]) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800313 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800314 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800315 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
316 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800317 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800318 })?;
319 result.push(KeyParameter {
320 tag: Tag::ATTESTATION_APPLICATION_ID,
321 value: KeyParameterValue::Blob(aaid),
322 });
323 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800324
325 // If we are generating/importing an asymmetric key, we need to make sure
326 // that NOT_BEFORE and NOT_AFTER are present.
327 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
328 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
329 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
330 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
331 result.push(KeyParameter {
332 tag: Tag::CERTIFICATE_NOT_BEFORE,
333 value: KeyParameterValue::DateTime(0),
334 })
335 }
336 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
337 result.push(KeyParameter {
338 tag: Tag::CERTIFICATE_NOT_AFTER,
339 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
340 })
341 }
342 }
343 _ => {}
344 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800345 Ok(result)
346 }
347
Janis Danisevskis1af91262020-08-10 14:58:08 -0700348 fn generate_key(
349 &self,
350 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700351 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700352 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700353 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700354 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700355 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700356 if key.domain != Domain::BLOB && key.alias.is_none() {
357 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
358 .context("In generate_key: Alias must be specified");
359 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000360 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361
362 let key = match key.domain {
363 Domain::APP => KeyDescriptor {
364 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000365 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700366 alias: key.alias.clone(),
367 blob: None,
368 },
369 _ => key.clone(),
370 };
371
372 // generate_key requires the rebind permission.
373 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
374
Janis Danisevskis2c084012021-01-31 22:23:17 -0800375 let params = Self::add_certificate_parameters(caller_uid, params)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800376 .context("In generate_key: Trying to get aaid.")?;
377
Janis Danisevskis1af91262020-08-10 14:58:08 -0700378 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800379 map_km_error(km_dev.addRngEntropy(entropy))
380 .context("In generate_key: Trying to add entropy.")?;
381 let creation_result = map_km_error(km_dev.generateKey(&params))
382 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700383
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000384 let user_id = uid_to_android_user(caller_uid);
385 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700386 }
387
388 fn import_key(
389 &self,
390 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700391 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700392 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700393 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700394 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700395 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700396 if key.domain != Domain::BLOB && key.alias.is_none() {
397 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
398 .context("In import_key: Alias must be specified");
399 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000400 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700401
402 let key = match key.domain {
403 Domain::APP => KeyDescriptor {
404 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000405 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700406 alias: key.alias.clone(),
407 blob: None,
408 },
409 _ => key.clone(),
410 };
411
412 // import_key requires the rebind permission.
413 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
414
Janis Danisevskis2c084012021-01-31 22:23:17 -0800415 let params = Self::add_certificate_parameters(caller_uid, params)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800416 .context("In import_key: Trying to get aaid.")?;
417
Janis Danisevskis1af91262020-08-10 14:58:08 -0700418 let format = params
419 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700420 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700421 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
422 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800423 .and_then(|p| match &p.value {
424 KeyParameterValue::Algorithm(Algorithm::AES)
425 | KeyParameterValue::Algorithm(Algorithm::HMAC)
426 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
427 KeyParameterValue::Algorithm(Algorithm::RSA)
428 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
429 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
430 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700431 })
432 .context("In import_key.")?;
433
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800434 let km_dev: Box<dyn IKeyMintDevice> =
435 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
436 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))
437 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700438
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000439 let user_id = uid_to_android_user(caller_uid);
440 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700441 }
442
443 fn import_wrapped_key(
444 &self,
445 key: &KeyDescriptor,
446 wrapping_key: &KeyDescriptor,
447 masking_key: Option<&[u8]>,
448 params: &[KeyParameter],
449 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700450 ) -> Result<KeyMetadata> {
Janis Danisevskis5d27fbb2021-01-21 16:36:18 -0800451 if !(key.domain == Domain::BLOB && key.alias.is_some()) {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700452 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
453 .context("In import_wrapped_key: Alias must be specified.");
454 }
455
Janis Danisevskisaec14592020-11-12 09:41:49 -0800456 if wrapping_key.domain == Domain::BLOB {
457 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
458 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
459 );
460 }
461
Janis Danisevskis1af91262020-08-10 14:58:08 -0700462 let wrapped_data = match &key.blob {
463 Some(d) => d,
464 None => {
465 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
466 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
467 )
468 }
469 };
470
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000471 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700472 let key = match key.domain {
473 Domain::APP => KeyDescriptor {
474 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000475 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700476 alias: key.alias.clone(),
477 blob: None,
478 },
479 _ => key.clone(),
480 };
481
482 // import_wrapped_key requires the rebind permission for the new key.
483 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
484
Janis Danisevskisaec14592020-11-12 09:41:49 -0800485 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700486 .with(|db| {
487 db.borrow_mut().load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800488 &wrapping_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800489 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700490 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000491 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700492 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
493 )
494 })
495 .context("Failed to load wrapping key.")?;
496 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
497 Some(blob) => blob,
498 None => {
499 return Err(error::Error::sys()).context(concat!(
500 "No km_blob after successfully loading key.",
501 " This should never happen."
502 ))
503 }
504 };
505
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 // km_dev.importWrappedKey does not return a certificate chain.
507 // TODO Do we assume that all wrapped keys are symmetric?
508 // let certificate_chain: Vec<KmCertificate> = Default::default();
509
510 let pw_sid = authenticators
511 .iter()
512 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700513 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700514 _ => None,
515 })
516 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
517 .context("A password authenticator SID must be specified.")?;
518
519 let fp_sid = authenticators
520 .iter()
521 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700522 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700523 _ => None,
524 })
525 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
526 .context("A fingerprint authenticator SID must be specified.")?;
527
528 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
529
530 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800531 let (creation_result, _) = self
532 .upgrade_keyblob_if_required_with(
533 &*km_dev,
534 Some(wrapping_key_id_guard),
535 wrapping_key_blob,
536 &[],
537 |wrapping_blob| {
538 let creation_result = map_km_error(km_dev.importWrappedKey(
539 wrapped_data,
540 wrapping_key_blob,
541 masking_key,
542 &params,
543 pw_sid,
544 fp_sid,
545 ))?;
546 Ok(creation_result)
547 },
548 )
549 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700550
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000551 let user_id = uid_to_android_user(caller_uid);
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800552 self.store_new_key(key, creation_result, user_id)
553 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700554 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800555
556 fn upgrade_keyblob_if_required_with<T, F>(
557 &self,
558 km_dev: &dyn IKeyMintDevice,
559 key_id_guard: Option<KeyIdGuard>,
560 blob: &[u8],
561 params: &[KeyParameter],
562 f: F,
563 ) -> Result<(T, Option<Vec<u8>>)>
564 where
565 F: Fn(&[u8]) -> Result<T, Error>,
566 {
567 match f(blob) {
568 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
569 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
570 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
571 key_id_guard.map_or(Ok(()), |key_id_guard| {
572 DB.with(|db| {
Janis Danisevskis377d1002021-01-27 19:07:48 -0800573 db.borrow_mut().set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800574 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800575 SubComponentType::KEY_BLOB,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800576 Some(&upgraded_blob),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800577 )
578 })
579 .context(concat!(
580 "In upgrade_keyblob_if_required_with: ",
581 "Failed to insert upgraded blob into the database.",
582 ))
583 })?;
584 match f(&upgraded_blob) {
585 Ok(v) => Ok((v, Some(upgraded_blob))),
586 Err(e) => Err(e).context(concat!(
587 "In upgrade_keyblob_if_required_with: ",
588 "Failed to perform operation on second try."
589 )),
590 }
591 }
592 Err(e) => {
593 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
594 }
595 Ok(v) => Ok((v, None)),
596 }
597 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700598}
599
600impl binder::Interface for KeystoreSecurityLevel {}
601
602impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700603 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700604 &self,
605 key: &KeyDescriptor,
606 operation_parameters: &[KeyParameter],
607 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700608 ) -> binder::public_api::Result<CreateOperationResponse> {
609 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700610 }
611 fn generateKey(
612 &self,
613 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700614 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700615 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700616 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700617 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700618 ) -> binder::public_api::Result<KeyMetadata> {
619 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700620 }
621 fn importKey(
622 &self,
623 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700624 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700625 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700626 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700627 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700628 ) -> binder::public_api::Result<KeyMetadata> {
629 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700630 }
631 fn importWrappedKey(
632 &self,
633 key: &KeyDescriptor,
634 wrapping_key: &KeyDescriptor,
635 masking_key: Option<&[u8]>,
636 params: &[KeyParameter],
637 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700638 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700639 map_or_log_err(
640 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700641 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700642 )
643 }
644}