blob: 83f0bee3f90eeaad8740c1713d3d76e6548728d4 [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 Danisevskis2ee014b2021-05-05 14:29:08 -070021use crate::database::{CertificateInfo, KeyIdGuard};
22use crate::error::{self, map_km_error, map_or_log_err, Error, ErrorCode};
23use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
24use 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,
167 &LEGACY_MIGRATOR,
168 &(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 Danisevskis7e8b4622021-02-13 10:01:59 -0800185 &(&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 Danisevskisaec14592020-11-12 09:41:49 -0800246 let (key_id_guard, mut key_entry) = DB
247 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700248 LEGACY_MIGRATOR.with_try_migrate(key, caller_uid, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000249 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700250 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000251 KeyType::Client,
252 KeyEntryLoadBits::KM,
253 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800254 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700255 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800256 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700257 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800258 }
259 Ok(())
260 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000261 )
262 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700263 })
264 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800265
266 let (blob, blob_metadata) =
267 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
268 "In create_operation: Successfully loaded key entry, ",
269 "but KM blob was missing."
270 ))?;
271 scoping_blob = blob;
272
Qi Wub9433b52020-12-01 14:52:46 +0800273 (
274 &scoping_blob,
275 Some((key_id_guard.id(), key_entry.into_key_parameters())),
276 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000277 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800278 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700279 }
280 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700281
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700282 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700283 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700284 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800285 |kp| match kp.value {
286 KeyParameterValue::KeyPurpose(p) => Ok(p),
287 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
288 .context("In create_operation: Malformed KeyParameter."),
289 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700290 )?;
291
Satya Tangirala2642ff92021-04-15 01:57:00 -0700292 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
293 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
294 let op_params: Vec<KeyParameter> =
295 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
296 let operation_parameters = op_params.as_slice();
297
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800298 let (immediate_hat, mut auth_info) = ENFORCEMENTS
299 .authorize_create(
300 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800301 key_properties.as_ref(),
302 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700303 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800304 )
305 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000306
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000307 let km_blob = SUPER_KEY
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800308 .read()
309 .unwrap()
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000310 .unwrap_key_if_required(&blob_metadata, km_blob)
311 .context("In create_operation. Failed to handle super encryption.")?;
312
Janis Danisevskisaec14592020-11-12 09:41:49 -0800313 let (begin_result, upgraded_blob) = self
314 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700315 &*self.keymint,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800316 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700317 &km_blob,
318 &blob_metadata,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700319 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800320 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700321 match map_km_error({
322 let _wp = self.watch_millis(
323 "In KeystoreSecurityLevel::create_operation: calling begin",
324 500,
325 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700326 self.keymint.begin(
327 purpose,
328 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700329 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700330 immediate_hat.as_ref(),
331 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700332 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800333 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800334 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800335 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700336 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100337 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
338 if let Some((key_id, _)) = key_properties {
339 if let Ok(Some(key)) =
340 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
341 {
342 log_key_integrity_violation(&key);
343 } else {
344 log::error!("Failed to load key descriptor for audit log");
345 }
346 }
347 return v;
348 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800349 v => return v,
350 }
351 },
352 )
353 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700354
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800355 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000356
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000357 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
358
Janis Danisevskis1af91262020-08-10 14:58:08 -0700359 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700360 Some(km_op) => self.operation_db.create_operation(
361 km_op,
362 caller_uid,
363 auth_info,
364 forced,
365 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
366 ),
367 None => {
368 return Err(Error::sys()).context(concat!(
369 "In create_operation: Begin operation returned successfully, ",
370 "but did not return a valid operation."
371 ))
372 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700373 };
374
Stephen Crane23cf7242022-01-19 17:49:46 +0000375 let op_binder: binder::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700376 KeystoreOperation::new_native_binder(operation)
377 .as_binder()
378 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700379 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700380
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700381 Ok(CreateOperationResponse {
382 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000383 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700384 parameters: match begin_result.params.len() {
385 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700386 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700387 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800388 // An upgraded blob should only be returned if the caller has permission
389 // to use Domain::BLOB keys. If we got to this point, we already checked
390 // that the caller had that permission.
391 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700392 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700393 }
394
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000395 fn add_required_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700396 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800397 uid: u32,
398 params: &[KeyParameter],
399 key: &KeyDescriptor,
400 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800401 let mut result = params.to_vec();
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000402
403 // Unconditionally add the CREATION_DATETIME tag and prevent callers from
404 // specifying it.
405 if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
406 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(
407 "In KeystoreSecurityLevel::add_required_parameters: \
408 Specifying Tag::CREATION_DATETIME is not allowed.",
409 );
410 }
411
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800412 // Add CREATION_DATETIME only if the backend version Keymint V1 (100) or newer.
413 if self.hw_info.versionNumber >= 100 {
414 result.push(KeyParameter {
415 tag: Tag::CREATION_DATETIME,
416 value: KeyParameterValue::DateTime(
417 SystemTime::now()
418 .duration_since(SystemTime::UNIX_EPOCH)
419 .context(
420 "In KeystoreSecurityLevel::add_required_parameters: \
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000421 Failed to get epoch time.",
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800422 )?
423 .as_millis()
424 .try_into()
425 .context(
426 "In KeystoreSecurityLevel::add_required_parameters: \
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000427 Failed to convert epoch time.",
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800428 )?,
429 ),
430 });
431 }
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000432
Janis Danisevskis2c084012021-01-31 22:23:17 -0800433 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800434 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700435 let aaid = {
436 let _wp = self.watch_millis(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000437 "In KeystoreSecurityLevel::add_required_parameters calling: get_aaid",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700438 500,
439 );
440 keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000441 anyhow!(format!("In add_required_parameters: get_aaid returned status {}.", e))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700442 })
443 }?;
444
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800445 result.push(KeyParameter {
446 tag: Tag::ATTESTATION_APPLICATION_ID,
447 value: KeyParameterValue::Blob(aaid),
448 });
449 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800450
Janis Danisevskise766edc2021-02-06 12:16:26 -0800451 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700452 check_key_permission(KeyPerm::GenUniqueId, key, &None).context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000453 "In add_required_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700454 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800455 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700456 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000457 "In add_required_parameters: Call to had_factory_reset_since_id_rotation failed.",
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700458 )? {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000459 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700460 tag: Tag::RESET_SINCE_ID_ROTATION,
461 value: KeyParameterValue::BoolValue(true),
462 })
463 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800464 }
465
Bram Bonné5d6c5102021-02-24 15:09:18 +0100466 // If the caller requests any device identifier attestation tag, check that they hold the
467 // correct Android permission.
468 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
469 check_device_attestation_permissions().context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000470 "In add_required_parameters: ",
Bram Bonné5d6c5102021-02-24 15:09:18 +0100471 "Caller does not have the permission to attest device identifiers."
472 ))?;
473 }
474
Janis Danisevskis2c084012021-01-31 22:23:17 -0800475 // If we are generating/importing an asymmetric key, we need to make sure
476 // that NOT_BEFORE and NOT_AFTER are present.
477 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
478 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
479 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
480 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
481 result.push(KeyParameter {
482 tag: Tag::CERTIFICATE_NOT_BEFORE,
483 value: KeyParameterValue::DateTime(0),
484 })
485 }
486 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
487 result.push(KeyParameter {
488 tag: Tag::CERTIFICATE_NOT_AFTER,
489 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
490 })
491 }
492 }
493 _ => {}
494 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800495 Ok(result)
496 }
497
Janis Danisevskis1af91262020-08-10 14:58:08 -0700498 fn generate_key(
499 &self,
500 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700501 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700502 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700503 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700504 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700505 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700506 if key.domain != Domain::BLOB && key.alias.is_none() {
507 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
508 .context("In generate_key: Alias must be specified");
509 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000510 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700511
512 let key = match key.domain {
513 Domain::APP => KeyDescriptor {
514 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000515 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700516 alias: key.alias.clone(),
517 blob: None,
518 },
519 _ => key.clone(),
520 };
521
522 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700523 // Must return on error for security reasons.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700524 check_key_permission(KeyPerm::Rebind, &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700525
526 let attestation_key_info = match (key.domain, attest_key_descriptor) {
527 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800528 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700529 .with(|db| {
530 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800531 &key,
532 caller_uid,
533 attest_key_descriptor,
534 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700535 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800536 &mut db.borrow_mut(),
537 )
538 })
539 .context("In generate_key: Trying to get an attestation key")?,
540 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700541 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000542 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800543 .context("In generate_key: Trying to get aaid.")?;
544
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700545 let creation_result = match attestation_key_info {
546 Some(AttestationKeyInfo::UserGenerated {
547 key_id_guard,
548 blob,
549 blob_metadata,
550 issuer_subject,
551 }) => self
552 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700553 &*self.keymint,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700554 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700555 &KeyBlob::Ref(&blob),
556 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700557 &params,
558 |blob| {
559 let attest_key = Some(AttestationKey {
560 keyBlob: blob.to_vec(),
561 attestKeyParams: vec![],
562 issuerSubjectName: issuer_subject.clone(),
563 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700564 map_km_error({
565 let _wp = self.watch_millis(
566 concat!(
567 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
568 "calling generate_key."
569 ),
570 5000, // Generate can take a little longer.
571 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700572 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700573 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700574 },
575 )
576 .context("In generate_key: Using user generated attestation key.")
577 .map(|(result, _)| result),
578 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700579 map_km_error({
580 let _wp = self.watch_millis(
581 concat!(
582 "In KeystoreSecurityLevel::generate_key (RemoteProvisioned): ",
583 "calling generate_key.",
584 ),
585 5000, // Generate can take a little longer.
586 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700587 self.keymint.generateKey(&params, Some(&attestation_key))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700588 })
589 .context("While generating Key with remote provisioned attestation key.")
590 .map(|mut creation_result| {
591 creation_result.certificateChain.push(attestation_certs);
592 creation_result
593 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700594 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700595 None => map_km_error({
596 let _wp = self.watch_millis(
597 concat!(
598 "In KeystoreSecurityLevel::generate_key (No attestation): ",
599 "calling generate_key.",
600 ),
601 5000, // Generate can take a little longer.
602 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700603 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700604 })
605 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800606 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700607 .context("In generate_key.")?;
608
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000609 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000610 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700611 }
612
613 fn import_key(
614 &self,
615 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700616 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700617 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700618 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700619 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700620 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700621 if key.domain != Domain::BLOB && key.alias.is_none() {
622 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
623 .context("In import_key: Alias must be specified");
624 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000625 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700626
627 let key = match key.domain {
628 Domain::APP => KeyDescriptor {
629 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000630 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631 alias: key.alias.clone(),
632 blob: None,
633 },
634 _ => key.clone(),
635 };
636
637 // import_key requires the rebind permission.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700638 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700639
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700640 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000641 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800642 .context("In import_key: Trying to get aaid.")?;
643
Janis Danisevskis1af91262020-08-10 14:58:08 -0700644 let format = params
645 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700646 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700647 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
648 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800649 .and_then(|p| match &p.value {
650 KeyParameterValue::Algorithm(Algorithm::AES)
651 | KeyParameterValue::Algorithm(Algorithm::HMAC)
652 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
653 KeyParameterValue::Algorithm(Algorithm::RSA)
654 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
655 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
656 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700657 })
658 .context("In import_key.")?;
659
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700660 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700661 let creation_result = map_km_error({
662 let _wp =
663 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
664 km_dev.importKey(&params, format, key_data, None /* attestKey */)
665 })
666 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700667
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000668 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000669 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700670 }
671
672 fn import_wrapped_key(
673 &self,
674 key: &KeyDescriptor,
675 wrapping_key: &KeyDescriptor,
676 masking_key: Option<&[u8]>,
677 params: &[KeyParameter],
678 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700679 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800680 let wrapped_data: &[u8] = match key {
681 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
682 | KeyDescriptor {
683 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
684 } => blob,
685 _ => {
686 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
687 concat!(
688 "In import_wrapped_key: Alias and blob must be specified ",
689 "and domain must be APP or SELINUX. {:?}"
690 ),
691 key
692 ))
693 }
694 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700695
Janis Danisevskisaec14592020-11-12 09:41:49 -0800696 if wrapping_key.domain == Domain::BLOB {
697 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
698 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
699 );
700 }
701
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000702 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000703 let user_id = uid_to_android_user(caller_uid);
704
Janis Danisevskis1af91262020-08-10 14:58:08 -0700705 let key = match key.domain {
706 Domain::APP => KeyDescriptor {
707 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000708 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700709 alias: key.alias.clone(),
710 blob: None,
711 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800712 Domain::SELINUX => KeyDescriptor {
713 domain: Domain::SELINUX,
714 nspace: key.nspace,
715 alias: key.alias.clone(),
716 blob: None,
717 },
718 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700719 };
720
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800721 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700722 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700723
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000724 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700725 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000726 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
727 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700728 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000729 KeyType::Client,
730 KeyEntryLoadBits::KM,
731 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700732 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000733 )
734 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700735 })
736 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000737
738 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
739 .take_key_blob_info()
740 .ok_or_else(error::Error::sys)
741 .context("No km_blob after successfully loading key. This should never happen.")?;
742
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800743 let wrapping_key_blob = SUPER_KEY
744 .read()
745 .unwrap()
746 .unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob)
747 .context(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000748 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
749 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700750
Janis Danisevskis1af91262020-08-10 14:58:08 -0700751 // km_dev.importWrappedKey does not return a certificate chain.
752 // TODO Do we assume that all wrapped keys are symmetric?
753 // let certificate_chain: Vec<KmCertificate> = Default::default();
754
755 let pw_sid = authenticators
756 .iter()
757 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700758 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700759 _ => None,
760 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800761 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700762
763 let fp_sid = authenticators
764 .iter()
765 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700766 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700767 _ => None,
768 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800769 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700770
771 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
772
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800773 let (creation_result, _) = self
774 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700775 &*self.keymint,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800776 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700777 &wrapping_key_blob,
778 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800779 &[],
780 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700781 let _wp = self.watch_millis(
782 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
783 500,
784 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700785 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800786 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800787 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800788 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700789 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800790 pw_sid,
791 fp_sid,
792 ))?;
793 Ok(creation_result)
794 },
795 )
796 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700797
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000798 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800799 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700800 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800801
Paul Crowley7a658392021-03-18 17:08:20 -0700802 fn store_upgraded_keyblob(
803 key_id_guard: KeyIdGuard,
804 km_uuid: Option<&Uuid>,
805 key_blob: &KeyBlob,
806 upgraded_blob: &[u8],
807 ) -> Result<()> {
808 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700809 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Paul Crowley7a658392021-03-18 17:08:20 -0700810 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
811
Paul Crowley44c02da2021-04-08 17:04:43 +0000812 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700813 if let Some(uuid) = km_uuid {
814 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
815 }
816
817 DB.with(|db| {
818 let mut db = db.borrow_mut();
819 db.set_blob(
820 &key_id_guard,
821 SubComponentType::KEY_BLOB,
822 Some(&upgraded_blob_to_be_stored),
823 Some(&new_blob_metadata),
824 )
825 })
826 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
827 }
828
Janis Danisevskisaec14592020-11-12 09:41:49 -0800829 fn upgrade_keyblob_if_required_with<T, F>(
830 &self,
831 km_dev: &dyn IKeyMintDevice,
832 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700833 key_blob: &KeyBlob,
834 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800835 params: &[KeyParameter],
836 f: F,
837 ) -> Result<(T, Option<Vec<u8>>)>
838 where
839 F: Fn(&[u8]) -> Result<T, Error>,
840 {
Paul Crowley7a658392021-03-18 17:08:20 -0700841 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800842 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700843 let upgraded_blob = {
844 let _wp = self.watch_millis(
845 concat!(
846 "In KeystoreSecurityLevel::upgrade_keyblob_if_required_with: ",
847 "calling upgradeKey."
848 ),
849 500,
850 );
851 map_km_error(km_dev.upgradeKey(key_blob, params))
852 }
853 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000854
Paul Crowley7a658392021-03-18 17:08:20 -0700855 if let Some(kid) = key_id_guard {
856 Self::store_upgraded_keyblob(
857 kid,
858 blob_metadata.km_uuid(),
859 key_blob,
860 &upgraded_blob,
861 )
862 .context(
863 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000864 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000865 }
866
Janis Danisevskisaec14592020-11-12 09:41:49 -0800867 match f(&upgraded_blob) {
868 Ok(v) => Ok((v, Some(upgraded_blob))),
869 Err(e) => Err(e).context(concat!(
870 "In upgrade_keyblob_if_required_with: ",
871 "Failed to perform operation on second try."
872 )),
873 }
874 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700875 result => {
876 if let Some(kid) = key_id_guard {
877 if key_blob.force_reencrypt() {
878 Self::store_upgraded_keyblob(
879 kid,
880 blob_metadata.km_uuid(),
881 key_blob,
882 key_blob,
883 )
884 .context(concat!(
885 "In upgrade_keyblob_if_required_with: ",
886 "store_upgraded_keyblob failed in forced reencrypt"
887 ))?;
888 }
889 }
890 result
891 .map(|v| (v, None))
892 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
893 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800894 }
895 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800896
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700897 fn convert_storage_key_to_ephemeral(
898 &self,
899 storage_key: &KeyDescriptor,
900 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800901 if storage_key.domain != Domain::BLOB {
902 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
903 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
904 "Key must be of Domain::BLOB"
905 ));
906 }
907 let key_blob = storage_key
908 .blob
909 .as_ref()
910 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
911 .context(
912 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
913 )?;
914
915 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700916 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Satya Tangirala3361b612021-03-08 14:36:11 -0800917 .context("In convert_storage_key_to_ephemeral: Check permission")?;
918
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700919 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700920 match {
921 let _wp = self.watch_millis(
922 concat!(
923 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
924 "calling convertStorageKeyToEphemeral (1)"
925 ),
926 500,
927 );
928 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
929 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700930 Ok(result) => {
931 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
932 }
933 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700934 let upgraded_blob = {
935 let _wp = self.watch_millis(
936 "In convert_storage_key_to_ephemeral: calling upgradeKey",
937 500,
938 );
939 map_km_error(km_dev.upgradeKey(key_blob, &[]))
940 }
941 .context("In convert_storage_key_to_ephemeral: Failed to upgrade key blob.")?;
942 let ephemeral_key = {
943 let _wp = self.watch_millis(
944 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
945 500,
946 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700947 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700948 }
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700949 .context(concat!(
950 "In convert_storage_key_to_ephemeral: ",
951 "Failed to retrieve ephemeral key (after upgrade)."
952 ))?;
953 Ok(EphemeralStorageKeyResponse {
954 ephemeralKey: ephemeral_key,
955 upgradedBlob: Some(upgraded_blob),
956 })
957 }
958 Err(e) => Err(e)
959 .context("In convert_storage_key_to_ephemeral: Failed to retrieve ephemeral key."),
960 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800961 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800962
963 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
964 if key.domain != Domain::BLOB {
965 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
966 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
967 }
968
969 let key_blob = key
970 .blob
971 .as_ref()
972 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
973 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
974
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700975 check_key_permission(KeyPerm::Delete, key, &None)
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800976 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
977
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700978 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700979 {
980 let _wp =
981 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700982 map_km_error(km_dev.deleteKey(key_blob)).context("In keymint device deleteKey")
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700983 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800984 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700985}
986
987impl binder::Interface for KeystoreSecurityLevel {}
988
989impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700990 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700991 &self,
992 key: &KeyDescriptor,
993 operation_parameters: &[KeyParameter],
994 forced: bool,
Stephen Crane23cf7242022-01-19 17:49:46 +0000995 ) -> binder::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000996 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700997 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700998 }
999 fn generateKey(
1000 &self,
1001 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001002 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001003 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001004 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001005 entropy: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001006 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001007 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1008 // time than other operations
1009 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001010 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001011 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001012 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001013 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001014 }
1015 fn importKey(
1016 &self,
1017 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001018 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001019 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001020 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001021 key_data: &[u8],
Stephen Crane23cf7242022-01-19 17:49:46 +00001022 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001023 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001024 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001025 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001026 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001027 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001028 }
1029 fn importWrappedKey(
1030 &self,
1031 key: &KeyDescriptor,
1032 wrapping_key: &KeyDescriptor,
1033 masking_key: Option<&[u8]>,
1034 params: &[KeyParameter],
1035 authenticators: &[AuthenticatorSpec],
Stephen Crane23cf7242022-01-19 17:49:46 +00001036 ) -> binder::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001037 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001038 let result =
1039 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001040 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001041 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001042 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001043 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001044 fn convertStorageKeyToEphemeral(
1045 &self,
1046 storage_key: &KeyDescriptor,
Stephen Crane23cf7242022-01-19 17:49:46 +00001047 ) -> binder::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001048 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001049 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1050 }
Stephen Crane23cf7242022-01-19 17:49:46 +00001051 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001052 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001053 let result = self.delete_key(key);
1054 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1055 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001056 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001057}