| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 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 is the implementation for the remote provisioning AIDL interface between | 
 | 16 | //! the network providers for remote provisioning and the system. This interface | 
 | 17 | //! allows the caller to prompt the Remote Provisioning HAL to generate keys and | 
 | 18 | //! CBOR blobs that can be ferried to a provisioning server that will return | 
 | 19 | //! certificate chains signed by some root authority and stored in a keystore SQLite | 
 | 20 | //! DB. | 
 | 21 |  | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 22 | use std::collections::HashMap; | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 23 |  | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 24 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 25 |     Algorithm::Algorithm, AttestationKey::AttestationKey, Certificate::Certificate, | 
| Max Bires | 834dd36 | 2021-03-23 13:01:57 -0700 | [diff] [blame] | 26 |     DeviceInfo::DeviceInfo, IRemotelyProvisionedComponent::IRemotelyProvisionedComponent, | 
 | 27 |     KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue, | 
 | 28 |     MacedPublicKey::MacedPublicKey, ProtectedData::ProtectedData, SecurityLevel::SecurityLevel, | 
 | 29 |     Tag::Tag, | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 30 | }; | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 31 | use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{ | 
 | 32 |     AttestationPoolStatus::AttestationPoolStatus, IRemoteProvisioning::BnRemoteProvisioning, | 
| Max Bires | d2ce46b | 2021-07-06 02:54:47 -0700 | [diff] [blame] | 33 |     IRemoteProvisioning::IRemoteProvisioning, ImplInfo::ImplInfo, | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 34 | }; | 
| Andrew Walbran | de45c8b | 2021-04-13 14:42:38 +0000 | [diff] [blame] | 35 | use android_security_remoteprovisioning::binder::{BinderFeatures, Strong}; | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 36 | use android_system_keystore2::aidl::android::system::keystore2::{ | 
 | 37 |     Domain::Domain, KeyDescriptor::KeyDescriptor, | 
 | 38 | }; | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 39 | use anyhow::{Context, Result}; | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 40 | use keystore2_crypto::parse_subject_from_certificate; | 
 | 41 | use std::sync::atomic::{AtomicBool, Ordering}; | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 42 |  | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 43 | use crate::database::{CertificateChain, KeystoreDB, Uuid}; | 
 | 44 | use crate::error::{self, map_or_log_err, map_rem_prov_error, Error}; | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 45 | use crate::globals::{get_keymint_device, get_remotely_provisioned_component, DB}; | 
