blob: 28de1ec8bf2dff62ea11bb963ae8ee5d6402db69 [file] [log] [blame]
Janis Danisevskis1af91262020-08-10 14:58:08 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis1af91262020-08-10 14:58:08 -070015//! This crate implements the IKeystoreSecurityLevel interface.
16
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070017use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
Pavel Grafovf45034a2021-05-12 22:35:45 +010018use crate::audit_log::{
19 log_key_deleted, log_key_generated, log_key_imported, log_key_integrity_violation,
20};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080021use crate::database::{BlobInfo, CertificateInfo, KeyIdGuard};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070022use crate::error::{self, map_km_error, map_or_log_err, Error, ErrorCode};
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080023use crate::globals::{DB, ENFORCEMENTS, LEGACY_IMPORTER, SUPER_KEY};
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070024use crate::key_parameter::KeyParameter as KsKeyParam;
25use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000026use crate::metrics_store::log_key_creation_event_stats;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070027use crate::remote_provisioning::RemProvState;
28use crate::super_key::{KeyBlob, SuperKeyManager};
29use crate::utils::{
Seth Moore66d9e902022-03-16 17:20:31 -070030 check_device_attestation_permissions, check_key_permission,
31 check_unique_id_attestation_permissions, is_device_id_attestation_tag,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070032 key_characteristics_to_internal, uid_to_android_user, watchdog as wd,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070033};
34use crate::{
35 database::{
36 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
37 KeyMetaEntry, KeyType, SubComponentType, Uuid,
38 },
39 operation::KeystoreOperation,
40 operation::LoggingInfo,
41 operation::OperationDb,
42 permission::KeyPerm,
43};
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070044use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
Shawn Willden708744a2020-12-11 13:05:27 +000045use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070046 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070047 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
48 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080049 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
50 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070051};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000052use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070053use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070054 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
Janis Danisevskisb2434d02021-04-20 12:49:27 -070055 Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
56 IKeystoreOperation::IKeystoreOperation, IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070057 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000058 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, ResponseCode::ResponseCode,
Janis Danisevskis1af91262020-08-10 14:58:08 -070059};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080060use anyhow::{anyhow, Context, Result};
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000061use std::convert::TryInto;
62use std::time::SystemTime;
Janis Danisevskis1af91262020-08-10 14:58:08 -070063
64/// Implementation of the IKeystoreSecurityLevel Interface.
65pub struct KeystoreSecurityLevel {
66 security_level: SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070067 keymint: Strong<dyn IKeyMintDevice>,
Max Bires8e93d2b2021-01-14 13:17:59 -080068 hw_info: KeyMintHardwareInfo,
69 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070070 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080071 rem_prov_state: RemProvState,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070072 id_rotation_state: IdRotationState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070073}
74
Janis Danisevskis1af91262020-08-10 14:58:08 -070075// Blob of 32 zeroes used as empty masking key.
76static ZERO_BLOB_32: &[u8] = &[0; 32];
77
Janis Danisevskis2c084012021-01-31 22:23:17 -080078// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
79// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
80const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
81
Janis Danisevskis1af91262020-08-10 14:58:08 -070082impl KeystoreSecurityLevel {
83 /// Creates a new security level instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +000084 /// BnKeystoreSecurityLevel proxy object. It also enables
85 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070086 /// we need it for checking keystore permissions.
87 pub fn new_native_binder(
88 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070089 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080090 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080091 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
92 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000093 let result = BnKeystoreSecurityLevel::new_binder(
94 Self {
95 security_level,
96 keymint: dev,
97 hw_info,
98 km_uuid,
99 operation_db: OperationDb::new(),
100 rem_prov_state: RemProvState::new(security_level, km_uuid),
101 id_rotation_state,
102 },
103 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
104 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800105 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700106 }
107
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700108 fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
109 let sec_level = self.security_level;
110 wd::watch_millis_with(id, millis, move || format!("SecurityLevel {:?}", sec_level))
111 }
112
Janis Danisevskis1af91262020-08-10 14:58:08 -0700113 fn store_new_key(
114 &self,
115 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700116 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000117 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000118 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700119 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700120 let KeyCreationResult {
121 keyBlob: key_blob,
122 keyCharacteristics: key_characteristics,
123 certificateChain: mut certificate_chain,
124 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700125
Max Bires8e93d2b2021-01-14 13:17:59 -0800126 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700127 match certificate_chain.len() {
128 0 => None,
129 _ => Some(certificate_chain.remove(0).encodedCertificate),
130 },
131 match certificate_chain.len() {
132 0 => None,
133 _ => Some(
134 certificate_chain
135 .iter()
Chariseea1e1c482022-02-26 01:26:35 +0000136 .flat_map(|c| c.encodedCertificate.iter())
Shawn Willdendbdac602021-01-12 22:35:16 -0700137 .copied()
138 .collect(),
139 ),
140 },
141 );
142
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000143 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
144
145 key_parameters.push(KsKeyParam::new(
146 KsKeyParamValue::UserID(user_id as i32),
147 SecurityLevel::SOFTWARE,
148 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700149
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800150 let creation_date = DateTime::now().context("Trying to make creation time.")?;
151
Janis Danisevskis1af91262020-08-10 14:58:08 -0700152 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800153 Domain::BLOB => KeyDescriptor {
154 domain: Domain::BLOB,
155 blob: Some(key_blob.to_vec()),
156 ..Default::default()
157 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700158 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800159 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800160 let mut db = db.borrow_mut();
161
162 let (key_blob, mut blob_metadata) = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800163 .read()
164 .unwrap()
Satya Tangirala60671e32021-03-04 16:12:19 -0800165 .handle_super_encryption_on_key_init(
166 &mut db,
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800167 &LEGACY_IMPORTER,
Satya Tangirala60671e32021-03-04 16:12:19 -0800168 &(key.domain),
169 &key_parameters,
170 flags,
171 user_id,
172 &key_blob,
173 )
174 .context("In store_new_key. Failed to handle super encryption.")?;
175
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176 let mut key_metadata = KeyMetaData::new();
177 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800178 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800179
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800180 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800181 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800182 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700183 KeyType::Client,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800184 &key_parameters,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800185 &BlobInfo::new(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800186 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800187 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800188 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800189 )
190 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700191 Ok(KeyDescriptor {
192 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800193 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700194 ..Default::default()
195 })
196 })
197 .context("In store_new_key.")?,
198 };
199
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700200 Ok(KeyMetadata {
201 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700202 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800203 certificate: cert_info.take_cert(),
204 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700205 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800206 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700207 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700208 }
209
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700210 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700211 &self,
212 key: &KeyDescriptor,
213 operation_parameters: &[KeyParameter],
214 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700215 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700216 let caller_uid = ThreadState::get_calling_uid();
217 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
218 // so that we can use it by reference like the blob provided by the key descriptor.
219 // Otherwise, we would have to clone the blob from the key descriptor.
220 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700222 Domain::BLOB => {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700223 check_key_permission(KeyPerm::Use, key, &None)
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700224 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800225 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700226 check_key_permission(KeyPerm::ReqForcedOp, key, &None).context(
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800227 "In create_operation: checking forced permission for Domain::BLOB.",
228 )?;
229 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700230 (
231 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700232 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700233 None => {
234 return Err(Error::sys()).context(concat!(
235 "In create_operation: Key blob must be specified when",
236 " using Domain::BLOB."
237 ))
238 }
239 },
240 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000241 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000242 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700243 )
244 }
245 _ => {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800246 let super_key = SUPER_KEY
247 .read()
248 .unwrap()
249 .get_per_boot_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisaec14592020-11-12 09:41:49 -0800250 let (key_id_guard, mut key_entry) = DB
251 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800252 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000253 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700254 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000255 KeyType::Client,
256 KeyEntryLoadBits::KM,
257 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800258 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700259 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800260 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700261 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800262 }
263 Ok(())
264 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000265 )
266 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700267 })
268 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800269
270 let (blob, blob_metadata) =
271 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
272 "In create_operation: Successfully loaded key entry, ",
273 "but KM blob was missing."
274 ))?;
275 scoping_blob = blob;
276
Qi Wub9433b52020-12-01 14:52:46 +0800277 (
278 &scoping_blob,
279 Some((key_id_guard.id(), key_entry.into_key_parameters())),
280 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000281 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800282 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700283 }
284 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700285
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700286 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700287 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700288 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800289 |kp| match kp.value {
290 KeyParameterValue::KeyPurpose(p) => Ok(p),
291 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
292 .context("In create_operation: Malformed KeyParameter."),
293 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700294 )?;
295
Satya Tangirala2642ff92021-04-15 01:57:00 -0700296 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
297 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
298 let op_params: Vec<KeyParameter> =
299 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
300 let operation_parameters = op_params.as_slice();
301
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800302 let (immediate_hat, mut auth_info) = ENFORCEMENTS
303 .authorize_create(
304 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800305 key_properties.as_ref(),
306 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700307 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800308 )
309 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000310
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000311 let km_blob = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800312 .read()
313 .unwrap()
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000314 .unwrap_key_if_required(&blob_metadata, km_blob)
315 .context("In create_operation. Failed to handle super encryption.")?;
316
Janis Danisevskisaec14592020-11-12 09:41:49 -0800317 let (begin_result, upgraded_blob) = self
318 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700319 &*self.keymint,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800320 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700321 &km_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800322 blob_metadata.km_uuid().copied(),
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700323 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800324 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700325 match map_km_error({
326 let _wp = self.watch_millis(
327 "In KeystoreSecurityLevel::create_operation: calling begin",
328 500,
329 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700330 self.keymint.begin(
331 purpose,
332 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700333 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700334 immediate_hat.as_ref(),
335 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700336 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800337 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800338 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800339 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700340 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100341 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
342 if let Some((key_id, _)) = key_properties {
343 if let Ok(Some(key)) =
344 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
345 {
346 log_key_integrity_violation(&key);
347 } else {
348 log::error!("Failed to load key descriptor for audit log");
349 }
350 }
351 return v;
352 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800353 v => return v,
354 }
355 },
356 )
357 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700358
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800359 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000360
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000361 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
362
Janis Danisevskis1af91262020-08-10 14:58:08 -0700363 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700364 Some(km_op) => self.operation_db.create_operation(
365 km_op,
366 caller_uid,
367 auth_info,
368 forced,
369 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
370 ),
371 None => {
372 return Err(Error::sys()).context(concat!(
373 "In create_operation: Begin operation returned successfully, ",
374 "but did not return a valid operation."
375 ))
376 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700377 };
378
Stephen Crane23cf7242022-01-19 17:49:46 +0000379 let op_binder: binder::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700380 KeystoreOperation::new_native_binder(operation)
381 .as_binder()
382 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700383 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700384
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700385 Ok(CreateOperationResponse {
386 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000387 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700388 parameters: match begin_result.params.len() {
389 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700390 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700391 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800392 // An upgraded blob should only be returned if the caller has permission
393 // to use Domain::BLOB keys. If we got to this point, we already checked
394 // that the caller had that permission.
395 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700396 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700397 }
398
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000399 fn add_required_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700400 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800401 uid: u32,
402 params: &[KeyParameter],
403 key: &KeyDescriptor,
404 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800405 let mut result = params.to_vec();
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000406
407 // Unconditionally add the CREATION_DATETIME tag and prevent callers from
408 // specifying it.
409 if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
410 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(
411 "In KeystoreSecurityLevel::add_required_parameters: \
412 Specifying Tag::CREATION_DATETIME is not allowed.",
413 );
414 }
415
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800416 // Add CREATION_DATETIME only if the backend version Keymint V1 (100) or newer.
417 if self.hw_info.versionNumber >= 100 {
418 result.push(KeyParameter {
419 tag: Tag::CREATION_DATETIME,
420 value: KeyParameterValue::DateTime(
421 SystemTime::now()
422 .duration_since(SystemTime::UNIX_EPOCH)
423 .context(
424 "In KeystoreSecurityLevel::add_required_parameters: \
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000425 Failed to get epoch time.",
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800426 )?
427 .as_millis()
428 .try_into()
429 .context(
430 "In KeystoreSecurityLevel::add_required_parameters: \
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000431 Failed to convert epoch time.",
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800432 )?,
433 ),
434 });
435 }
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000436
Janis Danisevskis2c084012021-01-31 22:23:17 -0800437 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800438 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700439 let aaid = {
440 let _wp = self.watch_millis(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000441 "In KeystoreSecurityLevel::add_required_parameters calling: get_aaid",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700442 500,
443 );
444 keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000445 anyhow!(format!("In add_required_parameters: get_aaid returned status {}.", e))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700446 })
447 }?;
448
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800449 result.push(KeyParameter {
450 tag: Tag::ATTESTATION_APPLICATION_ID,
451 value: KeyParameterValue::Blob(aaid),
452 });
453 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800454
Janis Danisevskise766edc2021-02-06 12:16:26 -0800455 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Seth Moore66d9e902022-03-16 17:20:31 -0700456 if check_key_permission(KeyPerm::GenUniqueId, key, &None).is_err()
457 && check_unique_id_attestation_permissions().is_err()
458 {
459 return Err(Error::perm()).context(
460 "In add_required_parameters: \
461 Caller does not have the permission to generate a unique ID",
462 );
463 }
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700464 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000465 "In add_required_parameters: Call to had_factory_reset_since_id_rotation failed.",
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700466 )? {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000467 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700468 tag: Tag::RESET_SINCE_ID_ROTATION,
469 value: KeyParameterValue::BoolValue(true),
470 })
471 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800472 }
473
Bram Bonné5d6c5102021-02-24 15:09:18 +0100474 // If the caller requests any device identifier attestation tag, check that they hold the
475 // correct Android permission.
476 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
477 check_device_attestation_permissions().context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000478 "In add_required_parameters: ",
Bram Bonné5d6c5102021-02-24 15:09:18 +0100479 "Caller does not have the permission to attest device identifiers."
480 ))?;
481 }
482
Janis Danisevskis2c084012021-01-31 22:23:17 -0800483 // If we are generating/importing an asymmetric key, we need to make sure
484 // that NOT_BEFORE and NOT_AFTER are present.
485 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
486 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
487 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
488 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
489 result.push(KeyParameter {
490 tag: Tag::CERTIFICATE_NOT_BEFORE,
491 value: KeyParameterValue::DateTime(0),
492 })
493 }
494 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
495 result.push(KeyParameter {
496 tag: Tag::CERTIFICATE_NOT_AFTER,
497 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
498 })
499 }
500 }
501 _ => {}
502 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800503 Ok(result)
504 }
505
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 fn generate_key(
507 &self,
508 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700509 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700510 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700511 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700512 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700513 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700514 if key.domain != Domain::BLOB && key.alias.is_none() {
515 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
516 .context("In generate_key: Alias must be specified");
517 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000518 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519
520 let key = match key.domain {
521 Domain::APP => KeyDescriptor {
522 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000523 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700524 alias: key.alias.clone(),
525 blob: None,
526 },
527 _ => key.clone(),
528 };
529
530 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700531 // Must return on error for security reasons.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700532 check_key_permission(KeyPerm::Rebind, &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700533
534 let attestation_key_info = match (key.domain, attest_key_descriptor) {
535 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800536 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700537 .with(|db| {
538 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800539 &key,
540 caller_uid,
541 attest_key_descriptor,
542 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700543 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800544 &mut db.borrow_mut(),
545 )
546 })
547 .context("In generate_key: Trying to get an attestation key")?,
548 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700549 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000550 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800551 .context("In generate_key: Trying to get aaid.")?;
552
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700553 let creation_result = match attestation_key_info {
554 Some(AttestationKeyInfo::UserGenerated {
555 key_id_guard,
556 blob,
557 blob_metadata,
558 issuer_subject,
559 }) => self
560 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700561 &*self.keymint,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700562 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700563 &KeyBlob::Ref(&blob),
Max Bires55620ff2022-02-11 13:34:15 -0800564 blob_metadata.km_uuid().copied(),
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700565 &params,
566 |blob| {
567 let attest_key = Some(AttestationKey {
568 keyBlob: blob.to_vec(),
569 attestKeyParams: vec![],
570 issuerSubjectName: issuer_subject.clone(),
571 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700572 map_km_error({
573 let _wp = self.watch_millis(
574 concat!(
575 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
576 "calling generate_key."
577 ),
578 5000, // Generate can take a little longer.
579 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700580 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700581 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700582 },
583 )
584 .context("In generate_key: Using user generated attestation key.")
585 .map(|(result, _)| result),
Max Bires55620ff2022-02-11 13:34:15 -0800586 Some(AttestationKeyInfo::RemoteProvisioned {
587 key_id_guard,
588 attestation_key,
589 attestation_certs,
590 }) => self
591 .upgrade_keyblob_if_required_with(
592 &*self.keymint,
593 Some(key_id_guard),
594 &KeyBlob::Ref(&attestation_key.keyBlob),
595 Some(self.rem_prov_state.get_uuid()),
596 &[],
597 |blob| {
598 map_km_error({
599 let _wp = self.watch_millis(
600 concat!(
601 "In KeystoreSecurityLevel::generate_key (RemoteProvisioned): ",
602 "calling generate_key.",
603 ),
604 5000, // Generate can take a little longer.
605 );
606 let dynamic_attest_key = Some(AttestationKey {
607 keyBlob: blob.to_vec(),
608 attestKeyParams: vec![],
609 issuerSubjectName: attestation_key.issuerSubjectName.clone(),
610 });
611 self.keymint.generateKey(&params, dynamic_attest_key.as_ref())
612 })
613 },
614 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700615 .context("While generating Key with remote provisioned attestation key.")
Max Bires55620ff2022-02-11 13:34:15 -0800616 .map(|(mut result, _)| {
617 result.certificateChain.push(attestation_certs);
618 result
619 }),
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700620 None => map_km_error({
621 let _wp = self.watch_millis(
622 concat!(
623 "In KeystoreSecurityLevel::generate_key (No attestation): ",
624 "calling generate_key.",
625 ),
626 5000, // Generate can take a little longer.
627 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700628 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700629 })
630 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800631 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700632 .context("In generate_key.")?;
633
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000634 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000635 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700636 }
637
638 fn import_key(
639 &self,
640 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700641 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700642 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700643 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700644 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700645 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700646 if key.domain != Domain::BLOB && key.alias.is_none() {
647 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
648 .context("In import_key: Alias must be specified");
649 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000650 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700651
652 let key = match key.domain {
653 Domain::APP => KeyDescriptor {
654 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000655 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700656 alias: key.alias.clone(),
657 blob: None,
658 },
659 _ => key.clone(),
660 };
661
662 // import_key requires the rebind permission.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700663 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700664
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700665 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000666 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800667 .context("In import_key: Trying to get aaid.")?;
668
Janis Danisevskis1af91262020-08-10 14:58:08 -0700669 let format = params
670 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700671 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700672 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
673 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800674 .and_then(|p| match &p.value {
675 KeyParameterValue::Algorithm(Algorithm::AES)
676 | KeyParameterValue::Algorithm(Algorithm::HMAC)
677 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
678 KeyParameterValue::Algorithm(Algorithm::RSA)
679 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
680 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
681 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700682 })
683 .context("In import_key.")?;
684
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700685 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700686 let creation_result = map_km_error({
687 let _wp =
688 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
689 km_dev.importKey(&params, format, key_data, None /* attestKey */)
690 })
691 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700692
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000693 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000694 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700695 }
696
697 fn import_wrapped_key(
698 &self,
699 key: &KeyDescriptor,
700 wrapping_key: &KeyDescriptor,
701 masking_key: Option<&[u8]>,
702 params: &[KeyParameter],
703 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700704 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800705 let wrapped_data: &[u8] = match key {
706 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
707 | KeyDescriptor {
708 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
709 } => blob,
710 _ => {
711 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
712 concat!(
713 "In import_wrapped_key: Alias and blob must be specified ",
714 "and domain must be APP or SELINUX. {:?}"
715 ),
716 key
717 ))
718 }
719 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700720
Janis Danisevskisaec14592020-11-12 09:41:49 -0800721 if wrapping_key.domain == Domain::BLOB {
722 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
723 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
724 );
725 }
726
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000727 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000728 let user_id = uid_to_android_user(caller_uid);
729
Janis Danisevskis1af91262020-08-10 14:58:08 -0700730 let key = match key.domain {
731 Domain::APP => KeyDescriptor {
732 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000733 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700734 alias: key.alias.clone(),
735 blob: None,
736 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800737 Domain::SELINUX => KeyDescriptor {
738 domain: Domain::SELINUX,
739 nspace: key.nspace,
740 alias: key.alias.clone(),
741 blob: None,
742 },
743 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700744 };
745
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800746 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700747 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700748
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800749 let super_key = SUPER_KEY.read().unwrap().get_per_boot_key_by_user_id(user_id);
750
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000751 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700752 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800753 LEGACY_IMPORTER.with_try_import(&key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000754 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700755 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000756 KeyType::Client,
757 KeyEntryLoadBits::KM,
758 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700759 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000760 )
761 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700762 })
763 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000764
765 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
766 .take_key_blob_info()
767 .ok_or_else(error::Error::sys)
768 .context("No km_blob after successfully loading key. This should never happen.")?;
769
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800770 let wrapping_key_blob = SUPER_KEY
771 .read()
772 .unwrap()
773 .unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob)
774 .context(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000775 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
776 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700777
Janis Danisevskis1af91262020-08-10 14:58:08 -0700778 // km_dev.importWrappedKey does not return a certificate chain.
779 // TODO Do we assume that all wrapped keys are symmetric?
780 // let certificate_chain: Vec<KmCertificate> = Default::default();
781
782 let pw_sid = authenticators
783 .iter()
784 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700785 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700786 _ => None,
787 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800788 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700789
790 let fp_sid = authenticators
791 .iter()
792 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700793 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700794 _ => None,
795 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800796 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700797
798 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
799
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800800 let (creation_result, _) = self
801 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700802 &*self.keymint,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800803 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700804 &wrapping_key_blob,
Max Bires55620ff2022-02-11 13:34:15 -0800805 wrapping_blob_metadata.km_uuid().copied(),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800806 &[],
807 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700808 let _wp = self.watch_millis(
809 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
810 500,
811 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700812 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800813 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800814 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800815 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700816 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800817 pw_sid,
818 fp_sid,
819 ))?;
820 Ok(creation_result)
821 },
822 )
823 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700824
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000825 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800826 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700827 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800828
Paul Crowley7a658392021-03-18 17:08:20 -0700829 fn store_upgraded_keyblob(
830 key_id_guard: KeyIdGuard,
Max Bires55620ff2022-02-11 13:34:15 -0800831 km_uuid: Option<Uuid>,
Paul Crowley7a658392021-03-18 17:08:20 -0700832 key_blob: &KeyBlob,
833 upgraded_blob: &[u8],
834 ) -> Result<()> {
835 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700836 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Paul Crowley7a658392021-03-18 17:08:20 -0700837 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
838
Paul Crowley44c02da2021-04-08 17:04:43 +0000839 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700840 if let Some(uuid) = km_uuid {
Max Bires55620ff2022-02-11 13:34:15 -0800841 new_blob_metadata.add(BlobMetaEntry::KmUuid(uuid));
Paul Crowley7a658392021-03-18 17:08:20 -0700842 }
843
844 DB.with(|db| {
845 let mut db = db.borrow_mut();
846 db.set_blob(
847 &key_id_guard,
848 SubComponentType::KEY_BLOB,
849 Some(&upgraded_blob_to_be_stored),
850 Some(&new_blob_metadata),
851 )
852 })
853 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
854 }
855
Janis Danisevskisaec14592020-11-12 09:41:49 -0800856 fn upgrade_keyblob_if_required_with<T, F>(
857 &self,
858 km_dev: &dyn IKeyMintDevice,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800859 mut key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700860 key_blob: &KeyBlob,
Max Bires55620ff2022-02-11 13:34:15 -0800861 km_uuid: Option<Uuid>,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800862 params: &[KeyParameter],
863 f: F,
864 ) -> Result<(T, Option<Vec<u8>>)>
865 where
866 F: Fn(&[u8]) -> Result<T, Error>,
867 {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800868 let (v, upgraded_blob) = crate::utils::upgrade_keyblob_if_required_with(
869 km_dev,
870 key_blob,
871 params,
872 f,
873 |upgraded_blob| {
874 if key_id_guard.is_some() {
875 // Unwrap cannot panic, because the is_some was true.
876 let kid = key_id_guard.take().unwrap();
Max Bires55620ff2022-02-11 13:34:15 -0800877 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, upgraded_blob).context(
878 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Paul Crowley7a658392021-03-18 17:08:20 -0700879 )
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800880 } else {
881 Ok(())
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000882 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800883 },
884 )
885 .context("In KeystoreSecurityLevel::upgrade_keyblob_if_required_with.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000886
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800887 // If no upgrade was needed, use the opportunity to reencrypt the blob if required
888 // and if the a key_id_guard is held. Note: key_id_guard can only be Some if no
889 // upgrade was performed above and if one was given in the first place.
890 if key_blob.force_reencrypt() {
891 if let Some(kid) = key_id_guard {
Max Bires55620ff2022-02-11 13:34:15 -0800892 Self::store_upgraded_keyblob(kid, km_uuid, key_blob, key_blob).context(concat!(
893 "In upgrade_keyblob_if_required_with: ",
894 "store_upgraded_keyblob failed in forced reencrypt"
895 ))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700896 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800897 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800898 Ok((v, upgraded_blob))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800899 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800900
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700901 fn convert_storage_key_to_ephemeral(
902 &self,
903 storage_key: &KeyDescriptor,
904 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800905 if storage_key.domain != Domain::BLOB {
906 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
907 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
908 "Key must be of Domain::BLOB"
909 ));
910 }
911 let key_blob = storage_key
912 .blob
913 .as_ref()
914 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
915 .context(
916 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
917 )?;
918
919 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700920 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Satya Tangirala3361b612021-03-08 14:36:11 -0800921 .context("In convert_storage_key_to_ephemeral: Check permission")?;
922
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700923 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700924 match {
925 let _wp = self.watch_millis(
926 concat!(
927 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
928 "calling convertStorageKeyToEphemeral (1)"
929 ),
930 500,
931 );
932 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
933 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700934 Ok(result) => {
935 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
936 }
937 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700938 let upgraded_blob = {
939 let _wp = self.watch_millis(
940 "In convert_storage_key_to_ephemeral: calling upgradeKey",
941 500,
942 );
943 map_km_error(km_dev.upgradeKey(key_blob, &[]))
944 }
945 .context("In convert_storage_key_to_ephemeral: Failed to upgrade key blob.")?;
946 let ephemeral_key = {
947 let _wp = self.watch_millis(
948 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
949 500,
950 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700951 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700952 }
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700953 .context(concat!(
954 "In convert_storage_key_to_ephemeral: ",
955 "Failed to retrieve ephemeral key (after upgrade)."
956 ))?;
957 Ok(EphemeralStorageKeyResponse {
958 ephemeralKey: ephemeral_key,
959 upgradedBlob: Some(upgraded_blob),
960 })
961 }
962 Err(e) => Err(e)
963 .context("In convert_storage_key_to_ephemeral: Failed to retrieve ephemeral key."),
964 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800965 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800966
967 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
968 if key.domain != Domain::BLOB {
969 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
970 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
971 }
972
973 let key_blob = key
974 .blob
975 .as_ref()
976 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
977 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
978
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700979 check_key_permission(KeyPerm::Delete, key, &None)
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800980 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
981
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700982 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700983 {
984 let _wp =
985 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700986 map_km_error(km_dev.deleteKey(key_blob)).context("In keymint device deleteKey")
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700987 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800988 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700989}
990
991impl binder::Interface for KeystoreSecurityLevel {}
992
993impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700994 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700995 &self,
996 key: &KeyDescriptor,
997 operation_parameters: &[KeyParameter],
998 forced: bool,
Stephen Crane23cf7242022-01-19 17:49:46 +0000999 ) -> binder::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001000 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001001 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001002 }
1003 fn generateKey(
1004 &self,
1005 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001006 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001007 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001008 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001009 entropy: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001010 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001011 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1012 // time than other operations
1013 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001014 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001015 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001016 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001017 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001018 }
1019 fn importKey(
1020 &self,
1021 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001022 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001023 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001024 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001025 key_data: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001026 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001027 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001028 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001029 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001030 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001031 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001032 }
1033 fn importWrappedKey(
1034 &self,
1035 key: &KeyDescriptor,
1036 wrapping_key: &KeyDescriptor,
1037 masking_key: Option<&[u8]>,
1038 params: &[KeyParameter],
1039 authenticators: &[AuthenticatorSpec],
Stephen Crane23cf7242022-01-19 17:49:46 +00001040 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001041 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001042 let result =
1043 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001044 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001045 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001046 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001047 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001048 fn convertStorageKeyToEphemeral(
1049 &self,
1050 storage_key: &KeyDescriptor,
Stephen Crane23cf7242022-01-19 17:49:46 +00001051 ) -> binder::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001052 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001053 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1054 }
Stephen Crane23cf7242022-01-19 17:49:46 +00001055 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001056 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001057 let result = self.delete_key(key);
1058 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1059 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001060 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001061}