blob: da1ff16e7a86e188e4292df7f5cfc64d5d839e0b [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
408 result.push(KeyParameter {
409 tag: Tag::CREATION_DATETIME,
410 value: KeyParameterValue::DateTime(
411 SystemTime::now()
412 .duration_since(SystemTime::UNIX_EPOCH)
413 .context(
414 "In KeystoreSecurityLevel::add_required_parameters: \
415 Failed to get epoch time.",
416 )?
417 .as_millis()
418 .try_into()
419 .context(
420 "In KeystoreSecurityLevel::add_required_parameters: \
421 Failed to convert epoch time.",
422 )?,
423 ),
424 });
425
Janis Danisevskis2c084012021-01-31 22:23:17 -0800426 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800427 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700428 let aaid = {
429 let _wp = self.watch_millis(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000430 "In KeystoreSecurityLevel::add_required_parameters calling: get_aaid",
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700431 500,
432 );
433 keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000434 anyhow!(format!("In add_required_parameters: get_aaid returned status {}.", e))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700435 })
436 }?;
437
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800438 result.push(KeyParameter {
439 tag: Tag::ATTESTATION_APPLICATION_ID,
440 value: KeyParameterValue::Blob(aaid),
441 });
442 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800443
Janis Danisevskise766edc2021-02-06 12:16:26 -0800444 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700445 check_key_permission(KeyPerm::GenUniqueId, key, &None).context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000446 "In add_required_parameters: ",
Janis Danisevskis83116e52021-04-06 13:36:58 -0700447 "Caller does not have the permission to generate a unique ID"
Janis Danisevskise766edc2021-02-06 12:16:26 -0800448 ))?;
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700449 if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000450 "In add_required_parameters: Call to had_factory_reset_since_id_rotation failed.",
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700451 )? {
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000452 result.push(KeyParameter {
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700453 tag: Tag::RESET_SINCE_ID_ROTATION,
454 value: KeyParameterValue::BoolValue(true),
455 })
456 }
Janis Danisevskise766edc2021-02-06 12:16:26 -0800457 }
458
Bram Bonné5d6c5102021-02-24 15:09:18 +0100459 // If the caller requests any device identifier attestation tag, check that they hold the
460 // correct Android permission.
461 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
462 check_device_attestation_permissions().context(concat!(
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000463 "In add_required_parameters: ",
Bram Bonné5d6c5102021-02-24 15:09:18 +0100464 "Caller does not have the permission to attest device identifiers."
465 ))?;
466 }
467
Janis Danisevskis2c084012021-01-31 22:23:17 -0800468 // If we are generating/importing an asymmetric key, we need to make sure
469 // that NOT_BEFORE and NOT_AFTER are present.
470 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
471 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
472 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
473 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
474 result.push(KeyParameter {
475 tag: Tag::CERTIFICATE_NOT_BEFORE,
476 value: KeyParameterValue::DateTime(0),
477 })
478 }
479 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
480 result.push(KeyParameter {
481 tag: Tag::CERTIFICATE_NOT_AFTER,
482 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
483 })
484 }
485 }
486 _ => {}
487 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800488 Ok(result)
489 }
490
Janis Danisevskis1af91262020-08-10 14:58:08 -0700491 fn generate_key(
492 &self,
493 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700494 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700495 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700496 flags: i32,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700497 _entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700498 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700499 if key.domain != Domain::BLOB && key.alias.is_none() {
500 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
501 .context("In generate_key: Alias must be specified");
502 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000503 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700504
505 let key = match key.domain {
506 Domain::APP => KeyDescriptor {
507 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000508 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700509 alias: key.alias.clone(),
510 blob: None,
511 },
512 _ => key.clone(),
513 };
514
515 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700516 // Must return on error for security reasons.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700517 check_key_permission(KeyPerm::Rebind, &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700518
519 let attestation_key_info = match (key.domain, attest_key_descriptor) {
520 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800521 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700522 .with(|db| {
523 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800524 &key,
525 caller_uid,
526 attest_key_descriptor,
527 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700528 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800529 &mut db.borrow_mut(),
530 )
531 })
532 .context("In generate_key: Trying to get an attestation key")?,
533 };
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700534 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000535 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800536 .context("In generate_key: Trying to get aaid.")?;
537
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700538 let creation_result = match attestation_key_info {
539 Some(AttestationKeyInfo::UserGenerated {
540 key_id_guard,
541 blob,
542 blob_metadata,
543 issuer_subject,
544 }) => self
545 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700546 &*self.keymint,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700547 Some(key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700548 &KeyBlob::Ref(&blob),
549 &blob_metadata,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700550 &params,
551 |blob| {
552 let attest_key = Some(AttestationKey {
553 keyBlob: blob.to_vec(),
554 attestKeyParams: vec![],
555 issuerSubjectName: issuer_subject.clone(),
556 });
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700557 map_km_error({
558 let _wp = self.watch_millis(
559 concat!(
560 "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
561 "calling generate_key."
562 ),
563 5000, // Generate can take a little longer.
564 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700565 self.keymint.generateKey(&params, attest_key.as_ref())
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700566 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700567 },
568 )
569 .context("In generate_key: Using user generated attestation key.")
570 .map(|(result, _)| result),
571 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700572 map_km_error({
573 let _wp = self.watch_millis(
574 concat!(
575 "In KeystoreSecurityLevel::generate_key (RemoteProvisioned): ",
576 "calling generate_key.",
577 ),
578 5000, // Generate can take a little longer.
579 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700580 self.keymint.generateKey(&params, Some(&attestation_key))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700581 })
582 .context("While generating Key with remote provisioned attestation key.")
583 .map(|mut creation_result| {
584 creation_result.certificateChain.push(attestation_certs);
585 creation_result
586 })
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700587 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700588 None => map_km_error({
589 let _wp = self.watch_millis(
590 concat!(
591 "In KeystoreSecurityLevel::generate_key (No attestation): ",
592 "calling generate_key.",
593 ),
594 5000, // Generate can take a little longer.
595 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700596 self.keymint.generateKey(&params, None)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700597 })
598 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800599 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700600 .context("In generate_key.")?;
601
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000602 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000603 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700604 }
605
606 fn import_key(
607 &self,
608 key: &KeyDescriptor,
Paul Crowleyd5653e52021-03-25 09:46:31 -0700609 _attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700610 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700611 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700612 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700613 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700614 if key.domain != Domain::BLOB && key.alias.is_none() {
615 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
616 .context("In import_key: Alias must be specified");
617 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000618 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700619
620 let key = match key.domain {
621 Domain::APP => KeyDescriptor {
622 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000623 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700624 alias: key.alias.clone(),
625 blob: None,
626 },
627 _ => key.clone(),
628 };
629
630 // import_key requires the rebind permission.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700631 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700632
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -0700633 let params = self
Janis Danisevskisd43c1b92021-11-09 14:56:17 +0000634 .add_required_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800635 .context("In import_key: Trying to get aaid.")?;
636
Janis Danisevskis1af91262020-08-10 14:58:08 -0700637 let format = params
638 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700639 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700640 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
641 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800642 .and_then(|p| match &p.value {
643 KeyParameterValue::Algorithm(Algorithm::AES)
644 | KeyParameterValue::Algorithm(Algorithm::HMAC)
645 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
646 KeyParameterValue::Algorithm(Algorithm::RSA)
647 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
648 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
649 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700650 })
651 .context("In import_key.")?;
652
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700653 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700654 let creation_result = map_km_error({
655 let _wp =
656 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
657 km_dev.importKey(&params, format, key_data, None /* attestKey */)
658 })
659 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700660
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000661 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000662 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700663 }
664
665 fn import_wrapped_key(
666 &self,
667 key: &KeyDescriptor,
668 wrapping_key: &KeyDescriptor,
669 masking_key: Option<&[u8]>,
670 params: &[KeyParameter],
671 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700672 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800673 let wrapped_data: &[u8] = match key {
674 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
675 | KeyDescriptor {
676 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
677 } => blob,
678 _ => {
679 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
680 concat!(
681 "In import_wrapped_key: Alias and blob must be specified ",
682 "and domain must be APP or SELINUX. {:?}"
683 ),
684 key
685 ))
686 }
687 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700688
Janis Danisevskisaec14592020-11-12 09:41:49 -0800689 if wrapping_key.domain == Domain::BLOB {
690 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
691 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
692 );
693 }
694
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000695 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000696 let user_id = uid_to_android_user(caller_uid);
697
Janis Danisevskis1af91262020-08-10 14:58:08 -0700698 let key = match key.domain {
699 Domain::APP => KeyDescriptor {
700 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000701 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700702 alias: key.alias.clone(),
703 blob: None,
704 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800705 Domain::SELINUX => KeyDescriptor {
706 domain: Domain::SELINUX,
707 nspace: key.nspace,
708 alias: key.alias.clone(),
709 blob: None,
710 },
711 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700712 };
713
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800714 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700715 check_key_permission(KeyPerm::Rebind, &key, &None).context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700716
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000717 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700718 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000719 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
720 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700721 wrapping_key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000722 KeyType::Client,
723 KeyEntryLoadBits::KM,
724 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700725 |k, av| check_key_permission(KeyPerm::Use, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000726 )
727 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700728 })
729 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000730
731 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
732 .take_key_blob_info()
733 .ok_or_else(error::Error::sys)
734 .context("No km_blob after successfully loading key. This should never happen.")?;
735
736 let wrapping_key_blob =
737 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
738 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
739 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700740
Janis Danisevskis1af91262020-08-10 14:58:08 -0700741 // km_dev.importWrappedKey does not return a certificate chain.
742 // TODO Do we assume that all wrapped keys are symmetric?
743 // let certificate_chain: Vec<KmCertificate> = Default::default();
744
745 let pw_sid = authenticators
746 .iter()
747 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700748 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700749 _ => None,
750 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800751 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700752
753 let fp_sid = authenticators
754 .iter()
755 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700756 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700757 _ => None,
758 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800759 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700760
761 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
762
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800763 let (creation_result, _) = self
764 .upgrade_keyblob_if_required_with(
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700765 &*self.keymint,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800766 Some(wrapping_key_id_guard),
Paul Crowley7a658392021-03-18 17:08:20 -0700767 &wrapping_key_blob,
768 &wrapping_blob_metadata,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800769 &[],
770 |wrapping_blob| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700771 let _wp = self.watch_millis(
772 "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
773 500,
774 );
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700775 let creation_result = map_km_error(self.keymint.importWrappedKey(
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800776 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800777 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800778 masking_key,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700779 params,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800780 pw_sid,
781 fp_sid,
782 ))?;
783 Ok(creation_result)
784 },
785 )
786 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700787
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000788 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800789 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700790 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800791
Paul Crowley7a658392021-03-18 17:08:20 -0700792 fn store_upgraded_keyblob(
793 key_id_guard: KeyIdGuard,
794 km_uuid: Option<&Uuid>,
795 key_blob: &KeyBlob,
796 upgraded_blob: &[u8],
797 ) -> Result<()> {
798 let (upgraded_blob_to_be_stored, new_blob_metadata) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700799 SuperKeyManager::reencrypt_if_required(key_blob, upgraded_blob)
Paul Crowley7a658392021-03-18 17:08:20 -0700800 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
801
Paul Crowley44c02da2021-04-08 17:04:43 +0000802 let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
Paul Crowley7a658392021-03-18 17:08:20 -0700803 if let Some(uuid) = km_uuid {
804 new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
805 }
806
807 DB.with(|db| {
808 let mut db = db.borrow_mut();
809 db.set_blob(
810 &key_id_guard,
811 SubComponentType::KEY_BLOB,
812 Some(&upgraded_blob_to_be_stored),
813 Some(&new_blob_metadata),
814 )
815 })
816 .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
817 }
818
Janis Danisevskisaec14592020-11-12 09:41:49 -0800819 fn upgrade_keyblob_if_required_with<T, F>(
820 &self,
821 km_dev: &dyn IKeyMintDevice,
822 key_id_guard: Option<KeyIdGuard>,
Paul Crowley7a658392021-03-18 17:08:20 -0700823 key_blob: &KeyBlob,
824 blob_metadata: &BlobMetaData,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800825 params: &[KeyParameter],
826 f: F,
827 ) -> Result<(T, Option<Vec<u8>>)>
828 where
829 F: Fn(&[u8]) -> Result<T, Error>,
830 {
Paul Crowley7a658392021-03-18 17:08:20 -0700831 match f(key_blob) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800832 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700833 let upgraded_blob = {
834 let _wp = self.watch_millis(
835 concat!(
836 "In KeystoreSecurityLevel::upgrade_keyblob_if_required_with: ",
837 "calling upgradeKey."
838 ),
839 500,
840 );
841 map_km_error(km_dev.upgradeKey(key_blob, params))
842 }
843 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000844
Paul Crowley7a658392021-03-18 17:08:20 -0700845 if let Some(kid) = key_id_guard {
846 Self::store_upgraded_keyblob(
847 kid,
848 blob_metadata.km_uuid(),
849 key_blob,
850 &upgraded_blob,
851 )
852 .context(
853 "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000854 )?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000855 }
856
Janis Danisevskisaec14592020-11-12 09:41:49 -0800857 match f(&upgraded_blob) {
858 Ok(v) => Ok((v, Some(upgraded_blob))),
859 Err(e) => Err(e).context(concat!(
860 "In upgrade_keyblob_if_required_with: ",
861 "Failed to perform operation on second try."
862 )),
863 }
864 }
Paul Crowley8d5b2532021-03-19 10:53:07 -0700865 result => {
866 if let Some(kid) = key_id_guard {
867 if key_blob.force_reencrypt() {
868 Self::store_upgraded_keyblob(
869 kid,
870 blob_metadata.km_uuid(),
871 key_blob,
872 key_blob,
873 )
874 .context(concat!(
875 "In upgrade_keyblob_if_required_with: ",
876 "store_upgraded_keyblob failed in forced reencrypt"
877 ))?;
878 }
879 }
880 result
881 .map(|v| (v, None))
882 .context("In upgrade_keyblob_if_required_with: Called closure failed.")
883 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800884 }
885 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800886
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700887 fn convert_storage_key_to_ephemeral(
888 &self,
889 storage_key: &KeyDescriptor,
890 ) -> Result<EphemeralStorageKeyResponse> {
Satya Tangirala3361b612021-03-08 14:36:11 -0800891 if storage_key.domain != Domain::BLOB {
892 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
893 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
894 "Key must be of Domain::BLOB"
895 ));
896 }
897 let key_blob = storage_key
898 .blob
899 .as_ref()
900 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
901 .context(
902 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
903 )?;
904
905 // convert_storage_key_to_ephemeral requires the associated permission
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700906 check_key_permission(KeyPerm::ConvertStorageKeyToEphemeral, storage_key, &None)
Satya Tangirala3361b612021-03-08 14:36:11 -0800907 .context("In convert_storage_key_to_ephemeral: Check permission")?;
908
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700909 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700910 match {
911 let _wp = self.watch_millis(
912 concat!(
913 "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
914 "calling convertStorageKeyToEphemeral (1)"
915 ),
916 500,
917 );
918 map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
919 } {
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700920 Ok(result) => {
921 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
922 }
923 Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700924 let upgraded_blob = {
925 let _wp = self.watch_millis(
926 "In convert_storage_key_to_ephemeral: calling upgradeKey",
927 500,
928 );
929 map_km_error(km_dev.upgradeKey(key_blob, &[]))
930 }
931 .context("In convert_storage_key_to_ephemeral: Failed to upgrade key blob.")?;
932 let ephemeral_key = {
933 let _wp = self.watch_millis(
934 "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
935 500,
936 );
Janis Danisevskis84af4d12021-07-22 17:39:15 -0700937 map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700938 }
Janis Danisevskisb2434d02021-04-20 12:49:27 -0700939 .context(concat!(
940 "In convert_storage_key_to_ephemeral: ",
941 "Failed to retrieve ephemeral key (after upgrade)."
942 ))?;
943 Ok(EphemeralStorageKeyResponse {
944 ephemeralKey: ephemeral_key,
945 upgradedBlob: Some(upgraded_blob),
946 })
947 }
948 Err(e) => Err(e)
949 .context("In convert_storage_key_to_ephemeral: Failed to retrieve ephemeral key."),
950 }
Satya Tangirala3361b612021-03-08 14:36:11 -0800951 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800952
953 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
954 if key.domain != Domain::BLOB {
955 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
956 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
957 }
958
959 let key_blob = key
960 .blob
961 .as_ref()
962 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
963 .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
964
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700965 check_key_permission(KeyPerm::Delete, key, &None)
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800966 .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
967
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700968 let km_dev = &self.keymint;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700969 {
970 let _wp =
971 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700972 map_km_error(km_dev.deleteKey(key_blob)).context("In keymint device deleteKey")
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700973 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -0800974 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700975}
976
977impl binder::Interface for KeystoreSecurityLevel {}
978
979impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700980 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700981 &self,
982 key: &KeyDescriptor,
983 operation_parameters: &[KeyParameter],
984 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700985 ) -> binder::public_api::Result<CreateOperationResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000986 let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700987 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700988 }
989 fn generateKey(
990 &self,
991 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700992 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700993 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700994 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700995 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700996 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000997 // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
998 // time than other operations
999 let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001000 let result = self.generate_key(key, attestation_key, params, flags, entropy);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001001 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001002 log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001003 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001004 }
1005 fn importKey(
1006 &self,
1007 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001008 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001009 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001010 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -07001011 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001012 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001013 let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001014 let result = self.import_key(key, attestation_key, params, flags, key_data);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001015 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001016 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001017 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001018 }
1019 fn importWrappedKey(
1020 &self,
1021 key: &KeyDescriptor,
1022 wrapping_key: &KeyDescriptor,
1023 masking_key: Option<&[u8]>,
1024 params: &[KeyParameter],
1025 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -07001026 ) -> binder::public_api::Result<KeyMetadata> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001027 let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001028 let result =
1029 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +00001030 log_key_creation_event_stats(self.security_level, params, &result);
Pavel Grafov94243c22021-04-21 18:03:11 +01001031 log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
Hasini Gunasingheb7142972021-02-20 03:11:27 +00001032 map_or_log_err(result, Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -07001033 }
Satya Tangirala3361b612021-03-08 14:36:11 -08001034 fn convertStorageKeyToEphemeral(
1035 &self,
1036 storage_key: &KeyDescriptor,
Janis Danisevskisb2434d02021-04-20 12:49:27 -07001037 ) -> binder::public_api::Result<EphemeralStorageKeyResponse> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001038 let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
Satya Tangirala3361b612021-03-08 14:36:11 -08001039 map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1040 }
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001041 fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +00001042 let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
Pavel Grafov94243c22021-04-21 18:03:11 +01001043 let result = self.delete_key(key);
1044 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1045 map_or_log_err(result, Ok)
Satya Tangirala04bca0d2021-03-08 22:27:54 -08001046 }
Janis Danisevskis1af91262020-08-10 14:58:08 -07001047}