blob: cf5e73e933489caaffa603dfc784bc25bb124ca0 [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};
Alice Wangf4b8b002023-02-08 08:53:23 +000019use diced_open_dice::{
20 retry_bcc_main_flow, Config, DiceMode, Hash, Hidden, InputValues, OwnedDiceArtifacts, 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.
Alice Wangf4b8b002023-02-08 08:53:23 +000034/// TODO(b/267575445): Replace with `OwnedDiceArtifacts` from the library `diced_open_dice`.
Andrew Sculld64ae7d2022-10-05 17:41:43 +000035pub struct DiceContext {
36 pub cdi_attest: [u8; CDI_SIZE],
37 pub cdi_seal: [u8; CDI_SIZE],
38 pub bcc: Vec<u8>,
39}
40
Alice Wangf4b8b002023-02-08 08:53:23 +000041impl From<OwnedDiceArtifacts> for DiceContext {
42 fn from(dice_artifacts: OwnedDiceArtifacts) -> Self {
43 Self {
44 cdi_attest: dice_artifacts.cdi_values.cdi_attest,
45 cdi_seal: dice_artifacts.cdi_values.cdi_seal,
46 bcc: dice_artifacts.bcc[..].to_vec(),
47 }
48 }
49}
50
Shikha Panwar566c9672022-11-15 14:39:58 +000051impl DiceContext {
52 pub fn get_sealing_key(&self, salt: &[u8], identifier: &[u8], keysize: u32) -> Result<ZVec> {
53 // Deterministically derive a key to use for sealing data based on salt. Use different salt
54 // for different keys.
55 let mut key = ZVec::new(keysize as usize)?;
56 hkdf(&mut key, Md::sha256(), &self.cdi_seal, salt, identifier)?;
57 Ok(key)
58 }
59}
60
Andrew Sculld64ae7d2022-10-05 17:41:43 +000061/// Artifacts that are mapped into the process address space from the driver.
62pub enum DiceDriver<'a> {
63 Real {
64 driver_path: PathBuf,
65 mmap_addr: *mut c_void,
66 mmap_size: usize,
67 cdi_attest: &'a [u8; CDI_SIZE],
68 cdi_seal: &'a [u8; CDI_SIZE],
69 bcc: &'a [u8],
70 },
71 Fake(DiceContext),
72}
73
74impl DiceDriver<'_> {
75 pub fn new(driver_path: &Path) -> Result<Self> {
76 if driver_path.exists() {
77 log::info!("Using DICE values from driver");
78 } else if super::is_strict_boot() {
79 bail!("Strict boot requires DICE value from driver but none were found");
80 } else {
81 log::warn!("Using sample DICE values");
Alice Wangf4b8b002023-02-08 08:53:23 +000082 let dice_artifacts = diced_sample_inputs::make_sample_bcc_and_cdis()
Andrew Sculld64ae7d2022-10-05 17:41:43 +000083 .expect("Failed to create sample dice artifacts.");
Alice Wangf4b8b002023-02-08 08:53:23 +000084 return Ok(Self::Fake(dice_artifacts.into()));
Andrew Sculld64ae7d2022-10-05 17:41:43 +000085 };
86
87 let mut file = fs::File::open(driver_path)
88 .map_err(|error| Error::new(error).context("Opening driver"))?;
89 let mmap_size =
90 file.read_u64::<NativeEndian>()
91 .map_err(|error| Error::new(error).context("Reading driver"))? as usize;
92 // It's safe to map the driver as the service will only create a single
93 // mapping per process.
94 let mmap_addr = unsafe {
95 let fd = file.as_raw_fd();
96 mmap(null_mut(), mmap_size, PROT_READ, MAP_PRIVATE, fd, 0)
97 };
98 if mmap_addr == MAP_FAILED {
99 bail!("Failed to mmap {:?}", driver_path);
100 }
101 // The slice is created for the region of memory that was just
102 // successfully mapped into the process address space so it will be
103 // accessible and not referenced from anywhere else.
104 let mmap_buf =
105 unsafe { slice::from_raw_parts((mmap_addr as *const u8).as_ref().unwrap(), mmap_size) };
106 // Very inflexible parsing / validation of the BccHandover data. Assumes deterministically
107 // encoded CBOR.
108 //
109 // BccHandover = {
110 // 1 : bstr .size 32, ; CDI_Attest
111 // 2 : bstr .size 32, ; CDI_Seal
112 // 3 : Bcc, ; Certificate chain
113 // }
114 if mmap_buf[0..4] != [0xa3, 0x01, 0x58, 0x20]
115 || mmap_buf[36..39] != [0x02, 0x58, 0x20]
116 || mmap_buf[71] != 0x03
117 {
118 bail!("BccHandover format mismatch");
119 }
120 Ok(Self::Real {
121 driver_path: driver_path.to_path_buf(),
122 mmap_addr,
123 mmap_size,
124 cdi_attest: mmap_buf[4..36].try_into().unwrap(),
125 cdi_seal: mmap_buf[39..71].try_into().unwrap(),
126 bcc: &mmap_buf[72..],
127 })
128 }
129
130 pub fn get_sealing_key(&self, identifier: &[u8]) -> Result<ZVec> {
131 // Deterministically derive a key to use for sealing data, rather than using the CDI
132 // directly, so we have the chance to rotate the key if needed. A salt isn't needed as the
133 // input key material is already cryptographically strong.
134 let cdi_seal = match self {
135 Self::Real { cdi_seal, .. } => cdi_seal,
136 Self::Fake(fake) => &fake.cdi_seal,
137 };
138 let salt = &[];
139 let mut key = ZVec::new(32)?;
140 hkdf(&mut key, Md::sha256(), cdi_seal, salt, identifier)?;
141 Ok(key)
142 }
143
144 pub fn derive(
145 self,
Alice Wang5aeed332023-02-02 09:42:21 +0000146 code_hash: Hash,
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000147 config_desc: &[u8],
Alice Wang5aeed332023-02-02 09:42:21 +0000148 authority_hash: Hash,
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000149 debug: bool,
Alice Wang5aeed332023-02-02 09:42:21 +0000150 hidden: Hidden,
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000151 ) -> Result<DiceContext> {
Alice Wanga7773662023-02-03 09:37:17 +0000152 let input_values = InputValues::new(
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000153 code_hash,
154 Config::Descriptor(config_desc),
155 authority_hash,
Alice Wang31226132023-01-31 12:44:39 +0000156 if debug { DiceMode::kDiceModeDebug } else { DiceMode::kDiceModeNormal },
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000157 hidden,
158 );
159 let (cdi_attest, cdi_seal, bcc) = match &self {
160 Self::Real { cdi_attest, cdi_seal, bcc, .. } => (*cdi_attest, *cdi_seal, *bcc),
161 Self::Fake(fake) => (&fake.cdi_attest, &fake.cdi_seal, fake.bcc.as_slice()),
162 };
Alice Wangf4b8b002023-02-08 08:53:23 +0000163 let dice_artifacts = retry_bcc_main_flow(cdi_attest, cdi_seal, bcc, &input_values)
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000164 .context("DICE derive from driver")?;
165 if let Self::Real { driver_path, .. } = &self {
166 // Writing to the device wipes the artifacts. The string is ignored by the driver but
167 // included for documentation.
168 fs::write(driver_path, "wipe")
169 .map_err(|err| Error::new(err).context("Wiping driver"))?;
170 }
Alice Wangf4b8b002023-02-08 08:53:23 +0000171 Ok(dice_artifacts.into())
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000172 }
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}