From 38711fde7bfbc3a742e344dae525961db58350d7 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:50:28 +0000 Subject: [PATCH 1/6] bootstrap: reboot after a GPT rewrite, then derive; bind PCR5 The firmware measures the GPT the boot started with (PCR5; PCR2 on GCE TDX, together with stage0's Authenticode). The data key was derived before ensure_partitions() rewrote it, so on TDX, where PCR2 must stay bound, the key moved at the first reboot and /data was lost once. - ensure_partitions() returns whether it wrote the GPT; a rewrite is read back from the device (BLKFLSBUF first) and must show p3 ending at the last usable LBA, else fail closed rather than reboot into the same rewrite. - bootstrap: after a GPT write, sync and reboot before deriving anything; the key is derived after ensure_partitions(). - DATA_KEY_PCRS binds PCR5 (all but PCR10). Growing the volume changes the key: /data is reinitialized. - PCR-BINDING.md: 2026-11-14 resolution. Tested: make ci; selftest x86_64 + aarch64 (pivot, grow); GCP pivot reboot test on n2d SEV-SNP and c3 TDX: /data survives the post-provisioning reboot. Co-Authored-By: Claude Opus 5.5 --- PCR-BINDING.md | 46 +++++++++++++++++++++++++++++------- crates/blockdev/src/lib.rs | 46 ++++++++++++++++++++++++++++++++---- crates/bootstrap/src/main.rs | 31 ++++++++++++++++++++---- crates/tpm-derive/src/lib.rs | 28 ++++++++++++---------- 4 files changed, 122 insertions(+), 29 deletions(-) diff --git a/PCR-BINDING.md b/PCR-BINDING.md index bee37ab..1886767 100644 --- a/PCR-BINDING.md +++ b/PCR-BINDING.md @@ -28,14 +28,15 @@ specific, documented reason. ## Current bound PCR set -`DISK_KEY_PCRS` in `crates/tpm-derive/src/lib.rs`: +`DATA_KEY_PCRS` in `crates/tpm-derive/src/lib.rs`: -> **Every PCR 0–23 except PCR5 and PCR10.** +> **Every PCR 0–23 except PCR10.** -i.e. `{0,1,2,3,4, 6,7,8,9, 11,12,13,14,15,16,17,18,19,20,21,22,23}`. PCR15 additionally -carries the workload measurement (below). Two PCRs are excluded, each for a reason: +i.e. `{0,1,2,3,4,5,6,7,8,9, 11,12,13,14,15,16,17,18,19,20,21,22,23}`. PCR15 additionally +carries the workload measurement (below). PCR5 has been bound since 2026-11-14 (resolution +below); PCR10 is excluded. -### PCR5 — excluded (GPT / boot-manager config-and-data) +### PCR5 — bound since 2026-11-14 (GPT); excluded before PCR5 measures the **GPT partition table** (UEFI `EV_EFI_GPT_EVENT`). Confirmed against EDK2 source: `SecurityPkg/Library/DxeTpm2MeasureBootLib/DxeTpm2MeasureBootLib.c`, @@ -46,8 +47,10 @@ stock OVMF, PCR5 is GPT-only. `bootstrap` **rewrites the GPT at runtime** on first boot (adds the runtime `p2` + data `p3` partitions into the grown volume). That changes the measured GPT, so PCR5 differs on -the *next* boot. Binding it would rebind the disk key on every partition create/grow and -wipe the data. → excluded. +the *next* boot. Until 2026-11-14 the key was derived before that rewrite, so binding PCR5 +would have moved the key at the first reboot → it was excluded. Now `bootstrap` reboots +after any GPT rewrite, before deriving the key (resolution below), so the key only ever +binds the final layout's GPT and PCR5 is bound. Caveat — **Nitro ≠ OVMF here.** AWS's Nitro TPM PCR profile *defines* PCR5 as *"Boot Manager Code Configuration and Data **and** GPT Partition Table"* (Nitro runs OVMF + AWS @@ -180,7 +183,34 @@ the cmdline** (only `lockdown=confidentiality`): stage0) + dm-verity (runtime partition). Attestation lives in PCR10, but our own chain is measured into **PCR14** and the workload into **PCR15** — we don't consume PCR10. -## Resolution (2026-07-11) +## Resolution (2026-11-14): grow, reboot, then derive; PCR5 bound + +On GCE TDX the firmware logs the GPT into **PCR2**, together with stage0's own Authenticode +hash (workspace `tools/pcr-replay/platforms/gcp/README.md`). PCR2 can't be excluded there +without losing stage0's identity from the key, so excluding PCR5 no longer kept the GPT out +of the key: on TDX the key moved at the first reboot and `/data` was lost once (GCP reboot +test, 2026-11-10). + +The fix is the same on every platform: if `ensure_partitions()` wrote the GPT this boot, +`bootstrap` syncs and reboots before deriving anything from the PCRs. The next boot finds +p3 filling the device, writes nothing, and derives the key from the final layout. A rewrite +is read back from the device (buffer cache dropped) and must show p3 ending at the last +usable LBA, or the boot fails closed instead of rebooting into the same rewrite. + +- The key binds the GPT everywhere, so **PCR5 is bound** (only PCR10 is excluded). +- First boot costs one extra boot; nothing written to `/data` is lost. +- **Growing the volume changes the key**: grow, reboot, `/data` reinitialized (fail + closed). Accepted: the disk layout is part of the measured state. +- Verifiers reproduce the rewritten GPT's measurement from the GPT digests the attestation + carries (lockboot/vaportpm#12), not from release artifacts. +- Rejected: binding stage0's identity through PCR7 and excluding PCR2. stage0's Secure Boot + keys are minted per build and discarded, but that guarantee rests on a deletion nobody can + demonstrate, not on a measurement. + +The Nitro caveat under PCR5 above still applies (O3 in the workspace's +`PLAN-GPT-MEASUREMENT.md`): confirm PCR5's contents on EC2 before relying on it there. + +## Resolution (2026-07-11, superseded for PCR5) **Bind every PCR except {5, 10}; both settled.** PCR5 is the runtime-mutated GPT; PCR10 is redundant for us (its boot aggregate = hash(PCR0–9), whose inputs we bind individually minus diff --git a/crates/blockdev/src/lib.rs b/crates/blockdev/src/lib.rs index 1642875..1d206f4 100644 --- a/crates/blockdev/src/lib.rs +++ b/crates/blockdev/src/lib.rs @@ -154,8 +154,12 @@ fn hex(bytes: &[u8]) -> String { /// the partitions on first boot and *grows* p3 into a larger volume later — p3's start /// never moves (p2 is fixed), so extending only its end preserves the encrypted data. /// Refuses to shrink. Rebuilds the GPT preserving the ESP at its exact extent (a table -/// rewrite doesn't touch partition contents). Returns `(runtime_path, data_path)`. -pub fn ensure_partitions(device: &Path, runtime_lbas: u64) -> Result<(PathBuf, PathBuf)> { +/// rewrite doesn't touch partition contents). Returns `(runtime_path, data_path, wrote)`: +/// `wrote` is true when the GPT was rewritten, which the firmware measures on the next boot +/// (the caller reboots before deriving anything from the PCRs). A rewrite is read back from +/// the device, bypassing the buffer cache, and must show p3 ending at the last usable LBA, so +/// a write that didn't persist fails here instead of rebooting into the same rewrite again. +pub fn ensure_partitions(device: &Path, runtime_lbas: u64) -> Result<(PathBuf, PathBuf, bool)> { let runtime_lbas = align_up(runtime_lbas, ALIGN_LBA); let esp_type = Uuid::parse_str(ESP_TYPE_GUID).unwrap(); let data_type = Uuid::parse_str(DATA_TYPE_GUID).unwrap(); @@ -210,7 +214,7 @@ pub fn ensure_partitions(device: &Path, runtime_lbas: u64) -> Result<(PathBuf, P } if dl == last_usable { // Already fills the device — leave the GPT untouched (kernel already has it). - return Ok((part_path(device, 2), part_path(device, 3))); + return Ok((part_path(device, 2), part_path(device, 3), false)); } // dl < last_usable → grow p3 (fall through to rebuild). } @@ -247,7 +251,41 @@ pub fn ensure_partitions(device: &Path, runtime_lbas: u64) -> Result<(PathBuf, P dev.sync_all().context("flush GPT to disk")?; reread_partition_table(device)?; - Ok((part_path(device, 2), part_path(device, 3))) + verify_data_fills(device, last_usable)?; + Ok((part_path(device, 2), part_path(device, 3), true)) +} + +/// Read the GPT back from the device itself (buffer cache dropped first) and check that the +/// data partition ends at `last_usable`, i.e. that the rewrite persisted. +fn verify_data_fills(device: &Path, last_usable: u64) -> Result<()> { + let f = OpenOptions::new() + .read(true) + .write(true) + .open(device) + .with_context(|| format!("open {} for BLKFLSBUF", device.display()))?; + const BLKFLSBUF: libc::c_ulong = 0x1261; // _IO(0x12, 97) + // SAFETY: valid fd; BLKFLSBUF takes no argument. + if unsafe { libc::ioctl(f.as_raw_fd(), BLKFLSBUF as _, 0) } < 0 { + return Err(std::io::Error::last_os_error()).context("BLKFLSBUF"); + } + drop(f); + let data_type = Uuid::parse_str(DATA_TYPE_GUID).unwrap(); + let disk = GptConfig::new() + .writable(false) + .open(device) + .with_context(|| format!("re-read GPT on {}", device.display()))?; + let data_last = disk + .partitions() + .values() + .find(|p| p.part_type_guid.guid == data_type) + .map(|p| p.last_lba); + if data_last != Some(last_usable) { + bail!( + "GPT rewrite did not persist on {}: data partition ends at {data_last:?}, expected {last_usable}", + device.display() + ); + } + Ok(()) } /// Force the kernel to re-read the partition table (`BLKRRPART`) so new partitions diff --git a/crates/bootstrap/src/main.rs b/crates/bootstrap/src/main.rs index dbfb216..1ac47e7 100644 --- a/crates/bootstrap/src/main.rs +++ b/crates/bootstrap/src/main.rs @@ -50,15 +50,23 @@ fn run() -> Result<()> { // SAFETY: fd 0 is a seekable memfd (stage1's model); rewind it for the downstream /init. unsafe { libc::lseek(0, 0, libc::SEEK_SET) }; - // XTS data key, bound to PCR14 (code+rootfs) + PCR15 (config) + the rest. - let key = tpm_derive::derive_data_key().context("derive data key")?; - // Partitions on the boot device. let device = blockdev::find_boot_device().context("find boot device")?; - let (runtime_part, data_part) = + let (runtime_part, data_part, wrote_gpt) = blockdev::ensure_partitions(&device, runtime_lbas(payload.rootfs_erofs.len())) .context("ensure partitions")?; + // The firmware measured the GPT this boot started with (PCR5; PCR2 on GCE TDX), and the data + // key binds it. If we just rewrote it (first boot, or a grown volume), reboot so the key is + // only ever derived from the final layout's measurement. The next boot finds p3 filling the + // device and writes nothing. A grown volume therefore gets a new key: /data is reinitialized. + if wrote_gpt { + provisioning_reboot(); + } + + // XTS data key, bound to PCR14 (code+rootfs) + PCR15 (config) + the rest. + let key = tpm_derive::derive_data_key().context("derive data key")?; + // Verity runtime (ro) = the overlay lower; flush-if-mismatch. let rt = blockdev::RuntimeImage { blob: &payload.rootfs_erofs, @@ -118,6 +126,21 @@ fn run() -> Result<()> { pivot::switch_root_exec(NEWROOT, INIT) } +/// Reboot after a GPT rewrite, before anything is derived from the PCRs. If the kernel refuses, +/// return to `fatal_halt` rather than continue on a measurement that no longer matches the disk. +fn provisioning_reboot() -> ! { + eprintln!("loader: GPT rewritten -> rebooting so the firmware measures the final layout"); + // SAFETY: PID 1; flush, then restart. reboot() only returns on failure. + unsafe { + libc::sync(); + libc::reboot(libc::LINUX_REBOOT_CMD_RESTART); + } + fatal_halt(anyhow::anyhow!( + "provisioning reboot failed: {}", + std::io::Error::last_os_error() + )) +} + /// Fatal boot error handler for PID 1. Log the error, give a 60 s grace window for console/serial /// capture, then issue a clean ACPI power-off so a failed instance *stops* rather than spinning a /// vCPU on a kernel panic (or looping via `panic=`-reboot). Never returns. In the QEMU harness the diff --git a/crates/tpm-derive/src/lib.rs b/crates/tpm-derive/src/lib.rs index 16b6743..e9cfbb3 100644 --- a/crates/tpm-derive/src/lib.rs +++ b/crates/tpm-derive/src/lib.rs @@ -34,22 +34,24 @@ pub fn extend_config_pcr(digest: &[u8; 32]) -> Result<()> { .context("extend PCR15 with config digest") } -/// PCRs the data key is bound to: **every PCR except PCR5 and PCR10** — bind broadly by default +/// PCRs the data key is bound to: **every PCR except PCR10** — bind broadly by default /// (per-instance keys make it free; values differ per instance/vendor), so any real change to -/// firmware/boot/policy/payload wipes. The two exclusions are settled, each measured elsewhere or -/// otherwise not additive for us — see PCR-BINDING.md for the full analysis: +/// firmware/boot/policy/payload wipes. See PCR-BINDING.md for the full analysis. /// -/// - **PCR5 (GPT):** the loader rewrites the GPT at runtime (adds p2/p3), so it changes across the -/// first reboot. (On Nitro its profile is even broader than the GPT.) -/// - **PCR10 (IMA):** redundant, not a loss. It carries the IMA *boot aggregate* = hash(PCR0-9) — -/// inputs we already bind individually (0-4,6,7,8,9), minus the deliberately-excluded PCR5 — -/// plus module measurements, which are already covered by the UKI measurement in **PCR14** (all -/// modules ship in the measured initramfs). We never use IMA appraisal (`security.ima` xattrs). -/// And `CONFIG_IMA=y` in the prebuilt Fedora kernel extends PCR10 with the boot aggregate -/// unconditionally, so it couldn't be suppressed short of recompiling the kernel anyway. +/// - **PCR5 (GPT) is bound:** the loader rewrites the GPT only on a first boot or a grown volume, +/// and reboots before deriving this key, so the key always binds the final layout's +/// measurement. On GCE TDX the firmware logs the GPT into PCR2 (with stage0's Authenticode) +/// instead; the same rule covers it. Growing the volume therefore changes the key: `/data` is +/// reinitialized. +/// - **PCR10 (IMA) is excluded:** redundant, not a loss. It carries the IMA *boot aggregate* = +/// hash(PCR0-9), inputs we already bind individually, plus module measurements, which are +/// already covered by the UKI measurement in **PCR14** (all modules ship in the measured +/// initramfs). We never use IMA appraisal (`security.ima` xattrs). And `CONFIG_IMA=y` in the +/// prebuilt Fedora kernel extends PCR10 with the boot aggregate unconditionally, so it couldn't +/// be suppressed short of recompiling the kernel anyway. const DATA_KEY_PCRS: &[u8] = &[ - 0, 1, 2, 3, 4, /* 5 excluded (GPT) */ 6, 7, 8, 9, /* 10 excluded (IMA) */ 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 excluded (IMA) */ 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, ]; /// Namespace for the `/data` encryption key on this TPM. From 36045008d2ee79c27cf0b278cf42d9a5ac3b3f65 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:56:27 +0000 Subject: [PATCH 2/6] Makefile: update-vaportpm target Re-resolves only Cargo.lock's vaportpm-attest entry after bumping the rev in crates/tpm-derive/Cargo.toml (builds are --locked; `make lock` re-resolves every dependency). Same target as stage1's. Used by the vaportpm repin step in workspace RELEASING.md. Co-Authored-By: Claude Opus 5.5 --- Makefile | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Makefile b/Makefile index d20c712..bda12f4 100644 --- a/Makefile +++ b/Makefile @@ -75,6 +75,12 @@ CARGO = cargo lock: $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) $(CARGO) generate-lockfile +# Re-resolve Cargo.lock's vaportpm-attest entry to the rev in tpm-derive's Cargo.toml (after +# bumping it), leaving every other dependency as locked (`lock` re-resolves them all). +.PHONY: update-vaportpm +update-vaportpm: docker-build-base + $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) $(CARGO) update -p vaportpm-attest + check: $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) $(CARGO) check --workspace --all-targets --locked From c28a722fc4bbd2682e3e65f37e48b5aa333ec790 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:31:46 +0000 Subject: [PATCH 3/6] deps: vaportpm-attest v0.4.1 Repin tpm-derive from v0.3.0 (7041f46) to the v0.4.1 release commit 157ec04, guard =0.4.1. derive.rs, session.rs and pcr.rs are unchanged between them, so the derived keys are the same. Cargo.lock: only the vaportpm-attest entry (make update-vaportpm). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 ++-- crates/tpm-derive/Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 91bea72..49a1472 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -586,8 +586,8 @@ dependencies = [ [[package]] name = "vaportpm-attest" -version = "0.3.0" -source = "git+https://github.com/lockboot/vaportpm?rev=7041f461eb33bc15ad914466042b7befe358d119#7041f461eb33bc15ad914466042b7befe358d119" +version = "0.4.1" +source = "git+https://github.com/lockboot/vaportpm?rev=157ec04bf2efafc9d096dd063c904d9739156a86#157ec04bf2efafc9d096dd063c904d9739156a86" dependencies = [ "anyhow", "base64", diff --git a/crates/tpm-derive/Cargo.toml b/crates/tpm-derive/Cargo.toml index f5ea56f..8f2dde9 100644 --- a/crates/tpm-derive/Cargo.toml +++ b/crates/tpm-derive/Cargo.toml @@ -8,5 +8,5 @@ license.workspace = true anyhow = { workspace = true } sha2 = { workspace = true } # The TPM I/O + deterministic PCR-bound derivation live in vaportpm. Pinned to the -# v0.3.0 release rev (matches the sibling repos' git-dep style). -vaportpm-attest = { git = "https://github.com/lockboot/vaportpm", rev = "7041f461eb33bc15ad914466042b7befe358d119", version = "=0.3.0" } +# v0.4.1 release rev (matches the sibling repos' git-dep style). +vaportpm-attest = { git = "https://github.com/lockboot/vaportpm", rev = "157ec04bf2efafc9d096dd063c904d9739156a86", version = "=0.4.1" } From 63efd1ccc1c15a01992883aa2c556ce7c0e8d732 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:31:46 +0000 Subject: [PATCH 4/6] ci: create the release as a draft, then publish action-gh-release with draft: false publishes the release before uploading its assets; an immutable release accepts no uploads once published, so the first tagged release would ship empty (vaportpm v0.4.0 did, vaportpm#14). Create it as a draft with the assets, then publish with `gh release edit --draft=false`. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e8c8853..51502ca 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -83,7 +83,10 @@ jobs: stage2-loader-aarch64 stage2.replay.json - - name: Create release + # Created as a draft with its assets, then published: a release is immutable from the + # moment it is published (repo setting, workspace tools/rulesets.sh) and then accepts no + # uploads, so publishing first leaves it empty (as vaportpm v0.4.0 was). + - name: Create draft release uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1 with: tag_name: ${{ github.ref_name }} @@ -91,11 +94,16 @@ jobs: stage2-loader-x86_64 stage2-loader-aarch64 stage2.replay.json - draft: false + draft: true prerelease: true generate_release_notes: true make_latest: true + - name: Publish release + env: + GH_TOKEN: ${{ github.token }} + run: gh release edit "${{ github.ref_name }}" -R "${{ github.repository }}" --draft=false + # ---- erofs-builder image (tag: v*) --------------------------------- # End-user forge: mkruntime + pinned erofs/verity/ext4 tools + this release's loaders for BOTH # arches baked in (`--arch `), so packing needs no separate loader download. Multi-arch so From 4779d053882c3507985401802db7068fb76c4b9f Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:27:32 +0000 Subject: [PATCH 5/6] PCR-BINDING: drop the reference to the removed workspace plan file Co-Authored-By: Claude --- PCR-BINDING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/PCR-BINDING.md b/PCR-BINDING.md index 1886767..40a3ffb 100644 --- a/PCR-BINDING.md +++ b/PCR-BINDING.md @@ -207,8 +207,8 @@ usable LBA, or the boot fails closed instead of rebooting into the same rewrite. keys are minted per build and discarded, but that guarantee rests on a deletion nobody can demonstrate, not on a measurement. -The Nitro caveat under PCR5 above still applies (O3 in the workspace's -`PLAN-GPT-MEASUREMENT.md`): confirm PCR5's contents on EC2 before relying on it there. +The Nitro caveat under PCR5 above still applies: confirm PCR5's contents on EC2 before +relying on it there. ## Resolution (2026-07-11, superseded for PCR5) From 748f845056a7814b233a91dbf7212e50ca54402f Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:23:02 +0000 Subject: [PATCH 6/6] pivot-init: print the config digest, stage1's attestation and every PCR The reboot-test payload now prints, on every boot it reaches, the evidence an off-machine check needs (workspace tools/cloudtest/check-run.py): the config digest bound into PCR15, stage1's attestation as base64 between the markers vaportpm-verify accepts, and every PCR as 'PCR ' (pcr-replay --check). It waits 3 s before a reboot or power-off so the serial console drains. Test payload only. Tested: make ci; selftest (pivot, grow) on x86_64 and aarch64; GCP n2d SEV, n2d SEV-SNP and c3 TDX (cloudtest be236c1f6330): the attestation verifies and the PCRs replay on both payload boots, /data survives the reboot. Co-Authored-By: Claude --- crates/bootstrap/examples/pivot-init.rs | 82 ++++++++++++++++++++++--- 1 file changed, 73 insertions(+), 9 deletions(-) diff --git a/crates/bootstrap/examples/pivot-init.rs b/crates/bootstrap/examples/pivot-init.rs index 52e3613..24b9952 100644 --- a/crates/bootstrap/examples/pivot-init.rs +++ b/crates/bootstrap/examples/pivot-init.rs @@ -8,11 +8,13 @@ //! ephemeral probe; reboot. //! boot 2: [persist] the /data sentinel survived; [integrity] the overlay-root probe did NOT //! (ephemeral). Then PASS. +//! Every boot also prints the evidence an off-machine check needs (workspace +//! `tools/cloudtest/`): the config digest, stage1's attestation and every PCR. //! Not production. use anyhow::{bail, Context, Result}; use std::fs; -use std::io::Read; +use std::io::{Read, Write}; use std::path::Path; const SENTINEL: &[u8] = b"LOCKBOOT-PIVOT-PERSIST-v1"; @@ -23,7 +25,12 @@ const BASE_MIB: u64 = 64; // the baked ext4 base; a grown /data must be well pas fn main() { println!("=== pivot-init (PID {}) ===", std::process::id()); - match run() { + let mut cfg = Vec::new(); + if let Err(e) = std::io::stdin().read_to_end(&mut cfg) { + println!("CONFIG error: {e}"); + } + dump_evidence(&cfg); + match run(&cfg) { Ok(true) => { println!("PIVOT_TEST=PASS all properties verified"); poweroff(); @@ -39,7 +46,7 @@ fn main() { } } -fn run() -> Result { +fn run(cfg: &[u8]) -> Result { let boot: u32 = fs::read_to_string(COUNTER) .ok() .and_then(|s| s.trim().parse().ok()) @@ -48,7 +55,7 @@ fn run() -> Result { println!("boot#{}", boot + 1); if boot == 0 { - check_config()?; + check_config(cfg)?; check_attestations()?; check_resized()?; fs::write(EPHEMERAL_PROBE, b"x").context("write ephemeral probe to /")?; @@ -74,11 +81,8 @@ fn run() -> Result { } /// [config] the transparent JSON arrives verbatim on stdin. -fn check_config() -> Result<()> { - let mut cfg = String::new(); - std::io::stdin() - .read_to_string(&mut cfg) - .context("read config from stdin")?; +fn check_config(cfg: &[u8]) -> Result<()> { + let cfg = String::from_utf8_lossy(cfg); if cfg.trim().is_empty() { bail!("empty config on stdin -- loader did not forward the doc"); } @@ -111,8 +115,66 @@ fn check_resized() -> Result<()> { Ok(()) } +/// Evidence for an off-machine check, in the formats its tools read: +/// - `CONFIG bytes= sha256=`: the digest the loader bound into PCR15; +/// - stage1's attestation, base64 between the markers vaportpm-verify accepts (base64 so no +/// console line is long enough to be split); +/// - every PCR in every bank as `PCR ` (pcr-replay `--check`). These are read +/// from the TPM here, not quoted. +fn dump_evidence(cfg: &[u8]) { + let d = tpm_derive::config_digest(cfg); + let hex: String = d.iter().map(|b| format!("{b:02x}")).collect(); + println!("CONFIG bytes={} sha256={hex}", cfg.len()); + + match fs::read("/run/lockboot/stage1.attest") { + Ok(a) => { + println!("===ATTESTATION-BEGIN==="); + for line in base64(&a).as_bytes().chunks(76) { + println!("{}", String::from_utf8_lossy(line)); + } + println!("===ATTESTATION-END==="); + } + Err(e) => println!("[attest] no stage1 attestation to print: {e}"), + } + + for bank in ["sha1", "sha256", "sha384", "sha512"] { + for i in 0..24 { + if let Ok(v) = fs::read_to_string(format!("/sys/class/tpm/tpm0/pcr-{bank}/{i}")) { + println!("PCR {bank} {i:02} {}", v.trim().to_lowercase()); + } + } + } + println!("=== PCR-DUMP-END ==="); +} + // ---- helpers ---- +/// Standard base64 with padding. +fn base64(data: &[u8]) -> String { + const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for c in data.chunks(3) { + let n = (c[0] as u32) << 16 + | (*c.get(1).unwrap_or(&0) as u32) << 8 + | *c.get(2).unwrap_or(&0) as u32; + for i in 0..4 { + out.push(if i <= c.len() { + A[(n >> (18 - 6 * i) & 63) as usize] as char + } else { + '=' + }); + } + } + out +} + +/// Let the console drain before the machine goes away: a 115200-baud serial console is still +/// sending the last lines when the kernel resets or powers down. +fn drain_console() { + let _ = std::io::stdout().flush(); + std::thread::sleep(std::time::Duration::from_secs(3)); +} + fn statvfs_total(path: &str) -> Result { let c = std::ffi::CString::new(path)?; let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; @@ -131,6 +193,7 @@ fn present(b: bool) -> &'static str { } fn reboot() { + drain_console(); // SAFETY: PID 1 warm reboot; sync then restart. unsafe { libc::sync(); @@ -140,6 +203,7 @@ fn reboot() { } fn poweroff() { + drain_console(); // SAFETY: PID 1 power-off; sync then poweroff. unsafe { libc::sync();