Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 1 | // Copyright 2022, 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 | //! Main entry point for the microdroid IDiceDevice HAL implementation. |
| 16 | |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 17 | use anyhow::{bail, Error, Result}; |
| 18 | use byteorder::{NativeEndian, ReadBytesExt}; |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 19 | use diced::{ |
| 20 | dice, |
| 21 | hal_node::{DiceArtifacts, DiceDevice, ResidentHal, UpdatableDiceArtifacts}, |
| 22 | }; |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 23 | use libc::{c_void, mmap, munmap, MAP_FAILED, MAP_PRIVATE, PROT_READ}; |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 24 | use serde::{Deserialize, Serialize}; |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 25 | use std::fs; |
| 26 | use std::os::unix::io::AsRawFd; |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 27 | use std::panic; |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 28 | use std::path::{Path, PathBuf}; |
| 29 | use std::ptr::null_mut; |
| 30 | use std::slice; |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 31 | use std::sync::Arc; |
| 32 | |
Andrew Scull | 79a67ff | 2022-03-14 09:14:10 +0000 | [diff] [blame^] | 33 | const AVF_STRICT_BOOT: &str = "/sys/firmware/devicetree/base/chosen/avf,strict-boot"; |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 34 | const DICE_HAL_SERVICE_NAME: &str = "android.hardware.security.dice.IDiceDevice/default"; |
| 35 | |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 36 | /// Artifacts that are mapped into the process address space from the driver. |
| 37 | struct MappedDriverArtifacts<'a> { |
| 38 | mmap_addr: *mut c_void, |
| 39 | mmap_size: usize, |
| 40 | cdi_attest: &'a [u8; dice::CDI_SIZE], |
| 41 | cdi_seal: &'a [u8; dice::CDI_SIZE], |
| 42 | bcc: &'a [u8], |
| 43 | } |
| 44 | |
| 45 | impl MappedDriverArtifacts<'_> { |
| 46 | fn new(driver_path: &Path) -> Result<Self> { |
| 47 | let mut file = fs::File::open(driver_path) |
| 48 | .map_err(|error| Error::new(error).context("Opening driver"))?; |
| 49 | let mmap_size = |
| 50 | file.read_u64::<NativeEndian>() |
| 51 | .map_err(|error| Error::new(error).context("Reading driver"))? as usize; |
| 52 | // It's safe to map the driver as the service will only create a single |
| 53 | // mapping per process. |
| 54 | let mmap_addr = unsafe { |
| 55 | let fd = file.as_raw_fd(); |
| 56 | mmap(null_mut(), mmap_size, PROT_READ, MAP_PRIVATE, fd, 0) |
| 57 | }; |
| 58 | if mmap_addr == MAP_FAILED { |
| 59 | bail!("Failed to mmap {:?}", driver_path); |
| 60 | } |
| 61 | // The slice is created for the region of memory that was just |
| 62 | // successfully mapped into the process address space so it will be |
| 63 | // accessible and not referenced from anywhere else. |
| 64 | let mmap_buf = |
| 65 | unsafe { slice::from_raw_parts((mmap_addr as *const u8).as_ref().unwrap(), mmap_size) }; |
| 66 | // Very inflexible parsing / validation of the BccHandover data. Assumes deterministically |
| 67 | // encoded CBOR. |
| 68 | // |
| 69 | // BccHandover = { |
| 70 | // 1 : bstr .size 32, ; CDI_Attest |
| 71 | // 2 : bstr .size 32, ; CDI_Seal |
| 72 | // 3 : Bcc, ; Certificate chain |
| 73 | // } |
| 74 | if mmap_buf[0..4] != [0xa3, 0x01, 0x58, 0x20] |
| 75 | || mmap_buf[36..39] != [0x02, 0x58, 0x20] |
| 76 | || mmap_buf[71] != 0x03 |
| 77 | { |
| 78 | bail!("BccHandover format mismatch"); |
| 79 | } |
| 80 | Ok(Self { |
| 81 | mmap_addr, |
| 82 | mmap_size, |
| 83 | cdi_attest: mmap_buf[4..36].try_into().unwrap(), |
| 84 | cdi_seal: mmap_buf[39..71].try_into().unwrap(), |
| 85 | bcc: &mmap_buf[72..], |
| 86 | }) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | impl Drop for MappedDriverArtifacts<'_> { |
| 91 | fn drop(&mut self) { |
| 92 | // All references to the mapped region have the same lifetime as self. |
| 93 | // Since self is being dropped, so are all the references to the mapped |
| 94 | // region meaning its safe to unmap. |
| 95 | let ret = unsafe { munmap(self.mmap_addr, self.mmap_size) }; |
| 96 | if ret != 0 { |
| 97 | log::warn!("Failed to munmap ({})", ret); |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | impl DiceArtifacts for MappedDriverArtifacts<'_> { |
| 103 | fn cdi_attest(&self) -> &[u8; dice::CDI_SIZE] { |
| 104 | self.cdi_attest |
| 105 | } |
| 106 | fn cdi_seal(&self) -> &[u8; dice::CDI_SIZE] { |
| 107 | self.cdi_seal |
| 108 | } |
| 109 | fn bcc(&self) -> Vec<u8> { |
| 110 | // The BCC only contains public information so it's fine to copy. |
| 111 | self.bcc.to_vec() |
| 112 | } |
| 113 | } |
| 114 | |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 115 | /// Artifacts that are kept in the process address space after the artifacts |
| 116 | /// from the driver have been consumed. |
| 117 | #[derive(Clone, Serialize, Deserialize)] |
| 118 | struct RawArtifacts { |
| 119 | cdi_attest: [u8; dice::CDI_SIZE], |
| 120 | cdi_seal: [u8; dice::CDI_SIZE], |
| 121 | bcc: Vec<u8>, |
| 122 | } |
| 123 | |
| 124 | impl DiceArtifacts for RawArtifacts { |
| 125 | fn cdi_attest(&self) -> &[u8; dice::CDI_SIZE] { |
| 126 | &self.cdi_attest |
| 127 | } |
| 128 | fn cdi_seal(&self) -> &[u8; dice::CDI_SIZE] { |
| 129 | &self.cdi_seal |
| 130 | } |
| 131 | fn bcc(&self) -> Vec<u8> { |
| 132 | // The BCC only contains public information so it's fine to copy. |
| 133 | self.bcc.clone() |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | #[derive(Clone, Serialize, Deserialize)] |
| 138 | enum DriverArtifactManager { |
Andrew Scull | 79a67ff | 2022-03-14 09:14:10 +0000 | [diff] [blame^] | 139 | Invalid, |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 140 | Driver(PathBuf), |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 141 | Updated(RawArtifacts), |
| 142 | } |
| 143 | |
| 144 | impl DriverArtifactManager { |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 145 | fn new(driver_path: &Path) -> Self { |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 146 | if driver_path.exists() { |
| 147 | log::info!("Using DICE values from driver"); |
| 148 | Self::Driver(driver_path.to_path_buf()) |
Andrew Scull | 79a67ff | 2022-03-14 09:14:10 +0000 | [diff] [blame^] | 149 | } else if Path::new(AVF_STRICT_BOOT).exists() { |
| 150 | log::error!("Strict boot requires DICE value from driver but none were found"); |
| 151 | Self::Invalid |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 152 | } else { |
| 153 | log::warn!("Using sample DICE values"); |
| 154 | let (cdi_attest, cdi_seal, bcc) = diced_sample_inputs::make_sample_bcc_and_cdis() |
| 155 | .expect("Failed to create sample dice artifacts."); |
| 156 | Self::Updated(RawArtifacts { |
| 157 | cdi_attest: cdi_attest[..].try_into().unwrap(), |
| 158 | cdi_seal: cdi_seal[..].try_into().unwrap(), |
| 159 | bcc, |
| 160 | }) |
| 161 | } |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 162 | } |
| 163 | } |
| 164 | |
| 165 | impl UpdatableDiceArtifacts for DriverArtifactManager { |
| 166 | fn with_artifacts<F, T>(&self, f: F) -> Result<T> |
| 167 | where |
| 168 | F: FnOnce(&dyn DiceArtifacts) -> Result<T>, |
| 169 | { |
| 170 | match self { |
Andrew Scull | 79a67ff | 2022-03-14 09:14:10 +0000 | [diff] [blame^] | 171 | Self::Invalid => bail!("No DICE artifacts available."), |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 172 | Self::Driver(driver_path) => f(&MappedDriverArtifacts::new(driver_path.as_path())?), |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 173 | Self::Updated(raw_artifacts) => f(raw_artifacts), |
| 174 | } |
| 175 | } |
| 176 | fn update(self, new_artifacts: &impl DiceArtifacts) -> Result<Self> { |
Andrew Scull | 79a67ff | 2022-03-14 09:14:10 +0000 | [diff] [blame^] | 177 | if let Self::Invalid = self { |
| 178 | bail!("Cannot update invalid DICE artifacts."); |
| 179 | } |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 180 | if let Self::Driver(driver_path) = self { |
| 181 | // Writing to the device wipes the artifcates. The string is ignored |
| 182 | // by the driver but included for documentation. |
| 183 | fs::write(driver_path, "wipe") |
| 184 | .map_err(|error| Error::new(error).context("Wiping driver"))?; |
| 185 | } |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 186 | Ok(Self::Updated(RawArtifacts { |
| 187 | cdi_attest: *new_artifacts.cdi_attest(), |
| 188 | cdi_seal: *new_artifacts.cdi_seal(), |
| 189 | bcc: new_artifacts.bcc(), |
| 190 | })) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | fn main() { |
| 195 | android_logger::init_once( |
| 196 | android_logger::Config::default() |
| 197 | .with_tag("android.hardware.security.dice") |
| 198 | .with_min_level(log::Level::Debug), |
| 199 | ); |
| 200 | // Redirect panic messages to logcat. |
| 201 | panic::set_hook(Box::new(|panic_info| { |
| 202 | log::error!("{}", panic_info); |
| 203 | })); |
| 204 | |
| 205 | // Saying hi. |
| 206 | log::info!("android.hardware.security.dice is starting."); |
| 207 | |
| 208 | let hal_impl = Arc::new( |
| 209 | unsafe { |
| 210 | // Safety: ResidentHal cannot be used in multi threaded processes. |
| 211 | // This service does not start a thread pool. The main thread is the only thread |
| 212 | // joining the thread pool, thereby keeping the process single threaded. |
Andrew Scull | a3b5c2a | 2022-01-21 19:19:15 +0000 | [diff] [blame] | 213 | ResidentHal::new(DriverArtifactManager::new(Path::new("/dev/open-dice0"))) |
Andrew Scull | f819594 | 2022-01-13 17:37:52 +0000 | [diff] [blame] | 214 | } |
| 215 | .expect("Failed to create ResidentHal implementation."), |
| 216 | ); |
| 217 | |
| 218 | let hal = DiceDevice::new_as_binder(hal_impl).expect("Failed to construct hal service."); |
| 219 | |
| 220 | binder::add_service(DICE_HAL_SERVICE_NAME, hal.as_binder()) |
| 221 | .expect("Failed to register IDiceDevice Service"); |
| 222 | |
| 223 | log::info!("Joining thread pool now."); |
| 224 | binder::ProcessState::join_thread_pool(); |
| 225 | } |