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