From 44eef04bac1a5ef8edfbaef18132ff99b36fbb34 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:27:18 +0000 Subject: [PATCH 01/10] init: tolerate unwritable optional sysctls (aarch64); build arch aliases `sysctl -f` now also skips, with a warning, a knob that is present but not writable, not only a missing one. kernel/nmi_watchdog exists on aarch64 but has no NMI watchdog behind it and rejects the write, which died init. It is now marked -f; all other hardening sysctls stay fatal. Makefile: add build-x86_64/build-aarch64/build-amd64/build-arm64 aliases, and drop the `--exclude mkuki --exclude deploy` from the musl stage1 build so the whole workspace is built for the target. Co-Authored-By: Claude Opus 5.5 --- Makefile | 8 ++++---- tools/build-uki/init | 6 ++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 1754bc3..e25d4a4 100644 --- a/Makefile +++ b/Makefile @@ -19,9 +19,9 @@ ARCHS = x86_64 aarch64 .PHONY: build build: $(ARCHS) -.PHONY: amd64 x86_64 arm64 aarch64 -amd64 x86_64: tools/build-uki/x86_64/linux.efi -arm64 aarch64: tools/build-uki/aarch64/linux.efi +.PHONY: build-amd64 build-x86_64 build-arm64 build-aarch64 amd64 x86_64 arm64 aarch64 +build-amd64 build-x86_64 amd64 x86_64: tools/build-uki/x86_64/linux.efi +build-arm64 build-aarch64 arm64 aarch64: tools/build-uki/aarch64/linux.efi # Reference production _stage1/_stage2 doc (served from S3 in prod). DEFAULT_STAGE2_URL = https://lockboot.s3.us-east-1.amazonaws.com/examples/stage2/user-data.json @@ -86,7 +86,7 @@ tools/build-uki/%/linux.efi: tools/build-uki/%/busybox tools/build-uki/%/stage1 tools/build-uki/%/stage1: docker-build-base mkdir -p tools/build-uki/$* $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ - bash -c "rustup target add $*-unknown-linux-musl && cargo build --release --locked --workspace --exclude mkuki --exclude deploy --target $*-unknown-linux-musl && cp -v target/$*-unknown-linux-musl/release/stage1 $@" + bash -c "rustup target add $*-unknown-linux-musl && cargo build --release --locked --workspace --target $*-unknown-linux-musl && cp -v target/$*-unknown-linux-musl/release/stage1 $@" # mkuki assembles the UKI from inside build.sh. Unlike stage1 (which runs on the # target arch), mkuki is a build-host tool that runs in the x86_64 build container diff --git a/tools/build-uki/init b/tools/build-uki/init index da8a042..a7495b6 100644 --- a/tools/build-uki/init +++ b/tools/build-uki/init @@ -8,7 +8,8 @@ log() { kmsg "<6>init: $*"; } warn() { kmsg "<4>init: $*"; } die() { kmsg "<3>init: $*"; $BB poweroff -f; } -# sysctl path value — write or die. Pass -f to skip missing files with a warning. +# sysctl path value — write or die. Pass -f to skip (with a warning) a knob that is +# missing OR present-but-unwritable on this arch (e.g. nmi_watchdog on aarch64). sysctl() { _opt=0; [ "${1:-}" = "-f" ] && { _opt=1; shift; } _path="/proc/sys/$1"; _name=$(echo "$1" | $BB tr '/' '.') @@ -17,6 +18,7 @@ sysctl() { die "sysctl: $_name not found" fi if ! echo "$2" > "$_path" 2>/dev/null; then + [ $_opt -eq 1 ] && { warn "sysctl: $_name=$2 skipped (write failed)"; return 0; } die "sysctl: $_name=$2 failed" fi log "sysctl: $_name=$2" @@ -110,7 +112,7 @@ sysctl net/core/bpf_jit_harden 2 # Fail closed: crash immediately on abnormal conditions rather than continuing # in a potentially exploitable state. crashkernel=0 + lockdown ensures no # memory dump is produced on panic. -sysctl kernel/nmi_watchdog 0 +sysctl -f kernel/nmi_watchdog 0 # present but not writable on aarch64 (no NMI watchdog) sysctl kernel/panic_on_oops 1 sysctl kernel/softlockup_panic 1 sysctl -f kernel/hung_task_panic 1 From cb8c7dccea59a569da7232b033602ca8f7768852 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:36:11 +0000 Subject: [PATCH 02/10] Dockerfile.build: drop virt-firmware and python3-pip stage0 now builds its Secure Boot varstores with tools/mkvarstore.py (stdlib only), so nothing runs virt-fw-vars, and pip was installed only for it. Synced from stage0's canonical copy (workspace `make sync-harness`). Co-Authored-By: Claude Opus 5.5 --- Dockerfile.build | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Dockerfile.build b/Dockerfile.build index f9df7d5..f9f73b1 100644 --- a/Dockerfile.build +++ b/Dockerfile.build @@ -22,7 +22,6 @@ RUN apt-get -qq update && \ openssl \ ovmf \ python3 \ - python3-pip \ qemu-efi-aarch64 \ rpm \ rpm2cpio \ @@ -30,8 +29,7 @@ RUN apt-get -qq update && \ util-linux \ uuid-runtime \ wget \ - xz-utils && \ - pip3 install --break-system-packages virt-firmware + xz-utils # Reproducible builds environment ENV SOURCE_DATE_EPOCH=0 From a5bc0eb2db6e78e5f120886dd61c53f0da7934d9 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:34:14 +0000 Subject: [PATCH 03/10] selftest: HARNESS_TIMEOUT + selftest- HARNESS_TIMEOUT passes qemu-test.sh --timeout through to the harness, so an unattended boot that hangs fails instead of blocking. selftest- is this repo's part of the workspace `make selftest`: test-chain in every _stage2 admission mode (sha256, sign, sign_args, manifest, fallback) plus smoke-args; a mode passes only if the leaf ran and received stage1's attestation. 300 s per boot on both arches. Co-Authored-By: Claude Opus 5.5 --- Makefile | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index e25d4a4..d5cc65c 100644 --- a/Makefile +++ b/Makefile @@ -269,7 +269,8 @@ test-chain-%: tools/build-uki/%/linux.efi build/%/stage2 \ -e YES_INSIDE_DOCKER_DO_DANGEROUS_IPTABLES=1 --cap-add=NET_ADMIN --device=/dev/net/tun \ $(HARNESS_IMAGE) --kind stage0 --arch $* \ --boot-disk "$(STAGE0_BOOT_DISK)" \ - --serve-dir "$$D" --user-data user-data.stage0.json $(if $(TRACE),--trace) + --serve-dir "$$D" --user-data user-data.stage0.json $(if $(TRACE),--trace) \ + $(if $(HARNESS_TIMEOUT),--timeout $(HARNESS_TIMEOUT)) # ---- Smoke test: _stage2 args actually reach the payload's argv ---- # Boot the full chain with a known inline args array (one arg contains a space, to prove @@ -288,6 +289,40 @@ smoke-args-%: fi +# ---- Self-test: stage1's part of the workspace `make selftest` (PASS/FAIL, non-zero on FAIL) ---- +# Boots the full chain (stage0 -> UKI -> stage1 -> example-stage2) in every _stage2 admission mode, +# then smoke-args. A mode PASSes only if the leaf actually ran (its argv echo + "Task complete") +# AND stage1 handed it an attestation (no "Error reading /tmp/stage1.attest"). Every boot is +# time-bounded (HARNESS_TIMEOUT -> qemu-test.sh --timeout), one bound for both arches. +# Needs the sibling stage0 boot.disk and the lockboot:harness image (stage0 `make selftest-`). +SELFTEST_TIMEOUT_x86_64 ?= 300 +SELFTEST_TIMEOUT_aarch64 ?= 300 +.PHONY: selftest +selftest: + @echo "needs an arch suffix, e.g. 'make selftest-x86_64'." >&2; exit 2 +selftest-%: + @fail=0; T=$(SELFTEST_TIMEOUT_$*); sum="build/$*/selftest.summary"; mkdir -p build/$*; : > "$$sum"; \ + for m in "sha256:" "sign:SIGN=1" "sign_args:SIGN=1 SIGN_ARGS=1" "manifest:SIGN=1 MANIFEST=1" "fallback:FALLBACK=1"; do \ + name="$${m%%:*}"; vars="$${m#*:}"; log="build/$*/selftest-$$name.log"; \ + echo "==================== stage1 chain test [$$name] $$vars -> $$log"; \ + $(MAKE) --no-print-directory test-chain-$* $$vars HARNESS_TIMEOUT=$$T > "$$log" 2>&1 || true; \ + if grep -q 'arg\[0\]:' "$$log" && grep -q '=== Task complete' "$$log" \ + && ! grep -q 'Error reading /tmp/stage1.attest' "$$log"; then \ + echo "PASS [$$name]" | tee -a "$$sum"; \ + else \ + echo "FAIL [$$name] (see $$log)" | tee -a "$$sum"; fail=1; \ + fi; \ + done; \ + echo "==================== stage1 smoke-args"; \ + if $(MAKE) --no-print-directory smoke-args-$* HARNESS_TIMEOUT=$$T > build/$*/selftest-smoke-args.log 2>&1; then \ + echo "PASS [smoke-args]" | tee -a "$$sum"; \ + else \ + echo "FAIL [smoke-args] (see build/$*/selftest-smoke-args.log)" | tee -a "$$sum"; fail=1; \ + fi; \ + echo "==================== stage1 self-test summary ($*)"; cat "$$sum"; \ + if [ "$$fail" = 0 ]; then echo "ALL STAGE1 SELF-TESTS PASSED ($*)"; else echo "SOME STAGE1 SELF-TESTS FAILED ($*)"; exit 1; fi + + ##################################################################### # Housekeeping From ac665524cd4b80e5c6860f5e4c7d22ec7c65054e Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:37:55 +0000 Subject: [PATCH 04/10] release: tag releases as plain v* The uki-v* prefix dates from the pre-split lockboot/lockboot repo, where one workflow carried two release tracks (stage0-v* and uki-v*) and the prefix told them apart. Each repo now releases one product, so every release repo uses plain v* (as vaportpm already does). Workflow trigger, release-job ref checks, and docs updated; release asset names are unchanged. The next stage1 release must sort above the existing v0.1.0 / v0.2.0 pre-releases. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 14 +++++++------- Makefile | 2 +- tools/publish.sh | 6 +++--- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4c8e23f..b6d87ea 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,9 +4,9 @@ on: push: branches: [main] # Release track gated by tag prefix: - # uki-v* → the netboot UKI (stage1), admitted by stage0 via sha256 + PCR 14 - # (The Secure Boot root of trust ships from the stage0 repo on its own stage0-v* track.) - tags: ['uki-v*'] + # v* → the netboot UKI (stage1), admitted by stage0 via sha256 + PCR 14 + # (The Secure Boot root of trust ships from the stage0 repo, on its own v* releases.) + tags: ['v*'] pull_request: branches: [main] workflow_dispatch: @@ -56,11 +56,11 @@ jobs: tools/build-uki/${{ matrix.arch }}/stage1 build/${{ matrix.arch }}/stage2 - # ---- UKI (stage1) release track (tag: uki-v*) ---------------------------- + # ---- UKI (stage1) release track (tag: v*) ---------------------------- release-uki: runs-on: ubuntu-latest needs: build - if: startsWith(github.ref, 'refs/tags/uki-v') + if: startsWith(github.ref, 'refs/tags/v') permissions: contents: write id-token: write @@ -96,12 +96,12 @@ jobs: generate_release_notes: true make_latest: true - # ---- stage1 runtime container image (tag: uki-v*) ------------------------ + # ---- stage1 runtime container image (tag: v*) ------------------------ # Minimal busybox + stage1 utility image; belongs to the stage1/UKI track. release-docker: runs-on: ubuntu-latest needs: build - if: startsWith(github.ref, 'refs/tags/uki-v') + if: startsWith(github.ref, 'refs/tags/v') permissions: contents: read packages: write diff --git a/Makefile b/Makefile index d5cc65c..9945d02 100644 --- a/Makefile +++ b/Makefile @@ -108,7 +108,7 @@ update-fedora-deps: docker-build-base ##################################################################### -# Runtime container image (busybox + stage1) -> ghcr on uki-v* tags. +# Runtime container image (busybox + stage1) -> ghcr on v* release tags. docker-buildx-setup: docker buildx create --name lockboot-builder --use || docker buildx use lockboot-builder diff --git a/tools/publish.sh b/tools/publish.sh index 01c49bb..5d6518d 100755 --- a/tools/publish.sh +++ b/tools/publish.sh @@ -10,9 +10,9 @@ # Usage: ./publish.sh [version] # dest-uri : s3://bucket/prefix or gs://bucket/prefix # arch : x86_64 | aarch64 -# version : a uki-v* release tag, or 'local' (default) to use a local build +# version : a v* release tag, or 'local' (default) to use a local build # -# Example: ./publish.sh s3://lockboot/uki x86_64 uki-v0.1.0 +# Example: ./publish.sh s3://lockboot/uki x86_64 v0.3.0 # ./publish.sh gs://lockboot/uki aarch64 local set -euo pipefail @@ -30,7 +30,7 @@ if [ "${ARCH}" != "x86_64" ] && [ "${ARCH}" != "aarch64" ]; then echo "Error: arch must be x86_64 or aarch64"; exit 1 fi -# Resolve the UKI: local build, or a verified uki-v* release artifact. +# Resolve the UKI: local build, or a verified v* release artifact. if [ "${VERSION}" != "local" ]; then TEMP_DIR=$(mktemp -d); trap "rm -rf ${TEMP_DIR}" EXIT GH_REPO=$(git remote get-url origin | sed 's/.*github.com[:/]\(.*\)\.git/\1/' || echo "") From 09dd1dd9b42aaccdad24dd92d823cd47f61de0a0 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:54:35 +0000 Subject: [PATCH 05/10] release: attest the files inside the release zips The release attestation covered only the GitHub artifact zips. A consumer can verify a zip and extract from it, but could not verify an extracted file on its own. The release job now unzips both arches and attests, in the same single attestation step, the zips plus every file inside them. Subjects come from a sha256sum-format checksums file (subject-checksums), named /, so the per-arch copies of same-named files stay distinguishable; verification matches by digest. xargs -r keeps an empty listing from hashing stdin. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b6d87ea..43625a4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -77,12 +77,26 @@ jobs: gh api repos/${{ github.repository }}/actions/artifacts/${ARTIFACT_ID}/zip > uki-${arch}.zip done - - name: Attest UKI zips + # One attestation covering the release zips and every file inside them. Consumers can verify + # a zip and extract from it, or verify an extracted file on its own (e.g. the linux.efi stage0 + # admits by sha256: `gh attestation verify linux.efi --repo ...`). Subjects are named via a + # checksums file so the per-arch copies of same-named files stay distinguishable + # (x86_64/... vs aarch64/...); verification itself matches by digest. + - name: List attestation subjects (zips + their contents) + run: | + for arch in x86_64 aarch64; do + mkdir -p "contents/$arch" && unzip -q "uki-$arch.zip" -d "contents/$arch" + done + { + sha256sum uki-x86_64.zip uki-aarch64.zip + (cd contents && find . -type f -printf '%P\n' | LC_ALL=C sort | xargs -r -d '\n' sha256sum) + } > subjects.sha256 + cat subjects.sha256 + + - name: Attest UKI zips and their contents uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3.0.0 with: - subject-path: | - uki-x86_64.zip - uki-aarch64.zip + subject-checksums: subjects.sha256 - name: Create UKI release uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1 From 603dc625763f969f26e251451fdb7e983f3a5381 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:10:41 +0000 Subject: [PATCH 06/10] pcrs: stage1's PCR contribution from the UKI; ship measurements.json tools/predict-pcrs.py derives what stage1 adds to the PCRs from linux.efi alone (confirmed event by event against the Linux TCG log of a QEMU stage0 -> stage1 -> stage2 boot): - PCR5: "Exit Boot Services Invocation" / "...Returned with Success". - PCR9: the Linux EFI stub's LoadOptions (UTF-16LE .cmdline + NUL) and the initrd systemd-stub v259 hands the kernel: .initrd padded to 4, then the stub's generated cpio carrying .osrel as /.extra/os-release (reconstructed byte for byte from systemd's cpio.c / stub.c). - PCR11: systemd-stub's name + contents pair for .linux .osrel .cmdline .initrd .uname .sbat. - PCR14: stage1's H_bank(sha256(stage2)), an input. The kernel is not measured into PCR4 (stage0 loads the UKI through its Security2 override); it is covered by PCR14 (whole UKI) and PCR11. UKIs with sections whose PCR9/PCR11 effect has not been verified (.ucode, .pcrsig, .profile, ...) are refused rather than guessed at. --emit-measurements writes only the fixed extends; build.sh emits measurements.json next to linux.efi and CI uploads it, so it ships in the attested release. --stage0 pcrs.json --stage2-sha256 gives the full state at the stage2 handoff (stage0's PCR14 for this UKI added if absent, checked if present). example-stage2 --dump-tpm (opt-in) prints the Linux event log and all PCRs for --check. Verified, all predicted PCRs in four banks: QEMU x86_64 and aarch64. The UKI rebuilds byte-identical with the new build step. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 1 + crates/example-stage2/src/main.rs | 54 +++++++++ tools/build-uki/build.sh | 5 + tools/predict-pcrs.py | 195 ++++++++++++++++++++++++++++++ 4 files changed, 255 insertions(+) create mode 100755 tools/predict-pcrs.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 43625a4..0f8b33a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,6 +50,7 @@ jobs: path: | tools/build-uki/${{ matrix.arch }}/linux.efi tools/build-uki/${{ matrix.arch }}/linux.efi.sha256 + tools/build-uki/${{ matrix.arch }}/measurements.json tools/build-uki/${{ matrix.arch }}/stage0-snippet.json tools/build-uki/${{ matrix.arch }}/os-release tools/build-uki/${{ matrix.arch }}/busybox diff --git a/crates/example-stage2/src/main.rs b/crates/example-stage2/src/main.rs index 2e4d154..980511b 100644 --- a/crates/example-stage2/src/main.rs +++ b/crates/example-stage2/src/main.rs @@ -32,12 +32,66 @@ fn main() { } println!(); + // Opt-in (`--dump-tpm`): the TCG event log (firmware + systemd-stub + kernel events) and every + // PCR the kernel exposes, so a PCR predictor can be checked event-by-event against this boot. + if args.iter().any(|a| a == "--dump-tpm") { + dump_tpm(); + } + println!("=== Task complete, waiting 60 seconds for console log capture ==="); thread::sleep(Duration::from_secs(60)); println!("=== Powering off ==="); poweroff(); } +/// Mount `fstype` at `target` (best effort: an already-mounted target is fine). +fn mount(fstype: &str, target: &str) { + let _ = fs::create_dir_all(target); + let src = std::ffi::CString::new(fstype).unwrap(); + let dst = std::ffi::CString::new(target).unwrap(); + let rc = unsafe { + libc::mount( + src.as_ptr(), + dst.as_ptr(), + src.as_ptr(), + 0, + std::ptr::null(), + ) + }; + if rc != 0 { + let e = std::io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::EBUSY) { + eprintln!("mount {fstype} on {target}: {e}"); + } + } +} + +/// Print the raw TCG2 event log as `TPMLOG ` lines (<= 64 bytes each, in order) and every +/// PCR as `PCR `, bracketed by stable markers. +fn dump_tpm() { + mount("sysfs", "/sys"); + mount("securityfs", "/sys/kernel/security"); + println!("=== TPMLOG-BEGIN ==="); + match fs::read("/sys/kernel/security/tpm0/binary_bios_measurements") { + Ok(log) => { + for chunk in log.chunks(64) { + let hex: String = chunk.iter().map(|b| format!("{b:02x}")).collect(); + println!("TPMLOG {hex}"); + } + println!("=== TPMLOG-END === bytes={}", log.len()); + } + Err(e) => println!("=== TPMLOG-END === error: {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 ==="); +} + fn poweroff() { let pid = std::process::id(); if pid == 1 { diff --git a/tools/build-uki/build.sh b/tools/build-uki/build.sh index 4e2ce51..fe43c34 100755 --- a/tools/build-uki/build.sh +++ b/tools/build-uki/build.sh @@ -301,6 +301,11 @@ cp "${KERNEL_PATH}" "${OUTPUT_DIR}/vmlinuz-${KERNEL_VERSION}" UKI_SHA256=$(sha256sum "${UKI_PATH}" | cut -d' ' -f1) echo "${UKI_SHA256} linux.efi" > "${OUTPUT_DIR}/linux.efi.sha256" +# stage1's fixed PCR contribution (PCR5/9/11 extends, per bank), reproduced from linux.efi alone: +# what a verifier appends to stage0's pcrs.json (see tools/predict-pcrs.py). +python3 "${SCRIPT_DIR}/../predict-pcrs.py" --uki "${UKI_PATH}" --emit-measurements \ + --out "${OUTPUT_DIR}/measurements.json" + # Ready-to-paste _stage1 user-data snippet (sha256 admission mode). Deployers who # want signed-mode rollforward re-sign linux.efi with their own ed25519 key. cat > "${OUTPUT_DIR}/stage0-snippet.json" < stage1 -> stage2 boot): +# +# PCR3, PCR4, PCR6, PCR7 unchanged from stage0. The kernel is NOT measured into PCR4: +# stage0 loads the UKI through its own Security2 override (no firmware +# image measurement), so the UKI is covered by PCR14 (whole file) and +# PCR11 (per section) instead. +# PCR5 stage0's value, then EV_EFI_ACTION "Exit Boot Services Invocation" and +# "Exit Boot Services Returned with Success" (firmware, at the kernel's ExitBootServices). +# PCR9 Linux EFI stub: EV_EVENT_TAG LOADED_IMAGE::LoadOptions = UTF-16LE(.cmdline) + NUL, then +# EV_EVENT_TAG "Linux initrd" = the initrd systemd-stub built (.initrd + a generated +# cpio holding .osrel as /.extra/os-release; see stub_initrd()). +# PCR11 systemd-stub: for each UKI section in systemd's fixed order, H(name + NUL) then +# H(section contents, VirtualSize bytes). +# PCR8, PCR12, PCR13 nothing measured (no stub cmdline override, credentials or sysexts). +# PCR14 stage0's value (which must be its measurement of THIS UKI -- checked), then stage1's +# H(sha256(stage2)). Direct TPM2_PCR_Extend, not logged. +# +# Composable: every PCR in the stage0 input is carried through and only the events above are +# appended, so the output is the complete PCR state at the stage1 -> stage2 handoff. A different +# stage2 starts from this file; a different stage1 starts from stage0's. +# +# PCR0-2 are the provider's firmware (golden readings, see stage0's predictor); PCR10 is IMA (its +# own log; stage2 does not bind it); PCR15 is stage2's config (stage2's own step). +# +# usage: predict-pcrs.py --uki linux.efi --emit-measurements [--out measurements.json] +# this stage's fixed extends only (shipped with each release, next to linux.efi) +# predict-pcrs.py --uki linux.efi --stage0 pcrs.json --stage2-sha256 HEX [--out F] +# the full state after stage1 (stage0's pcrs.json from its release, with or without its +# PCR14 for this UKI -- added if absent, checked if present) +# ... --check (compare against "PCR " lines, e.g. from +# example-stage2 --dump-tpm) +import argparse +import hashlib +import json +import re +import struct +import sys + +# systemd-stub's measured UKI sections, in the order it measures them (only those verified against +# a real event log; any other measured section is refused rather than guessed at). +MEASURED_ORDER = [".linux", ".osrel", ".cmdline", ".initrd", ".uname", ".sbat"] +# Sections systemd-stub also measures when present -- refused until their position is verified. +MEASURED_UNVERIFIED = [".ucode", ".splash", ".dtb", ".dtbauto", ".hwids", ".pcrpkey", + ".profile", ".efifw"] + + +def pe_sections(pe): + off = struct.unpack_from(" the state at the stage1 -> stage2 handoff.""" + out = {} + for bank, ext in measurements["extends"].items(): + H = getattr(hashlib, bank) + if bank not in prev["pcrs"]: + raise SystemExit(f"previous pcrs.json has no {bank} bank") + p = {int(k): v for k, v in prev["pcrs"][bank].items()} # carry everything; extend only ours + zero = "00" * H().digest_size + + def extend(pcr, digests): + v = bytes.fromhex(p.get(pcr, zero)) + for e in digests: + v = H(v + e).digest() + p[pcr] = v.hex() + + if 14 not in p: # stage0 predicted without a payload: add its measurement of this UKI + extend(14, [H(bytes.fromhex(uki_sha256)).digest()]) + elif p[14] != H(b"\0" * H().digest_size + H(bytes.fromhex(uki_sha256)).digest()).hexdigest(): + raise SystemExit(f"previous pcrs.json PCR14 ({bank}) is not stage0's measurement of this UKI") + for pcr, digests in ext.items(): + extend(int(pcr), [bytes.fromhex(d) for d in digests]) + for k in (8, 12, 13): # nothing measured: explicit, so a verifier can bind them + p.setdefault(k, zero) + extend(14, [H(bytes.fromhex(stage2_sha256)).digest()]) + out[bank] = {str(k): v for k, v in sorted(p.items())} + return {"pcrs": out} + + +def check(pred, log_path): + with open(log_path, "rb") as f: + txt = f.read().decode("latin1").replace("\r", "") + seen = {(a, int(i)): v for a, i, v in + re.findall(r"^(?:payload: )?PCR (\w+) (\d\d) ([0-9a-f]+)$", txt, re.M)} + bad = 0 + for bank, pcrs in pred["pcrs"].items(): + for i, want in pcrs.items(): + got = seen.get((bank, int(i))) + status = "ok" if got == want else ("MISSING" if got is None else "MISMATCH") + bad += status != "ok" + print(f"{bank:7} PCR{int(i):<2} {status:8} predicted {want[:16]}" + + ("" if status == "ok" or got is None else f" read {got[:16]}")) + print("ALL PREDICTED PCRS MATCH" if not bad else f"{bad} PREDICTED PCR(S) DO NOT MATCH") + return bad == 0 + + +def main(): + ap = argparse.ArgumentParser(description="stage1's PCR contribution, and the state after it") + ap.add_argument("--uki", required=True, help="the stage1 UKI (linux.efi)") + ap.add_argument("--emit-measurements", action="store_true", + help="write only this stage's fixed extends (the release artifact)") + ap.add_argument("--stage0", help="previous state: stage0's pcrs.json") + ap.add_argument("--stage2-sha256", help="sha256 of the stage2 binary stage1 runs") + ap.add_argument("--banks", default="sha256,sha384", help="comma-separated (default sha256,sha384)") + ap.add_argument("--out", help="write JSON here (default stdout)") + ap.add_argument("--check", metavar="LOG", help="compare against a serial log's PCR dump") + a = ap.parse_args() + with open(a.uki, "rb") as f: + uki = f.read() + res = measurements(uki, a.banks.split(",")) + if not a.emit_measurements: + if not (a.stage0 and a.stage2_sha256): + ap.error("--stage0 and --stage2-sha256 are required unless --emit-measurements") + with open(a.stage0) as f: + res = apply(json.load(f), res, hashlib.sha256(uki).hexdigest(), a.stage2_sha256) + if a.check: + sys.exit(0 if check(res, a.check) else 1) + js = json.dumps(res, indent=2) + "\n" + if a.out: + with open(a.out, "w") as f: + f.write(js) + else: + sys.stdout.write(js) + + +if __name__ == "__main__": + main() From d30a542d96e1f570d113acf8c9cfd625125d42bc Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:40:42 +0000 Subject: [PATCH 07/10] build: compile the UKI's stage1 alone (-p stage1) The musl stage1 rule ran `cargo build --workspace`, so every crate in the workspace (incl. the host tools mkuki and deploy since 44eef04 dropped their --exclude) was built together for the payload target. Resolver 2 unifies the features of shared dependencies across every package in one invocation, so host-tool dependency features leaked into the measured stage1 binary: building stage1 alone changes it (x86_64 bb12f3a0 -> ea7c72fd, aarch64 b040d7b1 -> 7720b36c), and with it the UKI hash. A host-tool dependency bump could otherwise move PCR14/PCR11 with no change to stage1. mkuki and deploy already have their own rules. Verified: make ci; full-chain QEMU boot on x86_64 and aarch64 with the rebuilt UKIs, every reconstructed PCR matching in four banks. Co-Authored-By: Claude Opus 5.5 --- Makefile | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 9945d02..fbb5019 100644 --- a/Makefile +++ b/Makefile @@ -80,13 +80,14 @@ tools/build-uki/%/linux.efi: tools/build-uki/%/busybox tools/build-uki/%/stage1 # Build AND extract stage1 inside the one container step, so the cp runs where # target/ exists rather than in the host/make context, which may not see the build -# container's target dir under nested docker (e.g. `act`). --exclude mkuki/deploy: they -# are build-host tools (mkuki assembles the UKI; deploy generates deployment config), so -# they must not be cross-compiled for the payload target $* here. +# container's target dir under nested docker (e.g. `act`). `-p stage1` only, in its own cargo +# invocation: resolver 2 unifies the features of shared dependencies across every package built +# together for a target, so building the host tools (mkuki, deploy) or anything else alongside +# would let their dependency features leak into the measured stage1 binary inside the UKI. tools/build-uki/%/stage1: docker-build-base mkdir -p tools/build-uki/$* $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ - bash -c "rustup target add $*-unknown-linux-musl && cargo build --release --locked --workspace --target $*-unknown-linux-musl && cp -v target/$*-unknown-linux-musl/release/stage1 $@" + bash -c "rustup target add $*-unknown-linux-musl && cargo build --release --locked -p stage1 --target $*-unknown-linux-musl && cp -v target/$*-unknown-linux-musl/release/stage1 $@" # mkuki assembles the UKI from inside build.sh. Unlike stage1 (which runs on the # target arch), mkuki is a build-host tool that runs in the x86_64 build container From f13596aea4d5e7666f45e8be4642ea5b736ceb2a Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:23:39 +0000 Subject: [PATCH 08/10] pcrs: emit stage1.replay.json (pcr-replay/v1) instead of measurements.json tools/predict-pcrs.py now writes stage1's PCR replay file from the UKI: every event systemd-stub, the kernel's EFI stub and ExitBootServices add between stage0's handoff and the stage2 handoff, each with its derivation from linux.efi (PE sections, the stub's generated initrd cpio, the LoadOptions string) and the digests computed here, plus the stage2 input (PCR14). Format and verifier: workspace tools/pcr-replay. build.sh writes it; CI uploads it with the UKI. Verified: make tools/build-uki//linux.efi writes it on both arches; QEMU x86_64 and aarch64 full chains reproduce (pcr-replay CHAIN VERIFIES, 30 events re-derived and verified); GCP n2d SEV-SNP full chain verifies with the workspace GCP platform file. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 2 +- tools/build-uki/build.sh | 8 +- tools/predict-pcrs.py | 214 +++++++++++++++--------------------- 3 files changed, 91 insertions(+), 133 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0f8b33a..4ed1306 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,7 +50,7 @@ jobs: path: | tools/build-uki/${{ matrix.arch }}/linux.efi tools/build-uki/${{ matrix.arch }}/linux.efi.sha256 - tools/build-uki/${{ matrix.arch }}/measurements.json + tools/build-uki/${{ matrix.arch }}/stage1.replay.json tools/build-uki/${{ matrix.arch }}/stage0-snippet.json tools/build-uki/${{ matrix.arch }}/os-release tools/build-uki/${{ matrix.arch }}/busybox diff --git a/tools/build-uki/build.sh b/tools/build-uki/build.sh index fe43c34..e27f38a 100755 --- a/tools/build-uki/build.sh +++ b/tools/build-uki/build.sh @@ -301,10 +301,10 @@ cp "${KERNEL_PATH}" "${OUTPUT_DIR}/vmlinuz-${KERNEL_VERSION}" UKI_SHA256=$(sha256sum "${UKI_PATH}" | cut -d' ' -f1) echo "${UKI_SHA256} linux.efi" > "${OUTPUT_DIR}/linux.efi.sha256" -# stage1's fixed PCR contribution (PCR5/9/11 extends, per bank), reproduced from linux.efi alone: -# what a verifier appends to stage0's pcrs.json (see tools/predict-pcrs.py). -python3 "${SCRIPT_DIR}/../predict-pcrs.py" --uki "${UKI_PATH}" --emit-measurements \ - --out "${OUTPUT_DIR}/measurements.json" +# stage1's PCR replay file (pcr-replay/v1): the events it adds after stage0's handoff, derived +# from linux.efi alone (see tools/predict-pcrs.py). +python3 "${SCRIPT_DIR}/../predict-pcrs.py" --uki "${UKI_PATH}" \ + --replay "${OUTPUT_DIR}/stage1.replay.json" # Ready-to-paste _stage1 user-data snippet (sha256 admission mode). Deployers who # want signed-mode rollforward re-sign linux.efi with their own ed25519 key. diff --git a/tools/predict-pcrs.py b/tools/predict-pcrs.py index 926534d..8654999 100755 --- a/tools/predict-pcrs.py +++ b/tools/predict-pcrs.py @@ -1,46 +1,34 @@ #!/usr/bin/env python3 -# Reproduce the PCRs stage1 leaves behind -- the stage1 link of the verification path. +# stage1's PCR replay file -- the stage1 link of the verification path. # -# Input: stage0's predicted PCRs (its release `pcrs.json`, from stage0 tools/predict-pcrs.py), -# the stage1 UKI (`linux.efi`), and the stage2 payload's sha256. Output: the PCRs as they stand -# when stage2 starts, per bank, by appending the exact events this stage adds (confirmed -# event-by-event against the Linux TCG event log of a QEMU stage0 -> stage1 -> stage2 boot): +# Given the stage1 UKI (linux.efi), write the events it adds between stage0's handoff and the +# stage2 handoff, as a pcr-replay/v1 file (format and verifier: workspace tools/pcr-replay). Each +# event carries a derivation from the UKI AND the digests computed here, independently, so a +# replay cross-checks both. Confirmed event-by-event against the Linux TCG event log of QEMU +# stage0 -> stage1 -> stage2 boots (x86_64, aarch64; sha1/256/384/512): # -# PCR3, PCR4, PCR6, PCR7 unchanged from stage0. The kernel is NOT measured into PCR4: -# stage0 loads the UKI through its own Security2 override (no firmware -# image measurement), so the UKI is covered by PCR14 (whole file) and -# PCR11 (per section) instead. -# PCR5 stage0's value, then EV_EFI_ACTION "Exit Boot Services Invocation" and -# "Exit Boot Services Returned with Success" (firmware, at the kernel's ExitBootServices). -# PCR9 Linux EFI stub: EV_EVENT_TAG LOADED_IMAGE::LoadOptions = UTF-16LE(.cmdline) + NUL, then -# EV_EVENT_TAG "Linux initrd" = the initrd systemd-stub built (.initrd + a generated -# cpio holding .osrel as /.extra/os-release; see stub_initrd()). -# PCR11 systemd-stub: for each UKI section in systemd's fixed order, H(name + NUL) then -# H(section contents, VirtualSize bytes). -# PCR8, PCR12, PCR13 nothing measured (no stub cmdline override, credentials or sysexts). -# PCR14 stage0's value (which must be its measurement of THIS UKI -- checked), then stage1's -# H(sha256(stage2)). Direct TPM2_PCR_Extend, not logged. +# PCR11 systemd-stub, EV_IPL: for each UKI section in systemd's fixed order, H(name + NUL) +# then H(section contents, VirtualSize bytes). +# PCR9 Linux EFI stub, EV_EVENT_TAG: LOADED_IMAGE::LoadOptions = UTF-16LE(.cmdline) + NUL, +# then "Linux initrd" = the initrd systemd-stub built (.initrd + a generated cpio +# holding .osrel as /.extra/os-release; see stub_initrd()). +# PCR5 firmware, EV_EFI_ACTION, at the kernel's ExitBootServices: "Exit Boot Services +# Invocation", "Exit Boot Services Returned with Success". +# PCR14 stage1's direct TPM2_PCR_Extend of stage2: H_bank(sha256(stage2)), not logged. An +# input (stage2 is the deployment's choice). +# PCR10 IMA: extended by the kernel from here on, its own log -- unpredictable. +# others not extended. The kernel is NOT measured into PCR4: stage0 loads the UKI through its +# own Security2 override (no firmware image measurement), so the UKI is covered by +# PCR14 (whole file, stage0's event) and PCR11 (per section) instead. # -# Composable: every PCR in the stage0 input is carried through and only the events above are -# appended, so the output is the complete PCR state at the stage1 -> stage2 handoff. A different -# stage2 starts from this file; a different stage1 starts from stage0's. -# -# PCR0-2 are the provider's firmware (golden readings, see stage0's predictor); PCR10 is IMA (its -# own log; stage2 does not bind it); PCR15 is stage2's config (stage2's own step). -# -# usage: predict-pcrs.py --uki linux.efi --emit-measurements [--out measurements.json] -# this stage's fixed extends only (shipped with each release, next to linux.efi) -# predict-pcrs.py --uki linux.efi --stage0 pcrs.json --stage2-sha256 HEX [--out F] -# the full state after stage1 (stage0's pcrs.json from its release, with or without its -# PCR14 for this UKI -- added if absent, checked if present) -# ... --check (compare against "PCR " lines, e.g. from -# example-stage2 --dump-tpm) +# usage: predict-pcrs.py --uki linux.efi --replay stage1.replay.json [--banks sha256,sha384] +from __future__ import annotations + import argparse import hashlib import json -import re import struct -import sys +from typing import Any # systemd-stub's measured UKI sections, in the order it measures them (only those verified against # a real event log; any other measured section is refused rather than guessed at). @@ -48,9 +36,15 @@ # Sections systemd-stub also measures when present -- refused until their position is verified. MEASURED_UNVERIFIED = [".ucode", ".splash", ".dtb", ".dtbauto", ".hwids", ".pcrpkey", ".profile", ".efifw"] +UKI = "linux.efi" +EBS = ["Exit Boot Services Invocation", "Exit Boot Services Returned with Success"] +# systemd src/boot/cpio.c pack_cpio_trailer: a literal, with the name size in upper case ("B") +# unlike the generated entries' lower-case fields, then NUL padding. +CPIO_TRAILER = ("070701" + "00000000" * 4 + "00000001" + "00000000" * 6 + "0000000B" + "00000000" + + "TRAILER!!!\0\0\0\0") -def pe_sections(pe): +def pe_sections(pe: bytes) -> dict[str, bytes]: off = struct.unpack_from(" bytes: return b + b"\0" * ((-len(b)) % 4) -def _cpio_hdr(ino, mode, size, name): - w = lambda v: b"%08x" % v # noqa: E731 +def _cpio_hdr(ino: int, mode: int, size: int, name: bytes) -> bytes: + def w(v: int) -> bytes: + return b"%08x" % v return _pad4(b"070701" + w(ino) + w(mode) + w(0) + w(0) + w(1) + w(0) + w(size) + w(0) * 4 + w(len(name) + 1) + w(0) + name + b"\0") -def stub_initrd(secs): +def stub_initrd(secs: dict[str, bytes]) -> bytes: """The initrd systemd-stub (v259) hands the kernel, which the kernel measures into PCR9: the UKI .initrd, then the stub's generated cpio carrying .osrel as /.extra/os-release (systemd src/boot/cpio.c pack_cpio_literal: dir .extra 0555 inode 1, file 0444 inode 2, @@ -85,14 +80,11 @@ def stub_initrd(secs): osrel = secs[".osrel"] cpio = (_cpio_hdr(1, 0o040000 | 0o555, 0, b".extra") + _cpio_hdr(2, 0o100000 | 0o444, len(osrel), b".extra/os-release") + _pad4(osrel) - + b"070701" + b"00000000" * 4 + b"00000001" + b"00000000" * 6 + b"0000000B" - + b"00000000" + b"TRAILER!!!\0\0\0\0") + + CPIO_TRAILER.encode()) return _pad4(secs[".initrd"]) + cpio -def measurements(uki, banks): - """This stage's fixed contribution, from the UKI alone: per bank, the digests it extends into - each PCR, in order. (Its PCR14 extend depends on the deployed stage2, so it is an input.)""" +def replay_file(uki: bytes, banks: list[str]) -> dict[str, Any]: secs = pe_sections(uki) bad = [s for s in MEASURED_UNVERIFIED + [".pcrsig"] if s in secs] if bad: @@ -101,94 +93,60 @@ def measurements(uki, banks): if missing: raise SystemExit(f"UKI lacks expected section(s) {missing}") cmdline = secs[".cmdline"].rstrip(b"\0").decode() - initrd = stub_initrd(secs) - out = {} - for bank in banks: - H = getattr(hashlib, bank) - out[bank] = { - "5": [H(b"Exit Boot Services Invocation").digest().hex(), - H(b"Exit Boot Services Returned with Success").digest().hex()], - "9": [H(cmdline.encode("utf-16-le") + b"\0\0").digest().hex(), H(initrd).digest().hex()], - "11": [d.hex() for s in MEASURED_ORDER - for d in (H(s.encode() + b"\0").digest(), H(secs[s]).digest())], - } - return {"extends": out} - - -def apply(prev, measurements, uki_sha256, stage2_sha256): - """Previous state (stage0's pcrs.json) + stage0's PCR14 measurement of the UKI + this stage's - fixed extends + its PCR14 measurement of stage2 -> the state at the stage1 -> stage2 handoff.""" - out = {} - for bank, ext in measurements["extends"].items(): - H = getattr(hashlib, bank) - if bank not in prev["pcrs"]: - raise SystemExit(f"previous pcrs.json has no {bank} bank") - p = {int(k): v for k, v in prev["pcrs"][bank].items()} # carry everything; extend only ours - zero = "00" * H().digest_size - - def extend(pcr, digests): - v = bytes.fromhex(p.get(pcr, zero)) - for e in digests: - v = H(v + e).digest() - p[pcr] = v.hex() - - if 14 not in p: # stage0 predicted without a payload: add its measurement of this UKI - extend(14, [H(bytes.fromhex(uki_sha256)).digest()]) - elif p[14] != H(b"\0" * H().digest_size + H(bytes.fromhex(uki_sha256)).digest()).hexdigest(): - raise SystemExit(f"previous pcrs.json PCR14 ({bank}) is not stage0's measurement of this UKI") - for pcr, digests in ext.items(): - extend(int(pcr), [bytes.fromhex(d) for d in digests]) - for k in (8, 12, 13): # nothing measured: explicit, so a verifier can bind them - p.setdefault(k, zero) - extend(14, [H(bytes.fromhex(stage2_sha256)).digest()]) - out[bank] = {str(k): v for k, v in sorted(p.items())} - return {"pcrs": out} - - -def check(pred, log_path): - with open(log_path, "rb") as f: - txt = f.read().decode("latin1").replace("\r", "") - seen = {(a, int(i)): v for a, i, v in - re.findall(r"^(?:payload: )?PCR (\w+) (\d\d) ([0-9a-f]+)$", txt, re.M)} - bad = 0 - for bank, pcrs in pred["pcrs"].items(): - for i, want in pcrs.items(): - got = seen.get((bank, int(i))) - status = "ok" if got == want else ("MISSING" if got is None else "MISMATCH") - bad += status != "ok" - print(f"{bank:7} PCR{int(i):<2} {status:8} predicted {want[:16]}" - + ("" if status == "ok" or got is None else f" read {got[:16]}")) - print("ALL PREDICTED PCRS MATCH" if not bad else f"{bad} PREDICTED PCR(S) DO NOT MATCH") - return bad == 0 - - -def main(): - ap = argparse.ArgumentParser(description="stage1's PCR contribution, and the state after it") + sec = lambda s: {"pe_section": s, "of": {"artifact": UKI}} # noqa: E731 + + # (pcr, type, by, about, derivation, bytes for the local computation) + ev: list[tuple[int, str, str, str, dict[str, Any], bytes]] = [] + for s in MEASURED_ORDER: + ev.append((11, "EV_IPL", "systemd-stub", f"section name {s}", {"utf8": s, "nul": True}, + s.encode() + b"\0")) + ev.append((11, "EV_IPL", "systemd-stub", f"section {s} ({len(secs[s])} bytes)", sec(s), secs[s])) + ev.append((9, "EV_EVENT_TAG", "Linux EFI stub", "LOADED_IMAGE::LoadOptions (the .cmdline)", + {"utf16le": cmdline, "nul": True}, cmdline.encode("utf-16-le") + b"\0\0")) + ev.append((9, "EV_EVENT_TAG", "Linux EFI stub", + "Linux initrd: .initrd + systemd-stub's cpio with .osrel as .extra/os-release", + {"concat": [{"pad": 4, "of": sec(".initrd")}, + {"cpio_newc": [{"ino": 1, "mode": "40555", "name": ".extra"}, + {"ino": 2, "mode": "100444", "name": ".extra/os-release", + "data": sec(".osrel")}]}, + {"utf8": CPIO_TRAILER}]}, + stub_initrd(secs))) + for s in EBS: + ev.append((5, "EV_EFI_ACTION", "firmware", "the kernel's ExitBootServices", {"utf8": s}, s.encode())) + + events: list[dict[str, Any]] = [ + {"pcr": pcr, "type": typ, "by": by, "about": about, "derive": expr, + "digests": {b: getattr(hashlib, b)(data).hexdigest() for b in banks}} + for pcr, typ, by, about, expr, data in ev] + events.append({"pcr": 14, "type": "unlogged", "by": "stage1", + "about": "the stage2 stage1 verified and runs: H_bank(sha256(stage2))", + "derive": {"input": "stage2"}}) + return { + "schema": "pcr-replay/v1", + "name": "stage1 " + ("x86_64" if b"x86_64" in secs[".uname"] else "aarch64"), + "about": "The stage1 UKI, from stage0's handoff to the stage2 handoff: systemd-stub, the " + "kernel's EFI stub and ExitBootServices, then stage1 measuring stage2.", + "artifacts": {UKI: {"sha256": hashlib.sha256(uki).hexdigest()}}, + "entry": UKI, + "inputs": {"stage2": {"about": "sha256 of the stage2 binary stage1 runs (the next stage)", + "next_entry": True}}, + "unextended": [0, 1, 2, 3, 4, 6, 7, 8, 12, 13] + list(range(15, 24)), + "unpredictable": {"10": "IMA (the kernel's own measurement log)"}, + "events": events, + } + + +def main() -> None: + ap = argparse.ArgumentParser(description="Write stage1's PCR replay file") ap.add_argument("--uki", required=True, help="the stage1 UKI (linux.efi)") - ap.add_argument("--emit-measurements", action="store_true", - help="write only this stage's fixed extends (the release artifact)") - ap.add_argument("--stage0", help="previous state: stage0's pcrs.json") - ap.add_argument("--stage2-sha256", help="sha256 of the stage2 binary stage1 runs") + ap.add_argument("--replay", required=True, help="write the pcr-replay/v1 file here") ap.add_argument("--banks", default="sha256,sha384", help="comma-separated (default sha256,sha384)") - ap.add_argument("--out", help="write JSON here (default stdout)") - ap.add_argument("--check", metavar="LOG", help="compare against a serial log's PCR dump") a = ap.parse_args() with open(a.uki, "rb") as f: uki = f.read() - res = measurements(uki, a.banks.split(",")) - if not a.emit_measurements: - if not (a.stage0 and a.stage2_sha256): - ap.error("--stage0 and --stage2-sha256 are required unless --emit-measurements") - with open(a.stage0) as f: - res = apply(json.load(f), res, hashlib.sha256(uki).hexdigest(), a.stage2_sha256) - if a.check: - sys.exit(0 if check(res, a.check) else 1) - js = json.dumps(res, indent=2) + "\n" - if a.out: - with open(a.out, "w") as f: - f.write(js) - else: - sys.stdout.write(js) + with open(a.replay, "w") as f: + json.dump(replay_file(uki, a.banks.split(",")), f, indent=2) + f.write("\n") if __name__ == "__main__": From b86bc5a452e3e4ad6c93b5266bd7f31d6ce33593 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:23:39 +0000 Subject: [PATCH 09/10] uki: drop init_on_free=1 from the kernel cmdline (kills the TD on GCE TDX) On GCE c3 Intel TDX, init_on_free=1 kills the TD during early boot on every boot: a silent reset at varying points (ACPI parsing, the boot-time "mem auto-init: clearing system memory", the swiotlb private->shared conversion). Found by bisecting this cmdline one TDX VM per step: every combination with init_on_free=1 died (21/21 boots), every combination without it booted first time, including the full production set minus init_on_free. Cause not understood yet. init_on_alloc=1 stays, so every allocation is still zeroed; what is lost is wiping freed data at free time, which the confidential-VM memory encryption (SEV-SNP / TDX) already covers against the host. One UKI per arch for every cloud, so the option goes everywhere. Verified: GCP c3 TDX and n2d SEV-SNP full chains (stage0 -> UKI -> stage2 pcr-dump) complete; QEMU x86_64 and aarch64 full chains verify. Co-Authored-By: Claude Opus 5.5 --- tools/build-uki/build.sh | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tools/build-uki/build.sh b/tools/build-uki/build.sh index e27f38a..b49e6d5 100755 --- a/tools/build-uki/build.sh +++ b/tools/build-uki/build.sh @@ -222,14 +222,20 @@ UKI_PATH="${OUTPUT_DIR}/linux.efi" # randomize_kstack_offset=on - Randomize kernel stack offset per syscall; makes stack-based exploits less reliable # page_alloc.shuffle=1 - Randomize page allocator freelists; makes heap layout less predictable # init_on_alloc=1 - Zero-fill memory on allocation; prevents info leaks from recycled memory -# init_on_free=1 - Zero-fill memory on free; makes use-after-free exploitation harder +# +# NOT used: init_on_free=1 (zero-fill on free). On GCE Intel TDX (c3, 2026-11) it kills the TD during +# early boot every time -- a silent reset at varying points (ACPI parsing, the boot-time "mem +# auto-init: clearing system memory", swiotlb conversion); found by bisecting this cmdline, every +# other option here is fine there. Cause not understood yet. init_on_alloc=1 still zeroes every +# allocation; what is lost is wiping freed data at free time, which the confidential-VM memory +# encryption (SEV-SNP / TDX) already covers against the host. # crashkernel=0 - Reserve no memory for kdump; prevents crash dumps even if NMI is sent via cloud API # vsyscall=none - (x86_64 only) Remove legacy vsyscall page; eliminates a fixed-address ROP gadget # # NOTE: SysRq is disabled via /proc/sys/kernel/sysrq in the init script, not here. # "sysrq=" is not a valid kernel cmdline parameter (the kernel ignores it). CMDLINE_PATH="${OUTPUT_DIR}/cmdline.txt" -CMDLINE_COMMON="earlycon hibernate=no lockdown=confidentiality debugfs=off oops=panic crashkernel=0 iommu.strict=1 slab_nomerge randomize_kstack_offset=on page_alloc.shuffle=1 init_on_alloc=1 init_on_free=1 ro" +CMDLINE_COMMON="earlycon hibernate=no lockdown=confidentiality debugfs=off oops=panic crashkernel=0 iommu.strict=1 slab_nomerge randomize_kstack_offset=on page_alloc.shuffle=1 init_on_alloc=1 ro" if [ "${ARCH}" = "x86_64" ]; then # console=ttyS0: EC2 PCI UART (only serial device, gets ttyS0) # console=ttyS1: QEMU q35 ISA serial (default COM1 is ttyS0 with no backend, From 46d2bd04df00daaf0b5b774850d3c5c61c4867cd Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:08:00 +0000 Subject: [PATCH 10/10] build-uki: drop stage0-snippet.json The fill-in template predates lockboot-deploy and was wrong for stage0 (https:// URL, no "payload" wrapper), so stage0 rejected it as written. lockboot-deploy create generates the _stage1 document; the template is no longer built or uploaded. linux.efi unchanged. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 5 ++--- tools/build-uki/build.sh | 11 +---------- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4ed1306..f5bf3d1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -34,14 +34,14 @@ jobs: # Build the netboot UKI and the example-stage2 leaf for every push/PR/tag. One # `make` builds the docker build-image once (docker-build-base) and produces: - # tools/build-uki//linux.efi (+ .sha256, snippet, os-release, busybox, stage1) + # tools/build-uki//linux.efi (+ .sha256, os-release, busybox, stage1) # build//stage2 (the example leaf payload) # No workspace / sibling repos needed: vaportpm is pulled from git, stage0 is not # a build-time dependency (it netboots the UKI at runtime). - name: Build UKI + example-stage2 for ${{ matrix.arch }} run: make ${{ matrix.arch }} stage2-${{ matrix.arch }} - # UKI (stage1) track: the netboot payload + its sha256 pin + the _stage1 snippet, + # UKI (stage1) track: the netboot payload + its sha256 pin, # busybox/stage1 for the runtime image, and the example-stage2 leaf. - name: Upload UKI artifacts for ${{ matrix.arch }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -51,7 +51,6 @@ jobs: tools/build-uki/${{ matrix.arch }}/linux.efi tools/build-uki/${{ matrix.arch }}/linux.efi.sha256 tools/build-uki/${{ matrix.arch }}/stage1.replay.json - tools/build-uki/${{ matrix.arch }}/stage0-snippet.json tools/build-uki/${{ matrix.arch }}/os-release tools/build-uki/${{ matrix.arch }}/busybox tools/build-uki/${{ matrix.arch }}/stage1 diff --git a/tools/build-uki/build.sh b/tools/build-uki/build.sh index b49e6d5..20de427 100755 --- a/tools/build-uki/build.sh +++ b/tools/build-uki/build.sh @@ -312,17 +312,8 @@ echo "${UKI_SHA256} linux.efi" > "${OUTPUT_DIR}/linux.efi.sha256" python3 "${SCRIPT_DIR}/../predict-pcrs.py" --uki "${UKI_PATH}" \ --replay "${OUTPUT_DIR}/stage1.replay.json" -# Ready-to-paste _stage1 user-data snippet (sha256 admission mode). Deployers who -# want signed-mode rollforward re-sign linux.efi with their own ed25519 key. -cat > "${OUTPUT_DIR}/stage0-snippet.json" <