blob: b187d3bcf6faf27286b252ab67f07c92ad17c72a [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
15#![allow(unused_variables)]
16
17//! This crate implements the IKeystoreSecurityLevel interface.
18
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080019use crate::globals::get_keymint_device;
Shawn Willden708744a2020-12-11 13:05:27 +000020use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Shawn Willden8fde4c22021-02-14 13:58:22 -070021 Algorithm::Algorithm, AttestationKey::AttestationKey,
22 HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
23 KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080024 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
25 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070026};
27use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070028 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
29 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
30 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070031 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080032 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070033};
34
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000035use crate::database::{CertificateInfo, KeyIdGuard};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000036use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000037use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000038use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000039use crate::super_key::{KeyBlob, SuperKeyManager};
Qi Wub9433b52020-12-01 14:52:46 +080040use crate::utils::{check_key_permission, uid_to_android_user, Asp};
Max Bires8e93d2b2021-01-14 13:17:59 -080041use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080042 database::{
43 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
44 KeyMetaEntry, KeyType, SubComponentType, Uuid,
45 },
46 operation::KeystoreOperation,
47 operation::OperationDb,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080048 permission::KeyPerm,
49};
50use crate::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070051 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
52 utils::key_characteristics_to_internal,
53};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080054use anyhow::{anyhow, Context, Result};
Stephen Crane221bbb52020-12-16 15:52:10 -080055use binder::{IBinder, Strong, ThreadState};
Shawn Willden34120872021-02-24 21:56:30 -070056use keystore2_crypto::parse_subject_from_certificate;
Janis Danisevskis1af91262020-08-10 14:58:08 -070057
58/// Implementation of the IKeystoreSecurityLevel Interface.
59pub struct KeystoreSecurityLevel {
60 security_level: SecurityLevel,
61 keymint: Asp,
Max Bires8e93d2b2021-01-14 13:17:59 -080062 #[allow(dead_code)]
63 hw_info: KeyMintHardwareInfo,
64 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070065 operation_db: OperationDb,
66}
67
Janis Danisevskis1af91262020-08-10 14:58:08 -070068// Blob of 32 zeroes used as empty masking key.
69static ZERO_BLOB_32: &[u8] = &[0; 32];
70
Janis Danisevskis2c084012021-01-31 22:23:17 -080071// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
72// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
73const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
74
Janis Danisevskis1af91262020-08-10 14:58:08 -070075impl KeystoreSecurityLevel {
76 /// Creates a new security level instance wrapped in a
77 /// BnKeystoreSecurityLevel proxy object. It also
78 /// calls `IBinder::set_requesting_sid` on the new interface, because
79 /// we need it for checking keystore permissions.
80 pub fn new_native_binder(
81 security_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -080082 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080083 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
84 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070085 let result = BnKeystoreSecurityLevel::new_binder(Self {
86 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080087 keymint: dev,
88 hw_info,
89 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070090 operation_db: OperationDb::new(),
91 });
92 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -080093 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -070094 }
95
96 fn store_new_key(
97 &self,
98 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -070099 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000100 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000101 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700102 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700103 let KeyCreationResult {
104 keyBlob: key_blob,
105 keyCharacteristics: key_characteristics,
106 certificateChain: mut certificate_chain,
107 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700108
Max Bires8e93d2b2021-01-14 13:17:59 -0800109 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700110 match certificate_chain.len() {
111 0 => None,
112 _ => Some(certificate_chain.remove(0).encodedCertificate),
113 },
114 match certificate_chain.len() {
115 0 => None,
116 _ => Some(
117 certificate_chain
118 .iter()
119 .map(|c| c.encodedCertificate.iter())
120 .flatten()
121 .copied()
122 .collect(),
123 ),
124 },
125 );
126
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000127 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
128
129 key_parameters.push(KsKeyParam::new(
130 KsKeyParamValue::UserID(user_id as i32),
131 SecurityLevel::SOFTWARE,
132 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700133
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800134 let creation_date = DateTime::now().context("Trying to make creation time.")?;
135
Janis Danisevskis1af91262020-08-10 14:58:08 -0700136 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800137 Domain::BLOB => KeyDescriptor {
138 domain: Domain::BLOB,
139 blob: Some(key_blob.to_vec()),
140 ..Default::default()
141 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700142 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800143 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800144 let mut db = db.borrow_mut();
145
146 let (key_blob, mut blob_metadata) = SUPER_KEY
147 .handle_super_encryption_on_key_init(
148 &mut db,
149 &LEGACY_MIGRATOR,
150 &(key.domain),
151 &key_parameters,
152 flags,
153 user_id,
154 &key_blob,
155 )
156 .context("In store_new_key. Failed to handle super encryption.")?;
157
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800158 let mut key_metadata = KeyMetaData::new();
159 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800160 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800161
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800162 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800163 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800164 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800165 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800166 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800167 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800168 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800169 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800170 )
171 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700172 Ok(KeyDescriptor {
173 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800174 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700175 ..Default::default()
176 })
177 })
178 .context("In store_new_key.")?,
179 };
180
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700181 Ok(KeyMetadata {
182 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700183 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800184 certificate: cert_info.take_cert(),
185 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700186 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800187 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700188 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700189 }
190
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700191 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700192 &self,
193 key: &KeyDescriptor,
194 operation_parameters: &[KeyParameter],
195 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700196 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700197 let caller_uid = ThreadState::get_calling_uid();
198 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
199 // so that we can use it by reference like the blob provided by the key descriptor.
200 // Otherwise, we would have to clone the blob from the key descriptor.
201 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800202 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700203 Domain::BLOB => {
204 check_key_permission(KeyPerm::use_(), key, &None)
205 .context("In create_operation: checking use permission for Domain::BLOB.")?;
206 (
207 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700208 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700209 None => {
210 return Err(Error::sys()).context(concat!(
211 "In create_operation: Key blob must be specified when",
212 " using Domain::BLOB."
213 ))
214 }
215 },
216 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000217 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000218 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700219 )
220 }
221 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800222 let (key_id_guard, mut key_entry) = DB
223 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000224 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
225 db.borrow_mut().load_key_entry(
226 &key,
227 KeyType::Client,
228 KeyEntryLoadBits::KM,
229 caller_uid,
230 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
231 )
232 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700233 })
234 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800235
236 let (blob, blob_metadata) =
237 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
238 "In create_operation: Successfully loaded key entry, ",
239 "but KM blob was missing."
240 ))?;
241 scoping_blob = blob;
242
Qi Wub9433b52020-12-01 14:52:46 +0800243 (
244 &scoping_blob,
245 Some((key_id_guard.id(), key_entry.into_key_parameters())),
246 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000247 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800248 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700249 }
250 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700251
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700252 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700253 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700254 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800255 |kp| match kp.value {
256 KeyParameterValue::KeyPurpose(p) => Ok(p),
257 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
258 .context("In create_operation: Malformed KeyParameter."),
259 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700260 )?;
261
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800262 let (immediate_hat, mut auth_info) = ENFORCEMENTS
263 .authorize_create(
264 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800265 key_properties.as_ref(),
266 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800267 // TODO b/178222844 Replace this with the configuration returned by
268 // KeyMintDevice::getHardwareInfo.
269 // For now we assume that strongbox implementations need secure timestamps.
270 self.security_level == SecurityLevel::STRONGBOX,
271 )
272 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000273
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800274 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000275
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000276 let user_id = uid_to_android_user(caller_uid);
277
278 let km_blob = SUPER_KEY
279 .unwrap_key_if_required(&blob_metadata, km_blob)
280 .context("In create_operation. Failed to handle super encryption.")?;
281
Stephen Crane221bbb52020-12-16 15:52:10 -0800282 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700283 .keymint
284 .get_interface()
285 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700286
Janis Danisevskisaec14592020-11-12 09:41:49 -0800287 let (begin_result, upgraded_blob) = self
288 .upgrade_keyblob_if_required_with(
289 &*km_dev,
290 key_id_guard,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000291 &(&km_blob, &blob_metadata),
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700292 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800293 |blob| loop {
294 match map_km_error(km_dev.begin(
295 purpose,
296 blob,
297 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800298 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800299 )) {
300 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
301 self.operation_db.prune(caller_uid)?;
302 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700303 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800304 v => return v,
305 }
306 },
307 )
308 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700309
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800310 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000311
Janis Danisevskis1af91262020-08-10 14:58:08 -0700312 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000313 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800314 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000315 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700316 None => return Err(Error::sys()).context("In create_operation: Begin operation returned successfully, but did not return a valid operation."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700317 };
318
Stephen Crane221bbb52020-12-16 15:52:10 -0800319 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700320 KeystoreOperation::new_native_binder(operation)
321 .as_binder()
322 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700323 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700324
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700325 Ok(CreateOperationResponse {
326 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000327 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700328 parameters: match begin_result.params.len() {
329 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700330 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700331 },
332 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700333 }
334
Janis Danisevskise766edc2021-02-06 12:16:26 -0800335 fn add_certificate_parameters(
336 uid: u32,
337 params: &[KeyParameter],
338 key: &KeyDescriptor,
339 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800340 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800341 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800342 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
343 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800344 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800345 })?;
346 result.push(KeyParameter {
347 tag: Tag::ATTESTATION_APPLICATION_ID,
348 value: KeyParameterValue::Blob(aaid),
349 });
350 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800351
Janis Danisevskise766edc2021-02-06 12:16:26 -0800352 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
353 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
354 "In add_certificate_parameters: ",
355 "Caller does not have the permission for device unique attestation."
356 ))?;
357 }
358
Janis Danisevskis2c084012021-01-31 22:23:17 -0800359 // If we are generating/importing an asymmetric key, we need to make sure
360 // that NOT_BEFORE and NOT_AFTER are present.
361 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
362 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
363 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
364 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
365 result.push(KeyParameter {
366 tag: Tag::CERTIFICATE_NOT_BEFORE,
367 value: KeyParameterValue::DateTime(0),
368 })
369 }
370 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
371 result.push(KeyParameter {
372 tag: Tag::CERTIFICATE_NOT_AFTER,
373 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
374 })
375 }
376 }
377 _ => {}
378 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800379 Ok(result)
380 }
381
Janis Danisevskis1af91262020-08-10 14:58:08 -0700382 fn generate_key(
383 &self,
384 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700385 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700386 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700387 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700388 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700389 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700390 if key.domain != Domain::BLOB && key.alias.is_none() {
391 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
392 .context("In generate_key: Alias must be specified");
393 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000394 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700395
396 let key = match key.domain {
397 Domain::APP => KeyDescriptor {
398 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000399 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700400 alias: key.alias.clone(),
401 blob: None,
402 },
403 _ => key.clone(),
404 };
405
406 // generate_key requires the rebind permission.
407 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
408
Shawn Willden8fde4c22021-02-14 13:58:22 -0700409 let attest_key = match attest_key_descriptor {
410 None => None,
411 Some(key) => Some(
412 self.get_attest_key(key, caller_uid)
413 .context("In generate_key: Trying to load attest key")?,
414 ),
415 };
416
Janis Danisevskise766edc2021-02-06 12:16:26 -0800417 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800418 .context("In generate_key: Trying to get aaid.")?;
419
Stephen Crane221bbb52020-12-16 15:52:10 -0800420 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800421 map_km_error(km_dev.addRngEntropy(entropy))
422 .context("In generate_key: Trying to add entropy.")?;
Shawn Willden8fde4c22021-02-14 13:58:22 -0700423 let creation_result = map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800424 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700425
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000426 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000427 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700428 }
429
Shawn Willden8fde4c22021-02-14 13:58:22 -0700430 fn get_attest_key(&self, key: &KeyDescriptor, caller_uid: u32) -> Result<AttestationKey> {
431 let (km_blob, cert) = self
432 .load_attest_key_blob_and_cert(&key, caller_uid)
433 .context("In get_attest_key: Failed to load blob and cert")?;
434
Shawn Willden34120872021-02-24 21:56:30 -0700435 let issuer_subject: Vec<u8> = parse_subject_from_certificate(&cert)
Shawn Willden8fde4c22021-02-14 13:58:22 -0700436 .context("In get_attest_key: Failed to parse subject from certificate.")?;
437
438 Ok(AttestationKey {
439 keyBlob: km_blob.to_vec(),
440 attestKeyParams: [].to_vec(),
441 issuerSubjectName: issuer_subject,
442 })
443 }
444
445 fn load_attest_key_blob_and_cert(
446 &self,
447 key: &KeyDescriptor,
448 caller_uid: u32,
449 ) -> Result<(Vec<u8>, Vec<u8>)> {
450 match key.domain {
451 Domain::BLOB => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
452 "In load_attest_key_blob_and_cert: Domain::BLOB attestation keys not supported",
453 ),
454 _ => {
455 let (key_id_guard, mut key_entry) = DB
456 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
457 db.borrow_mut().load_key_entry(
458 &key,
459 KeyType::Client,
460 KeyEntryLoadBits::BOTH,
461 caller_uid,
462 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
463 )
464 })
465 .context("In load_attest_key_blob_and_cert: Failed to load key.")?;
466
467 let (blob, _) =
468 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
469 "In load_attest_key_blob_and_cert: Successfully loaded key entry,",
470 " but KM blob was missing."
471 ))?;
472 let cert = key_entry.take_cert().ok_or_else(Error::sys).context(concat!(
473 "In load_attest_key_blob_and_cert: Successfully loaded key entry,",
474 " but cert was missing."
475 ))?;
476 Ok((blob, cert))
477 }
478 }
479 }
480
Janis Danisevskis1af91262020-08-10 14:58:08 -0700481 fn import_key(
482 &self,
483 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700484 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700485 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700486 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700487 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700488 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700489 if key.domain != Domain::BLOB && key.alias.is_none() {
490 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
491 .context("In import_key: Alias must be specified");
492 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000493 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700494
495 let key = match key.domain {
496 Domain::APP => KeyDescriptor {
497 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000498 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700499 alias: key.alias.clone(),
500 blob: None,
501 },
502 _ => key.clone(),
503 };
504
505 // import_key requires the rebind permission.
506 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
507
Janis Danisevskise766edc2021-02-06 12:16:26 -0800508 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800509 .context("In import_key: Trying to get aaid.")?;
510
Janis Danisevskis1af91262020-08-10 14:58:08 -0700511 let format = params
512 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700513 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700514 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
515 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800516 .and_then(|p| match &p.value {
517 KeyParameterValue::Algorithm(Algorithm::AES)
518 | KeyParameterValue::Algorithm(Algorithm::HMAC)
519 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
520 KeyParameterValue::Algorithm(Algorithm::RSA)
521 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
522 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
523 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700524 })
525 .context("In import_key.")?;
526
Stephen Crane221bbb52020-12-16 15:52:10 -0800527 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800528 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700529 let creation_result =
530 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
531 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700532
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000533 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000534 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700535 }
536
537 fn import_wrapped_key(
538 &self,
539 key: &KeyDescriptor,
540 wrapping_key: &KeyDescriptor,
541 masking_key: Option<&[u8]>,
542 params: &[KeyParameter],
543 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700544 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800545 let wrapped_data: &[u8] = match key {
546 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
547 | KeyDescriptor {
548 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
549 } => blob,
550 _ => {
551 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
552 concat!(
553 "In import_wrapped_key: Alias and blob must be specified ",
554 "and domain must be APP or SELINUX. {:?}"
555 ),
556 key
557 ))
558 }
559 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700560
Janis Danisevskisaec14592020-11-12 09:41:49 -0800561 if wrapping_key.domain == Domain::BLOB {
562 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
563 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
564 );
565 }
566
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000567 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000568 let user_id = uid_to_android_user(caller_uid);
569
Janis Danisevskis1af91262020-08-10 14:58:08 -0700570 let key = match key.domain {
571 Domain::APP => KeyDescriptor {
572 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000573 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700574 alias: key.alias.clone(),
575 blob: None,
576 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800577 Domain::SELINUX => KeyDescriptor {
578 domain: Domain::SELINUX,
579 nspace: key.nspace,
580 alias: key.alias.clone(),
581 blob: None,
582 },
583 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700584 };
585
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800586 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700587 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
588
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000589 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700590 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000591 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
592 db.borrow_mut().load_key_entry(
593 &wrapping_key,
594 KeyType::Client,
595 KeyEntryLoadBits::KM,
596 caller_uid,
597 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
598 )
599 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700600 })
601 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000602
603 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
604 .take_key_blob_info()
605 .ok_or_else(error::Error::sys)
606 .context("No km_blob after successfully loading key. This should never happen.")?;
607
608 let wrapping_key_blob =
609 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
610 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
611 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700612
Janis Danisevskis1af91262020-08-10 14:58:08 -0700613 // km_dev.importWrappedKey does not return a certificate chain.
614 // TODO Do we assume that all wrapped keys are symmetric?
615 // let certificate_chain: Vec<KmCertificate> = Default::default();
616
617 let pw_sid = authenticators
618 .iter()
619 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700620 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700621 _ => None,
622 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800623 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700624
625 let fp_sid = authenticators
626 .iter()
627 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700628 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700629 _ => None,
630 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800631 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700632
633 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
634
Stephen Crane221bbb52020-12-16 15:52:10 -0800635 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800636 let (creation_result, _) = self
637 .upgrade_keyblob_if_required_with(
638 &*km_dev,
639 Some(wrapping_key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000640 &(&wrapping_key_blob, &wrapping_blob_metadata),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800641 &[],
642 |wrapping_blob| {
643 let creation_result = map_km_error(km_dev.importWrappedKey(
644 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800645 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800646 masking_key,
647 &params,
648 pw_sid,
649 fp_sid,
650 ))?;
651 Ok(creation_result)
652 },
653 )
654 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700655
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000656 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800657 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700658 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800659
660 fn upgrade_keyblob_if_required_with<T, F>(
661 &self,
662 km_dev: &dyn IKeyMintDevice,
663 key_id_guard: Option<KeyIdGuard>,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000664 blob_info: &(&KeyBlob, &BlobMetaData),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800665 params: &[KeyParameter],
666 f: F,
667 ) -> Result<(T, Option<Vec<u8>>)>
668 where
669 F: Fn(&[u8]) -> Result<T, Error>,
670 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800671 match f(blob_info.0) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800672 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800673 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob_info.0, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800674 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000675
676 let (upgraded_blob_to_be_stored, blob_metadata) =
677 SuperKeyManager::reencrypt_on_upgrade_if_required(blob_info.0, &upgraded_blob)
678 .context(
679 "In upgrade_keyblob_if_required_with: Failed to handle super encryption.",
680 )?;
681
682 let mut blob_metadata = blob_metadata.unwrap_or_else(BlobMetaData::new);
683 if let Some(uuid) = blob_info.1.km_uuid() {
684 blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
685 }
686
Janis Danisevskisaec14592020-11-12 09:41:49 -0800687 key_id_guard.map_or(Ok(()), |key_id_guard| {
688 DB.with(|db| {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000689 let mut db = db.borrow_mut();
690 db.set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800691 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800692 SubComponentType::KEY_BLOB,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000693 Some(&upgraded_blob_to_be_stored),
694 Some(&blob_metadata),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800695 )
696 })
697 .context(concat!(
698 "In upgrade_keyblob_if_required_with: ",
699 "Failed to insert upgraded blob into the database.",
700 ))
701 })?;
702 match f(&upgraded_blob) {
703 Ok(v) => Ok((v, Some(upgraded_blob))),
704 Err(e) => Err(e).context(concat!(
705 "In upgrade_keyblob_if_required_with: ",
706 "Failed to perform operation on second try."
707 )),
708 }
709 }
710 Err(e) => {
711 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
712 }
713 Ok(v) => Ok((v, None)),
714 }
715 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700716}
717
718impl binder::Interface for KeystoreSecurityLevel {}
719
720impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700721 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700722 &self,
723 key: &KeyDescriptor,
724 operation_parameters: &[KeyParameter],
725 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700726 ) -> binder::public_api::Result<CreateOperationResponse> {
727 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700728 }
729 fn generateKey(
730 &self,
731 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700732 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700733 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700734 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700735 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700736 ) -> binder::public_api::Result<KeyMetadata> {
737 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700738 }
739 fn importKey(
740 &self,
741 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700742 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700743 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700744 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700745 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700746 ) -> binder::public_api::Result<KeyMetadata> {
747 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700748 }
749 fn importWrappedKey(
750 &self,
751 key: &KeyDescriptor,
752 wrapping_key: &KeyDescriptor,
753 masking_key: Option<&[u8]>,
754 params: &[KeyParameter],
755 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700756 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700757 map_or_log_err(
758 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700759 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700760 )
761 }
762}