blob: 8abff77758aaba7585cbffb27d93bb459c5cf280 [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};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070022use crate::error::{self, map_km_error, map_or_log_err, Error, ErrorCode};
Alice Wangbf6a6932023-11-07 11:47:12 +000023use crate::globals::{
24 get_remotely_provisioned_component_name, DB, ENFORCEMENTS, LEGACY_IMPORTER, SUPER_KEY,
25};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070026use crate::key_parameter::KeyParameter as KsKeyParam;
27use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000028use crate::ks_err;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000029use crate::metrics_store::log_key_creation_event_stats;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070030use crate::remote_provisioning::RemProvState;
Tri Vob5e43d12022-12-21 08:54:14 -080031use crate::rkpd_client::store_rkpd_attestation_key;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070032use crate::super_key::{KeyBlob, SuperKeyManager};
33use crate::utils::{
Seth Moore66d9e902022-03-16 17:20:31 -070034 check_device_attestation_permissions, check_key_permission,
35 check_unique_id_attestation_permissions, is_device_id_attestation_tag,
David Drysdale746e1be2023-07-05 17:39:57 +010036 key_characteristics_to_internal, uid_to_android_user, watchdog as wd, UNDEFINED_NOT_AFTER,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070037};
38use crate::{
39 database::{
40 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
41 KeyMetaEntry, KeyType, SubComponentType, Uuid,
42 },
43 operation::KeystoreOperation,
44 operation::LoggingInfo,
45 operation::OperationDb,
46 permission::KeyPerm,
47};
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070048use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
Shawn Willden708744a2020-12-11 13:05:27 +000049use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070050 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070051 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
52 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080053 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
54 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070055};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000056use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070057use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070058 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
Janis Danisevskisb2434d02021-04-20 12:49:27 -070059 Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
60 IKeystoreOperation::IKeystoreOperation, IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070061 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000062 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, ResponseCode::ResponseCode,
Janis Danisevskis1af91262020-08-10 14:58:08 -070063};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080064use anyhow::{anyhow, Context, Result};
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000065use std::convert::TryInto;
66use std::time::SystemTime;
Janis Danisevskis1af91262020-08-10 14:58:08 -070067
68/// Implementation of the IKeystoreSecurityLevel Interface.
69pub struct KeystoreSecurityLevel {
70 security_level: SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070071 keymint: Strong<dyn IKeyMintDevice>,
Max Bires8e93d2b2021-01-14 13:17:59 -080072 hw_info: KeyMintHardwareInfo,
73 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070074 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080075 rem_prov_state: RemProvState,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070076 id_rotation_state: IdRotationState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070077}
78
Janis Danisevskis1af91262020-08-10 14:58:08 -070079// Blob of 32 zeroes used as empty masking key.
80static ZERO_BLOB_32: &[u8] = &[0; 32];
81
82impl KeystoreSecurityLevel {
83 /// Creates a new security level instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +000084 /// BnKeystoreSecurityLevel proxy object. It also enables
85 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070086 /// we need it for checking keystore permissions.
87 pub fn new_native_binder(
88 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070089 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080090 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080091 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000092 .context(ks_err!("KeystoreSecurityLevel::new_native_binder."))?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000093 let result = BnKeystoreSecurityLevel::new_binder(
94 Self {
95 security_level,
96 keymint: dev,
97 hw_info,
98 km_uuid,
99 operation_db: OperationDb::new(),
100 rem_prov_state: RemProvState::new(security_level, km_uuid),
101 id_rotation_state,
102 },
103 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
104 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800105 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700106 }
107
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700108 fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
109 let sec_level = self.security_level;
110 wd::watch_millis_with(id, millis, move || format!("SecurityLevel {:?}", sec_level))
111 }
112
Janis Danisevskis1af91262020-08-10 14:58:08 -0700113 fn store_new_key(
114 &self,
115 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700116 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000117 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000118 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700119 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700120 let KeyCreationResult {
121 keyBlob: key_blob,
122 keyCharacteristics: key_characteristics,
123 certificateChain: mut certificate_chain,
124 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700125
Max Bires8e93d2b2021-01-14 13:17:59 -0800126 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700127 match certificate_chain.len() {
128 0 => None,
129 _ => Some(certificate_chain.remove(0).encodedCertificate),
130 },
131 match certificate_chain.len() {
132 0 => None,
133 _ => Some(
134 certificate_chain
135 .iter()
Chariseea1e1c482022-02-26 01:26:35 +0000136 .flat_map(|c| c.encodedCertificate.iter())
Shawn Willdendbdac602021-01-12 22:35:16 -0700137 .copied()
138 .collect(),
139 ),
140 },
141 );
142
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000143 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
144
145 key_parameters.push(KsKeyParam::new(
146 KsKeyParamValue::UserID(user_id as i32),
147 SecurityLevel::SOFTWARE,
148 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700149
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000150 let creation_date = DateTime::now().context(ks_err!("Trying to make creation time."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800151
Janis Danisevskis1af91262020-08-10 14:58:08 -0700152 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800153 Domain::BLOB => KeyDescriptor {
154 domain: Domain::BLOB,
155 blob: Some(key_blob.to_vec()),
156 ..Default::default()
157 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700158 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800159 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800160 let mut db = db.borrow_mut();
161
162 let (key_blob, mut blob_metadata) = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800163 .read()
164 .unwrap()
Satya Tangirala60671e32021-03-04 16:12:19 -0800165 .handle_super_encryption_on_key_init(
166 &mut db,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800167 &LEGACY_IMPORTER,
Satya Tangirala60671e32021-03-04 16:12:19 -0800168 &(key.domain),
169 &key_parameters,
170 flags,
171 user_id,
172 &key_blob,
173 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000174 .context(ks_err!("Failed to handle super encryption."))?;
Satya Tangirala60671e32021-03-04 16:12:19 -0800175
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176 let mut key_metadata = KeyMetaData::new();
177 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800178 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800179
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800180 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800181 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800182 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700183 KeyType::Client,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800184 &key_parameters,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800185 &BlobInfo::new(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800186 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800187 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800188 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800189 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000190 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700191 Ok(KeyDescriptor {
192 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800193 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700194 ..Default::default()
195 })
196 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000197 .context(ks_err!())?,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700198 };
199
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700200 Ok(KeyMetadata {
201 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700202 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800203 certificate: cert_info.take_cert(),
204 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700205 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800206 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700207 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700208 }
209
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700210 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700211 &self,
212 key: &KeyDescriptor,
213 operation_parameters: &[KeyParameter],
214 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700215 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700216 let caller_uid = ThreadState::get_calling_uid();
217 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
218 // so that we can use it by reference like the blob provided by the key descriptor.
219 // Otherwise, we would have to clone the blob from the key descriptor.
220 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700222 Domain::BLOB => {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700223 check_key_permission(KeyPerm::Use, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000224 .context(ks_err!("checking use permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800225 if forced {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000226 check_key_permission(KeyPerm::ReqForcedOp, key, &None)
227 .context(ks_err!("checking forced permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800228 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700229 (
230 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700231 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700232 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000233 return Err(Error::sys()).context(ks_err!(
234 "Key blob must be specified when \
235 using Domain::BLOB."
236 ));
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700237 }
238 },
239 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000240 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000241 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700242 )
243 }
244 _ => {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800245 let super_key = SUPER_KEY
246 .read()
247 .unwrap()
Eric Biggers673d34a2023-10-18 01:54:18 +0000248 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800249 let (key_id_guard, mut key_entry) = DB
250 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800251 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000252 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700253 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000254 KeyType::Client,
255 KeyEntryLoadBits::KM,
256 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800257 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700258 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800259 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700260 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800261 }
262 Ok(())
263 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000264 )
265 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700266 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000267 .context(ks_err!("Failed to load key blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800268
269 let (blob, blob_metadata) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000270 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(ks_err!(
271 "Successfully loaded key entry, \
272 but KM blob was missing."
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800273 ))?;
274 scoping_blob = blob;
275
Qi Wub9433b52020-12-01 14:52:46 +0800276 (
277 &scoping_blob,
278 Some((key_id_guard.id(), key_entry.into_key_parameters())),
279 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000280 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800281 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700282 }
283 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700284
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700285 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700286 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000287 .context(ks_err!("No operation purpose specified.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800288 |kp| match kp.value {
289 KeyParameterValue::KeyPurpose(p) => Ok(p),
290 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000291 .context(ks_err!("Malformed KeyParameter.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800292 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700293 )?;
294
Satya Tangirala2642ff92021-04-15 01:57:00 -0700295 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
296 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
297 let op_params: Vec<KeyParameter> =
298 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
299 let operation_parameters = op_params.as_slice();
300
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800301 let (immediate_hat, mut auth_info) = ENFORCEMENTS
302 .authorize_create(
303 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800304 key_properties.as_ref(),
305 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700306 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800307 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000308 .context(ks_err!())?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000309
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000310 let km_blob = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800311 .read()
312 .unwrap()
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000313 .unwrap_key_if_required(&blob_metadata, km_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000314 .context(ks_err!("Failed to handle super encryption."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000315
Janis Danisevskisaec14592020-11-12 09:41:49 -0800316 let (begin_result, upgraded_blob) = self
317 .upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800318 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700319 &km_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800320 blob_metadata.km_uuid().copied(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700321 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800322 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700323 match map_km_error({
324 let _wp = self.watch_millis(
325 "In KeystoreSecurityLevel::create_operation: calling begin",
326 500,
327 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700328 self.keymint.begin(
329 purpose,
330 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700331 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700332 immediate_hat.as_ref(),
333 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700334 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800335 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800336 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800337 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700338 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100339 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
340 if let Some((key_id, _)) = key_properties {
341 if let Ok(Some(key)) =
342 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
343 {
344 log_key_integrity_violation(&key);
345 } else {
346 log::error!("Failed to load key descriptor for audit log");
347 }
348 }
349 return v;
350 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800351 v => return v,
352 }
353 },
354 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000355 .context(ks_err!("Failed to begin operation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700356
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800357 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000358
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000359 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
360
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700362 Some(km_op) => self.operation_db.create_operation(
363 km_op,
364 caller_uid,
365 auth_info,
366 forced,
367 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
368 ),
369 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000370 return Err(Error::sys()).context(ks_err!(
371 "Begin operation returned successfully, \
372 but did not return a valid operation."
373 ));
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700374 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700375 };
376
Stephen Crane23cf7242022-01-19 17:49:46 +0000377 let op_binder: binder::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700378 KeystoreOperation::new_native_binder(operation)
379 .as_binder()
380 .into_interface()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000381 .context(ks_err!("Failed to create IKeystoreOperation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700382
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700383 Ok(CreateOperationResponse {
384 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000385 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700386 parameters: match begin_result.params.len() {
387 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700388 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700389 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800390 // An upgraded blob should only be returned if the caller has permission
391 // to use Domain::BLOB keys. If we got to this point, we already checked
392 // that the caller had that permission.
393 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700394 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700395 }
396
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000397 fn add_required_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700398 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800399 uid: u32,
400 params: &[KeyParameter],
401 key: &KeyDescriptor,
402 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800403 let mut result = params.to_vec();
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000404
Tri Vo74997ed2023-07-20 17:57:19 -0400405 // Prevent callers from specifying the CREATION_DATETIME tag.
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000406 if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000407 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
408 "KeystoreSecurityLevel::add_required_parameters: \
409 Specifying Tag::CREATION_DATETIME is not allowed."
410 ));
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000411 }
412
Tri Vo74997ed2023-07-20 17:57:19 -0400413 // Use this variable to refer to notion of "now". This eliminates discrepancies from
414 // quering the clock multiple times.
415 let creation_datetime = SystemTime::now();
416
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800417 // Add CREATION_DATETIME only if the backend version Keymint V1 (100) or newer.
418 if self.hw_info.versionNumber >= 100 {
419 result.push(KeyParameter {
420 tag: Tag::CREATION_DATETIME,
421 value: KeyParameterValue::DateTime(
Tri Vo74997ed2023-07-20 17:57:19 -0400422 creation_datetime
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800423 .duration_since(SystemTime::UNIX_EPOCH)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000424 .context(ks_err!(
425 "KeystoreSecurityLevel::add_required_parameters: \
426 Failed to get epoch time."
427 ))?
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800428 .as_millis()
429 .try_into()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000430 .context(ks_err!(
431 "KeystoreSecurityLevel::add_required_parameters: \
432 Failed to convert epoch time."
433 ))?,
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800434 ),
435 });
436 }
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000437
Janis Danisevskis2c084012021-01-31 22:23:17 -0800438 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800439 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700440 let aaid = {
441 let _wp = self.watch_millis(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000442 "In KeystoreSecurityLevel::add_required_parameters calling: get_aaid",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700443 500,
444 );
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000445 keystore2_aaid::get_aaid(uid)
446 .map_err(|e| anyhow!(ks_err!("get_aaid returned status {}.", e)))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700447 }?;
448
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800449 result.push(KeyParameter {
450 tag: Tag::ATTESTATION_APPLICATION_ID,
451 value: KeyParameterValue::Blob(aaid),
452 });
453 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800454
Janis Danisevskise766edc2021-02-06 12:16:26 -0800455 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Seth Moore66d9e902022-03-16 17:20:31 -0700456 if check_key_permission(KeyPerm::GenUniqueId, key, &None).is_err()
457 && check_unique_id_attestation_permissions().is_err()
458 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000459 return Err(Error::perm()).context(ks_err!(
460 "Caller does not have the permission to generate a unique ID"
461 ));
Seth Moore66d9e902022-03-16 17:20:31 -0700462 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000463 if self
464 .id_rotation_state
Tri Vo74997ed2023-07-20 17:57:19 -0400465 .had_factory_reset_since_id_rotation(&creation_datetime)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000466 .context(ks_err!("Call to had_factory_reset_since_id_rotation failed."))?
467 {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000468 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700469 tag: Tag::RESET_SINCE_ID_ROTATION,
470 value: KeyParameterValue::BoolValue(true),
471 })
472 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800473 }
474
Bram Bonné5d6c5102021-02-24 15:09:18 +0100475 // If the caller requests any device identifier attestation tag, check that they hold the
476 // correct Android permission.
477 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000478 check_device_attestation_permissions().context(ks_err!(
Bram Bonné5d6c5102021-02-24 15:09:18 +0100479 "Caller does not have the permission to attest device identifiers."
480 ))?;
481 }
482
Janis Danisevskis2c084012021-01-31 22:23:17 -0800483 // If we are generating/importing an asymmetric key, we need to make sure
484 // that NOT_BEFORE and NOT_AFTER are present.
485 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
486 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
487 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
488 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
489 result.push(KeyParameter {
490 tag: Tag::CERTIFICATE_NOT_BEFORE,
491 value: KeyParameterValue::DateTime(0),
492 })
493 }
494 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
495 result.push(KeyParameter {
496 tag: Tag::CERTIFICATE_NOT_AFTER,
497 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
498 })
499 }
500 }
501 _ => {}
502 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800503 Ok(result)
504 }
505
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 fn generate_key(
507 &self,
508 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700509 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700510 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700511 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700512 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700513 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700514 if key.domain != Domain::BLOB && key.alias.is_none() {
515 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000516 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700517 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000518 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519
520 let key = match key.domain {
521 Domain::APP => KeyDescriptor {
522 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000523 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700524 alias: key.alias.clone(),
525 blob: None,
526 },
527 _ => key.clone(),
528 };
529
530 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700531 // Must return on error for security reasons.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000532 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700533
534 let attestation_key_info = match (key.domain, attest_key_descriptor) {
535 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800536 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700537 .with(|db| {
538 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800539 &key,
540 caller_uid,
541 attest_key_descriptor,
542 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700543 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800544 &mut db.borrow_mut(),
545 )
546 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000547 .context(ks_err!("Trying to get an attestation key"))?,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800548 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700549 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000550 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000551 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800552
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700553 let creation_result = match attestation_key_info {
554 Some(AttestationKeyInfo::UserGenerated {
555 key_id_guard,
556 blob,
557 blob_metadata,
558 issuer_subject,
559 }) => self
560 .upgrade_keyblob_if_required_with(
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700561 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700562 &KeyBlob::Ref(&blob),
Max Bires55620ff2022-02-11 13:34:15 -0800563 blob_metadata.km_uuid().copied(),
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700564 &params,
565 |blob| {
566 let attest_key = Some(AttestationKey {
567 keyBlob: blob.to_vec(),
568 attestKeyParams: vec![],
569 issuerSubjectName: issuer_subject.clone(),
570 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700571 map_km_error({
572 let _wp = self.watch_millis(
573 concat!(
574 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
575 "calling generate_key."
576 ),
577 5000, // Generate can take a little longer.
578 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700579 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700580 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700581 },
582 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000583 .context(ks_err!("Using user generated attestation key."))
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700584 .map(|(result, _)| result),
Tri Vob5e43d12022-12-21 08:54:14 -0800585 Some(AttestationKeyInfo::RkpdProvisioned { attestation_key, attestation_certs }) => {
586 self.upgrade_rkpd_keyblob_if_required_with(&attestation_key.keyBlob, &[], |blob| {
587 map_km_error({
588 let _wp = self.watch_millis(
589 concat!(
590 "In KeystoreSecurityLevel::generate_key (RkpdProvisioned): ",
591 "calling generate_key.",
592 ),
593 5000, // Generate can take a little longer.
594 );
595 let dynamic_attest_key = Some(AttestationKey {
596 keyBlob: blob.to_vec(),
597 attestKeyParams: vec![],
598 issuerSubjectName: attestation_key.issuerSubjectName.clone(),
599 });
600 self.keymint.generateKey(&params, dynamic_attest_key.as_ref())
601 })
602 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000603 .context(ks_err!("While generating Key with remote provisioned attestation key."))
Tri Vob5e43d12022-12-21 08:54:14 -0800604 .map(|(mut result, _)| {
605 result.certificateChain.push(attestation_certs);
606 result
607 })
608 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700609 None => map_km_error({
610 let _wp = self.watch_millis(
611 concat!(
612 "In KeystoreSecurityLevel::generate_key (No attestation): ",
613 "calling generate_key.",
614 ),
615 5000, // Generate can take a little longer.
616 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700617 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700618 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000619 .context(ks_err!("While generating Key without explicit attestation key.")),
Max Bires97f96812021-02-23 23:44:57 -0800620 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000621 .context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700622
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000623 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000624 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700625 }
626
627 fn import_key(
628 &self,
629 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700630 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700632 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700633 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700634 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700635 if key.domain != Domain::BLOB && key.alias.is_none() {
636 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000637 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700638 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000639 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700640
641 let key = match key.domain {
642 Domain::APP => KeyDescriptor {
643 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000644 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700645 alias: key.alias.clone(),
646 blob: None,
647 },
648 _ => key.clone(),
649 };
650
651 // import_key requires the rebind permission.
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000652 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!("In import_key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700653
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700654 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000655 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000656 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800657
Janis Danisevskis1af91262020-08-10 14:58:08 -0700658 let format = params
659 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700660 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700661 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000662 .context(ks_err!("No KeyParameter 'Algorithm'."))
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800663 .and_then(|p| match &p.value {
664 KeyParameterValue::Algorithm(Algorithm::AES)
665 | KeyParameterValue::Algorithm(Algorithm::HMAC)
666 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
667 KeyParameterValue::Algorithm(Algorithm::RSA)
668 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
669 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000670 .context(ks_err!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700671 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000672 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700673
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700674 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700675 let creation_result = map_km_error({
676 let _wp =
677 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
678 km_dev.importKey(&params, format, key_data, None /* attestKey */)
679 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000680 .context(ks_err!("Trying to call importKey"))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700681
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000682 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000683 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700684 }
685
686 fn import_wrapped_key(
687 &self,
688 key: &KeyDescriptor,
689 wrapping_key: &KeyDescriptor,
690 masking_key: Option<&[u8]>,
691 params: &[KeyParameter],
692 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700693 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800694 let wrapped_data: &[u8] = match key {
695 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
696 | KeyDescriptor {
697 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
698 } => blob,
699 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000700 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(ks_err!(
701 "Alias and blob must be specified and domain must be APP or SELINUX. {:?}",
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800702 key
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000703 ));
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800704 }
705 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700706
Janis Danisevskisaec14592020-11-12 09:41:49 -0800707 if wrapping_key.domain == Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000708 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
709 .context(ks_err!("Import wrapped key not supported for self managed blobs."));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800710 }
711
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000712 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000713 let user_id = uid_to_android_user(caller_uid);
714
Janis Danisevskis1af91262020-08-10 14:58:08 -0700715 let key = match key.domain {
716 Domain::APP => KeyDescriptor {
717 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000718 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700719 alias: key.alias.clone(),
720 blob: None,
721 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800722 Domain::SELINUX => KeyDescriptor {
723 domain: Domain::SELINUX,
724 nspace: key.nspace,
725 alias: key.alias.clone(),
726 blob: None,
727 },
728 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700729 };
730
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800731 // Import_wrapped_key requires the rebind permission for the new key.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000732 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700733
Eric Biggers673d34a2023-10-18 01:54:18 +0000734 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800735
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000736 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700737 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800738 LEGACY_IMPORTER.with_try_import(&key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000739 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700740 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000741 KeyType::Client,
742 KeyEntryLoadBits::KM,
743 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700744 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000745 )
746 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700747 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000748 .context(ks_err!("Failed to load wrapping key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000749
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000750 let (wrapping_key_blob, wrapping_blob_metadata) =
751 wrapping_key_entry.take_key_blob_info().ok_or_else(error::Error::sys).context(
752 ks_err!("No km_blob after successfully loading key. This should never happen."),
753 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000754
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800755 let wrapping_key_blob = SUPER_KEY
756 .read()
757 .unwrap()
758 .unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000759 .context(ks_err!("Failed to handle super encryption for wrapping key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700760
Janis Danisevskis1af91262020-08-10 14:58:08 -0700761 // km_dev.importWrappedKey does not return a certificate chain.
762 // TODO Do we assume that all wrapped keys are symmetric?
763 // let certificate_chain: Vec<KmCertificate> = Default::default();
764
765 let pw_sid = authenticators
766 .iter()
767 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700768 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700769 _ => None,
770 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800771 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700772
773 let fp_sid = authenticators
774 .iter()
775 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700776 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700777 _ => None,
778 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800779 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700780
781 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
782
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800783 let (creation_result, _) = self
784 .upgrade_keyblob_if_required_with(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800785 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700786 &wrapping_key_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800787 wrapping_blob_metadata.km_uuid().copied(),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800788 &[],
789 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700790 let _wp = self.watch_millis(
791 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
792 500,
793 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700794 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800795 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800796 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800797 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700798 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800799 pw_sid,
800 fp_sid,
801 ))?;
802 Ok(creation_result)
803 },
804 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000805 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700806
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000807 self.store_new_key(key, creation_result, user_id, None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000808 .context(ks_err!("Trying to store the new key."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700809 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800810
Paul Crowley7a658392021-03-18 17:08:20 -0700811 fn store_upgraded_keyblob(
812 key_id_guard: KeyIdGuard,
Max Bires55620ff2022-02-11 13:34:15 -0800813 km_uuid: Option<Uuid>,
Paul Crowley7a658392021-03-18 17:08:20 -0700814 key_blob: &KeyBlob,
815 upgraded_blob: &[u8],
816 ) -> Result<()> {
817 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700818 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000819 .context(ks_err!("Failed to handle super encryption."))?;
Paul Crowley7a658392021-03-18 17:08:20 -0700820
Paul Crowley44c02da2021-04-08 17:04:43 +0000821 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700822 if let Some(uuid) = km_uuid {
Max Bires55620ff2022-02-11 13:34:15 -0800823 new_blob_metadata.add(BlobMetaEntry::KmUuid(uuid));
Paul Crowley7a658392021-03-18 17:08:20 -0700824 }
825
826 DB.with(|db| {
827 let mut db = db.borrow_mut();
828 db.set_blob(
829 &key_id_guard,
830 SubComponentType::KEY_BLOB,
831 Some(&upgraded_blob_to_be_stored),
832 Some(&new_blob_metadata),
833 )
834 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000835 .context(ks_err!("Failed to insert upgraded blob into the database."))
Paul Crowley7a658392021-03-18 17:08:20 -0700836 }
837
Janis Danisevskisaec14592020-11-12 09:41:49 -0800838 fn upgrade_keyblob_if_required_with<T, F>(
839 &self,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800840 mut key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700841 key_blob: &KeyBlob,
Max Bires55620ff2022-02-11 13:34:15 -0800842 km_uuid: Option<Uuid>,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800843 params: &[KeyParameter],
844 f: F,
845 ) -> Result<(T, Option<Vec<u8>>)>
846 where
847 F: Fn(&[u8]) -> Result<T, Error>,
848 {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800849 let (v, upgraded_blob) = crate::utils::upgrade_keyblob_if_required_with(
David Drysdale5accbaa2023-04-12 18:47:10 +0100850 &*self.keymint,
851 self.hw_info.versionNumber,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800852 key_blob,
853 params,
854 f,
855 |upgraded_blob| {
856 if key_id_guard.is_some() {
857 // Unwrap cannot panic, because the is_some was true.
858 let kid = key_id_guard.take().unwrap();
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000859 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, upgraded_blob)
860 .context(ks_err!("store_upgraded_keyblob failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800861 } else {
862 Ok(())
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000863 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800864 },
865 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000866 .context(ks_err!())?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000867
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800868 // If no upgrade was needed, use the opportunity to reencrypt the blob if required
869 // and if the a key_id_guard is held. Note: key_id_guard can only be Some if no
870 // upgrade was performed above and if one was given in the first place.
871 if key_blob.force_reencrypt() {
872 if let Some(kid) = key_id_guard {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000873 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, key_blob)
874 .context(ks_err!("store_upgraded_keyblob failed in forced reencrypt"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700875 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800876 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800877 Ok((v, upgraded_blob))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800878 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800879
Tri Vob5e43d12022-12-21 08:54:14 -0800880 fn upgrade_rkpd_keyblob_if_required_with<T, F>(
881 &self,
882 key_blob: &[u8],
883 params: &[KeyParameter],
884 f: F,
885 ) -> Result<(T, Option<Vec<u8>>)>
886 where
887 F: Fn(&[u8]) -> Result<T, Error>,
888 {
Alice Wangbf6a6932023-11-07 11:47:12 +0000889 let rpc_name = get_remotely_provisioned_component_name(&self.security_level)
890 .context(ks_err!("Trying to get IRPC name."))?;
Tri Vob5e43d12022-12-21 08:54:14 -0800891 crate::utils::upgrade_keyblob_if_required_with(
892 &*self.keymint,
David Drysdale5accbaa2023-04-12 18:47:10 +0100893 self.hw_info.versionNumber,
Tri Vob5e43d12022-12-21 08:54:14 -0800894 key_blob,
895 params,
896 f,
897 |upgraded_blob| {
Alice Wang4277d2e2023-11-08 09:15:54 +0000898 let _wp = wd::watch_millis("Calling store_rkpd_attestation_key()", 500);
Alice Wangbf6a6932023-11-07 11:47:12 +0000899 store_rkpd_attestation_key(&rpc_name, key_blob, upgraded_blob)
Tri Vob5e43d12022-12-21 08:54:14 -0800900 .context(ks_err!("Failed store_rkpd_attestation_key()."))
901 },
902 )
903 .context(ks_err!())
904 }
905
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700906 fn convert_storage_key_to_ephemeral(
907 &self,
908 storage_key: &KeyDescriptor,
909 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800910 if storage_key.domain != Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000911 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
912 .context(ks_err!("Key must be of Domain::BLOB"));
Satya Tangirala3361b612021-03-08 14:36:11 -0800913 }
914 let key_blob = storage_key
915 .blob
916 .as_ref()
917 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000918 .context(ks_err!("No key blob specified"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800919
920 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700921 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000922 .context(ks_err!("Check permission"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800923
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700924 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700925 match {
926 let _wp = self.watch_millis(
927 concat!(
928 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
929 "calling convertStorageKeyToEphemeral (1)"
930 ),
931 500,
932 );
933 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
934 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700935 Ok(result) => {
936 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
937 }
938 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700939 let upgraded_blob = {
940 let _wp = self.watch_millis(
941 "In convert_storage_key_to_ephemeral: calling upgradeKey",
942 500,
943 );
944 map_km_error(km_dev.upgradeKey(key_blob, &[]))
945 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000946 .context(ks_err!("Failed to upgrade key blob."))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700947 let ephemeral_key = {
948 let _wp = self.watch_millis(
949 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
950 500,
951 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700952 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700953 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000954 .context(ks_err!(
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700955 "Failed to retrieve ephemeral key (after upgrade)."
956 ))?;
957 Ok(EphemeralStorageKeyResponse {
958 ephemeralKey: ephemeral_key,
959 upgradedBlob: Some(upgraded_blob),
960 })
961 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000962 Err(e) => Err(e).context(ks_err!("Failed to retrieve ephemeral key.")),
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700963 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800964 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800965
966 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
967 if key.domain != Domain::BLOB {
968 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000969 .context(ks_err!("delete_key: Key must be of Domain::BLOB"));
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800970 }
971
972 let key_blob = key
973 .blob
974 .as_ref()
975 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000976 .context(ks_err!("delete_key: No key blob specified"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800977
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700978 check_key_permission(KeyPerm::Delete, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000979 .context(ks_err!("delete_key: Checking delete permissions"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800980
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700981 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700982 {
983 let _wp =
984 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000985 map_km_error(km_dev.deleteKey(key_blob)).context(ks_err!("keymint device deleteKey"))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700986 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800987 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700988}
989
990impl binder::Interface for KeystoreSecurityLevel {}
991
992impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700993 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700994 &self,
995 key: &KeyDescriptor,
996 operation_parameters: &[KeyParameter],
997 forced: bool,
Stephen Crane23cf7242022-01-19 17:49:46 +0000998 ) -> binder::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000999 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001000 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001001 }
1002 fn generateKey(
1003 &self,
1004 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001005 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001006 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001007 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001008 entropy: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001009 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001010 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1011 // time than other operations
1012 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001013 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001014 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001015 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001016 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001017 }
1018 fn importKey(
1019 &self,
1020 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001021 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001022 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001023 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001024 key_data: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001025 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001026 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001027 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001028 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001029 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001030 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001031 }
1032 fn importWrappedKey(
1033 &self,
1034 key: &KeyDescriptor,
1035 wrapping_key: &KeyDescriptor,
1036 masking_key: Option<&[u8]>,
1037 params: &[KeyParameter],
1038 authenticators: &[AuthenticatorSpec],
Stephen Crane23cf7242022-01-19 17:49:46 +00001039 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001040 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001041 let result =
1042 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001043 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001044 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001045 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001046 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001047 fn convertStorageKeyToEphemeral(
1048 &self,
1049 storage_key: &KeyDescriptor,
Stephen Crane23cf7242022-01-19 17:49:46 +00001050 ) -> binder::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001051 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001052 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1053 }
Stephen Crane23cf7242022-01-19 17:49:46 +00001054 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001055 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001056 let result = self.delete_key(key);
1057 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1058 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001059 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001060}
Alice Wangbf6a6932023-11-07 11:47:12 +00001061
1062#[cfg(test)]
1063mod tests {
1064 use super::*;
1065 use crate::error::map_km_error;
1066 use crate::globals::get_keymint_device;
1067 use crate::rkpd_client::{get_rkpd_attestation_key, store_rkpd_attestation_key};
1068 use crate::utils::upgrade_keyblob_if_required_with;
1069 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
1070 Algorithm::Algorithm, AttestationKey::AttestationKey, KeyParameter::KeyParameter,
1071 KeyParameterValue::KeyParameterValue, Tag::Tag,
1072 };
1073 use keystore2_crypto::parse_subject_from_certificate;
1074
1075 #[test]
1076 // This is a helper for a manual test. We want to check that after a system upgrade RKPD
1077 // attestation keys can also be upgraded and stored again with RKPD. The steps are:
1078 // 1. Run this test and check in stdout that no key upgrade happened.
1079 // 2. Perform a system upgrade.
1080 // 3. Run this test and check in stdout that key upgrade did happen.
1081 //
1082 // Note that this test must be run with that same UID every time. Running as root, i.e. UID 0,
1083 // should do the trick. Also, use "--nocapture" flag to get stdout.
1084 fn test_rkpd_attestation_key_upgrade() {
1085 binder::ProcessState::start_thread_pool();
1086 let security_level = SecurityLevel::TRUSTED_ENVIRONMENT;
1087 let (keymint, info, _) = get_keymint_device(&security_level).unwrap();
1088 let key_id = 0;
1089 let mut key_upgraded = false;
1090
1091 let rpc_name = get_remotely_provisioned_component_name(&security_level).unwrap();
1092 let key = get_rkpd_attestation_key(&rpc_name, key_id).unwrap();
1093 assert!(!key.keyBlob.is_empty());
1094 assert!(!key.encodedCertChain.is_empty());
1095
1096 upgrade_keyblob_if_required_with(
1097 &*keymint,
1098 info.versionNumber,
1099 &key.keyBlob,
1100 /*upgrade_params=*/ &[],
1101 /*km_op=*/
1102 |blob| {
1103 let params = vec![
1104 KeyParameter {
1105 tag: Tag::ALGORITHM,
1106 value: KeyParameterValue::Algorithm(Algorithm::AES),
1107 },
1108 KeyParameter {
1109 tag: Tag::ATTESTATION_CHALLENGE,
1110 value: KeyParameterValue::Blob(vec![0; 16]),
1111 },
1112 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(128) },
1113 ];
1114 let attestation_key = AttestationKey {
1115 keyBlob: blob.to_vec(),
1116 attestKeyParams: vec![],
1117 issuerSubjectName: parse_subject_from_certificate(&key.encodedCertChain)
1118 .unwrap(),
1119 };
1120
1121 map_km_error(keymint.generateKey(&params, Some(&attestation_key)))
1122 },
1123 /*new_blob_handler=*/
1124 |new_blob| {
1125 // This handler is only executed if a key upgrade was performed.
1126 key_upgraded = true;
Alice Wang4277d2e2023-11-08 09:15:54 +00001127 let _wp = wd::watch_millis("Calling store_rkpd_attestation_key()", 500);
Alice Wangbf6a6932023-11-07 11:47:12 +00001128 store_rkpd_attestation_key(&rpc_name, &key.keyBlob, new_blob).unwrap();
1129 Ok(())
1130 },
1131 )
1132 .unwrap();
1133
1134 if key_upgraded {
1135 println!("RKPD key was upgraded and stored with RKPD.");
1136 } else {
1137 println!("RKPD key was NOT upgraded.");
1138 }
1139 }
1140}