From a6f46bb16b0c3f24d21a00e22690a0c46b893479 Mon Sep 17 00:00:00 2001 From: Samuel Laferriere <9342524+samlaf@users.noreply.github.com> Date: Fri, 7 Aug 2026 15:43:22 -0400 Subject: [PATCH 1/8] attestation: make platform metadata best-effort for azure evidence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Azure marketplace kernels (linux-azure, linux-azure-fde) do not ship CONFIG_DMI_SYSFS, and where dmi-sysfs does exist its raw entries are readable only by root, so azure evidence generation on a stock Azure CVM fails with "Cannot retrieve platform metadata: I/O: No such file or directory". No verifier consults ram_bytes/num_disks for azure evidence — they exist for the portable image-hash policies on DCAP/GCP platforms — so collect them best-effort: use SMBIOS when available, otherwise fall back to /proc/meminfo for RAM and a /sys/block count for disks. The disk count holds to what platform::metadata_for would have returned: one named list of virtual device prefixes, the same set is_virtual_block_device excludes, and the Azure resource disk subtracted the way metadata_for subtracts it. A LUKS node carries dm-* devices, so a filter blind to those would over-count on exactly the machines this fallback exists for. The proper home for all of this is attest-measure's platform::metadata_for, where a /proc/meminfo fallback would cover every platform and caller; a TODO marks the added block for deletion once that lands in easy-tee/attest and the attest pin picks it up. --- crates/attestation/src/lib.rs | 80 +++++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/crates/attestation/src/lib.rs b/crates/attestation/src/lib.rs index 18c4b0b..9b02688 100644 --- a/crates/attestation/src/lib.rs +++ b/crates/attestation/src/lib.rs @@ -215,6 +215,81 @@ impl Decode for AttestationType { } } +// TODO: this fallback (and the two helpers below) belongs in +// attest-measure's `platform::metadata_for` — a /proc/meminfo fallback +// there would cover every platform and caller, not just azure. Upstream it +// to easy-tee/attest, then delete these once attested-tls picks up the +// fixed attest pin. +/// Platform metadata for Azure evidence, tolerating hosts without SMBIOS +/// access. +/// +/// Azure measurement policies are enforced against vTPM PCRs; no verifier +/// consults `ram_bytes`/`num_disks` for Azure evidence (they exist for the +/// portable image-hash policies on DCAP/GCP platforms). Azure marketplace +/// kernels (linux-azure, linux-azure-fde) do not ship CONFIG_DMI_SYSFS, and +/// where dmi-sysfs does exist its raw entries are readable by root only, so +/// a hard dependency on SMBIOS would break Azure attesters on stock kernels +/// and in non-root services. Use the real SMBIOS values when available and +/// fall back to /proc/meminfo plus a /sys/block disk count otherwise. +#[cfg(feature = "azure-attester")] +fn azure_platform_metadata() -> PlatformMetadata { + match attest_measure::platform::metadata_for(attest_types::AttestationType::AzureTdx) { + Ok(platform) => platform, + Err(error) => { + tracing::warn!( + "SMBIOS platform metadata unavailable ({error}); \ + falling back to /proc/meminfo" + ); + PlatformMetadata { + attestation_type: attest_types::AttestationType::AzureTdx, + ram_bytes: meminfo_total_bytes().unwrap_or(0), + // Mirror metadata_for's Azure adjustment: don't count the + // Azure resource disk. + num_disks: count_block_devices().saturating_sub(1), + // Azure evidence carries no CCEL, so metadata_for reports + // no SMBIOS handoff hash and no dm-verity boot for this + // platform. + acpi: None, + smbios_handoff: None, + dm_verity_boot: false, + } + } + } +} + +/// MemTotal from /proc/meminfo, in bytes. World-readable on every kernel. +#[cfg(feature = "azure-attester")] +fn meminfo_total_bytes() -> Option { + let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?; + let kib = meminfo + .lines() + .find_map(|line| line.strip_prefix("MemTotal:"))? + .trim() + .strip_suffix("kB")? + .trim() + .parse::() + .ok()?; + Some(kib * 1024) +} + +/// Physical block devices under /sys/block, excluding virtual ones — the +/// same filter attest-measure applies. +#[cfg(feature = "azure-attester")] +fn count_block_devices() -> u32 { + const VIRTUAL_PREFIXES: &[&str] = &["dm-", "loop", "md", "ram", "zram"]; + let Ok(entries) = std::fs::read_dir("/sys/block") else { + return 0; + }; + entries + .filter_map(|entry| entry.ok()) + .filter(|entry| { + let name = entry.file_name(); + let name = name.to_string_lossy(); + !VIRTUAL_PREFIXES.iter().any(|prefix| name.starts_with(prefix)) + }) + .count() as u32 +} + impl Display for AttestationType { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) @@ -292,13 +367,10 @@ impl AttestationGenerator { AttestationType::AzureTdx => { #[cfg(azure_attester_x86_64_linux)] { - let platform = attest_measure::platform::metadata_for( - self.attestation_type.try_into()?, - )?; Ok(AttestationExchangeMessage { attestation_evidence: Some(AttestationEvidence { quote: azure::create_azure_attestation(input_data)?, - platform, + platform: azure_platform_metadata(), }), }) } From b2f713396ecb7c2a1908565319567acd03ea7053 Mon Sep 17 00:00:00 2001 From: Samuel Laferriere <9342524+samlaf@users.noreply.github.com> Date: Fri, 11 Sep 2026 23:56:39 -0400 Subject: [PATCH 2/8] feat(attestation): export the compiled-in Azure vTPM root CAs (#6) Needed for https://linear.app/seismic-systems/issue/SEI-426/refactorenclave-archive-one-atomic-re-verification-bundle-instead-of A verdict on Azure evidence rests on two root CAs compiled into this crate. They are the one input a relying party archiving a verification cannot capture beside the evidence the way it captures the fetched DCAP bundle: the AK certificate chain rides in the evidence and nothing else on that leg is fetched, so the roots are the whole of what it chains to. Export them as `azure::AZURE_ROOT_CA_PEMS`, each asset's file stem and its PEM text in anchor order, so such a party can record which anchors a verdict rested on and notice when a replaying build carries different ones. The anchor list is now built from the same array, so the two cannot drift. --- .../attestation/src/azure/ak_certificate.rs | 22 ++++++++++++------- crates/attestation/src/azure/mod.rs | 1 + 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/crates/attestation/src/azure/ak_certificate.rs b/crates/attestation/src/azure/ak_certificate.rs index a2fefe1..97d7e52 100644 --- a/crates/attestation/src/azure/ak_certificate.rs +++ b/crates/attestation/src/azure/ak_certificate.rs @@ -20,15 +20,21 @@ const MICROSOFT_RSA_DEVICES_ROOT_2021: &str = pub(super) const AZURE_VIRTUAL_TPM_ROOT_2023: &str = include_str!("../../assets/azure-virtual-tpm-root-2023.pem"); +/// The root CAs an AK certificate chain is verified against, as compiled +/// in: each asset's file stem and its PEM text, in anchor order +/// +/// Compiled in rather than fetched, so they are the one verification input +/// a relying party cannot archive beside the evidence. Exported so such a +/// party can record which anchors a verdict rested on — a replay needs a +/// build carrying the same ones. +pub const AZURE_ROOT_CA_PEMS: [(&str, &str); 2] = [ + ("microsoft-rsa-devices-root-ca-2021", MICROSOFT_RSA_DEVICES_ROOT_2021), + ("azure-virtual-tpm-root-2023", AZURE_VIRTUAL_TPM_ROOT_2023), +]; + /// The root anchors for azure -static AZURE_ROOT_ANCHORS: Lazy>> = Lazy::new(|| { - vec![ - // Microsoft RSA Devices Root CA 2021 (older VMs) - pem_to_trust_anchor(MICROSOFT_RSA_DEVICES_ROOT_2021), - // Azure Virtual TPM Root CA 2023 (TDX + newer trusted launch) - pem_to_trust_anchor(AZURE_VIRTUAL_TPM_ROOT_2023), - ] -}); +static AZURE_ROOT_ANCHORS: Lazy>> = + Lazy::new(|| AZURE_ROOT_CA_PEMS.iter().map(|(_, pem)| pem_to_trust_anchor(pem)).collect()); /// Verify an AK certificate against pinned Azure root CAs. /// diff --git a/crates/attestation/src/azure/mod.rs b/crates/attestation/src/azure/mod.rs index 0a53029..0a29471 100644 --- a/crates/attestation/src/azure/mod.rs +++ b/crates/attestation/src/azure/mod.rs @@ -6,6 +6,7 @@ mod tpm_quote; mod tpms_attest; mod verify; +pub use ak_certificate::AZURE_ROOT_CA_PEMS; #[cfg(azure_attester_x86_64_linux)] pub use attester::{create_azure_attestation, detect_azure_cvm}; use az_cvm_vtpm::hcl; From 1e9963520dbe978e3da0b2280c255a59e64a84ed Mon Sep 17 00:00:00 2001 From: Henry Baldwin Date: Fri, 9 Oct 2026 18:53:20 +0000 Subject: [PATCH 3/8] attestation: pin Google's GCE-cc-tcb-root_1 Google signs one VMLaunchEndorsement per TDX firmware build under GCE-cc-tcb-root_1, published at https://pki.goog/cloud_integrity/. Compile that root in rather than fetch it at verification time, and export it with its published name so a relying party can record which root it trusted. x509-parser leaves the azure-verifier feature: GCP needs it on every build. --- Cargo.lock | 1 + crates/attestation/Cargo.toml | 5 ++-- .../attestation/assets/GCE-cc-tcb-root_1.crt | Bin 0 -> 1570 bytes crates/attestation/src/gcp/endorsement.rs | 24 ++++++++++++++++++ crates/attestation/src/gcp/mod.rs | 2 ++ crates/attestation/src/lib.rs | 2 ++ 6 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 crates/attestation/assets/GCE-cc-tcb-root_1.crt create mode 100644 crates/attestation/src/gcp/endorsement.rs diff --git a/Cargo.lock b/Cargo.lock index 368589b..4b85123 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -406,6 +406,7 @@ dependencies = [ "serde", "serde-saphyr", "serde_json", + "sha2 0.10.9", "tdx-attest 0.6.0", "tempfile", "thiserror 2.0.18", diff --git a/crates/attestation/Cargo.toml b/crates/attestation/Cargo.toml index f193e49..f7f4871 100644 --- a/crates/attestation/Cargo.toml +++ b/crates/attestation/Cargo.toml @@ -25,12 +25,14 @@ serde_json = "1.0.145" thiserror = "2.0.17" tracing = "0.1.41" ureq = "3.5.0" +# GCP firmware endorsement verification +x509-parser = { version = "0.18.0", features = ["verify"] } +sha2 = "0.10" mock-tdx = { workspace = true, optional = true } # For optional Azure support rustls-pki-types = { version = "1.14.0", optional = true } -x509-parser = { version = "0.18.0", optional = true } webpki = { package = "rustls-webpki", version = "0.103.8", optional = true } num-bigint = { version = "0.4.6", optional = true } base64 = { version = "0.22.1", optional = true } @@ -84,7 +86,6 @@ azure-verifier = [ "dep:pem-rfc7468", "dep:rustls-pki-types", "dep:webpki", - "dep:x509-parser", ] # Deprecated alias for `azure-attester`, kept only for backwards diff --git a/crates/attestation/assets/GCE-cc-tcb-root_1.crt b/crates/attestation/assets/GCE-cc-tcb-root_1.crt new file mode 100644 index 0000000000000000000000000000000000000000..045019cd089b8c78e99202d1d965b36fbafe3ba9 GIT binary patch literal 1570 zcmXqLVv{pyV!pJ1nTe5!iILI3k&RQU&7W z`mnLzVGv%U6vDZnki}+!ht8F=oaSY(avs;Wr(ZeQK6O{m_NkT^OW#WxHVPh!Zsiwx zE3&S+s8z(S;m0TMc_9y)(k4e+dEHNY_=qDux%2b$@OvQ-j@AEDs$959u-fk6^2K@f zDF)%vtai&=&Er0?Jxk!)FHu?}guDZ)Di;c-!T=tAfX45)TF@zy9&^-qQY$a=-iz%Gc)YDLWEs!Z+_>hpy3O!I<`K zd%7Dcxc1rZllu_=Qo+N|$?xaRo1E_+@0usJ?)IWZ677>x68yvpUYwV@l$5O|*?fKH zelyiVncP{4ZLd~FY@BPCBD?qW)K8+FyUJ7+otP*XaP$m!HVc<__{4mZGc0fSD7G&2 z{#|gq>Se3wR&AD!Qx86vIT`HCKgqOZ<2A3`!-0-RRhI6^-#hd5qqWxztADL?PRoza>^ZY5VdR{vF74zop`75~A?Jx*=T6zEC1kpE^ zFLX_|9M=lG-L9~2%9J3xhxwYux~ugLT=-HJqczR&>O8;Rxadx&ye~CfXWAk)xPDGG z%sdg~X6ou@Y@77td+MR;q^}J7(qxrhUEIPYxT$8U^v9@{2d9~s85tNCyBatf@BtIF zEI%XTe-;*Co?-)M2w7nepTmF+NC6XzfhNN1?pSTV|Hn5it_NL94{|MBp5N)uWPfT?uzK22_hsEzOkKXtP_Q!Ee~B~E{E2{JX02_X!TQ&QZ3WN8*KPRlX=B+m{lH45 z)dgoO#f2_LK5A)D`0l>iqD|ya(BYMa4(3dDU&YSO@s+C$GT#x$b}gWU%~OZr%jrnt z$5FL$&sel_iVYkDGn|Y`|b<wYk(`)#NUxDspkbA%c`w890(>V5SeADt|lB`Xh@a{wW#un~IZ~f~Y z?oLqLz0M}eMD=ad h?S@Cq<3r0%#N;Q;GU>8bzc6Xb7rpCu3PfLW0|2fPUseDB literal 0 HcmV?d00001 diff --git a/crates/attestation/src/gcp/endorsement.rs b/crates/attestation/src/gcp/endorsement.rs new file mode 100644 index 0000000..32b4f5c --- /dev/null +++ b/crates/attestation/src/gcp/endorsement.rs @@ -0,0 +1,24 @@ +//! The root Google signs its GCP firmware endorsements under + +/// `GCE-cc-tcb-root_1.crt` from `https://pki.goog/cloud_integrity/`, DER +pub const GCE_CC_TCB_ROOT_DER: &[u8] = include_bytes!("../../assets/GCE-cc-tcb-root_1.crt"); +/// The pinned root's published name +pub const GCE_CC_TCB_ROOT_NAME: &str = "GCE-cc-tcb-root_1"; + +#[cfg(test)] +mod tests { + use sha2::{Digest as _, Sha256}; + use x509_parser::prelude::*; + + use super::*; + + #[test] + fn the_pinned_root_is_the_published_one() { + assert_eq!( + hex::encode(Sha256::digest(GCE_CC_TCB_ROOT_DER)), + "e876bc6978bf4f3da445f98a0a82363c8c0bae5a1fc033c6df65846a6cb0f18c" + ); + let (_, root) = X509Certificate::from_der(GCE_CC_TCB_ROOT_DER).unwrap(); + assert_eq!(root.subject(), root.issuer()); + } +} diff --git a/crates/attestation/src/gcp/mod.rs b/crates/attestation/src/gcp/mod.rs index 244b8c2..e855cc4 100644 --- a/crates/attestation/src/gcp/mod.rs +++ b/crates/attestation/src/gcp/mod.rs @@ -1,6 +1,8 @@ //! Google Cloud Platform related attestation verification logic +mod endorsement; mod firmware; mod provenance; +pub use endorsement::{GCE_CC_TCB_ROOT_DER, GCE_CC_TCB_ROOT_NAME}; pub(crate) use firmware::{GcpFirmwareCache, fetch_firmware}; pub(crate) use provenance::{GcpProvenanceChecker, GcpProvenanceError}; diff --git a/crates/attestation/src/lib.rs b/crates/attestation/src/lib.rs index 9b02688..35d6437 100644 --- a/crates/attestation/src/lib.rs +++ b/crates/attestation/src/lib.rs @@ -25,6 +25,8 @@ pub use attest_types::{AttestationEvidence, PlatformMetadata}; /// Re-exported so callers can archive [EndorsementSnapshot::dcap] without /// depending on `dcap-qvl` directly pub use dcap_qvl::QuoteCollateralV3; +/// The root Google signs its GCP firmware endorsements under +pub use gcp::{GCE_CC_TCB_ROOT_DER, GCE_CC_TCB_ROOT_NAME}; use measurements::{ExpectedMeasurements, MultiMeasurements}; /// Re-exported to allow encoding and decoding AttestationEvidence to or /// from bytes From 65a7247760119ea17e26c0842dfd8a6c369b9ff3 Mon Sep 17 00:00:00 2001 From: Henry Baldwin Date: Fri, 9 Oct 2026 18:53:20 +0000 Subject: [PATCH 4/8] attestation: check Google's firmware endorsement on every live gcp-tdx verification Upstream consults Google's firmware endorsement only when a portable-image policy matches, so a gcp-tdx verification that pins registers gets no firmware check at all. After the provenance check, fetch the VMLaunchEndorsement Google publishes for the quote's MRTD and verify it at the verification instant: the leaf certificate is issued and signed by the pinned root, both are valid then, no unrecognised critical extension, key usage allows signing, the RSA-PSS signature over the golden measurement holds, and the measurement names the quote's MRTD. Google publishes no revocation source for these certificates, so none is consulted. The fetch and cache follow provenance.rs: one verified copy per MRTD, and a cached copy that stops verifying is evicted and refetched once. --- Cargo.lock | 2 + crates/attestation/Cargo.toml | 2 + crates/attestation/src/gcp/endorsement.rs | 524 +++++++++++++++++- crates/attestation/src/gcp/mod.rs | 8 +- crates/attestation/src/lib.rs | 37 +- .../gce-endorsement-c3-standard-4.binarypb | Bin 0 -> 5308 bytes 6 files changed, 566 insertions(+), 7 deletions(-) create mode 100644 crates/attestation/test-assets/gce-endorsement-c3-standard-4.binarypb diff --git a/Cargo.lock b/Cargo.lock index 4b85123..f75b281 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -399,7 +399,9 @@ dependencies = [ "parity-scale-codec", "pccs", "pem-rfc7468 0.7.0", + "prost", "reqwest 0.13.4", + "rsa", "rustls", "rustls-pki-types", "rustls-webpki", diff --git a/crates/attestation/Cargo.toml b/crates/attestation/Cargo.toml index f7f4871..5028a74 100644 --- a/crates/attestation/Cargo.toml +++ b/crates/attestation/Cargo.toml @@ -28,6 +28,8 @@ ureq = "3.5.0" # GCP firmware endorsement verification x509-parser = { version = "0.18.0", features = ["verify"] } sha2 = "0.10" +prost = "0.14" +rsa = "0.9" mock-tdx = { workspace = true, optional = true } diff --git a/crates/attestation/src/gcp/endorsement.rs b/crates/attestation/src/gcp/endorsement.rs index 32b4f5c..8e0f506 100644 --- a/crates/attestation/src/gcp/endorsement.rs +++ b/crates/attestation/src/gcp/endorsement.rs @@ -1,17 +1,485 @@ -//! The root Google signs its GCP firmware endorsements under +//! Google's endorsement of the firmware a GCP TDX quote's MRTD names +//! +//! Google publishes one signed `VMLaunchEndorsement` per TDX firmware +//! build, keyed by MRTD, signed under `GCE-cc-tcb-root`. A live `gcp-tdx` +//! verification fetches the quote's, verifies it at the verification +//! instant and records it in the [`EndorsementSnapshot`]; a replay verifies +//! the recorded one at the snapshot's instant. +//! +//! [`EndorsementSnapshot`]: crate::EndorsementSnapshot +use std::{ + collections::HashMap, + io::Read, + sync::{Arc, RwLock}, + time::Duration, +}; +use prost::Message; +use rsa::{ + RsaPublicKey, + pkcs8::DecodePublicKey, + pss::{Signature, VerifyingKey}, + signature::Verifier, +}; +use sha2::Sha256; +use thiserror::Error; +use x509_parser::prelude::*; + +use crate::HTTP_CONNECT_TIMEOUT; + +/// Where Google publishes one endorsement per TDX firmware MRTD +const GCE_TCB_ENDORSEMENT_BUCKET_URL: &str = + "https://storage.googleapis.com/gce_tcb_integrity/ovmf_x64_csm/tdx"; /// `GCE-cc-tcb-root_1.crt` from `https://pki.goog/cloud_integrity/`, DER pub const GCE_CC_TCB_ROOT_DER: &[u8] = include_bytes!("../../assets/GCE-cc-tcb-root_1.crt"); /// The pinned root's published name pub const GCE_CC_TCB_ROOT_NAME: &str = "GCE-cc-tcb-root_1"; +/// Overall timeout for fetching an endorsement (DNS, connect, TLS, read) +const GCE_TCB_ENDORSEMENT_FETCH_TIMEOUT: Duration = Duration::from_secs(30); +/// Maximum size in bytes of an endorsement document +const GCE_TCB_ENDORSEMENT_MAX_BYTES: u64 = 64 * 1024; + +/// `VMLaunchEndorsement` from Google's `gce-tcb-verifier` protobuf +#[derive(Clone, PartialEq, Message)] +struct VmLaunchEndorsement { + #[prost(bytes = "vec", tag = "1")] + serialized_uefi_golden: Vec, + #[prost(bytes = "vec", tag = "2")] + signature: Vec, +} + +/// `VMGoldenMeasurement`, the fields this check reads +#[derive(Clone, PartialEq, Message)] +struct VmGoldenMeasurement { + #[prost(bytes = "vec", tag = "4")] + cert: Vec, + #[prost(message, optional, tag = "8")] + tdx: Option, +} + +#[derive(Clone, PartialEq, Message)] +struct VmTdx { + #[prost(message, repeated, tag = "2")] + measurements: Vec, +} + +#[derive(Clone, PartialEq, Message)] +struct VmTdxMeasurement { + #[prost(bytes = "vec", tag = "3")] + mrtd: Vec, +} + +/// A `VMLaunchEndorsement` as Google published it, verbatim +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GcpFirmwareEndorsement(Vec); + +impl GcpFirmwareEndorsement { + /// Wrap published bytes; nothing is checked until [`Self::verify`] + pub fn new(bytes: Vec) -> Self { + Self(bytes) + } + + pub fn as_bytes(&self) -> &[u8] { + &self.0 + } + + pub fn into_bytes(self) -> Vec { + self.0 + } + + /// Verify at `at` (Unix seconds) that this endorsement names `mrtd` + pub fn verify(&self, mrtd: [u8; 48], at: u64) -> Result<(), GcpEndorsementError> { + verify_endorsement(&self.0, mrtd, at) + } +} + +/// Verify at `at` (Unix seconds) that `endorsement` names `mrtd`: its +/// certificate is issued and signed by the pinned root and valid then, and +/// its RSA-PSS signature over the golden measurement holds +fn verify_endorsement( + endorsement: &[u8], + mrtd: [u8; 48], + at: u64, +) -> Result<(), GcpEndorsementError> { + verify_endorsement_under_root(endorsement, GCE_CC_TCB_ROOT_DER, mrtd, at) +} + +fn verify_endorsement_under_root( + endorsement: &[u8], + root_der: &[u8], + mrtd: [u8; 48], + at: u64, +) -> Result<(), GcpEndorsementError> { + let endorsement = VmLaunchEndorsement::decode(endorsement)?; + let golden = VmGoldenMeasurement::decode(&*endorsement.serialized_uefi_golden)?; + let (_, root) = X509Certificate::from_der(root_der) + .map_err(|e| GcpEndorsementError::Cert(e.to_string()))?; + let (_, leaf) = X509Certificate::from_der(&golden.cert) + .map_err(|e| GcpEndorsementError::Cert(e.to_string()))?; + let at = i64::try_from(at) + .ok() + .and_then(|at| ASN1Time::from_timestamp(at).ok()) + .ok_or(GcpEndorsementError::CertNotValidAt)?; + verify_leaf_under_root(&leaf, &root, at)?; + let key = RsaPublicKey::from_public_key_der(leaf.public_key().raw) + .map_err(|e| GcpEndorsementError::Key(e.to_string()))?; + let signature = + Signature::try_from(&*endorsement.signature).map_err(|_| GcpEndorsementError::Signature)?; + VerifyingKey::::new(key) + .verify(&endorsement.serialized_uefi_golden, &signature) + .map_err(|_| GcpEndorsementError::Signature)?; + let tdx = golden.tdx.ok_or(GcpEndorsementError::NoTdx)?; + if tdx.measurements.iter().any(|m| m.mrtd == mrtd) { + Ok(()) + } else { + Err(GcpEndorsementError::MrtdNotEndorsed(hex::encode(mrtd))) + } +} + +/// The chain is one hop. The leaf must name the pinned root as its issuer, +/// carry the root's signature, be valid at `at` along with the root, and +/// carry no critical extension this check does not understand. Google +/// publishes no revocation source for these certificates, so none is +/// consulted. +fn verify_leaf_under_root( + leaf: &X509Certificate<'_>, + root: &X509Certificate<'_>, + at: ASN1Time, +) -> Result<(), GcpEndorsementError> { + if leaf.issuer() != root.subject() { + return Err(GcpEndorsementError::CertChain); + } + if !root.validity().is_valid_at(at) || !leaf.validity().is_valid_at(at) { + return Err(GcpEndorsementError::CertNotValidAt); + } + leaf.verify_signature(Some(root.public_key())).map_err(|_| GcpEndorsementError::CertChain)?; + for extension in leaf.extensions() { + match extension.parsed_extension() { + ParsedExtension::KeyUsage(usage) if !usage.digital_signature() => { + return Err(GcpEndorsementError::CertKeyUsage); + } + ParsedExtension::KeyUsage(_) | + ParsedExtension::BasicConstraints(_) | + ParsedExtension::ExtendedKeyUsage(_) | + ParsedExtension::SubjectKeyIdentifier(_) | + ParsedExtension::AuthorityKeyIdentifier(_) | + ParsedExtension::SubjectAlternativeName(_) => {} + _ if extension.critical => { + return Err(GcpEndorsementError::CertCriticalExtension(extension.oid.to_string())); + } + _ => {} + } + } + Ok(()) +} + +/// Fetches and verifies Google's endorsement for an MRTD, keeping one +/// verified copy per MRTD until it stops verifying +#[derive(Clone, Debug)] +pub(crate) struct GcpEndorsementChecker { + endorsements: Arc>>>, +} + +impl GcpEndorsementChecker { + pub(crate) fn new() -> Self { + Self { endorsements: Default::default() } + } + + /// Google's endorsement of `mrtd`, verified at `at` (Unix seconds); the + /// fetch runs on the tokio blocking pool when a runtime is available + pub(crate) async fn endorsement_for( + &self, + mrtd: [u8; 48], + at: u64, + ) -> Result { + self.endorsement_for_with_bucket_url(mrtd, GCE_TCB_ENDORSEMENT_BUCKET_URL.to_string(), at) + .await + } + + async fn endorsement_for_with_bucket_url( + &self, + mrtd: [u8; 48], + bucket_url: String, + at: u64, + ) -> Result { + match tokio::runtime::Handle::try_current() { + Ok(handle) => { + let checker = self.clone(); + handle + .spawn_blocking(move || { + checker.endorsement_for_with_bucket_url_blocking_at(mrtd, &bucket_url, at) + }) + .await + .map_err(|err| GcpEndorsementError::TaskJoin(err.to_string()))? + } + Err(_) => self.endorsement_for_with_bucket_url_blocking_at(mrtd, &bucket_url, at), + } + } + + /// Google's endorsement of `mrtd`, verified at `at` (Unix seconds); on + /// a multi-threaded tokio runtime the fetch is marked as blocking + pub(crate) fn endorsement_for_sync( + &self, + mrtd: [u8; 48], + at: u64, + ) -> Result { + self.endorsement_for_with_bucket_url_sync_at(mrtd, GCE_TCB_ENDORSEMENT_BUCKET_URL, at) + } + + fn endorsement_for_with_bucket_url_sync_at( + &self, + mrtd: [u8; 48], + bucket_url: &str, + at: u64, + ) -> Result { + let fetch = || self.endorsement_for_with_bucket_url_blocking_at(mrtd, bucket_url, at); + + match tokio::runtime::Handle::try_current() { + Ok(handle) + if matches!( + handle.runtime_flavor(), + tokio::runtime::RuntimeFlavor::MultiThread + ) => + { + tokio::task::block_in_place(fetch) + } + _ => fetch(), + } + } + + fn endorsement_for_with_bucket_url_blocking_at( + &self, + mrtd: [u8; 48], + bucket_url: &str, + at: u64, + ) -> Result { + let cached = self + .endorsements + .read() + .map_err(|err| GcpEndorsementError::CacheLock(err.to_string()))? + .get(&mrtd) + .cloned(); + if let Some(cached) = cached { + match cached.verify(mrtd, at) { + Ok(()) => return Ok((*cached).clone()), + Err(err) => { + tracing::warn!( + mrtd = hex::encode(mrtd), + error = %err, + "cached GCP firmware endorsement no longer verifies; refetching" + ); + let mut endorsements = self + .endorsements + .write() + .map_err(|err| GcpEndorsementError::CacheLock(err.to_string()))?; + if endorsements.get(&mrtd).is_some_and(|current| Arc::ptr_eq(current, &cached)) + { + endorsements.remove(&mrtd); + } + } + } + } + + let url = format!("{}/{}.binarypb", bucket_url.trim_end_matches('/'), hex::encode(mrtd)); + let endorsement = GcpFirmwareEndorsement::new(fetch_endorsement(&url)?); + endorsement.verify(mrtd, at)?; + self.endorsements + .write() + .map_err(|err| GcpEndorsementError::CacheLock(err.to_string()))? + .insert(mrtd, Arc::new(endorsement.clone())); + Ok(endorsement) + } +} + +/// Synchronously fetch an endorsement document +fn fetch_endorsement(url: &str) -> Result, GcpEndorsementError> { + let agent: ureq::Agent = ureq::Agent::config_builder() + .proxy(None) + .max_redirects(5) + .timeout_connect(Some(HTTP_CONNECT_TIMEOUT)) + .timeout_global(Some(GCE_TCB_ENDORSEMENT_FETCH_TIMEOUT)) + .build() + .into(); + let response = match agent.get(url).call() { + Ok(response) => response, + Err(ureq::Error::StatusCode(status)) => { + return Err(GcpEndorsementError::Fetch(format!("HTTP status {status}"))); + } + Err(err) => { + tracing::warn!(url, error = %err, "GCP firmware endorsement bucket unavailable"); + return Err(GcpEndorsementError::Unavailable(err.to_string())); + } + }; + + if response.status() != 200 { + return Err(GcpEndorsementError::Fetch(format!( + "unexpected HTTP status {}", + response.status() + ))); + } + + let mut document = Vec::new(); + response + .into_body() + .into_reader() + .take(GCE_TCB_ENDORSEMENT_MAX_BYTES + 1) + .read_to_end(&mut document) + .map_err(|err| GcpEndorsementError::Fetch(err.to_string()))?; + if document.len() as u64 > GCE_TCB_ENDORSEMENT_MAX_BYTES { + return Err(GcpEndorsementError::TooLarge); + } + Ok(document) +} + +#[derive(Error, Debug)] +pub enum GcpEndorsementError { + #[error("endorsement fetch: {0}")] + Fetch(String), + #[error("endorsement bucket unavailable: {0}")] + Unavailable(String), + #[error("endorsement exceeds maximum size")] + TooLarge, + #[error("malformed endorsement: {0}")] + Decode(#[from] prost::DecodeError), + #[error("endorsement certificate: {0}")] + Cert(String), + #[error("endorsement certificate is not issued by {GCE_CC_TCB_ROOT_NAME}")] + CertChain, + #[error("endorsement certificate is not valid at the verification instant")] + CertNotValidAt, + #[error("endorsement certificate has an unrecognised critical extension {0}")] + CertCriticalExtension(String), + #[error("endorsement certificate is not for digital signatures")] + CertKeyUsage, + #[error("endorsement public key: {0}")] + Key(String), + #[error("endorsement signature does not verify")] + Signature, + #[error("endorsement names no TDX measurements")] + NoTdx, + #[error("endorsement does not name MRTD {0}")] + MrtdNotEndorsed(String), + #[error("endorsement cache lock: {0}")] + CacheLock(String), + #[error("blocking task join: {0}")] + TaskJoin(String), +} #[cfg(test)] mod tests { - use sha2::{Digest as _, Sha256}; - use x509_parser::prelude::*; + use std::{ + io::Write as _, + net::TcpListener, + sync::atomic::{AtomicUsize, Ordering}, + }; + + use sha2::Digest as _; use super::*; + /// Google's endorsement of the c3-standard-4 firmware a guest booted on + /// 2026-10-01, that quote's MRTD, and an instant inside the + /// certificate's validity + const ENDORSEMENT: &[u8] = + include_bytes!("../../test-assets/gce-endorsement-c3-standard-4.binarypb"); + const MRTD: &str = "c1ee9c16e3afc506cfe042c5b846a368528f3b37618eafb27469bc114cf914e9222c91618470e7f2b28ac360968270a5"; + const AT: u64 = 1_790_873_673; + const AFTER_EXPIRY: u64 = 2_000_000_000; + + fn mrtd() -> [u8; 48] { + hex::decode(MRTD).unwrap().try_into().unwrap() + } + + /// Serve `ENDORSEMENT` for `MRTD` and 404 for anything else, counting + /// requests + fn spawn_endorsement_server() -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let hits = Arc::new(AtomicUsize::new(0)); + let counter = hits.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let mut stream = stream.unwrap(); + let mut request = [0u8; 2048]; + let n = stream.read(&mut request).unwrap_or(0); + let request = String::from_utf8_lossy(&request[..n]); + counter.fetch_add(1, Ordering::SeqCst); + let (status, body): (&str, &[u8]) = + if request.contains(&format!("/{MRTD}.binarypb")) { + ("200 OK", ENDORSEMENT) + } else { + ("404 Not Found", b"") + }; + let _ = write!( + stream, + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let _ = stream.write_all(body); + } + }); + (format!("http://{addr}"), hits) + } + + #[test] + fn the_fixture_endorses_the_firmware_it_was_fetched_for() { + verify_endorsement(ENDORSEMENT, mrtd(), AT).unwrap(); + } + + #[test] + fn another_mrtd_is_not_endorsed() { + assert!(matches!( + verify_endorsement(ENDORSEMENT, [0x11; 48], AT), + Err(GcpEndorsementError::MrtdNotEndorsed(_)) + )); + } + + #[test] + fn a_tampered_signature_or_body_fails() { + let mut tampered = ENDORSEMENT.to_vec(); + let last = tampered.len() - 1; + tampered[last] ^= 1; + assert!(matches!( + verify_endorsement(&tampered, mrtd(), AT), + Err(GcpEndorsementError::Signature) + )); + let mut tampered = ENDORSEMENT.to_vec(); + tampered[64] ^= 1; + assert!(verify_endorsement(&tampered, mrtd(), AT).is_err()); + assert!(matches!( + verify_endorsement(&ENDORSEMENT[..100], mrtd(), AT), + Err(GcpEndorsementError::Decode(_)) + )); + } + + #[test] + fn outside_the_certificates_validity_fails() { + assert!(matches!( + verify_endorsement(ENDORSEMENT, mrtd(), AFTER_EXPIRY), + Err(GcpEndorsementError::CertNotValidAt) + )); + } + + /// The leaf's issuer name and signature are both checked against the + /// root the verifier pins, not whichever root the leaf names + #[test] + fn a_certificate_under_another_root_is_rejected() { + let (_, other_root) = x509_parser::pem::parse_x509_pem(include_bytes!( + "../../assets/microsoft-rsa-devices-root-ca-2021.pem" + )) + .unwrap(); + assert!(matches!( + verify_endorsement_under_root(ENDORSEMENT, &other_root.contents, mrtd(), AT), + Err(GcpEndorsementError::CertChain) + )); + let endorsement = VmLaunchEndorsement::decode(ENDORSEMENT).unwrap(); + let golden = VmGoldenMeasurement::decode(&*endorsement.serialized_uefi_golden).unwrap(); + assert!(matches!( + verify_endorsement_under_root(ENDORSEMENT, &golden.cert, mrtd(), AT), + Err(GcpEndorsementError::CertChain) + )); + } + #[test] fn the_pinned_root_is_the_published_one() { assert_eq!( @@ -21,4 +489,54 @@ mod tests { let (_, root) = X509Certificate::from_der(GCE_CC_TCB_ROOT_DER).unwrap(); assert_eq!(root.subject(), root.issuer()); } + + #[test] + fn an_endorsement_is_fetched_once_then_served_from_cache() { + let (bucket_url, hits) = spawn_endorsement_server(); + let checker = GcpEndorsementChecker::new(); + + let first = + checker.endorsement_for_with_bucket_url_sync_at(mrtd(), &bucket_url, AT).unwrap(); + let second = + checker.endorsement_for_with_bucket_url_sync_at(mrtd(), &bucket_url, AT).unwrap(); + + assert_eq!(first.as_bytes(), ENDORSEMENT); + assert_eq!(first, second); + assert_eq!(hits.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_cached_endorsement_that_stops_verifying_is_evicted_and_refetched() { + let (bucket_url, hits) = spawn_endorsement_server(); + let checker = GcpEndorsementChecker::new(); + + checker.endorsement_for_with_bucket_url_sync_at(mrtd(), &bucket_url, AT).unwrap(); + assert!(matches!( + checker.endorsement_for_with_bucket_url_sync_at(mrtd(), &bucket_url, AFTER_EXPIRY), + Err(GcpEndorsementError::CertNotValidAt) + )); + assert_eq!(hits.load(Ordering::SeqCst), 2, "the stale entry is refetched, not served"); + checker.endorsement_for_with_bucket_url_sync_at(mrtd(), &bucket_url, AT).unwrap(); + assert_eq!(hits.load(Ordering::SeqCst), 3, "the failed refetch left nothing cached"); + } + + #[test] + fn an_mrtd_google_has_not_endorsed_fails_closed() { + let (bucket_url, _) = spawn_endorsement_server(); + let checker = GcpEndorsementChecker::new(); + assert!(matches!( + checker.endorsement_for_with_bucket_url_sync_at([0x22; 48], &bucket_url, AT), + Err(GcpEndorsementError::Fetch(_)) + )); + } + + #[tokio::test] + async fn the_async_fetch_runs_on_the_blocking_pool() { + let (bucket_url, hits) = spawn_endorsement_server(); + let checker = GcpEndorsementChecker::new(); + let endorsement = + checker.endorsement_for_with_bucket_url(mrtd(), bucket_url, AT).await.unwrap(); + assert_eq!(endorsement.as_bytes(), ENDORSEMENT); + assert_eq!(hits.load(Ordering::SeqCst), 1); + } } diff --git a/crates/attestation/src/gcp/mod.rs b/crates/attestation/src/gcp/mod.rs index e855cc4..84dc8ca 100644 --- a/crates/attestation/src/gcp/mod.rs +++ b/crates/attestation/src/gcp/mod.rs @@ -3,6 +3,12 @@ mod endorsement; mod firmware; mod provenance; -pub use endorsement::{GCE_CC_TCB_ROOT_DER, GCE_CC_TCB_ROOT_NAME}; +pub(crate) use endorsement::GcpEndorsementChecker; +pub use endorsement::{ + GCE_CC_TCB_ROOT_DER, + GCE_CC_TCB_ROOT_NAME, + GcpEndorsementError, + GcpFirmwareEndorsement, +}; pub(crate) use firmware::{GcpFirmwareCache, fetch_firmware}; pub(crate) use provenance::{GcpProvenanceChecker, GcpProvenanceError}; diff --git a/crates/attestation/src/lib.rs b/crates/attestation/src/lib.rs index 35d6437..b9085d0 100644 --- a/crates/attestation/src/lib.rs +++ b/crates/attestation/src/lib.rs @@ -25,8 +25,13 @@ pub use attest_types::{AttestationEvidence, PlatformMetadata}; /// Re-exported so callers can archive [EndorsementSnapshot::dcap] without /// depending on `dcap-qvl` directly pub use dcap_qvl::QuoteCollateralV3; -/// The root Google signs its GCP firmware endorsements under -pub use gcp::{GCE_CC_TCB_ROOT_DER, GCE_CC_TCB_ROOT_NAME}; +/// Google's endorsement of a GCP TDX quote's firmware +pub use gcp::{ + GCE_CC_TCB_ROOT_DER, + GCE_CC_TCB_ROOT_NAME, + GcpEndorsementError, + GcpFirmwareEndorsement, +}; use measurements::{ExpectedMeasurements, MultiMeasurements}; /// Re-exported to allow encoding and decoding AttestationEvidence to or /// from bytes @@ -39,7 +44,7 @@ use tokio::time::sleep; use crate::{ dcap::DcapVerificationError, - gcp::{GcpFirmwareCache, GcpProvenanceChecker, GcpProvenanceError}, + gcp::{GcpEndorsementChecker, GcpFirmwareCache, GcpProvenanceChecker, GcpProvenanceError}, measurements::{MeasurementFormatError, MeasurementPolicy}, }; @@ -521,6 +526,8 @@ pub struct AttestationVerifier { known_gcp_firmware: GcpFirmwareCache, /// Cached PPIDs that have a valid GCP host-registry document gcp_provenance_checker: GcpProvenanceChecker, + /// Google's endorsements of GCP firmware, one verified copy per MRTD + gcp_endorsement_checker: GcpEndorsementChecker, /// Dynamic measurement policy to re-fetch from file or URL dynamic_measurement_policy: Option, } @@ -565,6 +572,7 @@ impl AttestationVerifierBuilder { internal_pccs: Pccs::new(self.collateral_source, self.cache_policy), known_gcp_firmware: GcpFirmwareCache::new(), gcp_provenance_checker: GcpProvenanceChecker::new(), + gcp_endorsement_checker: GcpEndorsementChecker::new(), dynamic_measurement_policy: self.dynamic_measurement_policy, }; @@ -656,6 +664,7 @@ impl AttestationVerifier { ), known_gcp_firmware: GcpFirmwareCache::new(), gcp_provenance_checker: GcpProvenanceChecker::new(), + gcp_endorsement_checker: GcpEndorsementChecker::new(), dynamic_measurement_policy: None, } } @@ -675,6 +684,7 @@ impl AttestationVerifier { ), known_gcp_firmware: GcpFirmwareCache::new(), gcp_provenance_checker: GcpProvenanceChecker::new(), + gcp_endorsement_checker: GcpEndorsementChecker::new(), dynamic_measurement_policy: None, } } @@ -697,6 +707,7 @@ impl AttestationVerifier { ), known_gcp_firmware: GcpFirmwareCache::new(), gcp_provenance_checker: GcpProvenanceChecker::new(), + gcp_endorsement_checker: GcpEndorsementChecker::new(), dynamic_measurement_policy: None, } } @@ -778,6 +789,12 @@ impl AttestationVerifier { .await?; if attestation_type == AttestationType::GcpTdx { self.gcp_provenance_checker.verify_provenance(quote).await?; + self.gcp_endorsement_checker + .endorsement_for( + dcap_mrtd(&verified.measurements)?, + verified.endorsements.at, + ) + .await?; } verified } @@ -955,6 +972,10 @@ impl AttestationVerifier { }; if attestation_type == AttestationType::GcpTdx { self.gcp_provenance_checker.verify_provenance_sync("e)?; + self.gcp_endorsement_checker.endorsement_for_sync( + dcap_mrtd(&verified.measurements)?, + verified.endorsements.at, + )?; } verified } @@ -1263,6 +1284,14 @@ pub fn mock_platform_metadata( }) } +/// The MRTD a DCAP quote reports +fn dcap_mrtd(measurements: &MultiMeasurements) -> Result<[u8; 48], AttestationError> { + match measurements { + MultiMeasurements::Dcap(dcap) => Ok(dcap.mrtd), + _ => Err(AttestationError::AttestationTypeNotAccepted), + } +} + /// An error when generating or verifying an attestation #[derive(Error, Debug)] pub enum AttestationError { @@ -1282,6 +1311,8 @@ pub enum AttestationError { DcapVerification(#[from] DcapVerificationError), #[error("GCP provenance: {0}")] GcpProvenance(#[from] GcpProvenanceError), + #[error("GCP firmware endorsement: {0}")] + GcpFirmwareEndorsement(#[from] GcpEndorsementError), #[error("Attestation type not supported")] AttestationTypeNotSupported, #[error("Attestation type not accepted")] diff --git a/crates/attestation/test-assets/gce-endorsement-c3-standard-4.binarypb b/crates/attestation/test-assets/gce-endorsement-c3-standard-4.binarypb new file mode 100644 index 0000000000000000000000000000000000000000..6a63dc19bcbba728f7db17495ebc4c2d17504309 GIT binary patch literal 5308 zcmcguXH-;Yx26gXDlk~Eph&D4anAG^HJ_X_b7tmD?@d&g!kON?qKE}MG1y{36e0F* z#1gyM6%*_QON_yS8l$m9bBDOT@80j;`}3}Q);jB~z0ZE${qA?~=UFf2`+=BFspoee zZ0eA)wd(4k#EiGIw|t+Nx2h9R-k~>8o_Mh)F(E!7A-*pFcIf!!4DO6SI>*Oj0CG(_ z(78j$q8Z$HQ({s=d~)3CK0vSkj7a@&f7irT$pt15IsuptiOQr7S&2$HNJs-Zwp*!L z32Km#38c3hDOss}i`Ql^b{YxoIbtqMRtJvDh1yMot^l^(k(QMPJ5h_%Wb#^^C?Ol@ z-tJAzO6M@)e1jq1Z_wv^T`oTX1EjY9NzRHV0DXIOCQ<#F2ISn8&=cjcmUTU&SyS$_Z6 z0XvfqZ+p})x4CJc^V|Lj$7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`v9)d)P7Moa2Aj-` zr<*Ne1}19rGMqf0U8Qn|{7z-8F|J6Ef$+475*y57yGs;Av5=4V8nn6)C2R`#B&>)} zQ>+#c*c8y?4`HGjn+Eo?b!3+uL?lM8Cu-raC1H7pY70wQ2BsvaR7Z7T5!XqOi)dyO z+v5*;3|RM-P_*aQ~ioSl}O< z%GY<>jRlJdupX3jtTOKWdOIropU_Y)%vv#&+>gQu6Ci=i^G zK%;n?kLPg5u4}U$T5PX^9qyTDUGIMX zGlt5>0#{5Qsy>dMewB8g#?WmnzL&dr8NGnn8i#g!-gG%q?PHHV?nT+iZ<`nKY92F3o!#}_g}H{03+9c;0Q*fv z$H|}d*psq@N5g415*(|ffU@u~@mR;xY0?Hfry#6CNCtrI{pSsO~1n0~1 z+XhUS)nqQVPQCoX_to}2VgIlGz-=WGksfM@V zx#^y)ry1vz;Hl+jzqdowSoOqSz>&5U-5+c{(c$7<=tKj%)-0G^jdn@~C0|m>0LV0ljks-!bF<{^NU7uJJIQ z4;V(m@AKC8&+?}c#}3yY>RDmvcC79JEfJsa3QaCgdNsIB&V2vSsu7oG_(omYicK^A zRMHiy-_X`bSZ$aQsvYOqkaA-dowIe>fS+imZ=Sw!{|9kxW&>~Xp-Jqe>fX2;3mTQB zH;|fPix+14lgc~`n-14csw;4&$3Zew!613j4rsC zdS%++qBlpVbLzG~IktD(v9W8&Q^BgXl`f?wSKPd@HL`Pk>(Gr$_9zRspa&QI6<}Zb mrT5Bjx5^f>$LYhDT3)Z%vaHMaAI+{)lc#j7*SoY;UH=0aaq}Gj literal 0 HcmV?d00001 From edd14a39fa689d56793367836b43030ba15129c0 Mon Sep 17 00:00:00 2001 From: Henry Baldwin Date: Fri, 9 Oct 2026 20:04:42 +0000 Subject: [PATCH 5/8] attestation: enforce extended key usage on endorsement certificates An extended key usage, if present, must allow any purpose or server authentication: the rule Google's reference verifier applies through Go's default cert.Verify options. The leaf's signature is now checked after its extensions, so a leaf restricted to another purpose is rejected for that. The tests build such leaves with rcgen. --- Cargo.lock | 2 + crates/attestation/Cargo.toml | 2 + crates/attestation/src/gcp/endorsement.rs | 84 ++++++++++++++++++++--- 3 files changed, 77 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f75b281..a069503 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -400,6 +400,7 @@ dependencies = [ "pccs", "pem-rfc7468 0.7.0", "prost", + "rcgen 0.14.7", "reqwest 0.13.4", "rsa", "rustls", @@ -412,6 +413,7 @@ dependencies = [ "tdx-attest 0.6.0", "tempfile", "thiserror 2.0.18", + "time", "tokio", "tracing", "tss-esapi", diff --git a/crates/attestation/Cargo.toml b/crates/attestation/Cargo.toml index 5028a74..39d5adb 100644 --- a/crates/attestation/Cargo.toml +++ b/crates/attestation/Cargo.toml @@ -58,6 +58,8 @@ tss-esapi = { version = "7.6.0", optional = true } [dev-dependencies] base64 = "0.22.1" +rcgen = { version = "0.14.7", features = ["x509-parser"] } +time = "0.3.47" mock-tdx = { workspace = true } tempfile = "3.23.0" rustls = { workspace = true, default-features = false, features = ["aws_lc_rs"] } diff --git a/crates/attestation/src/gcp/endorsement.rs b/crates/attestation/src/gcp/endorsement.rs index 8e0f506..d0b82f7 100644 --- a/crates/attestation/src/gcp/endorsement.rs +++ b/crates/attestation/src/gcp/endorsement.rs @@ -137,10 +137,12 @@ fn verify_endorsement_under_root( } /// The chain is one hop. The leaf must name the pinned root as its issuer, -/// carry the root's signature, be valid at `at` along with the root, and -/// carry no critical extension this check does not understand. Google -/// publishes no revocation source for these certificates, so none is -/// consulted. +/// be valid at `at` along with the root, carry no critical extension this +/// check does not understand, and carry the root's signature. An extended +/// key usage, if present, must allow any purpose or server authentication, +/// the same rule Google's reference verifier applies through Go's default +/// `cert.Verify` options. Google publishes no revocation source for these +/// certificates, so none is consulted. fn verify_leaf_under_root( leaf: &X509Certificate<'_>, root: &X509Certificate<'_>, @@ -152,15 +154,17 @@ fn verify_leaf_under_root( if !root.validity().is_valid_at(at) || !leaf.validity().is_valid_at(at) { return Err(GcpEndorsementError::CertNotValidAt); } - leaf.verify_signature(Some(root.public_key())).map_err(|_| GcpEndorsementError::CertChain)?; for extension in leaf.extensions() { match extension.parsed_extension() { ParsedExtension::KeyUsage(usage) if !usage.digital_signature() => { return Err(GcpEndorsementError::CertKeyUsage); } + ParsedExtension::ExtendedKeyUsage(usage) if !(usage.any || usage.server_auth) => { + return Err(GcpEndorsementError::CertExtendedKeyUsage); + } ParsedExtension::KeyUsage(_) | - ParsedExtension::BasicConstraints(_) | ParsedExtension::ExtendedKeyUsage(_) | + ParsedExtension::BasicConstraints(_) | ParsedExtension::SubjectKeyIdentifier(_) | ParsedExtension::AuthorityKeyIdentifier(_) | ParsedExtension::SubjectAlternativeName(_) => {} @@ -170,6 +174,7 @@ fn verify_leaf_under_root( _ => {} } } + leaf.verify_signature(Some(root.public_key())).map_err(|_| GcpEndorsementError::CertChain)?; Ok(()) } @@ -351,6 +356,8 @@ pub enum GcpEndorsementError { CertCriticalExtension(String), #[error("endorsement certificate is not for digital signatures")] CertKeyUsage, + #[error("endorsement certificate's extended key usage excludes this use")] + CertExtendedKeyUsage, #[error("endorsement public key: {0}")] Key(String), #[error("endorsement signature does not verify")] @@ -460,8 +467,32 @@ mod tests { )); } - /// The leaf's issuer name and signature are both checked against the - /// root the verifier pins, not whichever root the leaf names + /// A leaf issued under Google's root name, signed by a key that is not + /// the root's, with the given extended key usages + fn leaf_under_googles_name(purposes: &[rcgen::ExtendedKeyUsagePurpose]) -> Vec { + let signer = rcgen::KeyPair::generate().unwrap(); + let issuer = rcgen::Issuer::from_ca_cert_der( + &rustls::pki_types::CertificateDer::from(GCE_CC_TCB_ROOT_DER), + rcgen::KeyPair::generate().unwrap(), + ) + .unwrap(); + let mut params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + params.not_before = + ::time::OffsetDateTime::from_unix_timestamp(AT as i64 - 86_400).unwrap(); + params.not_after = ::time::OffsetDateTime::from_unix_timestamp(AT as i64 + 86_400).unwrap(); + params.key_usages = vec![rcgen::KeyUsagePurpose::DigitalSignature]; + params.extended_key_usages = purposes.to_vec(); + params.signed_by(&signer, &issuer).unwrap().der().to_vec() + } + + fn check_leaf(leaf_der: &[u8]) -> Result<(), GcpEndorsementError> { + let (_, root) = X509Certificate::from_der(GCE_CC_TCB_ROOT_DER).unwrap(); + let (_, leaf) = X509Certificate::from_der(leaf_der).unwrap(); + assert_eq!(leaf.issuer(), root.subject(), "the test leaf must carry the root's name"); + verify_leaf_under_root(&leaf, &root, ASN1Time::from_timestamp(AT as i64).unwrap()) + } + + /// A leaf is rejected on its issuer name before anything else #[test] fn a_certificate_under_another_root_is_rejected() { let (_, other_root) = x509_parser::pem::parse_x509_pem(include_bytes!( @@ -472,14 +503,45 @@ mod tests { verify_endorsement_under_root(ENDORSEMENT, &other_root.contents, mrtd(), AT), Err(GcpEndorsementError::CertChain) )); - let endorsement = VmLaunchEndorsement::decode(ENDORSEMENT).unwrap(); - let golden = VmGoldenMeasurement::decode(&*endorsement.serialized_uefi_golden).unwrap(); + } + + /// Google's name on the leaf is not enough: the root's key must have + /// signed it + #[test] + fn a_leaf_with_the_roots_name_but_another_signer_is_rejected() { + assert!(matches!( + check_leaf(&leaf_under_googles_name(&[])), + Err(GcpEndorsementError::CertChain) + )); + assert!(matches!( + check_leaf(&leaf_under_googles_name(&[rcgen::ExtendedKeyUsagePurpose::ServerAuth])), + Err(GcpEndorsementError::CertChain) + )); assert!(matches!( - verify_endorsement_under_root(ENDORSEMENT, &golden.cert, mrtd(), AT), + check_leaf(&leaf_under_googles_name(&[rcgen::ExtendedKeyUsagePurpose::Any])), Err(GcpEndorsementError::CertChain) )); } + /// An extended key usage that excludes this use is rejected before the + /// signature is looked at + #[test] + fn a_leaf_restricted_to_another_purpose_is_rejected() { + for purposes in [ + vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth], + vec![rcgen::ExtendedKeyUsagePurpose::CodeSigning], + vec![ + rcgen::ExtendedKeyUsagePurpose::ClientAuth, + rcgen::ExtendedKeyUsagePurpose::EmailProtection, + ], + ] { + assert!(matches!( + check_leaf(&leaf_under_googles_name(&purposes)), + Err(GcpEndorsementError::CertExtendedKeyUsage) + )); + } + } + #[test] fn the_pinned_root_is_the_published_one() { assert_eq!( From 2ae0b5cdbc7e57e66a90ffa01acd0f1e78455fcd Mon Sep 17 00:00:00 2001 From: Henry Baldwin Date: Fri, 9 Oct 2026 18:53:20 +0000 Subject: [PATCH 6/8] attestation: record Google's firmware endorsement in EndorsementSnapshot A live gcp-tdx verification reports the endorsement it verified next to the DCAP collateral it consumed, so an archive of the evidence carries what is needed to re-check the firmware later. The README documents the gcp-tdx checks. --- crates/attestation/README.md | 12 ++++++++++++ crates/attestation/src/azure/verify.rs | 2 +- crates/attestation/src/dcap.rs | 2 +- crates/attestation/src/lib.rs | 26 ++++++++++++++++++++------ 4 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/attestation/README.md b/crates/attestation/README.md index e0839c4..68e618c 100644 --- a/crates/attestation/README.md +++ b/crates/attestation/README.md @@ -171,6 +171,18 @@ used, the quote will fail to verify. For special cases where outdated TCB should be allowed, a custom override function can be passed when verifying which may modify collateral before it is validated against the TCB. +A `gcp-tdx` verification also establishes that the quote comes from Google's +fleet and from firmware Google built. The PCK certificate's PPID must appear in +Google's confidential-host registry, and the quote's MRTD must be named by the +`VMLaunchEndorsement` Google publishes for it, signed under the +`GCE-cc-tcb-root_1` certificate compiled in from +[`assets/GCE-cc-tcb-root_1.crt`](assets/GCE-cc-tcb-root_1.crt) (published at +`https://pki.goog/cloud_integrity/GCE-cc-tcb-root_1.crt`, SHA-256 +`e876bc6978bf4f3da445f98a0a82363c8c0bae5a1fc033c6df65846a6cb0f18c`). The +endorsement is fetched once per MRTD, verified at the verification instant, +recorded in the `EndorsementSnapshot`, and re-verified at that instant when +archived evidence is replayed. + ## Measurements File Accepted measurements for the remote party can be specified in a JSON file diff --git a/crates/attestation/src/azure/verify.rs b/crates/attestation/src/azure/verify.rs index 18f5a9d..37274f3 100644 --- a/crates/attestation/src/azure/verify.rs +++ b/crates/attestation/src/azure/verify.rs @@ -383,7 +383,7 @@ mod tests { let err = verify_azure_attestation_archived( input, [0; 64], - &EndorsementSnapshot { at: 0, dcap: None }, + &EndorsementSnapshot { at: 0, dcap: None, gcp_firmware: None }, false, ) .unwrap_err(); diff --git a/crates/attestation/src/dcap.rs b/crates/attestation/src/dcap.rs index 1707a16..6bfcb47 100644 --- a/crates/attestation/src/dcap.rs +++ b/crates/attestation/src/dcap.rs @@ -421,7 +421,7 @@ mod tests { /// fetch #[test] fn archived_without_collateral_is_refused() { - let endorsements = EndorsementSnapshot { at: 0, dcap: None }; + let endorsements = EndorsementSnapshot { at: 0, dcap: None, gcp_firmware: None }; let err = verify_dcap_attestation_archived(Vec::new(), [0; 64], &endorsements).unwrap_err(); diff --git a/crates/attestation/src/lib.rs b/crates/attestation/src/lib.rs index b9085d0..e88e5a9 100644 --- a/crates/attestation/src/lib.rs +++ b/crates/attestation/src/lib.rs @@ -25,7 +25,8 @@ pub use attest_types::{AttestationEvidence, PlatformMetadata}; /// Re-exported so callers can archive [EndorsementSnapshot::dcap] without /// depending on `dcap-qvl` directly pub use dcap_qvl::QuoteCollateralV3; -/// Google's endorsement of a GCP TDX quote's firmware +/// Google's endorsement of a GCP TDX quote's firmware, recorded in the +/// snapshot pub use gcp::{ GCE_CC_TCB_ROOT_DER, GCE_CC_TCB_ROOT_NAME, @@ -473,12 +474,22 @@ pub struct EndorsementSnapshot { /// evidence carried its own or the platform has no DCAP leg. The bundle /// consumed, not a second copy: a cache can refresh between two fetches pub dcap: Option, + /// `Some` when the verification required Google's endorsement of the + /// quote's firmware, which `gcp-tdx` evidence does; `None` elsewhere + pub gcp_firmware: Option, } impl EndorsementSnapshot { /// A verification that fetched one DCAP collateral bundle pub fn dcap(collateral: QuoteCollateralV3, at: u64) -> Self { - Self { at, dcap: Some(collateral) } + Self { at, dcap: Some(collateral), gcp_firmware: None } + } + + /// The same snapshot, also recording Google's endorsement of the + /// firmware + pub fn with_gcp_firmware(mut self, endorsement: GcpFirmwareEndorsement) -> Self { + self.gcp_firmware = Some(endorsement); + self } } @@ -781,7 +792,7 @@ impl AttestationVerifier { .attestation_evidence .as_ref() .ok_or(AttestationError::AttestationTypeNotAccepted)?; - let (verified, quote) = dcap::verify_dcap_attestation( + let (mut verified, quote) = dcap::verify_dcap_attestation( attestation_evidence.quote.clone(), expected_input_data, self.internal_pccs.clone(), @@ -789,12 +800,14 @@ impl AttestationVerifier { .await?; if attestation_type == AttestationType::GcpTdx { self.gcp_provenance_checker.verify_provenance(quote).await?; - self.gcp_endorsement_checker + let endorsement = self + .gcp_endorsement_checker .endorsement_for( dcap_mrtd(&verified.measurements)?, verified.endorsements.at, ) .await?; + verified.endorsements.gcp_firmware = Some(endorsement); } verified } @@ -958,7 +971,7 @@ impl AttestationVerifier { .attestation_evidence .as_ref() .ok_or(AttestationError::AttestationTypeNotAccepted)?; - let (verified, quote) = match archived { + let (mut verified, quote) = match archived { None => dcap::verify_dcap_attestation_sync( attestation_evidence.quote.clone(), expected_input_data, @@ -972,10 +985,11 @@ impl AttestationVerifier { }; if attestation_type == AttestationType::GcpTdx { self.gcp_provenance_checker.verify_provenance_sync("e)?; - self.gcp_endorsement_checker.endorsement_for_sync( + let endorsement = self.gcp_endorsement_checker.endorsement_for_sync( dcap_mrtd(&verified.measurements)?, verified.endorsements.at, )?; + verified.endorsements.gcp_firmware = Some(endorsement); } verified } From 0b630dde1a3a5c974aa85b8b07f7dcf9ee32ea30 Mon Sep 17 00:00:00 2001 From: Henry Baldwin Date: Fri, 9 Oct 2026 20:51:59 +0000 Subject: [PATCH 7/8] attestation: replay archived gcp-tdx evidence against its recorded endorsement Upstream refuses archived verification of GCP evidence (https://github.com/flashbots/attested-tls/commit/a2898b9b62489c17f80224fc22071dcde5c7cd86) for two reasons: the replay fetched Google's firmware endorsement, whose certificate is checked against the wall clock, and the provenance registry is unsigned and mutable. The recorded endorsement answers the first. A replay re-verifies it at the snapshot's instant instead of fetching one, and a snapshot without one fails with GcpEndorsementError::NotArchived. Nothing answers the second: a replay skips the provenance lookup and trusts the original verification for it. That is acceptable for re-verifying our own founding archives, so this fork reverts the refusal. It stays fork-only until provenance has a replayable answer. The tests replay the crate's own GCP fixture with the endorsement Google publishes for it, and a real GCP founding, and refuse a missing, tampered or mismatched endorsement. --- crates/attestation/README.md | 5 +- crates/attestation/src/gcp/endorsement.rs | 2 + crates/attestation/src/lib.rs | 93 +++++++--- ...ement-gcp-tdx-1782809233226668671.binarypb | Bin 0 -> 5308 bytes .../gcp-tdx-founding-1790873673.json | 32 ++++ crates/attestation/tests/gcp_archive.rs | 166 ++++++++++++++++++ 6 files changed, 272 insertions(+), 26 deletions(-) create mode 100644 crates/attestation/test-assets/gce-endorsement-gcp-tdx-1782809233226668671.binarypb create mode 100644 crates/attestation/test-assets/gcp-tdx-founding-1790873673.json create mode 100644 crates/attestation/tests/gcp_archive.rs diff --git a/crates/attestation/README.md b/crates/attestation/README.md index 68e618c..529ff99 100644 --- a/crates/attestation/README.md +++ b/crates/attestation/README.md @@ -30,8 +30,9 @@ a node replaying a log whose state depended on that verdict, or a third party re-checking published evidence without trusting whoever verified it first. It says whether the evidence was valid when first verified, not whether the platform is trustworthy now: collateral that has since expired or been revoked -still passes. GCP evidence is not supported: its provenance registry is -unsigned and mutable, so a replay cannot reproduce that check. +still passes. GCP evidence is re-checked against the firmware endorsement +recorded in the snapshot, while the provenance lookup is skipped: Google's +registry is unsigned and mutable, and the original verification consulted it. Matched expected measurements can be transported in an HTTP header using `ExpectedMeasurements::to_header_format` and reconstructed with diff --git a/crates/attestation/src/gcp/endorsement.rs b/crates/attestation/src/gcp/endorsement.rs index d0b82f7..edd34d8 100644 --- a/crates/attestation/src/gcp/endorsement.rs +++ b/crates/attestation/src/gcp/endorsement.rs @@ -366,6 +366,8 @@ pub enum GcpEndorsementError { NoTdx, #[error("endorsement does not name MRTD {0}")] MrtdNotEndorsed(String), + #[error("archived snapshot carries no firmware endorsement")] + NotArchived, #[error("endorsement cache lock: {0}")] CacheLock(String), #[error("blocking task join: {0}")] diff --git a/crates/attestation/src/lib.rs b/crates/attestation/src/lib.rs index e88e5a9..54d4b04 100644 --- a/crates/attestation/src/lib.rs +++ b/crates/attestation/src/lib.rs @@ -884,14 +884,23 @@ impl AttestationVerifier { /// attests to it, so a caller replaying someone else's archive should /// know what pins it. /// - /// Nothing is fetched. GCP evidence is refused: its provenance registry - /// is unsigned and mutable, so a replay cannot reproduce that check. + /// Nothing whose answer can change over time is fetched. On GCP the + /// recorded firmware endorsement is re-verified at the snapshot's + /// instant, and a snapshot without one fails with + /// [`GcpEndorsementError::NotArchived`]. The provenance lookup against + /// Google's PPID registry is skipped: the registry is unsigned and + /// mutable, so a replay could only learn what it says today, and the + /// original verification already consulted it. Firmware for a + /// portable-image policy is still fetched on a cache miss, since it is + /// signed and content-addressed by the quote's MRTD, so the fetch + /// cannot change the verdict. Recording the provenance outcome and the + /// firmware in the snapshot would remove these caveats and is left for + /// a later change. /// /// Fails with /// [`AttestationError::ArchivedWithDynamicMeasurementPolicy`] - /// on a verifier with a dynamic measurement policy, with - /// [`AttestationError::ArchivedGcpNotSupported`] on GCP evidence, and - /// with [`DcapVerificationError::ArchivedWithoutDcapCollateral`] on a + /// on a verifier with a dynamic measurement policy, and with + /// [`DcapVerificationError::ArchivedWithoutDcapCollateral`] on a /// snapshot with no DCAP bundle. pub fn verify_attestation_archived( &self, @@ -902,9 +911,6 @@ impl AttestationVerifier { if self.dynamic_measurement_policy.is_some() { return Err(AttestationError::ArchivedWithDynamicMeasurementPolicy); } - if attestation_exchange_message.attestation_type() == AttestationType::GcpTdx { - return Err(AttestationError::ArchivedGcpNotSupported); - } self.verify_attestation_blocking( attestation_exchange_message, expected_input_data, @@ -914,7 +920,8 @@ impl AttestationVerifier { /// The body shared by [`Self::verify_attestation_sync`] and /// [`Self::verify_attestation_archived`], which differ only in where - /// the DCAP leg gets its endorsements + /// the DCAP and GCP firmware legs get their endorsements and whether + /// the GCP provenance lookup runs fn verify_attestation_blocking( &self, attestation_exchange_message: AttestationExchangeMessage, @@ -984,12 +991,21 @@ impl AttestationVerifier { )?, }; if attestation_type == AttestationType::GcpTdx { - self.gcp_provenance_checker.verify_provenance_sync("e)?; - let endorsement = self.gcp_endorsement_checker.endorsement_for_sync( - dcap_mrtd(&verified.measurements)?, - verified.endorsements.at, - )?; - verified.endorsements.gcp_firmware = Some(endorsement); + verified.endorsements.gcp_firmware = match archived { + // The registry is unsigned and mutable: a replay + // could only learn what it says now, so only a live + // verification asks + None => { + self.gcp_provenance_checker.verify_provenance_sync("e)?; + Some(self.gcp_endorsement_checker.endorsement_for_sync( + dcap_mrtd(&verified.measurements)?, + verified.endorsements.at, + )?) + } + Some(endorsements) => { + archived_gcp_firmware_endorsement(&verified, endorsements)? + } + }; } verified } @@ -1306,6 +1322,25 @@ fn dcap_mrtd(measurements: &MultiMeasurements) -> Result<[u8; 48], AttestationEr } } +/// The firmware endorsement a GCP replay was archived with, verified at the +/// snapshot's instant +fn archived_gcp_firmware_endorsement( + verified: &VerifiedAttestation, + endorsements: &EndorsementSnapshot, +) -> Result, AttestationError> { + let mrtd = dcap_mrtd(&verified.measurements)?; + // A quote minted by mock_tdx names firmware Google never endorsed, so a + // mock replay carries whatever endorsement it was given, as its DCAP + // leg carries mock collateral + #[cfg(any(test, feature = "mock"))] + if mrtd == mock_tdx::MOCK_MRTD { + return Ok(endorsements.gcp_firmware.clone()); + } + let endorsement = endorsements.gcp_firmware.clone().ok_or(GcpEndorsementError::NotArchived)?; + endorsement.verify(mrtd, endorsements.at)?; + Ok(Some(endorsement)) +} + /// An error when generating or verifying an attestation #[derive(Error, Debug)] pub enum AttestationError { @@ -1357,8 +1392,6 @@ pub enum AttestationError { PlatformMetadata(#[from] PlatformError), #[error("Archived verification cannot use a dynamic measurement policy")] ArchivedWithDynamicMeasurementPolicy, - #[error("Archived verification of GCP evidence is not supported")] - ArchivedGcpNotSupported, } #[cfg(test)] @@ -1515,10 +1548,11 @@ mod tests { assert!(matches!(err, AttestationError::ArchivedWithDynamicMeasurementPolicy), "{err:?}"); } - /// A replay cannot reproduce GCP's provenance check, so GCP evidence is - /// refused rather than verified as plain DCAP + /// A replay of GCP evidence does not consult the provenance registry. + /// A mock PPID is not in Google's registry, so were the lookup to run + /// it would fail closed #[test] - fn archived_gcp_replay_is_refused() { + fn archived_gcp_replay_skips_the_provenance_lookup() { let input_data = [7u8; 64]; let quote = dcap::create_dcap_attestation(input_data).unwrap(); let attestation_evidence = AttestationEvidence { @@ -1529,11 +1563,22 @@ mod tests { let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); let endorsements = EndorsementSnapshot::dcap(mock_tdx::mock_collateral(), now); - let err = verifier - .verify_attestation_archived(attestation_evidence.into(), input_data, &endorsements) - .unwrap_err(); + let replayed = verifier.verify_attestation_archived( + attestation_evidence.into(), + input_data, + &endorsements, + ); - assert!(matches!(err, AttestationError::ArchivedGcpNotSupported), "{err:?}"); + assert!( + matches!( + replayed, + Ok(Some(VerifiedAttestation { + expected_measurements: Some(ExpectedMeasurements::Dcap(_)), + .. + })) + ), + "expected archived GCP replay to pass the policy check: {replayed:?}" + ); } /// On the fetching path, the reported bundle is the one the fetch diff --git a/crates/attestation/test-assets/gce-endorsement-gcp-tdx-1782809233226668671.binarypb b/crates/attestation/test-assets/gce-endorsement-gcp-tdx-1782809233226668671.binarypb new file mode 100644 index 0000000000000000000000000000000000000000..98fca1512da3ca6255f7580be81fc6d7ed781e5a GIT binary patch literal 5308 zcmcgvXH-;Yw`KqV2M`36SP<-Gf^(+N=ogc7X3or<>Ah(brf{bBiWmW7*I3aQyV$Uz zL`6*$G-3(XSfZe!qR}X^VL?Uj5Z8C__uYGc-gVDf?~lFT{ha;ockky}=V12@!KNg= zc+q?|A^p;t=F_q1SF4_FiyOEm1t?4C3zWs3TN@XPiH*f%17Jeek<+=;U#DU)Sb)4X z4Mj(7tuZX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("../test-assets/gcp-tdx-1782809233226668671").to_vec(); + let platform = PlatformMetadata { + attestation_type: AttestationType::GcpTdx.try_into().unwrap(), + ram_bytes: 0, + num_disks: 0, + acpi: None, + dm_verity_boot: false, + smbios_handoff: None, + }; + Fixture { + at: 1_782_809_233, + evidence: AttestationEvidence { quote, platform }.into(), + dcap_collateral: serde_saphyr::from_slice(include_bytes!( + "../test-assets/gcp-tdx-collateral-1782809233226668671.yaml" + )) + .unwrap(), + endorsement: GcpFirmwareEndorsement::new( + include_bytes!("../test-assets/gce-endorsement-gcp-tdx-1782809233226668671.binarypb") + .to_vec(), + ), + } +} + +/// One founder's harvest on a c3-standard-4 guest, 2026-10-01, as its +/// verifier archived it +fn founding_fixture() -> Fixture { + #[derive(serde::Deserialize)] + struct Founding { + at: u64, + evidence: AttestationExchangeMessage, + dcap_collateral: QuoteCollateralV3, + gcp_firmware_endorsement: String, + } + let founding: Founding = + serde_json::from_str(include_str!("../test-assets/gcp-tdx-founding-1790873673.json")) + .unwrap(); + Fixture { + at: founding.at, + evidence: founding.evidence, + dcap_collateral: founding.dcap_collateral, + endorsement: GcpFirmwareEndorsement::new( + hex::decode(founding.gcp_firmware_endorsement).unwrap(), + ), + } +} + +fn fixtures() -> [Fixture; 2] { + [portable_fixture(), founding_fixture()] +} + +/// The binding the evidence carries, read back from the quote +fn report_data(evidence: &AttestationExchangeMessage) -> [u8; 64] { + let quote = &evidence.attestation_evidence.as_ref().unwrap().quote; + dcap_qvl::quote::Quote::parse(quote).unwrap().report.as_td10().unwrap().report_data +} + +fn verifier() -> AttestationVerifier { + let policy = + MeasurementPolicy::from_json_bytes(br#"[{"attestation_type": "gcp-tdx"}]"#.to_vec()) + .unwrap(); + AttestationVerifier::builder(policy).build() +} + +fn replay( + fixture: &Fixture, + endorsement: Option, +) -> Result, AttestationError> { + let mut endorsements = EndorsementSnapshot::dcap(fixture.dcap_collateral.clone(), fixture.at); + if let Some(endorsement) = endorsement { + endorsements = endorsements.with_gcp_firmware(endorsement); + } + verifier().verify_attestation_archived( + fixture.evidence.clone(), + report_data(&fixture.evidence), + &endorsements, + ) +} + +#[test] +fn a_gcp_archive_replays_with_its_recorded_endorsement() { + for fixture in fixtures() { + let replayed = replay(&fixture, Some(fixture.endorsement.clone())) + .unwrap() + .expect("the fixture carries an attestation"); + assert_eq!(replayed.endorsements.at, fixture.at); + assert_eq!(replayed.endorsements.gcp_firmware, Some(fixture.endorsement)); + } +} + +#[test] +fn a_gcp_archive_without_an_endorsement_is_refused() { + for fixture in fixtures() { + let replayed = replay(&fixture, None); + assert!( + matches!( + replayed, + Err(AttestationError::GcpFirmwareEndorsement(GcpEndorsementError::NotArchived)) + ), + "{replayed:?}" + ); + } +} + +#[test] +fn a_gcp_archive_with_a_tampered_endorsement_is_refused() { + for fixture in fixtures() { + let mut tampered = fixture.endorsement.clone().into_bytes(); + let last = tampered.len() - 1; + tampered[last] ^= 1; + let replayed = replay(&fixture, Some(GcpFirmwareEndorsement::new(tampered))); + assert!( + matches!( + replayed, + Err(AttestationError::GcpFirmwareEndorsement(GcpEndorsementError::Signature)) + ), + "{replayed:?}" + ); + } +} + +/// Each fixture's endorsement names its own firmware and not the other's +#[test] +fn an_endorsement_for_another_firmware_is_refused() { + let [portable, founding] = fixtures(); + for (fixture, other) in [(&portable, &founding), (&founding, &portable)] { + let replayed = replay(fixture, Some(other.endorsement.clone())); + assert!( + matches!( + replayed, + Err(AttestationError::GcpFirmwareEndorsement( + GcpEndorsementError::MrtdNotEndorsed(_) + )) + ), + "{replayed:?}" + ); + } +} From 16d333c96564481f4fbeb6958124f8ced53209fe Mon Sep 17 00:00:00 2001 From: Henry Baldwin Date: Fri, 9 Oct 2026 20:04:42 +0000 Subject: [PATCH 8/8] attestation: let verifiers share one endorsement cache The enclave builds a verifier per call, so each would fetch its own copy of an endorsement. GcpEndorsementChecker becomes public, and AttestationVerifierBuilder::with_gcp_endorsement_checker shares one between verifiers. Entries are keyed by MRTD and re-verified at every use. --- crates/attestation/src/gcp/endorsement.rs | 10 ++++++---- crates/attestation/src/gcp/mod.rs | 2 +- crates/attestation/src/lib.rs | 16 ++++++++++++++-- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/crates/attestation/src/gcp/endorsement.rs b/crates/attestation/src/gcp/endorsement.rs index edd34d8..12fddfa 100644 --- a/crates/attestation/src/gcp/endorsement.rs +++ b/crates/attestation/src/gcp/endorsement.rs @@ -180,14 +180,16 @@ fn verify_leaf_under_root( /// Fetches and verifies Google's endorsement for an MRTD, keeping one /// verified copy per MRTD until it stops verifying -#[derive(Clone, Debug)] -pub(crate) struct GcpEndorsementChecker { +#[derive(Clone, Debug, Default)] +pub struct GcpEndorsementChecker { endorsements: Arc>>>, } impl GcpEndorsementChecker { - pub(crate) fn new() -> Self { - Self { endorsements: Default::default() } + /// An empty cache; clones share it, so one checker can serve many + /// verifiers + pub fn new() -> Self { + Self::default() } /// Google's endorsement of `mrtd`, verified at `at` (Unix seconds); the diff --git a/crates/attestation/src/gcp/mod.rs b/crates/attestation/src/gcp/mod.rs index 84dc8ca..16f9d98 100644 --- a/crates/attestation/src/gcp/mod.rs +++ b/crates/attestation/src/gcp/mod.rs @@ -3,10 +3,10 @@ mod endorsement; mod firmware; mod provenance; -pub(crate) use endorsement::GcpEndorsementChecker; pub use endorsement::{ GCE_CC_TCB_ROOT_DER, GCE_CC_TCB_ROOT_NAME, + GcpEndorsementChecker, GcpEndorsementError, GcpFirmwareEndorsement, }; diff --git a/crates/attestation/src/lib.rs b/crates/attestation/src/lib.rs index 54d4b04..120afb0 100644 --- a/crates/attestation/src/lib.rs +++ b/crates/attestation/src/lib.rs @@ -30,6 +30,7 @@ pub use dcap_qvl::QuoteCollateralV3; pub use gcp::{ GCE_CC_TCB_ROOT_DER, GCE_CC_TCB_ROOT_NAME, + GcpEndorsementChecker, GcpEndorsementError, GcpFirmwareEndorsement, }; @@ -45,7 +46,7 @@ use tokio::time::sleep; use crate::{ dcap::DcapVerificationError, - gcp::{GcpEndorsementChecker, GcpFirmwareCache, GcpProvenanceChecker, GcpProvenanceError}, + gcp::{GcpFirmwareCache, GcpProvenanceChecker, GcpProvenanceError}, measurements::{MeasurementFormatError, MeasurementPolicy}, }; @@ -570,6 +571,9 @@ pub struct AttestationVerifierBuilder { dump_dcap_quotes: bool, /// Whether to override outdated TCB when on Azure override_azure_outdated_tcb: bool, + /// A cache of Google's firmware endorsements to share with other + /// verifiers + gcp_endorsement_checker: Option, } impl AttestationVerifierBuilder { @@ -583,7 +587,7 @@ impl AttestationVerifierBuilder { internal_pccs: Pccs::new(self.collateral_source, self.cache_policy), known_gcp_firmware: GcpFirmwareCache::new(), gcp_provenance_checker: GcpProvenanceChecker::new(), - gcp_endorsement_checker: GcpEndorsementChecker::new(), + gcp_endorsement_checker: self.gcp_endorsement_checker.unwrap_or_default(), dynamic_measurement_policy: self.dynamic_measurement_policy, }; @@ -591,6 +595,13 @@ impl AttestationVerifierBuilder { verifier } + /// Share one cache of Google's firmware endorsements between verifiers; + /// entries are keyed by MRTD and re-verified at every use + pub fn with_gcp_endorsement_checker(mut self, checker: GcpEndorsementChecker) -> Self { + self.gcp_endorsement_checker = Some(checker); + self + } + /// Whether to write quotes to files on disk pub fn with_dump_dcap_quotes(mut self, dump_dcap_quotes: bool) -> Self { self.dump_dcap_quotes = dump_dcap_quotes; @@ -656,6 +667,7 @@ impl AttestationVerifier { cache_policy: CachePolicy::Passthrough, dump_dcap_quotes: false, override_azure_outdated_tcb: false, + gcp_endorsement_checker: None, dynamic_measurement_policy: None, } }