| Hasini Gunasinghe | 8a1a224 | 2021-08-02 22:28:39 +0000 | [diff] [blame] | 46 | use crate::metrics_store::log_rkp_error_stats; | 
| Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 47 | use crate::utils::watchdog as wd; | 
| Hasini Gunasinghe | 8a1a224 | 2021-08-02 22:28:39 +0000 | [diff] [blame] | 48 | use android_security_metrics::aidl::android::security::metrics::RkpError::RkpError as MetricsRkpError; | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 49 |  | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 50 | /// Contains helper functions to check if remote provisioning is enabled on the system and, if so, | 
 | 51 | /// to assign and retrieve attestation keys and certificate chains. | 
 | 52 | #[derive(Default)] | 
 | 53 | pub struct RemProvState { | 
 | 54 |     security_level: SecurityLevel, | 
 | 55 |     km_uuid: Uuid, | 
 | 56 |     is_hal_present: AtomicBool, | 
 | 57 | } | 
 | 58 |  | 
 | 59 | impl RemProvState { | 
 | 60 |     /// Creates a RemProvState struct. | 
 | 61 |     pub fn new(security_level: SecurityLevel, km_uuid: Uuid) -> Self { | 
 | 62 |         Self { security_level, km_uuid, is_hal_present: AtomicBool::new(true) } | 
 | 63 |     } | 
 | 64 |  | 
 | 65 |     /// Checks if remote provisioning is enabled and partially caches the result. On a hybrid system | 
 | 66 |     /// remote provisioning can flip from being disabled to enabled depending on responses from the | 
 | 67 |     /// server, so unfortunately caching the presence or absence of the HAL is not enough to fully | 
 | 68 |     /// make decisions about the state of remote provisioning during runtime. | 
 | 69 |     fn check_rem_prov_enabled(&self, db: &mut KeystoreDB) -> Result<bool> { | 
 | 70 |         if !self.is_hal_present.load(Ordering::Relaxed) | 
 | 71 |             || get_remotely_provisioned_component(&self.security_level).is_err() | 
 | 72 |         { | 
 | 73 |             self.is_hal_present.store(false, Ordering::Relaxed); | 
 | 74 |             return Ok(false); | 
 | 75 |         } | 
 | 76 |         // To check if remote provisioning is enabled on a system that supports both remote | 
 | 77 |         // provisioning and factory provisioned keys, we only need to check if there are any | 
 | 78 |         // keys at all generated to indicate if the app has gotten the signal to begin filling | 
 | 79 |         // the key pool from the server. | 
 | 80 |         let pool_status = db | 
 | 81 |             .get_attestation_pool_status(0 /* date */, &self.km_uuid) | 
 | 82 |             .context("In check_rem_prov_enabled: failed to get attestation pool status.")?; | 
 | 83 |         Ok(pool_status.total != 0) | 
 | 84 |     } | 
 | 85 |  | 
 | 86 |     /// Fetches a remote provisioning attestation key and certificate chain inside of the | 
 | 87 |     /// returned `CertificateChain` struct if one exists for the given caller_uid. If one has not | 
 | 88 |     /// been assigned, this function will assign it. If there are no signed attestation keys | 
 | 89 |     /// available to be assigned, it will return the ResponseCode `OUT_OF_KEYS` | 
 | 90 |     fn get_rem_prov_attest_key( | 
 | 91 |         &self, | 
 | 92 |         key: &KeyDescriptor, | 
 | 93 |         caller_uid: u32, | 
 | 94 |         db: &mut KeystoreDB, | 
 | 95 |     ) -> Result<Option<CertificateChain>> { | 
 | 96 |         match key.domain { | 
 | 97 |             Domain::APP => { | 
 | 98 |                 // Attempt to get an Attestation Key once. If it fails, then the app doesn't | 
 | 99 |                 // have a valid chain assigned to it. The helper function will return None after | 
 | 100 |                 // attempting to assign a key. An error will be thrown if the pool is simply out | 
 | 101 |                 // of usable keys. Then another attempt to fetch the just-assigned key will be | 
 | 102 |                 // made. If this fails too, something is very wrong. | 
 | 103 |                 self.get_rem_prov_attest_key_helper(key, caller_uid, db) | 
 | 104 |                     .context("In get_rem_prov_attest_key: Failed to get a key")? | 
 | 105 |                     .map_or_else( | 
 | 106 |                         || self.get_rem_prov_attest_key_helper(key, caller_uid, db), | 
 | 107 |                         |v| Ok(Some(v)), | 
 | 108 |                     ) | 
 | 109 |                     .context(concat!( | 
 | 110 |                         "In get_rem_prov_attest_key: Failed to get a key after", | 
 | 111 |                         "attempting to assign one." | 
 | 112 |                     ))? | 
 | 113 |                     .map_or_else( | 
 | 114 |                         || { | 
 | 115 |                             Err(Error::sys()).context(concat!( | 
 | 116 |                                 "In get_rem_prov_attest_key: Attempted to assign a ", | 
 | 117 |                                 "key and failed silently. Something is very wrong." | 
 | 118 |                             )) | 
 | 119 |                         }, | 
 | 120 |                         |cert_chain| Ok(Some(cert_chain)), | 
 | 121 |                     ) | 
 | 122 |             } | 
 | 123 |             _ => Ok(None), | 
 | 124 |         } | 
 | 125 |     } | 
 | 126 |  | 
 | 127 |     /// Returns None if an AttestationKey fails to be assigned. Errors if no keys are available. | 
 | 128 |     fn get_rem_prov_attest_key_helper( | 
 | 129 |         &self, | 
 | 130 |         key: &KeyDescriptor, | 
 | 131 |         caller_uid: u32, | 
 | 132 |         db: &mut KeystoreDB, | 
 | 133 |     ) -> Result<Option<CertificateChain>> { | 
 | 134 |         let cert_chain = db | 
 | 135 |             .retrieve_attestation_key_and_cert_chain(key.domain, caller_uid as i64, &self.km_uuid) | 
 | 136 |             .context("In get_rem_prov_attest_key_helper: Failed to retrieve a key + cert chain")?; | 
 | 137 |         match cert_chain { | 
 | 138 |             Some(cert_chain) => Ok(Some(cert_chain)), | 
 | 139 |             // Either this app needs to be assigned a key, or the pool is empty. An error will | 
 | 140 |             // be thrown if there is no key available to assign. This will indicate that the app | 
 | 141 |             // should be nudged to provision more keys so keystore can retry. | 
 | 142 |             None => { | 
 | 143 |                 db.assign_attestation_key(key.domain, caller_uid as i64, &self.km_uuid) | 
 | 144 |                     .context("In get_rem_prov_attest_key_helper: Failed to assign a key")?; | 
 | 145 |                 Ok(None) | 
 | 146 |             } | 
 | 147 |         } | 
 | 148 |     } | 
 | 149 |  | 
 | 150 |     fn is_asymmetric_key(&self, params: &[KeyParameter]) -> bool { | 
 | 151 |         params.iter().any(|kp| { | 
 | 152 |             matches!( | 
 | 153 |                 kp, | 
 | 154 |                 KeyParameter { | 
 | 155 |                     tag: Tag::ALGORITHM, | 
 | 156 |                     value: KeyParameterValue::Algorithm(Algorithm::RSA) | 
 | 157 |                 } | KeyParameter { | 
 | 158 |                     tag: Tag::ALGORITHM, | 
 | 159 |                     value: KeyParameterValue::Algorithm(Algorithm::EC) | 
 | 160 |                 } | 
 | 161 |             ) | 
 | 162 |         }) | 
 | 163 |     } | 
 | 164 |  | 
 | 165 |     /// Checks to see (1) if the key in question should be attested to based on the algorithm and | 
 | 166 |     /// (2) if remote provisioning is present and enabled on the system. If these conditions are | 
 | 167 |     /// met, it makes an attempt to fetch the attestation key assigned to the `caller_uid`. | 
 | 168 |     /// | 
 | 169 |     /// It returns the ResponseCode `OUT_OF_KEYS` if there is not one key currently assigned to the | 
 | 170 |     /// `caller_uid` and there are none available to assign. | 
| Janis Danisevskis | 3541f3e | 2021-03-20 14:18:52 -0700 | [diff] [blame] | 171 |     pub fn get_remotely_provisioned_attestation_key_and_certs( | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 172 |         &self, | 
 | 173 |         key: &KeyDescriptor, | 
 | 174 |         caller_uid: u32, | 
 | 175 |         params: &[KeyParameter], | 
 | 176 |         db: &mut KeystoreDB, | 
| Janis Danisevskis | 3541f3e | 2021-03-20 14:18:52 -0700 | [diff] [blame] | 177 |     ) -> Result<Option<(AttestationKey, Certificate)>> { | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 178 |         if !self.is_asymmetric_key(params) || !self.check_rem_prov_enabled(db)? { | 
 | 179 |             // There is no remote provisioning component for this security level on the | 
 | 180 |             // device. Return None so the underlying KM instance knows to use its | 
 | 181 |             // factory provisioned key instead. Alternatively, it's not an asymmetric key | 
 | 182 |             // and therefore will not be attested. | 
| Janis Danisevskis | 3541f3e | 2021-03-20 14:18:52 -0700 | [diff] [blame] | 183 |             Ok(None) | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 184 |         } else { | 
| Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 185 |             match self.get_rem_prov_attest_key(key, caller_uid, db) { | 
| Max Bires | 31cdfb8 | 2021-07-06 02:59:25 -0700 | [diff] [blame] | 186 |                 Err(e) => { | 
 | 187 |                     log::error!( | 
 | 188 |                         concat!( | 
 | 189 |                             "In get_remote_provisioning_key_and_certs: Failed to get ", | 
 | 190 |                             "attestation key. {:?}" | 
 | 191 |                         ), | 
 | 192 |                         e | 
 | 193 |                     ); | 
| Hasini Gunasinghe | 8a1a224 | 2021-08-02 22:28:39 +0000 | [diff] [blame] | 194 |                     log_rkp_error_stats(MetricsRkpError::FALL_BACK_DURING_HYBRID); | 
| Max Bires | 31cdfb8 | 2021-07-06 02:59:25 -0700 | [diff] [blame] | 195 |                     Ok(None) | 
 | 196 |                 } | 
 | 197 |                 Ok(v) => match v { | 
 | 198 |                     Some(cert_chain) => Ok(Some(( | 
 | 199 |                         AttestationKey { | 
 | 200 |                             keyBlob: cert_chain.private_key.to_vec(), | 
 | 201 |                             attestKeyParams: vec![], | 
 | 202 |                             issuerSubjectName: parse_subject_from_certificate( | 
 | 203 |                                 &cert_chain.batch_cert, | 
 | 204 |                             ) | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 205 |                             .context(concat!( | 
| Max Bires | 31cdfb8 | 2021-07-06 02:59:25 -0700 | [diff] [blame] | 206 |                                 "In get_remote_provisioning_key_and_certs: Failed to ", | 
 | 207 |                                 "parse subject." | 
 | 208 |                             ))?, | 
 | 209 |                         }, | 
 | 210 |                         Certificate { encodedCertificate: cert_chain.cert_chain }, | 
 | 211 |                     ))), | 
 | 212 |                     None => Ok(None), | 
 | 213 |                 }, | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 214 |             } | 
 | 215 |         } | 
 | 216 |     } | 
 | 217 | } | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 218 | /// Implementation of the IRemoteProvisioning service. | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 219 | #[derive(Default)] | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 220 | pub struct RemoteProvisioningService { | 
| Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 221 |     device_by_sec_level: HashMap<SecurityLevel, Strong<dyn IRemotelyProvisionedComponent>>, | 
| Max Bires | d2ce46b | 2021-07-06 02:54:47 -0700 | [diff] [blame] | 222 |     curve_by_sec_level: HashMap<SecurityLevel, i32>, | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 223 | } | 
 | 224 |  | 
 | 225 | impl RemoteProvisioningService { | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 226 |     fn get_dev_by_sec_level( | 
 | 227 |         &self, | 
 | 228 |         sec_level: &SecurityLevel, | 
 | 229 |     ) -> Result<Strong<dyn IRemotelyProvisionedComponent>> { | 
 | 230 |         if let Some(dev) = self.device_by_sec_level.get(sec_level) { | 
| Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 231 |             Ok(dev.clone()) | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 232 |         } else { | 
 | 233 |             Err(error::Error::sys()).context(concat!( | 
 | 234 |                 "In get_dev_by_sec_level: Remote instance for requested security level", | 
 | 235 |                 " not found." | 
 | 236 |             )) | 
 | 237 |         } | 
 | 238 |     } | 
 | 239 |  | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 240 |     /// Creates a new instance of the remote provisioning service | 
| Stephen Crane | 221bbb5 | 2020-12-16 15:52:10 -0800 | [diff] [blame] | 241 |     pub fn new_native_binder() -> Result<Strong<dyn IRemoteProvisioning>> { | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 242 |         let mut result: Self = Default::default(); | 
 | 243 |         let dev = get_remotely_provisioned_component(&SecurityLevel::TRUSTED_ENVIRONMENT) | 
 | 244 |             .context("In new_native_binder: Failed to get TEE Remote Provisioner instance.")?; | 
| Max Bires | d2ce46b | 2021-07-06 02:54:47 -0700 | [diff] [blame] | 245 |         result.curve_by_sec_level.insert( | 
 | 246 |             SecurityLevel::TRUSTED_ENVIRONMENT, | 
 | 247 |             dev.getHardwareInfo() | 
 | 248 |                 .context("In new_native_binder: Failed to get hardware info for the TEE.")? | 
 | 249 |                 .supportedEekCurve, | 
 | 250 |         ); | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 251 |         result.device_by_sec_level.insert(SecurityLevel::TRUSTED_ENVIRONMENT, dev); | 
 | 252 |         if let Ok(dev) = get_remotely_provisioned_component(&SecurityLevel::STRONGBOX) { | 
| Max Bires | d2ce46b | 2021-07-06 02:54:47 -0700 | [diff] [blame] | 253 |             result.curve_by_sec_level.insert( | 
 | 254 |                 SecurityLevel::STRONGBOX, | 
 | 255 |                 dev.getHardwareInfo() | 
 | 256 |                     .context("In new_native_binder: Failed to get hardware info for StrongBox.")? | 
 | 257 |                     .supportedEekCurve, | 
 | 258 |             ); | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 259 |             result.device_by_sec_level.insert(SecurityLevel::STRONGBOX, dev); | 
 | 260 |         } | 
| Andrew Walbran | de45c8b | 2021-04-13 14:42:38 +0000 | [diff] [blame] | 261 |         Ok(BnRemoteProvisioning::new_binder(result, BinderFeatures::default())) | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 262 |     } | 
 | 263 |  | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 264 |     /// Generates a CBOR blob which will be assembled by the calling code into a larger | 
 | 265 |     /// CBOR blob intended for delivery to a provisioning serever. This blob will contain | 
 | 266 |     /// `num_csr` certificate signing requests for attestation keys generated in the TEE, | 
 | 267 |     /// along with a server provided `eek` and `challenge`. The endpoint encryption key will | 
 | 268 |     /// be used to encrypt the sensitive contents being transmitted to the server, and the | 
 | 269 |     /// challenge will ensure freshness. A `test_mode` flag will instruct the remote provisioning | 
 | 270 |     /// HAL if it is okay to accept EEKs that aren't signed by something that chains back to the | 
 | 271 |     /// baked in root of trust in the underlying IRemotelyProvisionedComponent instance. | 
| Max Bires | 834dd36 | 2021-03-23 13:01:57 -0700 | [diff] [blame] | 272 |     #[allow(clippy::too_many_arguments)] | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 273 |     pub fn generate_csr( | 
 | 274 |         &self, | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 275 |         test_mode: bool, | 
 | 276 |         num_csr: i32, | 
 | 277 |         eek: &[u8], | 
 | 278 |         challenge: &[u8], | 
 | 279 |         sec_level: SecurityLevel, | 
 | 280 |         protected_data: &mut ProtectedData, | 
| Max Bires | 834dd36 | 2021-03-23 13:01:57 -0700 | [diff] [blame] | 281 |         device_info: &mut DeviceInfo, | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 282 |     ) -> Result<Vec<u8>> { | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 283 |         let dev = self.get_dev_by_sec_level(&sec_level)?; | 
 | 284 |         let (_, _, uuid) = get_keymint_device(&sec_level)?; | 
 | 285 |         let keys_to_sign = DB.with::<_, Result<Vec<MacedPublicKey>>>(|db| { | 
 | 286 |             let mut db = db.borrow_mut(); | 
 | 287 |             Ok(db | 
 | 288 |                 .fetch_unsigned_attestation_keys(num_csr, &uuid)? | 
 | 289 |                 .iter() | 
 | 290 |                 .map(|key| MacedPublicKey { macedKey: key.to_vec() }) | 
 | 291 |                 .collect()) | 
 | 292 |         })?; | 
| Max Bires | 834dd36 | 2021-03-23 13:01:57 -0700 | [diff] [blame] | 293 |         let mut mac = map_rem_prov_error(dev.generateCertificateRequest( | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 294 |             test_mode, | 
 | 295 |             &keys_to_sign, | 
 | 296 |             eek, | 
 | 297 |             challenge, | 
| Max Bires | 834dd36 | 2021-03-23 13:01:57 -0700 | [diff] [blame] | 298 |             device_info, | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 299 |             protected_data, | 
 | 300 |         )) | 
 | 301 |         .context("In generate_csr: Failed to generate csr")?; | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 302 |         // TODO(b/180392379): Replace this manual CBOR generation with the cbor-serde crate as well. | 
 | 303 |         //                    This generates an array consisting of the mac and the public key Maps. | 
 | 304 |         //                    Just generate the actual MacedPublicKeys structure when the crate is | 
 | 305 |         //                    available. | 
| Matthew Maurer | b77a28d | 2021-05-07 16:08:20 -0700 | [diff] [blame] | 306 |         let mut cose_mac_0: Vec<u8> = vec![ | 
 | 307 |             (0b100_00000 | (keys_to_sign.len() + 1)) as u8, | 
 | 308 |             0b010_11000, // mac | 
 | 309 |             (mac.len() as u8), | 
 | 310 |         ]; | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 311 |         cose_mac_0.append(&mut mac); | 
| Max Bires | 67e9512 | 2021-06-21 00:20:23 -0700 | [diff] [blame] | 312 |         // If this is a test mode key, there is an extra 6 bytes added as an additional entry in | 
 | 313 |         // the COSE_Key struct to denote that. | 
 | 314 |         let test_mode_entry_shift = if test_mode { 0 } else { 6 }; | 
 | 315 |         let byte_dist_mac0_payload = 8; | 
 | 316 |         let cose_key_size = 83 - test_mode_entry_shift; | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 317 |         for maced_public_key in keys_to_sign { | 
| Max Bires | 67e9512 | 2021-06-21 00:20:23 -0700 | [diff] [blame] | 318 |             if maced_public_key.macedKey.len() > cose_key_size + byte_dist_mac0_payload { | 
 | 319 |                 cose_mac_0.extend_from_slice( | 
 | 320 |                     &maced_public_key.macedKey | 
 | 321 |                         [byte_dist_mac0_payload..cose_key_size + byte_dist_mac0_payload], | 
 | 322 |                 ); | 
| Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 323 |             } | 
 | 324 |         } | 
 | 325 |         Ok(cose_mac_0) | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 326 |     } | 
 | 327 |  | 
 | 328 |     /// Provisions a certificate chain for a key whose CSR was included in generate_csr. The | 
 | 329 |     /// `public_key` is used to index into the SQL database in order to insert the `certs` blob | 
 | 330 |     /// which represents a PEM encoded X.509 certificate chain. The `expiration_date` is provided | 
 | 331 |     /// as a convenience from the caller to avoid having to parse the certificates semantically | 
 | 332 |     /// here. | 
 | 333 |     pub fn provision_cert_chain( | 
 | 334 |         &self, | 
 | 335 |         public_key: &[u8], | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 336 |         batch_cert: &[u8], | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 337 |         certs: &[u8], | 
 | 338 |         expiration_date: i64, | 
 | 339 |         sec_level: SecurityLevel, | 
 | 340 |     ) -> Result<()> { | 
 | 341 |         DB.with::<_, Result<()>>(|db| { | 
 | 342 |             let mut db = db.borrow_mut(); | 
 | 343 |             let (_, _, uuid) = get_keymint_device(&sec_level)?; | 
| Matthew Maurer | b77a28d | 2021-05-07 16:08:20 -0700 | [diff] [blame] | 344 |             db.store_signed_attestation_certificate_chain( | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 345 |                 public_key, | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 346 |                 batch_cert, | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 347 |                 certs, /* DER encoded certificate chain */ | 
 | 348 |                 expiration_date, | 
 | 349 |                 &uuid, | 
| Matthew Maurer | b77a28d | 2021-05-07 16:08:20 -0700 | [diff] [blame] | 350 |             ) | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 351 |         }) | 
 | 352 |     } | 
 | 353 |  | 
 | 354 |     /// Submits a request to the Remote Provisioner HAL to generate a signing key pair. | 
 | 355 |     /// `is_test_mode` indicates whether or not the returned public key should be marked as being | 
 | 356 |     /// for testing in order to differentiate them from private keys. If the call is successful, | 
 | 357 |     /// the key pair is then added to the database. | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 358 |     pub fn generate_key_pair(&self, is_test_mode: bool, sec_level: SecurityLevel) -> Result<()> { | 
 | 359 |         let (_, _, uuid) = get_keymint_device(&sec_level)?; | 
 | 360 |         let dev = self.get_dev_by_sec_level(&sec_level)?; | 
 | 361 |         let mut maced_key = MacedPublicKey { macedKey: Vec::new() }; | 
 | 362 |         let priv_key = | 
 | 363 |             map_rem_prov_error(dev.generateEcdsaP256KeyPair(is_test_mode, &mut maced_key)) | 
 | 364 |                 .context("In generate_key_pair: Failed to generated ECDSA keypair.")?; | 
 | 365 |         // TODO(b/180392379): This is a brittle hack that relies on the consistent formatting of | 
 | 366 |         //                    the returned CBOR blob in order to extract the public key. | 
 | 367 |         let data = &maced_key.macedKey; | 
 | 368 |         if data.len() < 85 { | 
 | 369 |             return Err(error::Error::sys()).context(concat!( | 
 | 370 |                 "In generate_key_pair: CBOR blob returned from", | 
 | 371 |                 "RemotelyProvisionedComponent is definitely malformatted or empty." | 
 | 372 |             )); | 
 | 373 |         } | 
 | 374 |         let mut raw_key: Vec<u8> = vec![0; 64]; | 
 | 375 |         raw_key[0..32].clone_from_slice(&data[18..18 + 32]); | 
 | 376 |         raw_key[32..64].clone_from_slice(&data[53..53 + 32]); | 
 | 377 |         DB.with::<_, Result<()>>(|db| { | 
 | 378 |             let mut db = db.borrow_mut(); | 
| Matthew Maurer | b77a28d | 2021-05-07 16:08:20 -0700 | [diff] [blame] | 379 |             db.create_attestation_key_entry(&maced_key.macedKey, &raw_key, &priv_key, &uuid) | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 380 |         }) | 
 | 381 |     } | 
 | 382 |  | 
 | 383 |     /// Checks the security level of each available IRemotelyProvisionedComponent hal and returns | 
 | 384 |     /// all levels in an array to the caller. | 
