blob: 4cf41c509771d209d71a8fdc0c1bf1d800b2a736 [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::{
30 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070031 key_characteristics_to_internal, uid_to_android_user, watchdog as wd,
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070032};
33use crate::{
34 database::{
35 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
36 KeyMetaEntry, KeyType, SubComponentType, Uuid,
37 },
38 operation::KeystoreOperation,
39 operation::LoggingInfo,
40 operation::OperationDb,
41 permission::KeyPerm,
42};
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070043use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
Shawn Willden708744a2020-12-11 13:05:27 +000044use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070045 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070046 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
47 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080048 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
49 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070050};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000051use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070052use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070053 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
Janis Danisevskisb2434d02021-04-20 12:49:27 -070054 Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
55 IKeystoreOperation::IKeystoreOperation, IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070056 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000057 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, ResponseCode::ResponseCode,
Janis Danisevskis1af91262020-08-10 14:58:08 -070058};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080059use anyhow::{anyhow, Context, Result};
Janis Danisevskisd43c1b92021-11-09 14:56:17 +000060use std::convert::TryInto;
61use std::time::SystemTime;
Janis Danisevskis1af91262020-08-10 14:58:08 -070062
63/// Implementation of the IKeystoreSecurityLevel Interface.
64pub struct KeystoreSecurityLevel {
65 security_level: SecurityLevel,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070066 keymint: Strong<dyn IKeyMintDevice>,
Max Bires8e93d2b2021-01-14 13:17:59 -080067 hw_info: KeyMintHardwareInfo,
68 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070069 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080070 rem_prov_state: RemProvState,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070071 id_rotation_state: IdRotationState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070072}
73
Janis Danisevskis1af91262020-08-10 14:58:08 -070074// Blob of 32 zeroes used as empty masking key.
75static ZERO_BLOB_32: &[u8] = &[0; 32];
76
Janis Danisevskis2c084012021-01-31 22:23:17 -080077// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
78// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
79const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
80
Janis Danisevskis1af91262020-08-10 14:58:08 -070081impl KeystoreSecurityLevel {
82 /// Creates a new security level instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +000083 /// BnKeystoreSecurityLevel proxy object. It also enables
84 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070085 /// we need it for checking keystore permissions.
86 pub fn new_native_binder(
87 security_level: SecurityLevel,
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070088 id_rotation_state: IdRotationState,
Stephen Crane221bbb52020-12-16 15:52:10 -080089 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080090 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
91 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000092 let result = BnKeystoreSecurityLevel::new_binder(
93 Self {
94 security_level,
95 keymint: dev,
96 hw_info,
97 km_uuid,
98 operation_db: OperationDb::new(),
99 rem_prov_state: RemProvState::new(security_level, km_uuid),
100 id_rotation_state,
101 },
102 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
103 );
Max Bires8e93d2b2021-01-14 13:17:59 -0800104 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700105 }
106
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700107 fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
108 let sec_level = self.security_level;
109 wd::watch_millis_with(id, millis, move || format!("SecurityLevel {:?}", sec_level))
110 }
111
Janis Danisevskis1af91262020-08-10 14:58:08 -0700112 fn store_new_key(
113 &self,
114 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700115 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000116 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000117 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700118 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700119 let KeyCreationResult {
120 keyBlob: key_blob,
121 keyCharacteristics: key_characteristics,
122 certificateChain: mut certificate_chain,
123 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700124
Max Bires8e93d2b2021-01-14 13:17:59 -0800125 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700126 match certificate_chain.len() {
127 0 => None,
128 _ => Some(certificate_chain.remove(0).encodedCertificate),
129 },
130 match certificate_chain.len() {
131 0 => None,
132 _ => Some(
133 certificate_chain
134 .iter()
135 .map(|c| c.encodedCertificate.iter())
136 .flatten()
137 .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,
322 &blob_metadata,
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) {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700456 check_key_permission(KeyPerm::GenUniqueId, key, &None).context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000457 "In add_required_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700458 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800459 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700460 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000461 "In add_required_parameters: Call to had_factory_reset_since_id_rotation failed.",
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700462 )? {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000463 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700464 tag: Tag::RESET_SINCE_ID_ROTATION,
465 value: KeyParameterValue::BoolValue(true),
466 })
467 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800468 }
469
Bram Bonné5d6c5102021-02-24 15:09:18 +0100470 // If the caller requests any device identifier attestation tag, check that they hold the
471 // correct Android permission.
472 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
473 check_device_attestation_permissions().context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000474 "In add_required_parameters: ",
Bram Bonné5d6c5102021-02-24 15:09:18 +0100475 "Caller does not have the permission to attest device identifiers."
476 ))?;
477 }
478
Janis Danisevskis2c084012021-01-31 22:23:17 -0800479 // If we are generating/importing an asymmetric key, we need to make sure
480 // that NOT_BEFORE and NOT_AFTER are present.
481 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
482 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
483 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
484 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
485 result.push(KeyParameter {
486 tag: Tag::CERTIFICATE_NOT_BEFORE,
487 value: KeyParameterValue::DateTime(0),
488 })
489 }
490 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
491 result.push(KeyParameter {
492 tag: Tag::CERTIFICATE_NOT_AFTER,
493 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
494 })
495 }
496 }
497 _ => {}
498 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800499 Ok(result)
500 }
501
Janis Danisevskis1af91262020-08-10 14:58:08 -0700502 fn generate_key(
503 &self,
504 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700505 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700507 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700508 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700509 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700510 if key.domain != Domain::BLOB && key.alias.is_none() {
511 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
512 .context("In generate_key: Alias must be specified");
513 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000514 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700515
516 let key = match key.domain {
517 Domain::APP => KeyDescriptor {
518 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000519 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700520 alias: key.alias.clone(),
521 blob: None,
522 },
523 _ => key.clone(),
524 };
525
526 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700527 // Must return on error for security reasons.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700528 check_key_permission(KeyPerm::Rebind, &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700529
530 let attestation_key_info = match (key.domain, attest_key_descriptor) {
531 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800532 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700533 .with(|db| {
534 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800535 &key,
536 caller_uid,
537 attest_key_descriptor,
538 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700539 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800540 &mut db.borrow_mut(),
541 )
542 })
543 .context("In generate_key: Trying to get an attestation key")?,
544 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700545 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000546 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800547 .context("In generate_key: Trying to get aaid.")?;
548
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700549 let creation_result = match attestation_key_info {
550 Some(AttestationKeyInfo::UserGenerated {
551 key_id_guard,
552 blob,
553 blob_metadata,
554 issuer_subject,
555 }) => self
556 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700557 &*self.keymint,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700558 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700559 &KeyBlob::Ref(&blob),
560 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700561 &params,
562 |blob| {
563 let attest_key = Some(AttestationKey {
564 keyBlob: blob.to_vec(),
565 attestKeyParams: vec![],
566 issuerSubjectName: issuer_subject.clone(),
567 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700568 map_km_error({
569 let _wp = self.watch_millis(
570 concat!(
571 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
572 "calling generate_key."
573 ),
574 5000, // Generate can take a little longer.
575 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700576 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700577 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700578 },
579 )
580 .context("In generate_key: Using user generated attestation key.")
581 .map(|(result, _)| result),
582 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700583 map_km_error({
584 let _wp = self.watch_millis(
585 concat!(
586 "In KeystoreSecurityLevel::generate_key (RemoteProvisioned): ",
587 "calling generate_key.",
588 ),
589 5000, // Generate can take a little longer.
590 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700591 self.keymint.generateKey(&params, Some(&attestation_key))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700592 })
593 .context("While generating Key with remote provisioned attestation key.")
594 .map(|mut creation_result| {
595 creation_result.certificateChain.push(attestation_certs);
596 creation_result
597 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700598 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700599 None => map_km_error({
600 let _wp = self.watch_millis(
601 concat!(
602 "In KeystoreSecurityLevel::generate_key (No attestation): ",
603 "calling generate_key.",
604 ),
605 5000, // Generate can take a little longer.
606 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700607 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700608 })
609 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800610 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700611 .context("In generate_key.")?;
612
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000613 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000614 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700615 }
616
617 fn import_key(
618 &self,
619 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700620 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700621 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700622 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700623 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700624 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700625 if key.domain != Domain::BLOB && key.alias.is_none() {
626 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
627 .context("In import_key: Alias must be specified");
628 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000629 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700630
631 let key = match key.domain {
632 Domain::APP => KeyDescriptor {
633 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000634 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700635 alias: key.alias.clone(),
636 blob: None,
637 },
638 _ => key.clone(),
639 };
640
641 // import_key requires the rebind permission.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700642 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700643
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700644 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000645 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800646 .context("In import_key: Trying to get aaid.")?;
647
Janis Danisevskis1af91262020-08-10 14:58:08 -0700648 let format = params
649 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700650 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700651 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
652 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800653 .and_then(|p| match &p.value {
654 KeyParameterValue::Algorithm(Algorithm::AES)
655 | KeyParameterValue::Algorithm(Algorithm::HMAC)
656 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
657 KeyParameterValue::Algorithm(Algorithm::RSA)
658 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
659 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
660 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700661 })
662 .context("In import_key.")?;
663
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700664 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700665 let creation_result = map_km_error({
666 let _wp =
667 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
668 km_dev.importKey(&params, format, key_data, None /* attestKey */)
669 })
670 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700671
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000672 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000673 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700674 }
675
676 fn import_wrapped_key(
677 &self,
678 key: &KeyDescriptor,
679 wrapping_key: &KeyDescriptor,
680 masking_key: Option<&[u8]>,
681 params: &[KeyParameter],
682 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700683 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800684 let wrapped_data: &[u8] = match key {
685 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
686 | KeyDescriptor {
687 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
688 } => blob,
689 _ => {
690 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
691 concat!(
692 "In import_wrapped_key: Alias and blob must be specified ",
693 "and domain must be APP or SELINUX. {:?}"
694 ),
695 key
696 ))
697 }
698 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700699
Janis Danisevskisaec14592020-11-12 09:41:49 -0800700 if wrapping_key.domain == Domain::BLOB {
701 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
702 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
703 );
704 }
705
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000706 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000707 let user_id = uid_to_android_user(caller_uid);
708
Janis Danisevskis1af91262020-08-10 14:58:08 -0700709 let key = match key.domain {
710 Domain::APP => KeyDescriptor {
711 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000712 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700713 alias: key.alias.clone(),
714 blob: None,
715 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800716 Domain::SELINUX => KeyDescriptor {
717 domain: Domain::SELINUX,
718 nspace: key.nspace,
719 alias: key.alias.clone(),
720 blob: None,
721 },
722 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700723 };
724
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800725 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700726 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700727
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800728 let super_key = SUPER_KEY.read().unwrap().get_per_boot_key_by_user_id(user_id);
729
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000730 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700731 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800732 LEGACY_IMPORTER.with_try_import(&key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000733 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700734 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000735 KeyType::Client,
736 KeyEntryLoadBits::KM,
737 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700738 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000739 )
740 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700741 })
742 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000743
744 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
745 .take_key_blob_info()
746 .ok_or_else(error::Error::sys)
747 .context("No km_blob after successfully loading key. This should never happen.")?;
748
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800749 let wrapping_key_blob = SUPER_KEY
750 .read()
751 .unwrap()
752 .unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob)
753 .context(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000754 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
755 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700756
Janis Danisevskis1af91262020-08-10 14:58:08 -0700757 // km_dev.importWrappedKey does not return a certificate chain.
758 // TODO Do we assume that all wrapped keys are symmetric?
759 // let certificate_chain: Vec<KmCertificate> = Default::default();
760
761 let pw_sid = authenticators
762 .iter()
763 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700764 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700765 _ => None,
766 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800767 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700768
769 let fp_sid = authenticators
770 .iter()
771 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700772 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700773 _ => None,
774 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800775 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700776
777 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
778
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800779 let (creation_result, _) = self
780 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700781 &*self.keymint,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800782 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700783 &wrapping_key_blob,
784 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800785 &[],
786 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700787 let _wp = self.watch_millis(
788 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
789 500,
790 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700791 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800792 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800793 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800794 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700795 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800796 pw_sid,
797 fp_sid,
798 ))?;
799 Ok(creation_result)
800 },
801 )
802 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700803
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000804 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800805 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700806 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800807
Paul Crowley7a658392021-03-18 17:08:20 -0700808 fn store_upgraded_keyblob(
809 key_id_guard: KeyIdGuard,
810 km_uuid: Option<&Uuid>,
811 key_blob: &KeyBlob,
812 upgraded_blob: &[u8],
813 ) -> Result<()> {
814 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700815 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Paul Crowley7a658392021-03-18 17:08:20 -0700816 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
817
Paul Crowley44c02da2021-04-08 17:04:43 +0000818 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700819 if let Some(uuid) = km_uuid {
820 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
821 }
822
823 DB.with(|db| {
824 let mut db = db.borrow_mut();
825 db.set_blob(
826 &key_id_guard,
827 SubComponentType::KEY_BLOB,
828 Some(&upgraded_blob_to_be_stored),
829 Some(&new_blob_metadata),
830 )
831 })
832 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
833 }
834
Janis Danisevskisaec14592020-11-12 09:41:49 -0800835 fn upgrade_keyblob_if_required_with<T, F>(
836 &self,
837 km_dev: &dyn IKeyMintDevice,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800838 mut key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700839 key_blob: &KeyBlob,
840 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800841 params: &[KeyParameter],
842 f: F,
843 ) -> Result<(T, Option<Vec<u8>>)>
844 where
845 F: Fn(&[u8]) -> Result<T, Error>,
846 {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800847 let (v, upgraded_blob) = crate::utils::upgrade_keyblob_if_required_with(
848 km_dev,
849 key_blob,
850 params,
851 f,
852 |upgraded_blob| {
853 if key_id_guard.is_some() {
854 // Unwrap cannot panic, because the is_some was true.
855 let kid = key_id_guard.take().unwrap();
Paul Crowley7a658392021-03-18 17:08:20 -0700856 Self::store_upgraded_keyblob(
857 kid,
858 blob_metadata.km_uuid(),
859 key_blob,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800860 upgraded_blob,
Paul Crowley7a658392021-03-18 17:08:20 -0700861 )
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800862 .context("In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed")
863 } else {
864 Ok(())
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000865 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800866 },
867 )
868 .context("In KeystoreSecurityLevel::upgrade_keyblob_if_required_with.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000869
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800870 // If no upgrade was needed, use the opportunity to reencrypt the blob if required
871 // and if the a key_id_guard is held. Note: key_id_guard can only be Some if no
872 // upgrade was performed above and if one was given in the first place.
873 if key_blob.force_reencrypt() {
874 if let Some(kid) = key_id_guard {
875 Self::store_upgraded_keyblob(kid, blob_metadata.km_uuid(), key_blob, key_blob)
876 .context(concat!(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800877 "In upgrade_keyblob_if_required_with: ",
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800878 "store_upgraded_keyblob failed in forced reencrypt"
879 ))?;
Paul Crowley8d5b2532021-03-19 10:53:07 -0700880 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800881 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800882 Ok((v, upgraded_blob))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800883 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800884
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700885 fn convert_storage_key_to_ephemeral(
886 &self,
887 storage_key: &KeyDescriptor,
888 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800889 if storage_key.domain != Domain::BLOB {
890 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
891 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
892 "Key must be of Domain::BLOB"
893 ));
894 }
895 let key_blob = storage_key
896 .blob
897 .as_ref()
898 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
899 .context(
900 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
901 )?;
902
903 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700904 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Satya Tangirala3361b612021-03-08 14:36:11 -0800905 .context("In convert_storage_key_to_ephemeral: Check permission")?;
906
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700907 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700908 match {
909 let _wp = self.watch_millis(
910 concat!(
911 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
912 "calling convertStorageKeyToEphemeral (1)"
913 ),
914 500,
915 );
916 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
917 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700918 Ok(result) => {
919 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
920 }
921 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700922 let upgraded_blob = {
923 let _wp = self.watch_millis(
924 "In convert_storage_key_to_ephemeral: calling upgradeKey",
925 500,
926 );
927 map_km_error(km_dev.upgradeKey(key_blob, &[]))
928 }
929 .context("In convert_storage_key_to_ephemeral: Failed to upgrade key blob.")?;
930 let ephemeral_key = {
931 let _wp = self.watch_millis(
932 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
933 500,
934 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700935 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700936 }
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700937 .context(concat!(
938 "In convert_storage_key_to_ephemeral: ",
939 "Failed to retrieve ephemeral key (after upgrade)."
940 ))?;
941 Ok(EphemeralStorageKeyResponse {
942 ephemeralKey: ephemeral_key,
943 upgradedBlob: Some(upgraded_blob),
944 })
945 }
946 Err(e) => Err(e)
947 .context("In convert_storage_key_to_ephemeral: Failed to retrieve ephemeral key."),
948 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800949 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800950
951 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
952 if key.domain != Domain::BLOB {
953 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
954 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
955 }
956
957 let key_blob = key
958 .blob
959 .as_ref()
960 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
961 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
962
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700963 check_key_permission(KeyPerm::Delete, key, &None)
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800964 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
965
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700966 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700967 {
968 let _wp =
969 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700970 map_km_error(km_dev.deleteKey(key_blob)).context("In keymint device deleteKey")
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700971 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800972 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700973}
974
975impl binder::Interface for KeystoreSecurityLevel {}
976
977impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700978 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700979 &self,
980 key: &KeyDescriptor,
981 operation_parameters: &[KeyParameter],
982 forced: bool,
Stephen Crane23cf7242022-01-19 17:49:46 +0000983 ) -> binder::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000984 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700985 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700986 }
987 fn generateKey(
988 &self,
989 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700990 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700991 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700992 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700993 entropy: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +0000994 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000995 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
996 // time than other operations
997 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +0000998 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000999 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001000 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001001 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001002 }
1003 fn importKey(
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 key_data: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001010 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001011 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001012 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001013 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001014 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001015 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001016 }
1017 fn importWrappedKey(
1018 &self,
1019 key: &KeyDescriptor,
1020 wrapping_key: &KeyDescriptor,
1021 masking_key: Option<&[u8]>,
1022 params: &[KeyParameter],
1023 authenticators: &[AuthenticatorSpec],
Stephen Crane23cf7242022-01-19 17:49:46 +00001024 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001025 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001026 let result =
1027 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001028 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001029 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001030 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001031 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001032 fn convertStorageKeyToEphemeral(
1033 &self,
1034 storage_key: &KeyDescriptor,
Stephen Crane23cf7242022-01-19 17:49:46 +00001035 ) -> binder::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001036 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001037 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1038 }
Stephen Crane23cf7242022-01-19 17:49:46 +00001039 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001040 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001041 let result = self.delete_key(key);
1042 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1043 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001044 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001045}