blob: 50cb9bf4ba8dbc9114d5ac65dbbc59bdca9f6aee [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
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.")?;
205 (
206 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700207 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700208 None => {
209 return Err(Error::sys()).context(concat!(
210 "In create_operation: Key blob must be specified when",
211 " using Domain::BLOB."
212 ))
213 }
214 },
215 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000216 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000217 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700218 )
219 }
220 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800221 let (key_id_guard, mut key_entry) = DB
222 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000223 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
224 db.borrow_mut().load_key_entry(
225 &key,
226 KeyType::Client,
227 KeyEntryLoadBits::KM,
228 caller_uid,
229 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
230 )
231 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700232 })
233 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800234
235 let (blob, blob_metadata) =
236 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
237 "In create_operation: Successfully loaded key entry, ",
238 "but KM blob was missing."
239 ))?;
240 scoping_blob = blob;
241
Qi Wub9433b52020-12-01 14:52:46 +0800242 (
243 &scoping_blob,
244 Some((key_id_guard.id(), key_entry.into_key_parameters())),
245 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000246 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800247 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700248 }
249 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700250
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700251 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700252 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700253 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800254 |kp| match kp.value {
255 KeyParameterValue::KeyPurpose(p) => Ok(p),
256 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
257 .context("In create_operation: Malformed KeyParameter."),
258 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700259 )?;
260
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800261 let (immediate_hat, mut auth_info) = ENFORCEMENTS
262 .authorize_create(
263 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800264 key_properties.as_ref(),
265 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800266 // TODO b/178222844 Replace this with the configuration returned by
267 // KeyMintDevice::getHardwareInfo.
268 // For now we assume that strongbox implementations need secure timestamps.
269 self.security_level == SecurityLevel::STRONGBOX,
270 )
271 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000272
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800273 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000274
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000275 let user_id = uid_to_android_user(caller_uid);
276
277 let km_blob = SUPER_KEY
278 .unwrap_key_if_required(&blob_metadata, km_blob)
279 .context("In create_operation. Failed to handle super encryption.")?;
280
Stephen Crane221bbb52020-12-16 15:52:10 -0800281 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700282 .keymint
283 .get_interface()
284 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700285
Janis Danisevskisaec14592020-11-12 09:41:49 -0800286 let (begin_result, upgraded_blob) = self
287 .upgrade_keyblob_if_required_with(
288 &*km_dev,
289 key_id_guard,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000290 &(&km_blob, &blob_metadata),
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700291 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800292 |blob| loop {
293 match map_km_error(km_dev.begin(
294 purpose,
295 blob,
296 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800297 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800298 )) {
299 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
300 self.operation_db.prune(caller_uid)?;
301 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700302 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800303 v => return v,
304 }
305 },
306 )
307 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700308
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800309 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000310
Janis Danisevskis1af91262020-08-10 14:58:08 -0700311 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000312 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800313 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000314 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700315 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 -0700316 };
317
Stephen Crane221bbb52020-12-16 15:52:10 -0800318 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700319 KeystoreOperation::new_native_binder(operation)
320 .as_binder()
321 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700322 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700323
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700324 Ok(CreateOperationResponse {
325 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000326 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700327 parameters: match begin_result.params.len() {
328 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700329 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700330 },
331 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700332 }
333
Janis Danisevskise766edc2021-02-06 12:16:26 -0800334 fn add_certificate_parameters(
335 uid: u32,
336 params: &[KeyParameter],
337 key: &KeyDescriptor,
338 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800339 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800340 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800341 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
342 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800343 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800344 })?;
345 result.push(KeyParameter {
346 tag: Tag::ATTESTATION_APPLICATION_ID,
347 value: KeyParameterValue::Blob(aaid),
348 });
349 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800350
Janis Danisevskise766edc2021-02-06 12:16:26 -0800351 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
352 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
353 "In add_certificate_parameters: ",
354 "Caller does not have the permission for device unique attestation."
355 ))?;
356 }
357
Janis Danisevskis2c084012021-01-31 22:23:17 -0800358 // If we are generating/importing an asymmetric key, we need to make sure
359 // that NOT_BEFORE and NOT_AFTER are present.
360 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
361 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
362 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
363 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
364 result.push(KeyParameter {
365 tag: Tag::CERTIFICATE_NOT_BEFORE,
366 value: KeyParameterValue::DateTime(0),
367 })
368 }
369 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
370 result.push(KeyParameter {
371 tag: Tag::CERTIFICATE_NOT_AFTER,
372 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
373 })
374 }
375 }
376 _ => {}
377 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800378 Ok(result)
379 }
380
Janis Danisevskis1af91262020-08-10 14:58:08 -0700381 fn generate_key(
382 &self,
383 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700384 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700385 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700386 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700387 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700388 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700389 if key.domain != Domain::BLOB && key.alias.is_none() {
390 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
391 .context("In generate_key: Alias must be specified");
392 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000393 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700394
395 let key = match key.domain {
396 Domain::APP => KeyDescriptor {
397 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000398 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700399 alias: key.alias.clone(),
400 blob: None,
401 },
402 _ => key.clone(),
403 };
404
405 // generate_key requires the rebind permission.
406 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
407
Shawn Willden8fde4c22021-02-14 13:58:22 -0700408 let attest_key = match attest_key_descriptor {
409 None => None,
410 Some(key) => Some(
411 self.get_attest_key(key, caller_uid)
412 .context("In generate_key: Trying to load attest key")?,
413 ),
414 };
415
Janis Danisevskise766edc2021-02-06 12:16:26 -0800416 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800417 .context("In generate_key: Trying to get aaid.")?;
418
Stephen Crane221bbb52020-12-16 15:52:10 -0800419 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800420 map_km_error(km_dev.addRngEntropy(entropy))
421 .context("In generate_key: Trying to add entropy.")?;
Shawn Willden8fde4c22021-02-14 13:58:22 -0700422 let creation_result = map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800423 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700424
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000425 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000426 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700427 }
428
Shawn Willden8fde4c22021-02-14 13:58:22 -0700429 fn get_attest_key(&self, key: &KeyDescriptor, caller_uid: u32) -> Result<AttestationKey> {
430 let (km_blob, cert) = self
431 .load_attest_key_blob_and_cert(&key, caller_uid)
432 .context("In get_attest_key: Failed to load blob and cert")?;
433
Shawn Willden34120872021-02-24 21:56:30 -0700434 let issuer_subject: Vec<u8> = parse_subject_from_certificate(&cert)
Shawn Willden8fde4c22021-02-14 13:58:22 -0700435 .context("In get_attest_key: Failed to parse subject from certificate.")?;
436
437 Ok(AttestationKey {
438 keyBlob: km_blob.to_vec(),
439 attestKeyParams: [].to_vec(),
440 issuerSubjectName: issuer_subject,
441 })
442 }
443
444 fn load_attest_key_blob_and_cert(
445 &self,
446 key: &KeyDescriptor,
447 caller_uid: u32,
448 ) -> Result<(Vec<u8>, Vec<u8>)> {
449 match key.domain {
450 Domain::BLOB => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
451 "In load_attest_key_blob_and_cert: Domain::BLOB attestation keys not supported",
452 ),
453 _ => {
454 let (key_id_guard, mut key_entry) = DB
455 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
456 db.borrow_mut().load_key_entry(
457 &key,
458 KeyType::Client,
459 KeyEntryLoadBits::BOTH,
460 caller_uid,
461 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
462 )
463 })
464 .context("In load_attest_key_blob_and_cert: Failed to load key.")?;
465
466 let (blob, _) =
467 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
468 "In load_attest_key_blob_and_cert: Successfully loaded key entry,",
469 " but KM blob was missing."
470 ))?;
471 let cert = key_entry.take_cert().ok_or_else(Error::sys).context(concat!(
472 "In load_attest_key_blob_and_cert: Successfully loaded key entry,",
473 " but cert was missing."
474 ))?;
475 Ok((blob, cert))
476 }
477 }
478 }
479
Janis Danisevskis1af91262020-08-10 14:58:08 -0700480 fn import_key(
481 &self,
482 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700483 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700484 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700485 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700486 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700487 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700488 if key.domain != Domain::BLOB && key.alias.is_none() {
489 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
490 .context("In import_key: Alias must be specified");
491 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000492 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700493
494 let key = match key.domain {
495 Domain::APP => KeyDescriptor {
496 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000497 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700498 alias: key.alias.clone(),
499 blob: None,
500 },
501 _ => key.clone(),
502 };
503
504 // import_key requires the rebind permission.
505 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
506
Janis Danisevskise766edc2021-02-06 12:16:26 -0800507 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800508 .context("In import_key: Trying to get aaid.")?;
509
Janis Danisevskis1af91262020-08-10 14:58:08 -0700510 let format = params
511 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700512 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700513 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
514 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800515 .and_then(|p| match &p.value {
516 KeyParameterValue::Algorithm(Algorithm::AES)
517 | KeyParameterValue::Algorithm(Algorithm::HMAC)
518 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
519 KeyParameterValue::Algorithm(Algorithm::RSA)
520 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
521 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
522 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700523 })
524 .context("In import_key.")?;
525
Stephen Crane221bbb52020-12-16 15:52:10 -0800526 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800527 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700528 let creation_result =
529 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
530 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700531
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000532 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000533 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700534 }
535
536 fn import_wrapped_key(
537 &self,
538 key: &KeyDescriptor,
539 wrapping_key: &KeyDescriptor,
540 masking_key: Option<&[u8]>,
541 params: &[KeyParameter],
542 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700543 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800544 let wrapped_data: &[u8] = match key {
545 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
546 | KeyDescriptor {
547 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
548 } => blob,
549 _ => {
550 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
551 concat!(
552 "In import_wrapped_key: Alias and blob must be specified ",
553 "and domain must be APP or SELINUX. {:?}"
554 ),
555 key
556 ))
557 }
558 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700559
Janis Danisevskisaec14592020-11-12 09:41:49 -0800560 if wrapping_key.domain == Domain::BLOB {
561 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
562 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
563 );
564 }
565
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000566 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000567 let user_id = uid_to_android_user(caller_uid);
568
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569 let key = match key.domain {
570 Domain::APP => KeyDescriptor {
571 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000572 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700573 alias: key.alias.clone(),
574 blob: None,
575 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800576 Domain::SELINUX => KeyDescriptor {
577 domain: Domain::SELINUX,
578 nspace: key.nspace,
579 alias: key.alias.clone(),
580 blob: None,
581 },
582 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700583 };
584
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800585 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700586 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
587
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000588 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700589 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000590 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
591 db.borrow_mut().load_key_entry(
592 &wrapping_key,
593 KeyType::Client,
594 KeyEntryLoadBits::KM,
595 caller_uid,
596 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
597 )
598 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700599 })
600 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000601
602 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
603 .take_key_blob_info()
604 .ok_or_else(error::Error::sys)
605 .context("No km_blob after successfully loading key. This should never happen.")?;
606
607 let wrapping_key_blob =
608 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
609 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
610 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700611
Janis Danisevskis1af91262020-08-10 14:58:08 -0700612 // km_dev.importWrappedKey does not return a certificate chain.
613 // TODO Do we assume that all wrapped keys are symmetric?
614 // let certificate_chain: Vec<KmCertificate> = Default::default();
615
616 let pw_sid = authenticators
617 .iter()
618 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700619 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700620 _ => None,
621 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800622 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700623
624 let fp_sid = authenticators
625 .iter()
626 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700627 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700628 _ => None,
629 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800630 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631
632 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
633
Stephen Crane221bbb52020-12-16 15:52:10 -0800634 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800635 let (creation_result, _) = self
636 .upgrade_keyblob_if_required_with(
637 &*km_dev,
638 Some(wrapping_key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000639 &(&wrapping_key_blob, &wrapping_blob_metadata),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800640 &[],
641 |wrapping_blob| {
642 let creation_result = map_km_error(km_dev.importWrappedKey(
643 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800644 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800645 masking_key,
646 &params,
647 pw_sid,
648 fp_sid,
649 ))?;
650 Ok(creation_result)
651 },
652 )
653 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700654
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000655 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800656 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700657 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800658
659 fn upgrade_keyblob_if_required_with<T, F>(
660 &self,
661 km_dev: &dyn IKeyMintDevice,
662 key_id_guard: Option<KeyIdGuard>,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000663 blob_info: &(&KeyBlob, &BlobMetaData),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800664 params: &[KeyParameter],
665 f: F,
666 ) -> Result<(T, Option<Vec<u8>>)>
667 where
668 F: Fn(&[u8]) -> Result<T, Error>,
669 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800670 match f(blob_info.0) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800671 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800672 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob_info.0, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800673 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000674
675 let (upgraded_blob_to_be_stored, blob_metadata) =
676 SuperKeyManager::reencrypt_on_upgrade_if_required(blob_info.0, &upgraded_blob)
677 .context(
678 "In upgrade_keyblob_if_required_with: Failed to handle super encryption.",
679 )?;
680
681 let mut blob_metadata = blob_metadata.unwrap_or_else(BlobMetaData::new);
682 if let Some(uuid) = blob_info.1.km_uuid() {
683 blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
684 }
685
Janis Danisevskisaec14592020-11-12 09:41:49 -0800686 key_id_guard.map_or(Ok(()), |key_id_guard| {
687 DB.with(|db| {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000688 let mut db = db.borrow_mut();
689 db.set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800690 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800691 SubComponentType::KEY_BLOB,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000692 Some(&upgraded_blob_to_be_stored),
693 Some(&blob_metadata),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800694 )
695 })
696 .context(concat!(
697 "In upgrade_keyblob_if_required_with: ",
698 "Failed to insert upgraded blob into the database.",
699 ))
700 })?;
701 match f(&upgraded_blob) {
702 Ok(v) => Ok((v, Some(upgraded_blob))),
703 Err(e) => Err(e).context(concat!(
704 "In upgrade_keyblob_if_required_with: ",
705 "Failed to perform operation on second try."
706 )),
707 }
708 }
709 Err(e) => {
710 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
711 }
712 Ok(v) => Ok((v, None)),
713 }
714 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700715}
716
717impl binder::Interface for KeystoreSecurityLevel {}
718
719impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700720 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700721 &self,
722 key: &KeyDescriptor,
723 operation_parameters: &[KeyParameter],
724 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700725 ) -> binder::public_api::Result<CreateOperationResponse> {
726 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700727 }
728 fn generateKey(
729 &self,
730 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700731 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700732 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700733 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700734 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700735 ) -> binder::public_api::Result<KeyMetadata> {
736 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700737 }
738 fn importKey(
739 &self,
740 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700741 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700742 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700743 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700744 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700745 ) -> binder::public_api::Result<KeyMetadata> {
746 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700747 }
748 fn importWrappedKey(
749 &self,
750 key: &KeyDescriptor,
751 wrapping_key: &KeyDescriptor,
752 masking_key: Option<&[u8]>,
753 params: &[KeyParameter],
754 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700755 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700756 map_or_log_err(
757 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700758 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700759 )
760 }
761}