blob: ee725ebec7be14425b9145f3523cf17c0452942e [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 Danisevskis2ee014b2021-05-05 14:29:08 -070017use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
Pavel Grafovf45034a2021-05-12 22:35:45 +010018use crate::audit_log::{
19 log_key_deleted, log_key_generated, log_key_imported, log_key_integrity_violation,
20};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070021use crate::database::{CertificateInfo, KeyIdGuard};
22use crate::error::{self, map_km_error, map_or_log_err, Error, ErrorCode};
23use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
24use crate::key_parameter::KeyParameter as KsKeyParam;
25use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000026use crate::metrics_store::log_key_creation_event_stats;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070027use crate::remote_provisioning::RemProvState;
28use crate::super_key::{KeyBlob, SuperKeyManager};
29use crate::utils::{
30 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070031 key_characteristics_to_internal, uid_to_android_user, watchdog as wd,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070032};
33use crate::{
34 database::{
35 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
36 KeyMetaEntry, KeyType, SubComponentType, Uuid,
37 },
38 operation::KeystoreOperation,
39 operation::LoggingInfo,
40 operation::OperationDb,
41 permission::KeyPerm,
42};
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070043use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
Shawn Willden708744a2020-12-11 13:05:27 +000044use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070045 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070046 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
47 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080048 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
49 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070050};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000051use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070052use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070053 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
Janis Danisevskisb2434d02021-04-20 12:49:27 -070054 Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
55 IKeystoreOperation::IKeystoreOperation, IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070056 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080057 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070058};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080059use anyhow::{anyhow, Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -070060
61/// Implementation of the IKeystoreSecurityLevel Interface.
62pub struct KeystoreSecurityLevel {
63 security_level: SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070064 keymint: Strong<dyn IKeyMintDevice>,
Max Bires8e93d2b2021-01-14 13:17:59 -080065 hw_info: KeyMintHardwareInfo,
66 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070067 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080068 rem_prov_state: RemProvState,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070069 id_rotation_state: IdRotationState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070070}
71
Janis Danisevskis1af91262020-08-10 14:58:08 -070072// Blob of 32 zeroes used as empty masking key.
73static ZERO_BLOB_32: &[u8] = &[0; 32];
74
Janis Danisevskis2c084012021-01-31 22:23:17 -080075// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
76// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
77const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
78
Janis Danisevskis1af91262020-08-10 14:58:08 -070079impl KeystoreSecurityLevel {
80 /// Creates a new security level instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +000081 /// BnKeystoreSecurityLevel proxy object. It also enables
82 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070083 /// we need it for checking keystore permissions.
84 pub fn new_native_binder(
85 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070086 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080087 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080088 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
89 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000090 let result = BnKeystoreSecurityLevel::new_binder(
91 Self {
92 security_level,
93 keymint: dev,
94 hw_info,
95 km_uuid,
96 operation_db: OperationDb::new(),
97 rem_prov_state: RemProvState::new(security_level, km_uuid),
98 id_rotation_state,
99 },
100 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
101 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800102 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700103 }
104
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700105 fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
106 let sec_level = self.security_level;
107 wd::watch_millis_with(id, millis, move || format!("SecurityLevel {:?}", sec_level))
108 }
109
Janis Danisevskis1af91262020-08-10 14:58:08 -0700110 fn store_new_key(
111 &self,
112 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700113 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000114 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000115 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700116 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700117 let KeyCreationResult {
118 keyBlob: key_blob,
119 keyCharacteristics: key_characteristics,
120 certificateChain: mut certificate_chain,
121 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700122
Max Bires8e93d2b2021-01-14 13:17:59 -0800123 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700124 match certificate_chain.len() {
125 0 => None,
126 _ => Some(certificate_chain.remove(0).encodedCertificate),
127 },
128 match certificate_chain.len() {
129 0 => None,
130 _ => Some(
131 certificate_chain
132 .iter()
133 .map(|c| c.encodedCertificate.iter())
134 .flatten()
135 .copied()
136 .collect(),
137 ),
138 },
139 );
140
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000141 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
142
143 key_parameters.push(KsKeyParam::new(
144 KsKeyParamValue::UserID(user_id as i32),
145 SecurityLevel::SOFTWARE,
146 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700147
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800148 let creation_date = DateTime::now().context("Trying to make creation time.")?;
149
Janis Danisevskis1af91262020-08-10 14:58:08 -0700150 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800151 Domain::BLOB => KeyDescriptor {
152 domain: Domain::BLOB,
153 blob: Some(key_blob.to_vec()),
154 ..Default::default()
155 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700156 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800157 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800158 let mut db = db.borrow_mut();
159
160 let (key_blob, mut blob_metadata) = SUPER_KEY
161 .handle_super_encryption_on_key_init(
162 &mut db,
163 &LEGACY_MIGRATOR,
164 &(key.domain),
165 &key_parameters,
166 flags,
167 user_id,
168 &key_blob,
169 )
170 .context("In store_new_key. Failed to handle super encryption.")?;
171
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800172 let mut key_metadata = KeyMetaData::new();
173 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800174 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800175
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800177 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800178 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700179 KeyType::Client,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800180 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800181 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800182 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800183 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800184 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800185 )
186 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700187 Ok(KeyDescriptor {
188 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800189 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700190 ..Default::default()
191 })
192 })
193 .context("In store_new_key.")?,
194 };
195
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700196 Ok(KeyMetadata {
197 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700198 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800199 certificate: cert_info.take_cert(),
200 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700201 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800202 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700203 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700204 }
205
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700206 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700207 &self,
208 key: &KeyDescriptor,
209 operation_parameters: &[KeyParameter],
210 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700211 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700212 let caller_uid = ThreadState::get_calling_uid();
213 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
214 // so that we can use it by reference like the blob provided by the key descriptor.
215 // Otherwise, we would have to clone the blob from the key descriptor.
216 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800217 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700218 Domain::BLOB => {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700219 check_key_permission(KeyPerm::Use, key, &None)
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700220 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800221 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700222 check_key_permission(KeyPerm::ReqForcedOp, key, &None).context(
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800223 "In create_operation: checking forced permission for Domain::BLOB.",
224 )?;
225 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700226 (
227 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700228 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700229 None => {
230 return Err(Error::sys()).context(concat!(
231 "In create_operation: Key blob must be specified when",
232 " using Domain::BLOB."
233 ))
234 }
235 },
236 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000237 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000238 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700239 )
240 }
241 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800242 let (key_id_guard, mut key_entry) = DB
243 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700244 LEGACY_MIGRATOR.with_try_migrate(key, caller_uid, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000245 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700246 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000247 KeyType::Client,
248 KeyEntryLoadBits::KM,
249 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800250 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700251 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800252 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700253 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800254 }
255 Ok(())
256 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000257 )
258 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700259 })
260 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800261
262 let (blob, blob_metadata) =
263 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
264 "In create_operation: Successfully loaded key entry, ",
265 "but KM blob was missing."
266 ))?;
267 scoping_blob = blob;
268
Qi Wub9433b52020-12-01 14:52:46 +0800269 (
270 &scoping_blob,
271 Some((key_id_guard.id(), key_entry.into_key_parameters())),
272 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000273 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800274 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700275 }
276 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700277
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700278 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700279 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700280 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800281 |kp| match kp.value {
282 KeyParameterValue::KeyPurpose(p) => Ok(p),
283 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
284 .context("In create_operation: Malformed KeyParameter."),
285 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700286 )?;
287
Satya Tangirala2642ff92021-04-15 01:57:00 -0700288 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
289 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
290 let op_params: Vec<KeyParameter> =
291 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
292 let operation_parameters = op_params.as_slice();
293
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800294 let (immediate_hat, mut auth_info) = ENFORCEMENTS
295 .authorize_create(
296 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800297 key_properties.as_ref(),
298 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700299 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800300 )
301 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000302
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000303 let km_blob = SUPER_KEY
304 .unwrap_key_if_required(&blob_metadata, km_blob)
305 .context("In create_operation. Failed to handle super encryption.")?;
306
Janis Danisevskisaec14592020-11-12 09:41:49 -0800307 let (begin_result, upgraded_blob) = self
308 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700309 &*self.keymint,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800310 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700311 &km_blob,
312 &blob_metadata,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700313 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800314 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700315 match map_km_error({
316 let _wp = self.watch_millis(
317 "In KeystoreSecurityLevel::create_operation: calling begin",
318 500,
319 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700320 self.keymint.begin(
321 purpose,
322 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700323 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700324 immediate_hat.as_ref(),
325 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700326 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800327 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800328 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800329 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700330 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100331 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
332 if let Some((key_id, _)) = key_properties {
333 if let Ok(Some(key)) =
334 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
335 {
336 log_key_integrity_violation(&key);
337 } else {
338 log::error!("Failed to load key descriptor for audit log");
339 }
340 }
341 return v;
342 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800343 v => return v,
344 }
345 },
346 )
347 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700348
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800349 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000350
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000351 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
352
Janis Danisevskis1af91262020-08-10 14:58:08 -0700353 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700354 Some(km_op) => self.operation_db.create_operation(
355 km_op,
356 caller_uid,
357 auth_info,
358 forced,
359 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
360 ),
361 None => {
362 return Err(Error::sys()).context(concat!(
363 "In create_operation: Begin operation returned successfully, ",
364 "but did not return a valid operation."
365 ))
366 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700367 };
368
Stephen Crane221bbb52020-12-16 15:52:10 -0800369 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700370 KeystoreOperation::new_native_binder(operation)
371 .as_binder()
372 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700373 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700374
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700375 Ok(CreateOperationResponse {
376 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000377 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700378 parameters: match begin_result.params.len() {
379 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700380 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700381 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800382 // An upgraded blob should only be returned if the caller has permission
383 // to use Domain::BLOB keys. If we got to this point, we already checked
384 // that the caller had that permission.
385 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700386 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700387 }
388
Janis Danisevskise766edc2021-02-06 12:16:26 -0800389 fn add_certificate_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700390 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800391 uid: u32,
392 params: &[KeyParameter],
393 key: &KeyDescriptor,
394 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800395 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800396 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800397 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700398 let aaid = {
399 let _wp = self.watch_millis(
400 "In KeystoreSecurityLevel::add_certificate_parameters calling: get_aaid",
401 500,
402 );
403 keystore2_aaid::get_aaid(uid).map_err(|e| {
404 anyhow!(format!(
405 "In add_certificate_parameters: get_aaid returned status {}.",
406 e
407 ))
408 })
409 }?;
410
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800411 result.push(KeyParameter {
412 tag: Tag::ATTESTATION_APPLICATION_ID,
413 value: KeyParameterValue::Blob(aaid),
414 });
415 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800416
Janis Danisevskise766edc2021-02-06 12:16:26 -0800417 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700418 check_key_permission(KeyPerm::GenUniqueId, key, &None).context(concat!(
Janis Danisevskise766edc2021-02-06 12:16:26 -0800419 "In add_certificate_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700420 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800421 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700422 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
423 "In add_certificate_parameters: Call to had_factory_reset_since_id_rotation failed."
424 )? {
425 result.push(KeyParameter{
426 tag: Tag::RESET_SINCE_ID_ROTATION,
427 value: KeyParameterValue::BoolValue(true),
428 })
429 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800430 }
431
Bram Bonné5d6c5102021-02-24 15:09:18 +0100432 // If the caller requests any device identifier attestation tag, check that they hold the
433 // correct Android permission.
434 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
435 check_device_attestation_permissions().context(concat!(
436 "In add_certificate_parameters: ",
437 "Caller does not have the permission to attest device identifiers."
438 ))?;
439 }
440
Janis Danisevskis2c084012021-01-31 22:23:17 -0800441 // If we are generating/importing an asymmetric key, we need to make sure
442 // that NOT_BEFORE and NOT_AFTER are present.
443 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
444 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
445 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
446 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
447 result.push(KeyParameter {
448 tag: Tag::CERTIFICATE_NOT_BEFORE,
449 value: KeyParameterValue::DateTime(0),
450 })
451 }
452 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
453 result.push(KeyParameter {
454 tag: Tag::CERTIFICATE_NOT_AFTER,
455 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
456 })
457 }
458 }
459 _ => {}
460 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800461 Ok(result)
462 }
463
Janis Danisevskis1af91262020-08-10 14:58:08 -0700464 fn generate_key(
465 &self,
466 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700467 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700468 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700469 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700470 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700471 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700472 if key.domain != Domain::BLOB && key.alias.is_none() {
473 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
474 .context("In generate_key: Alias must be specified");
475 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000476 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700477
478 let key = match key.domain {
479 Domain::APP => KeyDescriptor {
480 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000481 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700482 alias: key.alias.clone(),
483 blob: None,
484 },
485 _ => key.clone(),
486 };
487
488 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700489 // Must return on error for security reasons.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700490 check_key_permission(KeyPerm::Rebind, &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700491
492 let attestation_key_info = match (key.domain, attest_key_descriptor) {
493 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800494 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700495 .with(|db| {
496 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800497 &key,
498 caller_uid,
499 attest_key_descriptor,
500 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700501 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800502 &mut db.borrow_mut(),
503 )
504 })
505 .context("In generate_key: Trying to get an attestation key")?,
506 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700507 let params = self
508 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800509 .context("In generate_key: Trying to get aaid.")?;
510
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700511 let creation_result = match attestation_key_info {
512 Some(AttestationKeyInfo::UserGenerated {
513 key_id_guard,
514 blob,
515 blob_metadata,
516 issuer_subject,
517 }) => self
518 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700519 &*self.keymint,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700520 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700521 &KeyBlob::Ref(&blob),
522 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700523 &params,
524 |blob| {
525 let attest_key = Some(AttestationKey {
526 keyBlob: blob.to_vec(),
527 attestKeyParams: vec![],
528 issuerSubjectName: issuer_subject.clone(),
529 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700530 map_km_error({
531 let _wp = self.watch_millis(
532 concat!(
533 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
534 "calling generate_key."
535 ),
536 5000, // Generate can take a little longer.
537 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700538 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700539 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700540 },
541 )
542 .context("In generate_key: Using user generated attestation key.")
543 .map(|(result, _)| result),
544 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700545 map_km_error({
546 let _wp = self.watch_millis(
547 concat!(
548 "In KeystoreSecurityLevel::generate_key (RemoteProvisioned): ",
549 "calling generate_key.",
550 ),
551 5000, // Generate can take a little longer.
552 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700553 self.keymint.generateKey(&params, Some(&attestation_key))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700554 })
555 .context("While generating Key with remote provisioned attestation key.")
556 .map(|mut creation_result| {
557 creation_result.certificateChain.push(attestation_certs);
558 creation_result
559 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700560 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700561 None => map_km_error({
562 let _wp = self.watch_millis(
563 concat!(
564 "In KeystoreSecurityLevel::generate_key (No attestation): ",
565 "calling generate_key.",
566 ),
567 5000, // Generate can take a little longer.
568 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700569 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700570 })
571 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800572 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700573 .context("In generate_key.")?;
574
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000575 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000576 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700577 }
578
579 fn import_key(
580 &self,
581 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700582 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700583 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700584 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700585 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700586 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700587 if key.domain != Domain::BLOB && key.alias.is_none() {
588 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
589 .context("In import_key: Alias must be specified");
590 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000591 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700592
593 let key = match key.domain {
594 Domain::APP => KeyDescriptor {
595 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000596 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700597 alias: key.alias.clone(),
598 blob: None,
599 },
600 _ => key.clone(),
601 };
602
603 // import_key requires the rebind permission.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700604 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700605
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700606 let params = self
607 .add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800608 .context("In import_key: Trying to get aaid.")?;
609
Janis Danisevskis1af91262020-08-10 14:58:08 -0700610 let format = params
611 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700612 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700613 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
614 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800615 .and_then(|p| match &p.value {
616 KeyParameterValue::Algorithm(Algorithm::AES)
617 | KeyParameterValue::Algorithm(Algorithm::HMAC)
618 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
619 KeyParameterValue::Algorithm(Algorithm::RSA)
620 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
621 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
622 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700623 })
624 .context("In import_key.")?;
625
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700626 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700627 let creation_result = map_km_error({
628 let _wp =
629 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
630 km_dev.importKey(&params, format, key_data, None /* attestKey */)
631 })
632 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700633
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000634 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000635 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700636 }
637
638 fn import_wrapped_key(
639 &self,
640 key: &KeyDescriptor,
641 wrapping_key: &KeyDescriptor,
642 masking_key: Option<&[u8]>,
643 params: &[KeyParameter],
644 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700645 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800646 let wrapped_data: &[u8] = match key {
647 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
648 | KeyDescriptor {
649 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
650 } => blob,
651 _ => {
652 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
653 concat!(
654 "In import_wrapped_key: Alias and blob must be specified ",
655 "and domain must be APP or SELINUX. {:?}"
656 ),
657 key
658 ))
659 }
660 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700661
Janis Danisevskisaec14592020-11-12 09:41:49 -0800662 if wrapping_key.domain == Domain::BLOB {
663 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
664 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
665 );
666 }
667
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000668 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000669 let user_id = uid_to_android_user(caller_uid);
670
Janis Danisevskis1af91262020-08-10 14:58:08 -0700671 let key = match key.domain {
672 Domain::APP => KeyDescriptor {
673 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000674 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700675 alias: key.alias.clone(),
676 blob: None,
677 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800678 Domain::SELINUX => KeyDescriptor {
679 domain: Domain::SELINUX,
680 nspace: key.nspace,
681 alias: key.alias.clone(),
682 blob: None,
683 },
684 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700685 };
686
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800687 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700688 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700689
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000690 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700691 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000692 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
693 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700694 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000695 KeyType::Client,
696 KeyEntryLoadBits::KM,
697 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700698 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000699 )
700 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700701 })
702 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000703
704 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
705 .take_key_blob_info()
706 .ok_or_else(error::Error::sys)
707 .context("No km_blob after successfully loading key. This should never happen.")?;
708
709 let wrapping_key_blob =
710 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
711 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
712 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700713
Janis Danisevskis1af91262020-08-10 14:58:08 -0700714 // km_dev.importWrappedKey does not return a certificate chain.
715 // TODO Do we assume that all wrapped keys are symmetric?
716 // let certificate_chain: Vec<KmCertificate> = Default::default();
717
718 let pw_sid = authenticators
719 .iter()
720 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700721 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700722 _ => None,
723 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800724 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700725
726 let fp_sid = authenticators
727 .iter()
728 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700729 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700730 _ => None,
731 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800732 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700733
734 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
735
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800736 let (creation_result, _) = self
737 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700738 &*self.keymint,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800739 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700740 &wrapping_key_blob,
741 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800742 &[],
743 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700744 let _wp = self.watch_millis(
745 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
746 500,
747 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700748 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800749 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800750 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800751 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700752 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800753 pw_sid,
754 fp_sid,
755 ))?;
756 Ok(creation_result)
757 },
758 )
759 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700760
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000761 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800762 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700763 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800764
Paul Crowley7a658392021-03-18 17:08:20 -0700765 fn store_upgraded_keyblob(
766 key_id_guard: KeyIdGuard,
767 km_uuid: Option<&Uuid>,
768 key_blob: &KeyBlob,
769 upgraded_blob: &[u8],
770 ) -> Result<()> {
771 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700772 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Paul Crowley7a658392021-03-18 17:08:20 -0700773 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
774
Paul Crowley44c02da2021-04-08 17:04:43 +0000775 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700776 if let Some(uuid) = km_uuid {
777 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
778 }
779
780 DB.with(|db| {
781 let mut db = db.borrow_mut();
782 db.set_blob(
783 &key_id_guard,
784 SubComponentType::KEY_BLOB,
785 Some(&upgraded_blob_to_be_stored),
786 Some(&new_blob_metadata),
787 )
788 })
789 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
790 }
791
Janis Danisevskisaec14592020-11-12 09:41:49 -0800792 fn upgrade_keyblob_if_required_with<T, F>(
793 &self,
794 km_dev: &dyn IKeyMintDevice,
795 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700796 key_blob: &KeyBlob,
797 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800798 params: &[KeyParameter],
799 f: F,
800 ) -> Result<(T, Option<Vec<u8>>)>
801 where
802 F: Fn(&[u8]) -> Result<T, Error>,
803 {
Paul Crowley7a658392021-03-18 17:08:20 -0700804 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800805 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700806 let upgraded_blob = {
807 let _wp = self.watch_millis(
808 concat!(
809 "In KeystoreSecurityLevel::upgrade_keyblob_if_required_with: ",
810 "calling upgradeKey."
811 ),
812 500,
813 );
814 map_km_error(km_dev.upgradeKey(key_blob, params))
815 }
816 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000817
Paul Crowley7a658392021-03-18 17:08:20 -0700818 if let Some(kid) = key_id_guard {
819 Self::store_upgraded_keyblob(
820 kid,
821 blob_metadata.km_uuid(),
822 key_blob,
823 &upgraded_blob,
824 )
825 .context(
826 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000827 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000828 }
829
Janis Danisevskisaec14592020-11-12 09:41:49 -0800830 match f(&upgraded_blob) {
831 Ok(v) => Ok((v, Some(upgraded_blob))),
832 Err(e) => Err(e).context(concat!(
833 "In upgrade_keyblob_if_required_with: ",
834 "Failed to perform operation on second try."
835 )),
836 }
837 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700838 result => {
839 if let Some(kid) = key_id_guard {
840 if key_blob.force_reencrypt() {
841 Self::store_upgraded_keyblob(
842 kid,
843 blob_metadata.km_uuid(),
844 key_blob,
845 key_blob,
846 )
847 .context(concat!(
848 "In upgrade_keyblob_if_required_with: ",
849 "store_upgraded_keyblob failed in forced reencrypt"
850 ))?;
851 }
852 }
853 result
854 .map(|v| (v, None))
855 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
856 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800857 }
858 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800859
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700860 fn convert_storage_key_to_ephemeral(
861 &self,
862 storage_key: &KeyDescriptor,
863 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800864 if storage_key.domain != Domain::BLOB {
865 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
866 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
867 "Key must be of Domain::BLOB"
868 ));
869 }
870 let key_blob = storage_key
871 .blob
872 .as_ref()
873 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
874 .context(
875 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
876 )?;
877
878 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700879 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Satya Tangirala3361b612021-03-08 14:36:11 -0800880 .context("In convert_storage_key_to_ephemeral: Check permission")?;
881
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700882 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700883 match {
884 let _wp = self.watch_millis(
885 concat!(
886 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
887 "calling convertStorageKeyToEphemeral (1)"
888 ),
889 500,
890 );
891 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
892 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700893 Ok(result) => {
894 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
895 }
896 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700897 let upgraded_blob = {
898 let _wp = self.watch_millis(
899 "In convert_storage_key_to_ephemeral: calling upgradeKey",
900 500,
901 );
902 map_km_error(km_dev.upgradeKey(key_blob, &[]))
903 }
904 .context("In convert_storage_key_to_ephemeral: Failed to upgrade key blob.")?;
905 let ephemeral_key = {
906 let _wp = self.watch_millis(
907 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
908 500,
909 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700910 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700911 }
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700912 .context(concat!(
913 "In convert_storage_key_to_ephemeral: ",
914 "Failed to retrieve ephemeral key (after upgrade)."
915 ))?;
916 Ok(EphemeralStorageKeyResponse {
917 ephemeralKey: ephemeral_key,
918 upgradedBlob: Some(upgraded_blob),
919 })
920 }
921 Err(e) => Err(e)
922 .context("In convert_storage_key_to_ephemeral: Failed to retrieve ephemeral key."),
923 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800924 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800925
926 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
927 if key.domain != Domain::BLOB {
928 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
929 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
930 }
931
932 let key_blob = key
933 .blob
934 .as_ref()
935 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
936 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
937
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700938 check_key_permission(KeyPerm::Delete, key, &None)
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800939 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
940
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700941 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700942 {
943 let _wp =
944 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700945 map_km_error(km_dev.deleteKey(key_blob)).context("In keymint device deleteKey")
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700946 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800947 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700948}
949
950impl binder::Interface for KeystoreSecurityLevel {}
951
952impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700953 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700954 &self,
955 key: &KeyDescriptor,
956 operation_parameters: &[KeyParameter],
957 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700958 ) -> binder::public_api::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000959 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700960 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700961 }
962 fn generateKey(
963 &self,
964 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700965 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700966 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700967 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700968 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700969 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000970 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
971 // time than other operations
972 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000973 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000974 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +0100975 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000976 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700977 }
978 fn importKey(
979 &self,
980 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700981 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700982 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700983 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700984 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700985 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000986 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000987 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000988 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +0100989 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000990 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700991 }
992 fn importWrappedKey(
993 &self,
994 key: &KeyDescriptor,
995 wrapping_key: &KeyDescriptor,
996 masking_key: Option<&[u8]>,
997 params: &[KeyParameter],
998 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700999 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001000 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001001 let result =
1002 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001003 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001004 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001005 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001006 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001007 fn convertStorageKeyToEphemeral(
1008 &self,
1009 storage_key: &KeyDescriptor,
Janis Danisevskisb2434d02021-04-20 12:49:27 -07001010 ) -> binder::public_api::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001011 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001012 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1013 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001014 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001015 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001016 let result = self.delete_key(key);
1017 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1018 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001019 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001020}