blob: 89c0e97506eddb086e53416fb89a0e0213fe5686 [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,
Shaquille Johnson668d2922024-07-02 18:03:47 +000037 key_characteristics_to_internal, log_security_safe_params, uid_to_android_user, watchdog as wd,
38 UNDEFINED_NOT_AFTER,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070039};
40use crate::{
41 database::{
42 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
43 KeyMetaEntry, KeyType, SubComponentType, Uuid,
44 },
45 operation::KeystoreOperation,
46 operation::LoggingInfo,
47 operation::OperationDb,
48 permission::KeyPerm,
49};
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070050use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
Shawn Willden708744a2020-12-11 13:05:27 +000051use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
David Drysdale76d95ba2024-09-25 14:00:10 +010052 Algorithm::Algorithm, AttestationKey::AttestationKey, Certificate::Certificate,
Shawn Willden8fde4c22021-02-14 13:58:22 -070053 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
54 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080055 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
56 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070057};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000058use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070059use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070060 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
Janis Danisevskisb2434d02021-04-20 12:49:27 -070061 Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
62 IKeystoreOperation::IKeystoreOperation, IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070063 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000064 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, ResponseCode::ResponseCode,
Janis Danisevskis1af91262020-08-10 14:58:08 -070065};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080066use anyhow::{anyhow, Context, Result};
Alice Wang01c16b62023-11-07 14:27:49 +000067use rkpd_client::store_rkpd_attestation_key;
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000068use std::convert::TryInto;
69use std::time::SystemTime;
Janis Danisevskis1af91262020-08-10 14:58:08 -070070
71/// Implementation of the IKeystoreSecurityLevel Interface.
72pub struct KeystoreSecurityLevel {
73 security_level: SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070074 keymint: Strong<dyn IKeyMintDevice>,
Max Bires8e93d2b2021-01-14 13:17:59 -080075 hw_info: KeyMintHardwareInfo,
76 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070077 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080078 rem_prov_state: RemProvState,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070079 id_rotation_state: IdRotationState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070080}
81
Janis Danisevskis1af91262020-08-10 14:58:08 -070082// Blob of 32 zeroes used as empty masking key.
83static ZERO_BLOB_32: &[u8] = &[0; 32];
84
85impl KeystoreSecurityLevel {
86 /// Creates a new security level instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +000087 /// BnKeystoreSecurityLevel proxy object. It also enables
88 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070089 /// we need it for checking keystore permissions.
90 pub fn new_native_binder(
91 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070092 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080093 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080094 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000095 .context(ks_err!("KeystoreSecurityLevel::new_native_binder."))?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000096 let result = BnKeystoreSecurityLevel::new_binder(
97 Self {
98 security_level,
99 keymint: dev,
100 hw_info,
101 km_uuid,
102 operation_db: OperationDb::new(),
David Drysdale8c4c4f32023-10-31 12:14:11 +0000103 rem_prov_state: RemProvState::new(security_level),
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000104 id_rotation_state,
105 },
106 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
107 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800108 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700109 }
110
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700111 fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
112 let sec_level = self.security_level;
David Drysdale387c85b2024-06-10 14:40:45 +0100113 wd::watch_millis_with(id, millis, sec_level)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700114 }
115
David Drysdale541846b2024-05-23 13:16:07 +0100116 fn watch(&self, id: &'static str) -> Option<wd::WatchPoint> {
117 let sec_level = self.security_level;
David Drysdale387c85b2024-06-10 14:40:45 +0100118 wd::watch_millis_with(id, wd::DEFAULT_TIMEOUT_MS, sec_level)
David Drysdale541846b2024-05-23 13:16:07 +0100119 }
120
Janis Danisevskis1af91262020-08-10 14:58:08 -0700121 fn store_new_key(
122 &self,
123 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700124 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000125 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000126 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700127 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700128 let KeyCreationResult {
129 keyBlob: key_blob,
130 keyCharacteristics: key_characteristics,
131 certificateChain: mut certificate_chain,
132 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700133
David Drysdale76d95ba2024-09-25 14:00:10 +0100134 // Unify the possible contents of the certificate chain. The first entry in the `Vec` is
135 // always the leaf certificate (if present), but the rest of the chain may be present as
136 // either:
137 // - `certificate_chain[1..n]`: each entry holds a single certificate, as returned by
138 // KeyMint, or
139 // - `certificate[1`]: a single `Certificate` from RKP that actually (and confusingly)
140 // holds the DER-encoded certs of the chain concatenated together.
Max Bires8e93d2b2021-01-14 13:17:59 -0800141 let mut cert_info: CertificateInfo = CertificateInfo::new(
David Drysdale76d95ba2024-09-25 14:00:10 +0100142 // Leaf is always a single cert in the first entry, if present.
Shawn Willdendbdac602021-01-12 22:35:16 -0700143 match certificate_chain.len() {
144 0 => None,
145 _ => Some(certificate_chain.remove(0).encodedCertificate),
146 },
David Drysdale76d95ba2024-09-25 14:00:10 +0100147 // Remainder may be either `[1..n]` individual certs, or just `[1]` holding a
148 // concatenated chain. Convert the former to the latter.
Shawn Willdendbdac602021-01-12 22:35:16 -0700149 match certificate_chain.len() {
150 0 => None,
151 _ => Some(
152 certificate_chain
153 .iter()
Chariseea1e1c482022-02-26 01:26:35 +0000154 .flat_map(|c| c.encodedCertificate.iter())
Shawn Willdendbdac602021-01-12 22:35:16 -0700155 .copied()
156 .collect(),
157 ),
158 },
159 );
160
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000161 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
162
163 key_parameters.push(KsKeyParam::new(
164 KsKeyParamValue::UserID(user_id as i32),
165 SecurityLevel::SOFTWARE,
166 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700167
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000168 let creation_date = DateTime::now().context(ks_err!("Trying to make creation time."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800169
Janis Danisevskis1af91262020-08-10 14:58:08 -0700170 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800171 Domain::BLOB => KeyDescriptor {
172 domain: Domain::BLOB,
173 blob: Some(key_blob.to_vec()),
174 ..Default::default()
175 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700176 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800177 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800178 let mut db = db.borrow_mut();
179
180 let (key_blob, mut blob_metadata) = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800181 .read()
182 .unwrap()
Satya Tangirala60671e32021-03-04 16:12:19 -0800183 .handle_super_encryption_on_key_init(
184 &mut db,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800185 &LEGACY_IMPORTER,
Satya Tangirala60671e32021-03-04 16:12:19 -0800186 &(key.domain),
187 &key_parameters,
188 flags,
189 user_id,
190 &key_blob,
191 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000192 .context(ks_err!("Failed to handle super encryption."))?;
Satya Tangirala60671e32021-03-04 16:12:19 -0800193
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800194 let mut key_metadata = KeyMetaData::new();
195 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800196 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800197
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800198 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800199 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800200 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700201 KeyType::Client,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800202 &key_parameters,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800203 &BlobInfo::new(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800204 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800205 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800206 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800207 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000208 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700209 Ok(KeyDescriptor {
210 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800211 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700212 ..Default::default()
213 })
214 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000215 .context(ks_err!())?,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700216 };
217
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700218 Ok(KeyMetadata {
219 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700220 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800221 certificate: cert_info.take_cert(),
222 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700223 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800224 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700225 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700226 }
227
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700228 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700229 &self,
230 key: &KeyDescriptor,
231 operation_parameters: &[KeyParameter],
232 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700233 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700234 let caller_uid = ThreadState::get_calling_uid();
235 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
236 // so that we can use it by reference like the blob provided by the key descriptor.
237 // Otherwise, we would have to clone the blob from the key descriptor.
238 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800239 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700240 Domain::BLOB => {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700241 check_key_permission(KeyPerm::Use, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000242 .context(ks_err!("checking use permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800243 if forced {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000244 check_key_permission(KeyPerm::ReqForcedOp, key, &None)
245 .context(ks_err!("checking forced permission for Domain::BLOB."))?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800246 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700247 (
248 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700249 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700250 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000251 return Err(Error::sys()).context(ks_err!(
252 "Key blob must be specified when \
253 using Domain::BLOB."
254 ));
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700255 }
256 },
257 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000258 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000259 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700260 )
261 }
262 _ => {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800263 let super_key = SUPER_KEY
264 .read()
265 .unwrap()
Eric Biggers673d34a2023-10-18 01:54:18 +0000266 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800267 let (key_id_guard, mut key_entry) = DB
268 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800269 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000270 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700271 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000272 KeyType::Client,
273 KeyEntryLoadBits::KM,
274 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800275 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700276 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800277 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700278 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800279 }
280 Ok(())
281 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000282 )
283 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700284 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000285 .context(ks_err!("Failed to load key blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800286
287 let (blob, blob_metadata) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000288 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(ks_err!(
289 "Successfully loaded key entry, \
290 but KM blob was missing."
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800291 ))?;
292 scoping_blob = blob;
293
Qi Wub9433b52020-12-01 14:52:46 +0800294 (
295 &scoping_blob,
296 Some((key_id_guard.id(), key_entry.into_key_parameters())),
297 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000298 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800299 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700300 }
301 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700302
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700303 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700304 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000305 .context(ks_err!("No operation purpose specified.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800306 |kp| match kp.value {
307 KeyParameterValue::KeyPurpose(p) => Ok(p),
308 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000309 .context(ks_err!("Malformed KeyParameter.")),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800310 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700311 )?;
312
Satya Tangirala2642ff92021-04-15 01:57:00 -0700313 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
314 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
315 let op_params: Vec<KeyParameter> =
316 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
317 let operation_parameters = op_params.as_slice();
318
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800319 let (immediate_hat, mut auth_info) = ENFORCEMENTS
320 .authorize_create(
321 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800322 key_properties.as_ref(),
323 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700324 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800325 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000326 .context(ks_err!())?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000327
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000328 let km_blob = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800329 .read()
330 .unwrap()
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000331 .unwrap_key_if_required(&blob_metadata, km_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000332 .context(ks_err!("Failed to handle super encryption."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000333
Janis Danisevskisaec14592020-11-12 09:41:49 -0800334 let (begin_result, upgraded_blob) = self
335 .upgrade_keyblob_if_required_with(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800336 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700337 &km_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800338 blob_metadata.km_uuid().copied(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700339 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800340 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700341 match map_km_error({
David Drysdalec652f6c2024-07-18 13:01:23 +0100342 let _wp = self.watch(
343 "KeystoreSecurityLevel::create_operation: calling IKeyMintDevice::begin",
344 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700345 self.keymint.begin(
346 purpose,
347 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700348 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700349 immediate_hat.as_ref(),
350 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700351 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800352 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800353 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800354 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700355 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100356 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
357 if let Some((key_id, _)) = key_properties {
358 if let Ok(Some(key)) =
359 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
360 {
361 log_key_integrity_violation(&key);
362 } else {
363 log::error!("Failed to load key descriptor for audit log");
364 }
365 }
366 return v;
367 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800368 v => return v,
369 }
370 },
371 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000372 .context(ks_err!("Failed to begin operation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700373
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800374 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000375
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000376 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
377
Janis Danisevskis1af91262020-08-10 14:58:08 -0700378 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700379 Some(km_op) => self.operation_db.create_operation(
380 km_op,
381 caller_uid,
382 auth_info,
383 forced,
384 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
385 ),
386 None => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000387 return Err(Error::sys()).context(ks_err!(
388 "Begin operation returned successfully, \
389 but did not return a valid operation."
390 ));
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700391 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700392 };
393
Stephen Crane23cf7242022-01-19 17:49:46 +0000394 let op_binder: binder::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700395 KeystoreOperation::new_native_binder(operation)
396 .as_binder()
397 .into_interface()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000398 .context(ks_err!("Failed to create IKeystoreOperation."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700399
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700400 Ok(CreateOperationResponse {
401 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000402 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700403 parameters: match begin_result.params.len() {
404 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700405 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700406 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800407 // An upgraded blob should only be returned if the caller has permission
408 // to use Domain::BLOB keys. If we got to this point, we already checked
409 // that the caller had that permission.
410 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700411 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700412 }
413
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000414 fn add_required_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700415 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800416 uid: u32,
417 params: &[KeyParameter],
418 key: &KeyDescriptor,
419 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800420 let mut result = params.to_vec();
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000421
Tri Vo74997ed2023-07-20 17:57:19 -0400422 // Prevent callers from specifying the CREATION_DATETIME tag.
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000423 if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000424 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
425 "KeystoreSecurityLevel::add_required_parameters: \
426 Specifying Tag::CREATION_DATETIME is not allowed."
427 ));
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000428 }
429
Tri Vo74997ed2023-07-20 17:57:19 -0400430 // Use this variable to refer to notion of "now". This eliminates discrepancies from
431 // quering the clock multiple times.
432 let creation_datetime = SystemTime::now();
433
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800434 // Add CREATION_DATETIME only if the backend version Keymint V1 (100) or newer.
435 if self.hw_info.versionNumber >= 100 {
436 result.push(KeyParameter {
437 tag: Tag::CREATION_DATETIME,
438 value: KeyParameterValue::DateTime(
Tri Vo74997ed2023-07-20 17:57:19 -0400439 creation_datetime
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800440 .duration_since(SystemTime::UNIX_EPOCH)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000441 .context(ks_err!(
442 "KeystoreSecurityLevel::add_required_parameters: \
443 Failed to get epoch time."
444 ))?
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800445 .as_millis()
446 .try_into()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000447 .context(ks_err!(
448 "KeystoreSecurityLevel::add_required_parameters: \
449 Failed to convert epoch time."
450 ))?,
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800451 ),
452 });
453 }
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000454
Janis Danisevskis2c084012021-01-31 22:23:17 -0800455 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800456 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Shaquille Johnsonc67296e2024-01-22 19:13:01 +0000457 let _wp =
David Drysdalec652f6c2024-07-18 13:01:23 +0100458 self.watch(" KeystoreSecurityLevel::add_required_parameters: calling get_aaid");
Shaquille Johnsonc67296e2024-01-22 19:13:01 +0000459 match keystore2_aaid::get_aaid(uid) {
460 Ok(aaid_ok) => {
461 result.push(KeyParameter {
462 tag: Tag::ATTESTATION_APPLICATION_ID,
463 value: KeyParameterValue::Blob(aaid_ok),
464 });
465 }
Rajesh Nyamagoudc5c69102024-06-27 21:25:10 +0000466 Err(e) if e == ResponseCode::GET_ATTESTATION_APPLICATION_ID_FAILED.0 as u32 => {
467 return Err(Error::Rc(ResponseCode::GET_ATTESTATION_APPLICATION_ID_FAILED))
468 .context(ks_err!("Attestation ID retrieval failed."));
469 }
Shaquille Johnsonc67296e2024-01-22 19:13:01 +0000470 Err(e) => {
471 return Err(anyhow!(e)).context(ks_err!("Attestation ID retrieval error."))
472 }
473 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800474 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800475
Janis Danisevskise766edc2021-02-06 12:16:26 -0800476 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Seth Moore66d9e902022-03-16 17:20:31 -0700477 if check_key_permission(KeyPerm::GenUniqueId, key, &None).is_err()
478 && check_unique_id_attestation_permissions().is_err()
479 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000480 return Err(Error::perm()).context(ks_err!(
481 "Caller does not have the permission to generate a unique ID"
482 ));
Seth Moore66d9e902022-03-16 17:20:31 -0700483 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000484 if self
485 .id_rotation_state
Tri Vo74997ed2023-07-20 17:57:19 -0400486 .had_factory_reset_since_id_rotation(&creation_datetime)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000487 .context(ks_err!("Call to had_factory_reset_since_id_rotation failed."))?
488 {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000489 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700490 tag: Tag::RESET_SINCE_ID_ROTATION,
491 value: KeyParameterValue::BoolValue(true),
492 })
493 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800494 }
495
Bram Bonné5d6c5102021-02-24 15:09:18 +0100496 // If the caller requests any device identifier attestation tag, check that they hold the
497 // correct Android permission.
498 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000499 check_device_attestation_permissions().context(ks_err!(
Bram Bonné5d6c5102021-02-24 15:09:18 +0100500 "Caller does not have the permission to attest device identifiers."
501 ))?;
502 }
503
Janis Danisevskis2c084012021-01-31 22:23:17 -0800504 // If we are generating/importing an asymmetric key, we need to make sure
505 // that NOT_BEFORE and NOT_AFTER are present.
506 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
507 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
508 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
509 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
510 result.push(KeyParameter {
511 tag: Tag::CERTIFICATE_NOT_BEFORE,
512 value: KeyParameterValue::DateTime(0),
513 })
514 }
515 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
516 result.push(KeyParameter {
517 tag: Tag::CERTIFICATE_NOT_AFTER,
518 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
519 })
520 }
521 }
522 _ => {}
523 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800524 Ok(result)
525 }
526
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 fn generate_key(
528 &self,
529 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700530 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700531 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700532 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700533 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700534 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700535 if key.domain != Domain::BLOB && key.alias.is_none() {
536 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000537 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700538 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000539 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700540
541 let key = match key.domain {
542 Domain::APP => KeyDescriptor {
543 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000544 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700545 alias: key.alias.clone(),
546 blob: None,
547 },
548 _ => key.clone(),
549 };
550
551 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700552 // Must return on error for security reasons.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000553 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700554
555 let attestation_key_info = match (key.domain, attest_key_descriptor) {
556 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800557 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700558 .with(|db| {
559 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800560 &key,
561 caller_uid,
562 attest_key_descriptor,
563 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700564 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800565 &mut db.borrow_mut(),
566 )
567 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000568 .context(ks_err!("Trying to get an attestation key"))?,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800569 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700570 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000571 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000572 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800573
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700574 let creation_result = match attestation_key_info {
575 Some(AttestationKeyInfo::UserGenerated {
576 key_id_guard,
577 blob,
578 blob_metadata,
579 issuer_subject,
580 }) => self
581 .upgrade_keyblob_if_required_with(
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700582 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700583 &KeyBlob::Ref(&blob),
Max Bires55620ff2022-02-11 13:34:15 -0800584 blob_metadata.km_uuid().copied(),
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700585 &params,
586 |blob| {
587 let attest_key = Some(AttestationKey {
588 keyBlob: blob.to_vec(),
589 attestKeyParams: vec![],
590 issuerSubjectName: issuer_subject.clone(),
591 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700592 map_km_error({
593 let _wp = self.watch_millis(
594 concat!(
David Drysdalec652f6c2024-07-18 13:01:23 +0100595 "KeystoreSecurityLevel::generate_key (UserGenerated): ",
596 "calling IKeyMintDevice::generate_key"
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700597 ),
598 5000, // Generate can take a little longer.
599 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700600 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700601 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700602 },
603 )
Shaquille Johnson668d2922024-07-02 18:03:47 +0000604 .context(ks_err!(
605 "While generating with a user-generated \
606 attestation key, params: {:?}.",
607 log_security_safe_params(&params)
608 ))
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700609 .map(|(result, _)| result),
Tri Vob5e43d12022-12-21 08:54:14 -0800610 Some(AttestationKeyInfo::RkpdProvisioned { attestation_key, attestation_certs }) => {
611 self.upgrade_rkpd_keyblob_if_required_with(&attestation_key.keyBlob, &[], |blob| {
612 map_km_error({
613 let _wp = self.watch_millis(
614 concat!(
David Drysdalec652f6c2024-07-18 13:01:23 +0100615 "KeystoreSecurityLevel::generate_key (RkpdProvisioned): ",
616 "calling IKeyMintDevice::generate_key",
Tri Vob5e43d12022-12-21 08:54:14 -0800617 ),
618 5000, // Generate can take a little longer.
619 );
620 let dynamic_attest_key = Some(AttestationKey {
621 keyBlob: blob.to_vec(),
622 attestKeyParams: vec![],
623 issuerSubjectName: attestation_key.issuerSubjectName.clone(),
624 });
625 self.keymint.generateKey(&params, dynamic_attest_key.as_ref())
626 })
627 })
Shaquille Johnson668d2922024-07-02 18:03:47 +0000628 .context(ks_err!(
629 "While generating Key {:?} with remote \
630 provisioned attestation key and params: {:?}.",
631 key.alias,
632 log_security_safe_params(&params)
633 ))
Tri Vob5e43d12022-12-21 08:54:14 -0800634 .map(|(mut result, _)| {
David Drysdale76d95ba2024-09-25 14:00:10 +0100635 // The `certificateChain` in a `KeyCreationResult` should normally have one
636 // `Certificate` for each certificate in the chain. To avoid having to
637 // unnecessarily parse the RKP chain (which is concatenated DER-encoded certs),
638 // stuff the whole concatenated chain into a single `Certificate`.
639 // This is untangled by `store_new_key()`.
640 result
641 .certificateChain
642 .push(Certificate { encodedCertificate: attestation_certs });
Tri Vob5e43d12022-12-21 08:54:14 -0800643 result
644 })
645 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700646 None => map_km_error({
647 let _wp = self.watch_millis(
648 concat!(
David Drysdalec652f6c2024-07-18 13:01:23 +0100649 "KeystoreSecurityLevel::generate_key (No attestation key): ",
650 "calling IKeyMintDevice::generate_key",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700651 ),
652 5000, // Generate can take a little longer.
653 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700654 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700655 })
Shaquille Johnson668d2922024-07-02 18:03:47 +0000656 .context(ks_err!(
657 "While generating without a provided \
658 attestation key and params: {:?}.",
659 log_security_safe_params(&params)
660 )),
Max Bires97f96812021-02-23 23:44:57 -0800661 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000662 .context(ks_err!())?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700663
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000664 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000665 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700666 }
667
668 fn import_key(
669 &self,
670 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700671 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700672 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700673 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700674 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700675 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700676 if key.domain != Domain::BLOB && key.alias.is_none() {
677 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000678 .context(ks_err!("Alias must be specified"));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700679 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000680 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700681
682 let key = match key.domain {
683 Domain::APP => KeyDescriptor {
684 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000685 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700686 alias: key.alias.clone(),
687 blob: None,
688 },
689 _ => key.clone(),
690 };
691
692 // import_key requires the rebind permission.
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000693 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!("In import_key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700694
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700695 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000696 .add_required_parameters(caller_uid, params, &key)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000697 .context(ks_err!("Trying to get aaid."))?;
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800698
Janis Danisevskis1af91262020-08-10 14:58:08 -0700699 let format = params
700 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700701 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700702 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000703 .context(ks_err!("No KeyParameter 'Algorithm'."))
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800704 .and_then(|p| match &p.value {
705 KeyParameterValue::Algorithm(Algorithm::AES)
706 | KeyParameterValue::Algorithm(Algorithm::HMAC)
707 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
708 KeyParameterValue::Algorithm(Algorithm::RSA)
709 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
710 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000711 .context(ks_err!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700712 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000713 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700714
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700715 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700716 let creation_result = map_km_error({
David Drysdalec652f6c2024-07-18 13:01:23 +0100717 let _wp =
718 self.watch("KeystoreSecurityLevel::import_key: calling IKeyMintDevice::importKey.");
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700719 km_dev.importKey(&params, format, key_data, None /* attestKey */)
720 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000721 .context(ks_err!("Trying to call importKey"))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700722
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000723 let user_id = uid_to_android_user(caller_uid);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000724 self.store_new_key(key, creation_result, user_id, Some(flags)).context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700725 }
726
727 fn import_wrapped_key(
728 &self,
729 key: &KeyDescriptor,
730 wrapping_key: &KeyDescriptor,
731 masking_key: Option<&[u8]>,
732 params: &[KeyParameter],
733 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700734 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800735 let wrapped_data: &[u8] = match key {
736 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
737 | KeyDescriptor {
738 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
739 } => blob,
740 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000741 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(ks_err!(
742 "Alias and blob must be specified and domain must be APP or SELINUX. {:?}",
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800743 key
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000744 ));
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800745 }
746 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700747
Janis Danisevskisaec14592020-11-12 09:41:49 -0800748 if wrapping_key.domain == Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000749 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
750 .context(ks_err!("Import wrapped key not supported for self managed blobs."));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800751 }
752
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000753 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000754 let user_id = uid_to_android_user(caller_uid);
755
Janis Danisevskis1af91262020-08-10 14:58:08 -0700756 let key = match key.domain {
757 Domain::APP => KeyDescriptor {
758 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000759 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700760 alias: key.alias.clone(),
761 blob: None,
762 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800763 Domain::SELINUX => KeyDescriptor {
764 domain: Domain::SELINUX,
765 nspace: key.nspace,
766 alias: key.alias.clone(),
767 blob: None,
768 },
769 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700770 };
771
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800772 // Import_wrapped_key requires the rebind permission for the new key.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000773 check_key_permission(KeyPerm::Rebind, &key, &None).context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700774
Eric Biggers673d34a2023-10-18 01:54:18 +0000775 let super_key = SUPER_KEY.read().unwrap().get_after_first_unlock_key_by_user_id(user_id);
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800776
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000777 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700778 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800779 LEGACY_IMPORTER.with_try_import(&key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000780 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700781 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000782 KeyType::Client,
783 KeyEntryLoadBits::KM,
784 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700785 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000786 )
787 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700788 })
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000789 .context(ks_err!("Failed to load wrapping key."))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000790
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000791 let (wrapping_key_blob, wrapping_blob_metadata) =
792 wrapping_key_entry.take_key_blob_info().ok_or_else(error::Error::sys).context(
793 ks_err!("No km_blob after successfully loading key. This should never happen."),
794 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000795
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800796 let wrapping_key_blob = SUPER_KEY
797 .read()
798 .unwrap()
799 .unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000800 .context(ks_err!("Failed to handle super encryption for wrapping key."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700801
Janis Danisevskis1af91262020-08-10 14:58:08 -0700802 // km_dev.importWrappedKey does not return a certificate chain.
803 // TODO Do we assume that all wrapped keys are symmetric?
804 // let certificate_chain: Vec<KmCertificate> = Default::default();
805
806 let pw_sid = authenticators
807 .iter()
808 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700809 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700810 _ => None,
811 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800812 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700813
814 let fp_sid = authenticators
815 .iter()
816 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700817 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700818 _ => None,
819 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800820 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700821
822 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
823
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800824 let (creation_result, _) = self
825 .upgrade_keyblob_if_required_with(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800826 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700827 &wrapping_key_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800828 wrapping_blob_metadata.km_uuid().copied(),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800829 &[],
830 |wrapping_blob| {
David Drysdale541846b2024-05-23 13:16:07 +0100831 let _wp = self.watch(
David Drysdalec652f6c2024-07-18 13:01:23 +0100832 "KeystoreSecurityLevel::import_wrapped_key: calling IKeyMintDevice::importWrappedKey.",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700833 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700834 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800835 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800836 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800837 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700838 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800839 pw_sid,
840 fp_sid,
841 ))?;
842 Ok(creation_result)
843 },
844 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000845 .context(ks_err!())?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700846
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000847 self.store_new_key(key, creation_result, user_id, None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000848 .context(ks_err!("Trying to store the new key."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700849 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800850
Paul Crowley7a658392021-03-18 17:08:20 -0700851 fn store_upgraded_keyblob(
852 key_id_guard: KeyIdGuard,
Max Bires55620ff2022-02-11 13:34:15 -0800853 km_uuid: Option<Uuid>,
Paul Crowley7a658392021-03-18 17:08:20 -0700854 key_blob: &KeyBlob,
855 upgraded_blob: &[u8],
856 ) -> Result<()> {
857 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700858 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000859 .context(ks_err!("Failed to handle super encryption."))?;
Paul Crowley7a658392021-03-18 17:08:20 -0700860
Paul Crowley44c02da2021-04-08 17:04:43 +0000861 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700862 if let Some(uuid) = km_uuid {
Max Bires55620ff2022-02-11 13:34:15 -0800863 new_blob_metadata.add(BlobMetaEntry::KmUuid(uuid));
Paul Crowley7a658392021-03-18 17:08:20 -0700864 }
865
866 DB.with(|db| {
867 let mut db = db.borrow_mut();
868 db.set_blob(
869 &key_id_guard,
870 SubComponentType::KEY_BLOB,
871 Some(&upgraded_blob_to_be_stored),
872 Some(&new_blob_metadata),
873 )
874 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000875 .context(ks_err!("Failed to insert upgraded blob into the database."))
Paul Crowley7a658392021-03-18 17:08:20 -0700876 }
877
Janis Danisevskisaec14592020-11-12 09:41:49 -0800878 fn upgrade_keyblob_if_required_with<T, F>(
879 &self,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800880 mut key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700881 key_blob: &KeyBlob,
Max Bires55620ff2022-02-11 13:34:15 -0800882 km_uuid: Option<Uuid>,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800883 params: &[KeyParameter],
884 f: F,
885 ) -> Result<(T, Option<Vec<u8>>)>
886 where
887 F: Fn(&[u8]) -> Result<T, Error>,
888 {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800889 let (v, upgraded_blob) = crate::utils::upgrade_keyblob_if_required_with(
David Drysdale5accbaa2023-04-12 18:47:10 +0100890 &*self.keymint,
891 self.hw_info.versionNumber,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800892 key_blob,
893 params,
894 f,
895 |upgraded_blob| {
896 if key_id_guard.is_some() {
897 // Unwrap cannot panic, because the is_some was true.
898 let kid = key_id_guard.take().unwrap();
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000899 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, upgraded_blob)
900 .context(ks_err!("store_upgraded_keyblob failed"))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800901 } else {
902 Ok(())
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000903 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800904 },
905 )
Shaquille Johnsona820ef52024-06-20 13:48:23 +0000906 .context(ks_err!("upgrade_keyblob_if_required_with(key_id={:?})", key_id_guard))?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000907
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800908 // If no upgrade was needed, use the opportunity to reencrypt the blob if required
909 // and if the a key_id_guard is held. Note: key_id_guard can only be Some if no
910 // upgrade was performed above and if one was given in the first place.
911 if key_blob.force_reencrypt() {
912 if let Some(kid) = key_id_guard {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000913 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, key_blob)
914 .context(ks_err!("store_upgraded_keyblob failed in forced reencrypt"))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700915 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800916 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800917 Ok((v, upgraded_blob))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800918 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800919
Tri Vob5e43d12022-12-21 08:54:14 -0800920 fn upgrade_rkpd_keyblob_if_required_with<T, F>(
921 &self,
922 key_blob: &[u8],
923 params: &[KeyParameter],
924 f: F,
925 ) -> Result<(T, Option<Vec<u8>>)>
926 where
927 F: Fn(&[u8]) -> Result<T, Error>,
928 {
Alice Wangbf6a6932023-11-07 11:47:12 +0000929 let rpc_name = get_remotely_provisioned_component_name(&self.security_level)
930 .context(ks_err!("Trying to get IRPC name."))?;
Tri Vob5e43d12022-12-21 08:54:14 -0800931 crate::utils::upgrade_keyblob_if_required_with(
932 &*self.keymint,
David Drysdale5accbaa2023-04-12 18:47:10 +0100933 self.hw_info.versionNumber,
Tri Vob5e43d12022-12-21 08:54:14 -0800934 key_blob,
935 params,
936 f,
937 |upgraded_blob| {
David Drysdale541846b2024-05-23 13:16:07 +0100938 let _wp = wd::watch("Calling store_rkpd_attestation_key()");
Alice Wang849cfe42023-11-10 12:43:36 +0000939 if let Err(e) = store_rkpd_attestation_key(&rpc_name, key_blob, upgraded_blob) {
940 Err(wrapped_rkpd_error_to_ks_error(&e)).context(format!("{e:?}"))
941 } else {
942 Ok(())
943 }
Tri Vob5e43d12022-12-21 08:54:14 -0800944 },
945 )
Shaquille Johnson668d2922024-07-02 18:03:47 +0000946 .context(ks_err!(
947 "upgrade_rkpd_keyblob_if_required_with(params={:?})",
948 log_security_safe_params(params)
949 ))
Tri Vob5e43d12022-12-21 08:54:14 -0800950 }
951
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700952 fn convert_storage_key_to_ephemeral(
953 &self,
954 storage_key: &KeyDescriptor,
955 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800956 if storage_key.domain != Domain::BLOB {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000957 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
958 .context(ks_err!("Key must be of Domain::BLOB"));
Satya Tangirala3361b612021-03-08 14:36:11 -0800959 }
960 let key_blob = storage_key
961 .blob
962 .as_ref()
963 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000964 .context(ks_err!("No key blob specified"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800965
966 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700967 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000968 .context(ks_err!("Check permission"))?;
Satya Tangirala3361b612021-03-08 14:36:11 -0800969
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700970 let km_dev = &self.keymint;
James Farrellefe1a2f2024-02-28 21:36:47 +0000971 let res = {
David Drysdale541846b2024-05-23 13:16:07 +0100972 let _wp = self.watch(concat!(
David Drysdalec652f6c2024-07-18 13:01:23 +0100973 "IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
974 "calling IKeyMintDevice::convertStorageKeyToEphemeral (1)"
David Drysdale541846b2024-05-23 13:16:07 +0100975 ));
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700976 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
James Farrellefe1a2f2024-02-28 21:36:47 +0000977 };
978 match res {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700979 Ok(result) => {
980 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
981 }
982 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700983 let upgraded_blob = {
David Drysdalec652f6c2024-07-18 13:01:23 +0100984 let _wp = self.watch("IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: calling IKeyMintDevice::upgradeKey");
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700985 map_km_error(km_dev.upgradeKey(key_blob, &[]))
986 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000987 .context(ks_err!("Failed to upgrade key blob."))?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700988 let ephemeral_key = {
David Drysdalec652f6c2024-07-18 13:01:23 +0100989 let _wp = self.watch(concat!(
990 "IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
991 "calling IKeyMintDevice::convertStorageKeyToEphemeral (2)"
992 ));
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700993 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700994 }
David Drysdalec652f6c2024-07-18 13:01:23 +0100995 .context(ks_err!("Failed to retrieve ephemeral key (after upgrade)."))?;
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700996 Ok(EphemeralStorageKeyResponse {
997 ephemeralKey: ephemeral_key,
998 upgradedBlob: Some(upgraded_blob),
999 })
1000 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001001 Err(e) => Err(e).context(ks_err!("Failed to retrieve ephemeral key.")),
Janis Danisevskisb2434d02021-04-20 12:49:27 -07001002 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001003 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001004
1005 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
1006 if key.domain != Domain::BLOB {
1007 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001008 .context(ks_err!("delete_key: Key must be of Domain::BLOB"));
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001009 }
1010
1011 let key_blob = key
1012 .blob
1013 .as_ref()
1014 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001015 .context(ks_err!("delete_key: No key blob specified"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001016
Janis Danisevskis39d57e72021-10-19 16:56:20 -07001017 check_key_permission(KeyPerm::Delete, key, &None)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001018 .context(ks_err!("delete_key: Checking delete permissions"))?;
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001019
Janis Danisevskis5f3a0572021-06-18 11:26:42 -07001020 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -07001021 {
David Drysdalec652f6c2024-07-18 13:01:23 +01001022 let _wp =
1023 self.watch("KeystoreSecuritylevel::delete_key: calling IKeyMintDevice::deleteKey");
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001024 map_km_error(km_dev.deleteKey(key_blob)).context(ks_err!("keymint device deleteKey"))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -07001025 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001026 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001027}
1028
1029impl binder::Interface for KeystoreSecurityLevel {}
1030
1031impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001032 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -07001033 &self,
1034 key: &KeyDescriptor,
1035 operation_parameters: &[KeyParameter],
1036 forced: bool,
Stephen Crane23cf7242022-01-19 17:49:46 +00001037 ) -> binder::Result<CreateOperationResponse> {
David Drysdale541846b2024-05-23 13:16:07 +01001038 let _wp = self.watch("IKeystoreSecurityLevel::createOperation");
David Drysdaledb7ddde2024-06-07 16:22:49 +01001039 self.create_operation(key, operation_parameters, forced).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001040 }
1041 fn generateKey(
1042 &self,
1043 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001044 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001045 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001046 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001047 entropy: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001048 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001049 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1050 // time than other operations
1051 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001052 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001053 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001054 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +01001055 result.map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001056 }
1057 fn importKey(
1058 &self,
1059 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001060 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001061 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001062 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001063 key_data: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001064 ) -> binder::Result<KeyMetadata> {
David Drysdale541846b2024-05-23 13:16:07 +01001065 let _wp = self.watch("IKeystoreSecurityLevel::importKey");
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001066 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001067 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001068 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +01001069 result.map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001070 }
1071 fn importWrappedKey(
1072 &self,
1073 key: &KeyDescriptor,
1074 wrapping_key: &KeyDescriptor,
1075 masking_key: Option<&[u8]>,
1076 params: &[KeyParameter],
1077 authenticators: &[AuthenticatorSpec],
Stephen Crane23cf7242022-01-19 17:49:46 +00001078 ) -> binder::Result<KeyMetadata> {
David Drysdale541846b2024-05-23 13:16:07 +01001079 let _wp = self.watch("IKeystoreSecurityLevel::importWrappedKey");
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001080 let result =
1081 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001082 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001083 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +01001084 result.map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001085 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001086 fn convertStorageKeyToEphemeral(
1087 &self,
1088 storage_key: &KeyDescriptor,
Stephen Crane23cf7242022-01-19 17:49:46 +00001089 ) -> binder::Result<EphemeralStorageKeyResponse> {
David Drysdale541846b2024-05-23 13:16:07 +01001090 let _wp = self.watch("IKeystoreSecurityLevel::convertStorageKeyToEphemeral");
David Drysdaledb7ddde2024-06-07 16:22:49 +01001091 self.convert_storage_key_to_ephemeral(storage_key).map_err(into_logged_binder)
Satya Tangirala3361b612021-03-08 14:36:11 -08001092 }
Stephen Crane23cf7242022-01-19 17:49:46 +00001093 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001094 let _wp = self.watch("IKeystoreSecurityLevel::deleteKey");
Pavel Grafov94243c22021-04-21 18:03:11 +01001095 let result = self.delete_key(key);
1096 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +01001097 result.map_err(into_logged_binder)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001098 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001099}
Alice Wangbf6a6932023-11-07 11:47:12 +00001100
1101#[cfg(test)]
1102mod tests {
1103 use super::*;
1104 use crate::error::map_km_error;
1105 use crate::globals::get_keymint_device;
Alice Wangbf6a6932023-11-07 11:47:12 +00001106 use crate::utils::upgrade_keyblob_if_required_with;
1107 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
1108 Algorithm::Algorithm, AttestationKey::AttestationKey, KeyParameter::KeyParameter,
1109 KeyParameterValue::KeyParameterValue, Tag::Tag,
1110 };
1111 use keystore2_crypto::parse_subject_from_certificate;
Alice Wang01c16b62023-11-07 14:27:49 +00001112 use rkpd_client::get_rkpd_attestation_key;
Alice Wangbf6a6932023-11-07 11:47:12 +00001113
1114 #[test]
1115 // This is a helper for a manual test. We want to check that after a system upgrade RKPD
1116 // attestation keys can also be upgraded and stored again with RKPD. The steps are:
1117 // 1. Run this test and check in stdout that no key upgrade happened.
1118 // 2. Perform a system upgrade.
1119 // 3. Run this test and check in stdout that key upgrade did happen.
1120 //
1121 // Note that this test must be run with that same UID every time. Running as root, i.e. UID 0,
1122 // should do the trick. Also, use "--nocapture" flag to get stdout.
1123 fn test_rkpd_attestation_key_upgrade() {
1124 binder::ProcessState::start_thread_pool();
1125 let security_level = SecurityLevel::TRUSTED_ENVIRONMENT;
1126 let (keymint, info, _) = get_keymint_device(&security_level).unwrap();
1127 let key_id = 0;
1128 let mut key_upgraded = false;
1129
1130 let rpc_name = get_remotely_provisioned_component_name(&security_level).unwrap();
1131 let key = get_rkpd_attestation_key(&rpc_name, key_id).unwrap();
1132 assert!(!key.keyBlob.is_empty());
1133 assert!(!key.encodedCertChain.is_empty());
1134
1135 upgrade_keyblob_if_required_with(
1136 &*keymint,
1137 info.versionNumber,
1138 &key.keyBlob,
1139 /*upgrade_params=*/ &[],
1140 /*km_op=*/
1141 |blob| {
1142 let params = vec![
1143 KeyParameter {
1144 tag: Tag::ALGORITHM,
1145 value: KeyParameterValue::Algorithm(Algorithm::AES),
1146 },
1147 KeyParameter {
1148 tag: Tag::ATTESTATION_CHALLENGE,
1149 value: KeyParameterValue::Blob(vec![0; 16]),
1150 },
1151 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(128) },
1152 ];
1153 let attestation_key = AttestationKey {
1154 keyBlob: blob.to_vec(),
1155 attestKeyParams: vec![],
1156 issuerSubjectName: parse_subject_from_certificate(&key.encodedCertChain)
1157 .unwrap(),
1158 };
1159
1160 map_km_error(keymint.generateKey(&params, Some(&attestation_key)))
1161 },
1162 /*new_blob_handler=*/
1163 |new_blob| {
1164 // This handler is only executed if a key upgrade was performed.
1165 key_upgraded = true;
David Drysdale541846b2024-05-23 13:16:07 +01001166 let _wp = wd::watch("Calling store_rkpd_attestation_key()");
Alice Wangbf6a6932023-11-07 11:47:12 +00001167 store_rkpd_attestation_key(&rpc_name, &key.keyBlob, new_blob).unwrap();
1168 Ok(())
1169 },
1170 )
1171 .unwrap();
1172
1173 if key_upgraded {
1174 println!("RKPD key was upgraded and stored with RKPD.");
1175 } else {
1176 println!("RKPD key was NOT upgraded.");
1177 }
1178 }
1179}