diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4c8e23f..f5bf3d1 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: @@ -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 @@ -50,17 +50,17 @@ jobs: path: | tools/build-uki/${{ matrix.arch }}/linux.efi tools/build-uki/${{ matrix.arch }}/linux.efi.sha256 - tools/build-uki/${{ matrix.arch }}/stage0-snippet.json + tools/build-uki/${{ matrix.arch }}/stage1.replay.json tools/build-uki/${{ matrix.arch }}/os-release tools/build-uki/${{ matrix.arch }}/busybox 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 @@ -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 @@ -96,12 +110,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/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 diff --git a/Makefile b/Makefile index 1754bc3..fbb5019 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 @@ -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 --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 -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 @@ -108,7 +109,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 @@ -269,7 +270,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 +290,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 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..20de427 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, @@ -301,17 +307,13 @@ 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" -# 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" <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 diff --git a/tools/predict-pcrs.py b/tools/predict-pcrs.py new file mode 100755 index 0000000..8654999 --- /dev/null +++ b/tools/predict-pcrs.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +# stage1's PCR replay file -- the stage1 link of the verification path. +# +# 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): +# +# 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. +# +# 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 struct +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). +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"] +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: bytes) -> dict[str, bytes]: + off = struct.unpack_from(" bytes: + return b + b"\0" * ((-len(b)) % 4) + + +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: 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, + mtime 0, then the trailer), each padded to 4 bytes (stub.c combine_initrds). No .ucode, + credentials, sysexts, confexts, .pcrsig, .pcrpkey or .profile -- the tool refuses UKIs + with those sections, and stage0 loads the UKI from memory, so there is no ESP directory + for the stub to pick credentials/sysexts up from.""" + 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) + + CPIO_TRAILER.encode()) + return _pad4(secs[".initrd"]) + cpio + + +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: + raise SystemExit(f"UKI has section(s) {bad} whose PCR9/PCR11 effect is unverified") + missing = [s for s in MEASURED_ORDER if s not in secs] + if missing: + raise SystemExit(f"UKI lacks expected section(s) {missing}") + cmdline = secs[".cmdline"].rstrip(b"\0").decode() + 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("--replay", required=True, help="write the pcr-replay/v1 file here") + ap.add_argument("--banks", default="sha256,sha384", help="comma-separated (default sha256,sha384)") + a = ap.parse_args() + with open(a.uki, "rb") as f: + uki = f.read() + with open(a.replay, "w") as f: + json.dump(replay_file(uki, a.banks.split(",")), f, indent=2) + f.write("\n") + + +if __name__ == "__main__": + main() 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 "")