blob: f2b34da37fa664f21b33d608cd07728378a7fcf4 [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
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000017use crate::crypto;
18use crate::crypto::hkdf_sh512;
19use crate::crypto::AeadCtx;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000020use crate::dice::PartialInputs;
21use crate::gpt;
22use crate::gpt::Partition;
23use crate::gpt::Partitions;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000024use core::fmt;
25use core::mem::size_of;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000026use diced_open_dice::DiceMode;
27use diced_open_dice::Hash;
28use diced_open_dice::Hidden;
29use log::trace;
30use uuid::Uuid;
Alice Wang0e086232023-06-12 13:47:40 +000031use virtio_drivers::transport::{pci::bus::PciRoot, DeviceType, Transport};
Pierre-Clément Tosi3e3d7332023-06-22 10:44:29 +000032use vmbase::rand;
Alice Wangeacb7382023-06-05 12:53:54 +000033use vmbase::util::ceiling_div;
Alice Wang0e086232023-06-12 13:47:40 +000034use vmbase::virtio::pci::{PciTransportIterator, VirtIOBlk};
Alice Wang7c55c7d2023-07-05 14:51:40 +000035use vmbase::virtio::HalImpl;
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +010036use zerocopy::AsBytes;
37use zerocopy::FromBytes;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000038
39pub enum Error {
40 /// Unexpected I/O error while accessing the underlying disk.
41 FailedIo(gpt::Error),
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000042 /// Failed to decrypt the entry.
43 FailedOpen(crypto::ErrorIterator),
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000044 /// Failed to generate a random salt to be stored.
45 FailedSaltGeneration(rand::Error),
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000046 /// Failed to encrypt the entry.
47 FailedSeal(crypto::ErrorIterator),
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000048 /// Impossible to create a new instance.img entry.
49 InstanceImageFull,
50 /// Badly formatted instance.img header block.
51 InvalidInstanceImageHeader,
52 /// No instance.img ("vm-instance") partition found.
53 MissingInstanceImage,
54 /// The instance.img doesn't contain a header.
55 MissingInstanceImageHeader,
56 /// Authority hash found in the pvmfw instance.img entry doesn't match the trusted public key.
57 RecordedAuthHashMismatch,
58 /// Code hash found in the pvmfw instance.img entry doesn't match the inputs.
59 RecordedCodeHashMismatch,
60 /// DICE mode found in the pvmfw instance.img entry doesn't match the current one.
61 RecordedDiceModeMismatch,
62 /// Size of the instance.img entry being read or written is not supported.
63 UnsupportedEntrySize(usize),
Alice Wang0e086232023-06-12 13:47:40 +000064 /// Failed to create VirtIO Block device.
65 VirtIOBlkCreationFailed(virtio_drivers::Error),
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000066}
67
68impl fmt::Display for Error {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 match self {
71 Self::FailedIo(e) => write!(f, "Failed I/O to disk: {e}"),
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000072 Self::FailedOpen(e_iter) => {
73 writeln!(f, "Failed to open the instance.img partition:")?;
74 for e in *e_iter {
75 writeln!(f, "\t{e}")?;
76 }
77 Ok(())
78 }
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000079 Self::FailedSaltGeneration(e) => write!(f, "Failed to generate salt: {e}"),
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000080 Self::FailedSeal(e_iter) => {
81 writeln!(f, "Failed to seal the instance.img partition:")?;
82 for e in *e_iter {
83 writeln!(f, "\t{e}")?;
84 }
85 Ok(())
86 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000087 Self::InstanceImageFull => write!(f, "Failed to obtain a free instance.img partition"),
88 Self::InvalidInstanceImageHeader => write!(f, "instance.img header is invalid"),
89 Self::MissingInstanceImage => write!(f, "Failed to find the instance.img partition"),
90 Self::MissingInstanceImageHeader => write!(f, "instance.img header is missing"),
91 Self::RecordedAuthHashMismatch => write!(f, "Recorded authority hash doesn't match"),
92 Self::RecordedCodeHashMismatch => write!(f, "Recorded code hash doesn't match"),
93 Self::RecordedDiceModeMismatch => write!(f, "Recorded DICE mode doesn't match"),
94 Self::UnsupportedEntrySize(sz) => write!(f, "Invalid entry size: {sz}"),
Alice Wang0e086232023-06-12 13:47:40 +000095 Self::VirtIOBlkCreationFailed(e) => {
96 write!(f, "Failed to create VirtIO Block device: {e}")
97 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000098 }
99 }
100}
101
102pub type Result<T> = core::result::Result<T, Error>;
103
104pub fn get_or_generate_instance_salt(
105 pci_root: &mut PciRoot,
106 dice_inputs: &PartialInputs,
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000107 secret: &[u8],
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000108) -> Result<(bool, Hidden)> {
109 let mut instance_img = find_instance_img(pci_root)?;
110
111 let entry = locate_entry(&mut instance_img)?;
112 trace!("Found pvmfw instance.img entry: {entry:?}");
113
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000114 let key = hkdf_sh512::<32>(secret, /*salt=*/ &[], b"vm-instance");
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000115 let mut blk = [0; BLK_SIZE];
116 match entry {
117 PvmfwEntry::Existing { header_index, payload_size } => {
118 if payload_size > blk.len() {
119 // We currently only support single-blk entries.
120 return Err(Error::UnsupportedEntrySize(payload_size));
121 }
122 let payload_index = header_index + 1;
123 instance_img.read_block(payload_index, &mut blk).map_err(Error::FailedIo)?;
124
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000125 let payload = &blk[..payload_size];
126 let mut entry = [0; size_of::<EntryBody>()];
127 let key = key.map_err(Error::FailedOpen)?;
128 let aead = AeadCtx::new_aes_256_gcm_randnonce(&key).map_err(Error::FailedOpen)?;
129 let decrypted = aead.open(&mut entry, payload).map_err(Error::FailedOpen)?;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000130
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100131 let body = EntryBody::read_from(decrypted).unwrap();
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000132 if body.code_hash != dice_inputs.code_hash {
133 Err(Error::RecordedCodeHashMismatch)
134 } else if body.auth_hash != dice_inputs.auth_hash {
135 Err(Error::RecordedAuthHashMismatch)
136 } else if body.mode() != dice_inputs.mode {
137 Err(Error::RecordedDiceModeMismatch)
138 } else {
139 Ok((false, body.salt))
140 }
141 }
142 PvmfwEntry::New { header_index } => {
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000143 let salt = rand::random_array().map_err(Error::FailedSaltGeneration)?;
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100144 let body = EntryBody::new(dice_inputs, &salt);
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000145
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000146 let key = key.map_err(Error::FailedSeal)?;
147 let aead = AeadCtx::new_aes_256_gcm_randnonce(&key).map_err(Error::FailedSeal)?;
148 // We currently only support single-blk entries.
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100149 let plaintext = body.as_bytes();
150 assert!(plaintext.len() + aead.aead().unwrap().max_overhead() < blk.len());
151 let encrypted = aead.seal(&mut blk, plaintext).map_err(Error::FailedSeal)?;
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000152 let payload_size = encrypted.len();
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000153 let payload_index = header_index + 1;
154 instance_img.write_block(payload_index, &blk).map_err(Error::FailedIo)?;
155
156 let header = EntryHeader::new(PvmfwEntry::UUID, payload_size);
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100157 header.write_to_prefix(blk.as_mut_slice()).unwrap();
158 blk[header.as_bytes().len()..].fill(0);
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000159 instance_img.write_block(header_index, &blk).map_err(Error::FailedIo)?;
160
161 Ok((true, salt))
162 }
163 }
164}
165
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100166#[derive(FromBytes)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000167#[repr(C, packed)]
168struct Header {
169 magic: [u8; Header::MAGIC.len()],
170 version: u16,
171}
172
173impl Header {
174 const MAGIC: &[u8] = b"Android-VM-instance";
175 const VERSION_1: u16 = 1;
176
177 pub fn is_valid(&self) -> bool {
178 self.magic == Self::MAGIC && self.version() == Self::VERSION_1
179 }
180
181 fn version(&self) -> u16 {
182 u16::from_le(self.version)
183 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000184}
185
186fn find_instance_img(pci_root: &mut PciRoot) -> Result<Partition> {
Alice Wang7c55c7d2023-07-05 14:51:40 +0000187 for transport in PciTransportIterator::<HalImpl>::new(pci_root)
188 .filter(|t| DeviceType::Block == t.device_type())
Alice Wang0e086232023-06-12 13:47:40 +0000189 {
Alice Wang7c55c7d2023-07-05 14:51:40 +0000190 let device =
191 VirtIOBlk::<HalImpl>::new(transport).map_err(Error::VirtIOBlkCreationFailed)?;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000192 match Partition::get_by_name(device, "vm-instance") {
193 Ok(Some(p)) => return Ok(p),
194 Ok(None) => {}
195 Err(e) => log::warn!("error while reading from disk: {e}"),
196 };
197 }
198
199 Err(Error::MissingInstanceImage)
200}
201
202#[derive(Debug)]
203enum PvmfwEntry {
204 Existing { header_index: usize, payload_size: usize },
205 New { header_index: usize },
206}
207
208const BLK_SIZE: usize = Partitions::LBA_SIZE;
209
210impl PvmfwEntry {
211 const UUID: Uuid = Uuid::from_u128(0x90d2174a038a4bc6adf3824848fc5825);
212}
213
214fn locate_entry(partition: &mut Partition) -> Result<PvmfwEntry> {
215 let mut blk = [0; BLK_SIZE];
216 let mut indices = partition.indices();
217 let header_index = indices.next().ok_or(Error::MissingInstanceImageHeader)?;
218 partition.read_block(header_index, &mut blk).map_err(Error::FailedIo)?;
219 // The instance.img header is only used for discovery/validation.
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100220 let header = Header::read_from_prefix(blk.as_slice()).unwrap();
221 if !header.is_valid() {
222 return Err(Error::InvalidInstanceImageHeader);
223 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000224
225 while let Some(header_index) = indices.next() {
226 partition.read_block(header_index, &mut blk).map_err(Error::FailedIo)?;
227
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100228 let header = EntryHeader::read_from_prefix(blk.as_slice()).unwrap();
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000229 match (header.uuid(), header.payload_size()) {
230 (uuid, _) if uuid.is_nil() => return Ok(PvmfwEntry::New { header_index }),
231 (PvmfwEntry::UUID, payload_size) => {
232 return Ok(PvmfwEntry::Existing { header_index, payload_size })
233 }
234 (uuid, payload_size) => {
235 trace!("Skipping instance.img entry {uuid}: {payload_size:?} bytes");
236 let n = ceiling_div(payload_size, BLK_SIZE).unwrap();
237 if n > 0 {
238 let _ = indices.nth(n - 1); // consume
239 }
240 }
241 };
242 }
243
244 Err(Error::InstanceImageFull)
245}
246
247/// Marks the start of an instance.img entry.
248///
249/// Note: Virtualization/microdroid_manager/src/instance.rs uses the name "partition".
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100250#[derive(AsBytes, FromBytes)]
251#[repr(C, packed)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000252struct EntryHeader {
253 uuid: u128,
254 payload_size: u64,
255}
256
257impl EntryHeader {
258 fn new(uuid: Uuid, payload_size: usize) -> Self {
Pierre-Clément Tosiafb126a2023-03-29 14:42:19 +0100259 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 +0000260 }
261
262 fn uuid(&self) -> Uuid {
Pierre-Clément Tosiafb126a2023-03-29 14:42:19 +0100263 Uuid::from_u128_le(self.uuid)
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000264 }
265
266 fn payload_size(&self) -> usize {
267 usize::try_from(u64::from_le(self.payload_size)).unwrap()
268 }
269}
270
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100271#[derive(AsBytes, FromBytes)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000272#[repr(C)]
273struct EntryBody {
274 code_hash: Hash,
275 auth_hash: Hash,
276 salt: Hidden,
277 mode: u8,
278}
279
280impl EntryBody {
281 fn new(dice_inputs: &PartialInputs, salt: &Hidden) -> Self {
282 let mode = match dice_inputs.mode {
283 DiceMode::kDiceModeNotInitialized => 0,
284 DiceMode::kDiceModeNormal => 1,
285 DiceMode::kDiceModeDebug => 2,
286 DiceMode::kDiceModeMaintenance => 3,
287 };
288
289 Self {
290 code_hash: dice_inputs.code_hash,
291 auth_hash: dice_inputs.auth_hash,
292 salt: *salt,
293 mode,
294 }
295 }
296
297 fn mode(&self) -> DiceMode {
298 match self.mode {
299 1 => DiceMode::kDiceModeNormal,
300 2 => DiceMode::kDiceModeDebug,
301 3 => DiceMode::kDiceModeMaintenance,
302 _ => DiceMode::kDiceModeNotInitialized,
303 }
304 }
305}