| Max Bires | d2ce46b | 2021-07-06 02:54:47 -0700 | [diff] [blame] | 385 |     pub fn get_implementation_info(&self) -> Result<Vec<ImplInfo>> { | 
 | 386 |         Ok(self | 
 | 387 |             .curve_by_sec_level | 
 | 388 |             .iter() | 
 | 389 |             .map(|(sec_level, curve)| ImplInfo { secLevel: *sec_level, supportedCurve: *curve }) | 
 | 390 |             .collect()) | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 391 |     } | 
| Max Bires | 60d7ed1 | 2021-03-05 15:59:22 -0800 | [diff] [blame] | 392 |  | 
 | 393 |     /// Deletes all attestation keys generated by the IRemotelyProvisionedComponent from the device, | 
 | 394 |     /// regardless of what state of the attestation key lifecycle they were in. | 
 | 395 |     pub fn delete_all_keys(&self) -> Result<i64> { | 
 | 396 |         DB.with::<_, Result<i64>>(|db| { | 
 | 397 |             let mut db = db.borrow_mut(); | 
| Matthew Maurer | b77a28d | 2021-05-07 16:08:20 -0700 | [diff] [blame] | 398 |             db.delete_all_attestation_keys() | 
| Max Bires | 60d7ed1 | 2021-03-05 15:59:22 -0800 | [diff] [blame] | 399 |         }) | 
 | 400 |     } | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 401 | } | 
 | 402 |  | 
