blob: 23a3c35b70e6f03ee76b590df1833feda6e87f7b [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 Danisevskis5ed8c532021-01-11 14:19:42 -080021 Algorithm::Algorithm, HardwareAuthenticatorType::HardwareAuthenticatorType,
22 IKeyMintDevice::IKeyMintDevice, KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
Max Bires8e93d2b2021-01-14 13:17:59 -080023 KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
24 KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
Janis Danisevskis1af91262020-08-10 14:58:08 -070025};
26use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -070027 AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
28 Domain::Domain, IKeystoreOperation::IKeystoreOperation,
29 IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
Janis Danisevskis1af91262020-08-10 14:58:08 -070030 IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080031 KeyMetadata::KeyMetadata, KeyParameters::KeyParameters,
Janis Danisevskis1af91262020-08-10 14:58:08 -070032};
33
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000034use crate::database::{CertificateInfo, KeyIdGuard};
35use crate::globals::{DB, ENFORCEMENTS, SUPER_KEY};
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000036use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000037use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000038use crate::super_key::{KeyBlob, SuperKeyManager};
Qi Wub9433b52020-12-01 14:52:46 +080039use crate::utils::{check_key_permission, uid_to_android_user, Asp};
Max Bires8e93d2b2021-01-14 13:17:59 -080040use crate::{
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080041 database::{
42 BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
43 KeyMetaEntry, KeyType, SubComponentType, Uuid,
44 },
45 operation::KeystoreOperation,
46 operation::OperationDb,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080047 permission::KeyPerm,
48};
49use crate::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070050 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
51 utils::key_characteristics_to_internal,
52};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080053use anyhow::{anyhow, Context, Result};
Stephen Crane221bbb52020-12-16 15:52:10 -080054use binder::{IBinder, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070055
56/// Implementation of the IKeystoreSecurityLevel Interface.
57pub struct KeystoreSecurityLevel {
58 security_level: SecurityLevel,
59 keymint: Asp,
Max Bires8e93d2b2021-01-14 13:17:59 -080060 #[allow(dead_code)]
61 hw_info: KeyMintHardwareInfo,
62 km_uuid: Uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070063 operation_db: OperationDb,
64}
65
Janis Danisevskis1af91262020-08-10 14:58:08 -070066// Blob of 32 zeroes used as empty masking key.
67static ZERO_BLOB_32: &[u8] = &[0; 32];
68
Janis Danisevskis2c084012021-01-31 22:23:17 -080069// Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
70// 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
71const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
72
Janis Danisevskis1af91262020-08-10 14:58:08 -070073impl KeystoreSecurityLevel {
74 /// Creates a new security level instance wrapped in a
75 /// BnKeystoreSecurityLevel proxy object. It also
76 /// calls `IBinder::set_requesting_sid` on the new interface, because
77 /// we need it for checking keystore permissions.
78 pub fn new_native_binder(
79 security_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -080080 ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
Max Bires8e93d2b2021-01-14 13:17:59 -080081 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
82 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070083 let result = BnKeystoreSecurityLevel::new_binder(Self {
84 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080085 keymint: dev,
86 hw_info,
87 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070088 operation_db: OperationDb::new(),
89 });
90 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -080091 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -070092 }
93
94 fn store_new_key(
95 &self,
96 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -070097 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +000098 user_id: u32,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000099 flags: Option<i32>,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700100 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -0700101 let KeyCreationResult {
102 keyBlob: key_blob,
103 keyCharacteristics: key_characteristics,
104 certificateChain: mut certificate_chain,
105 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700106
Max Bires8e93d2b2021-01-14 13:17:59 -0800107 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700108 match certificate_chain.len() {
109 0 => None,
110 _ => Some(certificate_chain.remove(0).encodedCertificate),
111 },
112 match certificate_chain.len() {
113 0 => None,
114 _ => Some(
115 certificate_chain
116 .iter()
117 .map(|c| c.encodedCertificate.iter())
118 .flatten()
119 .copied()
120 .collect(),
121 ),
122 },
123 );
124
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000125 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
126
127 key_parameters.push(KsKeyParam::new(
128 KsKeyParamValue::UserID(user_id as i32),
129 SecurityLevel::SOFTWARE,
130 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700131
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000132 let (key_blob, mut blob_metadata) = DB
133 .with(|db| {
134 SuperKeyManager::handle_super_encryption_on_key_init(
135 &mut db.borrow_mut(),
136 &SUPER_KEY,
137 &(key.domain),
138 &key_parameters,
139 flags,
140 user_id,
141 &key_blob,
142 )
143 })
144 .context("In store_new_key. Failed to handle super encryption.")?;
145
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800146 let creation_date = DateTime::now().context("Trying to make creation time.")?;
147
Janis Danisevskis1af91262020-08-10 14:58:08 -0700148 let key = match key.domain {
149 Domain::BLOB => {
Shawn Willdendbdac602021-01-12 22:35:16 -0700150 KeyDescriptor { domain: Domain::BLOB, blob: Some(key_blob), ..Default::default() }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700151 }
152 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800153 .with::<_, Result<KeyDescriptor>>(|db| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800154 let mut key_metadata = KeyMetaData::new();
155 key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800156 blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800157
158 let mut db = db.borrow_mut();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800159 let key_id = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800160 .store_new_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800161 &key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800162 &key_parameters,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800163 &(&key_blob, &blob_metadata),
Max Bires8e93d2b2021-01-14 13:17:59 -0800164 &cert_info,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800165 &key_metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800166 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800167 )
168 .context("In store_new_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700169 Ok(KeyDescriptor {
170 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800171 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700172 ..Default::default()
173 })
174 })
175 .context("In store_new_key.")?,
176 };
177
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700178 Ok(KeyMetadata {
179 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700180 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800181 certificate: cert_info.take_cert(),
182 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700183 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800184 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700185 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700186 }
187
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700188 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700189 &self,
190 key: &KeyDescriptor,
191 operation_parameters: &[KeyParameter],
192 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700193 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700194 let caller_uid = ThreadState::get_calling_uid();
195 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
196 // so that we can use it by reference like the blob provided by the key descriptor.
197 // Otherwise, we would have to clone the blob from the key descriptor.
198 let scoping_blob: Vec<u8>;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800199 let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700200 Domain::BLOB => {
201 check_key_permission(KeyPerm::use_(), key, &None)
202 .context("In create_operation: checking use permission for Domain::BLOB.")?;
203 (
204 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700205 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700206 None => {
207 return Err(Error::sys()).context(concat!(
208 "In create_operation: Key blob must be specified when",
209 " using Domain::BLOB."
210 ))
211 }
212 },
213 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000214 None,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000215 BlobMetaData::new(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700216 )
217 }
218 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800219 let (key_id_guard, mut key_entry) = DB
220 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700221 db.borrow_mut().load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800222 &key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800223 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700224 KeyEntryLoadBits::KM,
225 caller_uid,
226 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
227 )
228 })
229 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800230
231 let (blob, blob_metadata) =
232 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
233 "In create_operation: Successfully loaded key entry, ",
234 "but KM blob was missing."
235 ))?;
236 scoping_blob = blob;
237
Qi Wub9433b52020-12-01 14:52:46 +0800238 (
239 &scoping_blob,
240 Some((key_id_guard.id(), key_entry.into_key_parameters())),
241 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000242 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800243 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700244 }
245 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700246
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700247 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700248 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700249 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800250 |kp| match kp.value {
251 KeyParameterValue::KeyPurpose(p) => Ok(p),
252 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
253 .context("In create_operation: Malformed KeyParameter."),
254 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700255 )?;
256
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800257 let (immediate_hat, mut auth_info) = ENFORCEMENTS
258 .authorize_create(
259 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800260 key_properties.as_ref(),
261 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800262 // TODO b/178222844 Replace this with the configuration returned by
263 // KeyMintDevice::getHardwareInfo.
264 // For now we assume that strongbox implementations need secure timestamps.
265 self.security_level == SecurityLevel::STRONGBOX,
266 )
267 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000268
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800269 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000270
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000271 let user_id = uid_to_android_user(caller_uid);
272
273 let km_blob = SUPER_KEY
274 .unwrap_key_if_required(&blob_metadata, km_blob)
275 .context("In create_operation. Failed to handle super encryption.")?;
276
Stephen Crane221bbb52020-12-16 15:52:10 -0800277 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700278 .keymint
279 .get_interface()
280 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700281
Janis Danisevskisaec14592020-11-12 09:41:49 -0800282 let (begin_result, upgraded_blob) = self
283 .upgrade_keyblob_if_required_with(
284 &*km_dev,
285 key_id_guard,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000286 &(&km_blob, &blob_metadata),
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700287 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800288 |blob| loop {
289 match map_km_error(km_dev.begin(
290 purpose,
291 blob,
292 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800293 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800294 )) {
295 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
296 self.operation_db.prune(caller_uid)?;
297 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700298 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800299 v => return v,
300 }
301 },
302 )
303 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700304
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800305 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000306
Janis Danisevskis1af91262020-08-10 14:58:08 -0700307 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000308 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800309 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000310 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700311 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 -0700312 };
313
Stephen Crane221bbb52020-12-16 15:52:10 -0800314 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700315 KeystoreOperation::new_native_binder(operation)
316 .as_binder()
317 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700318 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700319
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700320 Ok(CreateOperationResponse {
321 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000322 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700323 parameters: match begin_result.params.len() {
324 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700325 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700326 },
327 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328 }
329
Janis Danisevskise766edc2021-02-06 12:16:26 -0800330 fn add_certificate_parameters(
331 uid: u32,
332 params: &[KeyParameter],
333 key: &KeyDescriptor,
334 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800335 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800336 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800337 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
338 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800339 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800340 })?;
341 result.push(KeyParameter {
342 tag: Tag::ATTESTATION_APPLICATION_ID,
343 value: KeyParameterValue::Blob(aaid),
344 });
345 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800346
Janis Danisevskise766edc2021-02-06 12:16:26 -0800347 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
348 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
349 "In add_certificate_parameters: ",
350 "Caller does not have the permission for device unique attestation."
351 ))?;
352 }
353
Janis Danisevskis2c084012021-01-31 22:23:17 -0800354 // If we are generating/importing an asymmetric key, we need to make sure
355 // that NOT_BEFORE and NOT_AFTER are present.
356 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
357 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
358 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
359 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
360 result.push(KeyParameter {
361 tag: Tag::CERTIFICATE_NOT_BEFORE,
362 value: KeyParameterValue::DateTime(0),
363 })
364 }
365 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
366 result.push(KeyParameter {
367 tag: Tag::CERTIFICATE_NOT_AFTER,
368 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
369 })
370 }
371 }
372 _ => {}
373 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800374 Ok(result)
375 }
376
Janis Danisevskis1af91262020-08-10 14:58:08 -0700377 fn generate_key(
378 &self,
379 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700380 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700381 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700382 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700383 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700384 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700385 if key.domain != Domain::BLOB && key.alias.is_none() {
386 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
387 .context("In generate_key: Alias must be specified");
388 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000389 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700390
391 let key = match key.domain {
392 Domain::APP => KeyDescriptor {
393 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000394 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700395 alias: key.alias.clone(),
396 blob: None,
397 },
398 _ => key.clone(),
399 };
400
401 // generate_key requires the rebind permission.
402 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
403
Janis Danisevskise766edc2021-02-06 12:16:26 -0800404 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800405 .context("In generate_key: Trying to get aaid.")?;
406
Stephen Crane221bbb52020-12-16 15:52:10 -0800407 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800408 map_km_error(km_dev.addRngEntropy(entropy))
409 .context("In generate_key: Trying to add entropy.")?;
410 let creation_result = map_km_error(km_dev.generateKey(&params))
411 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700412
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000413 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000414 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700415 }
416
417 fn import_key(
418 &self,
419 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700420 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700421 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700422 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700423 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700424 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700425 if key.domain != Domain::BLOB && key.alias.is_none() {
426 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
427 .context("In import_key: Alias must be specified");
428 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000429 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700430
431 let key = match key.domain {
432 Domain::APP => KeyDescriptor {
433 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000434 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700435 alias: key.alias.clone(),
436 blob: None,
437 },
438 _ => key.clone(),
439 };
440
441 // import_key requires the rebind permission.
442 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
443
Janis Danisevskise766edc2021-02-06 12:16:26 -0800444 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800445 .context("In import_key: Trying to get aaid.")?;
446
Janis Danisevskis1af91262020-08-10 14:58:08 -0700447 let format = params
448 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700449 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700450 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
451 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800452 .and_then(|p| match &p.value {
453 KeyParameterValue::Algorithm(Algorithm::AES)
454 | KeyParameterValue::Algorithm(Algorithm::HMAC)
455 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
456 KeyParameterValue::Algorithm(Algorithm::RSA)
457 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
458 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
459 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700460 })
461 .context("In import_key.")?;
462
Stephen Crane221bbb52020-12-16 15:52:10 -0800463 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800464 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
465 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))
466 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700467
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000468 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000469 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700470 }
471
472 fn import_wrapped_key(
473 &self,
474 key: &KeyDescriptor,
475 wrapping_key: &KeyDescriptor,
476 masking_key: Option<&[u8]>,
477 params: &[KeyParameter],
478 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700479 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800480 let wrapped_data: &[u8] = match key {
481 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
482 | KeyDescriptor {
483 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
484 } => blob,
485 _ => {
486 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
487 concat!(
488 "In import_wrapped_key: Alias and blob must be specified ",
489 "and domain must be APP or SELINUX. {:?}"
490 ),
491 key
492 ))
493 }
494 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700495
Janis Danisevskisaec14592020-11-12 09:41:49 -0800496 if wrapping_key.domain == Domain::BLOB {
497 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
498 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
499 );
500 }
501
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000502 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000503 let user_id = uid_to_android_user(caller_uid);
504
Janis Danisevskis1af91262020-08-10 14:58:08 -0700505 let key = match key.domain {
506 Domain::APP => KeyDescriptor {
507 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000508 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700509 alias: key.alias.clone(),
510 blob: None,
511 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800512 Domain::SELINUX => KeyDescriptor {
513 domain: Domain::SELINUX,
514 nspace: key.nspace,
515 alias: key.alias.clone(),
516 blob: None,
517 },
518 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700519 };
520
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800521 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700522 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
523
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000524 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700525 .with(|db| {
526 db.borrow_mut().load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -0800527 &wrapping_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800528 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700529 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000530 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700531 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
532 )
533 })
534 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000535
536 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
537 .take_key_blob_info()
538 .ok_or_else(error::Error::sys)
539 .context("No km_blob after successfully loading key. This should never happen.")?;
540
541 let wrapping_key_blob =
542 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
543 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
544 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700545
Janis Danisevskis1af91262020-08-10 14:58:08 -0700546 // km_dev.importWrappedKey does not return a certificate chain.
547 // TODO Do we assume that all wrapped keys are symmetric?
548 // let certificate_chain: Vec<KmCertificate> = Default::default();
549
550 let pw_sid = authenticators
551 .iter()
552 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700553 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700554 _ => None,
555 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800556 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700557
558 let fp_sid = authenticators
559 .iter()
560 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700561 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700562 _ => None,
563 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800564 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700565
566 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
567
Stephen Crane221bbb52020-12-16 15:52:10 -0800568 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800569 let (creation_result, _) = self
570 .upgrade_keyblob_if_required_with(
571 &*km_dev,
572 Some(wrapping_key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000573 &(&wrapping_key_blob, &wrapping_blob_metadata),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800574 &[],
575 |wrapping_blob| {
576 let creation_result = map_km_error(km_dev.importWrappedKey(
577 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800578 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800579 masking_key,
580 &params,
581 pw_sid,
582 fp_sid,
583 ))?;
584 Ok(creation_result)
585 },
586 )
587 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700588
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000589 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800590 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700591 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800592
593 fn upgrade_keyblob_if_required_with<T, F>(
594 &self,
595 km_dev: &dyn IKeyMintDevice,
596 key_id_guard: Option<KeyIdGuard>,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000597 blob_info: &(&KeyBlob, &BlobMetaData),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800598 params: &[KeyParameter],
599 f: F,
600 ) -> Result<(T, Option<Vec<u8>>)>
601 where
602 F: Fn(&[u8]) -> Result<T, Error>,
603 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800604 match f(blob_info.0) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800605 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800606 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob_info.0, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800607 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000608
609 let (upgraded_blob_to_be_stored, blob_metadata) =
610 SuperKeyManager::reencrypt_on_upgrade_if_required(blob_info.0, &upgraded_blob)
611 .context(
612 "In upgrade_keyblob_if_required_with: Failed to handle super encryption.",
613 )?;
614
615 let mut blob_metadata = blob_metadata.unwrap_or_else(BlobMetaData::new);
616 if let Some(uuid) = blob_info.1.km_uuid() {
617 blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
618 }
619
Janis Danisevskisaec14592020-11-12 09:41:49 -0800620 key_id_guard.map_or(Ok(()), |key_id_guard| {
621 DB.with(|db| {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000622 let mut db = db.borrow_mut();
623 db.set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800624 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800625 SubComponentType::KEY_BLOB,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000626 Some(&upgraded_blob_to_be_stored),
627 Some(&blob_metadata),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800628 )
629 })
630 .context(concat!(
631 "In upgrade_keyblob_if_required_with: ",
632 "Failed to insert upgraded blob into the database.",
633 ))
634 })?;
635 match f(&upgraded_blob) {
636 Ok(v) => Ok((v, Some(upgraded_blob))),
637 Err(e) => Err(e).context(concat!(
638 "In upgrade_keyblob_if_required_with: ",
639 "Failed to perform operation on second try."
640 )),
641 }
642 }
643 Err(e) => {
644 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
645 }
646 Ok(v) => Ok((v, None)),
647 }
648 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700649}
650
651impl binder::Interface for KeystoreSecurityLevel {}
652
653impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700654 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700655 &self,
656 key: &KeyDescriptor,
657 operation_parameters: &[KeyParameter],
658 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700659 ) -> binder::public_api::Result<CreateOperationResponse> {
660 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700661 }
662 fn generateKey(
663 &self,
664 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700665 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700666 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700667 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700668 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700669 ) -> binder::public_api::Result<KeyMetadata> {
670 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700671 }
672 fn importKey(
673 &self,
674 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700675 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700676 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700677 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700678 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700679 ) -> binder::public_api::Result<KeyMetadata> {
680 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700681 }
682 fn importWrappedKey(
683 &self,
684 key: &KeyDescriptor,
685 wrapping_key: &KeyDescriptor,
686 masking_key: Option<&[u8]>,
687 params: &[KeyParameter],
688 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700689 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700690 map_or_log_err(
691 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700692 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700693 )
694 }
695}