blob: 8ce802ecf042897b07337a3a76e5d7bbd9ecee4a [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::{
David Drysdaledb7ddde2024-06-07 16:22:49 +010023 self, into_logged_binder, map_km_error, wrapped_rkpd_error_to_ks_error, Error, ErrorCode,
Alice Wang849cfe42023-11-10 12:43:36 +000024};
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,
David Drysdale746e1be2023-07-05 17:39:57 +010037 key_characteristics_to_internal, uid_to_android_user, watchdog as wd, UNDEFINED_NOT_AFTER,
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
84impl KeystoreSecurityLevel {
85 /// Creates a new security level instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +000086 /// BnKeystoreSecurityLevel proxy object. It also enables
87 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070088 /// we need it for checking keystore permissions.
89 pub fn new_native_binder(
90 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070091 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080092 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080093 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000094 .context(ks_err!("KeystoreSecurityLevel::new_native_binder."))?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000095 let result = BnKeystoreSecurityLevel::new_binder(
96 Self {
97 security_level,
98 keymint: dev,
99 hw_info,
100 km_uuid,
101 operation_db: OperationDb::new(),
David Drysdale8c4c4f32023-10-31 12:14:11 +0000102 rem_prov_state: RemProvState::new(security_level),
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000103 id_rotation_state,
104 },
105 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
106 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800107 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700108 }
109
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700110 fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
111 let sec_level = self.security_level;
David Drysdale387c85b2024-06-10 14:40:45 +0100112 wd::watch_millis_with(id, millis, sec_level)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700113 }
114
David Drysdale541846b2024-05-23 13:16:07 +0100115 fn watch(&self, id: &'static str) -> Option<wd::WatchPoint> {
116 let sec_level = self.security_level;
David Drysdale387c85b2024-06-10 14:40:45 +0100117 wd::watch_millis_with(id, wd::DEFAULT_TIMEOUT_MS, sec_level)
David Drysdale541846b2024-05-23 13:16:07 +0100118 }
119
Janis Danisevskis1af91262020-08-10 14:58:08 -0700120 fn store_new_key(
121 &self,
122 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700123 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000124 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000125 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700126 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700127 let KeyCreationResult {
128 keyBlob: key_blob,
129 keyCharacteristics: key_characteristics,
130 certificateChain: mut certificate_chain,
131 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700132
Max Bires8e93d2b2021-01-14 13:17:59 -0800133 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700134 match certificate_chain.len() {
135 0 => None,
136 _ => Some(certificate_chain.remove(0).encodedCertificate),
137 },
138 match certificate_chain.len() {
139 0 => None,
140 _ => Some(
141 certificate_chain
142 .iter()
Chariseea1e1c482022-02-26 01:26:35 +0000143 .flat_map(|c| c.encodedCertificate.iter())
Shawn Willdendbdac602021-01-12 22:35:16 -0700144 .copied()
145 .collect(),
146 ),
147 },
148 );
149
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000150 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
151
152 key_parameters.push(KsKeyParam::new(
153 KsKeyParamValue::UserID(user_id as i32),
154 SecurityLevel::SOFTWARE,
155 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700156
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000157 let creation_date = DateTime::now().context(ks_err!("Trying to make creation time."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800158
Janis Danisevskis1af91262020-08-10 14:58:08 -0700159 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800160 Domain::BLOB => KeyDescriptor {
161 domain: Domain::BLOB,
162 blob: Some(key_blob.to_vec()),
163 ..Default::default()
164 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700165 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800166 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800167 let mut db = db.borrow_mut();
168
169 let (key_blob, mut blob_metadata) = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800170 .read()
171 .unwrap()
Satya Tangirala60671e32021-03-04 16:12:19 -0800172 .handle_super_encryption_on_key_init(
173 &mut db,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800174 &LEGACY_IMPORTER,
Satya Tangirala60671e32021-03-04 16:12:19 -0800175 &(key.domain),
176 &key_parameters,
177 flags,
178 user_id,
179 &key_blob,
180 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000181 .context(ks_err!("Failed to handle super encryption."))?;
Satya Tangirala60671e32021-03-04 16:12:19 -0800182
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800183 let mut key_metadata = KeyMetaData::new();
184 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800185 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800186
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800187 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800188 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800189 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700190 KeyType::Client,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800191 &key_parameters,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800192 &BlobInfo::new(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800193 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800194 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800195 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800196 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000197 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700198 Ok(KeyDescriptor {
199 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800200 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700201 ..Default::default()
202 })
203 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000204 .context(ks_err!())?,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700205 };
206
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700207 Ok(KeyMetadata {
208 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700209 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800210 certificate: cert_info.take_cert(),
211 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700212 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800213 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700214 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700215 }
216
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700217 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700218 &self,
219 key: &KeyDescriptor,
220 operation_parameters: &[KeyParameter],
221 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700222 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700223 let caller_uid = ThreadState::get_calling_uid();
224 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
225 // so that we can use it by reference like the blob provided by the key descriptor.
226 // Otherwise, we would have to clone the blob from the key descriptor.
227 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800228 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700229 Domain::BLOB => {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700230 check_key_permission(KeyPerm::Use, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000231 .context(ks_err!("checking use permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800232 if forced {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000233 check_key_permission(KeyPerm::ReqForcedOp, key, &None)
234 .context(ks_err!("checking forced permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800235 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700236 (
237 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700238 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700239 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000240 return Err(Error::sys()).context(ks_err!(
241 "Key blob must be specified when \
242 using Domain::BLOB."
243 ));
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700244 }
245 },
246 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000247 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000248 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700249 )
250 }
251 _ => {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800252 let super_key = SUPER_KEY
253 .read()
254 .unwrap()
Eric Biggers673d34a2023-10-18 01:54:18 +0000255 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800256 let (key_id_guard, mut key_entry) = DB
257 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800258 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000259 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700260 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000261 KeyType::Client,
262 KeyEntryLoadBits::KM,
263 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800264 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700265 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800266 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700267 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800268 }
269 Ok(())
270 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000271 )
272 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700273 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000274 .context(ks_err!("Failed to load key blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800275
276 let (blob, blob_metadata) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000277 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(ks_err!(
278 "Successfully loaded key entry, \
279 but KM blob was missing."
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800280 ))?;
281 scoping_blob = blob;
282
Qi Wub9433b52020-12-01 14:52:46 +0800283 (
284 &scoping_blob,
285 Some((key_id_guard.id(), key_entry.into_key_parameters())),
286 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000287 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800288 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700289 }
290 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700291
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700292 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700293 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000294 .context(ks_err!("No operation purpose specified.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800295 |kp| match kp.value {
296 KeyParameterValue::KeyPurpose(p) => Ok(p),
297 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000298 .context(ks_err!("Malformed KeyParameter.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800299 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700300 )?;
301
Satya Tangirala2642ff92021-04-15 01:57:00 -0700302 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
303 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
304 let op_params: Vec<KeyParameter> =
305 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
306 let operation_parameters = op_params.as_slice();
307
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800308 let (immediate_hat, mut auth_info) = ENFORCEMENTS
309 .authorize_create(
310 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800311 key_properties.as_ref(),
312 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700313 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800314 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000315 .context(ks_err!())?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000316
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000317 let km_blob = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800318 .read()
319 .unwrap()
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000320 .unwrap_key_if_required(&blob_metadata, km_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000321 .context(ks_err!("Failed to handle super encryption."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000322
Janis Danisevskisaec14592020-11-12 09:41:49 -0800323 let (begin_result, upgraded_blob) = self
324 .upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800325 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700326 &km_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800327 blob_metadata.km_uuid().copied(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700328 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800329 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700330 match map_km_error({
David Drysdale541846b2024-05-23 13:16:07 +0100331 let _wp =
332 self.watch("In KeystoreSecurityLevel::create_operation: calling begin");
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700333 self.keymint.begin(
334 purpose,
335 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700336 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700337 immediate_hat.as_ref(),
338 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700339 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800340 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800341 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800342 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700343 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100344 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
345 if let Some((key_id, _)) = key_properties {
346 if let Ok(Some(key)) =
347 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
348 {
349 log_key_integrity_violation(&key);
350 } else {
351 log::error!("Failed to load key descriptor for audit log");
352 }
353 }
354 return v;
355 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800356 v => return v,
357 }
358 },
359 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000360 .context(ks_err!("Failed to begin operation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800362 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000363
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000364 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
365
Janis Danisevskis1af91262020-08-10 14:58:08 -0700366 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700367 Some(km_op) => self.operation_db.create_operation(
368 km_op,
369 caller_uid,
370 auth_info,
371 forced,
372 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
373 ),
374 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000375 return Err(Error::sys()).context(ks_err!(
376 "Begin operation returned successfully, \
377 but did not return a valid operation."
378 ));
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700379 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700380 };
381
Stephen Crane23cf7242022-01-19 17:49:46 +0000382 let op_binder: binder::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700383 KeystoreOperation::new_native_binder(operation)
384 .as_binder()
385 .into_interface()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000386 .context(ks_err!("Failed to create IKeystoreOperation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700387
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700388 Ok(CreateOperationResponse {
389 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000390 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700391 parameters: match begin_result.params.len() {
392 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700393 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700394 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800395 // An upgraded blob should only be returned if the caller has permission
396 // to use Domain::BLOB keys. If we got to this point, we already checked
397 // that the caller had that permission.
398 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700399 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700400 }
401
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000402 fn add_required_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700403 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800404 uid: u32,
405 params: &[KeyParameter],
406 key: &KeyDescriptor,
407 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800408 let mut result = params.to_vec();
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000409
Tri Vo74997ed2023-07-20 17:57:19 -0400410 // Prevent callers from specifying the CREATION_DATETIME tag.
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000411 if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000412 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
413 "KeystoreSecurityLevel::add_required_parameters: \
414 Specifying Tag::CREATION_DATETIME is not allowed."
415 ));
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000416 }
417
Tri Vo74997ed2023-07-20 17:57:19 -0400418 // Use this variable to refer to notion of "now". This eliminates discrepancies from
419 // quering the clock multiple times.
420 let creation_datetime = SystemTime::now();
421
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800422 // Add CREATION_DATETIME only if the backend version Keymint V1 (100) or newer.
423 if self.hw_info.versionNumber >= 100 {
424 result.push(KeyParameter {
425 tag: Tag::CREATION_DATETIME,
426 value: KeyParameterValue::DateTime(
Tri Vo74997ed2023-07-20 17:57:19 -0400427 creation_datetime
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800428 .duration_since(SystemTime::UNIX_EPOCH)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000429 .context(ks_err!(
430 "KeystoreSecurityLevel::add_required_parameters: \
431 Failed to get epoch time."
432 ))?
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800433 .as_millis()
434 .try_into()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000435 .context(ks_err!(
436 "KeystoreSecurityLevel::add_required_parameters: \
437 Failed to convert epoch time."
438 ))?,
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800439 ),
440 });
441 }
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000442
Janis Danisevskis2c084012021-01-31 22:23:17 -0800443 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800444 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700445 let aaid = {
David Drysdale541846b2024-05-23 13:16:07 +0100446 let _wp = self
447 .watch("In KeystoreSecurityLevel::add_required_parameters calling: get_aaid");
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000448 keystore2_aaid::get_aaid(uid)
449 .map_err(|e| anyhow!(ks_err!("get_aaid returned status {}.", e)))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700450 }?;
451
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800452 result.push(KeyParameter {
453 tag: Tag::ATTESTATION_APPLICATION_ID,
454 value: KeyParameterValue::Blob(aaid),
455 });
456 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800457
Janis Danisevskise766edc2021-02-06 12:16:26 -0800458 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Seth Moore66d9e902022-03-16 17:20:31 -0700459 if check_key_permission(KeyPerm::GenUniqueId, key, &None).is_err()
460 && check_unique_id_attestation_permissions().is_err()
461 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000462 return Err(Error::perm()).context(ks_err!(
463 "Caller does not have the permission to generate a unique ID"
464 ));
Seth Moore66d9e902022-03-16 17:20:31 -0700465 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000466 if self
467 .id_rotation_state
Tri Vo74997ed2023-07-20 17:57:19 -0400468 .had_factory_reset_since_id_rotation(&creation_datetime)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000469 .context(ks_err!("Call to had_factory_reset_since_id_rotation failed."))?
470 {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000471 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700472 tag: Tag::RESET_SINCE_ID_ROTATION,
473 value: KeyParameterValue::BoolValue(true),
474 })
475 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800476 }
477
Bram Bonné5d6c5102021-02-24 15:09:18 +0100478 // If the caller requests any device identifier attestation tag, check that they hold the
479 // correct Android permission.
480 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000481 check_device_attestation_permissions().context(ks_err!(
Bram Bonné5d6c5102021-02-24 15:09:18 +0100482 "Caller does not have the permission to attest device identifiers."
483 ))?;
484 }
485
Janis Danisevskis2c084012021-01-31 22:23:17 -0800486 // If we are generating/importing an asymmetric key, we need to make sure
487 // that NOT_BEFORE and NOT_AFTER are present.
488 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
489 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
490 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
491 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
492 result.push(KeyParameter {
493 tag: Tag::CERTIFICATE_NOT_BEFORE,
494 value: KeyParameterValue::DateTime(0),
495 })
496 }
497 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
498 result.push(KeyParameter {
499 tag: Tag::CERTIFICATE_NOT_AFTER,
500 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
501 })
502 }
503 }
504 _ => {}
505 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800506 Ok(result)
507 }
508
Janis Danisevskis1af91262020-08-10 14:58:08 -0700509 fn generate_key(
510 &self,
511 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700512 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700513 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700514 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700515 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700516 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700517 if key.domain != Domain::BLOB && key.alias.is_none() {
518 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000519 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700520 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000521 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700522
523 let key = match key.domain {
524 Domain::APP => KeyDescriptor {
525 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000526 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 alias: key.alias.clone(),
528 blob: None,
529 },
530 _ => key.clone(),
531 };
532
533 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700534 // Must return on error for security reasons.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000535 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700536
537 let attestation_key_info = match (key.domain, attest_key_descriptor) {
538 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800539 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700540 .with(|db| {
541 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800542 &key,
543 caller_uid,
544 attest_key_descriptor,
545 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700546 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800547 &mut db.borrow_mut(),
548 )
549 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000550 .context(ks_err!("Trying to get an attestation key"))?,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800551 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700552 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000553 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000554 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800555
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700556 let creation_result = match attestation_key_info {
557 Some(AttestationKeyInfo::UserGenerated {
558 key_id_guard,
559 blob,
560 blob_metadata,
561 issuer_subject,
562 }) => self
563 .upgrade_keyblob_if_required_with(
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700564 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700565 &KeyBlob::Ref(&blob),
Max Bires55620ff2022-02-11 13:34:15 -0800566 blob_metadata.km_uuid().copied(),
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700567 &params,
568 |blob| {
569 let attest_key = Some(AttestationKey {
570 keyBlob: blob.to_vec(),
571 attestKeyParams: vec![],
572 issuerSubjectName: issuer_subject.clone(),
573 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700574 map_km_error({
575 let _wp = self.watch_millis(
576 concat!(
577 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
578 "calling generate_key."
579 ),
580 5000, // Generate can take a little longer.
581 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700582 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700583 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700584 },
585 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000586 .context(ks_err!("Using user generated attestation key."))
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700587 .map(|(result, _)| result),
Tri Vob5e43d12022-12-21 08:54:14 -0800588 Some(AttestationKeyInfo::RkpdProvisioned { attestation_key, attestation_certs }) => {
589 self.upgrade_rkpd_keyblob_if_required_with(&attestation_key.keyBlob, &[], |blob| {
590 map_km_error({
591 let _wp = self.watch_millis(
592 concat!(
593 "In KeystoreSecurityLevel::generate_key (RkpdProvisioned): ",
594 "calling generate_key.",
595 ),
596 5000, // Generate can take a little longer.
597 );
598 let dynamic_attest_key = Some(AttestationKey {
599 keyBlob: blob.to_vec(),
600 attestKeyParams: vec![],
601 issuerSubjectName: attestation_key.issuerSubjectName.clone(),
602 });
603 self.keymint.generateKey(&params, dynamic_attest_key.as_ref())
604 })
605 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000606 .context(ks_err!("While generating Key with remote provisioned attestation key."))
Tri Vob5e43d12022-12-21 08:54:14 -0800607 .map(|(mut result, _)| {
608 result.certificateChain.push(attestation_certs);
609 result
610 })
611 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700612 None => map_km_error({
613 let _wp = self.watch_millis(
614 concat!(
615 "In KeystoreSecurityLevel::generate_key (No attestation): ",
616 "calling generate_key.",
617 ),
618 5000, // Generate can take a little longer.
619 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700620 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700621 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000622 .context(ks_err!("While generating Key without explicit attestation key.")),
Max Bires97f96812021-02-23 23:44:57 -0800623 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000624 .context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700625
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000626 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000627 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700628 }
629
630 fn import_key(
631 &self,
632 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700633 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700634 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700635 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700636 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700637 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700638 if key.domain != Domain::BLOB && key.alias.is_none() {
639 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000640 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700641 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000642 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700643
644 let key = match key.domain {
645 Domain::APP => KeyDescriptor {
646 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000647 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700648 alias: key.alias.clone(),
649 blob: None,
650 },
651 _ => key.clone(),
652 };
653
654 // import_key requires the rebind permission.
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000655 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!("In import_key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700656
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700657 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000658 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000659 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800660
Janis Danisevskis1af91262020-08-10 14:58:08 -0700661 let format = params
662 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700663 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700664 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000665 .context(ks_err!("No KeyParameter 'Algorithm'."))
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800666 .and_then(|p| match &p.value {
667 KeyParameterValue::Algorithm(Algorithm::AES)
668 | KeyParameterValue::Algorithm(Algorithm::HMAC)
669 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
670 KeyParameterValue::Algorithm(Algorithm::RSA)
671 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
672 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000673 .context(ks_err!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700674 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000675 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700676
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700677 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700678 let creation_result = map_km_error({
David Drysdale541846b2024-05-23 13:16:07 +0100679 let _wp = self.watch("In KeystoreSecurityLevel::import_key: calling importKey.");
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700680 km_dev.importKey(&params, format, key_data, None /* attestKey */)
681 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000682 .context(ks_err!("Trying to call importKey"))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700683
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000684 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000685 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700686 }
687
688 fn import_wrapped_key(
689 &self,
690 key: &KeyDescriptor,
691 wrapping_key: &KeyDescriptor,
692 masking_key: Option<&[u8]>,
693 params: &[KeyParameter],
694 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700695 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800696 let wrapped_data: &[u8] = match key {
697 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
698 | KeyDescriptor {
699 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
700 } => blob,
701 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000702 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(ks_err!(
703 "Alias and blob must be specified and domain must be APP or SELINUX. {:?}",
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800704 key
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000705 ));
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800706 }
707 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700708
Janis Danisevskisaec14592020-11-12 09:41:49 -0800709 if wrapping_key.domain == Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000710 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
711 .context(ks_err!("Import wrapped key not supported for self managed blobs."));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800712 }
713
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000714 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000715 let user_id = uid_to_android_user(caller_uid);
716
Janis Danisevskis1af91262020-08-10 14:58:08 -0700717 let key = match key.domain {
718 Domain::APP => KeyDescriptor {
719 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000720 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700721 alias: key.alias.clone(),
722 blob: None,
723 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800724 Domain::SELINUX => KeyDescriptor {
725 domain: Domain::SELINUX,
726 nspace: key.nspace,
727 alias: key.alias.clone(),
728 blob: None,
729 },
730 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700731 };
732
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800733 // Import_wrapped_key requires the rebind permission for the new key.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000734 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700735
Eric Biggers673d34a2023-10-18 01:54:18 +0000736 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800737
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000738 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700739 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800740 LEGACY_IMPORTER.with_try_import(&key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000741 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700742 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000743 KeyType::Client,
744 KeyEntryLoadBits::KM,
745 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700746 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000747 )
748 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700749 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000750 .context(ks_err!("Failed to load wrapping key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000751
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000752 let (wrapping_key_blob, wrapping_blob_metadata) =
753 wrapping_key_entry.take_key_blob_info().ok_or_else(error::Error::sys).context(
754 ks_err!("No km_blob after successfully loading key. This should never happen."),
755 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000756
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800757 let wrapping_key_blob = SUPER_KEY
758 .read()
759 .unwrap()
760 .unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000761 .context(ks_err!("Failed to handle super encryption for wrapping key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700762
Janis Danisevskis1af91262020-08-10 14:58:08 -0700763 // km_dev.importWrappedKey does not return a certificate chain.
764 // TODO Do we assume that all wrapped keys are symmetric?
765 // let certificate_chain: Vec<KmCertificate> = Default::default();
766
767 let pw_sid = authenticators
768 .iter()
769 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700770 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700771 _ => None,
772 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800773 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700774
775 let fp_sid = authenticators
776 .iter()
777 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700778 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700779 _ => None,
780 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800781 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700782
783 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
784
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800785 let (creation_result, _) = self
786 .upgrade_keyblob_if_required_with(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800787 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700788 &wrapping_key_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800789 wrapping_blob_metadata.km_uuid().copied(),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800790 &[],
791 |wrapping_blob| {
David Drysdale541846b2024-05-23 13:16:07 +0100792 let _wp = self.watch(
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700793 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700794 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700795 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800796 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800797 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800798 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700799 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800800 pw_sid,
801 fp_sid,
802 ))?;
803 Ok(creation_result)
804 },
805 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000806 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700807
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000808 self.store_new_key(key, creation_result, user_id, None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000809 .context(ks_err!("Trying to store the new key."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700810 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800811
Paul Crowley7a658392021-03-18 17:08:20 -0700812 fn store_upgraded_keyblob(
813 key_id_guard: KeyIdGuard,
Max Bires55620ff2022-02-11 13:34:15 -0800814 km_uuid: Option<Uuid>,
Paul Crowley7a658392021-03-18 17:08:20 -0700815 key_blob: &KeyBlob,
816 upgraded_blob: &[u8],
817 ) -> Result<()> {
818 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700819 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000820 .context(ks_err!("Failed to handle super encryption."))?;
Paul Crowley7a658392021-03-18 17:08:20 -0700821
Paul Crowley44c02da2021-04-08 17:04:43 +0000822 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700823 if let Some(uuid) = km_uuid {
Max Bires55620ff2022-02-11 13:34:15 -0800824 new_blob_metadata.add(BlobMetaEntry::KmUuid(uuid));
Paul Crowley7a658392021-03-18 17:08:20 -0700825 }
826
827 DB.with(|db| {
828 let mut db = db.borrow_mut();
829 db.set_blob(
830 &key_id_guard,
831 SubComponentType::KEY_BLOB,
832 Some(&upgraded_blob_to_be_stored),
833 Some(&new_blob_metadata),
834 )
835 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000836 .context(ks_err!("Failed to insert upgraded blob into the database."))
Paul Crowley7a658392021-03-18 17:08:20 -0700837 }
838
Janis Danisevskisaec14592020-11-12 09:41:49 -0800839 fn upgrade_keyblob_if_required_with<T, F>(
840 &self,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800841 mut key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700842 key_blob: &KeyBlob,
Max Bires55620ff2022-02-11 13:34:15 -0800843 km_uuid: Option<Uuid>,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800844 params: &[KeyParameter],
845 f: F,
846 ) -> Result<(T, Option<Vec<u8>>)>
847 where
848 F: Fn(&[u8]) -> Result<T, Error>,
849 {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800850 let (v, upgraded_blob) = crate::utils::upgrade_keyblob_if_required_with(
David Drysdale5accbaa2023-04-12 18:47:10 +0100851 &*self.keymint,
852 self.hw_info.versionNumber,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800853 key_blob,
854 params,
855 f,
856 |upgraded_blob| {
857 if key_id_guard.is_some() {
858 // Unwrap cannot panic, because the is_some was true.
859 let kid = key_id_guard.take().unwrap();
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000860 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, upgraded_blob)
861 .context(ks_err!("store_upgraded_keyblob failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800862 } else {
863 Ok(())
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000864 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800865 },
866 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000867 .context(ks_err!())?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000868
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800869 // If no upgrade was needed, use the opportunity to reencrypt the blob if required
870 // and if the a key_id_guard is held. Note: key_id_guard can only be Some if no
871 // upgrade was performed above and if one was given in the first place.
872 if key_blob.force_reencrypt() {
873 if let Some(kid) = key_id_guard {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000874 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, key_blob)
875 .context(ks_err!("store_upgraded_keyblob failed in forced reencrypt"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700876 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800877 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800878 Ok((v, upgraded_blob))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800879 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800880
Tri Vob5e43d12022-12-21 08:54:14 -0800881 fn upgrade_rkpd_keyblob_if_required_with<T, F>(
882 &self,
883 key_blob: &[u8],
884 params: &[KeyParameter],
885 f: F,
886 ) -> Result<(T, Option<Vec<u8>>)>
887 where
888 F: Fn(&[u8]) -> Result<T, Error>,
889 {
Alice Wangbf6a6932023-11-07 11:47:12 +0000890 let rpc_name = get_remotely_provisioned_component_name(&self.security_level)
891 .context(ks_err!("Trying to get IRPC name."))?;
Tri Vob5e43d12022-12-21 08:54:14 -0800892 crate::utils::upgrade_keyblob_if_required_with(
893 &*self.keymint,
David Drysdale5accbaa2023-04-12 18:47:10 +0100894 self.hw_info.versionNumber,
Tri Vob5e43d12022-12-21 08:54:14 -0800895 key_blob,
896 params,
897 f,
898 |upgraded_blob| {
David Drysdale541846b2024-05-23 13:16:07 +0100899 let _wp = wd::watch("Calling store_rkpd_attestation_key()");
Alice Wang849cfe42023-11-10 12:43:36 +0000900 if let Err(e) = store_rkpd_attestation_key(&rpc_name, key_blob, upgraded_blob) {
901 Err(wrapped_rkpd_error_to_ks_error(&e)).context(format!("{e:?}"))
902 } else {
903 Ok(())
904 }
Tri Vob5e43d12022-12-21 08:54:14 -0800905 },
906 )
907 .context(ks_err!())
908 }
909
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700910 fn convert_storage_key_to_ephemeral(
911 &self,
912 storage_key: &KeyDescriptor,
913 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800914 if storage_key.domain != Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000915 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
916 .context(ks_err!("Key must be of Domain::BLOB"));
Satya Tangirala3361b612021-03-08 14:36:11 -0800917 }
918 let key_blob = storage_key
919 .blob
920 .as_ref()
921 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000922 .context(ks_err!("No key blob specified"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800923
924 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700925 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000926 .context(ks_err!("Check permission"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800927
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700928 let km_dev = &self.keymint;
James Farrellefe1a2f2024-02-28 21:36:47 +0000929 let res = {
David Drysdale541846b2024-05-23 13:16:07 +0100930 let _wp = self.watch(concat!(
931 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
932 "calling convertStorageKeyToEphemeral (1)"
933 ));
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700934 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
James Farrellefe1a2f2024-02-28 21:36:47 +0000935 };
936 match res {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700937 Ok(result) => {
938 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
939 }
940 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700941 let upgraded_blob = {
David Drysdale541846b2024-05-23 13:16:07 +0100942 let _wp = self.watch("In convert_storage_key_to_ephemeral: calling upgradeKey");
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700943 map_km_error(km_dev.upgradeKey(key_blob, &[]))
944 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000945 .context(ks_err!("Failed to upgrade key blob."))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700946 let ephemeral_key = {
David Drysdale541846b2024-05-23 13:16:07 +0100947 let _wp = self.watch(
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700948 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700949 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700950 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700951 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000952 .context(ks_err!(
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700953 "Failed to retrieve ephemeral key (after upgrade)."
954 ))?;
955 Ok(EphemeralStorageKeyResponse {
956 ephemeralKey: ephemeral_key,
957 upgradedBlob: Some(upgraded_blob),
958 })
959 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000960 Err(e) => Err(e).context(ks_err!("Failed to retrieve ephemeral key.")),
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700961 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800962 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800963
964 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
965 if key.domain != Domain::BLOB {
966 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000967 .context(ks_err!("delete_key: Key must be of Domain::BLOB"));
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800968 }
969
970 let key_blob = key
971 .blob
972 .as_ref()
973 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000974 .context(ks_err!("delete_key: No key blob specified"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800975
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700976 check_key_permission(KeyPerm::Delete, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000977 .context(ks_err!("delete_key: Checking delete permissions"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800978
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700979 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700980 {
David Drysdale541846b2024-05-23 13:16:07 +0100981 let _wp = self.watch("In KeystoreSecuritylevel::delete_key: calling deleteKey");
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000982 map_km_error(km_dev.deleteKey(key_blob)).context(ks_err!("keymint device deleteKey"))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700983 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800984 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700985}
986
987impl binder::Interface for KeystoreSecurityLevel {}
988
989impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700990 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700991 &self,
992 key: &KeyDescriptor,
993 operation_parameters: &[KeyParameter],
994 forced: bool,
Stephen Crane23cf7242022-01-19 17:49:46 +0000995 ) -> binder::Result<CreateOperationResponse> {
David Drysdale541846b2024-05-23 13:16:07 +0100996 let _wp = self.watch("IKeystoreSecurityLevel::createOperation");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100997 self.create_operation(key, operation_parameters, forced).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700998 }
999 fn generateKey(
1000 &self,
1001 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001002 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001003 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001004 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001005 entropy: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001006 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001007 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1008 // time than other operations
1009 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001010 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001011 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001012 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +01001013 result.map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001014 }
1015 fn importKey(
1016 &self,
1017 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001018 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001019 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001020 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001021 key_data: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001022 ) -> binder::Result<KeyMetadata> {
David Drysdale541846b2024-05-23 13:16:07 +01001023 let _wp = self.watch("IKeystoreSecurityLevel::importKey");
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001024 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001025 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001026 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +01001027 result.map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001028 }
1029 fn importWrappedKey(
1030 &self,
1031 key: &KeyDescriptor,
1032 wrapping_key: &KeyDescriptor,
1033 masking_key: Option<&[u8]>,
1034 params: &[KeyParameter],
1035 authenticators: &[AuthenticatorSpec],
Stephen Crane23cf7242022-01-19 17:49:46 +00001036 ) -> binder::Result<KeyMetadata> {
David Drysdale541846b2024-05-23 13:16:07 +01001037 let _wp = self.watch("IKeystoreSecurityLevel::importWrappedKey");
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001038 let result =
1039 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001040 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001041 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +01001042 result.map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001043 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001044 fn convertStorageKeyToEphemeral(
1045 &self,
1046 storage_key: &KeyDescriptor,
Stephen Crane23cf7242022-01-19 17:49:46 +00001047 ) -> binder::Result<EphemeralStorageKeyResponse> {
David Drysdale541846b2024-05-23 13:16:07 +01001048 let _wp = self.watch("IKeystoreSecurityLevel::convertStorageKeyToEphemeral");
David Drysdaledb7ddde2024-06-07 16:22:49 +01001049 self.convert_storage_key_to_ephemeral(storage_key).map_err(into_logged_binder)
Satya Tangirala3361b612021-03-08 14:36:11 -08001050 }
Stephen Crane23cf7242022-01-19 17:49:46 +00001051 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001052 let _wp = self.watch("IKeystoreSecurityLevel::deleteKey");
Pavel Grafov94243c22021-04-21 18:03:11 +01001053 let result = self.delete_key(key);
1054 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +01001055 result.map_err(into_logged_binder)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001056 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001057}
Alice Wangbf6a6932023-11-07 11:47:12 +00001058
1059#[cfg(test)]
1060mod tests {
1061 use super::*;
1062 use crate::error::map_km_error;
1063 use crate::globals::get_keymint_device;
Alice Wangbf6a6932023-11-07 11:47:12 +00001064 use crate::utils::upgrade_keyblob_if_required_with;
1065 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
1066 Algorithm::Algorithm, AttestationKey::AttestationKey, KeyParameter::KeyParameter,
1067 KeyParameterValue::KeyParameterValue, Tag::Tag,
1068 };
1069 use keystore2_crypto::parse_subject_from_certificate;
Alice Wang01c16b62023-11-07 14:27:49 +00001070 use rkpd_client::get_rkpd_attestation_key;
Alice Wangbf6a6932023-11-07 11:47:12 +00001071
1072 #[test]
1073 // This is a helper for a manual test. We want to check that after a system upgrade RKPD
1074 // attestation keys can also be upgraded and stored again with RKPD. The steps are:
1075 // 1. Run this test and check in stdout that no key upgrade happened.
1076 // 2. Perform a system upgrade.
1077 // 3. Run this test and check in stdout that key upgrade did happen.
1078 //
1079 // Note that this test must be run with that same UID every time. Running as root, i.e. UID 0,
1080 // should do the trick. Also, use "--nocapture" flag to get stdout.
1081 fn test_rkpd_attestation_key_upgrade() {
1082 binder::ProcessState::start_thread_pool();
1083 let security_level = SecurityLevel::TRUSTED_ENVIRONMENT;
1084 let (keymint, info, _) = get_keymint_device(&security_level).unwrap();
1085 let key_id = 0;
1086 let mut key_upgraded = false;
1087
1088 let rpc_name = get_remotely_provisioned_component_name(&security_level).unwrap();
1089 let key = get_rkpd_attestation_key(&rpc_name, key_id).unwrap();
1090 assert!(!key.keyBlob.is_empty());
1091 assert!(!key.encodedCertChain.is_empty());
1092
1093 upgrade_keyblob_if_required_with(
1094 &*keymint,
1095 info.versionNumber,
1096 &key.keyBlob,
1097 /*upgrade_params=*/ &[],
1098 /*km_op=*/
1099 |blob| {
1100 let params = vec![
1101 KeyParameter {
1102 tag: Tag::ALGORITHM,
1103 value: KeyParameterValue::Algorithm(Algorithm::AES),
1104 },
1105 KeyParameter {
1106 tag: Tag::ATTESTATION_CHALLENGE,
1107 value: KeyParameterValue::Blob(vec![0; 16]),
1108 },
1109 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(128) },
1110 ];
1111 let attestation_key = AttestationKey {
1112 keyBlob: blob.to_vec(),
1113 attestKeyParams: vec![],
1114 issuerSubjectName: parse_subject_from_certificate(&key.encodedCertChain)
1115 .unwrap(),
1116 };
1117
1118 map_km_error(keymint.generateKey(&params, Some(&attestation_key)))
1119 },
1120 /*new_blob_handler=*/
1121 |new_blob| {
1122 // This handler is only executed if a key upgrade was performed.
1123 key_upgraded = true;
David Drysdale541846b2024-05-23 13:16:07 +01001124 let _wp = wd::watch("Calling store_rkpd_attestation_key()");
Alice Wangbf6a6932023-11-07 11:47:12 +00001125 store_rkpd_attestation_key(&rpc_name, &key.keyBlob, new_blob).unwrap();
1126 Ok(())
1127 },
1128 )
1129 .unwrap();
1130
1131 if key_upgraded {
1132 println!("RKPD key was upgraded and stored with RKPD.");
1133 } else {
1134 println!("RKPD key was NOT upgraded.");
1135 }
1136 }
1137}