blob: 6b033f12f4e821abd6c3287c1d7e8f822556754e [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};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000035use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, 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| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000134 SUPER_KEY.handle_super_encryption_on_key_init(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000135 &mut db.borrow_mut(),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000136 &LEGACY_MIGRATOR,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000137 &(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| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000221 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
222 db.borrow_mut().load_key_entry(
223 &key,
224 KeyType::Client,
225 KeyEntryLoadBits::KM,
226 caller_uid,
227 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
228 )
229 })
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700230 })
231 .context("In create_operation: Failed to load key blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800232
233 let (blob, blob_metadata) =
234 key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
235 "In create_operation: Successfully loaded key entry, ",
236 "but KM blob was missing."
237 ))?;
238 scoping_blob = blob;
239
Qi Wub9433b52020-12-01 14:52:46 +0800240 (
241 &scoping_blob,
242 Some((key_id_guard.id(), key_entry.into_key_parameters())),
243 Some(key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000244 blob_metadata,
Qi Wub9433b52020-12-01 14:52:46 +0800245 )
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700246 }
247 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700248
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700249 let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700250 Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700251 .context("In create_operation: No operation purpose specified."),
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800252 |kp| match kp.value {
253 KeyParameterValue::KeyPurpose(p) => Ok(p),
254 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
255 .context("In create_operation: Malformed KeyParameter."),
256 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700257 )?;
258
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800259 let (immediate_hat, mut auth_info) = ENFORCEMENTS
260 .authorize_create(
261 purpose,
Qi Wub9433b52020-12-01 14:52:46 +0800262 key_properties.as_ref(),
263 operation_parameters.as_ref(),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800264 // TODO b/178222844 Replace this with the configuration returned by
265 // KeyMintDevice::getHardwareInfo.
266 // For now we assume that strongbox implementations need secure timestamps.
267 self.security_level == SecurityLevel::STRONGBOX,
268 )
269 .context("In create_operation.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000270
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800271 let immediate_hat = immediate_hat.unwrap_or_default();
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000272
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000273 let user_id = uid_to_android_user(caller_uid);
274
275 let km_blob = SUPER_KEY
276 .unwrap_key_if_required(&blob_metadata, km_blob)
277 .context("In create_operation. Failed to handle super encryption.")?;
278
Stephen Crane221bbb52020-12-16 15:52:10 -0800279 let km_dev: Strong<dyn IKeyMintDevice> = self
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700280 .keymint
281 .get_interface()
282 .context("In create_operation: Failed to get KeyMint device")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700283
Janis Danisevskisaec14592020-11-12 09:41:49 -0800284 let (begin_result, upgraded_blob) = self
285 .upgrade_keyblob_if_required_with(
286 &*km_dev,
287 key_id_guard,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000288 &(&km_blob, &blob_metadata),
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700289 &operation_parameters,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800290 |blob| loop {
291 match map_km_error(km_dev.begin(
292 purpose,
293 blob,
294 &operation_parameters,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800295 &immediate_hat,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800296 )) {
297 Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
298 self.operation_db.prune(caller_uid)?;
299 continue;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700300 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800301 v => return v,
302 }
303 },
304 )
305 .context("In create_operation: Failed to begin operation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700306
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800307 let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000308
Janis Danisevskis1af91262020-08-10 14:58:08 -0700309 let operation = match begin_result.operation {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000310 Some(km_op) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800311 self.operation_db.create_operation(km_op, caller_uid, auth_info)
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000312 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700313 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 -0700314 };
315
Stephen Crane221bbb52020-12-16 15:52:10 -0800316 let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700317 KeystoreOperation::new_native_binder(operation)
318 .as_binder()
319 .into_interface()
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700320 .context("In create_operation: Failed to create IKeystoreOperation.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700321
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700322 Ok(CreateOperationResponse {
323 iOperation: Some(op_binder),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000324 operationChallenge: operation_challenge,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700325 parameters: match begin_result.params.len() {
326 0 => None,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700327 _ => Some(KeyParameters { keyParameter: begin_result.params }),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700328 },
329 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700330 }
331
Janis Danisevskise766edc2021-02-06 12:16:26 -0800332 fn add_certificate_parameters(
333 uid: u32,
334 params: &[KeyParameter],
335 key: &KeyDescriptor,
336 ) -> Result<Vec<KeyParameter>> {
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800337 let mut result = params.to_vec();
Janis Danisevskis2c084012021-01-31 22:23:17 -0800338 // If there is an attestation challenge we need to get an application id.
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800339 if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
340 let aaid = keystore2_aaid::get_aaid(uid).map_err(|e| {
Janis Danisevskis2c084012021-01-31 22:23:17 -0800341 anyhow!(format!("In add_certificate_parameters: get_aaid returned status {}.", e))
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800342 })?;
343 result.push(KeyParameter {
344 tag: Tag::ATTESTATION_APPLICATION_ID,
345 value: KeyParameterValue::Blob(aaid),
346 });
347 }
Janis Danisevskis2c084012021-01-31 22:23:17 -0800348
Janis Danisevskise766edc2021-02-06 12:16:26 -0800349 if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
350 check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
351 "In add_certificate_parameters: ",
352 "Caller does not have the permission for device unique attestation."
353 ))?;
354 }
355
Janis Danisevskis2c084012021-01-31 22:23:17 -0800356 // If we are generating/importing an asymmetric key, we need to make sure
357 // that NOT_BEFORE and NOT_AFTER are present.
358 match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
359 Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
360 | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
361 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
362 result.push(KeyParameter {
363 tag: Tag::CERTIFICATE_NOT_BEFORE,
364 value: KeyParameterValue::DateTime(0),
365 })
366 }
367 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
368 result.push(KeyParameter {
369 tag: Tag::CERTIFICATE_NOT_AFTER,
370 value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
371 })
372 }
373 }
374 _ => {}
375 }
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800376 Ok(result)
377 }
378
Janis Danisevskis1af91262020-08-10 14:58:08 -0700379 fn generate_key(
380 &self,
381 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700382 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700383 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700384 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700385 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700386 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700387 if key.domain != Domain::BLOB && key.alias.is_none() {
388 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
389 .context("In generate_key: Alias must be specified");
390 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000391 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700392
393 let key = match key.domain {
394 Domain::APP => KeyDescriptor {
395 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000396 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700397 alias: key.alias.clone(),
398 blob: None,
399 },
400 _ => key.clone(),
401 };
402
403 // generate_key requires the rebind permission.
404 check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
405
Janis Danisevskise766edc2021-02-06 12:16:26 -0800406 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800407 .context("In generate_key: Trying to get aaid.")?;
408
Stephen Crane221bbb52020-12-16 15:52:10 -0800409 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800410 map_km_error(km_dev.addRngEntropy(entropy))
411 .context("In generate_key: Trying to add entropy.")?;
412 let creation_result = map_km_error(km_dev.generateKey(&params))
413 .context("In generate_key: While generating Key")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700414
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000415 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000416 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700417 }
418
419 fn import_key(
420 &self,
421 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700422 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700423 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700424 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700425 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700426 ) -> Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700427 if key.domain != Domain::BLOB && key.alias.is_none() {
428 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
429 .context("In import_key: Alias must be specified");
430 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000431 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700432
433 let key = match key.domain {
434 Domain::APP => KeyDescriptor {
435 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000436 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700437 alias: key.alias.clone(),
438 blob: None,
439 },
440 _ => key.clone(),
441 };
442
443 // import_key requires the rebind permission.
444 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
445
Janis Danisevskise766edc2021-02-06 12:16:26 -0800446 let params = Self::add_certificate_parameters(caller_uid, params, &key)
Janis Danisevskis212c68b2021-01-14 22:29:28 -0800447 .context("In import_key: Trying to get aaid.")?;
448
Janis Danisevskis1af91262020-08-10 14:58:08 -0700449 let format = params
450 .iter()
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700451 .find(|p| p.tag == Tag::ALGORITHM)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700452 .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
453 .context("No KeyParameter 'Algorithm'.")
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800454 .and_then(|p| match &p.value {
455 KeyParameterValue::Algorithm(Algorithm::AES)
456 | KeyParameterValue::Algorithm(Algorithm::HMAC)
457 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
458 KeyParameterValue::Algorithm(Algorithm::RSA)
459 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
460 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
461 .context(format!("Unknown Algorithm {:?}.", v)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700462 })
463 .context("In import_key.")?;
464
Stephen Crane221bbb52020-12-16 15:52:10 -0800465 let km_dev: Strong<dyn IKeyMintDevice> =
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800466 self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
467 let creation_result = map_km_error(km_dev.importKey(&params, format, key_data))
468 .context("In import_key: Trying to call importKey")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700469
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000470 let user_id = uid_to_android_user(caller_uid);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000471 self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700472 }
473
474 fn import_wrapped_key(
475 &self,
476 key: &KeyDescriptor,
477 wrapping_key: &KeyDescriptor,
478 masking_key: Option<&[u8]>,
479 params: &[KeyParameter],
480 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700481 ) -> Result<KeyMetadata> {
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800482 let wrapped_data: &[u8] = match key {
483 KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
484 | KeyDescriptor {
485 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
486 } => blob,
487 _ => {
488 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
489 concat!(
490 "In import_wrapped_key: Alias and blob must be specified ",
491 "and domain must be APP or SELINUX. {:?}"
492 ),
493 key
494 ))
495 }
496 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700497
Janis Danisevskisaec14592020-11-12 09:41:49 -0800498 if wrapping_key.domain == Domain::BLOB {
499 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
500 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
501 );
502 }
503
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000504 let caller_uid = ThreadState::get_calling_uid();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000505 let user_id = uid_to_android_user(caller_uid);
506
Janis Danisevskis1af91262020-08-10 14:58:08 -0700507 let key = match key.domain {
508 Domain::APP => KeyDescriptor {
509 domain: key.domain,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000510 nspace: caller_uid as i64,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700511 alias: key.alias.clone(),
512 blob: None,
513 },
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800514 Domain::SELINUX => KeyDescriptor {
515 domain: Domain::SELINUX,
516 nspace: key.nspace,
517 alias: key.alias.clone(),
518 blob: None,
519 },
520 _ => panic!("Unreachable."),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700521 };
522
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800523 // Import_wrapped_key requires the rebind permission for the new key.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700524 check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
525
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000526 let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700527 .with(|db| {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000528 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
529 db.borrow_mut().load_key_entry(
530 &wrapping_key,
531 KeyType::Client,
532 KeyEntryLoadBits::KM,
533 caller_uid,
534 |k, av| check_key_permission(KeyPerm::use_(), k, &av),
535 )
536 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700537 })
538 .context("Failed to load wrapping key.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000539
540 let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
541 .take_key_blob_info()
542 .ok_or_else(error::Error::sys)
543 .context("No km_blob after successfully loading key. This should never happen.")?;
544
545 let wrapping_key_blob =
546 SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
547 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
548 )?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700549
Janis Danisevskis1af91262020-08-10 14:58:08 -0700550 // km_dev.importWrappedKey does not return a certificate chain.
551 // TODO Do we assume that all wrapped keys are symmetric?
552 // let certificate_chain: Vec<KmCertificate> = Default::default();
553
554 let pw_sid = authenticators
555 .iter()
556 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700557 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700558 _ => None,
559 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800560 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700561
562 let fp_sid = authenticators
563 .iter()
564 .find_map(|a| match a.authenticatorType {
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700565 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700566 _ => None,
567 })
Janis Danisevskis32adc7d2021-02-07 14:04:01 -0800568 .unwrap_or(-1);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569
570 let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
571
Stephen Crane221bbb52020-12-16 15:52:10 -0800572 let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800573 let (creation_result, _) = self
574 .upgrade_keyblob_if_required_with(
575 &*km_dev,
576 Some(wrapping_key_id_guard),
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000577 &(&wrapping_key_blob, &wrapping_blob_metadata),
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800578 &[],
579 |wrapping_blob| {
580 let creation_result = map_km_error(km_dev.importWrappedKey(
581 wrapped_data,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800582 wrapping_blob,
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800583 masking_key,
584 &params,
585 pw_sid,
586 fp_sid,
587 ))?;
588 Ok(creation_result)
589 },
590 )
591 .context("In import_wrapped_key.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700592
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000593 self.store_new_key(key, creation_result, user_id, None)
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800594 .context("In import_wrapped_key: Trying to store the new key.")
Janis Danisevskis1af91262020-08-10 14:58:08 -0700595 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800596
597 fn upgrade_keyblob_if_required_with<T, F>(
598 &self,
599 km_dev: &dyn IKeyMintDevice,
600 key_id_guard: Option<KeyIdGuard>,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000601 blob_info: &(&KeyBlob, &BlobMetaData),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800602 params: &[KeyParameter],
603 f: F,
604 ) -> Result<(T, Option<Vec<u8>>)>
605 where
606 F: Fn(&[u8]) -> Result<T, Error>,
607 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800608 match f(blob_info.0) {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800609 Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800610 let upgraded_blob = map_km_error(km_dev.upgradeKey(blob_info.0, params))
Janis Danisevskisaec14592020-11-12 09:41:49 -0800611 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000612
613 let (upgraded_blob_to_be_stored, blob_metadata) =
614 SuperKeyManager::reencrypt_on_upgrade_if_required(blob_info.0, &upgraded_blob)
615 .context(
616 "In upgrade_keyblob_if_required_with: Failed to handle super encryption.",
617 )?;
618
619 let mut blob_metadata = blob_metadata.unwrap_or_else(BlobMetaData::new);
620 if let Some(uuid) = blob_info.1.km_uuid() {
621 blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
622 }
623
Janis Danisevskisaec14592020-11-12 09:41:49 -0800624 key_id_guard.map_or(Ok(()), |key_id_guard| {
625 DB.with(|db| {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000626 let mut db = db.borrow_mut();
627 db.set_blob(
Janis Danisevskisaec14592020-11-12 09:41:49 -0800628 &key_id_guard,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800629 SubComponentType::KEY_BLOB,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000630 Some(&upgraded_blob_to_be_stored),
631 Some(&blob_metadata),
Janis Danisevskisaec14592020-11-12 09:41:49 -0800632 )
633 })
634 .context(concat!(
635 "In upgrade_keyblob_if_required_with: ",
636 "Failed to insert upgraded blob into the database.",
637 ))
638 })?;
639 match f(&upgraded_blob) {
640 Ok(v) => Ok((v, Some(upgraded_blob))),
641 Err(e) => Err(e).context(concat!(
642 "In upgrade_keyblob_if_required_with: ",
643 "Failed to perform operation on second try."
644 )),
645 }
646 }
647 Err(e) => {
648 Err(e).context("In upgrade_keyblob_if_required_with: Failed perform operation.")
649 }
650 Ok(v) => Ok((v, None)),
651 }
652 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700653}
654
655impl binder::Interface for KeystoreSecurityLevel {}
656
657impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700658 fn createOperation(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700659 &self,
660 key: &KeyDescriptor,
661 operation_parameters: &[KeyParameter],
662 forced: bool,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700663 ) -> binder::public_api::Result<CreateOperationResponse> {
664 map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700665 }
666 fn generateKey(
667 &self,
668 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700669 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700670 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700671 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700672 entropy: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700673 ) -> binder::public_api::Result<KeyMetadata> {
674 map_or_log_err(self.generate_key(key, attestation_key, params, flags, entropy), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700675 }
676 fn importKey(
677 &self,
678 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700679 attestation_key: Option<&KeyDescriptor>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700680 params: &[KeyParameter],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700681 flags: i32,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700682 key_data: &[u8],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700683 ) -> binder::public_api::Result<KeyMetadata> {
684 map_or_log_err(self.import_key(key, attestation_key, params, flags, key_data), Ok)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700685 }
686 fn importWrappedKey(
687 &self,
688 key: &KeyDescriptor,
689 wrapping_key: &KeyDescriptor,
690 masking_key: Option<&[u8]>,
691 params: &[KeyParameter],
692 authenticators: &[AuthenticatorSpec],
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700693 ) -> binder::public_api::Result<KeyMetadata> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700694 map_or_log_err(
695 self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700696 Ok,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700697 )
698 }
699}