blob: 1cf770f6d6e55791b6d4723b9c1259f580377354 [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
Janis Danisevskis1af91262020-08-10 14:58:08 -070015//! This crate implements the IKeystoreSecurityLevel interface.
16
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070017use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
Shawn Willden708744a2020-12-11 13:05:27 +000018use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070019 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070020 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
21 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080022 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
23 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070024};
25use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070026 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
27 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
28 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070029 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080030 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070031};
32
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070033use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
34use crate::database::{CertificateInfo, KeyIdGuard};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000035use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000036use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000037use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Hasini Gunasingheb7142972021-02-20 03:11:27 +000038use crate::metrics::log_key_creation_event_stats;
Max Bires97f96812021-02-23 23:44:57 -080039use crate::remote_provisioning::RemProvState;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000040use crate::super_key::{KeyBlob, SuperKeyManager};
Bram Bonné5d6c5102021-02-24 15:09:18 +010041use crate::utils::{
42 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
43 uid_to_android_user, Asp,
44};
Max Bires8e93d2b2021-01-14 13:17:59 -080045use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080046 database::{
47 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
48 KeyMetaEntry, KeyType, SubComponentType, Uuid,
49 },
50 operation::KeystoreOperation,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +000051 operation::LoggingInfo,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080052 operation::OperationDb,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080053 permission::KeyPerm,
54};
55use crate::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070056 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
57 utils::key_characteristics_to_internal,
58};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080059use anyhow::{anyhow, Context, Result};
Andrew Walbran808e8602021-03-16 13:58:28 +000060use binder::{IBinderInternal, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070061
62/// Implementation of the IKeystoreSecurityLevel Interface.
63pub struct KeystoreSecurityLevel {
64 security_level: SecurityLevel,
65 keymint: Asp,
Max Bires8e93d2b2021-01-14 13:17:59 -080066 hw_info: KeyMintHardwareInfo,
67 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070068 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080069 rem_prov_state: RemProvState,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070070 id_rotation_state: IdRotationState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070071}
72
Janis Danisevskis1af91262020-08-10 14:58:08 -070073// Blob of 32 zeroes used as empty masking key.
74static ZERO_BLOB_32: &[u8] = &[0; 32];
75
Janis Danisevskis2c084012021-01-31 22:23:17 -080076// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
77// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
78const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
79
Janis Danisevskis1af91262020-08-10 14:58:08 -070080impl KeystoreSecurityLevel {
81 /// Creates a new security level instance wrapped in a
82 /// BnKeystoreSecurityLevel proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +000083 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070084 /// we need it for checking keystore permissions.
85 pub fn new_native_binder(
86 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070087 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080088 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080089 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
90 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070091 let result = BnKeystoreSecurityLevel::new_binder(Self {
92 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080093 keymint: dev,
94 hw_info,
95 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070096 operation_db: OperationDb::new(),
Max Bires97f96812021-02-23 23:44:57 -080097 rem_prov_state: RemProvState::new(security_level, km_uuid),
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070098 id_rotation_state,
Janis Danisevskis1af91262020-08-10 14:58:08 -070099 });
100 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -0800101 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700102 }
103
104 fn store_new_key(
105 &self,
106 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700107 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000108 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000109 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700110 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700111 let KeyCreationResult {
112 keyBlob: key_blob,
113 keyCharacteristics: key_characteristics,
114 certificateChain: mut certificate_chain,
115 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700116
Max Bires8e93d2b2021-01-14 13:17:59 -0800117 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700118 match certificate_chain.len() {
119 0 => None,
120 _ => Some(certificate_chain.remove(0).encodedCertificate),
121 },
122 match certificate_chain.len() {
123 0 => None,
124 _ => Some(
125 certificate_chain
126 .iter()
127 .map(|c| c.encodedCertificate.iter())
128 .flatten()
129 .copied()
130 .collect(),
131 ),
132 },
133 );
134
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000135 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
136
137 key_parameters.push(KsKeyParam::new(
138 KsKeyParamValue::UserID(user_id as i32),
139 SecurityLevel::SOFTWARE,
140 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700141
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800142 let creation_date = DateTime::now().context("Trying to make creation time.")?;
143
Janis Danisevskis1af91262020-08-10 14:58:08 -0700144 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800145 Domain::BLOB => KeyDescriptor {
146 domain: Domain::BLOB,
147 blob: Some(key_blob.to_vec()),
148 ..Default::default()
149 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700150 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800151 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800152 let mut db = db.borrow_mut();
153
154 let (key_blob, mut blob_metadata) = SUPER_KEY
155 .handle_super_encryption_on_key_init(
156 &mut db,
157 &LEGACY_MIGRATOR,
158 &(key.domain),
159 &key_parameters,
160 flags,
161 user_id,
162 &key_blob,
163 )
164 .context("In store_new_key. Failed to handle super encryption.")?;
165
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800166 let mut key_metadata = KeyMetaData::new();
167 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800168 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800171 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800172 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800173 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800174 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800175 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800177 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800178 )
179 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700180 Ok(KeyDescriptor {
181 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800182 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700183 ..Default::default()
184 })
185 })
186 .context("In store_new_key.")?,
187 };
188
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700189 Ok(KeyMetadata {
190 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700191 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800192 certificate: cert_info.take_cert(),
193 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700194 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800195 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700196 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700197 }
198
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700199 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700200 &self,
201 key: &KeyDescriptor,
202 operation_parameters: &[KeyParameter],
203 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700204 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700205 let caller_uid = ThreadState::get_calling_uid();
206 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
207 // so that we can use it by reference like the blob provided by the key descriptor.
208 // Otherwise, we would have to clone the blob from the key descriptor.
209 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800210 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700211 Domain::BLOB => {
212 check_key_permission(KeyPerm::use_(), key, &None)
213 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800214 if forced {
215 check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
216 "In create_operation: checking forced permission for Domain::BLOB.",
217 )?;
218 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700219 (
220 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700221 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700222 None => {
223 return Err(Error::sys()).context(concat!(
224 "In create_operation: Key blob must be specified when",
225 " using Domain::BLOB."
226 ))
227 }
228 },
229 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000230 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000231 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700232 )
233 }
234 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800235 let (key_id_guard, mut key_entry) = DB
236 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000237 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
238 db.borrow_mut().load_key_entry(
239 &key,
240 KeyType::Client,
241 KeyEntryLoadBits::KM,
242 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800243 |k, av| {
244 check_key_permission(KeyPerm::use_(), k, &av)?;
245 if forced {
246 check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
247 }
248 Ok(())
249 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000250 )
251 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700252 })
253 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800254
255 let (blob, blob_metadata) =
256 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
257 "In create_operation: Successfully loaded key entry, ",
258 "but KM blob was missing."
259 ))?;
260 scoping_blob = blob;
261
Qi Wub9433b52020-12-01 14:52:46 +0800262 (
263 &scoping_blob,
264 Some((key_id_guard.id(), key_entry.into_key_parameters())),
265 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000266 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800267 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700268 }
269 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700270
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700271 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700272 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700273 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800274 |kp| match kp.value {
275 KeyParameterValue::KeyPurpose(p) => Ok(p),
276 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
277 .context("In create_operation: Malformed KeyParameter."),
278 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700279 )?;
280
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800281 let (immediate_hat, mut auth_info) = ENFORCEMENTS
282 .authorize_create(
283 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800284 key_properties.as_ref(),
285 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700286 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800287 )
288 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000289
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800290 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000291
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000292 let km_blob = SUPER_KEY
293 .unwrap_key_if_required(&blob_metadata, km_blob)
294 .context("In create_operation. Failed to handle super encryption.")?;
295
Stephen Crane221bbb52020-12-16 15:52:10 -0800296 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700297 .keymint
298 .get_interface()
299 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700300
Janis Danisevskisaec14592020-11-12 09:41:49 -0800301 let (begin_result, upgraded_blob) = self
302 .upgrade_keyblob_if_required_with(
303 &*km_dev,
304 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700305 &km_blob,
306 &blob_metadata,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700307 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800308 |blob| loop {
309 match map_km_error(km_dev.begin(
310 purpose,
311 blob,
312 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800313 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800314 )) {
315 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800316 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800317 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700318 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800319 v => return v,
320 }
321 },
322 )
323 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700324
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800325 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000326
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000327 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
328
Janis Danisevskis1af91262020-08-10 14:58:08 -0700329 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000330 Some(km_op) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000331 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced,
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000332 LoggingInfo::new(self.security_level, purpose, op_params,
333 upgraded_blob.is_some()))
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000334 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700335 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 -0700336 };
337
Stephen Crane221bbb52020-12-16 15:52:10 -0800338 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700339 KeystoreOperation::new_native_binder(operation)
340 .as_binder()
341 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700342 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700343
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700344 Ok(CreateOperationResponse {
345 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000346 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700347 parameters: match begin_result.params.len() {
348 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700349 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700350 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800351 // An upgraded blob should only be returned if the caller has permission
352 // to use Domain::BLOB keys. If we got to this point, we already checked
353 // that the caller had that permission.
354 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700355 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700356 }
357
Janis Danisevskise766edc2021-02-06 12:16:26 -0800358 fn add_certificate_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700359 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800360 uid: u32,
361 params: &[KeyParameter],
362 key: &KeyDescriptor,
363 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800364 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800365 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800366 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
367 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800368 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800369 })?;
370 result.push(KeyParameter {
371 tag: Tag::ATTESTATION_APPLICATION_ID,
372 value: KeyParameterValue::Blob(aaid),
373 });
374 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800375
Janis Danisevskise766edc2021-02-06 12:16:26 -0800376 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
377 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
378 "In add_certificate_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700379 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800380 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700381 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
382 "In add_certificate_parameters: Call to had_factory_reset_since_id_rotation failed."
383 )? {
384 result.push(KeyParameter{
385 tag: Tag::RESET_SINCE_ID_ROTATION,
386 value: KeyParameterValue::BoolValue(true),
387 })
388 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800389 }
390
Bram Bonné5d6c5102021-02-24 15:09:18 +0100391 // If the caller requests any device identifier attestation tag, check that they hold the
392 // correct Android permission.
393 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
394 check_device_attestation_permissions().context(concat!(
395 "In add_certificate_parameters: ",
396 "Caller does not have the permission to attest device identifiers."
397 ))?;
398 }
399
Janis Danisevskis2c084012021-01-31 22:23:17 -0800400 // If we are generating/importing an asymmetric key, we need to make sure
401 // that NOT_BEFORE and NOT_AFTER are present.
402 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
403 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
404 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
405 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
406 result.push(KeyParameter {
407 tag: Tag::CERTIFICATE_NOT_BEFORE,
408 value: KeyParameterValue::DateTime(0),
409 })
410 }
411 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
412 result.push(KeyParameter {
413 tag: Tag::CERTIFICATE_NOT_AFTER,
414 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
415 })
416 }
417 }
418 _ => {}
419 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800420 Ok(result)
421 }
422
Janis Danisevskis1af91262020-08-10 14:58:08 -0700423 fn generate_key(
424 &self,
425 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700426 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700427 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700428 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700429 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700430 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700431 if key.domain != Domain::BLOB && key.alias.is_none() {
432 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
433 .context("In generate_key: Alias must be specified");
434 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000435 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700436
437 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 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700448 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700449 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700450
451 let attestation_key_info = match (key.domain, attest_key_descriptor) {
452 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800453 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700454 .with(|db| {
455 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800456 &key,
457 caller_uid,
458 attest_key_descriptor,
459 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700460 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800461 &mut db.borrow_mut(),
462 )
463 })
464 .context("In generate_key: Trying to get an attestation key")?,
465 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700466 let params = self
467 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800468 .context("In generate_key: Trying to get aaid.")?;
469
Stephen Crane221bbb52020-12-16 15:52:10 -0800470 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700471
472 let creation_result = match attestation_key_info {
473 Some(AttestationKeyInfo::UserGenerated {
474 key_id_guard,
475 blob,
476 blob_metadata,
477 issuer_subject,
478 }) => self
479 .upgrade_keyblob_if_required_with(
480 &*km_dev,
481 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700482 &KeyBlob::Ref(&blob),
483 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700484 &params,
485 |blob| {
486 let attest_key = Some(AttestationKey {
487 keyBlob: blob.to_vec(),
488 attestKeyParams: vec![],
489 issuerSubjectName: issuer_subject.clone(),
490 });
491 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
492 },
493 )
494 .context("In generate_key: Using user generated attestation key.")
495 .map(|(result, _)| result),
496 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
497 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
498 .context("While generating Key with remote provisioned attestation key.")
499 .map(|mut creation_result| {
500 creation_result.certificateChain.push(attestation_certs);
501 creation_result
502 })
503 }
504 None => map_km_error(km_dev.generateKey(&params, None))
505 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800506 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700507 .context("In generate_key.")?;
508
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000509 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000510 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700511 }
512
513 fn import_key(
514 &self,
515 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700516 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700517 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700518 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700520 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700521 if key.domain != Domain::BLOB && key.alias.is_none() {
522 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
523 .context("In import_key: Alias must be specified");
524 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000525 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700526
527 let key = match key.domain {
528 Domain::APP => KeyDescriptor {
529 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000530 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700531 alias: key.alias.clone(),
532 blob: None,
533 },
534 _ => key.clone(),
535 };
536
537 // import_key requires the rebind permission.
538 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
539
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700540 let params = self
541 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800542 .context("In import_key: Trying to get aaid.")?;
543
Janis Danisevskis1af91262020-08-10 14:58:08 -0700544 let format = params
545 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700546 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700547 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
548 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800549 .and_then(|p| match &p.value {
550 KeyParameterValue::Algorithm(Algorithm::AES)
551 | KeyParameterValue::Algorithm(Algorithm::HMAC)
552 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
553 KeyParameterValue::Algorithm(Algorithm::RSA)
554 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
555 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
556 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700557 })
558 .context("In import_key.")?;
559
Stephen Crane221bbb52020-12-16 15:52:10 -0800560 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800561 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700562 let creation_result =
563 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
564 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700565
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000566 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000567 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700568 }
569
570 fn import_wrapped_key(
571 &self,
572 key: &KeyDescriptor,
573 wrapping_key: &KeyDescriptor,
574 masking_key: Option<&[u8]>,
575 params: &[KeyParameter],
576 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700577 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800578 let wrapped_data: &[u8] = match key {
579 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
580 | KeyDescriptor {
581 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
582 } => blob,
583 _ => {
584 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
585 concat!(
586 "In import_wrapped_key: Alias and blob must be specified ",
587 "and domain must be APP or SELINUX. {:?}"
588 ),
589 key
590 ))
591 }
592 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700593
Janis Danisevskisaec14592020-11-12 09:41:49 -0800594 if wrapping_key.domain == Domain::BLOB {
595 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
596 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
597 );
598 }
599
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000600 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000601 let user_id = uid_to_android_user(caller_uid);
602
Janis Danisevskis1af91262020-08-10 14:58:08 -0700603 let key = match key.domain {
604 Domain::APP => KeyDescriptor {
605 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000606 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700607 alias: key.alias.clone(),
608 blob: None,
609 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800610 Domain::SELINUX => KeyDescriptor {
611 domain: Domain::SELINUX,
612 nspace: key.nspace,
613 alias: key.alias.clone(),
614 blob: None,
615 },
616 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700617 };
618
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800619 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700620 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
621
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000622 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700623 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000624 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
625 db.borrow_mut().load_key_entry(
626 &wrapping_key,
627 KeyType::Client,
628 KeyEntryLoadBits::KM,
629 caller_uid,
630 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
631 )
632 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700633 })
634 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000635
636 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
637 .take_key_blob_info()
638 .ok_or_else(error::Error::sys)
639 .context("No km_blob after successfully loading key. This should never happen.")?;
640
641 let wrapping_key_blob =
642 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
643 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
644 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700645
Janis Danisevskis1af91262020-08-10 14:58:08 -0700646 // km_dev.importWrappedKey does not return a certificate chain.
647 // TODO Do we assume that all wrapped keys are symmetric?
648 // let certificate_chain: Vec<KmCertificate> = Default::default();
649
650 let pw_sid = authenticators
651 .iter()
652 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700653 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700654 _ => None,
655 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800656 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700657
658 let fp_sid = authenticators
659 .iter()
660 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700661 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700662 _ => None,
663 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800664 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700665
666 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
667
Stephen Crane221bbb52020-12-16 15:52:10 -0800668 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800669 let (creation_result, _) = self
670 .upgrade_keyblob_if_required_with(
671 &*km_dev,
672 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700673 &wrapping_key_blob,
674 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800675 &[],
676 |wrapping_blob| {
677 let creation_result = map_km_error(km_dev.importWrappedKey(
678 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800679 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800680 masking_key,
681 &params,
682 pw_sid,
683 fp_sid,
684 ))?;
685 Ok(creation_result)
686 },
687 )
688 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700689
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000690 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800691 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700692 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800693
Paul Crowley7a658392021-03-18 17:08:20 -0700694 fn store_upgraded_keyblob(
695 key_id_guard: KeyIdGuard,
696 km_uuid: Option<&Uuid>,
697 key_blob: &KeyBlob,
698 upgraded_blob: &[u8],
699 ) -> Result<()> {
700 let (upgraded_blob_to_be_stored, new_blob_metadata) =
701 SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
702 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
703
704 let mut new_blob_metadata = new_blob_metadata.unwrap_or_else(BlobMetaData::new);
705 if let Some(uuid) = km_uuid {
706 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
707 }
708
709 DB.with(|db| {
710 let mut db = db.borrow_mut();
711 db.set_blob(
712 &key_id_guard,
713 SubComponentType::KEY_BLOB,
714 Some(&upgraded_blob_to_be_stored),
715 Some(&new_blob_metadata),
716 )
717 })
718 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
719 }
720
Janis Danisevskisaec14592020-11-12 09:41:49 -0800721 fn upgrade_keyblob_if_required_with<T, F>(
722 &self,
723 km_dev: &dyn IKeyMintDevice,
724 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700725 key_blob: &KeyBlob,
726 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800727 params: &[KeyParameter],
728 f: F,
729 ) -> Result<(T, Option<Vec<u8>>)>
730 where
731 F: Fn(&[u8]) -> Result<T, Error>,
732 {
Paul Crowley7a658392021-03-18 17:08:20 -0700733 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800734 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Paul Crowley7a658392021-03-18 17:08:20 -0700735 let upgraded_blob = map_km_error(km_dev.upgradeKey(key_blob, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800736 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000737
Paul Crowley7a658392021-03-18 17:08:20 -0700738 if let Some(kid) = key_id_guard {
739 Self::store_upgraded_keyblob(
740 kid,
741 blob_metadata.km_uuid(),
742 key_blob,
743 &upgraded_blob,
744 )
745 .context(
746 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000747 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000748 }
749
Janis Danisevskisaec14592020-11-12 09:41:49 -0800750 match f(&upgraded_blob) {
751 Ok(v) => Ok((v, Some(upgraded_blob))),
752 Err(e) => Err(e).context(concat!(
753 "In upgrade_keyblob_if_required_with: ",
754 "Failed to perform operation on second try."
755 )),
756 }
757 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700758 result => {
759 if let Some(kid) = key_id_guard {
760 if key_blob.force_reencrypt() {
761 Self::store_upgraded_keyblob(
762 kid,
763 blob_metadata.km_uuid(),
764 key_blob,
765 key_blob,
766 )
767 .context(concat!(
768 "In upgrade_keyblob_if_required_with: ",
769 "store_upgraded_keyblob failed in forced reencrypt"
770 ))?;
771 }
772 }
773 result
774 .map(|v| (v, None))
775 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
776 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800777 }
778 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800779
780 fn convert_storage_key_to_ephemeral(&self, storage_key: &KeyDescriptor) -> Result<Vec<u8>> {
781 if storage_key.domain != Domain::BLOB {
782 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
783 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
784 "Key must be of Domain::BLOB"
785 ));
786 }
787 let key_blob = storage_key
788 .blob
789 .as_ref()
790 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
791 .context(
792 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
793 )?;
794
795 // convert_storage_key_to_ephemeral requires the associated permission
796 check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
797 .context("In convert_storage_key_to_ephemeral: Check permission")?;
798
799 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
800 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
801 "Getting keymint device interface"
802 ))?;
803 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
804 .context("In keymint device convertStorageKeyToEphemeral")
805 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800806
807 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
808 if key.domain != Domain::BLOB {
809 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
810 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
811 }
812
813 let key_blob = key
814 .blob
815 .as_ref()
816 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
817 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
818
819 check_key_permission(KeyPerm::delete(), key, &None)
820 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
821
822 let km_dev: Strong<dyn IKeyMintDevice> = self
823 .keymint
824 .get_interface()
825 .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
826 map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
827 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700828}
829
830impl binder::Interface for KeystoreSecurityLevel {}
831
832impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700833 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700834 &self,
835 key: &KeyDescriptor,
836 operation_parameters: &[KeyParameter],
837 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700838 ) -> binder::public_api::Result<CreateOperationResponse> {
839 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700840 }
841 fn generateKey(
842 &self,
843 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700844 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700845 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700846 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700847 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700848 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000849 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000850 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000851 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700852 }
853 fn importKey(
854 &self,
855 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700856 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700857 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700858 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700859 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700860 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000861 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000862 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000863 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700864 }
865 fn importWrappedKey(
866 &self,
867 key: &KeyDescriptor,
868 wrapping_key: &KeyDescriptor,
869 masking_key: Option<&[u8]>,
870 params: &[KeyParameter],
871 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700872 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000873 let result =
874 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000875 log_key_creation_event_stats(self.security_level, params, &result);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000876 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700877 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800878 fn convertStorageKeyToEphemeral(
879 &self,
880 storage_key: &KeyDescriptor,
881 ) -> binder::public_api::Result<Vec<u8>> {
882 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
883 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800884 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
885 map_or_log_err(self.delete_key(key), Ok)
886 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700887}