1 // 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 //! This crate implements the IKeystoreSecurityLevel interface.
16 
17 use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
18 use crate::audit_log::{
19     log_key_deleted, log_key_generated, log_key_imported, log_key_integrity_violation,
20 };
21 use crate::database::{CertificateInfo, KeyIdGuard};
22 use crate::error::{self, map_km_error, map_or_log_err, Error, ErrorCode};
23 use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
24 use crate::key_parameter::KeyParameter as KsKeyParam;
25 use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
26 use crate::metrics_store::log_key_creation_event_stats;
27 use crate::remote_provisioning::RemProvState;
28 use crate::super_key::{KeyBlob, SuperKeyManager};
29 use crate::utils::{
30     check_device_attestation_permissions, check_key_permission, is_device_id_attestation_tag,
31     key_characteristics_to_internal, uid_to_android_user, watchdog as wd, Asp,
32 };
33 use crate::{
34     database::{
35         BlobMetaData, BlobMetaEntry, DateTime, KeyEntry, KeyEntryLoadBits, KeyMetaData,
36         KeyMetaEntry, KeyType, SubComponentType, Uuid,
37     },
38     operation::KeystoreOperation,
39     operation::LoggingInfo,
40     operation::OperationDb,
41     permission::KeyPerm,
42 };
43 use crate::{globals::get_keymint_device, id_rotation::IdRotationState};
44 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
45     Algorithm::Algorithm, AttestationKey::AttestationKey,
46     HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
47     KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat,
48     KeyMintHardwareInfo::KeyMintHardwareInfo, KeyParameter::KeyParameter,
49     KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
50 };
51 use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
52 use android_system_keystore2::aidl::android::system::keystore2::{
53     AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
54     Domain::Domain, EphemeralStorageKeyResponse::EphemeralStorageKeyResponse,
55     IKeystoreOperation::IKeystoreOperation, IKeystoreSecurityLevel::BnKeystoreSecurityLevel,
56     IKeystoreSecurityLevel::IKeystoreSecurityLevel, KeyDescriptor::KeyDescriptor,
57     KeyMetadata::KeyMetadata, KeyParameters::KeyParameters, ResponseCode::ResponseCode,
58 };
59 use anyhow::{anyhow, Context, Result};
60 use std::convert::TryInto;
61 use std::time::SystemTime;
62 
63 /// Implementation of the IKeystoreSecurityLevel Interface.
64 pub struct KeystoreSecurityLevel {
65     security_level: SecurityLevel,
66     keymint: Asp,
67     hw_info: KeyMintHardwareInfo,
68     km_uuid: Uuid,
69     operation_db: OperationDb,
70     rem_prov_state: RemProvState,
71     id_rotation_state: IdRotationState,
72 }
73 
74 // Blob of 32 zeroes used as empty masking key.
75 static ZERO_BLOB_32: &[u8] = &[0; 32];
76 
77 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to GeneralizedTime
78 // 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
79 const UNDEFINED_NOT_AFTER: i64 = 253402300799000i64;
80 
81 impl KeystoreSecurityLevel {
82     /// Creates a new security level instance wrapped in a
83     /// BnKeystoreSecurityLevel proxy object. It also enables
84     /// `BinderFeatures::set_requesting_sid` on the new interface, because
85     /// we need it for checking keystore permissions.
new_native_binder( security_level: SecurityLevel, id_rotation_state: IdRotationState, ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)>86     pub fn new_native_binder(
87         security_level: SecurityLevel,
88         id_rotation_state: IdRotationState,
89     ) -> Result<(Strong<dyn IKeystoreSecurityLevel>, Uuid)> {
90         let (dev, hw_info, km_uuid) = get_keymint_device(&security_level)
91             .context("In KeystoreSecurityLevel::new_native_binder.")?;
92         let result = BnKeystoreSecurityLevel::new_binder(
93             Self {
94                 security_level,
95                 keymint: dev,
96                 hw_info,
97                 km_uuid,
98                 operation_db: OperationDb::new(),
99                 rem_prov_state: RemProvState::new(security_level, km_uuid),
100                 id_rotation_state,
101             },
102             BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
103         );
104         Ok((result, km_uuid))
105     }
106 
watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint>107     fn watch_millis(&self, id: &'static str, millis: u64) -> Option<wd::WatchPoint> {
108         let sec_level = self.security_level;
109         wd::watch_millis_with(id, millis, move || format!("SecurityLevel {:?}", sec_level))
110     }
111 
store_new_key( &self, key: KeyDescriptor, creation_result: KeyCreationResult, user_id: u32, flags: Option<i32>, ) -> Result<KeyMetadata>112     fn store_new_key(
113         &self,
114         key: KeyDescriptor,
115         creation_result: KeyCreationResult,
116         user_id: u32,
117         flags: Option<i32>,
118     ) -> Result<KeyMetadata> {
119         let KeyCreationResult {
120             keyBlob: key_blob,
121             keyCharacteristics: key_characteristics,
122             certificateChain: mut certificate_chain,
123         } = creation_result;
124 
125         let mut cert_info: CertificateInfo = CertificateInfo::new(
126             match certificate_chain.len() {
127                 0 => None,
128                 _ => Some(certificate_chain.remove(0).encodedCertificate),
129             },
130             match certificate_chain.len() {
131                 0 => None,
132                 _ => Some(
133                     certificate_chain
134                         .iter()
135                         .map(|c| c.encodedCertificate.iter())
136                         .flatten()
137                         .copied()
138                         .collect(),
139                 ),
140             },
141         );
142 
143         let mut key_parameters = key_characteristics_to_internal(key_characteristics);
144 
145         key_parameters.push(KsKeyParam::new(
146             KsKeyParamValue::UserID(user_id as i32),
147             SecurityLevel::SOFTWARE,
148         ));
149 
150         let creation_date = DateTime::now().context("Trying to make creation time.")?;
151 
152         let key = match key.domain {
153             Domain::BLOB => KeyDescriptor {
154                 domain: Domain::BLOB,
155                 blob: Some(key_blob.to_vec()),
156                 ..Default::default()
157             },
158             _ => DB
159                 .with::<_, Result<KeyDescriptor>>(|db| {
160                     let mut db = db.borrow_mut();
161 
162                     let (key_blob, mut blob_metadata) = SUPER_KEY
163                         .handle_super_encryption_on_key_init(
164                             &mut db,
165                             &LEGACY_MIGRATOR,
166                             &(key.domain),
167                             &key_parameters,
168                             flags,
169                             user_id,
170                             &key_blob,
171                         )
172                         .context("In store_new_key. Failed to handle super encryption.")?;
173 
174                     let mut key_metadata = KeyMetaData::new();
175                     key_metadata.add(KeyMetaEntry::CreationDate(creation_date));
176                     blob_metadata.add(BlobMetaEntry::KmUuid(self.km_uuid));
177 
178                     let key_id = db
179                         .store_new_key(
180                             &key,
181                             KeyType::Client,
182                             &key_parameters,
183                             &(&key_blob, &blob_metadata),
184                             &cert_info,
185                             &key_metadata,
186                             &self.km_uuid,
187                         )
188                         .context("In store_new_key.")?;
189                     Ok(KeyDescriptor {
190                         domain: Domain::KEY_ID,
191                         nspace: key_id.id(),
192                         ..Default::default()
193                     })
194                 })
195                 .context("In store_new_key.")?,
196         };
197 
198         Ok(KeyMetadata {
199             key,
200             keySecurityLevel: self.security_level,
201             certificate: cert_info.take_cert(),
202             certificateChain: cert_info.take_cert_chain(),
203             authorizations: crate::utils::key_parameters_to_authorizations(key_parameters),
204             modificationTimeMs: creation_date.to_millis_epoch(),
205         })
206     }
207 
create_operation( &self, key: &KeyDescriptor, operation_parameters: &[KeyParameter], forced: bool, ) -> Result<CreateOperationResponse>208     fn create_operation(
209         &self,
210         key: &KeyDescriptor,
211         operation_parameters: &[KeyParameter],
212         forced: bool,
213     ) -> Result<CreateOperationResponse> {
214         let caller_uid = ThreadState::get_calling_uid();
215         // We use `scoping_blob` to extend the life cycle of the blob loaded from the database,
216         // so that we can use it by reference like the blob provided by the key descriptor.
217         // Otherwise, we would have to clone the blob from the key descriptor.
218         let scoping_blob: Vec<u8>;
219         let (km_blob, key_properties, key_id_guard, blob_metadata) = match key.domain {
220             Domain::BLOB => {
221                 check_key_permission(KeyPerm::use_(), key, &None)
222                     .context("In create_operation: checking use permission for Domain::BLOB.")?;
223                 if forced {
224                     check_key_permission(KeyPerm::req_forced_op(), key, &None).context(
225                         "In create_operation: checking forced permission for Domain::BLOB.",
226                     )?;
227                 }
228                 (
229                     match &key.blob {
230                         Some(blob) => blob,
231                         None => {
232                             return Err(Error::sys()).context(concat!(
233                                 "In create_operation: Key blob must be specified when",
234                                 " using Domain::BLOB."
235                             ))
236                         }
237                     },
238                     None,
239                     None,
240                     BlobMetaData::new(),
241                 )
242             }
243             _ => {
244                 let (key_id_guard, mut key_entry) = DB
245                     .with::<_, Result<(KeyIdGuard, KeyEntry)>>(|db| {
246                         LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
247                             db.borrow_mut().load_key_entry(
248                                 &key,
249                                 KeyType::Client,
250                                 KeyEntryLoadBits::KM,
251                                 caller_uid,
252                                 |k, av| {
253                                     check_key_permission(KeyPerm::use_(), k, &av)?;
254                                     if forced {
255                                         check_key_permission(KeyPerm::req_forced_op(), k, &av)?;
256                                     }
257                                     Ok(())
258                                 },
259                             )
260                         })
261                     })
262                     .context("In create_operation: Failed to load key blob.")?;
263 
264                 let (blob, blob_metadata) =
265                     key_entry.take_key_blob_info().ok_or_else(Error::sys).context(concat!(
266                         "In create_operation: Successfully loaded key entry, ",
267                         "but KM blob was missing."
268                     ))?;
269                 scoping_blob = blob;
270 
271                 (
272                     &scoping_blob,
273                     Some((key_id_guard.id(), key_entry.into_key_parameters())),
274                     Some(key_id_guard),
275                     blob_metadata,
276                 )
277             }
278         };
279 
280         let purpose = operation_parameters.iter().find(|p| p.tag == Tag::PURPOSE).map_or(
281             Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
282                 .context("In create_operation: No operation purpose specified."),
283             |kp| match kp.value {
284                 KeyParameterValue::KeyPurpose(p) => Ok(p),
285                 _ => Err(Error::Km(ErrorCode::INVALID_ARGUMENT))
286                     .context("In create_operation: Malformed KeyParameter."),
287             },
288         )?;
289 
290         // Remove Tag::PURPOSE from the operation_parameters, since some keymaster devices return
291         // an error on begin() if Tag::PURPOSE is in the operation_parameters.
292         let op_params: Vec<KeyParameter> =
293             operation_parameters.iter().filter(|p| p.tag != Tag::PURPOSE).cloned().collect();
294         let operation_parameters = op_params.as_slice();
295 
296         let (immediate_hat, mut auth_info) = ENFORCEMENTS
297             .authorize_create(
298                 purpose,
299                 key_properties.as_ref(),
300                 operation_parameters.as_ref(),
301                 self.hw_info.timestampTokenRequired,
302             )
303             .context("In create_operation.")?;
304 
305         let km_blob = SUPER_KEY
306             .unwrap_key_if_required(&blob_metadata, km_blob)
307             .context("In create_operation. Failed to handle super encryption.")?;
308 
309         let km_dev: Strong<dyn IKeyMintDevice> = self
310             .keymint
311             .get_interface()
312             .context("In create_operation: Failed to get KeyMint device")?;
313 
314         let (begin_result, upgraded_blob) = self
315             .upgrade_keyblob_if_required_with(
316                 &*km_dev,
317                 key_id_guard,
318                 &km_blob,
319                 &blob_metadata,
320                 &operation_parameters,
321                 |blob| loop {
322                     match map_km_error({
323                         let _wp = self.watch_millis(
324                             "In KeystoreSecurityLevel::create_operation: calling begin",
325                             500,
326                         );
327                         km_dev.begin(purpose, blob, &operation_parameters, immediate_hat.as_ref())
328                     }) {
329                         Err(Error::Km(ErrorCode::TOO_MANY_OPERATIONS)) => {
330                             self.operation_db.prune(caller_uid, forced)?;
331                             continue;
332                         }
333                         v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
334                             if let Some((key_id, _)) = key_properties {
335                                 if let Ok(Some(key)) =
336                                     DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
337                                 {
338                                     log_key_integrity_violation(&key);
339                                 } else {
340                                     log::error!("Failed to load key descriptor for audit log");
341                                 }
342                             }
343                             return v;
344                         }
345                         v => return v,
346                     }
347                 },
348             )
349             .context("In create_operation: Failed to begin operation.")?;
350 
351         let operation_challenge = auth_info.finalize_create_authorization(begin_result.challenge);
352 
353         let op_params: Vec<KeyParameter> = operation_parameters.to_vec();
354 
355         let operation = match begin_result.operation {
356             Some(km_op) => self.operation_db.create_operation(
357                 km_op,
358                 caller_uid,
359                 auth_info,
360                 forced,
361                 LoggingInfo::new(self.security_level, purpose, op_params, upgraded_blob.is_some()),
362             ),
363             None => {
364                 return Err(Error::sys()).context(concat!(
365                     "In create_operation: Begin operation returned successfully, ",
366                     "but did not return a valid operation."
367                 ))
368             }
369         };
370 
371         let op_binder: binder::public_api::Strong<dyn IKeystoreOperation> =
372             KeystoreOperation::new_native_binder(operation)
373                 .as_binder()
374                 .into_interface()
375                 .context("In create_operation: Failed to create IKeystoreOperation.")?;
376 
377         Ok(CreateOperationResponse {
378             iOperation: Some(op_binder),
379             operationChallenge: operation_challenge,
380             parameters: match begin_result.params.len() {
381                 0 => None,
382                 _ => Some(KeyParameters { keyParameter: begin_result.params }),
383             },
384             // An upgraded blob should only be returned if the caller has permission
385             // to use Domain::BLOB keys. If we got to this point, we already checked
386             // that the caller had that permission.
387             upgradedBlob: if key.domain == Domain::BLOB { upgraded_blob } else { None },
388         })
389     }
390 
add_required_parameters( &self, uid: u32, params: &[KeyParameter], key: &KeyDescriptor, ) -> Result<Vec<KeyParameter>>391     fn add_required_parameters(
392         &self,
393         uid: u32,
394         params: &[KeyParameter],
395         key: &KeyDescriptor,
396     ) -> Result<Vec<KeyParameter>> {
397         let mut result = params.to_vec();
398 
399         // Unconditionally add the CREATION_DATETIME tag and prevent callers from
400         // specifying it.
401         if params.iter().any(|kp| kp.tag == Tag::CREATION_DATETIME) {
402             return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(
403                 "In KeystoreSecurityLevel::add_required_parameters: \
404                 Specifying Tag::CREATION_DATETIME is not allowed.",
405             );
406         }
407 
408         result.push(KeyParameter {
409             tag: Tag::CREATION_DATETIME,
410             value: KeyParameterValue::DateTime(
411                 SystemTime::now()
412                     .duration_since(SystemTime::UNIX_EPOCH)
413                     .context(
414                         "In KeystoreSecurityLevel::add_required_parameters: \
415                         Failed to get epoch time.",
416                     )?
417                     .as_millis()
418                     .try_into()
419                     .context(
420                         "In KeystoreSecurityLevel::add_required_parameters: \
421                         Failed to convert epoch time.",
422                     )?,
423             ),
424         });
425 
426         // If there is an attestation challenge we need to get an application id.
427         if params.iter().any(|kp| kp.tag == Tag::ATTESTATION_CHALLENGE) {
428             let aaid = {
429                 let _wp = self.watch_millis(
430                     "In KeystoreSecurityLevel::add_required_parameters calling: get_aaid",
431                     500,
432                 );
433                 keystore2_aaid::get_aaid(uid).map_err(|e| {
434                     anyhow!(format!("In add_required_parameters: get_aaid returned status {}.", e))
435                 })
436             }?;
437 
438             result.push(KeyParameter {
439                 tag: Tag::ATTESTATION_APPLICATION_ID,
440                 value: KeyParameterValue::Blob(aaid),
441             });
442         }
443 
444         if params.iter().any(|kp| kp.tag == Tag::INCLUDE_UNIQUE_ID) {
445             check_key_permission(KeyPerm::gen_unique_id(), key, &None).context(concat!(
446                 "In add_required_parameters: ",
447                 "Caller does not have the permission to generate a unique ID"
448             ))?;
449             if self.id_rotation_state.had_factory_reset_since_id_rotation().context(
450                 "In add_required_parameters: Call to had_factory_reset_since_id_rotation failed.",
451             )? {
452                 result.push(KeyParameter {
453                     tag: Tag::RESET_SINCE_ID_ROTATION,
454                     value: KeyParameterValue::BoolValue(true),
455                 })
456             }
457         }
458 
459         // If the caller requests any device identifier attestation tag, check that they hold the
460         // correct Android permission.
461         if params.iter().any(|kp| is_device_id_attestation_tag(kp.tag)) {
462             check_device_attestation_permissions().context(concat!(
463                 "In add_required_parameters: ",
464                 "Caller does not have the permission to attest device identifiers."
465             ))?;
466         }
467 
468         // If we are generating/importing an asymmetric key, we need to make sure
469         // that NOT_BEFORE and NOT_AFTER are present.
470         match params.iter().find(|kp| kp.tag == Tag::ALGORITHM) {
471             Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::RSA) })
472             | Some(KeyParameter { tag: _, value: KeyParameterValue::Algorithm(Algorithm::EC) }) => {
473                 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_BEFORE) {
474                     result.push(KeyParameter {
475                         tag: Tag::CERTIFICATE_NOT_BEFORE,
476                         value: KeyParameterValue::DateTime(0),
477                     })
478                 }
479                 if !params.iter().any(|kp| kp.tag == Tag::CERTIFICATE_NOT_AFTER) {
480                     result.push(KeyParameter {
481                         tag: Tag::CERTIFICATE_NOT_AFTER,
482                         value: KeyParameterValue::DateTime(UNDEFINED_NOT_AFTER),
483                     })
484                 }
485             }
486             _ => {}
487         }
488         Ok(result)
489     }
490 
generate_key( &self, key: &KeyDescriptor, attest_key_descriptor: Option<&KeyDescriptor>, params: &[KeyParameter], flags: i32, _entropy: &[u8], ) -> Result<KeyMetadata>491     fn generate_key(
492         &self,
493         key: &KeyDescriptor,
494         attest_key_descriptor: Option<&KeyDescriptor>,
495         params: &[KeyParameter],
496         flags: i32,
497         _entropy: &[u8],
498     ) -> Result<KeyMetadata> {
499         if key.domain != Domain::BLOB && key.alias.is_none() {
500             return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
501                 .context("In generate_key: Alias must be specified");
502         }
503         let caller_uid = ThreadState::get_calling_uid();
504 
505         let key = match key.domain {
506             Domain::APP => KeyDescriptor {
507                 domain: key.domain,
508                 nspace: caller_uid as i64,
509                 alias: key.alias.clone(),
510                 blob: None,
511             },
512             _ => key.clone(),
513         };
514 
515         // generate_key requires the rebind permission.
516         // Must return on error for security reasons.
517         check_key_permission(KeyPerm::rebind(), &key, &None).context("In generate_key.")?;
518 
519         let attestation_key_info = match (key.domain, attest_key_descriptor) {
520             (Domain::BLOB, _) => None,
521             _ => DB
522                 .with(|db| {
523                     get_attest_key_info(
524                         &key,
525                         caller_uid,
526                         attest_key_descriptor,
527                         params,
528                         &self.rem_prov_state,
529                         &mut db.borrow_mut(),
530                     )
531                 })
532                 .context("In generate_key: Trying to get an attestation key")?,
533         };
534         let params = self
535             .add_required_parameters(caller_uid, params, &key)
536             .context("In generate_key: Trying to get aaid.")?;
537 
538         let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
539 
540         let creation_result = match attestation_key_info {
541             Some(AttestationKeyInfo::UserGenerated {
542                 key_id_guard,
543                 blob,
544                 blob_metadata,
545                 issuer_subject,
546             }) => self
547                 .upgrade_keyblob_if_required_with(
548                     &*km_dev,
549                     Some(key_id_guard),
550                     &KeyBlob::Ref(&blob),
551                     &blob_metadata,
552                     &params,
553                     |blob| {
554                         let attest_key = Some(AttestationKey {
555                             keyBlob: blob.to_vec(),
556                             attestKeyParams: vec![],
557                             issuerSubjectName: issuer_subject.clone(),
558                         });
559                         map_km_error({
560                             let _wp = self.watch_millis(
561                                 concat!(
562                                     "In KeystoreSecurityLevel::generate_key (UserGenerated): ",
563                                     "calling generate_key."
564                                 ),
565                                 5000, // Generate can take a little longer.
566                             );
567                             km_dev.generateKey(&params, attest_key.as_ref())
568                         })
569                     },
570                 )
571                 .context("In generate_key: Using user generated attestation key.")
572                 .map(|(result, _)| result),
573             Some(AttestationKeyInfo::RemoteProvisioned { attestation_key, attestation_certs }) => {
574                 map_km_error({
575                     let _wp = self.watch_millis(
576                         concat!(
577                             "In KeystoreSecurityLevel::generate_key (RemoteProvisioned): ",
578                             "calling generate_key.",
579                         ),
580                         5000, // Generate can take a little longer.
581                     );
582                     km_dev.generateKey(&params, Some(&attestation_key))
583                 })
584                 .context("While generating Key with remote provisioned attestation key.")
585                 .map(|mut creation_result| {
586                     creation_result.certificateChain.push(attestation_certs);
587                     creation_result
588                 })
589             }
590             None => map_km_error({
591                 let _wp = self.watch_millis(
592                     concat!(
593                         "In KeystoreSecurityLevel::generate_key (No attestation): ",
594                         "calling generate_key.",
595                     ),
596                     5000, // Generate can take a little longer.
597                 );
598                 km_dev.generateKey(&params, None)
599             })
600             .context("While generating Key without explicit attestation key."),
601         }
602         .context("In generate_key.")?;
603 
604         let user_id = uid_to_android_user(caller_uid);
605         self.store_new_key(key, creation_result, user_id, Some(flags)).context("In generate_key.")
606     }
607 
import_key( &self, key: &KeyDescriptor, _attestation_key: Option<&KeyDescriptor>, params: &[KeyParameter], flags: i32, key_data: &[u8], ) -> Result<KeyMetadata>608     fn import_key(
609         &self,
610         key: &KeyDescriptor,
611         _attestation_key: Option<&KeyDescriptor>,
612         params: &[KeyParameter],
613         flags: i32,
614         key_data: &[u8],
615     ) -> Result<KeyMetadata> {
616         if key.domain != Domain::BLOB && key.alias.is_none() {
617             return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
618                 .context("In import_key: Alias must be specified");
619         }
620         let caller_uid = ThreadState::get_calling_uid();
621 
622         let key = match key.domain {
623             Domain::APP => KeyDescriptor {
624                 domain: key.domain,
625                 nspace: caller_uid as i64,
626                 alias: key.alias.clone(),
627                 blob: None,
628             },
629             _ => key.clone(),
630         };
631 
632         // import_key requires the rebind permission.
633         check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_key.")?;
634 
635         let params = self
636             .add_required_parameters(caller_uid, params, &key)
637             .context("In import_key: Trying to get aaid.")?;
638 
639         let format = params
640             .iter()
641             .find(|p| p.tag == Tag::ALGORITHM)
642             .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
643             .context("No KeyParameter 'Algorithm'.")
644             .and_then(|p| match &p.value {
645                 KeyParameterValue::Algorithm(Algorithm::AES)
646                 | KeyParameterValue::Algorithm(Algorithm::HMAC)
647                 | KeyParameterValue::Algorithm(Algorithm::TRIPLE_DES) => Ok(KeyFormat::RAW),
648                 KeyParameterValue::Algorithm(Algorithm::RSA)
649                 | KeyParameterValue::Algorithm(Algorithm::EC) => Ok(KeyFormat::PKCS8),
650                 v => Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
651                     .context(format!("Unknown Algorithm {:?}.", v)),
652             })
653             .context("In import_key.")?;
654 
655         let km_dev: Strong<dyn IKeyMintDevice> =
656             self.keymint.get_interface().context("In import_key: Trying to get the KM device")?;
657         let creation_result = map_km_error({
658             let _wp =
659                 self.watch_millis("In KeystoreSecurityLevel::import_key: calling importKey.", 500);
660             km_dev.importKey(&params, format, key_data, None /* attestKey */)
661         })
662         .context("In import_key: Trying to call importKey")?;
663 
664         let user_id = uid_to_android_user(caller_uid);
665         self.store_new_key(key, creation_result, user_id, Some(flags)).context("In import_key.")
666     }
667 
import_wrapped_key( &self, key: &KeyDescriptor, wrapping_key: &KeyDescriptor, masking_key: Option<&[u8]>, params: &[KeyParameter], authenticators: &[AuthenticatorSpec], ) -> Result<KeyMetadata>668     fn import_wrapped_key(
669         &self,
670         key: &KeyDescriptor,
671         wrapping_key: &KeyDescriptor,
672         masking_key: Option<&[u8]>,
673         params: &[KeyParameter],
674         authenticators: &[AuthenticatorSpec],
675     ) -> Result<KeyMetadata> {
676         let wrapped_data: &[u8] = match key {
677             KeyDescriptor { domain: Domain::APP, blob: Some(ref blob), alias: Some(_), .. }
678             | KeyDescriptor {
679                 domain: Domain::SELINUX, blob: Some(ref blob), alias: Some(_), ..
680             } => blob,
681             _ => {
682                 return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(format!(
683                     concat!(
684                         "In import_wrapped_key: Alias and blob must be specified ",
685                         "and domain must be APP or SELINUX. {:?}"
686                     ),
687                     key
688                 ))
689             }
690         };
691 
692         if wrapping_key.domain == Domain::BLOB {
693             return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(
694                 "In import_wrapped_key: Import wrapped key not supported for self managed blobs.",
695             );
696         }
697 
698         let caller_uid = ThreadState::get_calling_uid();
699         let user_id = uid_to_android_user(caller_uid);
700 
701         let key = match key.domain {
702             Domain::APP => KeyDescriptor {
703                 domain: key.domain,
704                 nspace: caller_uid as i64,
705                 alias: key.alias.clone(),
706                 blob: None,
707             },
708             Domain::SELINUX => KeyDescriptor {
709                 domain: Domain::SELINUX,
710                 nspace: key.nspace,
711                 alias: key.alias.clone(),
712                 blob: None,
713             },
714             _ => panic!("Unreachable."),
715         };
716 
717         // Import_wrapped_key requires the rebind permission for the new key.
718         check_key_permission(KeyPerm::rebind(), &key, &None).context("In import_wrapped_key.")?;
719 
720         let (wrapping_key_id_guard, mut wrapping_key_entry) = DB
721             .with(|db| {
722                 LEGACY_MIGRATOR.with_try_migrate(&key, caller_uid, || {
723                     db.borrow_mut().load_key_entry(
724                         &wrapping_key,
725                         KeyType::Client,
726                         KeyEntryLoadBits::KM,
727                         caller_uid,
728                         |k, av| check_key_permission(KeyPerm::use_(), k, &av),
729                     )
730                 })
731             })
732             .context("Failed to load wrapping key.")?;
733 
734         let (wrapping_key_blob, wrapping_blob_metadata) = wrapping_key_entry
735             .take_key_blob_info()
736             .ok_or_else(error::Error::sys)
737             .context("No km_blob after successfully loading key. This should never happen.")?;
738 
739         let wrapping_key_blob =
740             SUPER_KEY.unwrap_key_if_required(&wrapping_blob_metadata, &wrapping_key_blob).context(
741                 "In import_wrapped_key. Failed to handle super encryption for wrapping key.",
742             )?;
743 
744         // km_dev.importWrappedKey does not return a certificate chain.
745         // TODO Do we assume that all wrapped keys are symmetric?
746         // let certificate_chain: Vec<KmCertificate> = Default::default();
747 
748         let pw_sid = authenticators
749             .iter()
750             .find_map(|a| match a.authenticatorType {
751                 HardwareAuthenticatorType::PASSWORD => Some(a.authenticatorId),
752                 _ => None,
753             })
754             .unwrap_or(-1);
755 
756         let fp_sid = authenticators
757             .iter()
758             .find_map(|a| match a.authenticatorType {
759                 HardwareAuthenticatorType::FINGERPRINT => Some(a.authenticatorId),
760                 _ => None,
761             })
762             .unwrap_or(-1);
763 
764         let masking_key = masking_key.unwrap_or(ZERO_BLOB_32);
765 
766         let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface()?;
767         let (creation_result, _) = self
768             .upgrade_keyblob_if_required_with(
769                 &*km_dev,
770                 Some(wrapping_key_id_guard),
771                 &wrapping_key_blob,
772                 &wrapping_blob_metadata,
773                 &[],
774                 |wrapping_blob| {
775                     let _wp = self.watch_millis(
776                         "In KeystoreSecurityLevel::import_wrapped_key: calling importWrappedKey.",
777                         500,
778                     );
779                     let creation_result = map_km_error(km_dev.importWrappedKey(
780                         wrapped_data,
781                         wrapping_blob,
782                         masking_key,
783                         &params,
784                         pw_sid,
785                         fp_sid,
786                     ))?;
787                     Ok(creation_result)
788                 },
789             )
790             .context("In import_wrapped_key.")?;
791 
792         self.store_new_key(key, creation_result, user_id, None)
793             .context("In import_wrapped_key: Trying to store the new key.")
794     }
795 
store_upgraded_keyblob( key_id_guard: KeyIdGuard, km_uuid: Option<&Uuid>, key_blob: &KeyBlob, upgraded_blob: &[u8], ) -> Result<()>796     fn store_upgraded_keyblob(
797         key_id_guard: KeyIdGuard,
798         km_uuid: Option<&Uuid>,
799         key_blob: &KeyBlob,
800         upgraded_blob: &[u8],
801     ) -> Result<()> {
802         let (upgraded_blob_to_be_stored, new_blob_metadata) =
803             SuperKeyManager::reencrypt_if_required(key_blob, &upgraded_blob)
804                 .context("In store_upgraded_keyblob: Failed to handle super encryption.")?;
805 
806         let mut new_blob_metadata = new_blob_metadata.unwrap_or_default();
807         if let Some(uuid) = km_uuid {
808             new_blob_metadata.add(BlobMetaEntry::KmUuid(*uuid));
809         }
810 
811         DB.with(|db| {
812             let mut db = db.borrow_mut();
813             db.set_blob(
814                 &key_id_guard,
815                 SubComponentType::KEY_BLOB,
816                 Some(&upgraded_blob_to_be_stored),
817                 Some(&new_blob_metadata),
818             )
819         })
820         .context("In store_upgraded_keyblob: Failed to insert upgraded blob into the database.")
821     }
822 
upgrade_keyblob_if_required_with<T, F>( &self, km_dev: &dyn IKeyMintDevice, key_id_guard: Option<KeyIdGuard>, key_blob: &KeyBlob, blob_metadata: &BlobMetaData, params: &[KeyParameter], f: F, ) -> Result<(T, Option<Vec<u8>>)> where F: Fn(&[u8]) -> Result<T, Error>,823     fn upgrade_keyblob_if_required_with<T, F>(
824         &self,
825         km_dev: &dyn IKeyMintDevice,
826         key_id_guard: Option<KeyIdGuard>,
827         key_blob: &KeyBlob,
828         blob_metadata: &BlobMetaData,
829         params: &[KeyParameter],
830         f: F,
831     ) -> Result<(T, Option<Vec<u8>>)>
832     where
833         F: Fn(&[u8]) -> Result<T, Error>,
834     {
835         match f(key_blob) {
836             Err(Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
837                 let upgraded_blob = {
838                     let _wp = self.watch_millis(
839                         concat!(
840                             "In KeystoreSecurityLevel::upgrade_keyblob_if_required_with: ",
841                             "calling upgradeKey."
842                         ),
843                         500,
844                     );
845                     map_km_error(km_dev.upgradeKey(key_blob, params))
846                 }
847                 .context("In upgrade_keyblob_if_required_with: Upgrade failed.")?;
848 
849                 if let Some(kid) = key_id_guard {
850                     Self::store_upgraded_keyblob(
851                         kid,
852                         blob_metadata.km_uuid(),
853                         key_blob,
854                         &upgraded_blob,
855                     )
856                     .context(
857                         "In upgrade_keyblob_if_required_with: store_upgraded_keyblob failed",
858                     )?;
859                 }
860 
861                 match f(&upgraded_blob) {
862                     Ok(v) => Ok((v, Some(upgraded_blob))),
863                     Err(e) => Err(e).context(concat!(
864                         "In upgrade_keyblob_if_required_with: ",
865                         "Failed to perform operation on second try."
866                     )),
867                 }
868             }
869             result => {
870                 if let Some(kid) = key_id_guard {
871                     if key_blob.force_reencrypt() {
872                         Self::store_upgraded_keyblob(
873                             kid,
874                             blob_metadata.km_uuid(),
875                             key_blob,
876                             key_blob,
877                         )
878                         .context(concat!(
879                             "In upgrade_keyblob_if_required_with: ",
880                             "store_upgraded_keyblob failed in forced reencrypt"
881                         ))?;
882                     }
883                 }
884                 result
885                     .map(|v| (v, None))
886                     .context("In upgrade_keyblob_if_required_with: Called closure failed.")
887             }
888         }
889     }
890 
convert_storage_key_to_ephemeral( &self, storage_key: &KeyDescriptor, ) -> Result<EphemeralStorageKeyResponse>891     fn convert_storage_key_to_ephemeral(
892         &self,
893         storage_key: &KeyDescriptor,
894     ) -> Result<EphemeralStorageKeyResponse> {
895         if storage_key.domain != Domain::BLOB {
896             return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT)).context(concat!(
897                 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
898                 "Key must be of Domain::BLOB"
899             ));
900         }
901         let key_blob = storage_key
902             .blob
903             .as_ref()
904             .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
905             .context(
906                 "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: No key blob specified",
907             )?;
908 
909         // convert_storage_key_to_ephemeral requires the associated permission
910         check_key_permission(KeyPerm::convert_storage_key_to_ephemeral(), storage_key, &None)
911             .context("In convert_storage_key_to_ephemeral: Check permission")?;
912 
913         let km_dev: Strong<dyn IKeyMintDevice> = self.keymint.get_interface().context(concat!(
914             "In IKeystoreSecurityLevel convert_storage_key_to_ephemeral: ",
915             "Getting keymint device interface"
916         ))?;
917         match {
918             let _wp = self.watch_millis(
919                 concat!(
920                     "In IKeystoreSecurityLevel::convert_storage_key_to_ephemeral: ",
921                     "calling convertStorageKeyToEphemeral (1)"
922                 ),
923                 500,
924             );
925             map_km_error(km_dev.convertStorageKeyToEphemeral(key_blob))
926         } {
927             Ok(result) => {
928                 Ok(EphemeralStorageKeyResponse { ephemeralKey: result, upgradedBlob: None })
929             }
930             Err(error::Error::Km(ErrorCode::KEY_REQUIRES_UPGRADE)) => {
931                 let upgraded_blob = {
932                     let _wp = self.watch_millis(
933                         "In convert_storage_key_to_ephemeral: calling upgradeKey",
934                         500,
935                     );
936                     map_km_error(km_dev.upgradeKey(key_blob, &[]))
937                 }
938                 .context("In convert_storage_key_to_ephemeral: Failed to upgrade key blob.")?;
939                 let ephemeral_key = {
940                     let _wp = self.watch_millis(
941                         "In convert_storage_key_to_ephemeral: calling convertStorageKeyToEphemeral (2)",
942                         500,
943                     );
944                     map_km_error(km_dev.convertStorageKeyToEphemeral(&upgraded_blob))
945                 }
946                     .context(concat!(
947                         "In convert_storage_key_to_ephemeral: ",
948                         "Failed to retrieve ephemeral key (after upgrade)."
949                     ))?;
950                 Ok(EphemeralStorageKeyResponse {
951                     ephemeralKey: ephemeral_key,
952                     upgradedBlob: Some(upgraded_blob),
953                 })
954             }
955             Err(e) => Err(e)
956                 .context("In convert_storage_key_to_ephemeral: Failed to retrieve ephemeral key."),
957         }
958     }
959 
delete_key(&self, key: &KeyDescriptor) -> Result<()>960     fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
961         if key.domain != Domain::BLOB {
962             return Err(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
963                 .context("In IKeystoreSecurityLevel delete_key: Key must be of Domain::BLOB");
964         }
965 
966         let key_blob = key
967             .blob
968             .as_ref()
969             .ok_or(error::Error::Km(ErrorCode::INVALID_ARGUMENT))
970             .context("In IKeystoreSecurityLevel delete_key: No key blob specified")?;
971 
972         check_key_permission(KeyPerm::delete(), key, &None)
973             .context("In IKeystoreSecurityLevel delete_key: Checking delete permissions")?;
974 
975         let km_dev: Strong<dyn IKeyMintDevice> = self
976             .keymint
977             .get_interface()
978             .context("In IKeystoreSecurityLevel delete_key: Getting keymint device interface")?;
979         {
980             let _wp =
981                 self.watch_millis("In KeystoreSecuritylevel::delete_key: calling deleteKey", 500);
982             map_km_error(km_dev.deleteKey(&key_blob)).context("In keymint device deleteKey")
983         }
984     }
985 }
986 
987 impl binder::Interface for KeystoreSecurityLevel {}
988 
989 impl IKeystoreSecurityLevel for KeystoreSecurityLevel {
createOperation( &self, key: &KeyDescriptor, operation_parameters: &[KeyParameter], forced: bool, ) -> binder::public_api::Result<CreateOperationResponse>990     fn createOperation(
991         &self,
992         key: &KeyDescriptor,
993         operation_parameters: &[KeyParameter],
994         forced: bool,
995     ) -> binder::public_api::Result<CreateOperationResponse> {
996         let _wp = self.watch_millis("IKeystoreSecurityLevel::createOperation", 500);
997         map_or_log_err(self.create_operation(key, operation_parameters, forced), Ok)
998     }
generateKey( &self, key: &KeyDescriptor, attestation_key: Option<&KeyDescriptor>, params: &[KeyParameter], flags: i32, entropy: &[u8], ) -> binder::public_api::Result<KeyMetadata>999     fn generateKey(
1000         &self,
1001         key: &KeyDescriptor,
1002         attestation_key: Option<&KeyDescriptor>,
1003         params: &[KeyParameter],
1004         flags: i32,
1005         entropy: &[u8],
1006     ) -> binder::public_api::Result<KeyMetadata> {
1007         // Duration is set to 5 seconds, because generateKey - especially for RSA keys, takes more
1008         // time than other operations
1009         let _wp = self.watch_millis("IKeystoreSecurityLevel::generateKey", 5000);
1010         let result = self.generate_key(key, attestation_key, params, flags, entropy);
1011         log_key_creation_event_stats(self.security_level, params, &result);
1012         log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
1013         map_or_log_err(result, Ok)
1014     }
importKey( &self, key: &KeyDescriptor, attestation_key: Option<&KeyDescriptor>, params: &[KeyParameter], flags: i32, key_data: &[u8], ) -> binder::public_api::Result<KeyMetadata>1015     fn importKey(
1016         &self,
1017         key: &KeyDescriptor,
1018         attestation_key: Option<&KeyDescriptor>,
1019         params: &[KeyParameter],
1020         flags: i32,
1021         key_data: &[u8],
1022     ) -> binder::public_api::Result<KeyMetadata> {
1023         let _wp = self.watch_millis("IKeystoreSecurityLevel::importKey", 500);
1024         let result = self.import_key(key, attestation_key, params, flags, key_data);
1025         log_key_creation_event_stats(self.security_level, params, &result);
1026         log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
1027         map_or_log_err(result, Ok)
1028     }
importWrappedKey( &self, key: &KeyDescriptor, wrapping_key: &KeyDescriptor, masking_key: Option<&[u8]>, params: &[KeyParameter], authenticators: &[AuthenticatorSpec], ) -> binder::public_api::Result<KeyMetadata>1029     fn importWrappedKey(
1030         &self,
1031         key: &KeyDescriptor,
1032         wrapping_key: &KeyDescriptor,
1033         masking_key: Option<&[u8]>,
1034         params: &[KeyParameter],
1035         authenticators: &[AuthenticatorSpec],
1036     ) -> binder::public_api::Result<KeyMetadata> {
1037         let _wp = self.watch_millis("IKeystoreSecurityLevel::importWrappedKey", 500);
1038         let result =
1039             self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
1040         log_key_creation_event_stats(self.security_level, params, &result);
1041         log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
1042         map_or_log_err(result, Ok)
1043     }
convertStorageKeyToEphemeral( &self, storage_key: &KeyDescriptor, ) -> binder::public_api::Result<EphemeralStorageKeyResponse>1044     fn convertStorageKeyToEphemeral(
1045         &self,
1046         storage_key: &KeyDescriptor,
1047     ) -> binder::public_api::Result<EphemeralStorageKeyResponse> {
1048         let _wp = self.watch_millis("IKeystoreSecurityLevel::convertStorageKeyToEphemeral", 500);
1049         map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
1050     }
deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()>1051     fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
1052         let _wp = self.watch_millis("IKeystoreSecurityLevel::deleteKey", 500);
1053         let result = self.delete_key(key);
1054         log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
1055         map_or_log_err(result, Ok)
1056     }
1057 }
1058