blob: 2af3544450977b4e651007322c48ccff6f5fe63c [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::{
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070021 Algorithm::Algorithm, AttestationKey::AttestationKey,
Shawn Willden8fde4c22021-02-14 13:58:22 -070022 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
Janis Danisevskis3541f3e2021-03-20 14:18:52 -070035use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
36use crate::database::{CertificateInfo, KeyIdGuard};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000037use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000038use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000039use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Max Bires97f96812021-02-23 23:44:57 -080040use crate::remote_provisioning::RemProvState;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000041use crate::super_key::{KeyBlob, SuperKeyManager};
Bram Bonné5d6c5102021-02-24 15:09:18 +010042use crate::utils::{
43 check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
44 uid_to_android_user, Asp,
45};
Max Bires8e93d2b2021-01-14 13:17:59 -080046use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080047 database::{
48 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
49 KeyMetaEntry, KeyType, SubComponentType, Uuid,
50 },
51 operation::KeystoreOperation,
52 operation::OperationDb,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080053 permission::KeyPerm,
54};
55use crate::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070056 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
57 utils::key_characteristics_to_internal,
58};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080059use anyhow::{anyhow, Context, Result};
Andrew Walbran808e8602021-03-16 13:58:28 +000060use binder::{IBinderInternal, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070061
62/// Implementation of the IKeystoreSecurityLevel Interface.
63pub struct KeystoreSecurityLevel {
64 security_level: SecurityLevel,
65 keymint: Asp,
Max Bires8e93d2b2021-01-14 13:17:59 -080066 #[allow(dead_code)]
67 hw_info: KeyMintHardwareInfo,
68 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070069 operation_db: OperationDb,
Max Bires97f96812021-02-23 23:44:57 -080070 rem_prov_state: RemProvState,
Janis Danisevskis1af91262020-08-10 14:58:08 -070071}
72
Janis Danisevskis1af91262020-08-10 14:58:08 -070073// Blob of 32 zeroes used as empty masking key.
74static ZERO_BLOB_32: &[u8] = &[0; 32];
75
Janis Danisevskis2c084012021-01-31 22:23:17 -080076// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
77// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
78const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
79
Janis Danisevskis1af91262020-08-10 14:58:08 -070080impl KeystoreSecurityLevel {
81 /// Creates a new security level instance wrapped in a
82 /// BnKeystoreSecurityLevel proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +000083 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -070084 /// we need it for checking keystore permissions.
85 pub fn new_native_binder(
86 security_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -080087 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080088 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
89 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070090 let result = BnKeystoreSecurityLevel::new_binder(Self {
91 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080092 keymint: dev,
93 hw_info,
94 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070095 operation_db: OperationDb::new(),
Max Bires97f96812021-02-23 23:44:57 -080096 rem_prov_state: RemProvState::new(security_level, km_uuid),
Janis Danisevskis1af91262020-08-10 14:58:08 -070097 });
98 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -080099 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700100 }
101
102 fn store_new_key(
103 &self,
104 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -0700105 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000106 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000107 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700108 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700109 let KeyCreationResult {
110 keyBlob: key_blob,
111 keyCharacteristics: key_characteristics,
112 certificateChain: mut certificate_chain,
113 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700114
Max Bires8e93d2b2021-01-14 13:17:59 -0800115 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700116 match certificate_chain.len() {
117 0 => None,
118 _ => Some(certificate_chain.remove(0).encodedCertificate),
119 },
120 match certificate_chain.len() {
121 0 => None,
122 _ => Some(
123 certificate_chain
124 .iter()
125 .map(|c| c.encodedCertificate.iter())
126 .flatten()
127 .copied()
128 .collect(),
129 ),
130 },
131 );
132
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000133 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
134
135 key_parameters.push(KsKeyParam::new(
136 KsKeyParamValue::UserID(user_id as i32),
137 SecurityLevel::SOFTWARE,
138 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700139
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800140 let creation_date = DateTime::now().context("Trying to make creation time.")?;
141
Janis Danisevskis1af91262020-08-10 14:58:08 -0700142 let key = match key.domain {
Satya Tangirala60671e32021-03-04 16:12:19 -0800143 Domain::BLOB => KeyDescriptor {
144 domain: Domain::BLOB,
145 blob: Some(key_blob.to_vec()),
146 ..Default::default()
147 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700148 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800149 .with::<_, Result<KeyDescriptor>>(|db| {
Satya Tangirala60671e32021-03-04 16:12:19 -0800150 let mut db = db.borrow_mut();
151
152 let (key_blob, mut blob_metadata) = SUPER_KEY
153 .handle_super_encryption_on_key_init(
154 &mut db,
155 &LEGACY_MIGRATOR,
156 &(key.domain),
157 &key_parameters,
158 flags,
159 user_id,
160 &key_blob,
161 )
162 .context("In store_new_key. Failed to handle super encryption.")?;
163
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800164 let mut key_metadata = KeyMetaData::new();
165 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800166 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800167
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800168 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800169 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800170 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800171 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800172 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800173 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800174 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800175 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800176 )
177 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700178 Ok(KeyDescriptor {
179 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800180 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700181 ..Default::default()
182 })
183 })
184 .context("In store_new_key.")?,
185 };
186
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700187 Ok(KeyMetadata {
188 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700189 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800190 certificate: cert_info.take_cert(),
191 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700192 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800193 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700194 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700195 }
196
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700197 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700198 &self,
199 key: &KeyDescriptor,
200 operation_parameters: &[KeyParameter],
201 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700202 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700203 let caller_uid = ThreadState::get_calling_uid();
204 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
205 // so that we can use it by reference like the blob provided by the key descriptor.
206 // Otherwise, we would have to clone the blob from the key descriptor.
207 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800208 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700209 Domain::BLOB => {
210 check_key_permission(KeyPerm::use_(), key, &None)
211 .context("In create_operation: checking use permission for Domain::BLOB.")?;
212 (
213 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700214 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700215 None => {
216 return Err(Error::sys()).context(concat!(
217 "In create_operation: Key blob must be specified when",
218 " using Domain::BLOB."
219 ))
220 }
221 },
222 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000223 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000224 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700225 )
226 }
227 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800228 let (key_id_guard, mut key_entry) = DB
229 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000230 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
231 db.borrow_mut().load_key_entry(
232 &key,
233 KeyType::Client,
234 KeyEntryLoadBits::KM,
235 caller_uid,
236 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
237 )
238 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700239 })
240 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800241
242 let (blob, blob_metadata) =
243 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
244 "In create_operation: Successfully loaded key entry, ",
245 "but KM blob was missing."
246 ))?;
247 scoping_blob = blob;
248
Qi Wub9433b52020-12-01 14:52:46 +0800249 (
250 &scoping_blob,
251 Some((key_id_guard.id(), key_entry.into_key_parameters())),
252 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000253 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800254 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700255 }
256 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700257
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700258 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700259 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700260 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800261 |kp| match kp.value {
262 KeyParameterValue::KeyPurpose(p) => Ok(p),
263 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
264 .context("In create_operation: Malformed KeyParameter."),
265 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700266 )?;
267
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800268 let (immediate_hat, mut auth_info) = ENFORCEMENTS
269 .authorize_create(
270 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800271 key_properties.as_ref(),
272 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800273 // TODO b/178222844 Replace this with the configuration returned by
274 // KeyMintDevice::getHardwareInfo.
275 // For now we assume that strongbox implementations need secure timestamps.
276 self.security_level == SecurityLevel::STRONGBOX,
277 )
278 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000279
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800280 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000281
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000282 let user_id = uid_to_android_user(caller_uid);
283
284 let km_blob = SUPER_KEY
285 .unwrap_key_if_required(&blob_metadata, km_blob)
286 .context("In create_operation. Failed to handle super encryption.")?;
287
Stephen Crane221bbb52020-12-16 15:52:10 -0800288 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700289 .keymint
290 .get_interface()
291 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700292
Janis Danisevskisaec14592020-11-12 09:41:49 -0800293 let (begin_result, upgraded_blob) = self
294 .upgrade_keyblob_if_required_with(
295 &*km_dev,
296 key_id_guard,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000297 &(&km_blob, &blob_metadata),
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700298 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800299 |blob| loop {
300 match map_km_error(km_dev.begin(
301 purpose,
302 blob,
303 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800304 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800305 )) {
306 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
307 self.operation_db.prune(caller_uid)?;
308 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700309 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800310 v => return v,
311 }
312 },
313 )
314 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700315
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800316 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000317
Janis Danisevskis1af91262020-08-10 14:58:08 -0700318 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000319 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800320 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000321 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700322 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 -0700323 };
324
Stephen Crane221bbb52020-12-16 15:52:10 -0800325 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700326 KeystoreOperation::new_native_binder(operation)
327 .as_binder()
328 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700329 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700330
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700331 Ok(CreateOperationResponse {
332 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000333 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700334 parameters: match begin_result.params.len() {
335 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700336 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700337 },
338 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700339 }
340
Janis Danisevskise766edc2021-02-06 12:16:26 -0800341 fn add_certificate_parameters(
342 uid: u32,
343 params: &[KeyParameter],
344 key: &KeyDescriptor,
345 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800346 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800347 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800348 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
349 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800350 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800351 })?;
352 result.push(KeyParameter {
353 tag: Tag::ATTESTATION_APPLICATION_ID,
354 value: KeyParameterValue::Blob(aaid),
355 });
356 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800357
Janis Danisevskise766edc2021-02-06 12:16:26 -0800358 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
359 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
360 "In add_certificate_parameters: ",
361 "Caller does not have the permission for device unique attestation."
362 ))?;
363 }
364
Bram Bonné5d6c5102021-02-24 15:09:18 +0100365 // If the caller requests any device identifier attestation tag, check that they hold the
366 // correct Android permission.
367 if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
368 check_device_attestation_permissions().context(concat!(
369 "In add_certificate_parameters: ",
370 "Caller does not have the permission to attest device identifiers."
371 ))?;
372 }
373
Janis Danisevskis2c084012021-01-31 22:23:17 -0800374 // If we are generating/importing an asymmetric key, we need to make sure
375 // that NOT_BEFORE and NOT_AFTER are present.
376 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
377 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
378 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
379 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
380 result.push(KeyParameter {
381 tag: Tag::CERTIFICATE_NOT_BEFORE,
382 value: KeyParameterValue::DateTime(0),
383 })
384 }
385 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
386 result.push(KeyParameter {
387 tag: Tag::CERTIFICATE_NOT_AFTER,
388 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
389 })
390 }
391 }
392 _ => {}
393 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800394 Ok(result)
395 }
396
Janis Danisevskis1af91262020-08-10 14:58:08 -0700397 fn generate_key(
398 &self,
399 key: &KeyDescriptor,
Shawn Willden8fde4c22021-02-14 13:58:22 -0700400 attest_key_descriptor: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700401 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700402 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700403 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700404 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700405 if key.domain != Domain::BLOB && key.alias.is_none() {
406 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
407 .context("In generate_key: Alias must be specified");
408 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000409 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700410
411 let key = match key.domain {
412 Domain::APP => KeyDescriptor {
413 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000414 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700415 alias: key.alias.clone(),
416 blob: None,
417 },
418 _ => key.clone(),
419 };
420
421 // generate_key requires the rebind permission.
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700422 // Must return on error for security reasons.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700423 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700424
425 let attestation_key_info = match (key.domain, attest_key_descriptor) {
426 (Domain::BLOB, _) => None,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800427 _ => DB
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700428 .with(|db| {
429 get_attest_key_info(
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800430 &key,
431 caller_uid,
432 attest_key_descriptor,
433 params,
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700434 &self.rem_prov_state,
Satya Tangiralafdb9c762021-03-09 22:34:22 -0800435 &mut db.borrow_mut(),
436 )
437 })
438 .context("In generate_key: Trying to get an attestation key")?,
439 };
Janis Danisevskise766edc2021-02-06 12:16:26 -0800440 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800441 .context("In generate_key: Trying to get aaid.")?;
442
Stephen Crane221bbb52020-12-16 15:52:10 -0800443 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700444
445 let creation_result = match attestation_key_info {
446 Some(AttestationKeyInfo::UserGenerated {
447 key_id_guard,
448 blob,
449 blob_metadata,
450 issuer_subject,
451 }) => self
452 .upgrade_keyblob_if_required_with(
453 &*km_dev,
454 Some(key_id_guard),
455 &(&KeyBlob::Ref(&blob), &blob_metadata),
456 &params,
457 |blob| {
458 let attest_key = Some(AttestationKey {
459 keyBlob: blob.to_vec(),
460 attestKeyParams: vec![],
461 issuerSubjectName: issuer_subject.clone(),
462 });
463 map_km_error(km_dev.generateKey(&params, attest_key.as_ref()))
464 },
465 )
466 .context("In generate_key: Using user generated attestation key.")
467 .map(|(result, _)| result),
468 Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
469 map_km_error(km_dev.generateKey(&params, Some(&attestation_key)))
470 .context("While generating Key with remote provisioned attestation key.")
471 .map(|mut creation_result| {
472 creation_result.certificateChain.push(attestation_certs);
473 creation_result
474 })
475 }
476 None => map_km_error(km_dev.generateKey(&params, None))
477 .context("While generating Key without explicit attestation key."),
Max Bires97f96812021-02-23 23:44:57 -0800478 }
Janis Danisevskis3541f3e2021-03-20 14:18:52 -0700479 .context("In generate_key.")?;
480
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000481 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000482 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700483 }
484
485 fn import_key(
486 &self,
487 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700488 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700489 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700490 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700491 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700492 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700493 if key.domain != Domain::BLOB && key.alias.is_none() {
494 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
495 .context("In import_key: Alias must be specified");
496 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000497 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700498
499 let key = match key.domain {
500 Domain::APP => KeyDescriptor {
501 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000502 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700503 alias: key.alias.clone(),
504 blob: None,
505 },
506 _ => key.clone(),
507 };
508
509 // import_key requires the rebind permission.
510 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
511
Janis Danisevskise766edc2021-02-06 12:16:26 -0800512 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800513 .context("In import_key: Trying to get aaid.")?;
514
Janis Danisevskis1af91262020-08-10 14:58:08 -0700515 let format = params
516 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700517 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700518 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
519 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800520 .and_then(|p| match &p.value {
521 KeyParameterValue::Algorithm(Algorithm::AES)
522 | KeyParameterValue::Algorithm(Algorithm::HMAC)
523 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
524 KeyParameterValue::Algorithm(Algorithm::RSA)
525 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
526 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
527 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700528 })
529 .context("In import_key.")?;
530
Stephen Crane221bbb52020-12-16 15:52:10 -0800531 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800532 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
Shawn Willdenc2f3acf2021-02-03 07:07:17 -0700533 let creation_result =
534 map_km_error(km_dev.importKey(&params, format, key_data, None /* attestKey */))
535 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700536
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000537 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000538 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700539 }
540
541 fn import_wrapped_key(
542 &self,
543 key: &KeyDescriptor,
544 wrapping_key: &KeyDescriptor,
545 masking_key: Option<&[u8]>,
546 params: &[KeyParameter],
547 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700548 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800549 let wrapped_data: &[u8] = match key {
550 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
551 | KeyDescriptor {
552 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
553 } => blob,
554 _ => {
555 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
556 concat!(
557 "In import_wrapped_key: Alias and blob must be specified ",
558 "and domain must be APP or SELINUX. {:?}"
559 ),
560 key
561 ))
562 }
563 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700564
Janis Danisevskisaec14592020-11-12 09:41:49 -0800565 if wrapping_key.domain == Domain::BLOB {
566 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
567 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
568 );
569 }
570
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000571 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000572 let user_id = uid_to_android_user(caller_uid);
573
Janis Danisevskis1af91262020-08-10 14:58:08 -0700574 let key = match key.domain {
575 Domain::APP => KeyDescriptor {
576 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000577 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700578 alias: key.alias.clone(),
579 blob: None,
580 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800581 Domain::SELINUX => KeyDescriptor {
582 domain: Domain::SELINUX,
583 nspace: key.nspace,
584 alias: key.alias.clone(),
585 blob: None,
586 },
587 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700588 };
589
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800590 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700591 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
592
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000593 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700594 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000595 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
596 db.borrow_mut().load_key_entry(
597 &wrapping_key,
598 KeyType::Client,
599 KeyEntryLoadBits::KM,
600 caller_uid,
601 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
602 )
603 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700604 })
605 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000606
607 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
608 .take_key_blob_info()
609 .ok_or_else(error::Error::sys)
610 .context("No km_blob after successfully loading key. This should never happen.")?;
611
612 let wrapping_key_blob =
613 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
614 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
615 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700616
Janis Danisevskis1af91262020-08-10 14:58:08 -0700617 // km_dev.importWrappedKey does not return a certificate chain.
618 // TODO Do we assume that all wrapped keys are symmetric?
619 // let certificate_chain: Vec<KmCertificate> = Default::default();
620
621 let pw_sid = authenticators
622 .iter()
623 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700624 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700625 _ => None,
626 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800627 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700628
629 let fp_sid = authenticators
630 .iter()
631 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700632 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700633 _ => None,
634 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800635 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700636
637 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
638
Stephen Crane221bbb52020-12-16 15:52:10 -0800639 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800640 let (creation_result, _) = self
641 .upgrade_keyblob_if_required_with(
642 &*km_dev,
643 Some(wrapping_key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000644 &(&wrapping_key_blob, &wrapping_blob_metadata),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800645 &[],
646 |wrapping_blob| {
647 let creation_result = map_km_error(km_dev.importWrappedKey(
648 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800649 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800650 masking_key,
651 &params,
652 pw_sid,
653 fp_sid,
654 ))?;
655 Ok(creation_result)
656 },
657 )
658 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700659
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000660 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800661 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700662 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800663
664 fn upgrade_keyblob_if_required_with<T, F>(
665 &self,
666 km_dev: &dyn IKeyMintDevice,
667 key_id_guard: Option<KeyIdGuard>,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000668 blob_info: &(&KeyBlob, &BlobMetaData),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800669 params: &[KeyParameter],
670 f: F,
671 ) -> Result<(T, Option<Vec<u8>>)>
672 where
673 F: Fn(&[u8]) -> Result<T, Error>,
674 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800675 match f(blob_info.0) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800676 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800677 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob_info.0, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800678 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000679
680 let (upgraded_blob_to_be_stored, blob_metadata) =
681 SuperKeyManager::reencrypt_on_upgrade_if_required(blob_info.0, &upgraded_blob)
682 .context(
683 "In upgrade_keyblob_if_required_with: Failed to handle super encryption.",
684 )?;
685
686 let mut blob_metadata = blob_metadata.unwrap_or_else(BlobMetaData::new);
687 if let Some(uuid) = blob_info.1.km_uuid() {
688 blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
689 }
690
Janis Danisevskisaec14592020-11-12 09:41:49 -0800691 key_id_guard.map_or(Ok(()), |key_id_guard| {
692 DB.with(|db| {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000693 let mut db = db.borrow_mut();
694 db.set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800695 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800696 SubComponentType::KEY_BLOB,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000697 Some(&upgraded_blob_to_be_stored),
698 Some(&blob_metadata),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800699 )
700 })
701 .context(concat!(
702 "In upgrade_keyblob_if_required_with: ",
703 "Failed to insert upgraded blob into the database.",
704 ))
705 })?;
706 match f(&upgraded_blob) {
707 Ok(v) => Ok((v, Some(upgraded_blob))),
708 Err(e) => Err(e).context(concat!(
709 "In upgrade_keyblob_if_required_with: ",
710 "Failed to perform operation on second try."
711 )),
712 }
713 }
714 Err(e) => {
715 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
716 }
717 Ok(v) => Ok((v, None)),
718 }
719 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700720}
721
722impl binder::Interface for KeystoreSecurityLevel {}
723
724impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700725 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700726 &self,
727 key: &KeyDescriptor,
728 operation_parameters: &[KeyParameter],
729 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700730 ) -> binder::public_api::Result<CreateOperationResponse> {
731 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700732 }
733 fn generateKey(
734 &self,
735 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700736 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700737 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700738 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700739 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700740 ) -> binder::public_api::Result<KeyMetadata> {
741 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700742 }
743 fn importKey(
744 &self,
745 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700746 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700747 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700748 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700749 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700750 ) -> binder::public_api::Result<KeyMetadata> {
751 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700752 }
753 fn importWrappedKey(
754 &self,
755 key: &KeyDescriptor,
756 wrapping_key: &KeyDescriptor,
757 masking_key: Option<&[u8]>,
758 params: &[KeyParameter],
759 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700760 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700761 map_or_log_err(
762 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700763 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700764 )
765 }
766}