blob: 8199c7c16742b2ad38b39990d1e2542255407129 [file] [log] [blame]
Andrew Scullf8195942022-01-13 17:37:52 +00001// 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 Sculla3b5c2a2022-01-21 19:19:15 +000017use anyhow::{bail, Error, Result};
18use byteorder::{NativeEndian, ReadBytesExt};
Andrew Scullf8195942022-01-13 17:37:52 +000019use diced::{
20 dice,
21 hal_node::{DiceArtifacts, DiceDevice, ResidentHal, UpdatableDiceArtifacts},
22};
Andrew Sculla3b5c2a2022-01-21 19:19:15 +000023use libc::{c_void, mmap, munmap, MAP_FAILED, MAP_PRIVATE, PROT_READ};
Andrew Scullf8195942022-01-13 17:37:52 +000024use serde::{Deserialize, Serialize};
Andrew Sculla3b5c2a2022-01-21 19:19:15 +000025use std::fs;
26use std::os::unix::io::AsRawFd;
Andrew Scullf8195942022-01-13 17:37:52 +000027use std::panic;
Andrew Sculla3b5c2a2022-01-21 19:19:15 +000028use std::path::{Path, PathBuf};
29use std::ptr::null_mut;
30use std::slice;
Andrew Scullf8195942022-01-13 17:37:52 +000031use std::sync::Arc;
32
Andrew Scull79a67ff2022-03-14 09:14:10 +000033const AVF_STRICT_BOOT: &str = "/sys/firmware/devicetree/base/chosen/avf,strict-boot";
Andrew Scullf8195942022-01-13 17:37:52 +000034const DICE_HAL_SERVICE_NAME: &str = "android.hardware.security.dice.IDiceDevice/default";
35
Andrew Sculla3b5c2a2022-01-21 19:19:15 +000036/// Artifacts that are mapped into the process address space from the driver.
37struct 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
45impl 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
90impl 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
102impl 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 Scullf8195942022-01-13 17:37:52 +0000115/// Artifacts that are kept in the process address space after the artifacts
116/// from the driver have been consumed.
117#[derive(Clone, Serialize, Deserialize)]
118struct RawArtifacts {
119 cdi_attest: [u8; dice::CDI_SIZE],
120 cdi_seal: [u8; dice::CDI_SIZE],
121 bcc: Vec<u8>,
122}
123
124impl 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)]
138enum DriverArtifactManager {
Andrew Scull79a67ff2022-03-14 09:14:10 +0000139 Invalid,
Andrew Sculla3b5c2a2022-01-21 19:19:15 +0000140 Driver(PathBuf),
Andrew Scullf8195942022-01-13 17:37:52 +0000141 Updated(RawArtifacts),
142}
143
144impl DriverArtifactManager {
Andrew Sculla3b5c2a2022-01-21 19:19:15 +0000145 fn new(driver_path: &Path) -> Self {
Andrew Sculla3b5c2a2022-01-21 19:19:15 +0000146 if driver_path.exists() {
147 log::info!("Using DICE values from driver");
148 Self::Driver(driver_path.to_path_buf())
Andrew Scull79a67ff2022-03-14 09:14:10 +0000149 } 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 Sculla3b5c2a2022-01-21 19:19:15 +0000152 } 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 Scullf8195942022-01-13 17:37:52 +0000162 }
163}
164
165impl 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 Scull79a67ff2022-03-14 09:14:10 +0000171 Self::Invalid => bail!("No DICE artifacts available."),
Andrew Sculla3b5c2a2022-01-21 19:19:15 +0000172 Self::Driver(driver_path) => f(&MappedDriverArtifacts::new(driver_path.as_path())?),
Andrew Scullf8195942022-01-13 17:37:52 +0000173 Self::Updated(raw_artifacts) => f(raw_artifacts),
174 }
175 }
176 fn update(self, new_artifacts: &impl DiceArtifacts) -> Result<Self> {
Andrew Scull79a67ff2022-03-14 09:14:10 +0000177 if let Self::Invalid = self {
178 bail!("Cannot update invalid DICE artifacts.");
179 }
Andrew Sculla3b5c2a2022-01-21 19:19:15 +0000180 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 Scullf8195942022-01-13 17:37:52 +0000186 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
194fn 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 Sculla3b5c2a2022-01-21 19:19:15 +0000213 ResidentHal::new(DriverArtifactManager::new(Path::new("/dev/open-dice0")))
Andrew Scullf8195942022-01-13 17:37:52 +0000214 }
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}