blob: 0ef57dc545dc252838dc0384e324b02014b24fe9 [file] [log] [blame]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +00001// Copyright 2023, 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//! Support for reading and writing to the instance.img.
16
17use crate::dice::PartialInputs;
18use crate::gpt;
19use crate::gpt::Partition;
20use crate::gpt::Partitions;
Alice Wangee07f722023-10-03 15:20:17 +000021use bssl_avf::{self, hkdf, Aead, AeadContext, Digester};
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000022use core::fmt;
23use core::mem::size_of;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000024use diced_open_dice::DiceMode;
25use diced_open_dice::Hash;
26use diced_open_dice::Hidden;
27use log::trace;
28use uuid::Uuid;
Alice Wang0e086232023-06-12 13:47:40 +000029use virtio_drivers::transport::{pci::bus::PciRoot, DeviceType, Transport};
Alice Wangeacb7382023-06-05 12:53:54 +000030use vmbase::util::ceiling_div;
Alice Wang0e086232023-06-12 13:47:40 +000031use vmbase::virtio::pci::{PciTransportIterator, VirtIOBlk};
Alice Wang7c55c7d2023-07-05 14:51:40 +000032use vmbase::virtio::HalImpl;
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +010033use zerocopy::AsBytes;
34use zerocopy::FromBytes;
Frederick Mayle2e779942023-10-15 18:27:31 +000035use zerocopy::FromZeroes;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000036
37pub enum Error {
38 /// Unexpected I/O error while accessing the underlying disk.
39 FailedIo(gpt::Error),
40 /// Impossible to create a new instance.img entry.
41 InstanceImageFull,
42 /// Badly formatted instance.img header block.
43 InvalidInstanceImageHeader,
44 /// No instance.img ("vm-instance") partition found.
45 MissingInstanceImage,
46 /// The instance.img doesn't contain a header.
47 MissingInstanceImageHeader,
48 /// Authority hash found in the pvmfw instance.img entry doesn't match the trusted public key.
49 RecordedAuthHashMismatch,
50 /// Code hash found in the pvmfw instance.img entry doesn't match the inputs.
51 RecordedCodeHashMismatch,
52 /// DICE mode found in the pvmfw instance.img entry doesn't match the current one.
53 RecordedDiceModeMismatch,
54 /// Size of the instance.img entry being read or written is not supported.
55 UnsupportedEntrySize(usize),
Alice Wang0e086232023-06-12 13:47:40 +000056 /// Failed to create VirtIO Block device.
57 VirtIOBlkCreationFailed(virtio_drivers::Error),
Alice Wang947f3f72023-09-29 09:04:07 +000058 /// An error happened during the interaction with BoringSSL.
59 BoringSslFailed(bssl_avf::Error),
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000060}
61
62impl fmt::Display for Error {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 match self {
65 Self::FailedIo(e) => write!(f, "Failed I/O to disk: {e}"),
66 Self::InstanceImageFull => write!(f, "Failed to obtain a free instance.img partition"),
67 Self::InvalidInstanceImageHeader => write!(f, "instance.img header is invalid"),
68 Self::MissingInstanceImage => write!(f, "Failed to find the instance.img partition"),
69 Self::MissingInstanceImageHeader => write!(f, "instance.img header is missing"),
70 Self::RecordedAuthHashMismatch => write!(f, "Recorded authority hash doesn't match"),
71 Self::RecordedCodeHashMismatch => write!(f, "Recorded code hash doesn't match"),
72 Self::RecordedDiceModeMismatch => write!(f, "Recorded DICE mode doesn't match"),
73 Self::UnsupportedEntrySize(sz) => write!(f, "Invalid entry size: {sz}"),
Alice Wang0e086232023-06-12 13:47:40 +000074 Self::VirtIOBlkCreationFailed(e) => {
75 write!(f, "Failed to create VirtIO Block device: {e}")
76 }
Alice Wang947f3f72023-09-29 09:04:07 +000077 Self::BoringSslFailed(e) => {
78 write!(f, "An error happened during the interaction with BoringSSL: {e}")
79 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000080 }
81 }
82}
83
Alice Wang947f3f72023-09-29 09:04:07 +000084impl From<bssl_avf::Error> for Error {
85 fn from(e: bssl_avf::Error) -> Self {
86 Self::BoringSslFailed(e)
87 }
88}
89
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000090pub type Result<T> = core::result::Result<T, Error>;
91
Shikha Panwar37490d42024-03-19 22:14:58 +000092fn aead_ctx_from_secret(secret: &[u8]) -> Result<AeadContext> {
93 let key = hkdf::<32>(secret, /* salt= */ &[], b"vm-instance", Digester::sha512())?;
94 Ok(AeadContext::new(Aead::aes_256_gcm_randnonce(), key.as_slice(), /* tag_len */ None)?)
95}
96
97/// Get the entry from instance.img. This method additionally returns Partition corresponding to
98/// pvmfw in the instance.img as well as index corresponding to empty header which can be used to
99/// record instance data with `record_instance_entry`.
100pub(crate) fn get_recorded_entry(
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000101 pci_root: &mut PciRoot,
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000102 secret: &[u8],
Shikha Panwar37490d42024-03-19 22:14:58 +0000103) -> Result<(Option<EntryBody>, Partition, usize)> {
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000104 let mut instance_img = find_instance_img(pci_root)?;
105
106 let entry = locate_entry(&mut instance_img)?;
107 trace!("Found pvmfw instance.img entry: {entry:?}");
108
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000109 match entry {
110 PvmfwEntry::Existing { header_index, payload_size } => {
Shikha Panwar37490d42024-03-19 22:14:58 +0000111 let aead_ctx = aead_ctx_from_secret(secret)?;
112 let mut blk = [0; BLK_SIZE];
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000113 if payload_size > blk.len() {
114 // We currently only support single-blk entries.
115 return Err(Error::UnsupportedEntrySize(payload_size));
116 }
117 let payload_index = header_index + 1;
118 instance_img.read_block(payload_index, &mut blk).map_err(Error::FailedIo)?;
119
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000120 let payload = &blk[..payload_size];
121 let mut entry = [0; size_of::<EntryBody>()];
Shikha Panwar37490d42024-03-19 22:14:58 +0000122 // The nonce is generated internally for `aes_256_gcm_randnonce`, so no additional
123 // nonce is required.
124 let decrypted =
125 aead_ctx.open(payload, /* nonce */ &[], /* ad */ &[], &mut entry)?;
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100126 let body = EntryBody::read_from(decrypted).unwrap();
Shikha Panwar37490d42024-03-19 22:14:58 +0000127 Ok((Some(body), instance_img, header_index))
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000128 }
Shikha Panwar37490d42024-03-19 22:14:58 +0000129 PvmfwEntry::New { header_index } => Ok((None, instance_img, header_index)),
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000130 }
131}
132
Shikha Panwar37490d42024-03-19 22:14:58 +0000133pub(crate) fn record_instance_entry(
134 body: &EntryBody,
135 secret: &[u8],
136 instance_img: &mut Partition,
137 header_index: usize,
138) -> Result<()> {
139 // We currently only support single-blk entries.
140 let mut blk = [0; BLK_SIZE];
141 let plaintext = body.as_bytes();
142 let aead_ctx = aead_ctx_from_secret(secret)?;
143 assert!(plaintext.len() + aead_ctx.aead().max_overhead() < blk.len());
144 let encrypted = aead_ctx.seal(plaintext, /* nonce */ &[], /* ad */ &[], &mut blk)?;
145 let payload_size = encrypted.len();
146 let payload_index = header_index + 1;
147 instance_img.write_block(payload_index, &blk).map_err(Error::FailedIo)?;
148
149 let header = EntryHeader::new(PvmfwEntry::UUID, payload_size);
150 header.write_to_prefix(blk.as_mut_slice()).unwrap();
151 blk[header.as_bytes().len()..].fill(0);
152 instance_img.write_block(header_index, &blk).map_err(Error::FailedIo)?;
153
154 Ok(())
155}
156
Frederick Mayle2e779942023-10-15 18:27:31 +0000157#[derive(FromZeroes, FromBytes)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000158#[repr(C, packed)]
159struct Header {
160 magic: [u8; Header::MAGIC.len()],
161 version: u16,
162}
163
164impl Header {
Chris Wailes9d09f572024-01-16 13:31:02 -0800165 const MAGIC: &'static [u8] = b"Android-VM-instance";
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000166 const VERSION_1: u16 = 1;
167
168 pub fn is_valid(&self) -> bool {
169 self.magic == Self::MAGIC && self.version() == Self::VERSION_1
170 }
171
172 fn version(&self) -> u16 {
173 u16::from_le(self.version)
174 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000175}
176
177fn find_instance_img(pci_root: &mut PciRoot) -> Result<Partition> {
Alice Wang7c55c7d2023-07-05 14:51:40 +0000178 for transport in PciTransportIterator::<HalImpl>::new(pci_root)
179 .filter(|t| DeviceType::Block == t.device_type())
Alice Wang0e086232023-06-12 13:47:40 +0000180 {
Alice Wang7c55c7d2023-07-05 14:51:40 +0000181 let device =
182 VirtIOBlk::<HalImpl>::new(transport).map_err(Error::VirtIOBlkCreationFailed)?;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000183 match Partition::get_by_name(device, "vm-instance") {
184 Ok(Some(p)) => return Ok(p),
185 Ok(None) => {}
186 Err(e) => log::warn!("error while reading from disk: {e}"),
187 };
188 }
189
190 Err(Error::MissingInstanceImage)
191}
192
193#[derive(Debug)]
194enum PvmfwEntry {
195 Existing { header_index: usize, payload_size: usize },
196 New { header_index: usize },
197}
198
199const BLK_SIZE: usize = Partitions::LBA_SIZE;
200
201impl PvmfwEntry {
202 const UUID: Uuid = Uuid::from_u128(0x90d2174a038a4bc6adf3824848fc5825);
203}
204
205fn locate_entry(partition: &mut Partition) -> Result<PvmfwEntry> {
206 let mut blk = [0; BLK_SIZE];
207 let mut indices = partition.indices();
208 let header_index = indices.next().ok_or(Error::MissingInstanceImageHeader)?;
209 partition.read_block(header_index, &mut blk).map_err(Error::FailedIo)?;
210 // The instance.img header is only used for discovery/validation.
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100211 let header = Header::read_from_prefix(blk.as_slice()).unwrap();
212 if !header.is_valid() {
213 return Err(Error::InvalidInstanceImageHeader);
214 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000215
216 while let Some(header_index) = indices.next() {
217 partition.read_block(header_index, &mut blk).map_err(Error::FailedIo)?;
218
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100219 let header = EntryHeader::read_from_prefix(blk.as_slice()).unwrap();
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000220 match (header.uuid(), header.payload_size()) {
221 (uuid, _) if uuid.is_nil() => return Ok(PvmfwEntry::New { header_index }),
222 (PvmfwEntry::UUID, payload_size) => {
223 return Ok(PvmfwEntry::Existing { header_index, payload_size })
224 }
225 (uuid, payload_size) => {
226 trace!("Skipping instance.img entry {uuid}: {payload_size:?} bytes");
227 let n = ceiling_div(payload_size, BLK_SIZE).unwrap();
228 if n > 0 {
229 let _ = indices.nth(n - 1); // consume
230 }
231 }
232 };
233 }
234
235 Err(Error::InstanceImageFull)
236}
237
238/// Marks the start of an instance.img entry.
239///
Jiyong Park7ec05d02024-07-22 12:26:04 +0900240/// Note: Virtualization/guest/microdroid_manager/src/instance.rs uses the name "partition".
Frederick Mayle2e779942023-10-15 18:27:31 +0000241#[derive(AsBytes, FromZeroes, FromBytes)]
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100242#[repr(C, packed)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000243struct EntryHeader {
244 uuid: u128,
245 payload_size: u64,
246}
247
248impl EntryHeader {
249 fn new(uuid: Uuid, payload_size: usize) -> Self {
Pierre-Clément Tosiafb126a2023-03-29 14:42:19 +0100250 Self { uuid: uuid.to_u128_le(), payload_size: u64::try_from(payload_size).unwrap().to_le() }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000251 }
252
253 fn uuid(&self) -> Uuid {
Pierre-Clément Tosiafb126a2023-03-29 14:42:19 +0100254 Uuid::from_u128_le(self.uuid)
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000255 }
256
257 fn payload_size(&self) -> usize {
258 usize::try_from(u64::from_le(self.payload_size)).unwrap()
259 }
260}
261
Frederick Mayle2e779942023-10-15 18:27:31 +0000262#[derive(AsBytes, FromZeroes, FromBytes)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000263#[repr(C)]
Shikha Panwar37490d42024-03-19 22:14:58 +0000264pub(crate) struct EntryBody {
265 pub code_hash: Hash,
266 pub auth_hash: Hash,
267 pub salt: Hidden,
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000268 mode: u8,
269}
270
271impl EntryBody {
Shikha Panwar37490d42024-03-19 22:14:58 +0000272 pub(crate) fn new(dice_inputs: &PartialInputs, salt: &Hidden) -> Self {
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000273 let mode = match dice_inputs.mode {
274 DiceMode::kDiceModeNotInitialized => 0,
275 DiceMode::kDiceModeNormal => 1,
276 DiceMode::kDiceModeDebug => 2,
277 DiceMode::kDiceModeMaintenance => 3,
278 };
279
280 Self {
281 code_hash: dice_inputs.code_hash,
282 auth_hash: dice_inputs.auth_hash,
283 salt: *salt,
284 mode,
285 }
286 }
287
Shikha Panwar37490d42024-03-19 22:14:58 +0000288 pub(crate) fn mode(&self) -> DiceMode {
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000289 match self.mode {
290 1 => DiceMode::kDiceModeNormal,
291 2 => DiceMode::kDiceModeDebug,
292 3 => DiceMode::kDiceModeMaintenance,
293 _ => DiceMode::kDiceModeNotInitialized,
294 }
295 }
296}