diff --git a/docs/attestation-gcp.md b/docs/attestation-gcp.md index 408535cfed..ce53bf409e 100644 --- a/docs/attestation-gcp.md +++ b/docs/attestation-gcp.md @@ -43,6 +43,20 @@ Verification runs in `Attestation::verify_with_time` and splits into TDX + TPM. the UKI Authenticode hash inside that CBOR file with the GCP TPM PCR2 UKI event. +### TDX boot-chain verification +Images built with `measurement.gcp.cbor` version 2 also record the RTMR1 and +RTMR2 values that GCE's TDVF produces when it boots the image. For these +images the verifier checks the TDX boot chain in addition to the TPM +(`dstack_mr::gcp::verify_gcp_tdx_boot`): +1. **MRTD** must be one of the GCE TDVF builds listed in `dstack-mr/src/gcp.rs`. +2. **RTMR0** is replayed from the attested event log, which keeps every RTMR0 + event's digest. The TD HOB, configuration firmware volume and ACPI table + events must match values recomputed by the verifier from the machine shape + in the VM config (`cpu_count`, `memory_size`, `num_gpus`, `numa_nodes`), which + `dstack-cloud` fills in from the GCE machine type. `gcp-acpi` regenerates + the ACPI tables for that shape. +3. **RTMR1 and RTMR2** must equal the values in `measurement.gcp.cbor`. + ### Optional RA TLS binding If the verifier provides a RA TLS pubkey, it enforces: `report_data == QuoteContentType::RaTlsCert.to_report_data(pubkey)`. diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 58235be860..60d64f98a3 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -2310,6 +2310,7 @@ dependencies = [ "dstack-types", "flate2", "fs-err", + "gcp-acpi", "hex", "hex-literal", "log", @@ -3233,6 +3234,15 @@ dependencies = [ "slab", ] +[[package]] +name = "gcp-acpi" +version = "0.1.0" +dependencies = [ + "hex", + "sha2 0.10.9", + "thiserror 2.0.18", +] + [[package]] name = "generator" version = "0.7.5" diff --git a/dstack/Cargo.toml b/dstack/Cargo.toml index 9e38113ae7..a146b40766 100644 --- a/dstack/Cargo.toml +++ b/dstack/Cargo.toml @@ -75,6 +75,7 @@ members = [ "crates/build-info", "crates/mock-attestation", "crates/qemu-acpi", + "crates/gcp-acpi", "crates/pki-fetch", "crates/dstack-verifier-wasm", "tools/key-recovery", @@ -100,6 +101,7 @@ dstack-volume = { path = "crates/dstack-volume" } dstack-api-auth = { path = "crates/api-auth" } dstack-build-info = { path = "crates/build-info" } qemu-acpi = { path = "crates/qemu-acpi" } +gcp-acpi = { path = "crates/gcp-acpi" } pki-fetch = { path = "crates/pki-fetch" } cc-eventlog = { path = "cc-eventlog" } supervisor = { path = "supervisor" } diff --git a/dstack/crates/gcp-acpi/Cargo.toml b/dstack/crates/gcp-acpi/Cargo.toml new file mode 100644 index 0000000000..873ccdb952 --- /dev/null +++ b/dstack/crates/gcp-acpi/Cargo.toml @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "gcp-acpi" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Pure Rust generator for the ACPI blobs Google Compute Engine measures into TDX RTMR0" + +[dependencies] +thiserror.workspace = true + +[dev-dependencies] +hex = { workspace = true, features = ["alloc"] } +sha2.workspace = true diff --git a/dstack/crates/gcp-acpi/src/aml.rs b/dstack/crates/gcp-acpi/src/aml.rs new file mode 100644 index 0000000000..e912d75994 --- /dev/null +++ b/dstack/crates/gcp-acpi/src/aml.rs @@ -0,0 +1,374 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! A small AML encoder whose terms are plain byte vectors. +//! +//! GCE emits fixed-width integers in places where `acpi_tables` would pick the +//! shortest encoding, so integer width is always chosen explicitly here: +//! [`int`] is the shortest form, [`byte`]/[`word`]/[`dword`]/[`qword`] are +//! fixed. Every other helper mirrors the ASL operator of the same name. + +pub(crate) type Term = Vec; + +fn concat(parts: impl IntoIterator) -> Term { + parts.into_iter().flatten().collect() +} + +/// `PkgLength` (ACPI 6.5 §20.2.4) for `len` bytes that follow it. +fn pkg_length(len: usize) -> Term { + let mut total = len + 1; + loop { + let enc = if total < 0x40 { + vec![total as u8] + } else { + let follow = if total < 0x1000 { + 1 + } else if total < 0x10_0000 { + 2 + } else { + 3 + }; + let mut enc = vec![((follow << 6) as u8) | (total & 0xf) as u8]; + enc.extend((0..follow).map(|i| (total >> (4 + 8 * i)) as u8)); + enc + }; + if enc.len() + len == total { + return enc; + } + total = enc.len() + len; + } +} + +/// A `FieldElement` bit length: a `PkgLength` that does not count itself. +fn field_length(bits: usize) -> Term { + if bits < 0x40 { + return vec![bits as u8]; + } + let follow = if bits < 0x1000 { 1 } else { 2 }; + let mut enc = vec![((follow << 6) as u8) | (bits & 0xf) as u8]; + enc.extend((0..follow).map(|i| (bits >> (4 + 8 * i)) as u8)); + enc +} + +fn package_op(opcode: &[u8], body: impl IntoIterator) -> Term { + let body = concat(body); + concat([opcode.to_vec(), pkg_length(body.len()), body]) +} + +/// A four-character `NameSeg`, padded with `_` as ASL does. +pub(crate) fn name_seg(name: &str) -> [u8; 4] { + assert!( + !name.is_empty() && name.len() <= 4, + "invalid NameSeg {name:?}" + ); + let mut seg = *b"____"; + seg[..name.len()].copy_from_slice(name.as_bytes()); + seg +} + +/// An ASL `NamePath` such as `\_SB.PCI0`, `^ISA` or `_UID`. +pub(crate) fn path(name: &str) -> Term { + let rest = name.trim_start_matches(['\\', '^']); + let mut out = name.as_bytes()[..name.len() - rest.len()].to_vec(); + let segs: Vec<[u8; 4]> = if rest.is_empty() { + vec![] + } else { + rest.split('.').map(name_seg).collect() + }; + match segs.len() { + 0 => out.push(0), + 1 => {} + 2 => out.push(0x2e), + n => out.extend([0x2f, n as u8]), + } + out.extend(segs.into_iter().flatten()); + out +} + +pub(crate) fn zero() -> Term { + vec![0x00] +} +pub(crate) fn one() -> Term { + vec![0x01] +} +pub(crate) fn ones() -> Term { + vec![0xff] +} +pub(crate) fn byte(v: u8) -> Term { + vec![0x0a, v] +} +pub(crate) fn word(v: u16) -> Term { + concat([vec![0x0b], v.to_le_bytes().to_vec()]) +} +pub(crate) fn dword(v: u32) -> Term { + concat([vec![0x0c], v.to_le_bytes().to_vec()]) +} +pub(crate) fn qword(v: u64) -> Term { + concat([vec![0x0e], v.to_le_bytes().to_vec()]) +} + +/// The shortest integer encoding, as `iasl` emits it. +pub(crate) fn int(v: u64) -> Term { + match v { + 0 => zero(), + 1 => one(), + 2..=0xff => byte(v as u8), + 0x100..=0xffff => word(v as u16), + 0x1_0000..=0xffff_ffff => dword(v as u32), + _ => qword(v), + } +} + +pub(crate) fn string(s: &str) -> Term { + concat([vec![0x0d], s.as_bytes().to_vec(), vec![0]]) +} + +/// `EisaId ("PNP0A03")` +pub(crate) fn eisa_id(id: &str) -> Term { + let b = id.as_bytes(); + assert!(b.len() == 7, "invalid EISA id {id:?}"); + let product = u32::from_str_radix(&id[3..], 16).expect("EISA product id is hex"); + let v = (u32::from(b[0] - 0x40) << 26) + | (u32::from(b[1] - 0x40) << 21) + | (u32::from(b[2] - 0x40) << 16) + | product; + dword(v.swap_bytes()) +} + +pub(crate) fn arg(i: u8) -> Term { + vec![0x68 + i] +} +pub(crate) fn local(i: u8) -> Term { + vec![0x60 + i] +} + +pub(crate) fn name(n: &str, value: Term) -> Term { + concat([vec![0x08], path(n), value]) +} +pub(crate) fn scope(n: &str, body: impl IntoIterator) -> Term { + package_op(&[0x10], std::iter::once(path(n)).chain(body)) +} +pub(crate) fn device(n: &str, body: impl IntoIterator) -> Term { + package_op(&[0x5b, 0x82], std::iter::once(path(n)).chain(body)) +} +fn method_with_flags(n: &str, flags: u8, body: impl IntoIterator) -> Term { + package_op(&[0x14], [path(n), vec![flags]].into_iter().chain(body)) +} +pub(crate) fn method(n: &str, args: u8, body: impl IntoIterator) -> Term { + method_with_flags(n, args, body) +} +pub(crate) fn serialized_method(n: &str, args: u8, body: impl IntoIterator) -> Term { + method_with_flags(n, args | 0x08, body) +} +pub(crate) fn if_(predicate: Term, body: impl IntoIterator) -> Term { + package_op(&[0xa0], std::iter::once(predicate).chain(body)) +} +pub(crate) fn else_(body: impl IntoIterator) -> Term { + package_op(&[0xa1], body) +} +pub(crate) fn while_(predicate: Term, body: impl IntoIterator) -> Term { + package_op(&[0xa2], std::iter::once(predicate).chain(body)) +} +/// `Package (count) { elements }` where `count` may exceed the initializers. +pub(crate) fn package_n(count: u8, elements: impl IntoIterator) -> Term { + package_op(&[0x12], std::iter::once(vec![count]).chain(elements)) +} +pub(crate) fn package(elements: Vec) -> Term { + let count = u8::try_from(elements.len()).expect("package has at most 255 elements"); + package_n(count, elements) +} +/// `Buffer (size) { data }` where `size` may exceed the initializer. +pub(crate) fn buffer_n(size: Term, data: &[u8]) -> Term { + package_op(&[0x11], [size, data.to_vec()]) +} +pub(crate) fn buffer(data: &[u8]) -> Term { + buffer_n(int(data.len() as u64), data) +} + +/// `Method` invocation; the argument count is implied by the callee. +pub(crate) fn call(n: &str, args: impl IntoIterator) -> Term { + concat(std::iter::once(path(n)).chain(args)) +} + +/// `External (name, type, args)` with the ACPI `ObjectType` codes. +pub(crate) fn external(n: &str, object_type: u8, args: u8) -> Term { + concat([vec![0x15], path(n), vec![object_type, args]]) +} +pub(crate) const PACKAGE_OBJ: u8 = 4; +pub(crate) const DEVICE_OBJ: u8 = 6; +pub(crate) const METHOD_OBJ: u8 = 8; + +pub(crate) const SYSTEM_IO: u8 = 1; +pub(crate) const PCI_CONFIG: u8 = 2; + +pub(crate) fn op_region(n: &str, space: u8, offset: Term, length: Term) -> Term { + concat([vec![0x5b, 0x80], path(n), vec![space], offset, length]) +} + +pub(crate) enum FieldUnit<'a> { + Named(&'a str, usize), + Reserved(usize), +} + +/// `Field (region, flags) { units }`; `flags` packs access type, lock and update rules. +pub(crate) fn field(region: &str, flags: u8, units: &[FieldUnit]) -> Term { + let units = units.iter().map(|unit| match unit { + FieldUnit::Named(n, bits) => concat([name_seg(n).to_vec(), field_length(*bits)]), + FieldUnit::Reserved(bits) => concat([vec![0], field_length(*bits)]), + }); + package_op( + &[0x5b, 0x81], + [path(region), vec![flags]].into_iter().chain(units), + ) +} + +pub(crate) fn mutex(n: &str, sync_level: u8) -> Term { + concat([vec![0x5b, 0x01], path(n), vec![sync_level]]) +} +pub(crate) fn acquire(mutex: Term, timeout: u16) -> Term { + concat([vec![0x5b, 0x23], mutex, timeout.to_le_bytes().to_vec()]) +} + +macro_rules! fixed_ops { + ($($(#[$doc:meta])* $name:ident($($arg:ident),*) = [$($op:expr),+];)*) => {$( + $(#[$doc])* + pub(crate) fn $name($($arg: Term),*) -> Term { + concat([vec![$($op),+] $(, $arg)*]) + } + )*}; +} + +fixed_ops! { + ret(value) = [0xa4]; + store(source, target) = [0x70]; + notify(object, value) = [0x86]; + add(a, b, target) = [0x72]; + subtract(a, b, target) = [0x74]; + increment(target) = [0x75]; + shift_left(a, b, target) = [0x79]; + shift_right(a, b, target) = [0x7a]; + and(a, b, target) = [0x7b]; + or(a, b, target) = [0x7d]; + deref_of(object) = [0x83]; + concatenate_res_template(a, b, target) = [0x84]; + size_of(object) = [0x87]; + index(object, idx, target) = [0x88]; + land(a, b) = [0x90]; + lor(a, b) = [0x91]; + lnot(a) = [0x92]; + lequal(a, b) = [0x93]; + lless(a, b) = [0x95]; + to_buffer(source, target) = [0x96]; + to_hex_string(source, target) = [0x98]; + release(mutex) = [0x5b, 0x27]; + sleep(ms) = [0x5b, 0x22]; +} + +fn create_field(opcode: u8, buf: Term, idx: Term, n: &str) -> Term { + concat([vec![opcode], buf, idx, path(n)]) +} +pub(crate) fn create_dword_field(buf: Term, idx: Term, n: &str) -> Term { + create_field(0x8a, buf, idx, n) +} +pub(crate) fn create_word_field(buf: Term, idx: Term, n: &str) -> Term { + create_field(0x8b, buf, idx, n) +} +pub(crate) fn create_byte_field(buf: Term, idx: Term, n: &str) -> Term { + create_field(0x8c, buf, idx, n) +} +pub(crate) fn create_qword_field(buf: Term, idx: Term, n: &str) -> Term { + create_field(0x8f, buf, idx, n) +} + +/// `ToUUID ("...")` as the 16-byte little-endian GUID buffer. +pub(crate) fn uuid(u: u128) -> Term { + let b = u.to_be_bytes(); + let mut le = [0u8; 16]; + le[..4].copy_from_slice(&[b[3], b[2], b[1], b[0]]); + le[4..6].copy_from_slice(&[b[5], b[4]]); + le[6..8].copy_from_slice(&[b[7], b[6]]); + le[8..].copy_from_slice(&b[8..]); + buffer(&le) +} + +/// Resource descriptors (ACPI 6.5 §6.4), concatenated by [`resource_template`]. +pub(crate) mod res { + use super::{buffer, concat, Term}; + + /// `IO (Decode16, min, max, alignment, length)` + pub(crate) fn io(min: u16, max: u16, alignment: u8, length: u8) -> Term { + concat([ + vec![0x47, 0x01], + min.to_le_bytes().to_vec(), + max.to_le_bytes().to_vec(), + vec![alignment, length], + ]) + } + /// `IRQNoFlags () { irqs }` + pub(crate) fn irq_no_flags(irqs: &[u8]) -> Term { + let mask: u16 = irqs.iter().map(|i| 1u16 << i).sum(); + concat([vec![0x22], mask.to_le_bytes().to_vec()]) + } + /// `Interrupt (ResourceConsumer, Level, ActiveHigh, Shared) { irqs }` + pub(crate) fn interrupt_level_shared(irqs: &[u32]) -> Term { + let mut body = vec![0x09, irqs.len() as u8]; + body.extend(irqs.iter().flat_map(|i| i.to_le_bytes())); + large(0x89, body) + } + fn large(tag: u8, body: Term) -> Term { + concat([vec![tag], (body.len() as u16).to_le_bytes().to_vec(), body]) + } + + pub(crate) const MEMORY_RANGE: u8 = 0; + pub(crate) const IO_RANGE: u8 = 1; + pub(crate) const BUS_NUMBER_RANGE: u8 = 2; + /// General flags: producer, positive decode, fixed minimum and maximum. + const PRODUCER_FIXED: u8 = 0x0c; + + /// Word, DWord and QWord address space descriptors with fixed min/max. + /// `type_flags` holds the cacheability/read-write or I/O range bits. + pub(crate) fn word_address( + kind: u8, + type_flags: u8, + [gran, min, max, tra, len]: [u16; 5], + ) -> Term { + let mut body = vec![kind, PRODUCER_FIXED, type_flags]; + body.extend( + [gran, min, max, tra, len] + .iter() + .flat_map(|v| v.to_le_bytes()), + ); + large(0x88, body) + } + pub(crate) fn dword_address( + kind: u8, + type_flags: u8, + [gran, min, max, tra, len]: [u32; 5], + ) -> Term { + let mut body = vec![kind, PRODUCER_FIXED, type_flags]; + body.extend( + [gran, min, max, tra, len] + .iter() + .flat_map(|v| v.to_le_bytes()), + ); + large(0x87, body) + } + pub(crate) fn qword_address( + kind: u8, + type_flags: u8, + [gran, min, max, tra, len]: [u64; 5], + ) -> Term { + let mut body = vec![kind, PRODUCER_FIXED, type_flags]; + body.extend( + [gran, min, max, tra, len] + .iter() + .flat_map(|v| v.to_le_bytes()), + ); + large(0x8a, body) + } + + /// `ResourceTemplate () { descriptors }`, closed by an end tag with a zero checksum. + pub(crate) fn resource_template(descriptors: impl IntoIterator) -> Term { + buffer(&concat(descriptors.into_iter().chain([vec![0x79, 0x00]]))) + } +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/acad.rs b/dstack/crates/gcp-acpi/src/dsdt/acad.rs new file mode 100644 index 0000000000..c88714508a --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/acad.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! The AC adapter device (`ACAD`) and its status register at 0xae10. + +use crate::aml::FieldUnit::*; +use crate::aml::*; + +/// GPU shapes report no AC adapter. +pub(super) fn build(enabled: bool) -> Vec { + vec![scope( + "_SB", + [ + name("ADEN", if enabled { one() } else { zero() }), + if_( + path("ADEN"), + [ + op_region("ACST", SYSTEM_IO, word(0xae10), byte(0x4)), + field("ACST", 0x3, &[Named("ACIN", 32)]), + device( + "ACAD", + [ + name("_HID", string("ACPI0003")), + method("_STA", 0, [ret(byte(0xf))]), + method("_PSR", 0, [ret(path("ACIN"))]), + ], + ), + ], + ), + ], + )] +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/chipset.rs b/dstack/crates/gcp-acpi/src/dsdt/chipset.rs new file mode 100644 index 0000000000..03f2c3ad77 --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/chipset.rs @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! PIIX-style chipset functions on PCI0: VGA, the PX13 power-management +//! function and the ISA bridge. + +use crate::aml::FieldUnit::*; +use crate::aml::*; + +pub(super) fn build() -> Vec { + vec![ + scope( + "_SB.PCI0", + [device( + "VGA", + [ + name("_ADR", dword(0x20000)), + op_region("PCIC", PCI_CONFIG, zero(), byte(0x4)), + field("PCIC", 0x3, &[Named("VEND", 32)]), + method("_S1D", 0, [ret(zero())]), + method("_S2D", 0, [ret(zero())]), + method( + "_S3D", + 0, + [ + if_(lequal(path("VEND"), dword(0x1001b36)), [ret(byte(0x3))]), + else_([ret(zero())]), + ], + ), + ], + )], + ), + scope( + "_SB.PCI0", + [device( + "PX13", + [ + name("_ADR", dword(0x10003)), + op_region("P13C", PCI_CONFIG, zero(), byte(0xff)), + ], + )], + ), + scope( + "_SB.PCI0", + [device( + "ISA", + [ + name("_ADR", dword(0x10000)), + op_region("P40C", PCI_CONFIG, byte(0x60), byte(0x4)), + field( + "^PX13.P13C", + 0x0, + &[ + Reserved(760), + Reserved(7), + Named("LPEN", 1), + Reserved(56), + Reserved(3), + Named("CAEN", 1), + Reserved(3), + Named("CBEN", 1), + ], + ), + name("FDEN", zero()), + ], + )], + ), + ] +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/cpus.rs b/dstack/crates/gcp-acpi/src/dsdt/cpus.rs new file mode 100644 index 0000000000..df12f533c8 --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/cpus.rs @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! CPU hotplug: `CPMA`/`CPST`/`CPEJ` back the per-CPU devices the SSDT +//! declares, and `PRSC` scans the present-CPU bitmap at 0xaf00. + +use crate::aml::FieldUnit::*; +use crate::aml::*; + +pub(super) fn build() -> Vec { + vec![scope( + "_SB", + [ + name("MDX2", zero()), + method( + "CPMA", + 1, + [ + store(deref_of(index(path("CPON"), arg(0), zero())), local(0)), + if_( + lor(path("MDX2"), lnot(lless(arg(0), byte(0xff)))), + [ + store( + // _MAT entry for UIDs above 0xfe; bytes 4..8 and 12..16 take the UID + buffer(&[ + 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]), + local(1), + ), + and(arg(0), byte(0xff), index(local(1), byte(0x4), zero())), + and( + shift_right(arg(0), byte(0x8), zero()), + byte(0xff), + index(local(1), byte(0x5), zero()), + ), + and( + shift_right(arg(0), byte(0x10), zero()), + byte(0xff), + index(local(1), byte(0x6), zero()), + ), + and( + shift_right(arg(0), byte(0x18), zero()), + byte(0xff), + index(local(1), byte(0x7), zero()), + ), + store(local(0), index(local(1), byte(0x8), zero())), + and(arg(0), byte(0xff), index(local(1), byte(0xc), zero())), + and( + shift_right(arg(0), byte(0x8), zero()), + byte(0xff), + index(local(1), byte(0xd), zero()), + ), + and( + shift_right(arg(0), byte(0x10), zero()), + byte(0xff), + index(local(1), byte(0xe), zero()), + ), + and( + shift_right(arg(0), byte(0x18), zero()), + byte(0xff), + index(local(1), byte(0xf), zero()), + ), + ret(local(1)), + ], + ), + store( + // Processor Local APIC structure; UID, APIC ID and flags are filled in below + buffer(&[0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + local(1), + ), + store(arg(0), index(local(1), byte(0x2), zero())), + store(arg(0), index(local(1), byte(0x3), zero())), + store(local(0), index(local(1), byte(0x4), zero())), + ret(local(1)), + ], + ), + method( + "CPST", + 1, + [ + store(deref_of(index(path("CPON"), arg(0), zero())), local(0)), + if_(local(0), [ret(byte(0xf))]), + else_([ret(zero())]), + ], + ), + method( + "CPEJ", + 2, + [ + call("DBUG", [string("CPEJ")]), + call("DBUG", [arg(0)]), + call("DBUG", [arg(1)]), + if_( + lequal(arg(1), one()), + [ + store(buffer_n(byte(0x80), &[]), local(0)), + shift_right(arg(0), byte(0x3), local(1)), + and(arg(0), byte(0x7), local(2)), + shift_left(one(), local(2), local(3)), + store(local(3), index(local(0), local(1), zero())), + store(local(0), path("PRS")), + ], + ), + sleep(byte(0xc8)), + ], + ), + op_region("PRST", SYSTEM_IO, word(0xaf00), byte(0x80)), + field("PRST", 0x1, &[Named("PRS", 1024)]), + method( + "PRSC", + 0, + [ + store(path("PRS"), local(5)), + store(zero(), local(2)), + store(zero(), local(0)), + while_( + lless(local(0), size_of(path("CPON"))), + [ + store(deref_of(index(path("CPON"), local(0), zero())), local(1)), + if_( + and(local(0), byte(0x7), zero()), + [shift_right(local(2), one(), local(2))], + ), + else_([store( + deref_of(index( + local(5), + shift_right(local(0), byte(0x3), zero()), + zero(), + )), + local(2), + )]), + and(local(2), one(), local(3)), + if_( + lnot(lequal(local(1), local(3))), + [ + store(local(3), index(path("CPON"), local(0), zero())), + if_(lequal(local(3), one()), [call("NTFY", [local(0), one()])]), + else_([call("NTFY", [local(0), byte(0x3)])]), + ], + ), + increment(local(0)), + ], + ), + ], + ), + ], + )] +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/dbg.rs b/dstack/crates/gcp-acpi/src/dsdt/dbg.rs new file mode 100644 index 0000000000..a7abaaa3ca --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/dbg.rs @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! `Scope (\\)`: the debug port at 0x402 and the `DBUG` string writer. + +use crate::aml::FieldUnit::*; +use crate::aml::*; + +pub(super) fn build() -> Vec { + vec![scope( + "\\", + [ + op_region("DBG", SYSTEM_IO, word(0x402), one()), + field("DBG", 0x1, &[Named("DBGB", 8)]), + method( + "DBUG", + 1, + [ + to_hex_string(arg(0), local(0)), + to_buffer(local(0), local(0)), + subtract(size_of(local(0)), one(), local(1)), + store(zero(), local(2)), + while_( + lless(local(2), local(1)), + [ + store(deref_of(index(local(0), local(2), zero())), path("DBGB")), + increment(local(2)), + ], + ), + store(byte(0xa), path("DBGB")), + ], + ), + ], + )] +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/gpe.rs b/dstack/crates/gcp-acpi/src/dsdt/gpe.rs new file mode 100644 index 0000000000..3596103399 --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/gpe.rs @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! `Scope (_GPE)`: general-purpose event handlers. + +use crate::aml::*; + +pub(super) fn build() -> Vec { + vec![scope( + "_GPE", + [ + name("_HID", string("ACPI0006")), + method("_L00", 0, []), + method("_E01", 0, [path("\\_SB.PCI0.PCNF")]), + method("_E02", 0, [path("\\_SB.PRSC")]), + method("_E03", 0, [path("\\_SB.MSCA")]), + method( + "_L04", + 0, + [if_( + path("\\_SB.ADEN"), + [notify(path("\\_SB.ACAD"), byte(0x80))], + )], + ), + method("_L05", 0, []), + method("_L06", 0, []), + method("_L07", 0, []), + method("_L08", 0, []), + method("_L09", 0, []), + method("_L0A", 0, []), + method("_L0B", 0, []), + method("_L0C", 0, []), + method("_L0D", 0, []), + method("_L0E", 0, []), + method("_L0F", 0, []), + ], + )] +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/isa.rs b/dstack/crates/gcp-acpi/src/dsdt/isa.rs new file mode 100644 index 0000000000..d68132714f --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/isa.rs @@ -0,0 +1,216 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! Legacy devices behind the ISA bridge: RTC, PS/2 keyboard and mouse, +//! floppy, parallel port, four serial ports and the pen tablet. + +use crate::aml::res::*; +use crate::aml::FieldUnit::*; +use crate::aml::*; + +/// Serial port `COMn` whose base address lives in `CnAD`. +fn com(n: u8, irq: u8, sta: Term) -> Term { + let base = format!("C{n}AD"); + device( + &format!("COM{n}"), + [ + name("_HID", eisa_id("PNP0501")), + name("_UID", int(n.into())), + sta, + name( + "CRES", + resource_template([io(0x0, 0x0, 0x0, 0x0), irq_no_flags(&[irq])]), + ), + method( + "_CRS", + 0, + [ + create_word_field(path("CRES"), byte(0x2), "CMIN"), + create_word_field(path("CRES"), byte(0x4), "CMAX"), + create_byte_field(path("CRES"), byte(0x7), "CLEN"), + store(path(&base), path("CMIN")), + store(path(&base), path("CMAX")), + store(byte(0x8), path("CLEN")), + ret(path("CRES")), + ], + ), + ], + ) +} + +/// `_STA`: in legacy mode follow the ISA enable bit, otherwise `enable`. +fn legacy_or_enabled(isa_bit: &str, enable: &str) -> Term { + let present_if = |bit: &str| { + [ + store(path(bit), local(1)), + if_(lequal(local(1), zero()), [ret(zero())]), + else_([ret(byte(0xf))]), + ] + }; + method( + "_STA", + 0, + [ + store(path("LGCY"), local(0)), + if_(lequal(local(0), zero()), present_if(isa_bit)), + else_(present_if(enable)), + ], + ) +} + +/// `_STA`: present only in legacy mode with the ISA enable bit set. +fn legacy_only(isa_bit: &str) -> Term { + method( + "_STA", + 0, + [ + store(path("LGCY"), local(0)), + if_( + lequal(local(0), zero()), + [ + store(path(isa_bit), local(1)), + if_(lequal(local(1), one()), [ret(byte(0xf))]), + ], + ), + ret(zero()), + ], + ) +} + +pub(super) fn build() -> Vec { + vec![scope( + "_SB.PCI0.ISA", + [ + op_region("ISAE", SYSTEM_IO, word(0xad00), one()), + field( + "ISAE", + 0x41, + &[ + Named("SERA", 1), + Named("SERB", 1), + Named("KBDC", 1), + Named("WPEN", 1), + Named("SERC", 1), + Named("SERD", 1), + Reserved(1), + Named("LGCY", 1), + ], + ), + device( + "RTC", + [ + name("_HID", eisa_id("PNP0B00")), + name( + "_CRS", + resource_template([ + io(0x70, 0x70, 0x10, 0x2), + irq_no_flags(&[8]), + io(0x72, 0x72, 0x2, 0x6), + ]), + ), + ], + ), + device( + "KBD", + [ + name("_HID", eisa_id("PNP0303")), + method( + "_STA", + 0, + [ + store(path("LGCY"), local(0)), + if_( + lequal(local(0), zero()), + [ + store(path("KBDC"), local(1)), + if_(lequal(local(1), zero()), [ret(zero())]), + else_([ret(byte(0xf))]), + ], + ), + else_([ret(byte(0xf))]), + ], + ), + name( + "_CRS", + resource_template([ + io(0x60, 0x60, 0x1, 0x1), + io(0x64, 0x64, 0x1, 0x1), + irq_no_flags(&[1]), + ]), + ), + ], + ), + device( + "MOU", + [ + name("_HID", eisa_id("PNP0F13")), + method( + "_STA", + 0, + [ + store(path("LGCY"), local(0)), + if_( + lequal(local(0), zero()), + [ + store(path("KBDC"), local(1)), + if_(lequal(local(1), zero()), [ret(zero())]), + else_([ret(byte(0xf))]), + ], + ), + else_([ret(byte(0xf))]), + ], + ), + name("_CRS", resource_template([irq_no_flags(&[12])])), + ], + ), + device( + "FDC0", + [ + name("_HID", eisa_id("PNP0700")), + method("_STA", 0, [ret(zero())]), + ], + ), + device( + "LPT", + [ + name("_HID", eisa_id("PNP0400")), + method("_STA", 0, [ret(zero())]), + ], + ), + name("C1AD", word(0x3f8)), + name("C2AD", word(0x2f8)), + name("C3AD", word(0x3e8)), + name("C4AD", word(0x2e8)), + com(1, 4, legacy_or_enabled("SERA", "CAEN")), + com(2, 3, legacy_or_enabled("SERB", "CBEN")), + com(3, 6, legacy_only("SERC")), + com(4, 7, legacy_only("SERD")), + device( + "PEN", + [ + name("_HID", eisa_id("WACF004")), + method( + "_STA", + 0, + [ + store(path("LGCY"), local(0)), + if_( + lequal(local(0), zero()), + [ + store(path("WPEN"), local(1)), + if_(lequal(local(1), zero()), [ret(zero())]), + else_([ret(byte(0xf))]), + ], + ), + else_([ret(zero())]), + ], + ), + name( + "_CRS", + resource_template([io(0x200, 0x208, 0x0, 0x8), irq_no_flags(&[7])]), + ), + ], + ), + ], + )] +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/links.rs b/dstack/crates/gcp-acpi/src/dsdt/links.rs new file mode 100644 index 0000000000..7ba860187f --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/links.rs @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! PCI interrupt link devices: `LNKA`..`LNKD` route through the PIIX PIRQ +//! registers `PRQ0`..`PRQ3`, `LNKS` is the fixed SCI link. + +use crate::aml::res::*; +use crate::aml::FieldUnit::*; +use crate::aml::*; + +/// `LNKx` backed by PIRQ register `PRQn`. +fn pirq_link(n: u8) -> Term { + let prq = format!("PRQ{n}"); + let prq = || path(&prq); + device( + &format!("LNK{}", (b'A' + n) as char), + [ + name("_HID", eisa_id("PNP0C0F")), + name("_UID", int(n.into())), + name( + "_PRS", + resource_template([interrupt_level_shared(&[5, 10, 11])]), + ), + method("_STA", 0, [ret(call("IQST", [prq()]))]), + method("_DIS", 0, [or(prq(), byte(0x80), prq())]), + method("_CRS", 0, [ret(call("IQCR", [prq()]))]), + method( + "_SRS", + 1, + [ + create_dword_field(arg(0), byte(0x5), "PRRI"), + store(path("PRRI"), prq()), + ], + ), + ], + ) +} + +pub(super) fn build() -> Vec { + let links = (0..4).map(pirq_link); + let rest = [ + field( + "PCI0.ISA.P40C", + 0x1, + &[ + Named("PRQ0", 8), + Named("PRQ1", 8), + Named("PRQ2", 8), + Named("PRQ3", 8), + ], + ), + method( + "IQST", + 1, + [ + if_(and(byte(0x80), arg(0), zero()), [ret(byte(0x9))]), + ret(byte(0xb)), + ], + ), + name("PRR0", resource_template([interrupt_level_shared(&[0])])), + serialized_method( + "IQCR", + 1, + [ + create_dword_field(path("PRR0"), byte(0x5), "PRRI"), + if_(lless(arg(0), byte(0x80)), [store(arg(0), path("PRRI"))]), + ret(path("PRR0")), + ], + ), + device( + "LNKS", + [ + name("_HID", eisa_id("PNP0C0F")), + name("_UID", byte(0x4)), + name("_PRS", resource_template([interrupt_level_shared(&[9])])), + method("_STA", 0, [ret(byte(0xb))]), + method("_DIS", 0, []), + method("_CRS", 0, [ret(path("_PRS"))]), + method("_SRS", 1, []), + ], + ), + ]; + vec![scope("_SB", links.chain(rest))] +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/memhp.rs b/dstack/crates/gcp-acpi/src/dsdt/memhp.rs new file mode 100644 index 0000000000..a46c72f369 --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/memhp.rs @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! Memory hotplug registers at 0xaf80 and the `M*` methods that serve them. + +use crate::aml::res::*; +use crate::aml::FieldUnit::*; +use crate::aml::*; + +pub(super) fn build() -> Vec { + vec![scope( + "_SB", + [ + mutex("MMTX", 0), + op_region("MOR", SYSTEM_IO, word(0xaf80), byte(0x80)), + field( + "MOR", + 0x3, + &[ + Named("MHPE", 32), + Named("MCNT", 32), + Named("MSEL", 32), + Named("MFLG", 32), + Named("MBL", 32), + Named("MBH", 32), + Named("MLL", 32), + Named("MLH", 32), + Named("MPDI", 32), + Named("MOSE", 32), + Named("MOSC", 32), + ], + ), + method( + "MSTA", + 1, + [ + store(zero(), local(0)), + acquire(path("MMTX"), 0xffff), + store(arg(0), path("MSEL")), + if_( + land( + lnot(lequal(and(path("MFLG"), one(), zero()), zero())), + lequal(and(path("MFLG"), byte(0x4), zero()), zero()), + ), + [store(byte(0xf), local(0))], + ), + release(path("MMTX")), + ret(local(0)), + ], + ), + method( + "MCRS", + 1, + [ + store( + resource_template([qword_address( + MEMORY_RANGE, + 0x3, + [0x0, 0x0, 0xfffffffffffffffe, 0x0, 0xffffffffffffffff], + )]), + local(0), + ), + create_dword_field(local(0), byte(0xe), "MINL"), + create_dword_field(local(0), byte(0x12), "MINH"), + create_dword_field(local(0), byte(0x16), "MAXL"), + create_dword_field(local(0), byte(0x1a), "MAXH"), + create_dword_field(local(0), byte(0x26), "LENL"), + create_dword_field(local(0), byte(0x2a), "LENH"), + acquire(path("MMTX"), 0xffff), + store(arg(0), path("MSEL")), + store(path("MBL"), path("MINL")), + store(path("MBH"), path("MINH")), + store(path("MLL"), path("LENL")), + store(path("MLH"), path("LENH")), + add(path("MINL"), path("LENL"), path("MAXL")), + add(path("MINH"), path("LENH"), path("MAXH")), + if_( + or( + lless(path("MAXL"), path("MINL")), + lless(path("MAXL"), path("LENL")), + zero(), + ), + [add(path("MAXH"), one(), path("MAXH"))], + ), + subtract(path("MAXL"), one(), path("MAXL")), + if_( + lequal(path("MAXL"), ones()), + [subtract(path("MAXH"), one(), path("MAXH"))], + ), + call("DBUG", [string("MCRS")]), + call("DBUG", [arg(0)]), + call("DBUG", [path("MINL")]), + call("DBUG", [path("MINH")]), + call("DBUG", [path("MAXL")]), + call("DBUG", [path("MAXH")]), + call("DBUG", [path("LENL")]), + call("DBUG", [path("LENH")]), + release(path("MMTX")), + ret(local(0)), + ], + ), + method( + "MPXM", + 1, + [ + acquire(path("MMTX"), 0xffff), + store(arg(0), path("MSEL")), + store(path("MPDI"), local(0)), + call("DBUG", [string("MPXM")]), + call("DBUG", [arg(0)]), + call("DBUG", [local(0)]), + release(path("MMTX")), + ret(local(0)), + ], + ), + method( + "MOST", + 4, + [ + acquire(path("MMTX"), 0xffff), + store(arg(0), path("MSEL")), + store(arg(1), path("MOSE")), + store(arg(2), path("MOSC")), + call("DBUG", [string("MOST")]), + call("DBUG", [arg(0)]), + call("DBUG", [arg(1)]), + call("DBUG", [arg(2)]), + call("DBUG", [arg(3)]), + release(path("MMTX")), + ], + ), + method( + "MEJ0", + 2, + [ + acquire(path("MMTX"), 0xffff), + call("DBUG", [string("MEJ0")]), + call("DBUG", [arg(0)]), + call("DBUG", [arg(1)]), + if_( + lequal(arg(1), one()), + [store(arg(0), path("MSEL")), store(byte(0x4), path("MFLG"))], + ), + release(path("MMTX")), + sleep(byte(0xc8)), + ], + ), + method( + "MSCA", + 0, + [ + acquire(path("MMTX"), 0xffff), + call("DBUG", [string("MSCA")]), + store(path("MCNT"), local(0)), + store(zero(), local(1)), + while_( + lless(local(1), local(0)), + [ + store(local(1), path("MSEL")), + store(path("MFLG"), local(2)), + if_( + lnot(lequal(and(local(2), byte(0x2), zero()), zero())), + [ + call("DBUG", [string("MSCA --> MNOT")]), + call("DBUG", [local(1)]), + call("MNOT", [local(1), one()]), + store(byte(0x2), path("MFLG")), + ], + ), + add(local(1), one(), local(1)), + ], + ), + release(path("MMTX")), + ], + ), + ], + )] +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/mod.rs b/dstack/crates/gcp-acpi/src/dsdt/mod.rs new file mode 100644 index 0000000000..4356761f51 --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/mod.rs @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! GCE's DSDT. It depends only on whether a GPU is attached: processors live +//! in the SSDT, and the PCI windows are patched in by the firmware after the +//! table has been measured. + +use crate::aml::*; + +mod acad; +mod chipset; +mod cpus; +mod dbg; +mod gpe; +mod isa; +mod links; +mod memhp; +mod pci0; +mod pcihp; + +/// DSDT integers the firmware rewrites with the PCI windows it assigned, in +/// the order GCE's vendor loader commands list them. +pub(crate) const PCI_WINDOW_NAMES: [&str; 30] = [ + "PB0S", "PB0E", "PB1V", "PB1S", "PB1E", "PB1L", "PBIS", "PBIE", "PWS0", "PWE0", "PWS1", "PWE1", + "PWS2", "PWE2", "PWS3", "PWE3", "PWS4", "PWE4", "PWS5", "PWE5", "PWS6", "PWE6", "PWS7", "PWE7", + "PWS8", "PWE8", "PWS9", "PWE9", "PWSA", "PWEA", +]; + +pub(crate) use pci0::names as host_bridges; + +/// DSDT body: everything after the 36-byte table header. +pub(crate) fn body(gpu: bool) -> Vec { + let externals = if_( + zero(), + [ + external("\\_SB.CPON", PACKAGE_OBJ, 0), + external("\\_SB.MNOT", METHOD_OBJ, 2), + external("\\_SB.NTFY", METHOD_OBJ, 2), + external("\\_SB.PCI0.PCNT", METHOD_OBJ, 2), + ], + ); + std::iter::once(externals) + .chain(dbg::build()) + .chain(pci0::build(gpu)) + .chain(chipset::build()) + .chain(isa::build()) + .chain(pcihp::build()) + .chain(links::build()) + .chain(cpus::build()) + .chain(acad::build(!gpu)) + .chain(memhp::build()) + .chain(gpe::build()) + .chain(gpu.then(pci0::extra_root).into_iter().flatten()) + .flatten() + .collect() +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/pci0.rs b/dstack/crates/gcp-acpi/src/dsdt/pci0.rs new file mode 100644 index 0000000000..e3782771dc --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/pci0.rs @@ -0,0 +1,303 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! `Scope (_SB)`: the PCI host bridges. PCI0 carries the legacy I/O and VGA +//! ranges; a GPU sits behind a second bridge, PR01, that owns buses 1-255. +//! +//! `_CRS` is assembled at runtime from named integers whose initial values +//! (0x80..0x9d) are placeholders; the firmware overwrites them with the windows +//! it assigned, as directed by GCE's vendor loader commands (see +//! [`super::PCI_WINDOW_NAMES`]). + +use crate::aml::res::*; +use crate::aml::*; + +/// Names of the host bridges, in the order GCE's loader patches them. +pub(crate) fn names(gpu: bool) -> impl Iterator { + ["PCI0"].into_iter().chain(gpu.then_some("PR01")) +} + +/// PCI0 and the scope-level switches its `_CRS` and `_OSC` read. +pub(super) fn build(gpu: bool) -> Vec { + vec![scope( + "_SB", + [ + name("POSC", zero()), + name("ZBR", zero()), + host_bridge(true, gpu), + ], + )] +} + +/// PR01, appended at the end of the DSDT. +pub(super) fn extra_root() -> Vec { + vec![scope("_SB", [host_bridge(false, true)])] +} + +fn host_bridge(primary: bool, gpu: bool) -> Term { + let (identity, cres, (bus_start, bus_end)) = if primary { + ( + [("_UID", one()), ("_BBN", zero()), ("_PXM", zero())], + vec![ + word_address(BUS_NUMBER_RANGE, 0x0, [0; 5]), + io(0x0, 0x0, 0x1, 0x0), + word_address(IO_RANGE, 0x3, [0; 5]), + word_address(IO_RANGE, 0x3, [0x0, 0x0, 0xfff, 0x0, 0x1000]), + word_address(IO_RANGE, 0x3, [0; 5]), + word_address(IO_RANGE, 0x3, [0x0, 0xa000, 0xbfff, 0x0, 0x2000]), + dword_address(MEMORY_RANGE, 0x3, [0; 5]), + dword_address(MEMORY_RANGE, 0x1, [0; 5]), + ], + (0, if gpu { 0 } else { 0xff }), + ) + } else { + ( + [("_UID", byte(2)), ("_BBN", byte(1)), ("_PXM", byte(0))], + vec![ + word_address(BUS_NUMBER_RANGE, 0x0, [0; 5]), + word_address(IO_RANGE, 0x3, [0; 5]), + dword_address(MEMORY_RANGE, 0x1, [0; 5]), + ], + (1, 0xff), + ) + }; + // Offsets in CRES of the `_MIN` of the I/O window and the first MMIO window. + let (io_window, mmio_window) = if primary { (0x40, 0x7c) } else { (0x18, 0x2a) }; + // Eleven 32-bit MMIO windows `PWSn`..`PWEn`, placeholders 0x86..0x9b. + let windows = (0..11u32).flat_map(|i| { + [ + name(&format!("PWS{i:X}"), dword(0x86 + 2 * i)), + name(&format!("PWE{i:X}"), dword(0x87 + 2 * i)), + ] + }); + let legacy_names = [ + name("PPCI", word(0xcf8)), + name("VGAS", dword(0xa0000)), + name("VGAL", dword(0x20000)), + ]; + let mut crs = vec![ + create_word_field(path("CRES"), byte(0x8), "BS32"), + create_word_field(path("CRES"), byte(0xa), "BE32"), + create_word_field(path("CRES"), byte(0xe), "BL32"), + store(path("PBBS"), path("BS32")), + store(path("PBBE"), path("BE32")), + add( + subtract(path("PBBE"), path("PBBS"), zero()), + one(), + path("BL32"), + ), + ]; + if primary { + crs.extend(legacy_io_crs()); + } + crs.extend([ + create_word_field(path("CRES"), byte(io_window), "IS32"), + create_word_field(path("CRES"), byte(io_window + 2), "IE32"), + create_word_field(path("CRES"), byte(io_window + 6), "IL32"), + store(path("PBIS"), path("IS32")), + store(path("PBIE"), path("IE32")), + add( + subtract(path("PBIE"), path("PBIS"), zero()), + one(), + path("IL32"), + ), + zero_if_empty("IS32", "IE32", "IL32"), + ]); + if primary { + crs.extend(vga_crs()); + } + crs.extend([ + create_dword_field(path("CRES"), byte(mmio_window), "PS32"), + create_dword_field(path("CRES"), byte(mmio_window + 4), "PE32"), + create_dword_field(path("CRES"), byte(mmio_window + 0xc), "PL32"), + if_( + lnot(lequal(path("PWS0"), zero())), + assign_window("PWS0", "PWE0", "PS32", "PE32", "PL32"), + ), + else_(assign_window("PB0S", "PB0E", "PS32", "PE32", "PL32")), + zero_if_empty("PS32", "PE32", "PL32"), + store(path("CRES"), local(0)), + create_dword_field(path("CRWM"), byte(0xa), "RS32"), + create_dword_field(path("CRWM"), byte(0xe), "RE32"), + create_dword_field(path("CRWM"), byte(0x16), "RL32"), + ]); + crs.extend((1..11).map(|i| { + let (start, end) = (format!("PWS{i:X}"), format!("PWE{i:X}")); + let mut body = assign_window(&start, &end, "RS32", "RE32", "RL32"); + body.push(concatenate_res_template(local(0), path("CRWM"), local(0))); + if_(lnot(lequal(path(&start), zero())), body) + })); + crs.extend([ + if_(lequal(path("PB1V"), zero()), [ret(local(0))]), + create_qword_field(path("CR64"), byte(0xe), "PS64"), + create_qword_field(path("CR64"), byte(0x16), "PE64"), + create_qword_field(path("CR64"), byte(0x26), "PL64"), + store(path("PB1S"), path("PS64")), + store(path("PB1E"), path("PE64")), + store(path("PB1L"), path("PL64")), + concatenate_res_template(local(0), path("CR64"), local(0)), + ret(local(0)), + ]); + + device( + if primary { "PCI0" } else { "PR01" }, + [name("_HID", eisa_id("PNP0A03"))] + .into_iter() + .chain(identity.map(|(n, v)| name(n, v))) + .chain([ + name("CRES", resource_template(cres)), + name( + "CRWM", + resource_template([dword_address(MEMORY_RANGE, 0x1, [0; 5])]), + ), + name( + "CR64", + resource_template([qword_address(MEMORY_RANGE, 0x3, [0; 5])]), + ), + name("PBBS", word(bus_start)), + name("PBBE", word(bus_end)), + name("PBIS", word(0x9c)), + name("PBIE", word(0x9d)), + name("PB0S", dword(0x80)), + name("PB0E", dword(0x81)), + ]) + .chain(windows) + .chain([ + name("PB1V", byte(0x82)), + name("PB1S", qword(0x83)), + name("PB1E", qword(0x84)), + name("PB1L", qword(0x85)), + ]) + .chain(legacy_names.into_iter().filter(|_| primary)) + .chain([method("_CRS", 0, crs), osc(), prt(primary)]), + ) +} + +/// `(start, end) -> (min, max, len)` of a resource descriptor. +fn assign_window(start: &str, end: &str, min: &str, max: &str, len: &str) -> Vec { + vec![ + store(path(start), path(min)), + store(path(end), path(max)), + add(subtract(path(end), path(start), zero()), one(), path(len)), + ] +} + +/// Drop an unassigned window unless `ZBR` asks to keep zero-based ranges. +fn zero_if_empty(min: &str, max: &str, len: &str) -> Term { + if_( + land( + lnot(path("ZBR")), + land(lequal(path(min), zero()), lequal(path(max), zero())), + ), + [store(zero(), path(len))], + ) +} + +/// PCI0's legacy I/O: ports below the config ports, the config ports, and +/// the ports above them up to 0xfff. +fn legacy_io_crs() -> Vec { + vec![ + create_word_field(path("CRES"), byte(0x20), "LMIN"), + create_word_field(path("CRES"), byte(0x22), "LMAX"), + create_word_field(path("CRES"), byte(0x26), "LLEN"), + store(zero(), path("LMIN")), + subtract(path("PPCI"), one(), path("LMAX")), + store(path("PPCI"), path("LLEN")), + create_word_field(path("CRES"), byte(0x12), "PMIN"), + create_word_field(path("CRES"), byte(0x14), "PMAX"), + create_byte_field(path("CRES"), byte(0x17), "PLEN"), + store(path("PPCI"), path("PMIN")), + store(path("PPCI"), path("PMAX")), + store(byte(0x8), path("PLEN")), + create_word_field(path("CRES"), byte(0x30), "CMIN"), + create_word_field(path("CRES"), byte(0x32), "CMAX"), + create_word_field(path("CRES"), byte(0x36), "CLEN"), + add(path("PMIN"), path("PLEN"), path("CMIN")), + add( + subtract(path("CMAX"), path("CMIN"), zero()), + one(), + path("CLEN"), + ), + ] +} + +/// PCI0's legacy VGA memory window. +fn vga_crs() -> Vec { + vec![ + create_dword_field(path("CRES"), byte(0x62), "FMIN"), + create_dword_field(path("CRES"), byte(0x66), "FMAX"), + create_dword_field(path("CRES"), byte(0x6e), "FLEN"), + store(path("VGAS"), path("FMIN")), + subtract(add(path("VGAS"), path("VGAL"), zero()), one(), path("FMAX")), + store(path("VGAL"), path("FLEN")), + ] +} + +fn osc() -> Term { + if_( + path("POSC"), + [ + name("SUPP", zero()), + name("CTRL", zero()), + serialized_method( + "_OSC", + 4, + [ + create_dword_field(arg(3), zero(), "CDW1"), + if_( + lequal( + arg(0), + // PCI Express host bridge _OSC + uuid(0x33db4d5b_1ff7_401c_9657_7441c03dd766), + ), + [ + create_dword_field(arg(3), byte(0x4), "CDW2"), + create_dword_field(arg(3), byte(0x8), "CDW3"), + store(path("CDW2"), path("SUPP")), + store(path("CDW3"), path("CTRL")), + and(path("CTRL"), byte(0x1f), path("CTRL")), + if_( + lnot(lequal(arg(1), one())), + [or(path("CDW1"), byte(0x8), path("CDW1"))], + ), + if_( + lnot(lequal(path("CDW3"), path("CTRL"))), + [or(path("CDW1"), byte(0x10), path("CDW1"))], + ), + store(path("CTRL"), path("CDW3")), + ret(arg(3)), + ], + ), + else_([or(path("CDW1"), byte(0x4), path("CDW1")), ret(arg(3))]), + ], + ), + ], + ) +} + +/// Swizzled INTx routing for 32 slots. PCI0 routes slot 1 INTA, the PIIX +/// function, to the dedicated `LNKS`. +fn prt(primary: bool) -> Term { + const LINKS: [&str; 4] = ["LNKA", "LNKB", "LNKC", "LNKD"]; + let routes = (0..32u32).flat_map(|slot| { + (0..4u8).map(move |pin| { + let address = if slot == 0 { + word(0xffff) + } else { + dword(slot << 16 | 0xffff) + }; + let pin_term = match pin { + 0 => zero(), + 1 => one(), + _ => byte(pin), + }; + let link = if primary && slot == 1 && pin == 0 { + "LNKS" + } else { + LINKS[(slot as usize + pin as usize + 3) % 4] + }; + package(vec![address, pin_term, path(link), zero()]) + }) + }); + name("_PRT", package(routes.collect())) +} diff --git a/dstack/crates/gcp-acpi/src/dsdt/pcihp.rs b/dstack/crates/gcp-acpi/src/dsdt/pcihp.rs new file mode 100644 index 0000000000..7e7d1017fa --- /dev/null +++ b/dstack/crates/gcp-acpi/src/dsdt/pcihp.rs @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! PCI hotplug registers (0xae00/0xae08) and the `PCEJ`/`PCNF` methods the +//! SSDT slot objects call. + +use crate::aml::FieldUnit::*; +use crate::aml::*; + +pub(super) fn build() -> Vec { + vec![scope( + "_SB.PCI0", + [ + op_region("PCST", SYSTEM_IO, word(0xae00), byte(0x8)), + field("PCST", 0x43, &[Named("PCIU", 32), Named("PCID", 32)]), + op_region("SEJ", SYSTEM_IO, word(0xae08), byte(0x4)), + field("SEJ", 0x43, &[Named("B0EJ", 32)]), + method("PCEJ", 1, [shift_left(one(), arg(0), path("B0EJ"))]), + method( + "PCNF", + 0, + [ + store(zero(), local(0)), + while_( + lless(local(0), byte(0x1f)), + [ + increment(local(0)), + if_( + and(path("PCIU"), shift_left(one(), local(0), zero()), zero()), + [call("PCNT", [local(0), one()])], + ), + if_( + and(path("PCID"), shift_left(one(), local(0), zero()), zero()), + [call("PCNT", [local(0), byte(0x3)])], + ), + ], + ), + ], + ), + ], + )] +} diff --git a/dstack/crates/gcp-acpi/src/lib.rs b/dstack/crates/gcp-acpi/src/lib.rs new file mode 100644 index 0000000000..2ea7e2f488 --- /dev/null +++ b/dstack/crates/gcp-acpi/src/lib.rs @@ -0,0 +1,220 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! Pure Rust generation of the ACPI blobs Google Compute Engine hands its +//! TDX guests over fw_cfg. +//! +//! GCE's TDVF measures `etc/table-loader`, `etc/vanadium/acpi/rsdp` and +//! `etc/vanadium/acpi/tables` into RTMR0 as three `ACPI DATA` events. They +//! are a function of the vCPU count, memory size and whether a GPU is +//! attached: disks, local SSDs and the zone do not change them. The output +//! matches GCE byte for byte for c3-standard-4, -8, -22, -44, -88 and -176 +//! and a3-highgpu-1g (one H100), which the tests replay. + +mod aml; +mod dsdt; +mod loader; +mod ssdt; +mod tables; + +use loader::{Loader, ZONE_FSEG, ZONE_HIGH}; + +pub const LOADER_FILE: &str = "etc/table-loader"; +pub const RSDP_FILE: &str = "etc/vanadium/acpi/rsdp"; +pub const TABLES_FILE: &str = "etc/vanadium/acpi/tables"; + +const GIB: u64 = 1 << 30; + +/// GCE puts two NUMA nodes on each socket. +const NODES_PER_SOCKET: u16 = 2; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MachineConfig { + pub cpu_count: u16, + pub memory_size: u64, + /// NUMA nodes. vCPUs and memory are split evenly between them. + pub numa_nodes: u16, + /// A GPU behind a second PCI root bridge, as on a3-highgpu-1g. + pub gpu: bool, +} + +impl MachineConfig { + /// End of the RAM below the 32-bit PCI hole, which a GPU widens. + pub fn low_memory_end(&self) -> u64 { + let end = if self.gpu { 2 * GIB } else { 3 * GIB }; + end.min(self.node_memory()) + } + + /// `(NUMA node, base, length)` of the RAM above 4 GiB: node 0 continues + /// the low RAM there and every further node follows contiguously. + pub fn high_memory(&self) -> impl Iterator { + let node_memory = self.node_memory(); + let node0 = node_memory - self.low_memory_end(); + (0..u32::from(self.numa_nodes)) + .map(move |node| match node { + 0 => (0, 4 * GIB, node0), + _ => ( + node, + 4 * GIB + node0 + u64::from(node - 1) * node_memory, + node_memory, + ), + }) + .filter(|&(_, _, length)| length > 0) + } + + fn node_memory(&self) -> u64 { + self.memory_size / u64::from(self.numa_nodes) + } + + /// `(APIC ID, NUMA node)` of every vCPU. Each socket starts at the next + /// power of two of its thread count. + fn cpus(&self) -> impl Iterator + Clone { + let per_node = self.cpu_count / self.numa_nodes; + let per_socket = per_node * NODES_PER_SOCKET.min(self.numa_nodes); + let stride = per_socket.next_power_of_two(); + (0..self.cpu_count).map(move |i| { + ( + i / per_socket * stride + i % per_socket, + u32::from(i / per_node), + ) + }) + } + + fn max_apic_id(&self) -> u16 { + self.cpus().last().map_or(0, |(id, _)| id) + } + + fn validate(&self) -> Result<(), Error> { + let (cpus, nodes) = (self.cpu_count, self.numa_nodes); + if nodes == 0 || cpus == 0 || !cpus.is_multiple_of(nodes) || self.max_apic_id() > 255 { + return Err(Error::Topology(cpus, nodes)); + } + if !self.memory_size.is_multiple_of(u64::from(nodes)) || self.node_memory() <= 0x10_0000 { + return Err(Error::MemorySize(self.memory_size)); + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AcpiBlobs { + pub tables: Vec, + pub rsdp: Vec, + pub loader: Vec, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("unsupported topology: {0} vCPUs on {1} NUMA nodes")] + Topology(u16, u16), + #[error("memory size {0:#x} does not cover low memory")] + MemorySize(u64), +} + +/// Generate the three measured fw_cfg blobs for one machine shape. +pub fn build(config: &MachineConfig) -> Result { + config.validate()?; + + let mut blob = Blob::default(); + let facs = blob.place(tables::facs()); + let dsdt = blob.place(tables::table(b"DSDT", 2, &dsdt::body(config.gpu))); + let facp = blob.place(tables::facp(facs.offset, dsdt.offset)); + let ssdt = blob.place(tables::table(b"SSDT", 2, &ssdt::body(config))); + let madt = blob.place(tables::madt(config)); + let waet = blob.place(tables::waet()); + let srat = blob.place(tables::srat(config)); + // GCE pads around the SLIT slot, which stays empty on single-node shapes. + blob.pad(16); + let slit = (config.numa_nodes > 1).then(|| blob.place(tables::slit(config))); + blob.pad(if slit.is_some() { 32 } else { 48 }); + let rsdt_entries: Vec = [facp, srat, madt, ssdt, waet] + .into_iter() + .chain(slit) + .collect(); + let rsdt = blob.place(tables::rsdt( + &rsdt_entries.iter().map(|t| t.offset).collect::>(), + )); + let rsdp = tables::rsdp(rsdt.offset); + + let mut l = Loader::default(); + l.allocate(RSDP_FILE, 16, ZONE_FSEG); + l.allocate(TABLES_FILE, 64, ZONE_HIGH); + for (index, bridge) in dsdt::host_bridges(config.gpu).enumerate() { + let offsets: Vec = dsdt::PCI_WINDOW_NAMES + .iter() + .map(|n| blob.name_value_offset(dsdt, bridge, n)) + .collect(); + l.patch_pci_windows(&offsets, index as u32); + } + blob.checksum(&mut l, dsdt); + for (field, size) in [(0x84, 8), (0x24, 4), (0x8c, 8), (0x28, 4)] { + // X_FIRMWARE_CTRL, FIRMWARE_CTRL, X_DSDT, DSDT + l.add_pointer(TABLES_FILE, TABLES_FILE, facp.offset + field, size); + } + for t in [facp, ssdt, madt, waet, srat].into_iter().chain(slit) { + blob.checksum(&mut l, t); + } + for i in 0..rsdt_entries.len() as u32 { + l.add_pointer(TABLES_FILE, TABLES_FILE, rsdt.offset + 36 + 4 * i, 4); + } + blob.checksum(&mut l, rsdt); + l.add_pointer(RSDP_FILE, TABLES_FILE, 16, 4); + l.add_checksum(RSDP_FILE, 8, 0, rsdp.len() as u32); + + Ok(AcpiBlobs { + tables: blob.0, + rsdp, + loader: l.finish(), + }) +} + +#[derive(Clone, Copy)] +struct Placed { + offset: u32, + length: u32, +} + +/// `etc/vanadium/acpi/tables`: tables packed on 16-byte boundaries. +#[derive(Default)] +struct Blob(Vec); + +impl Blob { + fn place(&mut self, table: Vec) -> Placed { + self.0.resize(self.0.len().next_multiple_of(16), 0); + let placed = Placed { + offset: self.0.len() as u32, + length: table.len() as u32, + }; + self.0.extend(table); + placed + } + + fn checksum(&self, loader: &mut Loader, t: Placed) { + loader.add_checksum(TABLES_FILE, t.offset + 9, t.offset, t.length); + } + + fn pad(&mut self, len: usize) { + self.0.resize(self.0.len().next_multiple_of(16) + len, 0); + } + + /// Blob offset of the integer data of `Name (n, ...)` inside `Device (device)` + /// of table `t`. + fn name_value_offset(&self, t: Placed, device: &str, n: &str) -> u32 { + let table = &self.0[t.offset as usize..(t.offset + t.length) as usize]; + let find = |from: usize, needle: &[u8]| { + table[from..] + .windows(needle.len()) + .position(|w| w == needle) + .map(|at| from + at + needle.len()) + .unwrap_or_else(|| panic!("DSDT has no {device}.{n}")) + }; + let device_start = find(0, &aml::name_seg(device)); + let mut name_op = vec![0x08]; + name_op.extend(aml::name_seg(n)); + // Skip the integer prefix byte. + t.offset + find(device_start, &name_op) as u32 + 1 + } +} + +#[cfg(test)] +mod tests; diff --git a/dstack/crates/gcp-acpi/src/loader.rs b/dstack/crates/gcp-acpi/src/loader.rs new file mode 100644 index 0000000000..a0f4707f8d --- /dev/null +++ b/dstack/crates/gcp-acpi/src/loader.rs @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! `etc/table-loader`: QEMU's 128-byte loader commands plus GCE's vendor +//! command that tells the firmware where to write the PCI windows. + +use crate::TABLES_FILE; + +const COMMAND_SIZE: usize = 128; +const FILE_NAME_SIZE: usize = 56; +/// Offsets one vendor command can carry. +const PATCH_OFFSETS_PER_COMMAND: usize = 16; +const PCI_WINDOW_PATCH: u32 = 0x8000_0003; + +#[derive(Default)] +pub(crate) struct Loader(Vec); + +fn file_name(name: &str) -> Vec { + let mut out = name.as_bytes().to_vec(); + out.resize(FILE_NAME_SIZE, 0); + out +} + +impl Loader { + fn push(&mut self, kind: u32, fields: Vec) { + let start = self.0.len(); + self.0.extend(kind.to_le_bytes()); + self.0.extend(fields); + assert!( + self.0.len() - start <= COMMAND_SIZE, + "loader command too long" + ); + self.0.resize(start + COMMAND_SIZE, 0); + } + + pub(crate) fn allocate(&mut self, file: &str, alignment: u32, zone: u8) { + let mut f = file_name(file); + f.extend(alignment.to_le_bytes()); + f.push(zone); + self.push(1, f); + } + + pub(crate) fn add_pointer(&mut self, dest: &str, src: &str, offset: u32, size: u8) { + let mut f = file_name(dest); + f.extend(file_name(src)); + f.extend(offset.to_le_bytes()); + f.push(size); + self.push(2, f); + } + + pub(crate) fn add_checksum(&mut self, file: &str, offset: u32, start: u32, length: u32) { + let mut f = file_name(file); + for v in [offset, start, length] { + f.extend(v.to_le_bytes()); + } + self.push(3, f); + } + + /// GCE vendor commands: offsets of the DSDT integers the firmware + /// overwrites with the PCI windows of host bridge `bridge`, 16 per + /// command, numbered consecutively and followed by the bridge index. + pub(crate) fn patch_pci_windows(&mut self, offsets: &[u32], bridge: u32) { + for (i, chunk) in offsets.chunks(PATCH_OFFSETS_PER_COMMAND).enumerate() { + let mut f = file_name(TABLES_FILE); + f.extend(chunk.iter().flat_map(|o| o.to_le_bytes())); + f.extend(bridge.to_le_bytes()); + self.push(PCI_WINDOW_PATCH + i as u32, f); + } + } + + pub(crate) fn finish(self) -> Vec { + self.0 + } +} + +/// Zones of the `ALLOCATE` command. +pub(crate) const ZONE_HIGH: u8 = 1; +pub(crate) const ZONE_FSEG: u8 = 2; diff --git a/dstack/crates/gcp-acpi/src/ssdt.rs b/dstack/crates/gcp-acpi/src/ssdt.rs new file mode 100644 index 0000000000..ada339a08a --- /dev/null +++ b/dstack/crates/gcp-acpi/src/ssdt.rs @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! GCE's SSDT: sleep states, the pvpanic device, PCI hotplug slots and one +//! hot-pluggable processor device per vCPU, named and numbered by APIC ID. + +use crate::aml::res::*; +use crate::aml::FieldUnit::*; +use crate::aml::*; +use crate::MachineConfig; + +/// SSDT body: everything after the 36-byte table header. +pub(crate) fn body(config: &MachineConfig) -> Vec { + let externals = if_( + zero(), + [ + external("\\_SB.PCI0", DEVICE_OBJ, 0), + external("\\_SB.PCI0.ISA", DEVICE_OBJ, 0), + external("\\_SB.PCI0.PCEJ", METHOD_OBJ, 1), + ], + ); + let sleep_states = scope( + "\\", + [ + name("_S3", package(vec![one(), one(), zero(), zero()])), + name("_S4", package(vec![zero(), zero(), zero(), zero()])), + name("_S5", package(vec![zero(), zero(), zero(), zero()])), + ], + ); + let pvpanic = scope( + "\\_SB.PCI0.ISA", + [device( + "PEVT", + [ + name("_HID", string("QEMU0001")), + name("PEST", word(0x0505)), + op_region("PEOR", SYSTEM_IO, path("PEST"), one()), + field("PEOR", 0x01, &[Named("PEPT", 8)]), + method( + "_STA", + 0, + [ + store(path("PEST"), local(0)), + if_(lequal(local(0), zero()), [ret(zero())]), + else_([ret(byte(0x0f))]), + ], + ), + method("RDPT", 0, [store(path("PEPT"), local(0)), ret(local(0))]), + method("WRPT", 1, [store(arg(0), path("PEPT"))]), + name("_CRS", resource_template([io(0, 0, 1, 1)])), + create_word_field(path("_CRS"), byte(2), "IOMN"), + create_word_field(path("_CRS"), byte(4), "IOMX"), + method( + "_INI", + 0, + [ + store(path("PEST"), path("IOMN")), + store(path("PEST"), path("IOMX")), + ], + ), + ], + )], + ); + let slot = |s: u8| format!("S{s:02X}"); + let slots = 1..0x20u8; + let pci_hotplug = scope( + "_SB", + [ + method("MNOT", 2, []), + // PCI hotplug is off when a GPU sits behind a second root bridge. + name("PCHP", if config.gpu { zero() } else { one() }), + if_( + path("PCHP"), + [scope( + "PCI0", + slots + .clone() + .map(|s| { + device( + &slot(s), + [ + name("_SUN", int(s.into())), + name("_ADR", dword(u32::from(s) << 16)), + method( + "NOEJ", + 1, + [if_( + lequal(arg(0), one()), + [call("PCEJ", [path("_SUN")])], + )], + ), + ], + ) + }) + .chain([method( + "PCNT", + 2, + slots.map(|s| { + if_( + lequal(arg(0), int(s.into())), + [notify(path(&slot(s)), arg(1))], + ) + }), + )]), + )], + ), + ], + ); + let ids: Vec = config.cpus().map(|(id, _)| id).collect(); + let cpu = |id: u16| format!("C{id:03X}"); + let processors = ids.iter().map(|&id| { + scope( + "_SB", + [device( + &cpu(id), + [ + name("_HID", string("ACPI0007")), + name("_UID", word(id)), + method("_MAT", 0, [ret(call("CPMA", [path("_UID")]))]), + method("_STA", 0, [ret(call("CPST", [path("_UID")]))]), + method("_EJ0", 1, [call("CPEJ", [path("_UID"), arg(0)])]), + ], + )], + ) + }); + // Indexed by APIC ID: the IDs between sockets are absent. + let present = scope( + "_SB", + [name( + "CPON", + package( + (0..=config.max_apic_id()) + .map(|id| if ids.contains(&id) { one() } else { zero() }) + .collect(), + ), + )], + ); + let notify_cpu = scope( + "_SB", + [method( + "NTFY", + 2, + ids.iter() + .map(|&id| if_(lequal(arg(0), word(id)), [notify(path(&cpu(id)), arg(1))])), + )], + ); + [externals, sleep_states, pvpanic, pci_hotplug] + .into_iter() + .chain(processors) + .chain([present, notify_cpu]) + .flatten() + .collect() +} diff --git a/dstack/crates/gcp-acpi/src/tables.rs b/dstack/crates/gcp-acpi/src/tables.rs new file mode 100644 index 0000000000..2f32070bbd --- /dev/null +++ b/dstack/crates/gcp-acpi/src/tables.rs @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! The fixed-layout ACPI tables. Table pointers hold offsets into the +//! `etc/vanadium/acpi/tables` blob and checksums are zero: the firmware fixes +//! both up while running the loader script, after measuring the blob. + +use crate::{MachineConfig, NODES_PER_SOCKET}; + +/// Standard table header with GCE's OEM fields and a zero checksum. +pub(crate) fn table(signature: &[u8; 4], revision: u8, body: &[u8]) -> Vec { + let length = u32::try_from(36 + body.len()).expect("ACPI table fits in u32"); + let mut out = signature.to_vec(); + out.extend(length.to_le_bytes()); + out.extend([revision, 0]); + out.extend(b"Google"); + out.extend(b"GOOG"); + out.extend(signature); + out.extend(1u32.to_le_bytes()); + out.extend(b"GOOG"); + out.extend(1u32.to_le_bytes()); + out.extend(body); + out +} + +pub(crate) fn facs() -> Vec { + let mut out = b"FACS".to_vec(); + out.extend(64u32.to_le_bytes()); + out.resize(64, 0); + out +} + +/// Generic Address Structure. +fn gas(space: u8, bit_width: u8, access_size: u8, address: u64) -> Vec { + let mut out = vec![space, bit_width, 0, access_size]; + out.extend(address.to_le_bytes()); + out +} + +const NULL_GAS: [u8; 12] = [0; 12]; +const SYSTEM_IO: u8 = 1; +const PM1_EVT: u16 = 0xb000; +const PM1_CNT: u16 = 0xb004; +const PM_TMR: u16 = 0xb008; +const GPE0: u16 = 0xafe0; + +/// FADT revision 6.4, PIIX4-style fixed hardware at 0xb000. +pub(crate) fn facp(facs: u32, dsdt: u32) -> Vec { + let mut b = Vec::new(); + b.extend(facs.to_le_bytes()); + b.extend(dsdt.to_le_bytes()); + b.extend([1, 0]); // reserved (model), unspecified PM profile + b.extend(9u16.to_le_bytes()); // SCI_INT + b.extend(0xb2u32.to_le_bytes()); // SMI_CMD + b.extend([0xf1, 0xf0, 0, 0]); // ACPI_ENABLE, ACPI_DISABLE, S4BIOS_REQ, PSTATE_CNT + for block in [PM1_EVT, 0, PM1_CNT, 0, 0, PM_TMR, GPE0, 0] { + b.extend(u32::from(block).to_le_bytes()); + } + b.extend([4, 2, 0, 4, 4, 0, 0, 0]); // block lengths, GPE1_BASE, CST_CNT + b.extend(0xfffu16.to_le_bytes()); // P_LVL2_LAT: C2 unsupported + b.extend(0xfffu16.to_le_bytes()); // P_LVL3_LAT: C3 unsupported + b.extend([0; 4]); // FLUSH_SIZE, FLUSH_STRIDE + b.extend([0; 5]); // DUTY_OFFSET, DUTY_WIDTH, DAY_ALRM, MON_ALRM, CENTURY + b.extend([0; 3]); // IAPC_BOOT_ARCH, reserved + b.extend(0x8485u32.to_le_bytes()); // WBINVD | PROC_C1 | SLP_BUTTON | RESET_REG_SUP | USE_PLATFORM_CLOCK + b.extend(gas(SYSTEM_IO, 8, 1, 0xcf9)); // RESET_REG + b.push(6); // RESET_VALUE + b.extend([0, 0]); // ARM_BOOT_ARCH + b.push(4); // FADT minor version + b.extend(u64::from(facs).to_le_bytes()); + b.extend(u64::from(dsdt).to_le_bytes()); + b.extend(gas(SYSTEM_IO, 32, 2, PM1_EVT.into())); + b.extend(NULL_GAS); + b.extend(gas(SYSTEM_IO, 16, 2, PM1_CNT.into())); + b.extend(NULL_GAS); // X_PM1b_CNT_BLK + b.extend(NULL_GAS); // X_PM2_CNT_BLK + b.extend(gas(SYSTEM_IO, 32, 3, PM_TMR.into())); + b.extend(gas(SYSTEM_IO, 32, 1, GPE0.into())); + b.extend(NULL_GAS); // X_GPE1_BLK + b.extend(NULL_GAS); // SLEEP_CONTROL_REG + b.extend(NULL_GAS); // SLEEP_STATUS_REG + b.extend([0; 8]); // hypervisor vendor identity + table(b"FACP", 6, &b) +} + +/// APIC IDs in MADT order: the first thread of every core, then the siblings. +fn apic_ids(config: &MachineConfig) -> Vec { + let mut ids: Vec = config.cpus().map(|(id, _)| id as u8).collect(); + ids.sort_by_key(|id| (id % 2, *id)); + ids +} + +pub(crate) fn madt(config: &MachineConfig) -> Vec { + let mut b = Vec::new(); + b.extend(0xfee0_0000u32.to_le_bytes()); // local APIC address + b.extend(1u32.to_le_bytes()); // PCAT_COMPAT + for id in apic_ids(config) { + b.extend([0, 8, id, id]); // processor local APIC: UID == APIC ID + b.extend(1u32.to_le_bytes()); // enabled + } + b.extend([1, 12, 0, 0]); // I/O APIC 0 + b.extend(0xfec0_0000u32.to_le_bytes()); + b.extend(0u32.to_le_bytes()); // GSI base + for irq in [5u8, 9, 10, 11] { + b.extend([2, 10, 0, irq]); // interrupt source override, ISA bus + b.extend(u32::from(irq).to_le_bytes()); + b.extend(0xdu16.to_le_bytes()); // active high, level triggered + } + b.extend([4, 6, 0xff, 0, 0, 1]); // local APIC NMI on LINT1 of every processor + table(b"APIC", 5, &b) +} + +pub(crate) fn waet() -> Vec { + table(b"WAET", 1, &2u32.to_le_bytes()) // ACPI PM timer: one read is good enough +} + +pub(crate) fn srat(config: &MachineConfig) -> Vec { + let mut b = Vec::new(); + b.extend(1u32.to_le_bytes()); // reserved, must be 1 + b.extend([0; 8]); + for (id, node) in config.cpus() { + b.extend([0, 16, node as u8, id as u8]); // processor affinity + b.extend(1u32.to_le_bytes()); // enabled + b.extend([0; 4]); // SAPIC EID, proximity domain [31:8] + b.extend([0; 4]); // clock domain + } + let mut memory = |node: u32, base: u64, length: u64| { + b.extend([1, 40]); + b.extend(node.to_le_bytes()); + b.extend([0; 2]); + b.extend(base.to_le_bytes()); + b.extend(length.to_le_bytes()); + b.extend([0; 4]); + b.extend(1u32.to_le_bytes()); // enabled + b.extend([0; 8]); + }; + memory(0, 0, 0xa_0000); + memory(0, 0x10_0000, config.low_memory_end() - 0x10_0000); + for (node, base, length) in config.high_memory() { + memory(node, base, length); + } + table(b"SRAT", 3, &b) +} + +/// Relative distances: 10 within a node, 12 between the two nodes of a +/// socket, 21 across sockets. +pub(crate) fn slit(config: &MachineConfig) -> Vec { + let nodes = config.numa_nodes; + let mut b = u64::from(nodes).to_le_bytes().to_vec(); + for i in 0..nodes { + for j in 0..nodes { + b.push( + match (i == j, i / NODES_PER_SOCKET == j / NODES_PER_SOCKET) { + (true, _) => 10, + (false, true) => 12, + (false, false) => 21, + }, + ); + } + } + table(b"SLIT", 1, &b) +} + +pub(crate) fn rsdt(entries: &[u32]) -> Vec { + let body: Vec = entries.iter().flat_map(|e| e.to_le_bytes()).collect(); + table(b"RSDT", 1, &body) +} + +/// ACPI 1.0 RSDP padded to the 2.0 size, as GCE ships it. +pub(crate) fn rsdp(rsdt: u32) -> Vec { + let mut out = b"RSD PTR ".to_vec(); + out.push(0); // checksum + out.extend(b"Google"); + out.push(0); // revision + out.extend(rsdt.to_le_bytes()); + out.resize(36, 0); + out +} diff --git a/dstack/crates/gcp-acpi/src/tests.rs b/dstack/crates/gcp-acpi/src/tests.rs new file mode 100644 index 0000000000..7bdcbc8533 --- /dev/null +++ b/dstack/crates/gcp-acpi/src/tests.rs @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +use sha2::{Digest, Sha384}; + +use crate::{build, MachineConfig}; + +/// A c3-standard shape: 4 GiB per vCPU, at most 44 vCPUs per NUMA node. +fn c3_standard(cpu_count: u16, numa_nodes: u16) -> MachineConfig { + MachineConfig { + cpu_count, + memory_size: u64::from(cpu_count) << 32, + numa_nodes, + gpu: false, + } +} + +const A3_HIGHGPU_1G: MachineConfig = MachineConfig { + cpu_count: 26, + memory_size: 234 << 30, + numa_nodes: 1, + gpu: true, +}; + +/// `ACPI DATA` digests from RTMR0 event logs of GCE TDX VMs, captured +/// 2026-12-02, in measurement order: table-loader, rsdp, tables. Disks, local +/// SSDs and the zone were varied without changing them. +fn captured() -> [(&'static str, MachineConfig, [&'static str; 3]); 7] { + [ + ( + "c3-standard-4", + c3_standard(4, 1), + [ + "ee0cc4f8fa34d548c7bad109ad5da7a7469c6a84967b919120b63bdfd9a50def29f37e0b7f0d40110304c70f1615998f", + "957129f88ef987bf483b2fd0b8b7fab43b5477e394a683f74fbf662217e8fa2279c2fed9b877ccea0c9b9be916b55cca", + "70cb7693cd1bee8a9870f8ab7b049e06960196c7f3c1a486b771d8205446ede22d45b7bcc3bbc0e9ec44b5eb7df3b84d", + ], + ), + ( + "c3-standard-8", + c3_standard(8, 1), + [ + "e828c43ec73e8bf887cd888d218257b453918c2dea7fba9c76344346d55c94f70a927ed0b342ba39bb88bdfae7226117", + "4b7f3aadcf86c3b58eb55c5a30026cdfc89db04af2b33e3e3e063c117d08b7af34cac43038da500718d89d09d81ee418", + "b3eaba03d9fc5a068e3bd3a88a4840642d65a10df4017eb6dff01e3ee469e7acd587839cc94b29a180bca1a13e6b9cfd", + ], + ), + ( + "c3-standard-22", + c3_standard(22, 1), + [ + "e9546f446612a4e1597caa283f52b5204c7739a1157f3b51bda90b4b9af3f56d443ab5ff9929079cfb523a91e3ee305e", + "23307a6e9314329d1a87c5eed0e4456e9c3d3912efe1ef0af6b8db62aeeff1cfda182a5245bedc3e74098eb103a6ef9f", + "fb3f7aef27e8bf958cdadf394dd6fa5f4b35a3760325052483d7bcf81eeb7be2796d017b9300c0de8104c71530181b3c", + ], + ), + ( + "c3-standard-44", + c3_standard(44, 1), + [ + "700fcf25c0a5719655e82a0122ea13dc440be8dbc326a6ceabc2c50af3ff26f666ec923e1595c0efa1c529fcb42304a7", + "82cdb41605a0514294b961a606f45649b514a66bbb15558e405e274f3ea4e2bae089d601b50bc29785e37d026a770d6d", + "4170f5e3d6d4b5e9ec2d171a52f08f47136839807e5466ef5527b86a91530b49515dedc9e5d5bf132b1c9477c653f634", + ], + ), + ( + "c3-standard-88", + c3_standard(88, 2), + [ + "6f0e6afb42ef596e115cd26cec263aacdbe1053c81a7b50aa6f0c6e1fa84e13b5bd92abb79c94a88db12ceb90b5e6a2a", + "abe9471a1fdb8c47e3aa113b9d6dc796a6622bf7a845081f55b4d3c3e8840aa870d1d1ebaf8926d6f2497930142f796a", + "42d328afbe9a44b87bb3093c6effcc3b3b30ef326fcf1ded027d04a3895517fe82ec9314d6fb831726c2b119e9258d7e", + ], + ), + ( + "c3-standard-176", + c3_standard(176, 4), + [ + "f8b3e3e2b43e3a1dec676f8e7796bb8b41d1859cc7a09da527730205838b5d40f10ed41bf71fa4120e1240fd5a341a67", + "92a6a07e0a02159e8500507ab9776e67b3c06ee38413ae18d1b30ac63c60fd4a8ab73acc8dedeb0ade6bf07a132fc05b", + "25ef23269edbcd233a7495f0e712cd0e6d4c678c046fee87bab7faff6dc5e711141cc01ba590a16e9320df68f9a7765f", + ], + ), + ( + "a3-highgpu-1g", + A3_HIGHGPU_1G, + [ + "bc851aa5b6e82ceca70f74c7405eca6f4bbccffa58637f52b06a22919574d6e336ab6c193798b926c1d942659176eaa4", + "088f7b46561423db400530582ed615f6c56f3686c8429f4cfef852925973edebe8b1fb9108bb6e808b4d9691388c381a", + "5b82d54c5794f5021247db1aabcf8aacd4de446348d6593b7f854a385843600a9216bcf9c23106af847aa839ea46ddfd", + ], + ), + ] +} + +#[test] +fn matches_gce_measurements() { + for (shape, config, expected) in captured() { + let blobs = build(&config).unwrap(); + let actual = + [&blobs.loader, &blobs.rsdp, &blobs.tables].map(|b| hex::encode(Sha384::digest(b))); + assert_eq!(actual, expected, "{shape}"); + } +} diff --git a/dstack/dstack-attest/src/attestation.rs b/dstack/dstack-attest/src/attestation.rs index 8060ef7c64..a38a47b4d2 100644 --- a/dstack/dstack-attest/src/attestation.rs +++ b/dstack/dstack-attest/src/attestation.rs @@ -327,7 +327,7 @@ fn tdx_root_der(root: Vec) -> Result> { pub use tpm_types::TpmQuote; use crate::amd_sev_snp::{AmdKdsClient, VerifiedAmdSnpReport}; -use crate::v1::{strip_tdx_event_log_for_config, strip_tdx_runtime_event_log}; +use crate::v1::{strip_gcp_tdx_event_log, strip_tdx_event_log_for_config}; pub use crate::v1::{Attestation as AttestationV1, PlatformEvidence, StackEvidence}; pub const SNP_REPORT_DATA_RANGE: std::ops::Range = 0x50..0x90; @@ -915,9 +915,8 @@ impl VersionedAttestation { ); } AttestationQuote::DstackGcpTdx(quote) => { - quote.tdx_quote.event_log = strip_tdx_runtime_event_log(std::mem::take( - &mut quote.tdx_quote.event_log, - )); + quote.tdx_quote.event_log = + strip_gcp_tdx_event_log(std::mem::take(&mut quote.tdx_quote.event_log)); } AttestationQuote::DstackAmdSevSnp(_) | AttestationQuote::DstackNitroEnclave(_) diff --git a/dstack/dstack-attest/src/v1.rs b/dstack/dstack-attest/src/v1.rs index 168fd58a89..b6a4fa39c6 100644 --- a/dstack/dstack-attest/src/v1.rs +++ b/dstack/dstack-attest/src/v1.rs @@ -16,14 +16,6 @@ pub(crate) fn is_tdx_acpi_data_event(event: &TdxEvent) -> bool { tdx::is_tdx_acpi_data_event(event) } -pub(crate) fn strip_tdx_runtime_event_log(event_log: Vec) -> Vec { - event_log - .into_iter() - .filter(|event| event.imr == 3) - .map(|event| event.stripped()) - .collect() -} - fn strip_tdx_lite_acpi_data_event(event: TdxEvent) -> TdxEvent { let mut event = event.stripped(); event.event_payload = TDX_ACPI_DATA_EVENT_PAYLOAD.to_vec(); @@ -45,10 +37,29 @@ pub(crate) fn strip_tdx_lite_event_log(event_log: Vec) -> Vec) -> Vec { + event_log + .into_iter() + .filter_map(|event| { + if is_tdx_acpi_data_event(&event) { + Some(strip_tdx_lite_acpi_data_event(event)) + } else if event.imr == 0 || event.imr == 3 { + Some(event.stripped()) + } else { + None + } + }) + .collect() +} + /// Always keep the RTMR0 ACPI DATA digest events (in addition to RTMR3 /// runtime events), regardless of the boot's `tdx_attestation_variant`. This -/// makes `strip_tdx_lite_event_log`'s output a strict superset of -/// `strip_tdx_runtime_event_log`'s, so a verifier can independently choose +/// makes `strip_tdx_lite_event_log`'s output a strict superset of the +/// runtime-only log, so a verifier can independently choose /// lite or legacy verification for any TDX boot instead of being limited to /// whatever the VMM resolved at launch. See /// `dstack_types::TdxAttestationVariant` for the full rationale. @@ -177,7 +188,7 @@ impl PlatformEvidence { tpm_quote, } => Self::GcpTdx { quote, - event_log: strip_tdx_runtime_event_log(event_log), + event_log: strip_gcp_tdx_event_log(event_log), tpm_quote, }, // No TDX event log to strip. Listed rather than caught by a @@ -615,6 +626,24 @@ mod tests { assert_eq!(stripped[3].event_payload, vec![0x42]); } + #[test] + fn gcp_stripping_keeps_rtmr0_digests_and_runtime_payloads() { + let mut event_log = (0..20).map(boot_event).collect::>(); + event_log[3] = acpi_data_event(3); + event_log.push(runtime_event()); + + let stripped = strip_gcp_tdx_event_log(event_log.clone()); + + let rtmr0 = event_log.iter().filter(|e| e.imr == 0).count(); + assert_eq!(stripped.len(), rtmr0 + 1); + assert!(stripped + .iter() + .filter(|e| e.imr == 0 && !is_tdx_acpi_data_event(e)) + .all(|e| e.event_payload.is_empty())); + assert_eq!(stripped[3].event_payload, TDX_ACPI_DATA_EVENT_PAYLOAD); + assert_eq!(stripped.last().unwrap().event_payload, vec![0x42]); + } + #[test] fn tdx_event_log_accessors_agree_on_gcp_tdx() { // The mut accessor used to match bare TDX only, so `fill_v2_preimages` diff --git a/dstack/dstack-mr/Cargo.toml b/dstack/dstack-mr/Cargo.toml index 631e74a143..a4cc4ffab8 100644 --- a/dstack/dstack-mr/Cargo.toml +++ b/dstack/dstack-mr/Cargo.toml @@ -37,6 +37,7 @@ scale.workspace = true dstack-types.workspace = true cc-eventlog.workspace = true qemu-acpi.workspace = true +gcp-acpi.workspace = true [dev-dependencies] dcap-qvl.workspace = true diff --git a/dstack/dstack-mr/src/gcp.rs b/dstack/dstack-mr/src/gcp.rs new file mode 100644 index 0000000000..a110a70ab0 --- /dev/null +++ b/dstack/dstack-mr/src/gcp.rs @@ -0,0 +1,345 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +//! GCP TDX boot-chain verification. +//! +//! GCE boots dstack's UKI disk with its own TDVF. This module checks every +//! register that boot produces instead of only the vTPM: +//! +//! - MRTD must be one of the GCE firmware builds listed in [`FIRMWARE`]. +//! - RTMR[0] is replayed from the attested event log. The firmware volume, +//! TD HOB and ACPI events must equal values recomputed here; the remaining +//! events are UEFI variables, whose contents only drive Secure Boot and +//! boot-device selection, both of which RTMR[1] pins down. +//! - RTMR[1] and RTMR[2] must equal the image's `measurement.gcp.cbor`, which +//! [`image_measurement`] derives from the UKI and its disk at build time. + +use anyhow::{bail, ensure, Context, Result}; +use cc_eventlog::TdxEvent; +use dstack_types::GcpTdxImageMeasurement; +pub use gcp_acpi::MachineConfig; +use hex_literal::hex; +use object::read::pe::PeFile64; + +use crate::kernel::authenticode_sha384_hash; +use crate::tdx::rtmr0_acpi_hashes_from_event_log; +use crate::util::{measure_log, measure_sha384}; +use crate::TdxMeasurements; + +/// A GCE TDVF build, identified by its MRTD. +struct Firmware { + /// Upload date of the build in `gs://gce_tcb_integrity/ovmf_x64_csm/`. + released: &'static str, + mrtd: [u8; 48], + /// SHA-384 of the configuration firmware volume, measured into RTMR[0]. + cfv: [u8; 48], +} + +/// GCE TDVF builds this verifier accepts: the builds GCE deployed as of +/// 2026-12 (2026-06-26 on a3-highgpu hosts, 2026-08-31 on c3) and the TDX +/// builds Google has endorsed since. MRTD and CFV are computed from the +/// published `.fd` images, whose TDX endorsements Google signs. +const FIRMWARE: &[Firmware] = &[ + Firmware { + released: "2026-06-26", + mrtd: hex!("8feb9ece523f9e458b156ffd84268bd88e6bfae2054c107d35a70f235e2fab67273bb4cb4d9e986e38a71ae4a402c4b6"), + cfv: hex!("1b0f9128a714869da1b6e8082d41f37f37f0f1f98b56eeb9074df94707a5994f0e9e8fe80725580274724ae6c179a1fb"), + }, + Firmware { + released: "2026-08-31", + mrtd: hex!("f21e6b48743fe14c2d090078ca1197f09ae4c99438677f2c79901ef80e2aeefe2f9a7eb6e3eb3b5047c4f1511731e5d3"), + cfv: hex!("98f78a03fdbd6f31e54b65dd0518b9a043b05c700339efb71ffae8335d6d1e60395dc5b0c719d5c1ccb41af64fd88849"), + }, + Firmware { + released: "2026-09-01", + mrtd: hex!("5546bb7690b1a521034b85d57fa910b272aeebe09c373bc1573e02d9c3a02984c1bebbab575214c5bdee794b9a2325b9"), + cfv: hex!("b44896db0078a89cda6b0b9ccb765f8088d1fcb151ab36e8866881ddec184307548810b6b203a93ad9166f5998416aa4"), + }, + Firmware { + released: "2026-10-05", + mrtd: hex!("85aefc5d443857c9df7fdcb2a52819268aaa5f094a40601fad6d525d18651c005fe23f4efb9c10d02e3fa27edf147b7b"), + cfv: hex!("b054c5f393e176aed46a4ada530fedf6fd4c7159c98b805153e408e294a33325d625d9a685829d1612e95b4c33a5a9c9"), + }, + Firmware { + released: "2026-11-04", + mrtd: hex!("8fd75eca6224a7adfb22d3c65d41cd0e8ba0e5d9a67d97f084fafa9aa2c1eff61829137cfd58e7e3cdaa7602c58912c5"), + cfv: hex!("ff46b9e8ffb8ef8657e2004db29aba1364edcb33beddf4ac43fd6eb938019473aa887f83b28bae688fa796031bafdeb7"), + }, + Firmware { + released: "2026-11-04", + mrtd: hex!("7f1769ec253b5b99541974edc4f3cf1af0c35aba43ebeb4e4962d78a73ec46e3833960c98b6d5906e89ed63fb687ba20"), + cfv: hex!("d972b290aa49524ead50a9787b48f0014ae27b56d84bb2140d0cf7accf040b5f8c63efdf3f088a71b673e0300fdd53da"), + }, +]; + +/// TDVF metadata sections of every build in [`FIRMWARE`], in metadata order +/// (BFV, CFV, three temporary-memory ranges around the TD HOB), as +/// `(guest address, size)`. +const TDVF_SECTIONS: [(u64, u64); 6] = [ + (0xffe2_0000, 0x1e_0000), + (0xffe0_0000, 0x2_0000), + (0x81_1000, 0xf000), + (0x80_b000, 0x2000), + (0x80_9000, 0x2000), + (0x80_0000, 0x6000), +]; +const TD_HOB_BASE: u64 = 0x80_9000; + +const EV_SEPARATOR: u32 = 0x4; +const EV_ACPI_DATA: u32 = 0xa; +const EV_EFI_VARIABLE_DRIVER_CONFIG: u32 = 0x8000_0001; +const EV_EFI_VARIABLE_BOOT: u32 = 0x8000_0002; +const EV_EFI_PLATFORM_FIRMWARE_BLOB2: u32 = 0x8000_000a; +const EV_EFI_HANDOFF_TABLES2: u32 = 0x8000_000b; +const EV_EFI_VARIABLE_AUTHORITY: u32 = 0x8000_00e0; + +/// The TD HOB GCE hands to TDVF: one resource per TDVF section, then the rest +/// of RAM as unaccepted memory: below the PCI hole, then one range per NUMA +/// node from 4 GiB upwards. +fn td_hob(machine: &MachineConfig) -> Vec { + const SYSTEM_MEMORY: u32 = 0; + const UNACCEPTED_MEMORY: u32 = 7; + const PRESENT_INITIALIZED_TESTED: u32 = 0x7; + const UNACCEPTED_ATTRIBUTES: u32 = 0x1000_0007; + + // EFI_HOB_HANDOFF_INFO_TABLE, version 9; EfiEndOfHobList is patched below. + let mut hob = vec![0u8; 56]; + hob[..4].copy_from_slice(&[0x01, 0x00, 56, 0]); + hob[8..12].copy_from_slice(&9u32.to_le_bytes()); + let mut resource = |kind: u32, attributes: u32, start: u64, length: u64| { + hob.extend([0x03, 0x00, 48, 0, 0, 0, 0, 0]); + hob.extend([0; 16]); // owner GUID + hob.extend(kind.to_le_bytes()); + hob.extend(attributes.to_le_bytes()); + hob.extend(start.to_le_bytes()); + hob.extend(length.to_le_bytes()); + }; + for (start, length) in TDVF_SECTIONS { + resource(SYSTEM_MEMORY, PRESENT_INITIALIZED_TESTED, start, length); + } + let low_end = machine.low_memory_end(); + let mut accepted: Vec<_> = TDVF_SECTIONS + .into_iter() + .filter(|(start, length)| start + length <= low_end) + .collect(); + accepted.sort(); + let mut cursor = 0; + for (start, length) in accepted { + if start > cursor { + resource( + UNACCEPTED_MEMORY, + UNACCEPTED_ATTRIBUTES, + cursor, + start - cursor, + ); + } + cursor = start + length; + } + resource( + UNACCEPTED_MEMORY, + UNACCEPTED_ATTRIBUTES, + cursor, + low_end - cursor, + ); + for (_, base, length) in machine.high_memory() { + resource(UNACCEPTED_MEMORY, UNACCEPTED_ATTRIBUTES, base, length); + } + let end_of_hob_list = TD_HOB_BASE + hob.len() as u64; + hob[48..56].copy_from_slice(&end_of_hob_list.to_le_bytes()); + hob +} + +/// Verify MRTD and RTMR[0..2] of a GCP TDX boot against its image measurement. +/// +/// `verified_mrs` must come from a verified quote and `event_log` must hold the +/// RTMR[0] events of that boot (payloads may be stripped; ACPI DATA events must +/// carry their names). `machine` is the VM shape the host claims; it is only +/// trusted as far as it reproduces the measured ACPI tables and TD HOB. Does +/// not judge RTMR[3] or the vTPM. +pub fn verify_gcp_tdx_boot( + verified_mrs: &TdxMeasurements, + event_log: &[TdxEvent], + image: &GcpTdxImageMeasurement, + machine: &MachineConfig, +) -> Result<()> { + let firmware = FIRMWARE + .iter() + .find(|f| f.mrtd[..] == verified_mrs.mrtd[..]) + .with_context(|| { + format!( + "MRTD {} is not a known GCE TDVF build", + hex::encode(&verified_mrs.mrtd) + ) + })?; + verify_rtmr0(firmware, verified_mrs, event_log, machine) + .with_context(|| format!("RTMR0 of GCE TDVF {} does not verify", firmware.released))?; + for (name, expected, actual) in [ + ("RTMR1", &image.rtmr1, &verified_mrs.rtmr1), + ("RTMR2", &image.rtmr2, &verified_mrs.rtmr2), + ] { + ensure!( + expected == actual, + "{name} mismatch: expected={}, actual={}", + hex::encode(expected), + hex::encode(actual) + ); + } + Ok(()) +} + +fn verify_rtmr0( + firmware: &Firmware, + verified_mrs: &TdxMeasurements, + event_log: &[TdxEvent], + machine: &MachineConfig, +) -> Result<()> { + let events: Vec<&TdxEvent> = event_log.iter().filter(|e| e.imr == 0).collect(); + let replayed = measure_log(&events.iter().map(|e| e.digest()).collect::>()); + ensure!( + replayed == verified_mrs.rtmr0, + "event log replays to {}, quote has {}", + hex::encode(&replayed), + hex::encode(&verified_mrs.rtmr0) + ); + + let reported_acpi = rtmr0_acpi_hashes_from_event_log(event_log)?; + let blobs = gcp_acpi::build(machine).context("unsupported machine shape")?; + ensure!( + [blobs.loader, blobs.rsdp, blobs.tables].map(|b| measure_sha384(&b)) + == [ + reported_acpi.loader, + reported_acpi.rsdp, + reported_acpi.tables + ], + "ACPI tables do not match {machine:?}" + ); + + let separator = measure_sha384(&[0; 4]); + let hob = measure_sha384(&td_hob(machine)); + let mut seen_hob = 0; + let mut seen_cfv = 0; + let mut seen_separator = 0; + for event in events { + let digest = event.digest(); + match event.event_type { + EV_EFI_HANDOFF_TABLES2 => { + ensure!(digest == hob, "TD HOB does not match {machine:?}"); + seen_hob += 1; + } + EV_EFI_PLATFORM_FIRMWARE_BLOB2 => { + ensure!( + digest[..] == firmware.cfv, + "configuration firmware volume mismatch" + ); + seen_cfv += 1; + } + EV_SEPARATOR => { + ensure!(digest == separator, "unexpected separator digest"); + seen_separator += 1; + } + // Checked against the regenerated tables above. + EV_ACPI_DATA => {} + EV_EFI_VARIABLE_DRIVER_CONFIG | EV_EFI_VARIABLE_BOOT | EV_EFI_VARIABLE_AUTHORITY => {} + other => bail!("unexpected RTMR0 event type {other:#x}"), + } + } + ensure!( + (seen_hob, seen_cfv, seen_separator) == (1, 1, 1), + "expected one TD HOB, CFV and separator event, found {seen_hob}, {seen_cfv} and {seen_separator}" + ); + Ok(()) +} + +/// UKI sections systemd-stub measures, in the order it measures them. +const UKI_MEASURED_SECTIONS: [&str; 10] = [ + ".linux", ".osrel", ".cmdline", ".initrd", ".ucode", ".splash", ".dtb", ".uname", ".sbat", + ".pcrpkey", +]; +/// Sections of a UKI that are not measured: the stub's own PE sections and the +/// signature over the measurements. +const UKI_UNMEASURED_SECTIONS: [&str; 7] = [ + ".text", ".rodata", ".data", ".sdmagic", ".reloc", ".pcrsig", ".bss", +]; + +/// Compute the RTMR[1] and RTMR[2] values GCE's TDVF produces when booting +/// `uki` from the disk whose first sectors are `disk_head`. +pub fn image_measurement(uki: &[u8], disk_head: &[u8]) -> Result { + let pe = PeFile64::parse(uki).context("UKI is not a PE32+ image")?; + let mut sections = Vec::new(); + for section in pe.section_table().iter() { + let name = std::str::from_utf8(section.raw_name()) + .context("UKI section name is not UTF-8")? + .trim_end_matches('\0'); + let start = section.pointer_to_raw_data.get(object::LittleEndian) as usize; + let size = section.virtual_size.get(object::LittleEndian) as usize; + let data = uki + .get(start..start + size) + .with_context(|| format!("UKI section {name} exceeds the file"))?; + sections.push((name, data)); + } + if let Some((name, _)) = sections.iter().find(|(name, _)| { + !UKI_MEASURED_SECTIONS.contains(name) && !UKI_UNMEASURED_SECTIONS.contains(name) + }) { + bail!("UKI section {name} is not modeled"); + } + let section = |name: &str| sections.iter().find(|(n, _)| *n == name).map(|(_, d)| *d); + let kernel = section(".linux").context("UKI has no .linux section")?; + + // Boot manager, GPT, the UKI and the kernel it loads, then ExitBootServices. + let rtmr1 = measure_log(&[ + measure_sha384(b"Calling EFI Application from Boot Option"), + measure_sha384(&[0; 4]), + measure_sha384(&gpt_event_data(disk_head)?), + authenticode_sha384_hash(uki)?, + authenticode_sha384_hash(kernel)?, + measure_sha384(b"Exit Boot Services Invocation"), + measure_sha384(b"Exit Boot Services Returned with Success"), + ]); + // systemd-stub: the NUL-terminated name of every section, then its contents. + let rtmr2 = measure_log( + &UKI_MEASURED_SECTIONS + .iter() + .filter_map(|name| Some((name, section(name)?))) + .flat_map(|(name, data)| { + [ + measure_sha384(&[name.as_bytes(), &[0]].concat()), + measure_sha384(data), + ] + }) + .collect::>(), + ); + Ok(GcpTdxImageMeasurement { rtmr1, rtmr2 }) +} + +/// `UEFI_GPT_DATA` as TDVF measures it: the primary GPT header followed by the +/// count and contents of the used partition entries. +fn gpt_event_data(disk: &[u8]) -> Result> { + const SECTOR: usize = 512; + let header = disk + .get(SECTOR..2 * SECTOR) + .context("disk has no GPT header")?; + ensure!(&header[..8] == b"EFI PART", "disk has no GPT header"); + let le32 = |at: usize| u32::from_le_bytes(header[at..at + 4].try_into().unwrap()) as usize; + let header_size = le32(12); + let entries_lba = u64::from_le_bytes(header[72..80].try_into().unwrap()) as usize; + let (count, entry_size) = (le32(80), le32(84)); + ensure!( + header_size <= SECTOR && entry_size >= 16, + "malformed GPT header" + ); + let entries_start = entries_lba * SECTOR; + let entries = disk + .get(entries_start..entries_start + count * entry_size) + .context("GPT partition entries lie beyond the supplied disk head")?; + let used: Vec<&[u8]> = entries + .chunks(entry_size) + .filter(|entry| entry[..16] != [0; 16]) + .collect(); + let mut data = header[..header_size].to_vec(); + data.extend((used.len() as u64).to_le_bytes()); + data.extend(used.concat()); + Ok(data) +} + +#[cfg(test)] +mod tests; diff --git a/dstack/dstack-mr/src/gcp/tests.rs b/dstack/dstack-mr/src/gcp/tests.rs new file mode 100644 index 0000000000..3639c9eca8 --- /dev/null +++ b/dstack/dstack-mr/src/gcp/tests.rs @@ -0,0 +1,230 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +/// A GCP TDX boot captured on GCE: its MRs and RTMR[0] event log. +struct Boot { + mrs: TdxMeasurements, + events: Vec, +} + +fn load(fixture: &str) -> Boot { + let mut mrs = TdxMeasurements { + mrtd: vec![], + rtmr0: vec![], + rtmr1: vec![], + rtmr2: vec![], + }; + let mut events = Vec::new(); + for line in fixture.lines().filter(|l| !l.starts_with('#')) { + let fields: Vec<&str> = line.split_whitespace().collect(); + let bytes = |i: usize| hex::decode(fields[i]).unwrap(); + match fields[0] { + "mrtd" => mrs.mrtd = bytes(1), + "rtmr0" => mrs.rtmr0 = bytes(1), + "rtmr1" => mrs.rtmr1 = bytes(1), + "rtmr2" => mrs.rtmr2 = bytes(1), + "event" => { + let event_type = + u32::from_str_radix(fields[1].trim_start_matches("0x"), 16).unwrap(); + let name = fields.get(3).copied().unwrap_or_default().to_string(); + let payload = if event_type == EV_ACPI_DATA { + b"ACPI DATA".to_vec() + } else { + vec![] + }; + let mut event = TdxEvent::new(0, event_type, name, payload); + event.digest = bytes(2); + events.push(event); + } + other => panic!("unknown fixture line {other}"), + } + } + Boot { mrs, events } +} + +/// The shape of the dstack boot fixture. +const C3_4: MachineConfig = MachineConfig { + cpu_count: 4, + memory_size: 16 << 30, + numa_nodes: 1, + gpu: false, +}; + +/// A c3-standard shape: 4 GiB per vCPU, at most 44 vCPUs per NUMA node. +fn c3_standard(cpu_count: u16, numa_nodes: u16) -> MachineConfig { + MachineConfig { + cpu_count, + memory_size: u64::from(cpu_count) << 32, + numa_nodes, + gpu: false, + } +} + +const A3_HIGHGPU_1G: MachineConfig = MachineConfig { + cpu_count: 26, + memory_size: 234 << 30, + numa_nodes: 1, + gpu: true, +}; + +fn dstack_boot() -> Boot { + load(include_str!( + "../../tests/fixtures/gcp-tdx/dstack-0.6.7-c3-standard-4.txt" + )) +} + +fn image(boot: &Boot) -> GcpTdxImageMeasurement { + GcpTdxImageMeasurement { + rtmr1: boot.mrs.rtmr1.clone(), + rtmr2: boot.mrs.rtmr2.clone(), + } +} + +/// Replace one RTMR[0] event digest and recompute RTMR[0], as a host that +/// controls the event log and the measured inputs could. +fn tamper(boot: &mut Boot, event_type: u32, digest: Vec) { + let event = boot + .events + .iter_mut() + .find(|e| e.event_type == event_type) + .unwrap(); + event.digest = digest; + boot.mrs.rtmr0 = measure_log(&boot.events.iter().map(|e| e.digest()).collect::>()); +} + +#[test] +fn captured_boots_verify() { + for (fixture, machine) in [ + ( + include_str!("../../tests/fixtures/gcp-tdx/dstack-0.6.7-c3-standard-4.txt"), + C3_4, + ), + ( + include_str!("../../tests/fixtures/gcp-tdx/ubuntu-c3-standard-8.txt"), + c3_standard(8, 1), + ), + ( + include_str!("../../tests/fixtures/gcp-tdx/ubuntu-c3-standard-22.txt"), + c3_standard(22, 1), + ), + ( + include_str!("../../tests/fixtures/gcp-tdx/ubuntu-c3-standard-44.txt"), + c3_standard(44, 1), + ), + ( + include_str!("../../tests/fixtures/gcp-tdx/ubuntu-c3-standard-88.txt"), + c3_standard(88, 2), + ), + ( + include_str!("../../tests/fixtures/gcp-tdx/ubuntu-c3-standard-176.txt"), + c3_standard(176, 4), + ), + ( + include_str!("../../tests/fixtures/gcp-tdx/ubuntu-a3-highgpu-1g.txt"), + A3_HIGHGPU_1G, + ), + ] { + let boot = load(fixture); + verify_gcp_tdx_boot(&boot.mrs, &boot.events, &image(&boot), &machine).unwrap(); + } +} + +#[test] +fn rejects_unknown_firmware() { + let mut boot = dstack_boot(); + boot.mrs.mrtd[0] ^= 1; + let err = verify_gcp_tdx_boot(&boot.mrs, &boot.events, &image(&boot), &C3_4).unwrap_err(); + assert!( + format!("{err:#}").contains("not a known GCE TDVF build"), + "{err:#}" + ); +} + +#[test] +fn rejects_an_event_log_that_does_not_replay() { + let mut boot = dstack_boot(); + boot.mrs.rtmr0[0] ^= 1; + let err = verify_gcp_tdx_boot(&boot.mrs, &boot.events, &image(&boot), &C3_4).unwrap_err(); + assert!(format!("{err:#}").contains("replays to"), "{err:#}"); +} + +#[test] +fn rejects_host_supplied_inputs() { + for (event_type, expected) in [ + (EV_EFI_HANDOFF_TABLES2, "TD HOB"), + ( + EV_EFI_PLATFORM_FIRMWARE_BLOB2, + "configuration firmware volume", + ), + (EV_ACPI_DATA, "ACPI tables do not match"), + (EV_SEPARATOR, "separator"), + ] { + let mut boot = dstack_boot(); + tamper(&mut boot, event_type, vec![0; 48]); + let err = verify_gcp_tdx_boot(&boot.mrs, &boot.events, &image(&boot), &C3_4).unwrap_err(); + assert!( + format!("{err:#}").contains(expected), + "{event_type:#x}: {err:#}" + ); + } +} + +#[test] +fn rejects_unexpected_rtmr0_events() { + let mut boot = dstack_boot(); + let mut extra = TdxEvent::new(0, 0x8000_0003, String::new(), vec![]); + extra.digest = vec![0; 48]; + boot.events.push(extra); + boot.mrs.rtmr0 = measure_log(&boot.events.iter().map(|e| e.digest()).collect::>()); + let err = verify_gcp_tdx_boot(&boot.mrs, &boot.events, &image(&boot), &C3_4).unwrap_err(); + assert!( + format!("{err:#}").contains("unexpected RTMR0 event type"), + "{err:#}" + ); +} + +#[test] +fn rejects_a_different_image() { + let boot = dstack_boot(); + for rtmr in [1, 2] { + let mut expected = image(&boot); + let reg = if rtmr == 1 { + &mut expected.rtmr1 + } else { + &mut expected.rtmr2 + }; + reg[0] ^= 1; + let err = verify_gcp_tdx_boot(&boot.mrs, &boot.events, &expected, &C3_4).unwrap_err(); + assert!( + format!("{err:#}").contains(&format!("RTMR{rtmr} mismatch")), + "{err:#}" + ); + } +} + +#[test] +fn gpt_event_counts_only_used_entries() { + let mut disk = vec![0u8; 4 * 512]; + disk[512..520].copy_from_slice(b"EFI PART"); + disk[512 + 12..512 + 16].copy_from_slice(&92u32.to_le_bytes()); + disk[512 + 72..512 + 80].copy_from_slice(&2u64.to_le_bytes()); + disk[512 + 80..512 + 84].copy_from_slice(&4u32.to_le_bytes()); + disk[512 + 84..512 + 88].copy_from_slice(&128u32.to_le_bytes()); + disk[1024] = 1; // first entry has a type GUID, the other three are empty + let data = gpt_event_data(&disk).unwrap(); + assert_eq!(data.len(), 92 + 8 + 128); + assert_eq!(data[92..100], 1u64.to_le_bytes()); +} + +#[test] +fn rejects_a_shape_that_does_not_reproduce_the_tables() { + let boot = dstack_boot(); + let machine = c3_standard(8, 1); + let err = verify_gcp_tdx_boot(&boot.mrs, &boot.events, &image(&boot), &machine).unwrap_err(); + assert!( + format!("{err:#}").contains("ACPI tables do not match"), + "{err:#}" + ); +} diff --git a/dstack/dstack-mr/src/kernel.rs b/dstack/dstack-mr/src/kernel.rs index 5a0a47cca8..3e58067aae 100644 --- a/dstack/dstack-mr/src/kernel.rs +++ b/dstack/dstack-mr/src/kernel.rs @@ -21,7 +21,7 @@ pub fn tdx_kernel_hash_uses_precomputed_high_mem(memory_size: u64) -> bool { } /// Calculates the Authenticode hash of a PE/COFF file -fn authenticode_sha384_hash(data: &[u8]) -> Result> { +pub(crate) fn authenticode_sha384_hash(data: &[u8]) -> Result> { let lfanew_offset = 0x3c; let lfanew: u32 = read_le(data, lfanew_offset, "DOS header")?; diff --git a/dstack/dstack-mr/src/lib.rs b/dstack/dstack-mr/src/lib.rs index 208b4412db..0fccd02e64 100644 --- a/dstack/dstack-mr/src/lib.rs +++ b/dstack/dstack-mr/src/lib.rs @@ -14,6 +14,7 @@ pub type RtmrLog = Vec>; pub type RtmrLogs = [RtmrLog; 3]; mod acpi; +pub mod gcp; mod kernel; mod machine; pub mod measurement; diff --git a/dstack/dstack-mr/src/main.rs b/dstack/dstack-mr/src/main.rs index 0b71c00ddb..60079de592 100644 --- a/dstack/dstack-mr/src/main.rs +++ b/dstack/dstack-mr/src/main.rs @@ -17,7 +17,7 @@ usage: dstack-mr inspect-measurement [tdx|snp|gcp|aws] dstack-mr tdx-measurement-cbor dstack-mr snp-measurement-cbor - dstack-mr gcp-measurement-cbor + dstack-mr gcp-measurement-cbor [ ] dstack-mr aws-measurement-cbor dstack-mr tdx-measurement-hash dstack-mr snp-measurement-hash @@ -25,6 +25,17 @@ usage: features: split-cbor-measurement-v3"; +/// The GPT header and partition entries of a dstack disk image lie well within +/// its first MiB. +const GCP_DISK_HEAD_SIZE: u64 = 1 << 20; + +fn read_head(path: &str, len: u64) -> Result> { + use std::io::Read; + let mut head = Vec::new(); + fs_err::File::open(path)?.take(len).read_to_end(&mut head)?; + Ok(head) +} + fn main() -> Result<()> { let mut args = std::env::args().skip(1); match args.next().as_deref() { @@ -73,9 +84,17 @@ fn main() -> Result<()> { read_hex_file(&hash_file).context("failed to read GCP UKI Authenticode hash")?; let hash = hex::decode(hash.trim()).context("GCP UKI Authenticode hash is not valid hex")?; - let cbor = dstack_types::GcpOsImageMeasurement::new(hash) - .map_err(anyhow::Error::msg)? - .to_cbor_vec(); + let mut measurement = + dstack_types::GcpOsImageMeasurement::new(hash).map_err(anyhow::Error::msg)?; + if let Some(uki_path) = args.next() { + let disk_path = args.next().context(USAGE)?; + let uki = fs_err::read(&uki_path)?; + let disk_head = read_head(&disk_path, GCP_DISK_HEAD_SIZE)?; + let tdx = dstack_mr::gcp::image_measurement(&uki, &disk_head) + .context("failed to compute GCP TDX RTMRs")?; + measurement = measurement.with_tdx(tdx).map_err(anyhow::Error::msg)?; + } + let cbor = measurement.to_cbor_vec(); std::io::stdout() .write_all(&cbor) .context("failed to write GCP measurement CBOR")?; diff --git a/dstack/dstack-mr/src/tdx.rs b/dstack/dstack-mr/src/tdx.rs index 484121307a..ceda5bbe02 100644 --- a/dstack/dstack-mr/src/tdx.rs +++ b/dstack/dstack-mr/src/tdx.rs @@ -492,7 +492,9 @@ pub fn tdx_measurements_from_measurement_document( }) } -fn rtmr0_acpi_hashes_from_event_log(event_log: &[TdxEvent]) -> Result { +pub(crate) fn rtmr0_acpi_hashes_from_event_log( + event_log: &[TdxEvent], +) -> Result { let rtmr0_events = event_log .iter() .filter(|event| event.imr == 0) diff --git a/dstack/dstack-mr/tests/fixtures/gcp-tdx/dstack-0.6.7-c3-standard-4.txt b/dstack/dstack-mr/tests/fixtures/gcp-tdx/dstack-0.6.7-c3-standard-4.txt new file mode 100644 index 0000000000..3c52f7ddea --- /dev/null +++ b/dstack/dstack-mr/tests/fixtures/gcp-tdx/dstack-0.6.7-c3-standard-4.txt @@ -0,0 +1,21 @@ +# dstack 0.6.7 UKI image on c3-standard-4, us-central1-a, 2026-12-02; MRs from the verified quote +mrtd f21e6b48743fe14c2d090078ca1197f09ae4c99438677f2c79901ef80e2aeefe2f9a7eb6e3eb3b5047c4f1511731e5d3 +rtmr0 4b08605d192148837400c4eee71f46b65ff960eaaf63494c472c4ddc4482d7c23d8671913ebec4b85c6edb89aa232662 +rtmr1 b10cde31f3a8b3c5991a6d2acd76d8af5acf8996c983b07cd2b8a8aa273f2ec02b5cc8a0e0d275da272fd03b63ba5e69 +rtmr2 fdae7a11f5aedae62bc4bf3085a4d7ec752824c0a071d789e70613a0a2a68548a89b6cb14a65acfb060c0cf6ab0628e5 +event 0x8000000b d587edd195019c7d650a7f6d2df37275e2fb2250d21770f02c4df72457b74dcd659d9974f645d708446ca9af192593b4 +event 0x8000000a 98f78a03fdbd6f31e54b65dd0518b9a043b05c700339efb71ffae8335d6d1e60395dc5b0c719d5c1ccb41af64fd88849 +event 0x80000001 cfa4e2c606f572627bf06d5669cc2ab1128358d27b45bc63ee9ea56ec109cfafb7194006f847a6a74b5eaed6b73332ec +event 0x80000001 a763553c9606770cd3a5e607f8e0c1ef01cdf2555af753fa3a1f6afe43eb7b2a0af4a6f80fd8e4dd10459668f3b011e0 +event 0x80000001 fd111537e6c0f7ca64fd189ee784cde86214e8495dbc36cd0ccbb5006377d250ab352fe05378bac5a81fa3132c58851e +event 0x80000001 0968b4cf1dde5df9983f718588e67eca142ba481ba1e517e97c701e740641027ad891a7e9da539cae4e17df0a9d22322 +event 0x80000001 4285252d954a0241a9788ee5c54ea6e0f1e0df7ff39c7c1ea81888cfd2d37a4b7888f38a2c0e0b6336df972ed6cbadd9 +event 0x4 394341b7182cd227c5c6b07ef8000cdfd86136c4292b8e576573ad7ed9ae41019f5818b4b971c9effc60e1ad9f1289f0 +event 0xa ee0cc4f8fa34d548c7bad109ad5da7a7469c6a84967b919120b63bdfd9a50def29f37e0b7f0d40110304c70f1615998f acpi-loader +event 0xa 957129f88ef987bf483b2fd0b8b7fab43b5477e394a683f74fbf662217e8fa2279c2fed9b877ccea0c9b9be916b55cca acpi-rsdp +event 0xa 70cb7693cd1bee8a9870f8ab7b049e06960196c7f3c1a486b771d8205446ede22d45b7bcc3bbc0e9ec44b5eb7df3b84d acpi-tables +event 0x80000002 d91b4ab46b54bed85a625ee1e38155898aba5dafb049518bde1ff3f86382b8650484aba151b9fc256c2ffba43223c6fd +event 0x80000002 a25333c7aec2e0993034938c7f11893b3c2bcaf67e88c342a3d586f6f7fae2c6a1247a9ed86988080a6d4be497d4fbb6 +event 0x80000002 9068065754ff3ae3dd58a5897535eeaf62a19a6757d82dd91349c41bae2e3f208e268abba2a4378bc5c8d1acf2fd260f +event 0x80000002 bf0c79530728b35b23e144594aec2af3e73aa5aeb76abb4e825de701e6f39cdf3b6724c07c1685dc9c3406c262033ac2 +event 0x80000002 23ada07f5261f12f34a0bd8e46760962d6b4d576a416f1fea1c64bc656b1d28eacf7047ae6e967c58fd2a98bfa74c298 diff --git a/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-a3-highgpu-1g.txt b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-a3-highgpu-1g.txt new file mode 100644 index 0000000000..bc1328bcf7 --- /dev/null +++ b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-a3-highgpu-1g.txt @@ -0,0 +1,23 @@ +# Ubuntu 24.04 on a3-highgpu-1g, spot, one NVIDIA H100, us-central1-a, 2026-12-02; MRs from the quote +mrtd 8feb9ece523f9e458b156ffd84268bd88e6bfae2054c107d35a70f235e2fab67273bb4cb4d9e986e38a71ae4a402c4b6 +rtmr0 1113f39fc44fe6b89b33e71617a5a3decb4836eae9c9bd58d4bd4cc0e47fad034d88715925232d046e726fe630357199 +rtmr1 d192154c2dec6fab2500361b5b191b3e6f0c49362a350aac3a24bcb37f8453e0f3ab34cb4f2bbb43bdc6cf2b32792ef0 +rtmr2 cf0bed675292495c82ac836afb69bb569a6cf1c20c08dd28b93ab789b754c927dcc7afe2638f8ae34a3378a4030fccca +event 0x8000000b 7a69d1e3ebd557ebdee0160f3fe1e73306bb5925b33bcf4c6002a6364c5bc0238e95d4d00471a5379d4f83ff64bd7a1d +event 0x8000000a 1b0f9128a714869da1b6e8082d41f37f37f0f1f98b56eeb9074df94707a5994f0e9e8fe80725580274724ae6c179a1fb +event 0x80000001 cfa4e2c606f572627bf06d5669cc2ab1128358d27b45bc63ee9ea56ec109cfafb7194006f847a6a74b5eaed6b73332ec +event 0x80000001 a763553c9606770cd3a5e607f8e0c1ef01cdf2555af753fa3a1f6afe43eb7b2a0af4a6f80fd8e4dd10459668f3b011e0 +event 0x80000001 fd111537e6c0f7ca64fd189ee784cde86214e8495dbc36cd0ccbb5006377d250ab352fe05378bac5a81fa3132c58851e +event 0x80000001 0968b4cf1dde5df9983f718588e67eca142ba481ba1e517e97c701e740641027ad891a7e9da539cae4e17df0a9d22322 +event 0x80000001 0a4f1f256f608a36dc75e25cc15533463d0cfcdfd6160f06f9f4cec7d0c4b53540b298077c028370bbf2fa93d25017a0 +event 0x4 394341b7182cd227c5c6b07ef8000cdfd86136c4292b8e576573ad7ed9ae41019f5818b4b971c9effc60e1ad9f1289f0 +event 0xa bc851aa5b6e82ceca70f74c7405eca6f4bbccffa58637f52b06a22919574d6e336ab6c193798b926c1d942659176eaa4 acpi-loader +event 0xa 088f7b46561423db400530582ed615f6c56f3686c8429f4cfef852925973edebe8b1fb9108bb6e808b4d9691388c381a acpi-rsdp +event 0xa 5b82d54c5794f5021247db1aabcf8aacd4de446348d6593b7f854a385843600a9216bcf9c23106af847aa839ea46ddfd acpi-tables +event 0x80000002 36dcbc80d613b2b98d78b720e75f951ecf3677a0c49c4b1f7374297c73bbdec7ad1840340f95122bd3a8216f9688e972 +event 0x80000002 04c29e91449a11c13f7f2ff319ee053b96de7cc8a63a790b57016872865682251aaf2bdb13ee07103e117f2e23c47324 +event 0x80000002 1e372f23d14759024b447da51fe41ab63a17f37f2e43f8118e9c573e6707b9518727d17d3be61e0063d6bf437beef21a +event 0x80000002 e5088cd88176b12c581744ff7e557e9ea416dd230474513170dbc7d3d7b0b742de2709532f02e25ae83dabb65fe3b794 +event 0x80000002 ba3846b1bed3a223ed37c819e4cb1fd72d422c46687531b6b57119e9eb3d6350936e271c6f9a9f40f907dca93b9cd60b +event 0x80000002 23ada07f5261f12f34a0bd8e46760962d6b4d576a416f1fea1c64bc656b1d28eacf7047ae6e967c58fd2a98bfa74c298 +event 0x800000e0 f143e2948d63fcd3442e841bb36a7e180871f0a8946541961fe9d12e70d0727874600956264dba531e2edd8729c5eb38 diff --git a/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-176.txt b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-176.txt new file mode 100644 index 0000000000..337b6e130f --- /dev/null +++ b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-176.txt @@ -0,0 +1,21 @@ +# Ubuntu 24.04 on c3-standard-176, us-central1-a, 2026-12-02; MRs from the quote +mrtd f21e6b48743fe14c2d090078ca1197f09ae4c99438677f2c79901ef80e2aeefe2f9a7eb6e3eb3b5047c4f1511731e5d3 +rtmr0 621cc1a5bded94b73a99b481126ff3d615eff302610bd1e90dffc21a0adea14d1a5405f8ee403959f2e5635be86a6e7e +rtmr1 d192154c2dec6fab2500361b5b191b3e6f0c49362a350aac3a24bcb37f8453e0f3ab34cb4f2bbb43bdc6cf2b32792ef0 +rtmr2 cf0bed675292495c82ac836afb69bb569a6cf1c20c08dd28b93ab789b754c927dcc7afe2638f8ae34a3378a4030fccca +event 0x8000000b 4a799801c4c54aefa7d32f01da8e7c42e4f8cba961db7e28b07d75a2ae79b686203d232cc5705554dd43782136d9c9af +event 0x8000000a 98f78a03fdbd6f31e54b65dd0518b9a043b05c700339efb71ffae8335d6d1e60395dc5b0c719d5c1ccb41af64fd88849 +event 0x80000001 cfa4e2c606f572627bf06d5669cc2ab1128358d27b45bc63ee9ea56ec109cfafb7194006f847a6a74b5eaed6b73332ec +event 0x80000001 a763553c9606770cd3a5e607f8e0c1ef01cdf2555af753fa3a1f6afe43eb7b2a0af4a6f80fd8e4dd10459668f3b011e0 +event 0x80000001 fd111537e6c0f7ca64fd189ee784cde86214e8495dbc36cd0ccbb5006377d250ab352fe05378bac5a81fa3132c58851e +event 0x80000001 0968b4cf1dde5df9983f718588e67eca142ba481ba1e517e97c701e740641027ad891a7e9da539cae4e17df0a9d22322 +event 0x80000001 0a4f1f256f608a36dc75e25cc15533463d0cfcdfd6160f06f9f4cec7d0c4b53540b298077c028370bbf2fa93d25017a0 +event 0x4 394341b7182cd227c5c6b07ef8000cdfd86136c4292b8e576573ad7ed9ae41019f5818b4b971c9effc60e1ad9f1289f0 +event 0xa f8b3e3e2b43e3a1dec676f8e7796bb8b41d1859cc7a09da527730205838b5d40f10ed41bf71fa4120e1240fd5a341a67 acpi-loader +event 0xa 92a6a07e0a02159e8500507ab9776e67b3c06ee38413ae18d1b30ac63c60fd4a8ab73acc8dedeb0ade6bf07a132fc05b acpi-rsdp +event 0xa 25ef23269edbcd233a7495f0e712cd0e6d4c678c046fee87bab7faff6dc5e711141cc01ba590a16e9320df68f9a7765f acpi-tables +event 0x80000002 7d89f01e0a18c425ef834051c46df703ada56d44d6f990dcf66ba5ae61b7e5574ff5a67efff0774791f4332b2a7c2961 +event 0x80000002 5eb6176e8592ab9f452fb353e1721fbb6b6df847580ec417033287ccf608d6cdb16676e76332dfa841d10aab573a0aa8 +event 0x80000002 a25333c7aec2e0993034938c7f11893b3c2bcaf67e88c342a3d586f6f7fae2c6a1247a9ed86988080a6d4be497d4fbb6 +event 0x80000002 23ada07f5261f12f34a0bd8e46760962d6b4d576a416f1fea1c64bc656b1d28eacf7047ae6e967c58fd2a98bfa74c298 +event 0x800000e0 f143e2948d63fcd3442e841bb36a7e180871f0a8946541961fe9d12e70d0727874600956264dba531e2edd8729c5eb38 diff --git a/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-22.txt b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-22.txt new file mode 100644 index 0000000000..94c8bac888 --- /dev/null +++ b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-22.txt @@ -0,0 +1,21 @@ +# Ubuntu 24.04 on c3-standard-22, europe-west4-a, 2026-12-02; MRs replayed from the CCEL +mrtd f21e6b48743fe14c2d090078ca1197f09ae4c99438677f2c79901ef80e2aeefe2f9a7eb6e3eb3b5047c4f1511731e5d3 +rtmr0 3cf290a460fdb8bfecdbf94bbe9ea8eef5c7a2519698e3959be9ab4f5908dfc2372295720d6a8ac2229a4efd148e5fcc +rtmr1 d192154c2dec6fab2500361b5b191b3e6f0c49362a350aac3a24bcb37f8453e0f3ab34cb4f2bbb43bdc6cf2b32792ef0 +rtmr2 cf0bed675292495c82ac836afb69bb569a6cf1c20c08dd28b93ab789b754c927dcc7afe2638f8ae34a3378a4030fccca +event 0x8000000b 320f025daa211bbd7a47e9eb2f04a87ae5148da6b88d27585bd28c3b9f8cde45b24db32227a395c31a183bcbf8cfb3cb +event 0x8000000a 98f78a03fdbd6f31e54b65dd0518b9a043b05c700339efb71ffae8335d6d1e60395dc5b0c719d5c1ccb41af64fd88849 +event 0x80000001 cfa4e2c606f572627bf06d5669cc2ab1128358d27b45bc63ee9ea56ec109cfafb7194006f847a6a74b5eaed6b73332ec +event 0x80000001 a763553c9606770cd3a5e607f8e0c1ef01cdf2555af753fa3a1f6afe43eb7b2a0af4a6f80fd8e4dd10459668f3b011e0 +event 0x80000001 fd111537e6c0f7ca64fd189ee784cde86214e8495dbc36cd0ccbb5006377d250ab352fe05378bac5a81fa3132c58851e +event 0x80000001 0968b4cf1dde5df9983f718588e67eca142ba481ba1e517e97c701e740641027ad891a7e9da539cae4e17df0a9d22322 +event 0x80000001 0a4f1f256f608a36dc75e25cc15533463d0cfcdfd6160f06f9f4cec7d0c4b53540b298077c028370bbf2fa93d25017a0 +event 0x4 394341b7182cd227c5c6b07ef8000cdfd86136c4292b8e576573ad7ed9ae41019f5818b4b971c9effc60e1ad9f1289f0 +event 0xa e9546f446612a4e1597caa283f52b5204c7739a1157f3b51bda90b4b9af3f56d443ab5ff9929079cfb523a91e3ee305e acpi-loader +event 0xa 23307a6e9314329d1a87c5eed0e4456e9c3d3912efe1ef0af6b8db62aeeff1cfda182a5245bedc3e74098eb103a6ef9f acpi-rsdp +event 0xa fb3f7aef27e8bf958cdadf394dd6fa5f4b35a3760325052483d7bcf81eeb7be2796d017b9300c0de8104c71530181b3c acpi-tables +event 0x80000002 7d89f01e0a18c425ef834051c46df703ada56d44d6f990dcf66ba5ae61b7e5574ff5a67efff0774791f4332b2a7c2961 +event 0x80000002 5eb6176e8592ab9f452fb353e1721fbb6b6df847580ec417033287ccf608d6cdb16676e76332dfa841d10aab573a0aa8 +event 0x80000002 a25333c7aec2e0993034938c7f11893b3c2bcaf67e88c342a3d586f6f7fae2c6a1247a9ed86988080a6d4be497d4fbb6 +event 0x80000002 23ada07f5261f12f34a0bd8e46760962d6b4d576a416f1fea1c64bc656b1d28eacf7047ae6e967c58fd2a98bfa74c298 +event 0x800000e0 f143e2948d63fcd3442e841bb36a7e180871f0a8946541961fe9d12e70d0727874600956264dba531e2edd8729c5eb38 diff --git a/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-44.txt b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-44.txt new file mode 100644 index 0000000000..56ce647bcf --- /dev/null +++ b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-44.txt @@ -0,0 +1,21 @@ +# Ubuntu 24.04 on c3-standard-44, us-central1-a, 2026-12-02; MRs from the quote +mrtd f21e6b48743fe14c2d090078ca1197f09ae4c99438677f2c79901ef80e2aeefe2f9a7eb6e3eb3b5047c4f1511731e5d3 +rtmr0 2a55fdfcd43997d1687bea08fa21613e6b6f7ea15d9c798ec5577251aa1a507a6ce8b77588f3ecf3d30404505811423c +rtmr1 d192154c2dec6fab2500361b5b191b3e6f0c49362a350aac3a24bcb37f8453e0f3ab34cb4f2bbb43bdc6cf2b32792ef0 +rtmr2 cf0bed675292495c82ac836afb69bb569a6cf1c20c08dd28b93ab789b754c927dcc7afe2638f8ae34a3378a4030fccca +event 0x8000000b cd7fe1dfcc7b55df4842a8cb22e88f480059f7469826e3e92077c9e6c07d41d29ad486aef053f1a8ebf3eca18c95f5b5 +event 0x8000000a 98f78a03fdbd6f31e54b65dd0518b9a043b05c700339efb71ffae8335d6d1e60395dc5b0c719d5c1ccb41af64fd88849 +event 0x80000001 cfa4e2c606f572627bf06d5669cc2ab1128358d27b45bc63ee9ea56ec109cfafb7194006f847a6a74b5eaed6b73332ec +event 0x80000001 a763553c9606770cd3a5e607f8e0c1ef01cdf2555af753fa3a1f6afe43eb7b2a0af4a6f80fd8e4dd10459668f3b011e0 +event 0x80000001 fd111537e6c0f7ca64fd189ee784cde86214e8495dbc36cd0ccbb5006377d250ab352fe05378bac5a81fa3132c58851e +event 0x80000001 0968b4cf1dde5df9983f718588e67eca142ba481ba1e517e97c701e740641027ad891a7e9da539cae4e17df0a9d22322 +event 0x80000001 0a4f1f256f608a36dc75e25cc15533463d0cfcdfd6160f06f9f4cec7d0c4b53540b298077c028370bbf2fa93d25017a0 +event 0x4 394341b7182cd227c5c6b07ef8000cdfd86136c4292b8e576573ad7ed9ae41019f5818b4b971c9effc60e1ad9f1289f0 +event 0xa 700fcf25c0a5719655e82a0122ea13dc440be8dbc326a6ceabc2c50af3ff26f666ec923e1595c0efa1c529fcb42304a7 acpi-loader +event 0xa 82cdb41605a0514294b961a606f45649b514a66bbb15558e405e274f3ea4e2bae089d601b50bc29785e37d026a770d6d acpi-rsdp +event 0xa 4170f5e3d6d4b5e9ec2d171a52f08f47136839807e5466ef5527b86a91530b49515dedc9e5d5bf132b1c9477c653f634 acpi-tables +event 0x80000002 7d89f01e0a18c425ef834051c46df703ada56d44d6f990dcf66ba5ae61b7e5574ff5a67efff0774791f4332b2a7c2961 +event 0x80000002 5eb6176e8592ab9f452fb353e1721fbb6b6df847580ec417033287ccf608d6cdb16676e76332dfa841d10aab573a0aa8 +event 0x80000002 a25333c7aec2e0993034938c7f11893b3c2bcaf67e88c342a3d586f6f7fae2c6a1247a9ed86988080a6d4be497d4fbb6 +event 0x80000002 23ada07f5261f12f34a0bd8e46760962d6b4d576a416f1fea1c64bc656b1d28eacf7047ae6e967c58fd2a98bfa74c298 +event 0x800000e0 f143e2948d63fcd3442e841bb36a7e180871f0a8946541961fe9d12e70d0727874600956264dba531e2edd8729c5eb38 diff --git a/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-8.txt b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-8.txt new file mode 100644 index 0000000000..d922e2b44a --- /dev/null +++ b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-8.txt @@ -0,0 +1,23 @@ +# Ubuntu 24.04 on c3-standard-8-lssd, us-central1-a, 2026-12-02; MRs replayed from the CCEL +mrtd f21e6b48743fe14c2d090078ca1197f09ae4c99438677f2c79901ef80e2aeefe2f9a7eb6e3eb3b5047c4f1511731e5d3 +rtmr0 b26596091554ffa7a6e222800542e212c860ef8426d1d02d09dc39afe3ecbc62f3659e7aa7a48209e59692c17b8ba9ce +rtmr1 d192154c2dec6fab2500361b5b191b3e6f0c49362a350aac3a24bcb37f8453e0f3ab34cb4f2bbb43bdc6cf2b32792ef0 +rtmr2 cf0bed675292495c82ac836afb69bb569a6cf1c20c08dd28b93ab789b754c927dcc7afe2638f8ae34a3378a4030fccca +event 0x8000000b 39e89cd8ec6f35e35e86a9b2f9b6b4bdf0e71abc8bcb67f9ba48f37f511d865e909dca970cf364f926b2738435d41341 +event 0x8000000a 98f78a03fdbd6f31e54b65dd0518b9a043b05c700339efb71ffae8335d6d1e60395dc5b0c719d5c1ccb41af64fd88849 +event 0x80000001 cfa4e2c606f572627bf06d5669cc2ab1128358d27b45bc63ee9ea56ec109cfafb7194006f847a6a74b5eaed6b73332ec +event 0x80000001 a763553c9606770cd3a5e607f8e0c1ef01cdf2555af753fa3a1f6afe43eb7b2a0af4a6f80fd8e4dd10459668f3b011e0 +event 0x80000001 fd111537e6c0f7ca64fd189ee784cde86214e8495dbc36cd0ccbb5006377d250ab352fe05378bac5a81fa3132c58851e +event 0x80000001 0968b4cf1dde5df9983f718588e67eca142ba481ba1e517e97c701e740641027ad891a7e9da539cae4e17df0a9d22322 +event 0x80000001 0a4f1f256f608a36dc75e25cc15533463d0cfcdfd6160f06f9f4cec7d0c4b53540b298077c028370bbf2fa93d25017a0 +event 0x4 394341b7182cd227c5c6b07ef8000cdfd86136c4292b8e576573ad7ed9ae41019f5818b4b971c9effc60e1ad9f1289f0 +event 0xa e828c43ec73e8bf887cd888d218257b453918c2dea7fba9c76344346d55c94f70a927ed0b342ba39bb88bdfae7226117 acpi-loader +event 0xa 4b7f3aadcf86c3b58eb55c5a30026cdfc89db04af2b33e3e3e063c117d08b7af34cac43038da500718d89d09d81ee418 acpi-rsdp +event 0xa b3eaba03d9fc5a068e3bd3a88a4840642d65a10df4017eb6dff01e3ee469e7acd587839cc94b29a180bca1a13e6b9cfd acpi-tables +event 0x80000002 36dcbc80d613b2b98d78b720e75f951ecf3677a0c49c4b1f7374297c73bbdec7ad1840340f95122bd3a8216f9688e972 +event 0x80000002 04c29e91449a11c13f7f2ff319ee053b96de7cc8a63a790b57016872865682251aaf2bdb13ee07103e117f2e23c47324 +event 0x80000002 1e372f23d14759024b447da51fe41ab63a17f37f2e43f8118e9c573e6707b9518727d17d3be61e0063d6bf437beef21a +event 0x80000002 e5088cd88176b12c581744ff7e557e9ea416dd230474513170dbc7d3d7b0b742de2709532f02e25ae83dabb65fe3b794 +event 0x80000002 ba3846b1bed3a223ed37c819e4cb1fd72d422c46687531b6b57119e9eb3d6350936e271c6f9a9f40f907dca93b9cd60b +event 0x80000002 23ada07f5261f12f34a0bd8e46760962d6b4d576a416f1fea1c64bc656b1d28eacf7047ae6e967c58fd2a98bfa74c298 +event 0x800000e0 f143e2948d63fcd3442e841bb36a7e180871f0a8946541961fe9d12e70d0727874600956264dba531e2edd8729c5eb38 diff --git a/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-88.txt b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-88.txt new file mode 100644 index 0000000000..50aeeedef4 --- /dev/null +++ b/dstack/dstack-mr/tests/fixtures/gcp-tdx/ubuntu-c3-standard-88.txt @@ -0,0 +1,21 @@ +# Ubuntu 24.04 on c3-standard-88, us-central1-a, 2026-12-02; MRs from the quote +mrtd f21e6b48743fe14c2d090078ca1197f09ae4c99438677f2c79901ef80e2aeefe2f9a7eb6e3eb3b5047c4f1511731e5d3 +rtmr0 a7717654c9a89b794aa0da0a4b3a22e8fd83be3e4cb026dae2725624dc718b9e1d04e9b6b5233607fed5f4497163bd32 +rtmr1 d192154c2dec6fab2500361b5b191b3e6f0c49362a350aac3a24bcb37f8453e0f3ab34cb4f2bbb43bdc6cf2b32792ef0 +rtmr2 cf0bed675292495c82ac836afb69bb569a6cf1c20c08dd28b93ab789b754c927dcc7afe2638f8ae34a3378a4030fccca +event 0x8000000b 3a9b3f6fea180447b5361f28c312a6e88ef710ff1a404093d87d04096ecc6f862b2018992816056ab0dc41d9bb230ddf +event 0x8000000a 98f78a03fdbd6f31e54b65dd0518b9a043b05c700339efb71ffae8335d6d1e60395dc5b0c719d5c1ccb41af64fd88849 +event 0x80000001 cfa4e2c606f572627bf06d5669cc2ab1128358d27b45bc63ee9ea56ec109cfafb7194006f847a6a74b5eaed6b73332ec +event 0x80000001 a763553c9606770cd3a5e607f8e0c1ef01cdf2555af753fa3a1f6afe43eb7b2a0af4a6f80fd8e4dd10459668f3b011e0 +event 0x80000001 fd111537e6c0f7ca64fd189ee784cde86214e8495dbc36cd0ccbb5006377d250ab352fe05378bac5a81fa3132c58851e +event 0x80000001 0968b4cf1dde5df9983f718588e67eca142ba481ba1e517e97c701e740641027ad891a7e9da539cae4e17df0a9d22322 +event 0x80000001 0a4f1f256f608a36dc75e25cc15533463d0cfcdfd6160f06f9f4cec7d0c4b53540b298077c028370bbf2fa93d25017a0 +event 0x4 394341b7182cd227c5c6b07ef8000cdfd86136c4292b8e576573ad7ed9ae41019f5818b4b971c9effc60e1ad9f1289f0 +event 0xa 6f0e6afb42ef596e115cd26cec263aacdbe1053c81a7b50aa6f0c6e1fa84e13b5bd92abb79c94a88db12ceb90b5e6a2a acpi-loader +event 0xa abe9471a1fdb8c47e3aa113b9d6dc796a6622bf7a845081f55b4d3c3e8840aa870d1d1ebaf8926d6f2497930142f796a acpi-rsdp +event 0xa 42d328afbe9a44b87bb3093c6effcc3b3b30ef326fcf1ded027d04a3895517fe82ec9314d6fb831726c2b119e9258d7e acpi-tables +event 0x80000002 7d89f01e0a18c425ef834051c46df703ada56d44d6f990dcf66ba5ae61b7e5574ff5a67efff0774791f4332b2a7c2961 +event 0x80000002 5eb6176e8592ab9f452fb353e1721fbb6b6df847580ec417033287ccf608d6cdb16676e76332dfa841d10aab573a0aa8 +event 0x80000002 a25333c7aec2e0993034938c7f11893b3c2bcaf67e88c342a3d586f6f7fae2c6a1247a9ed86988080a6d4be497d4fbb6 +event 0x80000002 23ada07f5261f12f34a0bd8e46760962d6b4d576a416f1fea1c64bc656b1d28eacf7047ae6e967c58fd2a98bfa74c298 +event 0x800000e0 f143e2948d63fcd3442e841bb36a7e180871f0a8946541961fe9d12e70d0727874600956264dba531e2edd8729c5eb38 diff --git a/dstack/dstack-types/src/lib.rs b/dstack/dstack-types/src/lib.rs index 4f9cb36e56..44f71466cd 100644 --- a/dstack/dstack-types/src/lib.rs +++ b/dstack/dstack-types/src/lib.rs @@ -1747,10 +1747,26 @@ pub fn verify_measurement_material( /// the UKI as a PE/COFF Authenticode SHA-256 digest. The unified image identity /// remains `sha256(sha256sum.txt)`; this material is bound to that identity by /// the `measurement.gcp.cbor` entry in `sha256sum.txt`. +/// +/// Version 2 adds the RTMR[1] and RTMR[2] values the image produces when GCE's +/// TDVF boots it. Their presence makes the verifier check the TDX boot chain +/// (MRTD and RTMR[0..2]) in addition to the vTPM, so a v2 image cannot be +/// verified with the vTPM checks alone. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct GcpOsImageMeasurement { #[serde(with = "hex_bytes")] pub uki_authenticode_sha256: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tdx: Option, +} + +/// Expected TDX RTMRs of a GCP image: both depend only on the boot disk. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct GcpTdxImageMeasurement { + #[serde(with = "hex_bytes")] + pub rtmr1: Vec, + #[serde(with = "hex_bytes")] + pub rtmr2: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -1758,28 +1774,29 @@ struct CborGcpOsImageMeasurement { version: u32, #[serde(rename = "uki_auth", with = "hex_bytes")] uki_authenticode_sha256: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + tdx: Option, } impl From<&GcpOsImageMeasurement> for CborGcpOsImageMeasurement { fn from(measurement: &GcpOsImageMeasurement) -> Self { Self { - version: GcpOsImageMeasurement::VERSION, + version: if measurement.tdx.is_some() { + GcpOsImageMeasurement::VERSION_TDX + } else { + GcpOsImageMeasurement::VERSION + }, uki_authenticode_sha256: measurement.uki_authenticode_sha256.clone(), - } - } -} - -impl From for GcpOsImageMeasurement { - fn from(measurement: CborGcpOsImageMeasurement) -> Self { - Self { - uki_authenticode_sha256: measurement.uki_authenticode_sha256, + tdx: measurement.tdx.clone(), } } } impl GcpOsImageMeasurement { pub const VERSION: u32 = 1; + pub const VERSION_TDX: u32 = 2; pub const UKI_AUTHENTICODE_SHA256_LEN: usize = 32; + pub const RTMR_LEN: usize = 48; pub fn new(uki_authenticode_sha256: Vec) -> Result { if uki_authenticode_sha256.len() != Self::UKI_AUTHENTICODE_SHA256_LEN { @@ -1791,9 +1808,21 @@ impl GcpOsImageMeasurement { } Ok(Self { uki_authenticode_sha256, + tdx: None, }) } + pub fn with_tdx(mut self, tdx: GcpTdxImageMeasurement) -> Result { + if tdx.rtmr1.len() != Self::RTMR_LEN || tdx.rtmr2.len() != Self::RTMR_LEN { + return Err(format!( + "GcpOsImageMeasurement: RTMRs must be {} bytes", + Self::RTMR_LEN + )); + } + self.tdx = Some(tdx); + Ok(self) + } + pub fn to_cbor_vec(&self) -> Vec { cbor_to_vec( &CborGcpOsImageMeasurement::from(self), @@ -1804,14 +1833,20 @@ impl GcpOsImageMeasurement { pub fn from_cbor_slice(bytes: &[u8]) -> Result { let measurement: CborGcpOsImageMeasurement = cbor_from_slice(bytes, "GcpOsImageMeasurement")?; - if measurement.version != Self::VERSION { - return Err(format!( - "GcpOsImageMeasurement unsupported version {}, expected {}", - measurement.version, - Self::VERSION - )); + let decoded = Self::new(measurement.uki_authenticode_sha256)?; + match (measurement.version, measurement.tdx) { + (Self::VERSION, None) => Ok(decoded), + (Self::VERSION_TDX, Some(tdx)) => decoded.with_tdx(tdx), + (Self::VERSION | Self::VERSION_TDX, _) => Err(format!( + "GcpOsImageMeasurement version {} does not match its TDX fields", + measurement.version + )), + (version, _) => Err(format!( + "GcpOsImageMeasurement unsupported version {version}, expected {} or {}", + Self::VERSION, + Self::VERSION_TDX + )), } - Self::new(measurement.uki_authenticode_sha256) } pub fn cbor_json_value_from_slice(bytes: &[u8]) -> Result { diff --git a/dstack/scripts/bin/dstack-cloud b/dstack/scripts/bin/dstack-cloud index 2060f83aed..fabd273826 100755 --- a/dstack/scripts/bin/dstack-cloud +++ b/dstack/scripts/bin/dstack-cloud @@ -221,6 +221,9 @@ class App: } +GCE_CPUS_PER_NUMA_NODE = 44 + + @dataclass class GcpConfig: """GCP deployment configuration.""" @@ -660,6 +663,9 @@ class CloudDeploymentManager: }, } + if platform == "gcp": + vm_config.update(self._gcp_machine_shape(platform_config)) + sys_config = { "kms_urls": kms_urls, "gateway_urls": gateway_urls, @@ -704,6 +710,31 @@ class CloudDeploymentManager: return result + def _gcp_machine_shape(self, config: GcpConfig) -> Dict[str, int]: + """vCPUs, memory and GPUs of the machine type. + + The verifier regenerates the ACPI tables GCE measures into RTMR0 from them. + """ + result = self._run_gcloud([ + "compute", "machine-types", "describe", config.machine_type, + f"--zone={config.zone}", + f"--project={config.project}", + "--format=json", + ]) + machine = json.loads(result.stdout) + cpus = machine["guestCpus"] + shape = { + "cpu_count": cpus, + "memory_size": machine["memoryMb"] << 20, + "num_gpus": sum(a["guestAcceleratorCount"] for a in machine.get("accelerators", [])), + } + # GCE places at most 44 vCPUs on a NUMA node; gcloud does not report + # the node count. An absent list means one node. + nodes = -(-cpus // GCE_CPUS_PER_NUMA_NODE) + if nodes > 1: + shape["numa_nodes"] = [{} for _ in range(nodes)] + return shape + def _run_gsutil(self, args: List[str], check: bool = True) -> subprocess.CompletedProcess: """Run a gsutil command.""" cmd = ["gsutil"] + args diff --git a/dstack/verifier/src/verification.rs b/dstack/verifier/src/verification.rs index 6e2a745f45..c0b52626de 100644 --- a/dstack/verifier/src/verification.rs +++ b/dstack/verifier/src/verification.rs @@ -10,7 +10,7 @@ use std::{ time::Duration, }; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{anyhow, bail, ensure, Context, Result}; use dstack_mr::{tdx::assert_tdx_mrs_eq, TdxMeasurements}; use dstack_types::{sha256sum, TdxAttestationVariant, VmConfig}; use hex_literal::hex; @@ -732,7 +732,18 @@ impl CvmVerifier { else { bail!("GCP TDX quote without a GCP TDX report"); }; - self.verify_os_image_hash_for_gcp_tdx(&vm_config, tpm_report)?; + let measurement = self.verify_os_image_hash_for_gcp_tdx(&vm_config, tpm_report)?; + if let Some(tdx) = &measurement.tdx { + let tdx_quote = attestation.tdx_quote().context("No TDX quote")?; + dstack_mr::gcp::verify_gcp_tdx_boot( + &verified_tdx_mrs(attestation)?, + &tdx_quote.event_log, + tdx, + &gcp_machine(&vm_config)?, + ) + .context("GCP TDX boot chain does not verify")?; + details.acpi_tables_verified = true; + } } // The declared scheme alone selects the path, matched exhaustively // so a new variant fails the build here instead of taking one. @@ -932,7 +943,7 @@ impl CvmVerifier { &self, vm_config: &VmConfig, tpm_report: &TpmVerifiedReport, - ) -> Result<()> { + ) -> Result { // Verify PCR 0 (GCP OVMF firmware) const EXPECTED_PCR0: [u8; 32] = hex!("0cca9ec161b09288802e5a112255d21340ed5b797f5fe29cecccfd8f67b9f802"); @@ -982,7 +993,7 @@ impl CvmVerifier { "✓ UKI hash verified from PCR 2 Event Log (Event 28), digest: {}", hex::encode(event_28_digest) ); - Ok(()) + Ok(measurement) } pub async fn download_image(&self, hex_os_image_hash: &str, dst_dir: &Path) -> Result<()> { @@ -1080,6 +1091,36 @@ fn is_transient(err: &anyhow::Error) -> bool { } /// MRTD and RTMR0-2 from the verified TD report. +/// The GCE machine shape the VM config claims. It only selects which ACPI +/// tables and TD HOB to regenerate; they must still match the measured ones. +fn gcp_machine(vm_config: &VmConfig) -> Result { + ensure!( + vm_config.cpu_count > 0 && vm_config.memory_size > 0, + "GCP TDX boot-chain verification requires vm_config.cpu_count and memory_size" + ); + ensure!( + vm_config + .numa_nodes + .iter() + .all(|node| node.pxb_bus.is_none()), + "GCE has no PCIe expander bridges" + ); + Ok(dstack_mr::gcp::MachineConfig { + cpu_count: vm_config + .cpu_count + .try_into() + .context("cpu_count out of range")?, + memory_size: vm_config.memory_size, + numa_nodes: vm_config + .numa_nodes + .len() + .max(1) + .try_into() + .context("too many NUMA nodes")?, + gpu: vm_config.num_gpus > 0, + }) +} + fn verified_tdx_mrs(attestation: &VerifiedAttestation) -> Result { let report = attestation .report @@ -1198,6 +1239,47 @@ mod tests { } } + const GCP_PCR0: [u8; 32] = + hex!("0cca9ec161b09288802e5a112255d21340ed5b797f5fe29cecccfd8f67b9f802"); + + fn gcp_vm_config(measurement: &dstack_types::GcpOsImageMeasurement) -> serde_json::Value { + let measurement_bytes = measurement.to_cbor_vec(); + let checksum_file = format!( + "{} measurement.gcp.cbor\n", + hex::encode(Sha256::digest(&measurement_bytes)) + ) + .into_bytes(); + let os_image_hash = dstack_types::image_hash_from_sha256sum(&checksum_file); + serde_json::json!({ + "os_image_hash": hex::encode(os_image_hash), + "cpu_count": 4, + "memory_size": 16u64 << 30, + "gcp_measurement": dstack_types::GcpOsImageMeasurementDocument::new( + checksum_file, + measurement_bytes, + ), + }) + } + + /// A GCP vTPM report with `pcr0` and the UKI digest as the third PCR2 event. + fn gcp_tpm_report(pcr0: Vec, uki_hash: Vec) -> TpmVerifiedReport { + TpmVerifiedReport { + pcr_values: vec![tpm_types::PcrValue { + index: 0, + algorithm: "sha256".into(), + value: pcr0, + }], + event_log: [vec![1; 32], vec![2; 32], uki_hash] + .into_iter() + .map(|digest| tpm_types::TpmEvent { + pcr_index: 2, + digest, + }) + .collect(), + ..tpm_report_for_gcp() + } + } + fn tpm_report_for_gcp() -> TpmVerifiedReport { TpmVerifiedReport { attest: TpmAttest { @@ -1424,46 +1506,12 @@ mod tests { .is_err()); let uki_hash = vec![0x24; 32]; - let measurement = dstack_types::GcpOsImageMeasurement::new(uki_hash.clone()).unwrap(); - let measurement_bytes = measurement.to_cbor_vec(); - let checksum_file = format!( - "{} measurement.gcp.cbor\n", - hex::encode(Sha256::digest(&measurement_bytes)) - ) - .into_bytes(); - let os_image_hash = dstack_types::image_hash_from_sha256sum(&checksum_file); - let gcp_config: VmConfig = serde_json::from_value(serde_json::json!({ - "os_image_hash": hex::encode(os_image_hash), - "gcp_measurement": dstack_types::GcpOsImageMeasurementDocument::new( - checksum_file, - measurement_bytes, - ), - })) + let gcp_config: VmConfig = serde_json::from_value(gcp_vm_config( + &dstack_types::GcpOsImageMeasurement::new(uki_hash.clone()).unwrap(), + )) .unwrap(); - let expected_pcr0 = - hex!("0cca9ec161b09288802e5a112255d21340ed5b797f5fe29cecccfd8f67b9f802"); - let gcp_report = |pcr0: Vec, event_28: Vec| TpmVerifiedReport { - pcr_values: vec![tpm_types::PcrValue { - index: 0, - algorithm: "sha256".into(), - value: pcr0, - }], - event_log: vec![ - tpm_types::TpmEvent { - pcr_index: 2, - digest: vec![1; 32], - }, - tpm_types::TpmEvent { - pcr_index: 2, - digest: vec![2; 32], - }, - tpm_types::TpmEvent { - pcr_index: 2, - digest: event_28, - }, - ], - ..tpm_report_for_gcp() - }; + let expected_pcr0 = GCP_PCR0; + let gcp_report = gcp_tpm_report; verifier .verify_os_image_hash_for_gcp_tdx( &gcp_config, @@ -1492,6 +1540,67 @@ mod tests { .is_err()); } + /// A v2 measurement makes the TDX boot chain mandatory: a boot whose vTPM + /// checks pass but whose MRTD is not a GCE TDVF build is rejected. + #[tokio::test] + async fn gcp_v2_measurement_requires_the_tdx_boot_chain() { + let uki_hash = vec![0x24; 32]; + let v1 = dstack_types::GcpOsImageMeasurement::new(uki_hash.clone()).unwrap(); + let v2 = v1 + .clone() + .with_tdx(dstack_types::GcpTdxImageMeasurement { + rtmr1: vec![0; 48], + rtmr2: vec![0; 48], + }) + .unwrap(); + let attestation = verified_attestation( + AttestationQuote::DstackGcpTdx(DstackGcpTdxQuote { + tdx_quote: TdxQuote { + quote: Vec::new(), + event_log: Vec::new(), + }, + tpm_quote: TpmQuote { + message: Vec::new(), + signature: Vec::new(), + pcr_values: Vec::new(), + ak_cert: Vec::new(), + platform: dstack_types::Platform::Gcp, + event_log: Vec::new(), + }, + }), + DstackVerifiedReport::DstackGcpTdx { + tdx_report: tdx_report("UpToDate", &[]), + tpm_report: gcp_tpm_report(GCP_PCR0.to_vec(), uki_hash), + }, + ); + let verify = |measurement| { + let attestation = &attestation; + async move { + let mut details = VerificationDetails::default(); + let result = test_verifier() + .verify_os_image_hash( + gcp_vm_config(&measurement).to_string(), + attestation, + &mut details, + ) + .await; + (result, details.acpi_tables_verified) + } + }; + + let (result, acpi_verified) = verify(v1).await; + result.unwrap(); + assert!(!acpi_verified); + + let (result, acpi_verified) = verify(v2).await; + let err = result.unwrap_err(); + assert!( + format!("{err:#}").contains("not a known GCE TDVF build"), + "{err:#}" + ); + assert!(!acpi_verified); + } + #[test] fn aws_os_image_check_requires_measurement() { let pcrs = aws_boot_pcrs(0x04); diff --git a/os/image/assemble.sh b/os/image/assemble.sh index 5aca18b3dc..53551493eb 100755 --- a/os/image/assemble.sh +++ b/os/image/assemble.sh @@ -522,7 +522,8 @@ if [[ "$UKI_CREATED" = "1" ]]; then exit 1 fi echo "Generating measurement.gcp.cbor via ${DSTACK_MR_BIN}" - "${DSTACK_MR_BIN}" gcp-measurement-cbor "${OUTPUT_DIR}/auth_hash.txt" > "${OUTPUT_DIR}/measurement.gcp.cbor" + "${DSTACK_MR_BIN}" gcp-measurement-cbor "${OUTPUT_DIR}/auth_hash.txt" \ + "$UKI_IMAGE" "${OUTPUT_DIR}/disk.raw" > "${OUTPUT_DIR}/measurement.gcp.cbor" if [[ "$IS_DEV" = "true" ]]; then gcp_event_log_template="${GCP_TPM_EVENT_LOG_TEMPLATE:-$(dirname "$0")/../../dstack/cc-eventlog/samples/tpm_eventlog.bin}" echo "Generating image-specific GCP TPM event log for the dev image"