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