Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/measure/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ ureq = "3"
rsa = "0.9"
x509-parser = { version = "0.18", features = ["verify"] }
prost = "0.14"
fatfs = { version = "0.3.6", default-features = false, features = ["std", "alloc"] }
flate2 = "1.1.9"
tar = "0.4.46"

[dev-dependencies]
tempfile = "3"
Expand Down
22 changes: 22 additions & 0 deletions crates/measure/src/dcap/gpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,28 @@ pub(super) fn disk_guid_hash(uki_size: u64) -> [u8; 48] {
Sha384::digest(&blob).into()
}

/// Calculate UEFI GPT event hash from rootfs disk image GPT header
pub(crate) fn disk_guid_hash_from_header(raw: &[u8]) -> [u8; 48] {
const SECTOR: usize = 512;
let header = &raw[SECTOR..SECTOR + 92];
let num_entries =
u32::from_le_bytes(raw[SECTOR + 80..SECTOR + 84].try_into().unwrap()) as usize;
let entry_size = u32::from_le_bytes(raw[SECTOR + 84..SECTOR + 88].try_into().unwrap()) as usize;
let array = &raw[2 * SECTOR..2 * SECTOR + num_entries * entry_size];

// Skip partitions with type GUID 000...
let used: Vec<&[u8]> =
array.chunks_exact(entry_size).filter(|e| e[..16].iter().any(|&b| b != 0)).collect();

let mut blob = Vec::with_capacity(92 + 8 + used.len() * entry_size);
blob.extend_from_slice(header);
blob.extend_from_slice(&(used.len() as u64).to_le_bytes());
for e in &used {
blob.extend_from_slice(e);
}
Sha384::digest(&blob).into()
}

/// 92-byte GPT primary header with empty HeaderCRC32
fn build_header(disk_size_sectors: u64, partition_array_crc: u32) -> Vec<u8> {
let mut h = Vec::with_capacity(92);
Expand Down
4 changes: 2 additions & 2 deletions crates/measure/src/dcap/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub mod gcp;
pub mod secure_boot;
pub mod self_hosted;

mod gpt;
pub(crate) mod gpt;
mod tdvf;
pub use firmware::{DcapFirmware, FirmwareError, GoogleError, HobTemplate};
use serde::Serialize;
Expand Down Expand Up @@ -51,7 +51,7 @@ pub fn measure(uki: &Uki) -> DcapImageHashes {
kernel_authenticode: uki.kernel_authenticode_sha384,
cmdline_hash: sha384(&to_utf16le_null_terminated(&uki.cmdline)),
initrd_hash: uki.section(".initrd").expect("UKI missing .initrd section").digest_sha384,
gpt_disk_guid_hash: gpt::disk_guid_hash(uki.size),
gpt_disk_guid_hash: uki.disk_guid_hash.unwrap_or_else(|| gpt::disk_guid_hash(uki.size)),
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/measure/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub trait Measurement {
fn debug_json(&self) -> serde_json::Value;
}

/// Produces a portable measurement from a UKI file
/// Produces portable measurement from `.efi`, `.raw`, or `.tar.gz` image
pub fn measure(uki_data: &[u8]) -> Result<PortableMeasurements, UkiError> {
let uki = Uki::parse(uki_data)?;
Ok(PortableMeasurements {
Expand Down
54 changes: 54 additions & 0 deletions crates/measure/src/uki.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::io::{Cursor, Read};

use authenticode::{PeOffsetError, authenticode_digest};
use object::{Object, ObjectSection, read::pe::PeFile64};
use sha2::{Digest, Sha256, Sha384};
Expand All @@ -9,6 +11,8 @@ pub enum UkiError {
Pe(#[from] object::read::Error),
#[error("authenticode digest: {0}")]
Authenticode(#[from] PeOffsetError),
#[error("disk image: {0}")]
Disk(&'static str),
}

/// Parsed UKI with pre-computed digests
Expand All @@ -20,6 +24,8 @@ pub struct Uki {
pub kernel_authenticode_sha384: [u8; 48],
pub kernel_authenticode_sha256: [u8; 32],
pub cmdline: Vec<u8>,
/// Only needed when the UKI is embedded in a disk image with a rootfs
pub disk_guid_hash: Option<[u8; 48]>,
}

pub struct UkiSection {
Expand All @@ -36,7 +42,23 @@ const UKI_MEASURED_SECTIONS: &[&str] =
&[".linux", ".osrel", ".cmdline", ".initrd", ".splash", ".dtb", ".uname", ".sbat", ".pcrkey"];

impl Uki {
/// Parse a UKI file (`.efi`) or a disk image (`.raw` / `.tar.gz`)
/// Disk images are only needed when there's a separate rootfs
pub fn parse(data: &[u8]) -> Result<Self, UkiError> {
if data.starts_with(&[0x1f, 0x8b]) {
// GCP .tar.gz containing .raw disk image containing UKI
Self::parse(&untar_disk_raw(data)?)
} else if data.get(512..520) == Some(b"EFI PART".as_slice()) {
// .raw disk image containing UKI
let disk_guid_hash = crate::dcap::gpt::disk_guid_hash_from_header(data);
Self::parse_pe(&extract_uki(data)?, Some(disk_guid_hash))
} else {
// Only UKI with no rootfs
Self::parse_pe(data, None)
}
}

fn parse_pe(data: &[u8], disk_guid_hash: Option<[u8; 48]>) -> Result<Self, UkiError> {
let pe = PeFile64::parse(data)?;

let mut sections = Vec::new();
Expand Down Expand Up @@ -81,6 +103,7 @@ impl Uki {
kernel_authenticode_sha256,
sections,
cmdline,
disk_guid_hash,
})
}

Expand Down Expand Up @@ -130,3 +153,34 @@ fn section_measure_order(name: &str) -> Option<usize> {
fn should_measure(name: &str) -> bool {
UKI_MEASURED_SECTIONS.contains(&name) && name != ".pcrsig"
}

/// Extract `disk.raw` from a GCP .tar.gz
fn untar_disk_raw(targz: &[u8]) -> Result<Vec<u8>, UkiError> {
let err = |_| UkiError::Disk("invalid tar.gz");
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(targz));
let mut entry = archive
.entries()
.map_err(err)?
.next()
.ok_or(UkiError::Disk("empty tar.gz"))?
.map_err(err)?;
let mut raw = Vec::new();
entry.read_to_end(&mut raw).map_err(err)?;
Ok(raw)
}

// Extract UKI from a disk image
fn extract_uki(disk: &[u8]) -> Result<Vec<u8>, UkiError> {
let entry = disk.get(1024..1152).ok_or(UkiError::Disk("no partition table"))?; // LBA 2
let start = u64::from_le_bytes(entry[32..40].try_into().unwrap()) as usize;
let end = u64::from_le_bytes(entry[40..48].try_into().unwrap()) as usize;
let esp = disk.get(start * 512..(end + 1) * 512).ok_or(UkiError::Disk("bad ESP bounds"))?;
let fs = fatfs::FileSystem::new(Cursor::new(esp.to_vec()), fatfs::FsOptions::new())
.map_err(|_| UkiError::Disk("invalid ESP filesystem"))?;
let mut uki = Vec::new();
fs.root_dir()
.open_file("EFI/BOOT/BOOTX64.EFI")
.and_then(|mut f| f.read_to_end(&mut uki))
.map_err(|_| UkiError::Disk("could not read UKI from ESP"))?;
Ok(uki)
}