blob: 7a27452a0121db8c98aac1dc7680bdaa33e0c26d [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 Danisevskisf84d0b02022-01-26 14:11:14 -080021use crate::database::{BlobInfo, CertificateInfo, KeyIdGuard};
Alice Wang849cfe42023-11-10 12:43:36 +000022use crate::error::{
23 self, map_km_error, map_or_log_err, wrapped_rkpd_error_to_ks_error, Error, ErrorCode,
24};
Alice Wangbf6a6932023-11-07 11:47:12 +000025use crate::globals::{
26 get_remotely_provisioned_component_name, DB, ENFORCEMENTS, LEGACY_IMPORTER, SUPER_KEY,
27};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070028use crate::key_parameter::KeyParameter as KsKeyParam;
29use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000030use crate::ks_err;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000031use crate::metrics_store::log_key_creation_event_stats;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070032use crate::remote_provisioning::RemProvState;
33use crate::super_key::{KeyBlob, SuperKeyManager};
34use crate::utils::{
Seth Moore66d9e902022-03-16 17:20:31 -070035 check_device_attestation_permissions, check_key_permission,
36 check_unique_id_attestation_permissions, is_device_id_attestation_tag,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070037 key_characteristics_to_internal, uid_to_android_user, watchdog as wd,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070038};
39use crate::{
40 database::{
41 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
42 KeyMetaEntry, KeyType, SubComponentType, Uuid,
43 },
44 operation::KeystoreOperation,
45 operation::LoggingInfo,
46 operation::OperationDb,
47 permission::KeyPerm,
48};
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070049use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
Shawn Willden708744a2020-12-11 13:05:27 +000050use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070051 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070052 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
53 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080054 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
55 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070056};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000057use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070058use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070059 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
Janis Danisevskisb2434d02021-04-20 12:49:27 -070060 Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
61 IKeystoreOperation::IKeystoreOperation, IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070062 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000063 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, ResponseCode::ResponseCode,
Janis Danisevskis1af91262020-08-10 14:58:08 -070064};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080065use anyhow::{anyhow, Context, Result};
Alice Wang01c16b62023-11-07 14:27:49 +000066use rkpd_client::store_rkpd_attestation_key;
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000067use std::convert::TryInto;
68use std::time::SystemTime;
Janis Danisevskis1af91262020-08-10 14:58:08 -070069
70/// Implementation of the IKeystoreSecurityLevel Interface.
71pub struct KeystoreSecurityLevel {
72 security_level: SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070073 keymint: Strong<dyn IKeyMintDevice>,
Max Bires8e93d2b2021-01-14 13:17:59 -080074 hw_info: KeyMintHardwareInfo,
75 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070076 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080077 rem_prov_state: RemProvState,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070078 id_rotation_state: IdRotationState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070079}
80
Janis Danisevskis1af91262020-08-10 14:58:08 -070081// Blob of 32 zeroes used as empty masking key.
82static ZERO_BLOB_32: &[u8] = &[0; 32];
83
Janis Danisevskis2c084012021-01-31 22:23:17 -080084// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
85// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
86const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
87
Janis Danisevskis1af91262020-08-10 14:58:08 -070088impl KeystoreSecurityLevel {
89 /// Creates a new security level instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +000090 /// BnKeystoreSecurityLevel proxy object. It also enables
91 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070092 /// we need it for checking keystore permissions.
93 pub fn new_native_binder(
94 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070095 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080096 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080097 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000098 .context(ks_err!("KeystoreSecurityLevel::new_native_binder."))?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000099 let result = BnKeystoreSecurityLevel::new_binder(
100 Self {
101 security_level,
102 keymint: dev,
103 hw_info,
104 km_uuid,
105 operation_db: OperationDb::new(),
106 rem_prov_state: RemProvState::new(security_level, km_uuid),
107 id_rotation_state,
108 },
109 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
110 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800111 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700112 }
113
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700114 fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
115 let sec_level = self.security_level;
116 wd::watch_millis_with(id, millis, move || format!("SecurityLevel {:?}", sec_level))
117 }
118
Janis Danisevskis1af91262020-08-10 14:58:08 -0700119 fn store_new_key(
120 &self,
121 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700122 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000123 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000124 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700125 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700126 let KeyCreationResult {
127 keyBlob: key_blob,
128 keyCharacteristics: key_characteristics,
129 certificateChain: mut certificate_chain,
130 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700131
Max Bires8e93d2b2021-01-14 13:17:59 -0800132 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700133 match certificate_chain.len() {
134 0 => None,
135 _ => Some(certificate_chain.remove(0).encodedCertificate),
136 },
137 match certificate_chain.len() {
138 0 => None,
139 _ => Some(
140 certificate_chain
141 .iter()
Chariseea1e1c482022-02-26 01:26:35 +0000142 .flat_map(|c| c.encodedCertificate.iter())
Shawn Willdendbdac602021-01-12 22:35:16 -0700143 .copied()
144 .collect(),
145 ),
146 },
147 );
148
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000149 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
150
151 key_parameters.push(KsKeyParam::new(
152 KsKeyParamValue::UserID(user_id as i32),
153 SecurityLevel::SOFTWARE,
154 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700155
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000156 let creation_date = DateTime::now().context(ks_err!("Trying to make creation time."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800157
Janis Danisevskis1af91262020-08-10 14:58:08 -0700158 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800159 Domain::BLOB => KeyDescriptor {
160 domain: Domain::BLOB,
161 blob: Some(key_blob.to_vec()),
162 ..Default::default()
163 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700164 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800165 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800166 let mut db = db.borrow_mut();
167
168 let (key_blob, mut blob_metadata) = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800169 .read()
170 .unwrap()
Satya Tangirala60671e32021-03-04 16:12:19 -0800171 .handle_super_encryption_on_key_init(
172 &mut db,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800173 &LEGACY_IMPORTER,
Satya Tangirala60671e32021-03-04 16:12:19 -0800174 &(key.domain),
175 &key_parameters,
176 flags,
177 user_id,
178 &key_blob,
179 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000180 .context(ks_err!("Failed to handle super encryption."))?;
Satya Tangirala60671e32021-03-04 16:12:19 -0800181
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800182 let mut key_metadata = KeyMetaData::new();
183 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800184 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800185
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800186 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800187 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800188 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700189 KeyType::Client,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800190 &key_parameters,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800191 &BlobInfo::new(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800192 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800193 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800194 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800195 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000196 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700197 Ok(KeyDescriptor {
198 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800199 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700200 ..Default::default()
201 })
202 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000203 .context(ks_err!())?,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700204 };
205
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700206 Ok(KeyMetadata {
207 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700208 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800209 certificate: cert_info.take_cert(),
210 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700211 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800212 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700213 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700214 }
215
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700216 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700217 &self,
218 key: &KeyDescriptor,
219 operation_parameters: &[KeyParameter],
220 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700221 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700222 let caller_uid = ThreadState::get_calling_uid();
223 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
224 // so that we can use it by reference like the blob provided by the key descriptor.
225 // Otherwise, we would have to clone the blob from the key descriptor.
226 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800227 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700228 Domain::BLOB => {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700229 check_key_permission(KeyPerm::Use, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000230 .context(ks_err!("checking use permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800231 if forced {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000232 check_key_permission(KeyPerm::ReqForcedOp, key, &None)
233 .context(ks_err!("checking forced permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800234 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700235 (
236 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700237 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700238 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000239 return Err(Error::sys()).context(ks_err!(
240 "Key blob must be specified when \
241 using Domain::BLOB."
242 ));
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700243 }
244 },
245 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000246 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000247 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700248 )
249 }
250 _ => {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800251 let super_key = SUPER_KEY
252 .read()
253 .unwrap()
Eric Biggers673d34a2023-10-18 01:54:18 +0000254 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800255 let (key_id_guard, mut key_entry) = DB
256 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800257 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000258 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700259 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000260 KeyType::Client,
261 KeyEntryLoadBits::KM,
262 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800263 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700264 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800265 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700266 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800267 }
268 Ok(())
269 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000270 )
271 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700272 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000273 .context(ks_err!("Failed to load key blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800274
275 let (blob, blob_metadata) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000276 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(ks_err!(
277 "Successfully loaded key entry, \
278 but KM blob was missing."
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800279 ))?;
280 scoping_blob = blob;
281
Qi Wub9433b52020-12-01 14:52:46 +0800282 (
283 &scoping_blob,
284 Some((key_id_guard.id(), key_entry.into_key_parameters())),
285 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000286 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800287 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700288 }
289 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700290
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700291 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700292 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000293 .context(ks_err!("No operation purpose specified.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800294 |kp| match kp.value {
295 KeyParameterValue::KeyPurpose(p) => Ok(p),
296 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000297 .context(ks_err!("Malformed KeyParameter.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800298 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700299 )?;
300
Satya Tangirala2642ff92021-04-15 01:57:00 -0700301 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
302 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
303 let op_params: Vec<KeyParameter> =
304 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
305 let operation_parameters = op_params.as_slice();
306
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800307 let (immediate_hat, mut auth_info) = ENFORCEMENTS
308 .authorize_create(
309 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800310 key_properties.as_ref(),
311 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700312 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800313 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000314 .context(ks_err!())?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000315
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000316 let km_blob = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800317 .read()
318 .unwrap()
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000319 .unwrap_key_if_required(&blob_metadata, km_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000320 .context(ks_err!("Failed to handle super encryption."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000321
Janis Danisevskisaec14592020-11-12 09:41:49 -0800322 let (begin_result, upgraded_blob) = self
323 .upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800324 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700325 &km_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800326 blob_metadata.km_uuid().copied(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700327 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800328 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700329 match map_km_error({
330 let _wp = self.watch_millis(
331 "In KeystoreSecurityLevel::create_operation: calling begin",
332 500,
333 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700334 self.keymint.begin(
335 purpose,
336 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700337 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700338 immediate_hat.as_ref(),
339 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700340 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800341 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800342 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800343 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700344 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100345 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
346 if let Some((key_id, _)) = key_properties {
347 if let Ok(Some(key)) =
348 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
349 {
350 log_key_integrity_violation(&key);
351 } else {
352 log::error!("Failed to load key descriptor for audit log");
353 }
354 }
355 return v;
356 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800357 v => return v,
358 }
359 },
360 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000361 .context(ks_err!("Failed to begin operation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700362
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800363 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000364
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000365 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
366
Janis Danisevskis1af91262020-08-10 14:58:08 -0700367 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700368 Some(km_op) => self.operation_db.create_operation(
369 km_op,
370 caller_uid,
371 auth_info,
372 forced,
373 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
374 ),
375 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000376 return Err(Error::sys()).context(ks_err!(
377 "Begin operation returned successfully, \
378 but did not return a valid operation."
379 ));
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700380 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700381 };
382
Stephen Crane23cf7242022-01-19 17:49:46 +0000383 let op_binder: binder::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700384 KeystoreOperation::new_native_binder(operation)
385 .as_binder()
386 .into_interface()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000387 .context(ks_err!("Failed to create IKeystoreOperation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700388
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700389 Ok(CreateOperationResponse {
390 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000391 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700392 parameters: match begin_result.params.len() {
393 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700394 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700395 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800396 // An upgraded blob should only be returned if the caller has permission
397 // to use Domain::BLOB keys. If we got to this point, we already checked
398 // that the caller had that permission.
399 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700400 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700401 }
402
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000403 fn add_required_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700404 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800405 uid: u32,
406 params: &[KeyParameter],
407 key: &KeyDescriptor,
408 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800409 let mut result = params.to_vec();
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000410
Tri Vo74997ed2023-07-20 17:57:19 -0400411 // Prevent callers from specifying the CREATION_DATETIME tag.
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000412 if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000413 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
414 "KeystoreSecurityLevel::add_required_parameters: \
415 Specifying Tag::CREATION_DATETIME is not allowed."
416 ));
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000417 }
418
Tri Vo74997ed2023-07-20 17:57:19 -0400419 // Use this variable to refer to notion of "now". This eliminates discrepancies from
420 // quering the clock multiple times.
421 let creation_datetime = SystemTime::now();
422
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800423 // Add CREATION_DATETIME only if the backend version Keymint V1 (100) or newer.
424 if self.hw_info.versionNumber >= 100 {
425 result.push(KeyParameter {
426 tag: Tag::CREATION_DATETIME,
427 value: KeyParameterValue::DateTime(
Tri Vo74997ed2023-07-20 17:57:19 -0400428 creation_datetime
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800429 .duration_since(SystemTime::UNIX_EPOCH)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000430 .context(ks_err!(
431 "KeystoreSecurityLevel::add_required_parameters: \
432 Failed to get epoch time."
433 ))?
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800434 .as_millis()
435 .try_into()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000436 .context(ks_err!(
437 "KeystoreSecurityLevel::add_required_parameters: \
438 Failed to convert epoch time."
439 ))?,
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800440 ),
441 });
442 }
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000443
Janis Danisevskis2c084012021-01-31 22:23:17 -0800444 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800445 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700446 let aaid = {
447 let _wp = self.watch_millis(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000448 "In KeystoreSecurityLevel::add_required_parameters calling: get_aaid",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700449 500,
450 );
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000451 keystore2_aaid::get_aaid(uid)
452 .map_err(|e| anyhow!(ks_err!("get_aaid returned status {}.", e)))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700453 }?;
454
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800455 result.push(KeyParameter {
456 tag: Tag::ATTESTATION_APPLICATION_ID,
457 value: KeyParameterValue::Blob(aaid),
458 });
459 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800460
Janis Danisevskise766edc2021-02-06 12:16:26 -0800461 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Seth Moore66d9e902022-03-16 17:20:31 -0700462 if check_key_permission(KeyPerm::GenUniqueId, key, &None).is_err()
463 && check_unique_id_attestation_permissions().is_err()
464 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000465 return Err(Error::perm()).context(ks_err!(
466 "Caller does not have the permission to generate a unique ID"
467 ));
Seth Moore66d9e902022-03-16 17:20:31 -0700468 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000469 if self
470 .id_rotation_state
Tri Vo74997ed2023-07-20 17:57:19 -0400471 .had_factory_reset_since_id_rotation(&creation_datetime)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000472 .context(ks_err!("Call to had_factory_reset_since_id_rotation failed."))?
473 {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000474 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700475 tag: Tag::RESET_SINCE_ID_ROTATION,
476 value: KeyParameterValue::BoolValue(true),
477 })
478 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800479 }
480
Bram Bonné5d6c5102021-02-24 15:09:18 +0100481 // If the caller requests any device identifier attestation tag, check that they hold the
482 // correct Android permission.
483 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000484 check_device_attestation_permissions().context(ks_err!(
Bram Bonné5d6c5102021-02-24 15:09:18 +0100485 "Caller does not have the permission to attest device identifiers."
486 ))?;
487 }
488
Janis Danisevskis2c084012021-01-31 22:23:17 -0800489 // If we are generating/importing an asymmetric key, we need to make sure
490 // that NOT_BEFORE and NOT_AFTER are present.
491 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
492 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
493 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
494 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
495 result.push(KeyParameter {
496 tag: Tag::CERTIFICATE_NOT_BEFORE,
497 value: KeyParameterValue::DateTime(0),
498 })
499 }
500 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
501 result.push(KeyParameter {
502 tag: Tag::CERTIFICATE_NOT_AFTER,
503 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
504 })
505 }
506 }
507 _ => {}
508 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800509 Ok(result)
510 }
511
Janis Danisevskis1af91262020-08-10 14:58:08 -0700512 fn generate_key(
513 &self,
514 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700515 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700516 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700517 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700518 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700519 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700520 if key.domain != Domain::BLOB && key.alias.is_none() {
521 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000522 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700523 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000524 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700525
526 let key = match key.domain {
527 Domain::APP => KeyDescriptor {
528 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000529 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700530 alias: key.alias.clone(),
531 blob: None,
532 },
533 _ => key.clone(),
534 };
535
536 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700537 // Must return on error for security reasons.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000538 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700539
540 let attestation_key_info = match (key.domain, attest_key_descriptor) {
541 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800542 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700543 .with(|db| {
544 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800545 &key,
546 caller_uid,
547 attest_key_descriptor,
548 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700549 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800550 &mut db.borrow_mut(),
551 )
552 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000553 .context(ks_err!("Trying to get an attestation key"))?,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800554 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700555 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000556 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000557 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800558
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700559 let creation_result = match attestation_key_info {
560 Some(AttestationKeyInfo::UserGenerated {
561 key_id_guard,
562 blob,
563 blob_metadata,
564 issuer_subject,
565 }) => self
566 .upgrade_keyblob_if_required_with(
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700567 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700568 &KeyBlob::Ref(&blob),
Max Bires55620ff2022-02-11 13:34:15 -0800569 blob_metadata.km_uuid().copied(),
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700570 &params,
571 |blob| {
572 let attest_key = Some(AttestationKey {
573 keyBlob: blob.to_vec(),
574 attestKeyParams: vec![],
575 issuerSubjectName: issuer_subject.clone(),
576 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700577 map_km_error({
578 let _wp = self.watch_millis(
579 concat!(
580 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
581 "calling generate_key."
582 ),
583 5000, // Generate can take a little longer.
584 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700585 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700586 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700587 },
588 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000589 .context(ks_err!("Using user generated attestation key."))
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700590 .map(|(result, _)| result),
Tri Vob5e43d12022-12-21 08:54:14 -0800591 Some(AttestationKeyInfo::RkpdProvisioned { attestation_key, attestation_certs }) => {
592 self.upgrade_rkpd_keyblob_if_required_with(&attestation_key.keyBlob, &[], |blob| {
593 map_km_error({
594 let _wp = self.watch_millis(
595 concat!(
596 "In KeystoreSecurityLevel::generate_key (RkpdProvisioned): ",
597 "calling generate_key.",
598 ),
599 5000, // Generate can take a little longer.
600 );
601 let dynamic_attest_key = Some(AttestationKey {
602 keyBlob: blob.to_vec(),
603 attestKeyParams: vec![],
604 issuerSubjectName: attestation_key.issuerSubjectName.clone(),
605 });
606 self.keymint.generateKey(&params, dynamic_attest_key.as_ref())
607 })
608 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000609 .context(ks_err!("While generating Key with remote provisioned attestation key."))
Tri Vob5e43d12022-12-21 08:54:14 -0800610 .map(|(mut result, _)| {
611 result.certificateChain.push(attestation_certs);
612 result
613 })
614 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700615 None => map_km_error({
616 let _wp = self.watch_millis(
617 concat!(
618 "In KeystoreSecurityLevel::generate_key (No attestation): ",
619 "calling generate_key.",
620 ),
621 5000, // Generate can take a little longer.
622 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700623 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700624 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000625 .context(ks_err!("While generating Key without explicit attestation key.")),
Max Bires97f96812021-02-23 23:44:57 -0800626 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000627 .context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700628
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000629 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000630 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631 }
632
633 fn import_key(
634 &self,
635 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700636 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700637 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700638 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700639 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700640 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700641 if key.domain != Domain::BLOB && key.alias.is_none() {
642 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000643 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700644 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000645 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700646
647 let key = match key.domain {
648 Domain::APP => KeyDescriptor {
649 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000650 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700651 alias: key.alias.clone(),
652 blob: None,
653 },
654 _ => key.clone(),
655 };
656
657 // import_key requires the rebind permission.
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000658 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!("In import_key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700659
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700660 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000661 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000662 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800663
Janis Danisevskis1af91262020-08-10 14:58:08 -0700664 let format = params
665 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700666 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700667 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000668 .context(ks_err!("No KeyParameter 'Algorithm'."))
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800669 .and_then(|p| match &p.value {
670 KeyParameterValue::Algorithm(Algorithm::AES)
671 | KeyParameterValue::Algorithm(Algorithm::HMAC)
672 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
673 KeyParameterValue::Algorithm(Algorithm::RSA)
674 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
675 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000676 .context(ks_err!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700677 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000678 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700679
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700680 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700681 let creation_result = map_km_error({
682 let _wp =
683 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
684 km_dev.importKey(&params, format, key_data, None /* attestKey */)
685 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000686 .context(ks_err!("Trying to call importKey"))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700687
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000688 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000689 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700690 }
691
692 fn import_wrapped_key(
693 &self,
694 key: &KeyDescriptor,
695 wrapping_key: &KeyDescriptor,
696 masking_key: Option<&[u8]>,
697 params: &[KeyParameter],
698 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700699 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800700 let wrapped_data: &[u8] = match key {
701 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
702 | KeyDescriptor {
703 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
704 } => blob,
705 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000706 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(ks_err!(
707 "Alias and blob must be specified and domain must be APP or SELINUX. {:?}",
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800708 key
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000709 ));
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800710 }
711 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700712
Janis Danisevskisaec14592020-11-12 09:41:49 -0800713 if wrapping_key.domain == Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000714 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
715 .context(ks_err!("Import wrapped key not supported for self managed blobs."));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800716 }
717
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000718 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000719 let user_id = uid_to_android_user(caller_uid);
720
Janis Danisevskis1af91262020-08-10 14:58:08 -0700721 let key = match key.domain {
722 Domain::APP => KeyDescriptor {
723 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000724 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700725 alias: key.alias.clone(),
726 blob: None,
727 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800728 Domain::SELINUX => KeyDescriptor {
729 domain: Domain::SELINUX,
730 nspace: key.nspace,
731 alias: key.alias.clone(),
732 blob: None,
733 },
734 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700735 };
736
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800737 // Import_wrapped_key requires the rebind permission for the new key.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000738 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700739
Eric Biggers673d34a2023-10-18 01:54:18 +0000740 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800741
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000742 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700743 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800744 LEGACY_IMPORTER.with_try_import(&key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000745 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700746 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000747 KeyType::Client,
748 KeyEntryLoadBits::KM,
749 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700750 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000751 )
752 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700753 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000754 .context(ks_err!("Failed to load wrapping key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000755
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000756 let (wrapping_key_blob, wrapping_blob_metadata) =
757 wrapping_key_entry.take_key_blob_info().ok_or_else(error::Error::sys).context(
758 ks_err!("No km_blob after successfully loading key. This should never happen."),
759 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000760
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800761 let wrapping_key_blob = SUPER_KEY
762 .read()
763 .unwrap()
764 .unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000765 .context(ks_err!("Failed to handle super encryption for wrapping key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700766
Janis Danisevskis1af91262020-08-10 14:58:08 -0700767 // km_dev.importWrappedKey does not return a certificate chain.
768 // TODO Do we assume that all wrapped keys are symmetric?
769 // let certificate_chain: Vec<KmCertificate> = Default::default();
770
771 let pw_sid = authenticators
772 .iter()
773 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700774 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700775 _ => None,
776 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800777 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700778
779 let fp_sid = authenticators
780 .iter()
781 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700782 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700783 _ => None,
784 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800785 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700786
787 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
788
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800789 let (creation_result, _) = self
790 .upgrade_keyblob_if_required_with(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800791 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700792 &wrapping_key_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800793 wrapping_blob_metadata.km_uuid().copied(),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800794 &[],
795 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700796 let _wp = self.watch_millis(
797 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
798 500,
799 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700800 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800801 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800802 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800803 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700804 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800805 pw_sid,
806 fp_sid,
807 ))?;
808 Ok(creation_result)
809 },
810 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000811 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700812
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000813 self.store_new_key(key, creation_result, user_id, None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000814 .context(ks_err!("Trying to store the new key."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700815 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800816
Paul Crowley7a658392021-03-18 17:08:20 -0700817 fn store_upgraded_keyblob(
818 key_id_guard: KeyIdGuard,
Max Bires55620ff2022-02-11 13:34:15 -0800819 km_uuid: Option<Uuid>,
Paul Crowley7a658392021-03-18 17:08:20 -0700820 key_blob: &KeyBlob,
821 upgraded_blob: &[u8],
822 ) -> Result<()> {
823 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700824 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000825 .context(ks_err!("Failed to handle super encryption."))?;
Paul Crowley7a658392021-03-18 17:08:20 -0700826
Paul Crowley44c02da2021-04-08 17:04:43 +0000827 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700828 if let Some(uuid) = km_uuid {
Max Bires55620ff2022-02-11 13:34:15 -0800829 new_blob_metadata.add(BlobMetaEntry::KmUuid(uuid));
Paul Crowley7a658392021-03-18 17:08:20 -0700830 }
831
832 DB.with(|db| {
833 let mut db = db.borrow_mut();
834 db.set_blob(
835 &key_id_guard,
836 SubComponentType::KEY_BLOB,
837 Some(&upgraded_blob_to_be_stored),
838 Some(&new_blob_metadata),
839 )
840 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000841 .context(ks_err!("Failed to insert upgraded blob into the database."))
Paul Crowley7a658392021-03-18 17:08:20 -0700842 }
843
Janis Danisevskisaec14592020-11-12 09:41:49 -0800844 fn upgrade_keyblob_if_required_with<T, F>(
845 &self,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800846 mut key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700847 key_blob: &KeyBlob,
Max Bires55620ff2022-02-11 13:34:15 -0800848 km_uuid: Option<Uuid>,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800849 params: &[KeyParameter],
850 f: F,
851 ) -> Result<(T, Option<Vec<u8>>)>
852 where
853 F: Fn(&[u8]) -> Result<T, Error>,
854 {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800855 let (v, upgraded_blob) = crate::utils::upgrade_keyblob_if_required_with(
David Drysdale5accbaa2023-04-12 18:47:10 +0100856 &*self.keymint,
857 self.hw_info.versionNumber,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800858 key_blob,
859 params,
860 f,
861 |upgraded_blob| {
862 if key_id_guard.is_some() {
863 // Unwrap cannot panic, because the is_some was true.
864 let kid = key_id_guard.take().unwrap();
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000865 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, upgraded_blob)
866 .context(ks_err!("store_upgraded_keyblob failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800867 } else {
868 Ok(())
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000869 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800870 },
871 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000872 .context(ks_err!())?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000873
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800874 // If no upgrade was needed, use the opportunity to reencrypt the blob if required
875 // and if the a key_id_guard is held. Note: key_id_guard can only be Some if no
876 // upgrade was performed above and if one was given in the first place.
877 if key_blob.force_reencrypt() {
878 if let Some(kid) = key_id_guard {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000879 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, key_blob)
880 .context(ks_err!("store_upgraded_keyblob failed in forced reencrypt"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700881 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800882 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800883 Ok((v, upgraded_blob))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800884 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800885
Tri Vob5e43d12022-12-21 08:54:14 -0800886 fn upgrade_rkpd_keyblob_if_required_with<T, F>(
887 &self,
888 key_blob: &[u8],
889 params: &[KeyParameter],
890 f: F,
891 ) -> Result<(T, Option<Vec<u8>>)>
892 where
893 F: Fn(&[u8]) -> Result<T, Error>,
894 {
Alice Wangbf6a6932023-11-07 11:47:12 +0000895 let rpc_name = get_remotely_provisioned_component_name(&self.security_level)
896 .context(ks_err!("Trying to get IRPC name."))?;
Tri Vob5e43d12022-12-21 08:54:14 -0800897 crate::utils::upgrade_keyblob_if_required_with(
898 &*self.keymint,
David Drysdale5accbaa2023-04-12 18:47:10 +0100899 self.hw_info.versionNumber,
Tri Vob5e43d12022-12-21 08:54:14 -0800900 key_blob,
901 params,
902 f,
903 |upgraded_blob| {
Alice Wang4277d2e2023-11-08 09:15:54 +0000904 let _wp = wd::watch_millis("Calling store_rkpd_attestation_key()", 500);
Alice Wang849cfe42023-11-10 12:43:36 +0000905 if let Err(e) = store_rkpd_attestation_key(&rpc_name, key_blob, upgraded_blob) {
906 Err(wrapped_rkpd_error_to_ks_error(&e)).context(format!("{e:?}"))
907 } else {
908 Ok(())
909 }
Tri Vob5e43d12022-12-21 08:54:14 -0800910 },
911 )
912 .context(ks_err!())
913 }
914
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700915 fn convert_storage_key_to_ephemeral(
916 &self,
917 storage_key: &KeyDescriptor,
918 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800919 if storage_key.domain != Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000920 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
921 .context(ks_err!("Key must be of Domain::BLOB"));
Satya Tangirala3361b612021-03-08 14:36:11 -0800922 }
923 let key_blob = storage_key
924 .blob
925 .as_ref()
926 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000927 .context(ks_err!("No key blob specified"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800928
929 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700930 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000931 .context(ks_err!("Check permission"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800932
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700933 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700934 match {
935 let _wp = self.watch_millis(
936 concat!(
937 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
938 "calling convertStorageKeyToEphemeral (1)"
939 ),
940 500,
941 );
942 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
943 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700944 Ok(result) => {
945 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
946 }
947 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700948 let upgraded_blob = {
949 let _wp = self.watch_millis(
950 "In convert_storage_key_to_ephemeral: calling upgradeKey",
951 500,
952 );
953 map_km_error(km_dev.upgradeKey(key_blob, &[]))
954 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000955 .context(ks_err!("Failed to upgrade key blob."))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700956 let ephemeral_key = {
957 let _wp = self.watch_millis(
958 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
959 500,
960 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700961 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700962 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000963 .context(ks_err!(
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700964 "Failed to retrieve ephemeral key (after upgrade)."
965 ))?;
966 Ok(EphemeralStorageKeyResponse {
967 ephemeralKey: ephemeral_key,
968 upgradedBlob: Some(upgraded_blob),
969 })
970 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000971 Err(e) => Err(e).context(ks_err!("Failed to retrieve ephemeral key.")),
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700972 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800973 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800974
975 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
976 if key.domain != Domain::BLOB {
977 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000978 .context(ks_err!("delete_key: Key must be of Domain::BLOB"));
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800979 }
980
981 let key_blob = key
982 .blob
983 .as_ref()
984 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000985 .context(ks_err!("delete_key: No key blob specified"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800986
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700987 check_key_permission(KeyPerm::Delete, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000988 .context(ks_err!("delete_key: Checking delete permissions"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800989
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700990 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700991 {
992 let _wp =
993 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000994 map_km_error(km_dev.deleteKey(key_blob)).context(ks_err!("keymint device deleteKey"))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700995 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800996 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700997}
998
999impl binder::Interface for KeystoreSecurityLevel {}
1000
1001impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001002 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -07001003 &self,
1004 key: &KeyDescriptor,
1005 operation_parameters: &[KeyParameter],
1006 forced: bool,
Stephen Crane23cf7242022-01-19 17:49:46 +00001007 ) -> binder::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001008 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001009 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001010 }
1011 fn generateKey(
1012 &self,
1013 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001014 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001015 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001016 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001017 entropy: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001018 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001019 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1020 // time than other operations
1021 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001022 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001023 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001024 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001025 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001026 }
1027 fn importKey(
1028 &self,
1029 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001030 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001031 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001032 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001033 key_data: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001034 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001035 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001036 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001037 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001038 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001039 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001040 }
1041 fn importWrappedKey(
1042 &self,
1043 key: &KeyDescriptor,
1044 wrapping_key: &KeyDescriptor,
1045 masking_key: Option<&[u8]>,
1046 params: &[KeyParameter],
1047 authenticators: &[AuthenticatorSpec],
Stephen Crane23cf7242022-01-19 17:49:46 +00001048 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001049 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001050 let result =
1051 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001052 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001053 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001054 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001055 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001056 fn convertStorageKeyToEphemeral(
1057 &self,
1058 storage_key: &KeyDescriptor,
Stephen Crane23cf7242022-01-19 17:49:46 +00001059 ) -> binder::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001060 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001061 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1062 }
Stephen Crane23cf7242022-01-19 17:49:46 +00001063 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001064 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001065 let result = self.delete_key(key);
1066 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1067 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001068 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001069}
Alice Wangbf6a6932023-11-07 11:47:12 +00001070
1071#[cfg(test)]
1072mod tests {
1073 use super::*;
1074 use crate::error::map_km_error;
1075 use crate::globals::get_keymint_device;
Alice Wangbf6a6932023-11-07 11:47:12 +00001076 use crate::utils::upgrade_keyblob_if_required_with;
1077 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
1078 Algorithm::Algorithm, AttestationKey::AttestationKey, KeyParameter::KeyParameter,
1079 KeyParameterValue::KeyParameterValue, Tag::Tag,
1080 };
1081 use keystore2_crypto::parse_subject_from_certificate;
Alice Wang01c16b62023-11-07 14:27:49 +00001082 use rkpd_client::get_rkpd_attestation_key;
Alice Wangbf6a6932023-11-07 11:47:12 +00001083
1084 #[test]
1085 // This is a helper for a manual test. We want to check that after a system upgrade RKPD
1086 // attestation keys can also be upgraded and stored again with RKPD. The steps are:
1087 // 1. Run this test and check in stdout that no key upgrade happened.
1088 // 2. Perform a system upgrade.
1089 // 3. Run this test and check in stdout that key upgrade did happen.
1090 //
1091 // Note that this test must be run with that same UID every time. Running as root, i.e. UID 0,
1092 // should do the trick. Also, use "--nocapture" flag to get stdout.
1093 fn test_rkpd_attestation_key_upgrade() {
1094 binder::ProcessState::start_thread_pool();
1095 let security_level = SecurityLevel::TRUSTED_ENVIRONMENT;
1096 let (keymint, info, _) = get_keymint_device(&security_level).unwrap();
1097 let key_id = 0;
1098 let mut key_upgraded = false;
1099
1100 let rpc_name = get_remotely_provisioned_component_name(&security_level).unwrap();
1101 let key = get_rkpd_attestation_key(&rpc_name, key_id).unwrap();
1102 assert!(!key.keyBlob.is_empty());
1103 assert!(!key.encodedCertChain.is_empty());
1104
1105 upgrade_keyblob_if_required_with(
1106 &*keymint,
1107 info.versionNumber,
1108 &key.keyBlob,
1109 /*upgrade_params=*/ &[],
1110 /*km_op=*/
1111 |blob| {
1112 let params = vec![
1113 KeyParameter {
1114 tag: Tag::ALGORITHM,
1115 value: KeyParameterValue::Algorithm(Algorithm::AES),
1116 },
1117 KeyParameter {
1118 tag: Tag::ATTESTATION_CHALLENGE,
1119 value: KeyParameterValue::Blob(vec![0; 16]),
1120 },
1121 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(128) },
1122 ];
1123 let attestation_key = AttestationKey {
1124 keyBlob: blob.to_vec(),
1125 attestKeyParams: vec![],
1126 issuerSubjectName: parse_subject_from_certificate(&key.encodedCertChain)
1127 .unwrap(),
1128 };
1129
1130 map_km_error(keymint.generateKey(&params, Some(&attestation_key)))
1131 },
1132 /*new_blob_handler=*/
1133 |new_blob| {
1134 // This handler is only executed if a key upgrade was performed.
1135 key_upgraded = true;
Alice Wang4277d2e2023-11-08 09:15:54 +00001136 let _wp = wd::watch_millis("Calling store_rkpd_attestation_key()", 500);
Alice Wangbf6a6932023-11-07 11:47:12 +00001137 store_rkpd_attestation_key(&rpc_name, &key.keyBlob, new_blob).unwrap();
1138 Ok(())
1139 },
1140 )
1141 .unwrap();
1142
1143 if key_upgraded {
1144 println!("RKPD key was upgraded and stored with RKPD.");
1145 } else {
1146 println!("RKPD key was NOT upgraded.");
1147 }
1148 }
1149}