blob: 417e3c52eb558cc3e899e1e8a8fe4112b6413b8d [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};
Stephen Crane221bbb52020-12-16 15:52:10 -080056use binder::{IBinder, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070057
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,
Stephen Crane221bbb52020-12-16 15:52:10 -080082 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080083 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
Stephen Crane221bbb52020-12-16 15:52:10 -0800259 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700260 .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
Stephen Crane221bbb52020-12-16 15:52:10 -0800296 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700297 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 Danisevskise766edc2021-02-06 12:16:26 -0800312 fn add_certificate_parameters(
313 uid: u32,
314 params: &[KeyParameter],
315 key: &KeyDescriptor,
316 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800317 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800318 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800319 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
320 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800321 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800322 })?;
323 result.push(KeyParameter {
324 tag: Tag::ATTESTATION_APPLICATION_ID,
325 value: KeyParameterValue::Blob(aaid),
326 });
327 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800328
Janis Danisevskise766edc2021-02-06 12:16:26 -0800329 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
330 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
331 "In add_certificate_parameters: ",
332 "Caller does not have the permission for device unique attestation."
333 ))?;
334 }
335
Janis Danisevskis2c084012021-01-31 22:23:17 -0800336 // If we are generating/importing an asymmetric key, we need to make sure
337 // that NOT_BEFORE and NOT_AFTER are present.
338 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
339 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
340 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
341 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
342 result.push(KeyParameter {
343 tag: Tag::CERTIFICATE_NOT_BEFORE,
344 value: KeyParameterValue::DateTime(0),
345 })
346 }
347 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
348 result.push(KeyParameter {
349 tag: Tag::CERTIFICATE_NOT_AFTER,
350 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
351 })
352 }
353 }
354 _ => {}
355 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800356 Ok(result)
357 }
358
Janis Danisevskis1af91262020-08-10 14:58:08 -0700359 fn generate_key(
360 &self,
361 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700362 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700363 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700364 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700365 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700366 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700367 if key.domain != Domain::BLOB && key.alias.is_none() {
368 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
369 .context("In generate_key: Alias must be specified");
370 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000371 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700372
373 let key = match key.domain {
374 Domain::APP => KeyDescriptor {
375 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000376 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700377 alias: key.alias.clone(),
378 blob: None,
379 },
380 _ => key.clone(),
381 };
382
383 // generate_key requires the rebind permission.
384 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
385
Janis Danisevskise766edc2021-02-06 12:16:26 -0800386 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800387 .context("In generate_key: Trying to get aaid.")?;
388
Stephen Crane221bbb52020-12-16 15:52:10 -0800389 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800390 map_km_error(km_dev.addRngEntropy(entropy))
391 .context("In generate_key: Trying to add entropy.")?;
392 let creation_result = map_km_error(km_dev.generateKey(&params))
393 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700394
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000395 let user_id = uid_to_android_user(caller_uid);
396 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700397 }
398
399 fn import_key(
400 &self,
401 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700402 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700403 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700404 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700405 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700406 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700407 if key.domain != Domain::BLOB && key.alias.is_none() {
408 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
409 .context("In import_key: Alias must be specified");
410 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000411 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700412
413 let key = match key.domain {
414 Domain::APP => KeyDescriptor {
415 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000416 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700417 alias: key.alias.clone(),
418 blob: None,
419 },
420 _ => key.clone(),
421 };
422
423 // import_key requires the rebind permission.
424 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
425
Janis Danisevskise766edc2021-02-06 12:16:26 -0800426 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800427 .context("In import_key: Trying to get aaid.")?;
428
Janis Danisevskis1af91262020-08-10 14:58:08 -0700429 let format = params
430 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700431 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700432 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
433 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800434 .and_then(|p| match &p.value {
435 KeyParameterValue::Algorithm(Algorithm::AES)
436 | KeyParameterValue::Algorithm(Algorithm::HMAC)
437 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
438 KeyParameterValue::Algorithm(Algorithm::RSA)
439 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
440 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
441 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700442 })
443 .context("In import_key.")?;
444
Stephen Crane221bbb52020-12-16 15:52:10 -0800445 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800446 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
447 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))
448 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700449
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000450 let user_id = uid_to_android_user(caller_uid);
451 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700452 }
453
454 fn import_wrapped_key(
455 &self,
456 key: &KeyDescriptor,
457 wrapping_key: &KeyDescriptor,
458 masking_key: Option<&[u8]>,
459 params: &[KeyParameter],
460 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700461 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800462 let wrapped_data: &[u8] = match key {
463 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
464 | KeyDescriptor {
465 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
466 } => blob,
467 _ => {
468 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
469 concat!(
470 "In import_wrapped_key: Alias and blob must be specified ",
471 "and domain must be APP or SELINUX. {:?}"
472 ),
473 key
474 ))
475 }
476 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700477
Janis Danisevskisaec14592020-11-12 09:41:49 -0800478 if wrapping_key.domain == Domain::BLOB {
479 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
480 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
481 );
482 }
483
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000484 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700485 let key = match key.domain {
486 Domain::APP => KeyDescriptor {
487 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000488 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700489 alias: key.alias.clone(),
490 blob: None,
491 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800492 Domain::SELINUX => KeyDescriptor {
493 domain: Domain::SELINUX,
494 nspace: key.nspace,
495 alias: key.alias.clone(),
496 blob: None,
497 },
498 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700499 };
500
501 // import_wrapped_key requires the rebind permission for the new key.
502 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
503
Janis Danisevskisaec14592020-11-12 09:41:49 -0800504 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700505 .with(|db| {
506 db.borrow_mut().load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800507 &wrapping_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800508 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700509 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000510 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700511 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
512 )
513 })
514 .context("Failed to load wrapping key.")?;
515 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
516 Some(blob) => blob,
517 None => {
518 return Err(error::Error::sys()).context(concat!(
519 "No km_blob after successfully loading key.",
520 " This should never happen."
521 ))
522 }
523 };
524
Janis Danisevskis1af91262020-08-10 14:58:08 -0700525 // km_dev.importWrappedKey does not return a certificate chain.
526 // TODO Do we assume that all wrapped keys are symmetric?
527 // let certificate_chain: Vec<KmCertificate> = Default::default();
528
529 let pw_sid = authenticators
530 .iter()
531 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700532 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700533 _ => None,
534 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800535 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700536
537 let fp_sid = authenticators
538 .iter()
539 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700540 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700541 _ => None,
542 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800543 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700544
545 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
546
Stephen Crane221bbb52020-12-16 15:52:10 -0800547 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800548 let (creation_result, _) = self
549 .upgrade_keyblob_if_required_with(
550 &*km_dev,
551 Some(wrapping_key_id_guard),
552 wrapping_key_blob,
553 &[],
554 |wrapping_blob| {
555 let creation_result = map_km_error(km_dev.importWrappedKey(
556 wrapped_data,
557 wrapping_key_blob,
558 masking_key,
559 &params,
560 pw_sid,
561 fp_sid,
562 ))?;
563 Ok(creation_result)
564 },
565 )
566 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700567
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000568 let user_id = uid_to_android_user(caller_uid);
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800569 self.store_new_key(key, creation_result, user_id)
570 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700571 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800572
573 fn upgrade_keyblob_if_required_with<T, F>(
574 &self,
575 km_dev: &dyn IKeyMintDevice,
576 key_id_guard: Option<KeyIdGuard>,
577 blob: &[u8],
578 params: &[KeyParameter],
579 f: F,
580 ) -> Result<(T, Option<Vec<u8>>)>
581 where
582 F: Fn(&[u8]) -> Result<T, Error>,
583 {
584 match f(blob) {
585 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
586 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
587 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
588 key_id_guard.map_or(Ok(()), |key_id_guard| {
589 DB.with(|db| {
Janis Danisevskis377d1002021-01-27 19:07:48 -0800590 db.borrow_mut().set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800591 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800592 SubComponentType::KEY_BLOB,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800593 Some(&upgraded_blob),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800594 )
595 })
596 .context(concat!(
597 "In upgrade_keyblob_if_required_with: ",
598 "Failed to insert upgraded blob into the database.",
599 ))
600 })?;
601 match f(&upgraded_blob) {
602 Ok(v) => Ok((v, Some(upgraded_blob))),
603 Err(e) => Err(e).context(concat!(
604 "In upgrade_keyblob_if_required_with: ",
605 "Failed to perform operation on second try."
606 )),
607 }
608 }
609 Err(e) => {
610 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
611 }
612 Ok(v) => Ok((v, None)),
613 }
614 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700615}
616
617impl binder::Interface for KeystoreSecurityLevel {}
618
619impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700620 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700621 &self,
622 key: &KeyDescriptor,
623 operation_parameters: &[KeyParameter],
624 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700625 ) -> binder::public_api::Result<CreateOperationResponse> {
626 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700627 }
628 fn generateKey(
629 &self,
630 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700631 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700632 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700633 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700634 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700635 ) -> binder::public_api::Result<KeyMetadata> {
636 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700637 }
638 fn importKey(
639 &self,
640 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700641 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700642 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700643 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700644 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700645 ) -> binder::public_api::Result<KeyMetadata> {
646 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700647 }
648 fn importWrappedKey(
649 &self,
650 key: &KeyDescriptor,
651 wrapping_key: &KeyDescriptor,
652 masking_key: Option<&[u8]>,
653 params: &[KeyParameter],
654 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700655 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700656 map_or_log_err(
657 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700658 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700659 )
660 }
661}