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