blob: 10355598d319617c915d9324883ea6de1897bc36 [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};
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +010035use zerocopy::AsBytes;
36use zerocopy::FromBytes;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000037
38pub enum Error {
39 /// Unexpected I/O error while accessing the underlying disk.
40 FailedIo(gpt::Error),
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000041 /// Failed to decrypt the entry.
42 FailedOpen(crypto::ErrorIterator),
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000043 /// Failed to generate a random salt to be stored.
44 FailedSaltGeneration(rand::Error),
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000045 /// Failed to encrypt the entry.
46 FailedSeal(crypto::ErrorIterator),
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000047 /// Impossible to create a new instance.img entry.
48 InstanceImageFull,
49 /// Badly formatted instance.img header block.
50 InvalidInstanceImageHeader,
51 /// No instance.img ("vm-instance") partition found.
52 MissingInstanceImage,
53 /// The instance.img doesn't contain a header.
54 MissingInstanceImageHeader,
55 /// Authority hash found in the pvmfw instance.img entry doesn't match the trusted public key.
56 RecordedAuthHashMismatch,
57 /// Code hash found in the pvmfw instance.img entry doesn't match the inputs.
58 RecordedCodeHashMismatch,
59 /// DICE mode found in the pvmfw instance.img entry doesn't match the current one.
60 RecordedDiceModeMismatch,
61 /// Size of the instance.img entry being read or written is not supported.
62 UnsupportedEntrySize(usize),
Alice Wang0e086232023-06-12 13:47:40 +000063 /// Failed to create VirtIO Block device.
64 VirtIOBlkCreationFailed(virtio_drivers::Error),
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000065}
66
67impl fmt::Display for Error {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 match self {
70 Self::FailedIo(e) => write!(f, "Failed I/O to disk: {e}"),
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000071 Self::FailedOpen(e_iter) => {
72 writeln!(f, "Failed to open the instance.img partition:")?;
73 for e in *e_iter {
74 writeln!(f, "\t{e}")?;
75 }
76 Ok(())
77 }
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000078 Self::FailedSaltGeneration(e) => write!(f, "Failed to generate salt: {e}"),
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +000079 Self::FailedSeal(e_iter) => {
80 writeln!(f, "Failed to seal the instance.img partition:")?;
81 for e in *e_iter {
82 writeln!(f, "\t{e}")?;
83 }
84 Ok(())
85 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000086 Self::InstanceImageFull => write!(f, "Failed to obtain a free instance.img partition"),
87 Self::InvalidInstanceImageHeader => write!(f, "instance.img header is invalid"),
88 Self::MissingInstanceImage => write!(f, "Failed to find the instance.img partition"),
89 Self::MissingInstanceImageHeader => write!(f, "instance.img header is missing"),
90 Self::RecordedAuthHashMismatch => write!(f, "Recorded authority hash doesn't match"),
91 Self::RecordedCodeHashMismatch => write!(f, "Recorded code hash doesn't match"),
92 Self::RecordedDiceModeMismatch => write!(f, "Recorded DICE mode doesn't match"),
93 Self::UnsupportedEntrySize(sz) => write!(f, "Invalid entry size: {sz}"),
Alice Wang0e086232023-06-12 13:47:40 +000094 Self::VirtIOBlkCreationFailed(e) => {
95 write!(f, "Failed to create VirtIO Block device: {e}")
96 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +000097 }
98 }
99}
100
101pub type Result<T> = core::result::Result<T, Error>;
102
103pub fn get_or_generate_instance_salt(
104 pci_root: &mut PciRoot,
105 dice_inputs: &PartialInputs,
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000106 secret: &[u8],
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000107) -> Result<(bool, Hidden)> {
108 let mut instance_img = find_instance_img(pci_root)?;
109
110 let entry = locate_entry(&mut instance_img)?;
111 trace!("Found pvmfw instance.img entry: {entry:?}");
112
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000113 let key = hkdf_sh512::<32>(secret, /*salt=*/ &[], b"vm-instance");
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000114 let mut blk = [0; BLK_SIZE];
115 match entry {
116 PvmfwEntry::Existing { header_index, payload_size } => {
117 if payload_size > blk.len() {
118 // We currently only support single-blk entries.
119 return Err(Error::UnsupportedEntrySize(payload_size));
120 }
121 let payload_index = header_index + 1;
122 instance_img.read_block(payload_index, &mut blk).map_err(Error::FailedIo)?;
123
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000124 let payload = &blk[..payload_size];
125 let mut entry = [0; size_of::<EntryBody>()];
126 let key = key.map_err(Error::FailedOpen)?;
127 let aead = AeadCtx::new_aes_256_gcm_randnonce(&key).map_err(Error::FailedOpen)?;
128 let decrypted = aead.open(&mut entry, payload).map_err(Error::FailedOpen)?;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000129
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100130 let body = EntryBody::read_from(decrypted).unwrap();
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000131 if body.code_hash != dice_inputs.code_hash {
132 Err(Error::RecordedCodeHashMismatch)
133 } else if body.auth_hash != dice_inputs.auth_hash {
134 Err(Error::RecordedAuthHashMismatch)
135 } else if body.mode() != dice_inputs.mode {
136 Err(Error::RecordedDiceModeMismatch)
137 } else {
138 Ok((false, body.salt))
139 }
140 }
141 PvmfwEntry::New { header_index } => {
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000142 let salt = rand::random_array().map_err(Error::FailedSaltGeneration)?;
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100143 let body = EntryBody::new(dice_inputs, &salt);
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000144
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000145 let key = key.map_err(Error::FailedSeal)?;
146 let aead = AeadCtx::new_aes_256_gcm_randnonce(&key).map_err(Error::FailedSeal)?;
147 // We currently only support single-blk entries.
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100148 let plaintext = body.as_bytes();
149 assert!(plaintext.len() + aead.aead().unwrap().max_overhead() < blk.len());
150 let encrypted = aead.seal(&mut blk, plaintext).map_err(Error::FailedSeal)?;
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000151 let payload_size = encrypted.len();
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000152 let payload_index = header_index + 1;
153 instance_img.write_block(payload_index, &blk).map_err(Error::FailedIo)?;
154
155 let header = EntryHeader::new(PvmfwEntry::UUID, payload_size);
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100156 header.write_to_prefix(blk.as_mut_slice()).unwrap();
157 blk[header.as_bytes().len()..].fill(0);
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000158 instance_img.write_block(header_index, &blk).map_err(Error::FailedIo)?;
159
160 Ok((true, salt))
161 }
162 }
163}
164
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100165#[derive(FromBytes)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000166#[repr(C, packed)]
167struct Header {
168 magic: [u8; Header::MAGIC.len()],
169 version: u16,
170}
171
172impl Header {
173 const MAGIC: &[u8] = b"Android-VM-instance";
174 const VERSION_1: u16 = 1;
175
176 pub fn is_valid(&self) -> bool {
177 self.magic == Self::MAGIC && self.version() == Self::VERSION_1
178 }
179
180 fn version(&self) -> u16 {
181 u16::from_le(self.version)
182 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000183}
184
185fn find_instance_img(pci_root: &mut PciRoot) -> Result<Partition> {
Alice Wang0e086232023-06-12 13:47:40 +0000186 for transport in
187 PciTransportIterator::new(pci_root).filter(|t| DeviceType::Block == t.device_type())
188 {
189 let device = VirtIOBlk::new(transport).map_err(Error::VirtIOBlkCreationFailed)?;
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000190 match Partition::get_by_name(device, "vm-instance") {
191 Ok(Some(p)) => return Ok(p),
192 Ok(None) => {}
193 Err(e) => log::warn!("error while reading from disk: {e}"),
194 };
195 }
196
197 Err(Error::MissingInstanceImage)
198}
199
200#[derive(Debug)]
201enum PvmfwEntry {
202 Existing { header_index: usize, payload_size: usize },
203 New { header_index: usize },
204}
205
206const BLK_SIZE: usize = Partitions::LBA_SIZE;
207
208impl PvmfwEntry {
209 const UUID: Uuid = Uuid::from_u128(0x90d2174a038a4bc6adf3824848fc5825);
210}
211
212fn locate_entry(partition: &mut Partition) -> Result<PvmfwEntry> {
213 let mut blk = [0; BLK_SIZE];
214 let mut indices = partition.indices();
215 let header_index = indices.next().ok_or(Error::MissingInstanceImageHeader)?;
216 partition.read_block(header_index, &mut blk).map_err(Error::FailedIo)?;
217 // The instance.img header is only used for discovery/validation.
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100218 let header = Header::read_from_prefix(blk.as_slice()).unwrap();
219 if !header.is_valid() {
220 return Err(Error::InvalidInstanceImageHeader);
221 }
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000222
223 while let Some(header_index) = indices.next() {
224 partition.read_block(header_index, &mut blk).map_err(Error::FailedIo)?;
225
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100226 let header = EntryHeader::read_from_prefix(blk.as_slice()).unwrap();
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000227 match (header.uuid(), header.payload_size()) {
228 (uuid, _) if uuid.is_nil() => return Ok(PvmfwEntry::New { header_index }),
229 (PvmfwEntry::UUID, payload_size) => {
230 return Ok(PvmfwEntry::Existing { header_index, payload_size })
231 }
232 (uuid, payload_size) => {
233 trace!("Skipping instance.img entry {uuid}: {payload_size:?} bytes");
234 let n = ceiling_div(payload_size, BLK_SIZE).unwrap();
235 if n > 0 {
236 let _ = indices.nth(n - 1); // consume
237 }
238 }
239 };
240 }
241
242 Err(Error::InstanceImageFull)
243}
244
245/// Marks the start of an instance.img entry.
246///
247/// Note: Virtualization/microdroid_manager/src/instance.rs uses the name "partition".
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100248#[derive(AsBytes, FromBytes)]
249#[repr(C, packed)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000250struct EntryHeader {
251 uuid: u128,
252 payload_size: u64,
253}
254
255impl EntryHeader {
256 fn new(uuid: Uuid, payload_size: usize) -> Self {
Pierre-Clément Tosiafb126a2023-03-29 14:42:19 +0100257 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 +0000258 }
259
260 fn uuid(&self) -> Uuid {
Pierre-Clément Tosiafb126a2023-03-29 14:42:19 +0100261 Uuid::from_u128_le(self.uuid)
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000262 }
263
264 fn payload_size(&self) -> usize {
265 usize::try_from(u64::from_le(self.payload_size)).unwrap()
266 }
267}
268
Pierre-Clément Tosi8ad980f2023-04-25 18:23:11 +0100269#[derive(AsBytes, FromBytes)]
Pierre-Clément Tosi1cc5eb72023-02-02 11:09:18 +0000270#[repr(C)]
271struct EntryBody {
272 code_hash: Hash,
273 auth_hash: Hash,
274 salt: Hidden,
275 mode: u8,
276}
277
278impl EntryBody {
279 fn new(dice_inputs: &PartialInputs, salt: &Hidden) -> Self {
280 let mode = match dice_inputs.mode {
281 DiceMode::kDiceModeNotInitialized => 0,
282 DiceMode::kDiceModeNormal => 1,
283 DiceMode::kDiceModeDebug => 2,
284 DiceMode::kDiceModeMaintenance => 3,
285 };
286
287 Self {
288 code_hash: dice_inputs.code_hash,
289 auth_hash: dice_inputs.auth_hash,
290 salt: *salt,
291 mode,
292 }
293 }
294
295 fn mode(&self) -> DiceMode {
296 match self.mode {
297 1 => DiceMode::kDiceModeNormal,
298 2 => DiceMode::kDiceModeDebug,
299 3 => DiceMode::kDiceModeMaintenance,
300 _ => DiceMode::kDiceModeNotInitialized,
301 }
302 }
303}