blob: 8368c93bb4339380687e0f025c2cd93bbf39538f [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 Willden8fde4c22021-02-14 13:58:22 -070056use keystore2_crypto::parse_issuer_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
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000134 let (key_blob, mut blob_metadata) = DB
135 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000136 SUPER_KEY.handle_super_encryption_on_key_init(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000137 &mut db.borrow_mut(),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000138 &LEGACY_MIGRATOR,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000139 &(key.domain),
140 &key_parameters,
141 flags,
142 user_id,
143 &key_blob,
144 )
145 })
146 .context("In store_new_key. Failed to handle super encryption.")?;
147
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800148 let creation_date = DateTime::now().context("Trying to make creation time.")?;
149
Janis Danisevskis1af91262020-08-10 14:58:08 -0700150 let key = match key.domain {
151 Domain::BLOB => {
Shawn Willdendbdac602021-01-12 22:35:16 -0700152 KeyDescriptor { domain: Domain::BLOB, blob: Some(key_blob), ..Default::default() }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700153 }
154 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800155 .with::<_, Result<KeyDescriptor>>(|db| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800156 let mut key_metadata = KeyMetaData::new();
157 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800158 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800159
160 let mut db = db.borrow_mut();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800161 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800162 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800163 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800164 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800165 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800166 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800167 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800168 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800169 )
170 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700171 Ok(KeyDescriptor {
172 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800173 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700174 ..Default::default()
175 })
176 })
177 .context("In store_new_key.")?,
178 };
179
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700180 Ok(KeyMetadata {
181 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700182 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800183 certificate: cert_info.take_cert(),
184 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700185 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800186 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700187 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700188 }
189
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700190 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700191 &self,
192 key: &KeyDescriptor,
193 operation_parameters: &[KeyParameter],
194 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700195 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700196 let caller_uid = ThreadState::get_calling_uid();
197 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
198 // so that we can use it by reference like the blob provided by the key descriptor.
199 // Otherwise, we would have to clone the blob from the key descriptor.
200 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800201 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700202 Domain::BLOB => {
203 check_key_permission(KeyPerm::use_(), key, &None)
204 .context("In create_operation: checking use permission for Domain::BLOB.")?;
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800205 if forced {
206 check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
207 "In create_operation: checking forced permission for Domain::BLOB.",
208 )?;
209 }
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700210 (
211 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700212 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700213 None => {
214 return Err(Error::sys()).context(concat!(
215 "In create_operation: Key blob must be specified when",
216 " using Domain::BLOB."
217 ))
218 }
219 },
220 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000221 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000222 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700223 )
224 }
225 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800226 let (key_id_guard, mut key_entry) = DB
227 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000228 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
229 db.borrow_mut().load_key_entry(
230 &key,
231 KeyType::Client,
232 KeyEntryLoadBits::KM,
233 caller_uid,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800234 |k, av| {
235 check_key_permission(KeyPerm::use_(), k, &av)?;
236 if forced {
237 check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
238 }
239 Ok(())
240 },
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000241 )
242 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700243 })
244 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800245
246 let (blob, blob_metadata) =
247 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
248 "In create_operation: Successfully loaded key entry, ",
249 "but KM blob was missing."
250 ))?;
251 scoping_blob = blob;
252
Qi Wub9433b52020-12-01 14:52:46 +0800253 (
254 &scoping_blob,
255 Some((key_id_guard.id(), key_entry.into_key_parameters())),
256 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000257 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800258 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700259 }
260 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700261
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700262 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700263 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700264 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800265 |kp| match kp.value {
266 KeyParameterValue::KeyPurpose(p) => Ok(p),
267 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
268 .context("In create_operation: Malformed KeyParameter."),
269 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700270 )?;
271
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800272 let (immediate_hat, mut auth_info) = ENFORCEMENTS
273 .authorize_create(
274 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800275 key_properties.as_ref(),
276 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800277 // TODO b/178222844 Replace this with the configuration returned by
278 // KeyMintDevice::getHardwareInfo.
279 // For now we assume that strongbox implementations need secure timestamps.
280 self.security_level == SecurityLevel::STRONGBOX,
281 )
282 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000283
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800284 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000285
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000286 let km_blob = SUPER_KEY
287 .unwrap_key_if_required(&blob_metadata, km_blob)
288 .context("In create_operation. Failed to handle super encryption.")?;
289
Stephen Crane221bbb52020-12-16 15:52:10 -0800290 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700291 .keymint
292 .get_interface()
293 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700294
Janis Danisevskisaec14592020-11-12 09:41:49 -0800295 let (begin_result, upgraded_blob) = self
296 .upgrade_keyblob_if_required_with(
297 &*km_dev,
298 key_id_guard,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000299 &(&km_blob, &blob_metadata),
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700300 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800301 |blob| loop {
302 match map_km_error(km_dev.begin(
303 purpose,
304 blob,
305 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800306 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800307 )) {
308 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800309 self.operation_db.prune(caller_uid, forced)?;
Janis Danisevskisaec14592020-11-12 09:41:49 -0800310 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700311 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800312 v => return v,
313 }
314 },
315 )
316 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700317
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800318 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000319
Janis Danisevskis1af91262020-08-10 14:58:08 -0700320 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000321 Some(km_op) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800322 self.operation_db.create_operation(km_op, caller_uid, auth_info, forced)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000323 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700324 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 -0700325 };
326
Stephen Crane221bbb52020-12-16 15:52:10 -0800327 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328 KeystoreOperation::new_native_binder(operation)
329 .as_binder()
330 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700331 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700332
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700333 Ok(CreateOperationResponse {
334 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000335 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700336 parameters: match begin_result.params.len() {
337 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700338 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700339 },
340 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700341 }
342
Janis Danisevskise766edc2021-02-06 12:16:26 -0800343 fn add_certificate_parameters(
344 uid: u32,
345 params: &[KeyParameter],
346 key: &KeyDescriptor,
347 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800348 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800349 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800350 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
351 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800352 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800353 })?;
354 result.push(KeyParameter {
355 tag: Tag::ATTESTATION_APPLICATION_ID,
356 value: KeyParameterValue::Blob(aaid),
357 });
358 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800359
Janis Danisevskise766edc2021-02-06 12:16:26 -0800360 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
361 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
362 "In add_certificate_parameters: ",
363 "Caller does not have the permission for device unique attestation."
364 ))?;
365 }
366
Janis Danisevskis2c084012021-01-31 22:23:17 -0800367 // If we are generating/importing an asymmetric key, we need to make sure
368 // that NOT_BEFORE and NOT_AFTER are present.
369 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
370 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
371 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
372 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
373 result.push(KeyParameter {
374 tag: Tag::CERTIFICATE_NOT_BEFORE,
375 value: KeyParameterValue::DateTime(0),
376 })
377 }
378 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
379 result.push(KeyParameter {
380 tag: Tag::CERTIFICATE_NOT_AFTER,
381 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
382 })
383 }
384 }
385 _ => {}
386 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800387 Ok(result)
388 }
389
Janis Danisevskis1af91262020-08-10 14:58:08 -0700390 fn generate_key(
391 &self,
392 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700393 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700394 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700395 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700396 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700397 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700398 if key.domain != Domain::BLOB && key.alias.is_none() {
399 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
400 .context("In generate_key: Alias must be specified");
401 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000402 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700403
404 let key = match key.domain {
405 Domain::APP => KeyDescriptor {
406 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000407 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700408 alias: key.alias.clone(),
409 blob: None,
410 },
411 _ => key.clone(),
412 };
413
414 // generate_key requires the rebind permission.
415 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
416
Shawn Willden8fde4c22021-02-14 13:58:22 -0700417 let attest_key = match attest_key_descriptor {
418 None => None,
419 Some(key) => Some(
420 self.get_attest_key(key, caller_uid)
421 .context("In generate_key: Trying to load attest key")?,
422 ),
423 };
424
Janis Danisevskise766edc2021-02-06 12:16:26 -0800425 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800426 .context("In generate_key: Trying to get aaid.")?;
427
Stephen Crane221bbb52020-12-16 15:52:10 -0800428 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800429 map_km_error(km_dev.addRngEntropy(entropy))
430 .context("In generate_key: Trying to add entropy.")?;
Shawn Willden8fde4c22021-02-14 13:58:22 -0700431 let creation_result = map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800432 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700433
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000434 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000435 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700436 }
437
Shawn Willden8fde4c22021-02-14 13:58:22 -0700438 fn get_attest_key(&self, key: &KeyDescriptor, caller_uid: u32) -> Result<AttestationKey> {
439 let (km_blob, cert) = self
440 .load_attest_key_blob_and_cert(&key, caller_uid)
441 .context("In get_attest_key: Failed to load blob and cert")?;
442
443 let issuer_subject: Vec<u8> = parse_issuer_subject_from_certificate(&cert)
444 .context("In get_attest_key: Failed to parse subject from certificate.")?;
445
446 Ok(AttestationKey {
447 keyBlob: km_blob.to_vec(),
448 attestKeyParams: [].to_vec(),
449 issuerSubjectName: issuer_subject,
450 })
451 }
452
453 fn load_attest_key_blob_and_cert(
454 &self,
455 key: &KeyDescriptor,
456 caller_uid: u32,
457 ) -> Result<(Vec<u8>, Vec<u8>)> {
458 match key.domain {
459 Domain::BLOB => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
460 "In load_attest_key_blob_and_cert: Domain::BLOB attestation keys not supported",
461 ),
462 _ => {
463 let (key_id_guard, mut key_entry) = DB
464 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
465 db.borrow_mut().load_key_entry(
466 &key,
467 KeyType::Client,
468 KeyEntryLoadBits::BOTH,
469 caller_uid,
470 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
471 )
472 })
473 .context("In load_attest_key_blob_and_cert: Failed to load key.")?;
474
475 let (blob, _) =
476 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
477 "In load_attest_key_blob_and_cert: Successfully loaded key entry,",
478 " but KM blob was missing."
479 ))?;
480 let cert = key_entry.take_cert().ok_or_else(Error::sys).context(concat!(
481 "In load_attest_key_blob_and_cert: Successfully loaded key entry,",
482 " but cert was missing."
483 ))?;
484 Ok((blob, cert))
485 }
486 }
487 }
488
Janis Danisevskis1af91262020-08-10 14:58:08 -0700489 fn import_key(
490 &self,
491 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700492 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700493 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700494 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700495 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700496 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700497 if key.domain != Domain::BLOB && key.alias.is_none() {
498 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
499 .context("In import_key: Alias must be specified");
500 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000501 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700502
503 let key = match key.domain {
504 Domain::APP => KeyDescriptor {
505 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000506 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700507 alias: key.alias.clone(),
508 blob: None,
509 },
510 _ => key.clone(),
511 };
512
513 // import_key requires the rebind permission.
514 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
515
Janis Danisevskise766edc2021-02-06 12:16:26 -0800516 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800517 .context("In import_key: Trying to get aaid.")?;
518
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519 let format = params
520 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700521 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700522 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
523 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800524 .and_then(|p| match &p.value {
525 KeyParameterValue::Algorithm(Algorithm::AES)
526 | KeyParameterValue::Algorithm(Algorithm::HMAC)
527 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
528 KeyParameterValue::Algorithm(Algorithm::RSA)
529 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
530 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
531 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700532 })
533 .context("In import_key.")?;
534
Stephen Crane221bbb52020-12-16 15:52:10 -0800535 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800536 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700537 let creation_result =
538 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
539 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700540
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000541 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000542 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700543 }
544
545 fn import_wrapped_key(
546 &self,
547 key: &KeyDescriptor,
548 wrapping_key: &KeyDescriptor,
549 masking_key: Option<&[u8]>,
550 params: &[KeyParameter],
551 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700552 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800553 let wrapped_data: &[u8] = match key {
554 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
555 | KeyDescriptor {
556 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
557 } => blob,
558 _ => {
559 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
560 concat!(
561 "In import_wrapped_key: Alias and blob must be specified ",
562 "and domain must be APP or SELINUX. {:?}"
563 ),
564 key
565 ))
566 }
567 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700568
Janis Danisevskisaec14592020-11-12 09:41:49 -0800569 if wrapping_key.domain == Domain::BLOB {
570 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
571 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
572 );
573 }
574
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000575 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000576 let user_id = uid_to_android_user(caller_uid);
577
Janis Danisevskis1af91262020-08-10 14:58:08 -0700578 let key = match key.domain {
579 Domain::APP => KeyDescriptor {
580 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000581 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700582 alias: key.alias.clone(),
583 blob: None,
584 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800585 Domain::SELINUX => KeyDescriptor {
586 domain: Domain::SELINUX,
587 nspace: key.nspace,
588 alias: key.alias.clone(),
589 blob: None,
590 },
591 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700592 };
593
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800594 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700595 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
596
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000597 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700598 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000599 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
600 db.borrow_mut().load_key_entry(
601 &wrapping_key,
602 KeyType::Client,
603 KeyEntryLoadBits::KM,
604 caller_uid,
605 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
606 )
607 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700608 })
609 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000610
611 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
612 .take_key_blob_info()
613 .ok_or_else(error::Error::sys)
614 .context("No km_blob after successfully loading key. This should never happen.")?;
615
616 let wrapping_key_blob =
617 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
618 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
619 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700620
Janis Danisevskis1af91262020-08-10 14:58:08 -0700621 // km_dev.importWrappedKey does not return a certificate chain.
622 // TODO Do we assume that all wrapped keys are symmetric?
623 // let certificate_chain: Vec<KmCertificate> = Default::default();
624
625 let pw_sid = authenticators
626 .iter()
627 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700628 HardwareAuthenticatorType::PASSWORD => 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 fp_sid = authenticators
634 .iter()
635 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700636 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700637 _ => None,
638 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800639 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700640
641 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
642
Stephen Crane221bbb52020-12-16 15:52:10 -0800643 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800644 let (creation_result, _) = self
645 .upgrade_keyblob_if_required_with(
646 &*km_dev,
647 Some(wrapping_key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000648 &(&wrapping_key_blob, &wrapping_blob_metadata),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800649 &[],
650 |wrapping_blob| {
651 let creation_result = map_km_error(km_dev.importWrappedKey(
652 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800653 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800654 masking_key,
655 &params,
656 pw_sid,
657 fp_sid,
658 ))?;
659 Ok(creation_result)
660 },
661 )
662 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700663
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000664 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800665 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700666 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800667
668 fn upgrade_keyblob_if_required_with<T, F>(
669 &self,
670 km_dev: &dyn IKeyMintDevice,
671 key_id_guard: Option<KeyIdGuard>,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000672 blob_info: &(&KeyBlob, &BlobMetaData),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800673 params: &[KeyParameter],
674 f: F,
675 ) -> Result<(T, Option<Vec<u8>>)>
676 where
677 F: Fn(&[u8]) -> Result<T, Error>,
678 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800679 match f(blob_info.0) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800680 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800681 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob_info.0, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800682 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000683
684 let (upgraded_blob_to_be_stored, blob_metadata) =
685 SuperKeyManager::reencrypt_on_upgrade_if_required(blob_info.0, &upgraded_blob)
686 .context(
687 "In upgrade_keyblob_if_required_with: Failed to handle super encryption.",
688 )?;
689
690 let mut blob_metadata = blob_metadata.unwrap_or_else(BlobMetaData::new);
691 if let Some(uuid) = blob_info.1.km_uuid() {
692 blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
693 }
694
Janis Danisevskisaec14592020-11-12 09:41:49 -0800695 key_id_guard.map_or(Ok(()), |key_id_guard| {
696 DB.with(|db| {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000697 let mut db = db.borrow_mut();
698 db.set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800699 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800700 SubComponentType::KEY_BLOB,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000701 Some(&upgraded_blob_to_be_stored),
702 Some(&blob_metadata),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800703 )
704 })
705 .context(concat!(
706 "In upgrade_keyblob_if_required_with: ",
707 "Failed to insert upgraded blob into the database.",
708 ))
709 })?;
710 match f(&upgraded_blob) {
711 Ok(v) => Ok((v, Some(upgraded_blob))),
712 Err(e) => Err(e).context(concat!(
713 "In upgrade_keyblob_if_required_with: ",
714 "Failed to perform operation on second try."
715 )),
716 }
717 }
718 Err(e) => {
719 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
720 }
721 Ok(v) => Ok((v, None)),
722 }
723 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700724}
725
726impl binder::Interface for KeystoreSecurityLevel {}
727
728impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700729 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700730 &self,
731 key: &KeyDescriptor,
732 operation_parameters: &[KeyParameter],
733 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700734 ) -> binder::public_api::Result<CreateOperationResponse> {
735 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700736 }
737 fn generateKey(
738 &self,
739 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700740 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700741 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700742 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700743 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700744 ) -> binder::public_api::Result<KeyMetadata> {
745 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700746 }
747 fn importKey(
748 &self,
749 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700750 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700751 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700752 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700753 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700754 ) -> binder::public_api::Result<KeyMetadata> {
755 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700756 }
757 fn importWrappedKey(
758 &self,
759 key: &KeyDescriptor,
760 wrapping_key: &KeyDescriptor,
761 masking_key: Option<&[u8]>,
762 params: &[KeyParameter],
763 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700764 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700765 map_or_log_err(
766 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700767 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700768 )
769 }
770}