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