Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 1 | // 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 Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 17 | use crate::crypto; |
| 18 | use crate::crypto::hkdf_sh512; |
| 19 | use crate::crypto::AeadCtx; |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 20 | use crate::dice::PartialInputs; |
| 21 | use crate::gpt; |
| 22 | use crate::gpt::Partition; |
| 23 | use crate::gpt::Partitions; |
Pierre-Clément Tosi | a59103d | 2023-02-02 14:46:55 +0000 | [diff] [blame] | 24 | use crate::rand; |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 25 | use core::fmt; |
| 26 | use core::mem::size_of; |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 27 | use diced_open_dice::DiceMode; |
| 28 | use diced_open_dice::Hash; |
| 29 | use diced_open_dice::Hidden; |
| 30 | use log::trace; |
| 31 | use uuid::Uuid; |
Alice Wang | 0e08623 | 2023-06-12 13:47:40 +0000 | [diff] [blame] | 32 | use virtio_drivers::transport::{pci::bus::PciRoot, DeviceType, Transport}; |
Alice Wang | eacb738 | 2023-06-05 12:53:54 +0000 | [diff] [blame] | 33 | use vmbase::util::ceiling_div; |
Alice Wang | 0e08623 | 2023-06-12 13:47:40 +0000 | [diff] [blame] | 34 | use vmbase::virtio::pci::{PciTransportIterator, VirtIOBlk}; |
Pierre-Clément Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 35 | use zerocopy::AsBytes; |
| 36 | use zerocopy::FromBytes; |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 37 | |
| 38 | pub enum Error { |
| 39 | /// Unexpected I/O error while accessing the underlying disk. |
| 40 | FailedIo(gpt::Error), |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 41 | /// Failed to decrypt the entry. |
| 42 | FailedOpen(crypto::ErrorIterator), |
Pierre-Clément Tosi | a59103d | 2023-02-02 14:46:55 +0000 | [diff] [blame] | 43 | /// Failed to generate a random salt to be stored. |
| 44 | FailedSaltGeneration(rand::Error), |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 45 | /// Failed to encrypt the entry. |
| 46 | FailedSeal(crypto::ErrorIterator), |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 47 | /// 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 Wang | 0e08623 | 2023-06-12 13:47:40 +0000 | [diff] [blame] | 63 | /// Failed to create VirtIO Block device. |
| 64 | VirtIOBlkCreationFailed(virtio_drivers::Error), |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 65 | } |
| 66 | |
| 67 | impl 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 Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 71 | 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 Tosi | a59103d | 2023-02-02 14:46:55 +0000 | [diff] [blame] | 78 | Self::FailedSaltGeneration(e) => write!(f, "Failed to generate salt: {e}"), |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 79 | 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 Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 86 | 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 Wang | 0e08623 | 2023-06-12 13:47:40 +0000 | [diff] [blame] | 94 | Self::VirtIOBlkCreationFailed(e) => { |
| 95 | write!(f, "Failed to create VirtIO Block device: {e}") |
| 96 | } |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | pub type Result<T> = core::result::Result<T, Error>; |
| 102 | |
| 103 | pub fn get_or_generate_instance_salt( |
| 104 | pci_root: &mut PciRoot, |
| 105 | dice_inputs: &PartialInputs, |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 106 | secret: &[u8], |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 107 | ) -> 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 Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 113 | let key = hkdf_sh512::<32>(secret, /*salt=*/ &[], b"vm-instance"); |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 114 | 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 Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 124 | 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 Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 129 | |
Pierre-Clément Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 130 | let body = EntryBody::read_from(decrypted).unwrap(); |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 131 | 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 Tosi | a59103d | 2023-02-02 14:46:55 +0000 | [diff] [blame] | 142 | let salt = rand::random_array().map_err(Error::FailedSaltGeneration)?; |
Pierre-Clément Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 143 | let body = EntryBody::new(dice_inputs, &salt); |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 144 | |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 145 | 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 Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 148 | 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 Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 151 | let payload_size = encrypted.len(); |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 152 | 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 Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 156 | header.write_to_prefix(blk.as_mut_slice()).unwrap(); |
| 157 | blk[header.as_bytes().len()..].fill(0); |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 158 | instance_img.write_block(header_index, &blk).map_err(Error::FailedIo)?; |
| 159 | |
| 160 | Ok((true, salt)) |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
Pierre-Clément Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 165 | #[derive(FromBytes)] |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 166 | #[repr(C, packed)] |
| 167 | struct Header { |
| 168 | magic: [u8; Header::MAGIC.len()], |
| 169 | version: u16, |
| 170 | } |
| 171 | |
| 172 | impl 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 Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 183 | } |
| 184 | |
| 185 | fn find_instance_img(pci_root: &mut PciRoot) -> Result<Partition> { |
Alice Wang | 0e08623 | 2023-06-12 13:47:40 +0000 | [diff] [blame] | 186 | 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 Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 190 | 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)] |
| 201 | enum PvmfwEntry { |
| 202 | Existing { header_index: usize, payload_size: usize }, |
| 203 | New { header_index: usize }, |
| 204 | } |
| 205 | |
| 206 | const BLK_SIZE: usize = Partitions::LBA_SIZE; |
| 207 | |
| 208 | impl PvmfwEntry { |
| 209 | const UUID: Uuid = Uuid::from_u128(0x90d2174a038a4bc6adf3824848fc5825); |
| 210 | } |
| 211 | |
| 212 | fn 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 Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 218 | let header = Header::read_from_prefix(blk.as_slice()).unwrap(); |
| 219 | if !header.is_valid() { |
| 220 | return Err(Error::InvalidInstanceImageHeader); |
| 221 | } |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 222 | |
| 223 | while let Some(header_index) = indices.next() { |
| 224 | partition.read_block(header_index, &mut blk).map_err(Error::FailedIo)?; |
| 225 | |
Pierre-Clément Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 226 | let header = EntryHeader::read_from_prefix(blk.as_slice()).unwrap(); |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 227 | 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 Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 248 | #[derive(AsBytes, FromBytes)] |
| 249 | #[repr(C, packed)] |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 250 | struct EntryHeader { |
| 251 | uuid: u128, |
| 252 | payload_size: u64, |
| 253 | } |
| 254 | |
| 255 | impl EntryHeader { |
| 256 | fn new(uuid: Uuid, payload_size: usize) -> Self { |
Pierre-Clément Tosi | afb126a | 2023-03-29 14:42:19 +0100 | [diff] [blame] | 257 | Self { uuid: uuid.to_u128_le(), payload_size: u64::try_from(payload_size).unwrap().to_le() } |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 258 | } |
| 259 | |
| 260 | fn uuid(&self) -> Uuid { |
Pierre-Clément Tosi | afb126a | 2023-03-29 14:42:19 +0100 | [diff] [blame] | 261 | Uuid::from_u128_le(self.uuid) |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 262 | } |
| 263 | |
| 264 | fn payload_size(&self) -> usize { |
| 265 | usize::try_from(u64::from_le(self.payload_size)).unwrap() |
| 266 | } |
| 267 | } |
| 268 | |
Pierre-Clément Tosi | 8ad980f | 2023-04-25 18:23:11 +0100 | [diff] [blame] | 269 | #[derive(AsBytes, FromBytes)] |
Pierre-Clément Tosi | 1cc5eb7 | 2023-02-02 11:09:18 +0000 | [diff] [blame] | 270 | #[repr(C)] |
| 271 | struct EntryBody { |
| 272 | code_hash: Hash, |
| 273 | auth_hash: Hash, |
| 274 | salt: Hidden, |
| 275 | mode: u8, |
| 276 | } |
| 277 | |
| 278 | impl 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 | } |