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