blob: f6d8108617a2fdbf3dd36af64b82c1fd71033558 [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
Max Bires8e93d2b2021-01-14 13:17:59 -080019use crate::{database::Uuid, gc::Gc, 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 Gunasinghe888dd352020-11-17 23:08:39 +000034use crate::globals::ENFORCEMENTS;
35use crate::key_parameter::KeyParameter as KsKeyParam;
Hasini Gunasinghea020b532021-01-07 21:42:35 +000036use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
Qi Wub9433b52020-12-01 14:52:46 +080037use crate::utils::{check_key_permission, uid_to_android_user, Asp};
Max Bires8e93d2b2021-01-14 13:17:59 -080038use crate::{
39 database::{CertificateInfo, KeyIdGuard},
40 globals::DB,
41};
Janis Danisevskis1af91262020-08-10 14:58:08 -070042use crate::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080043 database::{DateTime, KeyMetaData, KeyMetaEntry, KeyType},
44 permission::KeyPerm,
45};
46use crate::{
Janis Danisevskis1af91262020-08-10 14:58:08 -070047 database::{KeyEntry, KeyEntryLoadBits, SubComponentType},
48 operation::KeystoreOperation,
49 operation::OperationDb,
50};
Janis Danisevskis04b02832020-10-26 09:21:40 -070051use crate::{
52 error::{self, map_km_error, map_or_log_err, Error, ErrorCode},
53 utils::key_characteristics_to_internal,
54};
Janis Danisevskis212c68b2021-01-14 22:29:28 -080055use anyhow::{anyhow, Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -070056use binder::{IBinder, Interface, ThreadState};
57
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
71impl KeystoreSecurityLevel {
72 /// Creates a new security level instance wrapped in a
73 /// BnKeystoreSecurityLevel proxy object. It also
74 /// calls `IBinder::set_requesting_sid` on the new interface, because
75 /// we need it for checking keystore permissions.
76 pub fn new_native_binder(
77 security_level: SecurityLevel,
Max Bires8e93d2b2021-01-14 13:17:59 -080078 ) -> Result<(impl IKeystoreSecurityLevel + Send, Uuid)> {
79 let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
80 .context("In KeystoreSecurityLevel::new_native_binder.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -070081 let result = BnKeystoreSecurityLevel::new_binder(Self {
82 security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -080083 keymint: dev,
84 hw_info,
85 km_uuid,
Janis Danisevskis1af91262020-08-10 14:58:08 -070086 operation_db: OperationDb::new(),
87 });
88 result.as_binder().set_requesting_sid(true);
Max Bires8e93d2b2021-01-14 13:17:59 -080089 Ok((result, km_uuid))
Janis Danisevskis1af91262020-08-10 14:58:08 -070090 }
91
92 fn store_new_key(
93 &self,
94 key: KeyDescriptor,
Shawn Willdendbdac602021-01-12 22:35:16 -070095 creation_result: KeyCreationResult,
Hasini Gunasinghea020b532021-01-07 21:42:35 +000096 user_id: u32,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070097 ) -> Result<KeyMetadata> {
Shawn Willdendbdac602021-01-12 22:35:16 -070098 let KeyCreationResult {
99 keyBlob: key_blob,
100 keyCharacteristics: key_characteristics,
101 certificateChain: mut certificate_chain,
102 } = creation_result;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700103
Max Bires8e93d2b2021-01-14 13:17:59 -0800104 let mut cert_info: CertificateInfo = CertificateInfo::new(
Shawn Willdendbdac602021-01-12 22:35:16 -0700105 match certificate_chain.len() {
106 0 => None,
107 _ => Some(certificate_chain.remove(0).encodedCertificate),
108 },
109 match certificate_chain.len() {
110 0 => None,
111 _ => Some(
112 certificate_chain
113 .iter()
114 .map(|c| c.encodedCertificate.iter())
115 .flatten()
116 .copied()
117 .collect(),
118 ),
119 },
120 );
121
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000122 let mut key_parameters = key_characteristics_to_internal(key_characteristics);
123
124 key_parameters.push(KsKeyParam::new(
125 KsKeyParamValue::UserID(user_id as i32),
126 SecurityLevel::SOFTWARE,
127 ));
Janis Danisevskis04b02832020-10-26 09:21:40 -0700128
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800129 let creation_date = DateTime::now().context("Trying to make creation time.")?;
130
Janis Danisevskis1af91262020-08-10 14:58:08 -0700131 let key = match key.domain {
132 Domain::BLOB => {
Shawn Willdendbdac602021-01-12 22:35:16 -0700133 KeyDescriptor { domain: Domain::BLOB, blob: Some(key_blob), ..Default::default() }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700134 }
135 _ => DB
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800136 .with::<_, Result<KeyDescriptor>>(|db| {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800137 let mut metadata = KeyMetaData::new();
138 metadata.add(KeyMetaEntry::CreationDate(creation_date));
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800139
140 let mut db = db.borrow_mut();
Janis Danisevskis4507f3b2021-01-13 16:34:39 -0800141 let (need_gc, key_id) = db
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800142 .store_new_key(
143 key,
144 &key_parameters,
Shawn Willdendbdac602021-01-12 22:35:16 -0700145 &key_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -0800146 &cert_info,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800147 &metadata,
Max Bires8e93d2b2021-01-14 13:17:59 -0800148 &self.km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800149 )
150 .context("In store_new_key.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -0800151 if need_gc {
152 Gc::notify_gc();
153 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700154 Ok(KeyDescriptor {
155 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800156 nspace: key_id.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700157 ..Default::default()
158 })
159 })
160 .context("In store_new_key.")?,
161 };
162
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700163 Ok(KeyMetadata {
164 key,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700165 keySecurityLevel: self.security_level,
Max Bires8e93d2b2021-01-14 13:17:59 -0800166 certificate: cert_info.take_cert(),
167 certificateChain: cert_info.take_cert_chain(),
Janis Danisevskis04b02832020-10-26 09:21:40 -0700168 authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800169 modificationTimeMs: creation_date.to_millis_epoch(),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700170 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700171 }
172
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700173 fn create_operation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700174 &self,
175 key: &KeyDescriptor,
176 operation_parameters: &[KeyParameter],
177 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700178 ) -> Result<CreateOperationResponse> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700179 let caller_uid = ThreadState::get_calling_uid();
180 // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
181 // so that we can use it by reference like the blob provided by the key descriptor.
182 // Otherwise, we would have to clone the blob from the key descriptor.
183 let scoping_blob: Vec<u8>;
Qi Wub9433b52020-12-01 14:52:46 +0800184 let (km_blob, key_properties, key_id_guard) = match key.domain {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700185 Domain::BLOB => {
186 check_key_permission(KeyPerm::use_(), key, &None)
187 .context("In create_operation: checking use permission for Domain::BLOB.")?;
188 (
189 match &key.blob {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700190 Some(blob) => blob,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700191 None => {
192 return Err(Error::sys()).context(concat!(
193 "In create_operation: Key blob must be specified when",
194 " using Domain::BLOB."
195 ))
196 }
197 },
198 None,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000199 None,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700200 )
201 }
202 _ => {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800203 let (key_id_guard, mut key_entry) = DB
204 .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700205 db.borrow_mut().load_key_entry(
206 key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800207 KeyType::Client,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700208 KeyEntryLoadBits::KM,
209 caller_uid,
210 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
211 )
212 })
213 .context("In create_operation: Failed to load key blob.")?;
214 scoping_blob = match key_entry.take_km_blob() {
215 Some(blob) => blob,
216 None => {
217 return Err(Error::sys()).context(concat!(
218 "In create_operation: Successfully loaded key entry,",
219 " but KM blob was missing."
220 ))
221 }
222 };
Qi Wub9433b52020-12-01 14:52:46 +0800223 (
224 &scoping_blob,
225 Some((key_id_guard.id(), key_entry.into_key_parameters())),
226 Some(key_id_guard),
227 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700228 }
229 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700230
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700231 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700232 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700233 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800234 |kp| match kp.value {
235 KeyParameterValue::KeyPurpose(p) => Ok(p),
236 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
237 .context("In create_operation: Malformed KeyParameter."),
238 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700239 )?;
240
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800241 let (immediate_hat, mut auth_info) = ENFORCEMENTS
242 .authorize_create(
243 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800244 key_properties.as_ref(),
245 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800246 // TODO b/178222844 Replace this with the configuration returned by
247 // KeyMintDevice::getHardwareInfo.
248 // For now we assume that strongbox implementations need secure timestamps.
249 self.security_level == SecurityLevel::STRONGBOX,
250 )
251 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000252
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800253 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000254
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700255 let km_dev: Box<dyn IKeyMintDevice> = self
256 .keymint
257 .get_interface()
258 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700259
Janis Danisevskisaec14592020-11-12 09:41:49 -0800260 let (begin_result, upgraded_blob) = self
261 .upgrade_keyblob_if_required_with(
262 &*km_dev,
263 key_id_guard,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700264 &km_blob,
265 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800266 |blob| loop {
267 match map_km_error(km_dev.begin(
268 purpose,
269 blob,
270 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800271 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800272 )) {
273 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
274 self.operation_db.prune(caller_uid)?;
275 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700276 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800277 v => return v,
278 }
279 },
280 )
281 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700282
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800283 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000284
Janis Danisevskis1af91262020-08-10 14:58:08 -0700285 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000286 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800287 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000288 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700289 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 -0700290 };
291
292 let op_binder: Box<dyn IKeystoreOperation> =
293 KeystoreOperation::new_native_binder(operation)
294 .as_binder()
295 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700296 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700297
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700298 Ok(CreateOperationResponse {
299 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000300 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700301 parameters: match begin_result.params.len() {
302 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700303 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700304 },
305 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700306 }
307
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800308 fn add_attestation_parameters(uid: u32, params: &[KeyParameter]) -> Result<Vec<KeyParameter>> {
309 let mut result = params.to_vec();
310 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
311 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
312 anyhow!(format!("In add_attestation_parameters: get_aaid returned status {}.", e))
313 })?;
314 result.push(KeyParameter {
315 tag: Tag::ATTESTATION_APPLICATION_ID,
316 value: KeyParameterValue::Blob(aaid),
317 });
318 }
319 Ok(result)
320 }
321
Janis Danisevskis1af91262020-08-10 14:58:08 -0700322 fn generate_key(
323 &self,
324 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700325 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700326 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700327 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700329 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700330 if key.domain != Domain::BLOB && key.alias.is_none() {
331 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
332 .context("In generate_key: Alias must be specified");
333 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000334 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700335
336 let key = match key.domain {
337 Domain::APP => KeyDescriptor {
338 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000339 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700340 alias: key.alias.clone(),
341 blob: None,
342 },
343 _ => key.clone(),
344 };
345
346 // generate_key requires the rebind permission.
347 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
348
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800349 let params = Self::add_attestation_parameters(caller_uid, params)
350 .context("In generate_key: Trying to get aaid.")?;
351
Janis Danisevskis1af91262020-08-10 14:58:08 -0700352 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800353 map_km_error(km_dev.addRngEntropy(entropy))
354 .context("In generate_key: Trying to add entropy.")?;
355 let creation_result = map_km_error(km_dev.generateKey(&params))
356 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700357
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000358 let user_id = uid_to_android_user(caller_uid);
359 self.store_new_key(key, creation_result, user_id).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700360 }
361
362 fn import_key(
363 &self,
364 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700365 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700366 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700367 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700368 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700369 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700370 if key.domain != Domain::BLOB && key.alias.is_none() {
371 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
372 .context("In import_key: Alias must be specified");
373 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000374 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700375
376 let key = match key.domain {
377 Domain::APP => KeyDescriptor {
378 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000379 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700380 alias: key.alias.clone(),
381 blob: None,
382 },
383 _ => key.clone(),
384 };
385
386 // import_key requires the rebind permission.
387 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
388
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800389 let params = Self::add_attestation_parameters(caller_uid, params)
390 .context("In import_key: Trying to get aaid.")?;
391
Janis Danisevskis1af91262020-08-10 14:58:08 -0700392 let format = params
393 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700394 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700395 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
396 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800397 .and_then(|p| match &p.value {
398 KeyParameterValue::Algorithm(Algorithm::AES)
399 | KeyParameterValue::Algorithm(Algorithm::HMAC)
400 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
401 KeyParameterValue::Algorithm(Algorithm::RSA)
402 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
403 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
404 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700405 })
406 .context("In import_key.")?;
407
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800408 let km_dev: Box<dyn IKeyMintDevice> =
409 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
410 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))
411 .context("In import_key: Trying to call importKey")?;
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);
414 self.store_new_key(key, creation_result, user_id).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700415 }
416
417 fn import_wrapped_key(
418 &self,
419 key: &KeyDescriptor,
420 wrapping_key: &KeyDescriptor,
421 masking_key: Option<&[u8]>,
422 params: &[KeyParameter],
423 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700424 ) -> Result<KeyMetadata> {
Janis Danisevskis5d27fbb2021-01-21 16:36:18 -0800425 if !(key.domain == Domain::BLOB && key.alias.is_some()) {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700426 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
427 .context("In import_wrapped_key: Alias must be specified.");
428 }
429
Janis Danisevskisaec14592020-11-12 09:41:49 -0800430 if wrapping_key.domain == Domain::BLOB {
431 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
432 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
433 );
434 }
435
Janis Danisevskis1af91262020-08-10 14:58:08 -0700436 let wrapped_data = match &key.blob {
437 Some(d) => d,
438 None => {
439 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
440 "In import_wrapped_key: Blob must be specified and hold wrapped key data.",
441 )
442 }
443 };
444
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000445 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700446 let key = match key.domain {
447 Domain::APP => KeyDescriptor {
448 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000449 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700450 alias: key.alias.clone(),
451 blob: None,
452 },
453 _ => key.clone(),
454 };
455
456 // import_wrapped_key requires the rebind permission for the new key.
457 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
458
Janis Danisevskisaec14592020-11-12 09:41:49 -0800459 let (wrapping_key_id_guard, wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700460 .with(|db| {
461 db.borrow_mut().load_key_entry(
462 wrapping_key.clone(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800463 KeyType::Client,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700464 KeyEntryLoadBits::KM,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000465 caller_uid,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700466 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
467 )
468 })
469 .context("Failed to load wrapping key.")?;
470 let wrapping_key_blob = match wrapping_key_entry.km_blob() {
471 Some(blob) => blob,
472 None => {
473 return Err(error::Error::sys()).context(concat!(
474 "No km_blob after successfully loading key.",
475 " This should never happen."
476 ))
477 }
478 };
479
Janis Danisevskis1af91262020-08-10 14:58:08 -0700480 // km_dev.importWrappedKey does not return a certificate chain.
481 // TODO Do we assume that all wrapped keys are symmetric?
482 // let certificate_chain: Vec<KmCertificate> = Default::default();
483
484 let pw_sid = authenticators
485 .iter()
486 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700487 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700488 _ => None,
489 })
490 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
491 .context("A password authenticator SID must be specified.")?;
492
493 let fp_sid = authenticators
494 .iter()
495 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700496 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700497 _ => None,
498 })
499 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
500 .context("A fingerprint authenticator SID must be specified.")?;
501
502 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
503
504 let km_dev: Box<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800505 let (creation_result, _) = self
506 .upgrade_keyblob_if_required_with(
507 &*km_dev,
508 Some(wrapping_key_id_guard),
509 wrapping_key_blob,
510 &[],
511 |wrapping_blob| {
512 let creation_result = map_km_error(km_dev.importWrappedKey(
513 wrapped_data,
514 wrapping_key_blob,
515 masking_key,
516 &params,
517 pw_sid,
518 fp_sid,
519 ))?;
520 Ok(creation_result)
521 },
522 )
523 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700524
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000525 let user_id = uid_to_android_user(caller_uid);
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800526 self.store_new_key(key, creation_result, user_id)
527 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700528 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800529
530 fn upgrade_keyblob_if_required_with<T, F>(
531 &self,
532 km_dev: &dyn IKeyMintDevice,
533 key_id_guard: Option<KeyIdGuard>,
534 blob: &[u8],
535 params: &[KeyParameter],
536 f: F,
537 ) -> Result<(T, Option<Vec<u8>>)>
538 where
539 F: Fn(&[u8]) -> Result<T, Error>,
540 {
541 match f(blob) {
542 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
543 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob, params))
544 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
545 key_id_guard.map_or(Ok(()), |key_id_guard| {
546 DB.with(|db| {
Janis Danisevskis377d1002021-01-27 19:07:48 -0800547 db.borrow_mut().set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800548 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800549 SubComponentType::KEY_BLOB,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800550 Some(&upgraded_blob),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800551 )
552 })
553 .context(concat!(
554 "In upgrade_keyblob_if_required_with: ",
555 "Failed to insert upgraded blob into the database.",
556 ))
557 })?;
558 match f(&upgraded_blob) {
559 Ok(v) => Ok((v, Some(upgraded_blob))),
560 Err(e) => Err(e).context(concat!(
561 "In upgrade_keyblob_if_required_with: ",
562 "Failed to perform operation on second try."
563 )),
564 }
565 }
566 Err(e) => {
567 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
568 }
569 Ok(v) => Ok((v, None)),
570 }
571 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700572}
573
574impl binder::Interface for KeystoreSecurityLevel {}
575
576impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700577 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700578 &self,
579 key: &KeyDescriptor,
580 operation_parameters: &[KeyParameter],
581 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700582 ) -> binder::public_api::Result<CreateOperationResponse> {
583 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700584 }
585 fn generateKey(
586 &self,
587 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700588 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700589 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700590 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700591 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700592 ) -> binder::public_api::Result<KeyMetadata> {
593 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700594 }
595 fn importKey(
596 &self,
597 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700598 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700599 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700600 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700601 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700602 ) -> binder::public_api::Result<KeyMetadata> {
603 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700604 }
605 fn importWrappedKey(
606 &self,
607 key: &KeyDescriptor,
608 wrapping_key: &KeyDescriptor,
609 masking_key: Option<&[u8]>,
610 params: &[KeyParameter],
611 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700612 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700613 map_or_log_err(
614 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700615 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700616 )
617 }
618}