| Hasini Gunasinghe | 8af67ea | 2021-06-30 17:09:01 +0000 | [diff] [blame] | 403 | /// Populates the AttestationPoolStatus parcelable with information about how many | 
 | 404 | /// certs will be expiring by the date provided in `expired_by` along with how many | 
 | 405 | /// keys have not yet been assigned. | 
 | 406 | pub fn get_pool_status(expired_by: i64, sec_level: SecurityLevel) -> Result<AttestationPoolStatus> { | 
 | 407 |     let (_, _, uuid) = get_keymint_device(&sec_level)?; | 
 | 408 |     DB.with::<_, Result<AttestationPoolStatus>>(|db| { | 
 | 409 |         let mut db = db.borrow_mut(); | 
 | 410 |         // delete_expired_attestation_keys is always safe to call, and will remove anything | 
 | 411 |         // older than the date at the time of calling. No work should be done on the | 
 | 412 |         // attestation keys unless the pool status is checked first, so this call should be | 
 | 413 |         // enough to routinely clean out expired keys. | 
 | 414 |         db.delete_expired_attestation_keys()?; | 
 | 415 |         db.get_attestation_pool_status(expired_by, &uuid) | 
 | 416 |     }) | 
 | 417 | } | 
 | 418 |  | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 419 | impl binder::Interface for RemoteProvisioningService {} | 
 | 420 |  | 
 | 421 | // Implementation of IRemoteProvisioning. See AIDL spec at | 
 | 422 | // :aidl/android/security/remoteprovisioning/IRemoteProvisioning.aidl | 
 | 423 | impl IRemoteProvisioning for RemoteProvisioningService { | 
 | 424 |     fn getPoolStatus( | 
 | 425 |         &self, | 
 | 426 |         expired_by: i64, | 
 | 427 |         sec_level: SecurityLevel, | 
 | 428 |     ) -> binder::public_api::Result<AttestationPoolStatus> { | 
| Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 429 |         let _wp = wd::watch_millis("IRemoteProvisioning::getPoolStatus", 500); | 
| Hasini Gunasinghe | 8af67ea | 2021-06-30 17:09:01 +0000 | [diff] [blame] | 430 |         map_or_log_err(get_pool_status(expired_by, sec_level), Ok) | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 431 |     } | 
 | 432 |  | 
 | 433 |     fn generateCsr( | 
 | 434 |         &self, | 
 | 435 |         test_mode: bool, | 
 | 436 |         num_csr: i32, | 
 | 437 |         eek: &[u8], | 
 | 438 |         challenge: &[u8], | 
 | 439 |         sec_level: SecurityLevel, | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 440 |         protected_data: &mut ProtectedData, | 
| Max Bires | 834dd36 | 2021-03-23 13:01:57 -0700 | [diff] [blame] | 441 |         device_info: &mut DeviceInfo, | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 442 |     ) -> binder::public_api::Result<Vec<u8>> { | 
| Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 443 |         let _wp = wd::watch_millis("IRemoteProvisioning::generateCsr", 500); | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 444 |         map_or_log_err( | 
| Max Bires | 834dd36 | 2021-03-23 13:01:57 -0700 | [diff] [blame] | 445 |             self.generate_csr( | 
 | 446 |                 test_mode, | 
 | 447 |                 num_csr, | 
 | 448 |                 eek, | 
 | 449 |                 challenge, | 
 | 450 |                 sec_level, | 
 | 451 |                 protected_data, | 
 | 452 |                 device_info, | 
 | 453 |             ), | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 454 |             Ok, | 
 | 455 |         ) | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 456 |     } | 
 | 457 |  | 
 | 458 |     fn provisionCertChain( | 
 | 459 |         &self, | 
 | 460 |         public_key: &[u8], | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 461 |         batch_cert: &[u8], | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 462 |         certs: &[u8], | 
 | 463 |         expiration_date: i64, | 
 | 464 |         sec_level: SecurityLevel, | 
 | 465 |     ) -> binder::public_api::Result<()> { | 
| Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 466 |         let _wp = wd::watch_millis("IRemoteProvisioning::provisionCertChain", 500); | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 467 |         map_or_log_err( | 
 | 468 |             self.provision_cert_chain(public_key, batch_cert, certs, expiration_date, sec_level), | 
 | 469 |             Ok, | 
 | 470 |         ) | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 471 |     } | 
 | 472 |  | 
 | 473 |     fn generateKeyPair( | 
 | 474 |         &self, | 
 | 475 |         is_test_mode: bool, | 
 | 476 |         sec_level: SecurityLevel, | 
 | 477 |     ) -> binder::public_api::Result<()> { | 
| Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 478 |         let _wp = wd::watch_millis("IRemoteProvisioning::generateKeyPair", 500); | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 479 |         map_or_log_err(self.generate_key_pair(is_test_mode, sec_level), Ok) | 
 | 480 |     } | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 481 |  | 
| Max Bires | d2ce46b | 2021-07-06 02:54:47 -0700 | [diff] [blame] | 482 |     fn getImplementationInfo(&self) -> binder::public_api::Result<Vec<ImplInfo>> { | 
| Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 483 |         let _wp = wd::watch_millis("IRemoteProvisioning::getSecurityLevels", 500); | 
| Max Bires | d2ce46b | 2021-07-06 02:54:47 -0700 | [diff] [blame] | 484 |         map_or_log_err(self.get_implementation_info(), Ok) | 
| Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 485 |     } | 
| Max Bires | 60d7ed1 | 2021-03-05 15:59:22 -0800 | [diff] [blame] | 486 |  | 
 | 487 |     fn deleteAllKeys(&self) -> binder::public_api::Result<i64> { | 
| Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 488 |         let _wp = wd::watch_millis("IRemoteProvisioning::deleteAllKeys", 500); | 
| Max Bires | 60d7ed1 | 2021-03-05 15:59:22 -0800 | [diff] [blame] | 489 |         map_or_log_err(self.delete_all_keys(), Ok) | 
 | 490 |     } | 
| Max Bires | 148c08e | 2020-10-13 13:41:41 -0700 | [diff] [blame] | 491 | } |