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
17 use anyhow::{bail, Error, Result};
18 use byteorder::{NativeEndian, ReadBytesExt};
19 use diced::{
20 dice,
21 hal_node::{DiceArtifacts, DiceDevice, ResidentHal, UpdatableDiceArtifacts},
22 };
23 use libc::{c_void, mmap, munmap, MAP_FAILED, MAP_PRIVATE, PROT_READ};
24 use serde::{Deserialize, Serialize};
25 use std::fs;
26 use std::os::unix::io::AsRawFd;
27 use std::panic;
28 use std::path::{Path, PathBuf};
29 use std::ptr::null_mut;
30 use std::slice;
31 use std::sync::Arc;
32
33 const AVF_STRICT_BOOT: &str = "/sys/firmware/devicetree/base/chosen/avf,strict-boot";
34 const DICE_HAL_SERVICE_NAME: &str = "android.hardware.security.dice.IDiceDevice/default";
35
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<'_> {
new(driver_path: &Path) -> Result<Self>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<'_> {
drop(&mut self)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<'_> {
cdi_attest(&self) -> &[u8; dice::CDI_SIZE]103 fn cdi_attest(&self) -> &[u8; dice::CDI_SIZE] {
104 self.cdi_attest
105 }
cdi_seal(&self) -> &[u8; dice::CDI_SIZE]106 fn cdi_seal(&self) -> &[u8; dice::CDI_SIZE] {
107 self.cdi_seal
108 }
bcc(&self) -> Vec<u8>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
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 {
cdi_attest(&self) -> &[u8; dice::CDI_SIZE]125 fn cdi_attest(&self) -> &[u8; dice::CDI_SIZE] {
126 &self.cdi_attest
127 }
cdi_seal(&self) -> &[u8; dice::CDI_SIZE]128 fn cdi_seal(&self) -> &[u8; dice::CDI_SIZE] {
129 &self.cdi_seal
130 }
bcc(&self) -> Vec<u8>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 {
139 Invalid,
140 Driver(PathBuf),
141 Updated(RawArtifacts),
142 }
143
144 impl DriverArtifactManager {
new(driver_path: &Path) -> Self145 fn new(driver_path: &Path) -> Self {
146 if driver_path.exists() {
147 log::info!("Using DICE values from driver");
148 Self::Driver(driver_path.to_path_buf())
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
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 }
162 }
163 }
164
165 impl UpdatableDiceArtifacts for DriverArtifactManager {
with_artifacts<F, T>(&self, f: F) -> Result<T> where F: FnOnce(&dyn DiceArtifacts) -> Result<T>,166 fn with_artifacts<F, T>(&self, f: F) -> Result<T>
167 where
168 F: FnOnce(&dyn DiceArtifacts) -> Result<T>,
169 {
170 match self {
171 Self::Invalid => bail!("No DICE artifacts available."),
172 Self::Driver(driver_path) => f(&MappedDriverArtifacts::new(driver_path.as_path())?),
173 Self::Updated(raw_artifacts) => f(raw_artifacts),
174 }
175 }
update(self, new_artifacts: &impl DiceArtifacts) -> Result<Self>176 fn update(self, new_artifacts: &impl DiceArtifacts) -> Result<Self> {
177 if let Self::Invalid = self {
178 bail!("Cannot update invalid DICE artifacts.");
179 }
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 }
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
main()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.
213 ResidentHal::new(DriverArtifactManager::new(Path::new("/dev/open-dice0")))
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 }
226