blob: 3881db3adbf2c117bb1cc53881472650bcc4aef2 [file] [log] [blame]
Andrew Sculld64ae7d2022-10-05 17:41:43 +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//! Logic for handling the DICE values and boot operations.
16
17use anyhow::{bail, Context, Error, Result};
18use byteorder::{NativeEndian, ReadBytesExt};
19use diced_open_dice_cbor::{
20 Config, ContextImpl, InputValuesOwned, Mode, OpenDiceCborContext, CDI_SIZE, HASH_SIZE,
21 HIDDEN_SIZE,
22};
23use keystore2_crypto::ZVec;
24use libc::{c_void, mmap, munmap, MAP_FAILED, MAP_PRIVATE, PROT_READ};
25use openssl::hkdf::hkdf;
26use openssl::md::Md;
27use std::fs;
28use std::os::unix::io::AsRawFd;
29use std::path::{Path, PathBuf};
30use std::ptr::null_mut;
31use std::slice;
32
33/// Artifacts that are kept in the process address space after the artifacts from the driver have
34/// been consumed.
35pub struct DiceContext {
36 pub cdi_attest: [u8; CDI_SIZE],
37 pub cdi_seal: [u8; CDI_SIZE],
38 pub bcc: Vec<u8>,
39}
40
41/// Artifacts that are mapped into the process address space from the driver.
42pub enum DiceDriver<'a> {
43 Real {
44 driver_path: PathBuf,
45 mmap_addr: *mut c_void,
46 mmap_size: usize,
47 cdi_attest: &'a [u8; CDI_SIZE],
48 cdi_seal: &'a [u8; CDI_SIZE],
49 bcc: &'a [u8],
50 },
51 Fake(DiceContext),
52}
53
54impl DiceDriver<'_> {
55 pub fn new(driver_path: &Path) -> Result<Self> {
56 if driver_path.exists() {
57 log::info!("Using DICE values from driver");
58 } else if super::is_strict_boot() {
59 bail!("Strict boot requires DICE value from driver but none were found");
60 } else {
61 log::warn!("Using sample DICE values");
62 let (cdi_attest, cdi_seal, bcc) = diced_sample_inputs::make_sample_bcc_and_cdis()
63 .expect("Failed to create sample dice artifacts.");
64 return Ok(Self::Fake(DiceContext {
65 cdi_attest: cdi_attest[..].try_into().unwrap(),
66 cdi_seal: cdi_seal[..].try_into().unwrap(),
67 bcc,
68 }));
69 };
70
71 let mut file = fs::File::open(driver_path)
72 .map_err(|error| Error::new(error).context("Opening driver"))?;
73 let mmap_size =
74 file.read_u64::<NativeEndian>()
75 .map_err(|error| Error::new(error).context("Reading driver"))? as usize;
76 // It's safe to map the driver as the service will only create a single
77 // mapping per process.
78 let mmap_addr = unsafe {
79 let fd = file.as_raw_fd();
80 mmap(null_mut(), mmap_size, PROT_READ, MAP_PRIVATE, fd, 0)
81 };
82 if mmap_addr == MAP_FAILED {
83 bail!("Failed to mmap {:?}", driver_path);
84 }
85 // The slice is created for the region of memory that was just
86 // successfully mapped into the process address space so it will be
87 // accessible and not referenced from anywhere else.
88 let mmap_buf =
89 unsafe { slice::from_raw_parts((mmap_addr as *const u8).as_ref().unwrap(), mmap_size) };
90 // Very inflexible parsing / validation of the BccHandover data. Assumes deterministically
91 // encoded CBOR.
92 //
93 // BccHandover = {
94 // 1 : bstr .size 32, ; CDI_Attest
95 // 2 : bstr .size 32, ; CDI_Seal
96 // 3 : Bcc, ; Certificate chain
97 // }
98 if mmap_buf[0..4] != [0xa3, 0x01, 0x58, 0x20]
99 || mmap_buf[36..39] != [0x02, 0x58, 0x20]
100 || mmap_buf[71] != 0x03
101 {
102 bail!("BccHandover format mismatch");
103 }
104 Ok(Self::Real {
105 driver_path: driver_path.to_path_buf(),
106 mmap_addr,
107 mmap_size,
108 cdi_attest: mmap_buf[4..36].try_into().unwrap(),
109 cdi_seal: mmap_buf[39..71].try_into().unwrap(),
110 bcc: &mmap_buf[72..],
111 })
112 }
113
114 pub fn get_sealing_key(&self, identifier: &[u8]) -> Result<ZVec> {
115 // Deterministically derive a key to use for sealing data, rather than using the CDI
116 // directly, so we have the chance to rotate the key if needed. A salt isn't needed as the
117 // input key material is already cryptographically strong.
118 let cdi_seal = match self {
119 Self::Real { cdi_seal, .. } => cdi_seal,
120 Self::Fake(fake) => &fake.cdi_seal,
121 };
122 let salt = &[];
123 let mut key = ZVec::new(32)?;
124 hkdf(&mut key, Md::sha256(), cdi_seal, salt, identifier)?;
125 Ok(key)
126 }
127
128 pub fn derive(
129 self,
130 code_hash: [u8; HASH_SIZE],
131 config_desc: &[u8],
132 authority_hash: [u8; HASH_SIZE],
133 debug: bool,
134 hidden: [u8; HIDDEN_SIZE],
135 ) -> Result<DiceContext> {
136 let input_values = InputValuesOwned::new(
137 code_hash,
138 Config::Descriptor(config_desc),
139 authority_hash,
140 None,
141 if debug { Mode::Debug } else { Mode::Normal },
142 hidden,
143 );
144 let (cdi_attest, cdi_seal, bcc) = match &self {
145 Self::Real { cdi_attest, cdi_seal, bcc, .. } => (*cdi_attest, *cdi_seal, *bcc),
146 Self::Fake(fake) => (&fake.cdi_attest, &fake.cdi_seal, fake.bcc.as_slice()),
147 };
148 let (cdi_attest, cdi_seal, bcc) = OpenDiceCborContext::new()
149 .bcc_main_flow(cdi_attest, cdi_seal, bcc, &input_values)
150 .context("DICE derive from driver")?;
151 if let Self::Real { driver_path, .. } = &self {
152 // Writing to the device wipes the artifacts. The string is ignored by the driver but
153 // included for documentation.
154 fs::write(driver_path, "wipe")
155 .map_err(|err| Error::new(err).context("Wiping driver"))?;
156 }
157 Ok(DiceContext {
158 cdi_attest: cdi_attest[..].try_into().unwrap(),
159 cdi_seal: cdi_seal[..].try_into().unwrap(),
160 bcc,
161 })
162 }
163}
164
165impl Drop for DiceDriver<'_> {
166 fn drop(&mut self) {
167 if let &mut Self::Real { mmap_addr, mmap_size, .. } = self {
168 // All references to the mapped region have the same lifetime as self. Since self is
169 // being dropped, so are all the references to the mapped region meaning its safe to
170 // unmap.
171 let ret = unsafe { munmap(mmap_addr, mmap_size) };
172 if ret != 0 {
173 log::warn!("Failed to munmap ({})", ret);
174 }
175 }
176 }
177}