blob: 31bf294f275508c9eeabac62285cc547dd7bceb9 [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
163 .handle_super_encryption_on_key_init(
164 &mut db,
165 &LEGACY_MIGRATOR,
166 &(key.domain),
167 &key_parameters,
168 flags,
169 user_id,
170 &key_blob,
171 )
172 .context("In store_new_key. Failed to handle super encryption.")?;
173
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800174 let mut key_metadata = KeyMetaData::new();
175 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800177
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800178 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800179 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800180 &key,
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700181 KeyType::Client,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800182 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800183 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800184 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800185 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800186 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800187 )
188 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700189 Ok(KeyDescriptor {
190 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800191 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700192 ..Default::default()
193 })
194 })
195 .context("In store_new_key.")?,
196 };
197
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700198 Ok(KeyMetadata {
199 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700200 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800201 certificate: cert_info.take_cert(),
202 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700203 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800204 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700205 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700206 }
207
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700208 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700209 &self,
210 key: &KeyDescriptor,
211 operation_parameters: &[KeyParameter],
212 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700213 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700214 let caller_uid = ThreadState::get_calling_uid();
215 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
216 // so that we can use it by reference like the blob provided by the key descriptor.
217 // Otherwise, we would have to clone the blob from the key descriptor.
218 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800219 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700220 Domain::BLOB => {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700221 check_key_permission(KeyPerm::Use, key, &None)
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700222 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800223 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700224 check_key_permission(KeyPerm::ReqForcedOp, key, &None).context(
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800225 "In create_operation: checking forced permission for Domain::BLOB.",
226 )?;
227 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700228 (
229 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700230 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700231 None => {
232 return Err(Error::sys()).context(concat!(
233 "In create_operation: Key blob must be specified when",
234 " using Domain::BLOB."
235 ))
236 }
237 },
238 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000239 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000240 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700241 )
242 }
243 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800244 let (key_id_guard, mut key_entry) = DB
245 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700246 LEGACY_MIGRATOR.with_try_migrate(key, caller_uid, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000247 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700248 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000249 KeyType::Client,
250 KeyEntryLoadBits::KM,
251 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800252 |k, av| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700253 check_key_permission(KeyPerm::Use, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800254 if forced {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700255 check_key_permission(KeyPerm::ReqForcedOp, k, &av)?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800256 }
257 Ok(())
258 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000259 )
260 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700261 })
262 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800263
264 let (blob, blob_metadata) =
265 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
266 "In create_operation: Successfully loaded key entry, ",
267 "but KM blob was missing."
268 ))?;
269 scoping_blob = blob;
270
Qi Wub9433b52020-12-01 14:52:46 +0800271 (
272 &scoping_blob,
273 Some((key_id_guard.id(), key_entry.into_key_parameters())),
274 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000275 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800276 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700277 }
278 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700279
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700280 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700281 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700282 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800283 |kp| match kp.value {
284 KeyParameterValue::KeyPurpose(p) => Ok(p),
285 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
286 .context("In create_operation: Malformed KeyParameter."),
287 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700288 )?;
289
Satya Tangirala2642ff92021-04-15 01:57:00 -0700290 // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
291 // an error on begin() if Tag::PURPOSE is in the operation_parameters.
292 let op_params: Vec<KeyParameter> =
293 operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
294 let operation_parameters = op_params.as_slice();
295
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800296 let (immediate_hat, mut auth_info) = ENFORCEMENTS
297 .authorize_create(
298 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800299 key_properties.as_ref(),
300 operation_parameters.as_ref(),
Janis Danisevskise3f7d202021-03-20 14:21:22 -0700301 self.hw_info.timestampTokenRequired,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800302 )
303 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000304
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000305 let km_blob = SUPER_KEY
306 .unwrap_key_if_required(&blob_metadata, km_blob)
307 .context("In create_operation. Failed to handle super encryption.")?;
308
Janis Danisevskisaec14592020-11-12 09:41:49 -0800309 let (begin_result, upgraded_blob) = self
310 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700311 &*self.keymint,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800312 key_id_guard,
Paul Crowley7a658392021-03-18 17:08:20 -0700313 &km_blob,
314 &blob_metadata,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700315 operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800316 |blob| loop {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700317 match map_km_error({
318 let _wp = self.watch_millis(
319 "In KeystoreSecurityLevel::create_operation: calling begin",
320 500,
321 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700322 self.keymint.begin(
323 purpose,
324 blob,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700325 operation_parameters,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700326 immediate_hat.as_ref(),
327 )
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700328 }) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800329 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800330 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800331 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700332 }
Pavel Grafovf45034a2021-05-12 22:35:45 +0100333 v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
334 if let Some((key_id, _)) = key_properties {
335 if let Ok(Some(key)) =
336 DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
337 {
338 log_key_integrity_violation(&key);
339 } else {
340 log::error!("Failed to load key descriptor for audit log");
341 }
342 }
343 return v;
344 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800345 v => return v,
346 }
347 },
348 )
349 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700350
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800351 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000352
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000353 let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
354
Janis Danisevskis1af91262020-08-10 14:58:08 -0700355 let operation = match begin_result.operation {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700356 Some(km_op) => self.operation_db.create_operation(
357 km_op,
358 caller_uid,
359 auth_info,
360 forced,
361 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
362 ),
363 None => {
364 return Err(Error::sys()).context(concat!(
365 "In create_operation: Begin operation returned successfully, ",
366 "but did not return a valid operation."
367 ))
368 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700369 };
370
Stephen Crane221bbb52020-12-16 15:52:10 -0800371 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700372 KeystoreOperation::new_native_binder(operation)
373 .as_binder()
374 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700375 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700376
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700377 Ok(CreateOperationResponse {
378 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000379 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700380 parameters: match begin_result.params.len() {
381 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700382 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700383 },
Satya Tangiralae2016a82021-03-05 09:28:30 -0800384 // An upgraded blob should only be returned if the caller has permission
385 // to use Domain::BLOB keys. If we got to this point, we already checked
386 // that the caller had that permission.
387 upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700388 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700389 }
390
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000391 fn add_required_parameters(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700392 &self,
Janis Danisevskise766edc2021-02-06 12:16:26 -0800393 uid: u32,
394 params: &[KeyParameter],
395 key: &KeyDescriptor,
396 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800397 let mut result = params.to_vec();
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000398
399 // Unconditionally add the CREATION_DATETIME tag and prevent callers from
400 // specifying it.
401 if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
402 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(
403 "In KeystoreSecurityLevel::add_required_parameters: \
404 Specifying Tag::CREATION_DATETIME is not allowed.",
405 );
406 }
407
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800408 // Add CREATION_DATETIME only if the backend version Keymint V1 (100) or newer.
409 if self.hw_info.versionNumber >= 100 {
410 result.push(KeyParameter {
411 tag: Tag::CREATION_DATETIME,
412 value: KeyParameterValue::DateTime(
413 SystemTime::now()
414 .duration_since(SystemTime::UNIX_EPOCH)
415 .context(
416 "In KeystoreSecurityLevel::add_required_parameters: \
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000417 Failed to get epoch time.",
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800418 )?
419 .as_millis()
420 .try_into()
421 .context(
422 "In KeystoreSecurityLevel::add_required_parameters: \
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000423 Failed to convert epoch time.",
Janis Danisevskis2b3c7232021-12-20 13:16:23 -0800424 )?,
425 ),
426 });
427 }
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000428
Janis Danisevskis2c084012021-01-31 22:23:17 -0800429 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800430 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700431 let aaid = {
432 let _wp = self.watch_millis(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000433 "In KeystoreSecurityLevel::add_required_parameters calling: get_aaid",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700434 500,
435 );
436 keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000437 anyhow!(format!("In add_required_parameters: get_aaid returned status {}.", e))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700438 })
439 }?;
440
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800441 result.push(KeyParameter {
442 tag: Tag::ATTESTATION_APPLICATION_ID,
443 value: KeyParameterValue::Blob(aaid),
444 });
445 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800446
Janis Danisevskise766edc2021-02-06 12:16:26 -0800447 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700448 check_key_permission(KeyPerm::GenUniqueId, key, &None).context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000449 "In add_required_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700450 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800451 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700452 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000453 "In add_required_parameters: Call to had_factory_reset_since_id_rotation failed.",
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700454 )? {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000455 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700456 tag: Tag::RESET_SINCE_ID_ROTATION,
457 value: KeyParameterValue::BoolValue(true),
458 })
459 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800460 }
461
Bram Bonné5d6c5102021-02-24 15:09:18 +0100462 // If the caller requests any device identifier attestation tag, check that they hold the
463 // correct Android permission.
464 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
465 check_device_attestation_permissions().context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000466 "In add_required_parameters: ",
Bram Bonné5d6c5102021-02-24 15:09:18 +0100467 "Caller does not have the permission to attest device identifiers."
468 ))?;
469 }
470
Janis Danisevskis2c084012021-01-31 22:23:17 -0800471 // If we are generating/importing an asymmetric key, we need to make sure
472 // that NOT_BEFORE and NOT_AFTER are present.
473 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
474 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
475 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
476 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
477 result.push(KeyParameter {
478 tag: Tag::CERTIFICATE_NOT_BEFORE,
479 value: KeyParameterValue::DateTime(0),
480 })
481 }
482 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
483 result.push(KeyParameter {
484 tag: Tag::CERTIFICATE_NOT_AFTER,
485 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
486 })
487 }
488 }
489 _ => {}
490 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800491 Ok(result)
492 }
493
Janis Danisevskis1af91262020-08-10 14:58:08 -0700494 fn generate_key(
495 &self,
496 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700497 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700498 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700499 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700500 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700501 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700502 if key.domain != Domain::BLOB && key.alias.is_none() {
503 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
504 .context("In generate_key: Alias must be specified");
505 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000506 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700507
508 let key = match key.domain {
509 Domain::APP => KeyDescriptor {
510 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000511 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700512 alias: key.alias.clone(),
513 blob: None,
514 },
515 _ => key.clone(),
516 };
517
518 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700519 // Must return on error for security reasons.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700520 check_key_permission(KeyPerm::Rebind, &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700521
522 let attestation_key_info = match (key.domain, attest_key_descriptor) {
523 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800524 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700525 .with(|db| {
526 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800527 &key,
528 caller_uid,
529 attest_key_descriptor,
530 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700531 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800532 &mut db.borrow_mut(),
533 )
534 })
535 .context("In generate_key: Trying to get an attestation key")?,
536 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700537 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000538 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800539 .context("In generate_key: Trying to get aaid.")?;
540
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700541 let creation_result = match attestation_key_info {
542 Some(AttestationKeyInfo::UserGenerated {
543 key_id_guard,
544 blob,
545 blob_metadata,
546 issuer_subject,
547 }) => self
548 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700549 &*self.keymint,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700550 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700551 &KeyBlob::Ref(&blob),
552 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700553 &params,
554 |blob| {
555 let attest_key = Some(AttestationKey {
556 keyBlob: blob.to_vec(),
557 attestKeyParams: vec![],
558 issuerSubjectName: issuer_subject.clone(),
559 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700560 map_km_error({
561 let _wp = self.watch_millis(
562 concat!(
563 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
564 "calling generate_key."
565 ),
566 5000, // Generate can take a little longer.
567 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700568 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700569 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700570 },
571 )
572 .context("In generate_key: Using user generated attestation key.")
573 .map(|(result, _)| result),
574 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700575 map_km_error({
576 let _wp = self.watch_millis(
577 concat!(
578 "In KeystoreSecurityLevel::generate_key (RemoteProvisioned): ",
579 "calling generate_key.",
580 ),
581 5000, // Generate can take a little longer.
582 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700583 self.keymint.generateKey(&params, Some(&attestation_key))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700584 })
585 .context("While generating Key with remote provisioned attestation key.")
586 .map(|mut creation_result| {
587 creation_result.certificateChain.push(attestation_certs);
588 creation_result
589 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700590 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700591 None => map_km_error({
592 let _wp = self.watch_millis(
593 concat!(
594 "In KeystoreSecurityLevel::generate_key (No attestation): ",
595 "calling generate_key.",
596 ),
597 5000, // Generate can take a little longer.
598 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700599 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700600 })
601 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800602 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700603 .context("In generate_key.")?;
604
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000605 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000606 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700607 }
608
609 fn import_key(
610 &self,
611 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700612 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700613 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700614 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700615 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700616 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700617 if key.domain != Domain::BLOB && key.alias.is_none() {
618 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
619 .context("In import_key: Alias must be specified");
620 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000621 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700622
623 let key = match key.domain {
624 Domain::APP => KeyDescriptor {
625 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000626 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700627 alias: key.alias.clone(),
628 blob: None,
629 },
630 _ => key.clone(),
631 };
632
633 // import_key requires the rebind permission.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700634 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700635
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700636 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000637 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800638 .context("In import_key: Trying to get aaid.")?;
639
Janis Danisevskis1af91262020-08-10 14:58:08 -0700640 let format = params
641 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700642 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700643 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
644 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800645 .and_then(|p| match &p.value {
646 KeyParameterValue::Algorithm(Algorithm::AES)
647 | KeyParameterValue::Algorithm(Algorithm::HMAC)
648 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
649 KeyParameterValue::Algorithm(Algorithm::RSA)
650 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
651 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
652 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700653 })
654 .context("In import_key.")?;
655
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700656 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700657 let creation_result = map_km_error({
658 let _wp =
659 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
660 km_dev.importKey(&params, format, key_data, None /* attestKey */)
661 })
662 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700663
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000664 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000665 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700666 }
667
668 fn import_wrapped_key(
669 &self,
670 key: &KeyDescriptor,
671 wrapping_key: &KeyDescriptor,
672 masking_key: Option<&[u8]>,
673 params: &[KeyParameter],
674 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700675 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800676 let wrapped_data: &[u8] = match key {
677 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
678 | KeyDescriptor {
679 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
680 } => blob,
681 _ => {
682 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
683 concat!(
684 "In import_wrapped_key: Alias and blob must be specified ",
685 "and domain must be APP or SELINUX. {:?}"
686 ),
687 key
688 ))
689 }
690 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700691
Janis Danisevskisaec14592020-11-12 09:41:49 -0800692 if wrapping_key.domain == Domain::BLOB {
693 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
694 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
695 );
696 }
697
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000698 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000699 let user_id = uid_to_android_user(caller_uid);
700
Janis Danisevskis1af91262020-08-10 14:58:08 -0700701 let key = match key.domain {
702 Domain::APP => KeyDescriptor {
703 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000704 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700705 alias: key.alias.clone(),
706 blob: None,
707 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800708 Domain::SELINUX => KeyDescriptor {
709 domain: Domain::SELINUX,
710 nspace: key.nspace,
711 alias: key.alias.clone(),
712 blob: None,
713 },
714 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700715 };
716
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800717 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700718 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700719
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000720 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700721 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000722 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
723 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700724 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000725 KeyType::Client,
726 KeyEntryLoadBits::KM,
727 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700728 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000729 )
730 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700731 })
732 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000733
734 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
735 .take_key_blob_info()
736 .ok_or_else(error::Error::sys)
737 .context("No km_blob after successfully loading key. This should never happen.")?;
738
739 let wrapping_key_blob =
740 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
741 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
742 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700743
Janis Danisevskis1af91262020-08-10 14:58:08 -0700744 // km_dev.importWrappedKey does not return a certificate chain.
745 // TODO Do we assume that all wrapped keys are symmetric?
746 // let certificate_chain: Vec<KmCertificate> = Default::default();
747
748 let pw_sid = authenticators
749 .iter()
750 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700751 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700752 _ => None,
753 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800754 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700755
756 let fp_sid = authenticators
757 .iter()
758 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700759 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700760 _ => None,
761 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800762 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700763
764 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
765
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800766 let (creation_result, _) = self
767 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700768 &*self.keymint,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800769 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700770 &wrapping_key_blob,
771 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800772 &[],
773 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700774 let _wp = self.watch_millis(
775 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
776 500,
777 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700778 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800779 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800780 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800781 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700782 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800783 pw_sid,
784 fp_sid,
785 ))?;
786 Ok(creation_result)
787 },
788 )
789 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700790
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000791 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800792 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700793 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800794
Paul Crowley7a658392021-03-18 17:08:20 -0700795 fn store_upgraded_keyblob(
796 key_id_guard: KeyIdGuard,
797 km_uuid: Option<&Uuid>,
798 key_blob: &KeyBlob,
799 upgraded_blob: &[u8],
800 ) -> Result<()> {
801 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700802 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Paul Crowley7a658392021-03-18 17:08:20 -0700803 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
804
Paul Crowley44c02da2021-04-08 17:04:43 +0000805 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700806 if let Some(uuid) = km_uuid {
807 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
808 }
809
810 DB.with(|db| {
811 let mut db = db.borrow_mut();
812 db.set_blob(
813 &key_id_guard,
814 SubComponentType::KEY_BLOB,
815 Some(&upgraded_blob_to_be_stored),
816 Some(&new_blob_metadata),
817 )
818 })
819 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
820 }
821
Janis Danisevskisaec14592020-11-12 09:41:49 -0800822 fn upgrade_keyblob_if_required_with<T, F>(
823 &self,
824 km_dev: &dyn IKeyMintDevice,
825 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700826 key_blob: &KeyBlob,
827 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800828 params: &[KeyParameter],
829 f: F,
830 ) -> Result<(T, Option<Vec<u8>>)>
831 where
832 F: Fn(&[u8]) -> Result<T, Error>,
833 {
Paul Crowley7a658392021-03-18 17:08:20 -0700834 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800835 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700836 let upgraded_blob = {
837 let _wp = self.watch_millis(
838 concat!(
839 "In KeystoreSecurityLevel::upgrade_keyblob_if_required_with: ",
840 "calling upgradeKey."
841 ),
842 500,
843 );
844 map_km_error(km_dev.upgradeKey(key_blob, params))
845 }
846 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000847
Paul Crowley7a658392021-03-18 17:08:20 -0700848 if let Some(kid) = key_id_guard {
849 Self::store_upgraded_keyblob(
850 kid,
851 blob_metadata.km_uuid(),
852 key_blob,
853 &upgraded_blob,
854 )
855 .context(
856 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000857 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000858 }
859
Janis Danisevskisaec14592020-11-12 09:41:49 -0800860 match f(&upgraded_blob) {
861 Ok(v) => Ok((v, Some(upgraded_blob))),
862 Err(e) => Err(e).context(concat!(
863 "In upgrade_keyblob_if_required_with: ",
864 "Failed to perform operation on second try."
865 )),
866 }
867 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700868 result => {
869 if let Some(kid) = key_id_guard {
870 if key_blob.force_reencrypt() {
871 Self::store_upgraded_keyblob(
872 kid,
873 blob_metadata.km_uuid(),
874 key_blob,
875 key_blob,
876 )
877 .context(concat!(
878 "In upgrade_keyblob_if_required_with: ",
879 "store_upgraded_keyblob failed in forced reencrypt"
880 ))?;
881 }
882 }
883 result
884 .map(|v| (v, None))
885 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
886 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800887 }
888 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800889
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700890 fn convert_storage_key_to_ephemeral(
891 &self,
892 storage_key: &KeyDescriptor,
893 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800894 if storage_key.domain != Domain::BLOB {
895 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
896 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
897 "Key must be of Domain::BLOB"
898 ));
899 }
900 let key_blob = storage_key
901 .blob
902 .as_ref()
903 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
904 .context(
905 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
906 )?;
907
908 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700909 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Satya Tangirala3361b612021-03-08 14:36:11 -0800910 .context("In convert_storage_key_to_ephemeral: Check permission")?;
911
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700912 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700913 match {
914 let _wp = self.watch_millis(
915 concat!(
916 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
917 "calling convertStorageKeyToEphemeral (1)"
918 ),
919 500,
920 );
921 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
922 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700923 Ok(result) => {
924 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
925 }
926 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700927 let upgraded_blob = {
928 let _wp = self.watch_millis(
929 "In convert_storage_key_to_ephemeral: calling upgradeKey",
930 500,
931 );
932 map_km_error(km_dev.upgradeKey(key_blob, &[]))
933 }
934 .context("In convert_storage_key_to_ephemeral: Failed to upgrade key blob.")?;
935 let ephemeral_key = {
936 let _wp = self.watch_millis(
937 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
938 500,
939 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700940 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700941 }
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700942 .context(concat!(
943 "In convert_storage_key_to_ephemeral: ",
944 "Failed to retrieve ephemeral key (after upgrade)."
945 ))?;
946 Ok(EphemeralStorageKeyResponse {
947 ephemeralKey: ephemeral_key,
948 upgradedBlob: Some(upgraded_blob),
949 })
950 }
951 Err(e) => Err(e)
952 .context("In convert_storage_key_to_ephemeral: Failed to retrieve ephemeral key."),
953 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800954 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800955
956 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
957 if key.domain != Domain::BLOB {
958 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
959 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
960 }
961
962 let key_blob = key
963 .blob
964 .as_ref()
965 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
966 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
967
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700968 check_key_permission(KeyPerm::Delete, key, &None)
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800969 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
970
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700971 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700972 {
973 let _wp =
974 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700975 map_km_error(km_dev.deleteKey(key_blob)).context("In keymint device deleteKey")
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700976 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800977 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700978}
979
980impl binder::Interface for KeystoreSecurityLevel {}
981
982impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700983 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700984 &self,
985 key: &KeyDescriptor,
986 operation_parameters: &[KeyParameter],
987 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700988 ) -> binder::public_api::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000989 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700990 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700991 }
992 fn generateKey(
993 &self,
994 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700995 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700996 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700997 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700998 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700999 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001000 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1001 // time than other operations
1002 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001003 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001004 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001005 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001006 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001007 }
1008 fn importKey(
1009 &self,
1010 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001011 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001012 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001013 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001014 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001015 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001016 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001017 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001018 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001019 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001020 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001021 }
1022 fn importWrappedKey(
1023 &self,
1024 key: &KeyDescriptor,
1025 wrapping_key: &KeyDescriptor,
1026 masking_key: Option<&[u8]>,
1027 params: &[KeyParameter],
1028 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001029 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001030 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001031 let result =
1032 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001033 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001034 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001035 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001036 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001037 fn convertStorageKeyToEphemeral(
1038 &self,
1039 storage_key: &KeyDescriptor,
Janis Danisevskisb2434d02021-04-20 12:49:27 -07001040 ) -> binder::public_api::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001041 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001042 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1043 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001044 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001045 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001046 let result = self.delete_key(key);
1047 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1048 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001049 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001050}