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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,27 @@ 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 }}
files: |
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 <arch>`), so packing needs no separate loader download. Multi-arch so
Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

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

6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
46 changes: 38 additions & 8 deletions PCR-BINDING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand All @@ -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
Expand Down Expand Up @@ -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: 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
Expand Down
46 changes: 42 additions & 4 deletions crates/blockdev/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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).
}
Expand Down Expand Up @@ -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
Expand Down
82 changes: 73 additions & 9 deletions crates/bootstrap/examples/pivot-init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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();
Expand All @@ -39,7 +46,7 @@ fn main() {
}
}

fn run() -> Result<bool> {
fn run(cfg: &[u8]) -> Result<bool> {
let boot: u32 = fs::read_to_string(COUNTER)
.ok()
.and_then(|s| s.trim().parse().ok())
Expand All @@ -48,7 +55,7 @@ fn run() -> Result<bool> {
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 /")?;
Expand All @@ -74,11 +81,8 @@ fn run() -> Result<bool> {
}

/// [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");
}
Expand Down Expand Up @@ -111,8 +115,66 @@ fn check_resized() -> Result<()> {
Ok(())
}

/// Evidence for an off-machine check, in the formats its tools read:
/// - `CONFIG bytes=<n> sha256=<hex>`: 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 <bank> <nn> <hex>` (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<u64> {
let c = std::ffi::CString::new(path)?;
let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
Expand All @@ -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();
Expand All @@ -140,6 +203,7 @@ fn reboot() {
}

fn poweroff() {
drain_console();
// SAFETY: PID 1 power-off; sync then poweroff.
unsafe {
libc::sync();
Expand Down
31 changes: 27 additions & 4 deletions crates/bootstrap/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions crates/tpm-derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Loading
Loading