diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ca6425a..d0b0510 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,8 +3,8 @@ name: build on: push: branches: [main] - # stage0 is the db-signed root of trust; tag stage0-v* to cut a release. - tags: ['stage0-v*'] + # stage0 is the db-signed root of trust; tag v* to cut a release. + tags: ['v*'] pull_request: branches: [main] workflow_dispatch: @@ -44,16 +44,20 @@ jobs: build/${{ matrix.arch }}/boot.disk build/${{ matrix.arch }}/BOOT*.EFI build/${{ matrix.arch }}/efi-vars.* + build/${{ matrix.arch }}/dbx.esl + build/${{ matrix.arch }}/dbx.auth.bin + build/${{ matrix.arch }}/pcrs.json + build/${{ matrix.arch }}/stage0.replay.json build/${{ matrix.arch }}/os-release build/${{ matrix.arch }}/*.cer build/${{ matrix.arch }}/*.guid if-no-files-found: error - # ---- Release track (tag: stage0-v*) -------------------------------------- + # ---- Release track (tag: v*) -------------------------------------- release-stage0: runs-on: ubuntu-latest needs: build - if: startsWith(github.ref, 'refs/tags/stage0-v') + if: startsWith(github.ref, 'refs/tags/v') permissions: contents: write id-token: write @@ -73,12 +77,27 @@ jobs: gh api repos/${{ github.repository }}/actions/artifacts/${ARTIFACT_ID}/zip > stage0-${arch}.zip done - - name: Attest stage0 zips + # One attestation covering the release zips, every file inside them, and the released + # harness script. Consumers can verify a zip and extract from it, or verify an extracted file + # on its own (`gh attestation verify BOOTX64.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 + qemu-test.sh) + run: | + for arch in x86_64 aarch64; do + mkdir -p "contents/$arch" && unzip -q "stage0-$arch.zip" -d "contents/$arch" + done + { + sha256sum stage0-x86_64.zip stage0-aarch64.zip + (cd tools && sha256sum qemu-test.sh) + (cd contents && find . -type f -printf '%P\n' | LC_ALL=C sort | xargs -r -d '\n' sha256sum) + } > subjects.sha256 + cat subjects.sha256 + + - name: Attest stage0 zips, their contents, and qemu-test.sh uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3.0.0 with: - subject-path: | - stage0-x86_64.zip - stage0-aarch64.zip + subject-checksums: subjects.sha256 - name: Create stage0 release uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1 @@ -94,3 +113,83 @@ jobs: prerelease: true generate_release_notes: true make_latest: true + + # ---- QEMU test-harness image (tag: v*) ----------------------------- + # End-user harness: qemu + swtpm + OVMF/AAVMF + the EC2 metadata mock, qemu-test.sh as entrypoint. + # Published with the stage0 release it ships beside: its firmware boots that release's efi-vars. + # Multi-arch so it runs identically on amd64 and arm64 hosts (KVM when host == guest arch, TCG + # otherwise). Consumers pin the digest appended to the release notes below, not the tag. + release-harness: + runs-on: ubuntu-latest + needs: release-stage0 + if: startsWith(github.ref, 'refs/tags/v') + permissions: + contents: write + packages: write + id-token: write + attestations: write + + steps: + - name: Checkout repository + uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + + - name: Set up QEMU (arm64 layers on the amd64 runner) + uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata for Docker + id: meta + uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 + with: + images: ghcr.io/${{ github.repository }}-harness + tags: | + type=ref,event=tag + flavor: | + latest=false + + - name: Build and push multi-arch harness + id: push + uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0 + with: + context: . + file: ./Dockerfile.harness + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + annotations: ${{ steps.meta.outputs.annotations }} + provenance: true + sbom: true + + - name: Attest harness image + uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3.0.0 + with: + subject-name: ghcr.io/${{ github.repository }}-harness + subject-digest: ${{ steps.push.outputs.digest }} + push-to-registry: true + + - name: Append image digest to the release notes + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.ref_name }} + DIGEST: ${{ steps.push.outputs.digest }} + run: | + gh release view "$TAG" -R "${{ github.repository }}" --json body -q .body > notes.md + { + echo + echo "### Test harness image" + echo + echo '```' + echo "ghcr.io/${{ github.repository }}-harness@${DIGEST}" + echo '```' + } >> notes.md + gh release edit "$TAG" -R "${{ github.repository }}" --notes-file notes.md 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/Dockerfile.harness b/Dockerfile.harness index 1e4fe60..a5638da 100644 --- a/Dockerfile.harness +++ b/Dockerfile.harness @@ -1,6 +1,10 @@ # Lean QEMU test-harness runtime for qemu-test.sh: no rust/sbsign/kernel toolchain, # just the qemu/swtpm layer needed to boot a disk and mock the metadata service. -FROM debian:bookworm-slim +# Pinned by digest (multi-arch index): the OVMF/AAVMF CODE images here are what boot the varstores +# tools/mkvarstore.py lays out for bookworm's pflash geometry, so the firmware must not drift. +# Published multi-arch (linux/amd64 + linux/arm64) to ghcr on stage0-v* tags, alongside the +# stage0 release it was built with. +FROM debian:bookworm-slim@sha256:99c0b25c46d0214d5a2091092e7908907dcaecd6a962cde0ac700acee222b6f3 RUN apt-get -qq update && \ apt-get install -y --no-install-recommends \ @@ -22,15 +26,23 @@ RUN apt-get -qq update && \ tcpdump && \ rm -rf /var/lib/apt/lists/* -# Pre-bake the EC2 metadata mock so make/CI runs don't download into the -# bind-mounted repo. qemu-test.sh checks EC2_MOCK_CACHE (set to /opt by the -# Makefile) before falling back to its own download. +# Pre-bake the EC2 metadata mock for the image's arch so make/CI runs don't download into the +# bind-mounted repo. qemu-test.sh checks EC2_MOCK_CACHE (set to /opt by the Makefile) before +# falling back to its own download; hashes match the ones in qemu-test.sh. +ARG TARGETARCH ARG AEMM_VERSION=v1.13.0 -ARG AEMM_SHA256=4f89ddc71ac53ce540bda1f9c340526d558eed8e41349761f2798acf1b254950 -RUN curl -fsSL -o /opt/ec2-metadata-mock-linux-amd64 \ - "https://github.com/aws/amazon-ec2-metadata-mock/releases/download/${AEMM_VERSION}/ec2-metadata-mock-linux-amd64" && \ - echo "${AEMM_SHA256} /opt/ec2-metadata-mock-linux-amd64" | sha256sum -c - && \ - chmod +x /opt/ec2-metadata-mock-linux-amd64 +ARG AEMM_SHA256_amd64=4f89ddc71ac53ce540bda1f9c340526d558eed8e41349761f2798acf1b254950 +ARG AEMM_SHA256_arm64=9dae5b5849365dbaa133309da81f49bafe94ec0aa7e6b05ce3eb7a8f151c2217 +RUN case "${TARGETARCH}" in \ + amd64) sha="${AEMM_SHA256_amd64}" ;; \ + arm64) sha="${AEMM_SHA256_arm64}" ;; \ + *) echo "unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \ + esac && \ + f=/opt/ec2-metadata-mock-linux-${TARGETARCH} && \ + curl -fsSL -o "$f" \ + "https://github.com/aws/amazon-ec2-metadata-mock/releases/download/${AEMM_VERSION}/ec2-metadata-mock-linux-${TARGETARCH}" && \ + echo "${sha} $f" | sha256sum -c - && \ + chmod +x "$f" # The mock is baked at /opt; point the entrypoint script at it by default. ENV EC2_MOCK_CACHE=/opt diff --git a/Makefile b/Makefile index 7ad2905..dd38204 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,9 @@ build/%/stage0.efi build/%/payload.efi build/%/boot.disk STAGE0_DIR = crates/stage0 +# STAGE0_FEATURES=verbose: debug build of stage0 (DNS/TCP/HTTP step logging). Changes the +# measured binary -- debug only, never a release. +STAGE0_FEATURES ?= # Default to the host architecture (uname -m gives x86_64 / aarch64 on Linux), so # bare `make`, `make boot`, `make test` "just work". Override with ARCH=... or by @@ -35,8 +38,22 @@ docker-build-harness: # ---- Secure Boot keys: stage0's own snakeoil PK/KEK/db (regenerated per build) ---- # The pattern rule generates the whole set into build/keys via tools/gen-keys.sh; # release.pem (below) is matched by its explicit rule instead. +# +# HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY=1 -- DEV ITERATION ONLY: reuse the existing build/keys +# instead of re-minting them, so a rebuilt boot.disk still matches a cloud image/varstore already +# enrolled with these keys (fast driver/debug loops: swap the disk, keep the keys). Never for a +# release or any published image: the keys then outlive a single build. Refused under CI. +ifeq ($(HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY),1) +ifneq ($(CI),) +$(error HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY is refused under CI) +endif +$(warning !!! HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY=1: REUSING existing Secure Boot keys in build/keys -- DEV ONLY, never release/publish this build !!!) +build/keys/%: + @test -f $@ || { echo "HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY: $@ missing -- build once without it to mint keys" >&2; exit 1; } +else build/keys/%: docker-build-base $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) ./tools/gen-keys.sh build/keys +endif # ---- stage0-sign: this repo's standalone host-side signer (ed25519 keygen + domain-separated # signatures), so stage0 builds + tests without stage1's deploy tool. Built + run in the container. @@ -53,17 +70,17 @@ sign-test: docker-build-base # ---- CI gate: fmt + clippy + unit tests across all crates (what the branch ruleset requires) ---- # stage0 is not one cargo workspace: 4 independent crates in two target families. The EFI crates -# (ena, stage0, stage0-test-payload) are no_std UEFI and not host-testable -> fmt + clippy on the +# (ena, gvnic, stage0, stage0-test-payload) are no_std UEFI and not host-testable -> fmt + clippy on the # UEFI target; the host signer (stage0-sign) also runs its unit tests (incl. the golden vector). -UEFI_CRATES := ena stage0 stage0-test-payload +UEFI_CRATES := ena gvnic stage0 stage0-test-payload HOST_CRATES := stage0-sign .PHONY: ci fmt-fix fmt-fix: docker-build-base ## Apply rustfmt across all crates (no --check) $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) bash -c '\ for c in $(UEFI_CRATES) $(HOST_CRATES); do cargo fmt --manifest-path crates/$$c/Cargo.toml; done' -# ena.efi is include_bytes!'d by the stage0 crate, so it must exist before clippy/check can +# ena.efi + gvnic.efi are include_bytes!'d by the stage0 crate, so they must exist before clippy/check can # compile it (a clean CI checkout has no build/ artifacts; a warm local tree hid this). -ci: docker-build-base build/x86_64/ena.efi +ci: docker-build-base build/x86_64/ena.efi build/x86_64/gvnic.efi $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) bash -c '\ set -e; rustup target add x86_64-unknown-uefi x86_64-unknown-linux-musl; \ for c in $(UEFI_CRATES) $(HOST_CRATES); do \ @@ -93,14 +110,22 @@ build/%/ena.efi: docker-build-base $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path crates/ena/Cargo.toml --target $*-unknown-uefi && cp -v crates/ena/target/$*-unknown-uefi/release/ena.efi $@" +# ---- Build the gvnic.efi UEFI driver (embedded into stage0 for GCP/gVNIC netboot) ---- +# Same shape as ena.efi, for the Google Virtual NIC: GCP's UEFI firmware ships no gVNIC +# driver, and GCP requires gVNIC for Confidential VMs and Arm. Embedded unconditionally. +.PRECIOUS: build/%/gvnic.efi +build/%/gvnic.efi: docker-build-base + $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ + bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path crates/gvnic/Cargo.toml --target $*-unknown-uefi && cp -v crates/gvnic/target/$*-unknown-uefi/release/gvnic.efi $@" + # ---- Build the stage0 UEFI binary ---- # mkdir runs inside the container (as DOCKER_SAMEUSER) so the output dir is owned # by the build user, not by the host caller (which is root under `gh act`). -# stage0 include_bytes! build/$*/ena.efi unconditionally (one measured unit), so the -# ena.efi prerequisite must be built first; nothing extra to pass on the command line. -build/%/stage0.efi: build/%/ena.efi docker-build-base +# stage0 include_bytes! build/$*/{ena,gvnic}.efi unconditionally (one measured unit), so the +# driver prerequisites must be built first; nothing extra to pass on the command line. +build/%/stage0.efi: build/%/ena.efi build/%/gvnic.efi docker-build-base $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ - bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path $(STAGE0_DIR)/Cargo.toml --target $*-unknown-uefi && cp -v $(STAGE0_DIR)/target/$*-unknown-uefi/release/stage0.efi $@" + bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path $(STAGE0_DIR)/Cargo.toml --target $*-unknown-uefi $(if $(STAGE0_FEATURES),--features $(STAGE0_FEATURES)) && cp -v $(STAGE0_DIR)/target/$*-unknown-uefi/release/stage0.efi $@" # ---- Assemble + db-sign the boot disk (privileged: losetup/mount) ---- build/%/boot.disk: build/%/stage0.efi build/keys/db.crt @@ -132,9 +157,10 @@ build/%/args.json.sig: build/keys/release.pem | sign-bin # ---- QEMU harness: the lean harness image bakes qemu-test.sh as its entrypoint # (and the EC2_MOCK_CACHE + iptables-ack env), so we just append CLI args. ---- +# HARNESS_TIMEOUT= bounds each boot (qemu-test.sh --timeout); unset = no limit. STAGE0_QEMU = $(DOCKER_RUN) $(DOCKER_OPT_KVM) \ --cap-add=NET_ADMIN --device=/dev/net/tun \ - $(HARNESS_IMAGE) + $(HARNESS_IMAGE) $(if $(HARNESS_TIMEOUT),--timeout $(HARNESS_TIMEOUT)) # Boot stage0 under QEMU. Serves a staging dir (so payload, signed args, and a signed # manifest are all served uniformly at http://SERVE_HOST/) and regenerates the @@ -220,6 +246,17 @@ smoke-boot-%: build/%/boot.disk build/%/payload.efi build/%/args.json.sig docker smoke-boot: smoke-boot-$(ARCH) +# ---- Self-test: stage0's part of the workspace `make selftest` (PASS/FAIL, non-zero on FAIL). +# The boot-test matrix above, with every boot time-bounded so a hang fails instead of blocking. +# One bound for both arches (~3x the slowest measured boot; aarch64 is TCG-emulated but fast). +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-%: + $(MAKE) --no-print-directory smoke-boot-$* HARNESS_TIMEOUT=$(SELFTEST_TIMEOUT_$*) + # Arch-less convenience forms target the host architecture ($(ARCH)). .PHONY: build boot test build: build-$(ARCH) diff --git a/crates/gvnic/Cargo.lock b/crates/gvnic/Cargo.lock new file mode 100644 index 0000000..5c7ef15 --- /dev/null +++ b/crates/gvnic/Cargo.lock @@ -0,0 +1,142 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "gvnic" +version = "0.1.0" +dependencies = [ + "uefi", + "uefi-raw", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "ptr_meta" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b9a0cf95a1196af61d4f1cbdab967179516d9a4a4312af1f31948f8f6224a79" +dependencies = [ + "ptr_meta_derive", +] + +[[package]] +name = "ptr_meta_derive" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7347867d0a7e1208d93b46767be83e2b8f978c3dad35f775ac8d8847551d6fe1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "ucs2" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba" +dependencies = [ + "bit_field", +] + +[[package]] +name = "uefi" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7569ceafb898907ff764629bac90ac24ba4203c38c33ef79ee88c74aa35b11" +dependencies = [ + "bitflags", + "cfg-if", + "log", + "ptr_meta", + "ucs2", + "uefi-macros", + "uefi-raw", + "uguid", +] + +[[package]] +name = "uefi-macros" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3dad47b3af8f99116c0f6d4d669c439487d9aaf1c8d9480d686cda6f3a8aa23" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "uefi-raw" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cad96b8baaf1615d3fdd0f03d04a0b487d857c1b51b19dcbfe05e2e3c447b78" +dependencies = [ + "bitflags", + "uguid", +] + +[[package]] +name = "uguid" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab14ea9660d240e7865ce9d54ecdbd1cd9fa5802ae6f4512f093c7907e921533" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" diff --git a/crates/gvnic/Cargo.toml b/crates/gvnic/Cargo.toml new file mode 100644 index 0000000..10e48e9 --- /dev/null +++ b/crates/gvnic/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "gvnic" +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" +description = "UEFI SimpleNetworkProtocol driver for the Google Virtual NIC (gVNIC / gve)" + +# Standalone workspace like ena/stage0: only builds for *-unknown-uefi, kept out of any +# parent workspace. Produces `gvnic.efi`, a resident UEFI boot-service driver that stage0 +# loads at runtime (GCP's UEFI firmware ships no gVNIC driver, and GCP requires gVNIC for +# Confidential VMs and Arm). build.rs forces the EFI_BOOT_SERVICE_DRIVER PE subsystem so +# the image stays resident. +[workspace] + +[features] +# Step-by-step probe/AQ logging (clock.rs vlog!); default prints errors + one summary line. +verbose = [] + +[dependencies] +uefi = { version = "0.35", features = ["alloc", "global_allocator", "panic_handler"] } +uefi-raw = "0.11" + +[profile.release] +opt-level = "s" +lto = true +codegen-units = 1 +panic = "abort" diff --git a/crates/gvnic/build.rs b/crates/gvnic/build.rs new file mode 100644 index 0000000..9e1b3d5 --- /dev/null +++ b/crates/gvnic/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Force the PE subsystem to EFI Boot Service Driver (11) instead of the target's +//! default EFI Application (10). A UEFI *application* is unloaded the moment its +//! entry point returns, which would tear down our DriverBinding; a boot-service +//! driver stays resident. lld-link takes the last `/subsystem`, and this link-arg +//! is emitted after the target's, so it wins. Done here (not .cargo/config.toml) so +//! it travels with the crate regardless of where cargo is invoked. +fn main() { + println!("cargo::rustc-link-arg-bins=/subsystem:efi_boot_service_driver"); +} diff --git a/crates/gvnic/src/binding.rs b/crates/gvnic/src/binding.rs new file mode 100644 index 0000000..110ea3c --- /dev/null +++ b/crates/gvnic/src/binding.rs @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! `EFI_DRIVER_BINDING_PROTOCOL` for gVNIC. `supported()` is the gate that keeps the +//! driver inert on non-GCP platforms: it returns `SUCCESS` only for PCI `1ae0:0042`. +//! `start()` brings the device up; `stop()` is stubbed (as in ena). + +use alloc::boxed::Box; + +use uefi::boot; +use uefi::{Handle, Status}; +use uefi_raw::protocol::device_path::DevicePathProtocol; +use uefi_raw::protocol::driver::DriverBindingProtocol; +use uefi_raw::Handle as RawHandle; + +use crate::device::{GVNIC_DEVICE_ID, GVNIC_VENDOR_ID}; +use crate::pci::PciIo; + +/// Build and install the DriverBinding on our own image handle. The instance must +/// outlive this function (the firmware keeps the pointer), so it is leaked. +pub fn install() -> uefi::Result<()> { + let image = boot::image_handle(); + let binding = Box::new(DriverBindingProtocol { + supported, + start, + stop, + version: 0x10, + image_handle: image.as_ptr(), + driver_binding_handle: image.as_ptr(), + }); + let ptr = Box::into_raw(binding); + unsafe { + boot::install_protocol_interface(Some(image), &DriverBindingProtocol::GUID, ptr.cast())?; + } + Ok(()) +} + +/// Return SUCCESS only for a gVNIC controller. Opens PciIo with GetProtocol (a +/// non-owning test open) and checks vendor + device id. +unsafe extern "efiapi" fn supported( + _this: *const DriverBindingProtocol, + controller_handle: RawHandle, + _remaining: *const DevicePathProtocol, +) -> Status { + let Some(controller) = (unsafe { Handle::from_ptr(controller_handle) }) else { + return Status::UNSUPPORTED; + }; + let params = boot::OpenProtocolParams { + handle: controller, + agent: boot::image_handle(), + controller: None, + }; + let pci = match unsafe { + boot::open_protocol::(params, boot::OpenProtocolAttributes::GetProtocol) + } { + Ok(p) => p, + Err(_) => return Status::UNSUPPORTED, + }; + // Gate on vendor AND device id: other Google virtual devices share vendor 0x1ae0. + match pci.vendor_device() { + Ok((GVNIC_VENDOR_ID, GVNIC_DEVICE_ID)) => Status::SUCCESS, + _ => Status::UNSUPPORTED, + } +} + +/// Bind the gVNIC controller: open PciIo BY_DRIVER (claiming the device), probe it +/// (reset + admin queue + describe/configure + QPLs + one TX/RX queue pair), then install +/// SNP on the handle. EDK2's MNP/IP4/TCP4/UDP4 binds on top, producing IP4_CONFIG2 for stage0. +unsafe extern "efiapi" fn start( + _this: *const DriverBindingProtocol, + controller_handle: RawHandle, + _remaining: *const DevicePathProtocol, +) -> Status { + let Some(controller) = (unsafe { Handle::from_ptr(controller_handle) }) else { + return Status::UNSUPPORTED; + }; + let params = boot::OpenProtocolParams { + handle: controller, + agent: boot::image_handle(), + controller: Some(controller), + }; + let pci = match unsafe { + boot::open_protocol::(params, boot::OpenProtocolAttributes::ByDriver) + } { + Ok(p) => p, + Err(e) => { + // ALREADY_STARTED is expected: connect_all_controllers reaches the NIC twice (via + // the parent bus and directly), so start() is invoked a second time once we + // already manage the device. That is benign; only log genuine failures. + if e.status() != Status::ALREADY_STARTED { + log!("start(): open PciIo BY_DRIVER failed: {:?}", e.status()); + } + return e.status(); + } + }; + vlog!("start(): probing gVNIC device..."); + // On any error, `pci` drops here and closes the BY_DRIVER open (releasing the device). + let nic = match unsafe { crate::device::probe(&pci.0) } { + Ok(nic) => nic, + Err(e) => { + log!("probe FAILED: {:?}", e); + return e; + } + }; + // Keep PciIo open for the device's lifetime (probe stored the raw pointer in `nic`). + core::mem::forget(pci); + match crate::snp::install(controller, nic) { + Ok(()) => { + vlog!("SNP installed on controller; networking should come up"); + Status::SUCCESS + } + Err(e) => { + log!("SNP install failed: {:?}", e.status()); + e.status() + } + } +} + +/// Unbind: shutdown queues, uninstall SNP, free DMA, close PciIo. Stubbed. +unsafe extern "efiapi" fn stop( + _this: *const DriverBindingProtocol, + _controller_handle: RawHandle, + _number_of_children: usize, + _child_handle_buffer: *const RawHandle, +) -> Status { + Status::UNSUPPORTED +} diff --git a/crates/gvnic/src/clock.rs b/crates/gvnic/src/clock.rs new file mode 100644 index 0000000..e1d8ade --- /dev/null +++ b/crates/gvnic/src/clock.rs @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Log lines on stage0's timeline: `[ S.mmm] gvnic: ...`, the same stamp as stage0's `slog!`. +//! +//! stage0 passes its epoch as this image's LoadOptions: the free-running cycle counter's value +//! at its t = 0 and its calibrated cycles per millisecond, each a little-endian u64 (stage0 +//! `timing::epoch`). This driver reads the same counter (x86_64 `rdtsc`, aarch64 +//! `cntvct_el0`), so no second calibration. Without an epoch the stamp is `[ ?.???]`. + +use core::sync::atomic::{AtomicU64, Ordering}; + +static START: AtomicU64 = AtomicU64::new(0); +static CYCLES_PER_MS: AtomicU64 = AtomicU64::new(0); + +/// Take the epoch from this image's LoadOptions (16 bytes; anything else leaves it unset). +pub fn init(load_options: Option<&[u8]>) { + if let Some(o) = load_options { + if o.len() == 16 { + let le = |b: &[u8]| u64::from_le_bytes(b.try_into().unwrap_or([0; 8])); + START.store(le(&o[..8]), Ordering::Relaxed); + CYCLES_PER_MS.store(le(&o[8..]), Ordering::Relaxed); + } + } +} + +#[cfg(target_arch = "x86_64")] +#[inline] +fn raw() -> u64 { + // SAFETY: `rdtsc` is unprivileged and always present on x86_64 UEFI hosts. + unsafe { core::arch::x86_64::_rdtsc() } +} + +#[cfg(target_arch = "aarch64")] +#[inline] +fn raw() -> u64 { + let v: u64; + // SAFETY: CNTVCT_EL0 is the EL0-readable virtual counter; the read is side-effect free. + unsafe { core::arch::asm!("mrs {}, cntvct_el0", out(reg) v, options(nomem, nostack)) }; + v +} + +/// The current stamp, formatted like stage0's (`{:>5}.{:03}` seconds). +pub struct Stamp; + +impl core::fmt::Display for Stamp { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let per_ms = CYCLES_PER_MS.load(Ordering::Relaxed); + if per_ms == 0 { + return write!(f, "{:>5}.???", "?"); + } + let ms = raw().wrapping_sub(START.load(Ordering::Relaxed)) / per_ms; + write!(f, "{:>5}.{:03}", ms / 1000, ms % 1000) + } +} + +/// Always printed: errors, and the one-line probe summary. +macro_rules! log { + ($($a:tt)*) => { + uefi::println!("[{}] gvnic: {}", $crate::clock::Stamp, format_args!($($a)*)) + }; +} + +/// Step-by-step detail, compiled in only with the `verbose` feature. +#[cfg(feature = "verbose")] +macro_rules! vlog { + ($($a:tt)*) => { log!($($a)*) }; +} + +/// No-op form; still references the arguments so they don't trip unused warnings. +#[cfg(not(feature = "verbose"))] +macro_rules! vlog { + ($($a:tt)*) => {{ + let _ = format_args!($($a)*); + }}; +} diff --git a/crates/gvnic/src/device.rs b/crates/gvnic/src/device.rs new file mode 100644 index 0000000..4a742f5 --- /dev/null +++ b/crates/gvnic/src/device.rs @@ -0,0 +1,1004 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Device protocol derived from the Linux `gve` driver (drivers/net/ethernet/google/gve), +// Copyright (C) 2015-2024 Google LLC, licensed `(GPL-2.0 OR MIT)`; used here under the MIT +// terms. Reference: torvalds/linux @ 45e0a63f9c86. Section numbers (`spec §N`) refer to the +// extracted protocol notes for that tree; `gve_*.{c,h}:line` cite the reference directly. + +//! gVNIC hardware layer: the bare minimum to push and poll Ethernet frames, enough for +//! EDK2's IP4/TCP4 stack to netboot over it. +//! +//! Queue format GQI_QPL ("registered pages"), ONE TX + ONE RX queue, polled (no +//! interrupts), no offloads, no RSS. Everything device-facing is BIG-endian: BAR0 +//! registers, admin-queue commands, descriptors, doorbells, event counters. +//! +//! BAR0 (registers) goes through `PciIo.Mem`; BAR2 (queue doorbells) is written with direct +//! stores to the BAR's host address, as every reference driver does (Linux iowrite32be, +//! FreeBSD bus_write_4, DPDK rte_write32, iPXE's EFI build writel). GCE backs the doorbell BAR +//! as memory rather than trapping MMIO: under Intel TDX the firmware's `PciIo.Mem` path is a +//! TDVMCALL MMIO hypercall that never reaches it (writes dropped, reads 0), while a direct store +//! through the firmware's shared MMIO mapping does. +//! +//! Flow (probe): PCI enable -> version string -> register admin queue (by PCI revision) -> +//! VERIFY_DRIVER_COMPATIBILITY -> DESCRIBE_DEVICE (+ option TLVs) -> +//! CONFIGURE_DEVICE_RESOURCES -> allocate rings + QPLs -> REGISTER_PAGE_LIST (TX, RX) -> +//! CREATE_TX_QUEUE -> CREATE_RX_QUEUE -> RX doorbell -> link poll -> ExitBootServices hook. +//! +//! Data path: TX copies each frame into a fixed 2 KiB slot of the TX QPL and posts ONE +//! packet descriptor (seg_addr = QPL byte offset); completions come from the TX event +//! counter. RX buffers are QPL pages (slot i = page i, never flipped); a descriptor is +//! ready when its 3-bit seqno matches the expected one (1..7); the frame starts 2 bytes in. +//! +//! All DMA memory is `PciIo.AllocateBuffer` + `Map(CommonBuffer)`, so it is also correct +//! under memory encryption (SEV), where it must be shared with the host. + +// Several fields exist only to keep device-visible buffers alive (never read back), and a +// few protocol constants are kept for reference. +#![allow(dead_code)] + +use alloc::vec; +use alloc::vec::Vec; +use core::ffi::c_void; +use core::ptr::NonNull; +use core::sync::atomic::{fence, Ordering}; + +use uefi::boot::{self, EventType, Tpl}; +use uefi::{Event, Status}; + +use crate::pci::{PciAttrOp, PciIoProtocol, PciMapOp, PciWidth, PCI_ATTR_BUS_MASTER}; + +/// PCI identity (gve.h:26,29: PCI_VENDOR_ID_GOOGLE / PCI_DEV_ID_GVNIC). +pub const GVNIC_VENDOR_ID: u16 = 0x1ae0; +pub const GVNIC_DEVICE_ID: u16 = 0x0042; + +/// BAR0 = register block, BAR2 = doorbells (array of BE32, index i at byte 4*i). +const REG_BAR: u8 = 0; +const DB_BAR: u8 = 2; + +/// `struct gve_registers` offsets (gve_register.h:11-24). +mod regs { + pub const DEVICE_STATUS: u64 = 0x00; + pub const DRIVER_STATUS: u64 = 0x04; + pub const MAX_TX_QUEUES: u64 = 0x08; + pub const MAX_RX_QUEUES: u64 = 0x0c; + pub const ADMINQ_PFN: u64 = 0x10; + pub const ADMINQ_DOORBELL: u64 = 0x14; + pub const ADMINQ_EVENT_COUNTER: u64 = 0x18; + pub const DRIVER_VERSION: u64 = 0x1f; + pub const ADMINQ_BASE_HI: u64 = 0x20; + pub const ADMINQ_BASE_LO: u64 = 0x24; + pub const ADMINQ_LENGTH: u64 = 0x28; +} + +/// device_status bits (gve_register.h:26-31). +const DEV_STS_RESET_REQUESTED: u32 = 1 << 1; +const DEV_STS_LINK_UP: u32 = 1 << 2; +const DEV_STS_IS_RESET: u32 = 1 << 4; +/// driver_status bits (gve_register.h:33-36). +const DRV_STS_RUN: u32 = 1 << 0; +const DRV_STS_RESET: u32 = 1 << 1; + +/// Admin opcodes (gve_adminq.h:13-35). +const OP_DESCRIBE_DEVICE: u32 = 0x1; +const OP_CONFIGURE_DEVICE_RESOURCES: u32 = 0x2; +const OP_REGISTER_PAGE_LIST: u32 = 0x3; +const OP_CREATE_TX_QUEUE: u32 = 0x5; +const OP_CREATE_RX_QUEUE: u32 = 0x6; +const OP_UNREGISTER_PAGE_LIST: u32 = 0x4; +const OP_DESTROY_TX_QUEUE: u32 = 0x7; +const OP_DESTROY_RX_QUEUE: u32 = 0x8; +const OP_DECONFIGURE_DEVICE_RESOURCES: u32 = 0x9; +/// TX QPL id (Linux's: TX QPLs are numbered from 0). +const TX_QPL_ID: u32 = 0; +const OP_VERIFY_DRIVER_COMPATIBILITY: u32 = 0xf; + +/// Admin status codes (gve_adminq.h:47-66). +const AQ_PASSED: u32 = 0x0000_0001; +const AQ_UNIMPLEMENTED: u32 = 0xffff_fffe; + +/// Device-option ids (gve_adminq.h:192-204). +const OPT_GQI_RAW_ADDRESSING: u16 = 0x1; +const OPT_GQI_RDA: u16 = 0x2; +const OPT_GQI_QPL: u16 = 0x3; +const OPT_DQO_RDA: u16 = 0x4; +const OPT_DQO_QPL: u16 = 0x7; +const OPT_JUMBO_FRAMES: u16 = 0x8; +/// GVE_SUP_JUMBO_FRAMES_MASK (gve_adminq.h:222). +const SUP_JUMBO_FRAMES: u32 = 1 << 2; + +/// CONFIGURE_DEVICE_RESOURCES queue_format (gve.h:749-755). +const QUEUE_FORMAT_GQI_QPL: u8 = 2; +/// VERIFY_DRIVER_COMPATIBILITY capability bit 0 = gqi_qpl (gve_adminq.h:233-258). +const DRIVER_CAP_GQI_QPL: u64 = 1 << 0; +const DRIVER_INFO_LEN: usize = 304; // sizeof(struct gve_driver_info) + +/// Version string, written byte-by-byte to DRIVER_VERSION (gve_main.c:32-40, 2631-2646). +const VERSION_STRING: &[u8] = b"GVE-1.0.0\n"; + +/// Polling limits (gve_adminq.c:15-17): 20 ms steps; 100 for a command, 500 for a release. +const SLEEP_MS: usize = 20; +const CMD_CHECKS: usize = 100; +const RELEASE_CHECKS: usize = 500; +const LINK_CHECKS: usize = 250; // 5 s (Linux does not wait; we log the outcome) + +const PAGE: usize = 4096; +const AQ_SLOTS: u32 = (PAGE / 64) as u32; // 64 slots of 64 bytes +const BUF: usize = 2048; // RX packet_buffer_size and TX slot size (gve.h:62) +const RX_PAD: usize = 2; // GVE_RX_PAD (gve_desc.h:79-82) +const ETH_HLEN: usize = 14; +/// Largest MTU whose frame (+ RX pad) fits one 2 KiB buffer: keeps RX single-fragment and +/// TX single-descriptor (spec §9). +const MTU_CAP: u32 = (BUF - ETH_HLEN - RX_PAD) as u32; +const MTU_MIN: u32 = 68; + +/// RX descriptor flags_seq (host order after BE16 decode; gve_desc.h:109-119). +const RXF_ERR: u16 = 1 << (3 + 8); +const RXF_PKT_CONT: u16 = 1 << (3 + 10); + +const EFI_BOOT_SERVICES_DATA: u32 = 4; +const EFI_ALLOCATE_ANY_PAGES: u32 = 0; +/// EFI_PCI_IO_ATTRIBUTE_MEMORY. +const PCI_ATTR_MEMORY: u64 = 0x0200; + +fn delay_ms(ms: usize) { + boot::stall(ms * 1000); +} + +// ---- big-endian field access in DMA memory (byte-wise, volatile) --------------- + +unsafe fn put_be16(p: *mut u8, off: usize, v: u16) { + for (i, b) in v.to_be_bytes().iter().enumerate() { + p.add(off + i).write_volatile(*b); + } +} +unsafe fn put_be32(p: *mut u8, off: usize, v: u32) { + for (i, b) in v.to_be_bytes().iter().enumerate() { + p.add(off + i).write_volatile(*b); + } +} +unsafe fn put_be64(p: *mut u8, off: usize, v: u64) { + for (i, b) in v.to_be_bytes().iter().enumerate() { + p.add(off + i).write_volatile(*b); + } +} +unsafe fn get_be16(p: *const u8, off: usize) -> u16 { + u16::from_be_bytes([p.add(off).read_volatile(), p.add(off + 1).read_volatile()]) +} +unsafe fn get_be32(p: *const u8, off: usize) -> u32 { + let mut b = [0u8; 4]; + for (i, x) in b.iter_mut().enumerate() { + *x = p.add(off + i).read_volatile(); + } + u32::from_be_bytes(b) +} +unsafe fn get_be64(p: *const u8, off: usize) -> u64 { + let mut b = [0u8; 8]; + for (i, x) in b.iter_mut().enumerate() { + *x = p.add(off + i).read_volatile(); + } + u64::from_be_bytes(b) +} + +// Command buffers are plain [u8; 64] built on the stack, then copied into the AQ slot. +fn cmd_new(opcode: u32) -> [u8; 64] { + let mut c = [0u8; 64]; + c[0..4].copy_from_slice(&opcode.to_be_bytes()); + c +} +fn cmd_u8(c: &mut [u8; 64], off: usize, v: u8) { + c[off] = v; +} +fn cmd_be16(c: &mut [u8; 64], off: usize, v: u16) { + c[off..off + 2].copy_from_slice(&v.to_be_bytes()); +} +fn cmd_be32(c: &mut [u8; 64], off: usize, v: u32) { + c[off..off + 4].copy_from_slice(&v.to_be_bytes()); +} +fn cmd_be64(c: &mut [u8; 64], off: usize, v: u64) { + c[off..off + 8].copy_from_slice(&v.to_be_bytes()); +} + +// ---- MMIO (BAR0 registers, BAR2 doorbells) via PciIo.Mem; device is big-endian --- + +unsafe fn mmio_read32(pci: &PciIoProtocol, bar: u8, off: u64) -> u32 { + let mut v: u32 = 0; + let st = (pci.mem.read)(pci, PciWidth::U32, bar, off, 1, (&mut v as *mut u32).cast()); + if !st.is_success() { + log!(" MMIO read bar{bar}@0x{off:02x} failed: {st:?}"); + } + u32::from_be(v) +} +unsafe fn mmio_write32(pci: &PciIoProtocol, bar: u8, off: u64, val: u32) { + let mut v = val.to_be(); + let st = (pci.mem.write)(pci, PciWidth::U32, bar, off, 1, (&mut v as *mut u32).cast()); + if !st.is_success() { + log!(" MMIO write bar{bar}@0x{off:02x} failed: {st:?}"); + } +} +unsafe fn mmio_write16(pci: &PciIoProtocol, bar: u8, off: u64, val: u16) { + let mut v = val.to_be(); + let st = (pci.mem.write)(pci, PciWidth::U16, bar, off, 1, (&mut v as *mut u16).cast()); + if !st.is_success() { + log!(" MMIO write16 bar{bar}@0x{off:02x} failed: {st:?}"); + } +} +unsafe fn mmio_write8(pci: &PciIoProtocol, bar: u8, off: u64, val: u8) { + let mut v = val; + let _ = (pci.mem.write)(pci, PciWidth::U8, bar, off, 1, (&mut v as *mut u8).cast()); +} +unsafe fn reg_rd(pci: &PciIoProtocol, off: u64) -> u32 { + mmio_read32(pci, REG_BAR, off) +} +unsafe fn reg_wr(pci: &PciIoProtocol, off: u64, v: u32) { + mmio_write32(pci, REG_BAR, off, v) +} +/// Ring doorbell `db_index` (BAR2 + 4*db_index) with a free-running count. Release fence +/// first, so every descriptor/payload store is visible before the device is told. +unsafe fn doorbell(db: *mut u8, db_index: u32, value: u32) { + fence(Ordering::Release); + (db.add(4 * db_index as usize) as *mut u32).write_volatile(value.to_be()); +} + +/// Host address and length of memory BAR `bar`, from `PciIo.GetBarAttributes` (its first +/// memory descriptor; host = AddrRangeMin - AddrTranslationOffset, EDK2 TO_HOST_ADDRESS). +unsafe fn bar_host_range(pci: &PciIoProtocol, bar: u8) -> Result<(u64, u64), Status> { + let mut res: *mut c_void = core::ptr::null_mut(); + let st = (pci.get_bar_attributes)(pci, bar, core::ptr::null_mut(), &mut res); + if !st.is_success() || res.is_null() { + log!("GetBarAttributes(bar{bar}) failed: {st:?}"); + return Err(if st.is_success() { + Status::DEVICE_ERROR + } else { + st + }); + } + // ACPI QWORD address-space descriptor (0x8A): ResType @3, AddrRangeMin @14, + // AddrTranslationOffset @30, AddrLen @38 (packed). + let p = res as *const u8; + let rd = |o: usize| (p.add(o) as *const u64).read_unaligned(); + let found = (*p == 0x8a && *p.add(3) == 0).then(|| (rd(14).wrapping_sub(rd(30)), rd(38))); + let _ = boot::free_pool(NonNull::new_unchecked(res as *mut u8)); + found.ok_or_else(|| { + log!("bar{bar}: no memory descriptor"); + Status::DEVICE_ERROR + }) +} + +unsafe fn cfg_r8(pci: &PciIoProtocol, off: u32) -> u8 { + let mut v: u8 = 0; + let _ = (pci.pci.read)(pci, PciWidth::U8, off, 1, (&mut v as *mut u8).cast()); + v +} +unsafe fn cfg_r16(pci: &PciIoProtocol, off: u32) -> u16 { + let mut v: u16 = 0; + let _ = (pci.pci.read)(pci, PciWidth::U16, off, 1, (&mut v as *mut u16).cast()); + v +} +unsafe fn cfg_w16(pci: &PciIoProtocol, off: u32, val: u16) { + let mut v = val; + let _ = (pci.pci.write)(pci, PciWidth::U16, off, 1, (&mut v as *mut u16).cast()); +} + +/// MSI-X table size (Message Control bits[10:0] + 1), or 0 if there is no MSI-X capability. +/// Read only: MSI-X stays DISABLED (we poll); the count sizes the notification blocks the +/// device expects in CONFIGURE_DEVICE_RESOURCES, exactly as Linux computes it. +unsafe fn msix_table_size(pci: &PciIoProtocol) -> u32 { + let mut off = (cfg_r8(pci, 0x34) & 0xfc) as u32; // capabilities pointer + let mut guard = 0; + while off != 0 && guard < 48 { + if cfg_r8(pci, off) == 0x11 { + return (cfg_r16(pci, off + 2) & 0x7ff) as u32 + 1; + } + off = (cfg_r8(pci, off + 1) & 0xfc) as u32; + guard += 1; + } + 0 +} + +// ---- DMA (common buffer via PciIo) ------------------------------------------------- + +/// A coherent DMA region: host pointer + device bus address. Never freed (the device owns +/// it for the controller's lifetime; after a reset nothing references it). +struct Dma { + host: *mut u8, + dev: u64, + mapping: *mut c_void, + pages: usize, +} + +impl Dma { + /// Allocate `bytes` (rounded up to pages), zeroed, mapped as ONE contiguous bus-master + /// common buffer (QPLs rely on page i being at `dev + i*4096`). + unsafe fn alloc(pci: &PciIoProtocol, bytes: usize) -> Result { + let pages = bytes.div_ceil(PAGE).max(1); + let mut host: *mut c_void = core::ptr::null_mut(); + let st = (pci.allocate_buffer)( + pci, + EFI_ALLOCATE_ANY_PAGES, + EFI_BOOT_SERVICES_DATA, + pages, + &mut host, + 0, + ); + if !st.is_success() || host.is_null() { + log!(" AllocateBuffer({pages} pages) failed: {st:?}"); + return Err(if st.is_success() { + Status::OUT_OF_RESOURCES + } else { + st + }); + } + core::ptr::write_bytes(host as *mut u8, 0, pages * PAGE); + let want = pages * PAGE; + let mut nbytes = want; + let mut dev: u64 = 0; + let mut mapping: *mut c_void = core::ptr::null_mut(); + let st = (pci.map)( + pci, + PciMapOp::CommonBuffer, + host as *const c_void, + &mut nbytes, + &mut dev, + &mut mapping, + ); + if !st.is_success() || nbytes != want { + log!(" Map({want} bytes) failed: {st:?} (mapped {nbytes})"); + let _ = (pci.free_buffer)(pci, pages, host); + return Err(if st.is_success() { + Status::OUT_OF_RESOURCES + } else { + st + }); + } + Ok(Dma { + host: host as *mut u8, + dev, + mapping, + pages, + }) + } +} + +// ---- Admin queue (spec §3) ------------------------------------------------------------- + +struct AdminQueue { + dma: Dma, + /// Free-running producer count; the device's event counter must equal it when idle. + prod: u32, +} + +impl AdminQueue { + /// Submit one 64-byte command and wait for it; returns the device status word. + unsafe fn exec_status(&mut self, pci: &PciIoProtocol, cmd: &[u8; 64]) -> Result { + let tail = reg_rd(pci, regs::ADMINQ_EVENT_COUNTER); + if tail != self.prod { + log!(" AQ out of sync: event_counter={tail} prod={}", self.prod); + return Err(Status::DEVICE_ERROR); + } + let slot = self.dma.host.add(((self.prod % AQ_SLOTS) * 64) as usize); + for (i, b) in cmd.iter().enumerate() { + slot.add(i).write_volatile(*b); + } + self.prod = self.prod.wrapping_add(1); + fence(Ordering::Release); + reg_wr(pci, regs::ADMINQ_DOORBELL, self.prod); + let mut done = false; + for _ in 0..CMD_CHECKS { + if reg_rd(pci, regs::ADMINQ_EVENT_COUNTER) == self.prod { + done = true; + break; + } + delay_ms(SLEEP_MS); + } + let opcode = u32::from_be_bytes([cmd[0], cmd[1], cmd[2], cmd[3]]); + if !done { + log!(" AQ opcode 0x{opcode:x}: timed out"); + return Err(Status::TIMEOUT); + } + fence(Ordering::Acquire); + Ok(get_be32(slot, 4)) + } + + /// Submit one command; anything but PASSED is an error (logged with the opcode). + unsafe fn exec(&mut self, pci: &PciIoProtocol, cmd: &[u8; 64]) -> Result<(), Status> { + let st = self.exec_status(pci, cmd)?; + let opcode = u32::from_be_bytes([cmd[0], cmd[1], cmd[2], cmd[3]]); + if st == AQ_PASSED { + vlog!(" AQ opcode 0x{opcode:x}: PASSED"); + Ok(()) + } else { + log!(" AQ opcode 0x{opcode:x}: status 0x{st:08x}"); + Err(Status::DEVICE_ERROR) + } + } +} + +/// Register the admin queue (spec §3.2; gve_adminq.c:341-354): PFN on rev 0, else +/// length + base hi/lo + RUN. +unsafe fn register_adminq(pci: &PciIoProtocol, rev: u8, aq: &Dma) { + if rev < 1 { + reg_wr(pci, regs::ADMINQ_PFN, (aq.dev / PAGE as u64) as u32); + } else { + mmio_write16(pci, REG_BAR, regs::ADMINQ_LENGTH, PAGE as u16); + reg_wr(pci, regs::ADMINQ_BASE_HI, (aq.dev >> 32) as u32); + reg_wr(pci, regs::ADMINQ_BASE_LO, aq.dev as u32); + reg_wr(pci, regs::DRIVER_STATUS, DRV_STS_RUN); + } +} + +/// Reset handshake = release the admin queue (spec §2.4; gve_adminq.c:368-397). The only +/// guarantee the device has stopped DMA. Bounded (500 x 20 ms); returns whether it completed. +unsafe fn reset(pci: &PciIoProtocol, rev: u8) -> bool { + if rev < 1 { + reg_wr(pci, regs::ADMINQ_PFN, 0); + for _ in 0..RELEASE_CHECKS { + if reg_rd(pci, regs::ADMINQ_PFN) == 0 { + return true; + } + delay_ms(SLEEP_MS); + } + } else { + reg_wr(pci, regs::DRIVER_STATUS, DRV_STS_RESET); + for _ in 0..RELEASE_CHECKS { + if reg_rd(pci, regs::DEVICE_STATUS) & DEV_STS_IS_RESET != 0 { + return true; + } + delay_ms(SLEEP_MS); + } + } + false +} + +// ---- ExitBootServices: stop DMA before the OS owns the memory --------------------------- + +/// Tear the device down at ExitBootServices, as Linux does on close + remove (gve_close -> +/// gve_destroy_rings + gve_unregister_qpls, gve_teardown_device_resources, gve_adminq_release): +/// destroy the queues, unregister both page lists, deconfigure the device resources, then reset. +/// The device must let go of every page it was given before the firmware IOMMU's own EBS +/// handler (TPL_CALLBACK, after this one at TPL_NOTIFY) converts them back to private memory -- +/// RX buffers are posted into boot-services memory the OS is about to reuse. Admin-queue commands +/// use pre-allocated DMA memory and Stall-based polling only (no allocation, as EBS requires). A +/// failed command surrenders to the reset, as gve_close does. No logging (console may be gone). +unsafe extern "efiapi" fn on_exit_boot_services(_e: Event, ctx: Option>) { + if let Some(c) = ctx { + (*(c.as_ptr() as *mut Gvnic)).teardown(); + } +} + +/// Arm the ExitBootServices teardown for `nic`, which must stay at this address (the SNP +/// device it lives in is leaked) for the life of boot services. +pub unsafe fn arm_exit_boot_services(nic: *mut Gvnic) { + match boot::create_event( + EventType::SIGNAL_EXIT_BOOT_SERVICES, + Tpl::NOTIFY, + Some(on_exit_boot_services), + NonNull::new(nic.cast()), + ) { + Ok(_) => vlog!("ExitBootServices teardown armed"), + Err(e) => log!( + "ExitBootServices hook FAILED: {:?} (device left running)", + e.status() + ), + } +} + +// ---- Device description (spec §4.2) ----------------------------------------------------- + +struct Desc { + max_registered_pages: u64, + tx_entries: u32, + rx_entries: u32, + mtu: u32, + counters: u32, + tx_pages_per_qpl: u32, + mac: [u8; 6], +} + +/// Parse the device descriptor + option TLVs; log everything (first-boot visibility); pick +/// GQI_QPL (present, or no format option at all = Linux's default) or fail. +unsafe fn parse_describe(buf: *const u8) -> Result { + let mut d = Desc { + max_registered_pages: get_be64(buf, 0), + tx_entries: get_be16(buf, 10) as u32, + rx_entries: get_be16(buf, 12) as u32, + mtu: get_be16(buf, 16) as u32, + counters: get_be16(buf, 18) as u32, + tx_pages_per_qpl: get_be16(buf, 20) as u32, + mac: [0; 6], + }; + for (i, m) in d.mac.iter_mut().enumerate() { + *m = buf.add(24 + i).read_volatile(); + } + let num_opts = get_be16(buf, 30) as usize; + let total_len = (get_be16(buf, 32) as usize).clamp(40, PAGE); + vlog!( + " describe: max_reg_pages={} tx_entries={} rx_entries={} default_queues={} mtu={} counters={} tx_pages_per_qpl={} rx_pages_per_qpl={} options={} total_len={}", + d.max_registered_pages, d.tx_entries, d.rx_entries, get_be16(buf, 14), d.mtu, + d.counters, d.tx_pages_per_qpl, get_be16(buf, 22), num_opts, total_len + ); + + let mut off = 40usize; + let mut gqi_qpl_mask: Option = None; + let mut other_formats: Vec = Vec::new(); + let mut jumbo_mtu: Option = None; + for _ in 0..num_opts { + if off + 8 > total_len { + log!(" describe: option header runs past total_length"); + return Err(Status::DEVICE_ERROR); + } + let id = get_be16(buf, off); + let len = get_be16(buf, off + 2) as usize; + let req = get_be32(buf, off + 4); + let p = off + 8; + if p + len > total_len { + log!(" describe: option 0x{id:x} runs past total_length"); + return Err(Status::DEVICE_ERROR); + } + let mask = if len >= 4 { get_be32(buf, p) } else { 0 }; + vlog!(" option 0x{id:x} len={len} required_features=0x{req:x} mask=0x{mask:x}"); + if req == 0 { + match id { + OPT_GQI_QPL if len >= 4 => gqi_qpl_mask = Some(mask), + OPT_JUMBO_FRAMES if len >= 6 => jumbo_mtu = Some(get_be16(buf, p + 4) as u32), + OPT_GQI_RAW_ADDRESSING | OPT_GQI_RDA | OPT_DQO_RDA | OPT_DQO_QPL => { + other_formats.push(id) + } + _ => {} + } + } + off = p + len; + } + + // Queue format: GQI_QPL if offered, or if no format option is present at all (Linux's + // default, gve_adminq.c:1158-1165). Otherwise this device needs a mode we don't drive. + let mask = match gqi_qpl_mask { + Some(m) => m, + None if other_formats.is_empty() => 0, + None => { + log!(" describe: GQI_QPL not offered (formats offered: {other_formats:x?})"); + return Err(Status::UNSUPPORTED); + } + }; + if !other_formats.is_empty() { + vlog!(" describe: also offered {other_formats:x?}; using GQI_QPL"); + } + if let (Some(j), true) = (jumbo_mtu, mask & SUP_JUMBO_FRAMES != 0) { + d.mtu = j; + } + Ok(d) +} + +// ---- Queues ----------------------------------------------------------------------------- + +struct Tx { + ring: Dma, // entries * 16 B packet descriptors + qpl: Dma, // tx_pages_per_qpl pages, carved into BUF-sized slots + entries: u32, + slots: u32, + req: u32, // free-running: descriptors posted + done: u32, // free-running: descriptors reaped + db_index: u32, + counter: *const u8, // &counter_array[counter_index] + callers: Vec<*const c_void>, +} + +struct Rx { + desc: Dma, // entries * 64 B, device-written + data: Dma, // entries * 8 B: BE64 QPL offset per slot (= i * 4096, never changed) + qpl: Dma, // entries pages, one buffer per page at offset 0 + entries: u32, + cnt: u32, // free-running: descriptors consumed + fill: u32, // free-running: slots posted + seq: u16, // expected seqno, 1..7 + db_index: u32, + skip_cont: bool, // dropping the rest of a multi-fragment packet +} + +/// A bound gVNIC: one TX + one RX GQI-QPL queue, polled. +pub struct Gvnic { + pci: *const PciIoProtocol, + /// Host address of BAR2 (doorbells), written directly (see the module docs). + db: *mut u8, + /// RX QPL id (TX is [`TX_QPL_ID`]), for unregistering at teardown. + rx_qpl_id: u32, + /// Device MTU (L3 payload; GCP default 1460), capped so a frame fits one 2 KiB buffer. + pub mtu: u32, + mac: [u8; 6], + rev: u8, + aq: AdminQueue, + counters: Dma, + irq_dbs: Dma, + qres: Dma, + tx: Tx, + rx: Rx, +} + +impl Gvnic { + pub fn mac(&self) -> [u8; 6] { + self.mac + } + + /// Release everything the device holds, then reset it (see [`on_exit_boot_services`]). + unsafe fn teardown(&mut self) { + let pci = &*self.pci; + let steps: [(u32, Option); 5] = [ + (OP_DESTROY_TX_QUEUE, Some(0)), + (OP_DESTROY_RX_QUEUE, Some(0)), + (OP_UNREGISTER_PAGE_LIST, Some(TX_QPL_ID)), + (OP_UNREGISTER_PAGE_LIST, Some(self.rx_qpl_id)), + (OP_DECONFIGURE_DEVICE_RESOURCES, None), + ]; + for (op, id) in steps { + let mut c = cmd_new(op); + if let Some(id) = id { + cmd_be32(&mut c, 8, id); + } + if self.aq.exec(pci, &c).is_err() { + break; // surrender to the reset (gve_close) + } + } + let _ = reset(pci, self.rev); + } + + /// RX is fully posted at probe (the data ring must be prefilled before CREATE_RX_QUEUE, + /// spec §4.7), so SNP Initialize has nothing to do here. + pub unsafe fn init_rx(&mut self) {} + + /// Copy one received frame into `out` (capacity `cap`); `None` if nothing is pending. + /// Errored, multi-fragment, or oversized frames are consumed and dropped. + pub unsafe fn receive(&mut self, out: *mut u8, cap: usize) -> Option { + let db = self.db; + let rx = &mut self.rx; + loop { + let idx = (rx.cnt % rx.entries) as usize; + let d = rx.desc.host.add(idx * 64); + let flags_seq = get_be16(d, 62); + if flags_seq & 0x7 != rx.seq { + return None; + } + fence(Ordering::Acquire); + let len = get_be16(d, 60) as usize; + let cont = flags_seq & RXF_PKT_CONT != 0; + let mut got = None; + if rx.skip_cont { + rx.skip_cont = cont; // drop through the last fragment + } else if flags_seq & RXF_ERR != 0 || cont || !(RX_PAD..=BUF).contains(&len) { + rx.skip_cont = cont; + } else { + let n = len - RX_PAD; + if n <= cap { + let src = rx.qpl.host.add(idx * PAGE + RX_PAD); + core::ptr::copy_nonoverlapping(src, out, n); + got = Some(n); + } + } + // Hand the slot back only after its data was copied out (spec §7.5). + rx.cnt = rx.cnt.wrapping_add(1); + rx.seq = if rx.seq == 7 { 1 } else { rx.seq + 1 }; + rx.fill = rx.fill.wrapping_add(1); + doorbell(db, rx.db_index, rx.fill); + if got.is_some() { + return got; + } + } + } + + /// Queue one complete Ethernet frame. `caller` is the SNP buffer, handed back by + /// `poll_tx()` once the device has consumed the descriptor. + pub unsafe fn transmit( + &mut self, + data: *const u8, + len: usize, + caller: *const c_void, + ) -> Result<(), Status> { + let tx = &mut self.tx; + if len == 0 || len > self.mtu as usize + ETH_HLEN { + return Err(Status::INVALID_PARAMETER); + } + let in_flight = tx.req.wrapping_sub(tx.done); + if in_flight >= tx.entries.min(tx.slots) { + return Err(Status::NOT_READY); + } + let slot = (tx.req % tx.slots) as usize; + let qpl_off = slot * BUF; + core::ptr::copy_nonoverlapping(data, tx.qpl.host.add(qpl_off), len); + // gve_tx_pkt_desc (gve_desc.h:26-34): type_flags=STD(0), offsets 0, desc_cnt=1, + // len = seg_len = frame length, seg_addr = QPL byte offset. + let d = tx.ring.host.add(((tx.req % tx.entries) * 16) as usize); + d.write_volatile(0); + d.add(1).write_volatile(0); + d.add(2).write_volatile(0); + d.add(3).write_volatile(1); + put_be16(d, 4, len as u16); + put_be16(d, 6, len as u16); + put_be64(d, 8, qpl_off as u64); + tx.callers[slot] = caller; + tx.req = tx.req.wrapping_add(1); + doorbell(self.db, tx.db_index, tx.req); + Ok(()) + } + + /// Reap one completed TX: the caller's buffer pointer, or `None`. + pub unsafe fn poll_tx(&mut self) -> Option<*const c_void> { + let tx = &mut self.tx; + let nic_done = get_be32(tx.counter, 0); + fence(Ordering::Acquire); + let completed = nic_done.wrapping_sub(tx.done); + let in_flight = tx.req.wrapping_sub(tx.done); + if completed == 0 || completed > in_flight { + return None; + } + let slot = (tx.done % tx.slots) as usize; + tx.done = tx.done.wrapping_add(1); + Some(tx.callers[slot]) + } +} + +/// Bring the device up (spec §10.1). On failure after the admin queue is registered the +/// device is reset, so nothing is left doing DMA. +pub unsafe fn probe(pci: &PciIoProtocol) -> Result { + let rev = cfg_r8(pci, 0x08); + vlog!("PCI 1ae0:0042 revision {rev}"); + + // Memory decode + bus mastering; INTx disabled (Command bit 10). MSI-X left disabled. + let st = (pci.attributes)( + pci, + PciAttrOp::Enable, + PCI_ATTR_MEMORY | PCI_ATTR_BUS_MASTER, + core::ptr::null_mut(), + ); + if st.is_success() { + vlog!("memory+bus-master enable: {st:?}"); + } else { + log!("memory+bus-master enable: {st:?}"); + } + cfg_w16(pci, 0x04, cfg_r16(pci, 0x04) | (1 << 10)); + + let num_msix = msix_table_size(pci); + if num_msix < 3 { + log!("MSI-X table size {num_msix} < 3 (GVE_MIN_MSIX)"); + return Err(Status::UNSUPPORTED); + } + let num_ntfy = (num_msix - 1) & !1; + let max_tx = reg_rd(pci, regs::MAX_TX_QUEUES); + let max_rx = reg_rd(pci, regs::MAX_RX_QUEUES); + let dev_status = reg_rd(pci, regs::DEVICE_STATUS); + vlog!("msix={num_msix} ntfy_blks={num_ntfy} max_tx={max_tx} max_rx={max_rx} device_status=0x{dev_status:x}"); + if max_tx == 0 || max_rx == 0 { + return Err(Status::DEVICE_ERROR); + } + + for b in VERSION_STRING { + mmio_write8(pci, REG_BAR, regs::DRIVER_VERSION, *b); + } + + // Before the admin queue exists, so a failure here leaves nothing to reset. + let (db_base, db_len) = bar_host_range(pci, DB_BAR)?; + + let aq_dma = Dma::alloc(pci, PAGE)?; + register_adminq(pci, rev, &aq_dma); + let ec = reg_rd(pci, regs::ADMINQ_EVENT_COUNTER); + if ec != 0 { + log!("event_counter={ec} after AQ registration (expected 0)"); + } + let aq = AdminQueue { + dma: aq_dma, + prod: ec, + }; + + match bring_up(pci, rev, num_ntfy, max_tx, aq, db_base as *mut u8, db_len) { + Ok(nic) => Ok(nic), + Err(e) => { + let ok = reset(pci, rev); + log!( + "bring-up failed ({e:?}); device reset {}", + if ok { "OK" } else { "TIMED OUT" } + ); + Err(e) + } + } +} + +/// Steps 7-19 of the bring-up checklist; the admin queue moves into the returned device. +unsafe fn bring_up( + pci: &PciIoProtocol, + rev: u8, + num_ntfy: u32, + max_tx: u32, + mut aq: AdminQueue, + db: *mut u8, + db_len: u64, +) -> Result { + // VERIFY_DRIVER_COMPATIBILITY (spec §4.1): PASSED or UNIMPLEMENTED both fine. + let info = Dma::alloc(pci, DRIVER_INFO_LEN)?; + info.host.write_volatile(1); // os_type: 1 (the only value defined) + put_be64(info.host, 16, DRIVER_CAP_GQI_QPL); + for (i, b) in b"lockboot-gvnic".iter().enumerate() { + info.host.add(48 + i).write_volatile(*b); + info.host.add(176 + i).write_volatile(*b); + } + let mut c = cmd_new(OP_VERIFY_DRIVER_COMPATIBILITY); + cmd_be64(&mut c, 8, DRIVER_INFO_LEN as u64); + cmd_be64(&mut c, 16, info.dev); + match aq.exec_status(pci, &c)? { + AQ_PASSED => vlog!(" verify-driver-compatibility: PASSED"), + AQ_UNIMPLEMENTED => vlog!(" verify-driver-compatibility: UNIMPLEMENTED (ok)"), + s => { + log!(" verify-driver-compatibility: status 0x{s:08x}"); + return Err(Status::DEVICE_ERROR); + } + } + + // DESCRIBE_DEVICE (spec §4.2). + let desc_buf = Dma::alloc(pci, PAGE)?; + let mut c = cmd_new(OP_DESCRIBE_DEVICE); + cmd_be64(&mut c, 8, desc_buf.dev); + cmd_be32(&mut c, 16, 1); // descriptor version + cmd_be32(&mut c, 20, PAGE as u32); // available length + aq.exec(pci, &c)?; + let d = parse_describe(desc_buf.host)?; + + let pow2 = |n: u32| n != 0 && n.is_power_of_two(); + if !pow2(d.tx_entries) || !pow2(d.rx_entries) || d.counters == 0 || d.tx_pages_per_qpl == 0 { + log!(" describe: unusable ring/counter geometry"); + return Err(Status::DEVICE_ERROR); + } + let pages_needed = d.tx_pages_per_qpl as u64 + d.rx_entries as u64; + if pages_needed > d.max_registered_pages { + log!(" describe: need {pages_needed} QPL pages > max_registered_pages"); + return Err(Status::DEVICE_ERROR); + } + if d.mtu < MTU_MIN { + log!(" describe: mtu {} < {MTU_MIN}", d.mtu); + return Err(Status::DEVICE_ERROR); + } + let mtu = d.mtu.min(MTU_CAP); + + // CONFIGURE_DEVICE_RESOURCES (spec §4.3): counter array + irq-doorbell index array. + let counters = Dma::alloc(pci, d.counters as usize * 4)?; + let irq_dbs = Dma::alloc(pci, num_ntfy as usize * 64)?; + let mut c = cmd_new(OP_CONFIGURE_DEVICE_RESOURCES); + cmd_be64(&mut c, 8, counters.dev); + cmd_be64(&mut c, 16, irq_dbs.dev); + cmd_be32(&mut c, 24, d.counters); + cmd_be32(&mut c, 28, num_ntfy); + cmd_be32(&mut c, 32, 64); // irq_db_stride + cmd_be32(&mut c, 36, 0); // ntfy_blk_msix_base_idx + cmd_u8(&mut c, 40, QUEUE_FORMAT_GQI_QPL); + aq.exec(pci, &c)?; + + // Rings + QPLs. Queue resources: one page, TX at 0, RX at 64. + let qres = Dma::alloc(pci, PAGE)?; + let tx_ring = Dma::alloc(pci, d.tx_entries as usize * 16)?; + let tx_qpl = Dma::alloc(pci, d.tx_pages_per_qpl as usize * PAGE)?; + let rx_desc = Dma::alloc(pci, d.rx_entries as usize * 64)?; + let rx_data = Dma::alloc(pci, d.rx_entries as usize * 8)?; + let rx_qpl = Dma::alloc(pci, d.rx_entries as usize * PAGE)?; + for i in 0..d.rx_entries as usize { + put_be64(rx_data.host, i * 8, (i * PAGE) as u64); + } + + // REGISTER_PAGE_LIST (spec §4.5): TX id 0, RX id min(max_tx, ntfy/2) (Linux's values). + let tx_qpl_id = TX_QPL_ID; + let rx_qpl_id = max_tx.min(num_ntfy / 2); + for (id, qpl, pages) in [ + (tx_qpl_id, &tx_qpl, d.tx_pages_per_qpl), + (rx_qpl_id, &rx_qpl, d.rx_entries), + ] { + let list = Dma::alloc(pci, pages as usize * 8)?; + for i in 0..pages as usize { + put_be64(list.host, i * 8, qpl.dev + (i * PAGE) as u64); + } + let mut c = cmd_new(OP_REGISTER_PAGE_LIST); + cmd_be32(&mut c, 8, id); + cmd_be32(&mut c, 12, pages); + cmd_be64(&mut c, 16, list.dev); + cmd_be64(&mut c, 24, PAGE as u64); + aq.exec(pci, &c)?; + } + + // CREATE_TX_QUEUE (spec §4.6). + let mut c = cmd_new(OP_CREATE_TX_QUEUE); + cmd_be32(&mut c, 8, 0); // queue_id + cmd_be64(&mut c, 16, qres.dev); + cmd_be64(&mut c, 24, tx_ring.dev); + cmd_be32(&mut c, 32, tx_qpl_id); + cmd_be32(&mut c, 36, 0); // ntfy_id + cmd_be16(&mut c, 48, d.tx_entries as u16); + aq.exec(pci, &c)?; + let tx_db = get_be32(qres.host, 0); + let tx_ctr = get_be32(qres.host, 4); + + // CREATE_RX_QUEUE (spec §4.7). Data ring is already prefilled. + let mut c = cmd_new(OP_CREATE_RX_QUEUE); + cmd_be32(&mut c, 8, 0); // queue_id + cmd_be32(&mut c, 12, 0); // index + cmd_be32(&mut c, 20, num_ntfy / 2); // ntfy_id + cmd_be64(&mut c, 24, qres.dev + 64); + cmd_be64(&mut c, 32, rx_desc.dev); + cmd_be64(&mut c, 40, rx_data.dev); + cmd_be32(&mut c, 48, rx_qpl_id); + cmd_be16(&mut c, 52, d.rx_entries as u16); + cmd_be16(&mut c, 54, BUF as u16); // packet_buffer_size + aq.exec(pci, &c)?; + let rx_db = get_be32(qres.host, 64); + vlog!(" queues: tx db={tx_db} counter={tx_ctr} rx db={rx_db}"); + if tx_ctr >= d.counters { + log!( + " tx counter_index {tx_ctr} out of range ({} counters)", + d.counters + ); + return Err(Status::DEVICE_ERROR); + } + // The doorbells are written through a raw pointer: keep the device's indices inside BAR2. + for (q, idx) in [("tx", tx_db), ("rx", rx_db)] { + if 4 * idx as u64 + 4 > db_len { + log!(" {q} doorbell index {idx} outside BAR2 ({db_len} bytes)"); + return Err(Status::DEVICE_ERROR); + } + } + + // Post every RX slot (spec §7.2 step 6). + doorbell(db, rx_db, d.rx_entries); + + // Link (spec §2.5): Linux does not wait; we poll briefly and log. + let mut link = false; + for _ in 0..LINK_CHECKS { + if reg_rd(pci, regs::DEVICE_STATUS) & DEV_STS_LINK_UP != 0 { + link = true; + break; + } + delay_ms(SLEEP_MS); + } + + // The one line a successful probe prints by default (detail: the `verbose` feature). + let m = d.mac; + log!( + "1ae0:0042 rev {rev}, GQI_QPL, 1 tx/1 rx, mtu {}, mac {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}, link {}", + d.mtu, + m[0], + m[1], + m[2], + m[3], + m[4], + m[5], + if link { "up" } else { "NOT up after 5s (continuing)" } + ); + + let tx_slots = (d.tx_pages_per_qpl as usize * PAGE / BUF) as u32; + let tx_counter = counters.host.add(tx_ctr as usize * 4) as *const u8; + Ok(Gvnic { + pci, + db, + rx_qpl_id, + mtu, + mac: d.mac, + rev, + aq, + counters, + irq_dbs, + qres, + tx: Tx { + counter: tx_counter, + ring: tx_ring, + qpl: tx_qpl, + entries: d.tx_entries, + slots: tx_slots, + req: 0, + done: 0, + db_index: tx_db, + callers: vec![core::ptr::null(); tx_slots as usize], + }, + rx: Rx { + desc: rx_desc, + data: rx_data, + qpl: rx_qpl, + entries: d.rx_entries, + cnt: 0, + fill: d.rx_entries, + seq: 1, + db_index: rx_db, + skip_cont: false, + }, + }) +} diff --git a/crates/gvnic/src/main.rs b/crates/gvnic/src/main.rs new file mode 100644 index 0000000..1631de4 --- /dev/null +++ b/crates/gvnic/src/main.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! `gvnic.efi` - a UEFI SimpleNetworkProtocol driver for the Google Virtual NIC (gVNIC, +//! PCI `1ae0:0042`, Linux driver name `gve`). +//! +//! GCP's UEFI firmware ships no gVNIC driver (its x86 OVMF has the full NetworkPkg stack +//! -- SNP/MNP/ARP/IP4/DHCP4/UDP4/TCP4 -- but no NIC driver for gVNIC, and no longer one +//! for virtio-net either), while GCP *requires* gVNIC for Confidential VMs and Arm. So the +//! firmware's IP stack never has an SNP to bind to and stage0's `net::bringup()` fails +//! with `IP4_CONFIG2 NOT_FOUND`. This driver fills that gap exactly as `ena.efi` does on +//! EC2: it produces `EFI_SIMPLE_NETWORK_PROTOCOL` on the gVNIC controller and EDK2's +//! existing MNP/IP4/TCP4/UDP4 stack layers on top, so stage0's networking is unchanged. +//! +//! A well-behaved UEFI Driver-Model driver: the entry point only installs a +//! `DriverBinding` and returns; it touches no hardware until the firmware calls `Start()` +//! on a matching gVNIC handle, so on other platforms (EC2/ENA, local QEMU) it sits idle. +//! +//! stage0 loads it from a measured PE section (integrity bound via PCR4, like ena.efi). +//! +//! Device protocol: derived from the Linux `gve` driver (drivers/net/ethernet/google/gve, +//! Copyright Google LLC, `(GPL-2.0 OR MIT)`), used under the MIT terms; reference commit +//! 45e0a63f9c86. See `device.rs`. + +#![no_std] +#![no_main] + +extern crate alloc; + +#[macro_use] +mod clock; +mod binding; +mod device; +mod pci; +mod snp; + +use uefi::boot; +use uefi::prelude::*; +use uefi::proto::loaded_image::LoadedImage; + +#[entry] +fn main() -> Status { + uefi::helpers::init().unwrap(); + // stage0's log-timestamp epoch, if it passed one (clock.rs). + if let Ok(li) = boot::open_protocol_exclusive::(boot::image_handle()) { + clock::init(li.load_options_as_bytes()); + } + // Install the DriverBinding and return SUCCESS. Because the PE subsystem is + // EFI_BOOT_SERVICE_DRIVER, the image stays resident after this returns; the + // firmware (or stage0's connect_all_controllers) calls back into binding::start + // when it connects the gVNIC controller. + match binding::install() { + Ok(()) => { + vlog!("DriverBinding installed (idle until a gVNIC device binds)"); + Status::SUCCESS + } + Err(e) => { + log!("failed to install DriverBinding: {:?}", e.status()); + e.status() + } + } +} diff --git a/crates/gvnic/src/pci.rs b/crates/gvnic/src/pci.rs new file mode 100644 index 0000000..840ea39 --- /dev/null +++ b/crates/gvnic/src/pci.rs @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Minimal `EFI_PCI_IO_PROTOCOL` binding. uefi/uefi-raw don't expose it, so we +//! hand-roll the vtable. Only the members the NIC drivers (ena, gvnic) use are given real +//! signatures; the unused slots are kept as pointer-sized placeholders so the +//! struct layout (a firmware-provided vtable indexed by offset) stays correct. + +// Map/attribute helpers are wired for the device layer that lands next. +#![allow(dead_code)] + +use core::ffi::c_void; + +use uefi::proto::unsafe_protocol; +use uefi::{guid, Guid, Status}; + +/// `EFI_PCI_IO_PROTOCOL_WIDTH` (the values the driver uses). +#[repr(u32)] +#[derive(Clone, Copy)] +pub enum PciWidth { + U8 = 0, + U16 = 1, + U32 = 2, + U64 = 3, +} + +/// `EFI_PCI_IO_PROTOCOL_OPERATION` for `Map`. +#[repr(u32)] +#[derive(Clone, Copy)] +pub enum PciMapOp { + Read = 0, + Write = 1, + CommonBuffer = 2, +} + +/// `EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION`. +#[repr(u32)] +#[derive(Clone, Copy)] +pub enum PciAttrOp { + Get = 0, + Set = 1, + Enable = 2, + Disable = 3, + Supported = 4, +} + +/// `EFI_PCI_IO_ATTRIBUTE_BUS_MASTER`: enable the device as a PCI bus master (required +/// before any DMA / `Map`). NB 0x0400, not 0x0004 (which is VGA_PALETTE_IO). +pub const PCI_ATTR_BUS_MASTER: u64 = 0x0400; + +/// BAR-relative MMIO read/write: `Mem.Read` / `Mem.Write`. +type MemFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + width: PciWidth, + bar_index: u8, + offset: u64, + count: usize, + buffer: *mut c_void, +) -> Status; + +/// PCI config-space read/write: `Pci.Read` / `Pci.Write` (note: u32 offset, no BAR). +type ConfigFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + width: PciWidth, + offset: u32, + count: usize, + buffer: *mut c_void, +) -> Status; + +type MapFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + operation: PciMapOp, + host_address: *const c_void, + number_of_bytes: *mut usize, + device_address: *mut u64, + mapping: *mut *mut c_void, +) -> Status; + +type UnmapFn = + unsafe extern "efiapi" fn(this: *const PciIoProtocol, mapping: *mut c_void) -> Status; + +// alloc_type / memory_type are EFI enums; u32 matches their ABI without importing them. +type AllocBufferFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + alloc_type: u32, + memory_type: u32, + pages: usize, + host_address: *mut *mut c_void, + attributes: u64, +) -> Status; + +type FreeBufferFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + pages: usize, + host_address: *mut c_void, +) -> Status; + +/// `GetBarAttributes(This, BarIndex, Supports, Resources)`: `*Resources` is a pool buffer of ACPI +/// address-space descriptors (end tag 0x79) that the caller frees. +pub type GetBarAttributesFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + bar_index: u8, + supports: *mut u64, + resources: *mut *mut c_void, +) -> Status; + +type AttributesFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + operation: PciAttrOp, + attributes: u64, + result: *mut u64, +) -> Status; + +#[repr(C)] +pub struct PciIoAccess { + pub read: MemFn, + pub write: MemFn, +} + +#[repr(C)] +pub struct PciIoConfigAccess { + pub read: ConfigFn, + pub write: ConfigFn, +} + +/// `EFI_PCI_IO_PROTOCOL`. Field order matches the UEFI spec exactly (it is a +/// firmware vtable). Unused members are `usize` placeholders (pointer-sized). +#[repr(C)] +pub struct PciIoProtocol { + poll_mem: usize, + poll_io: usize, + pub mem: PciIoAccess, + pub io: PciIoAccess, + pub pci: PciIoConfigAccess, + copy_mem: usize, + pub map: MapFn, + pub unmap: UnmapFn, + pub allocate_buffer: AllocBufferFn, + pub free_buffer: FreeBufferFn, + flush: usize, + get_location: usize, + pub attributes: AttributesFn, + pub get_bar_attributes: GetBarAttributesFn, + set_bar_attributes: usize, + pub rom_size: u64, + pub rom_image: *mut c_void, +} + +impl PciIoProtocol { + pub const GUID: Guid = guid!("4cf5b200-68b8-4ca5-9eec-b23e3f50029a"); +} + +/// High-level wrapper so the protocol works with `boot::open_protocol::`. +#[unsafe_protocol(PciIoProtocol::GUID)] +pub struct PciIo(pub PciIoProtocol); + +impl PciIo { + /// Read PCI config dword 0: low 16 bits = vendor id, high 16 = device id. + pub fn vendor_device(&self) -> uefi::Result<(u16, u16)> { + let mut dw: u32 = 0; + let st = unsafe { + (self.0.pci.read)(&self.0, PciWidth::U32, 0, 1, (&mut dw as *mut u32).cast()) + }; + if st.is_success() { + Ok((dw as u16, (dw >> 16) as u16)) + } else { + Err(st.into()) + } + } +} diff --git a/crates/gvnic/src/snp.rs b/crates/gvnic/src/snp.rs new file mode 100644 index 0000000..7f0cd44 --- /dev/null +++ b/crates/gvnic/src/snp.rs @@ -0,0 +1,320 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! `EFI_SIMPLE_NETWORK_PROTOCOL` production, backed by a [`Gvnic`] device. +//! +//! The SNP interface is the first field of [`SnpDev`], so the firmware-visible +//! `*const SimpleNetworkProtocol` is also a `*mut SnpDev` (the EDK2 "CR" idiom): each +//! member fn recovers the device with `dev(this)`. State machine mirrors VirtioNetDxe: +//! Stopped -> Started -> Initialized. Reset/StationAddress/Statistics/NvData are +//! UNSUPPORTED (as VirtioNetDxe does); the rest drive the gVNIC TX/RX queues. +//! Same shape as ena's snp.rs; differs only in the device type and in taking the +//! advertised max packet size from the device MTU (GCP defaults to 1460, not 1500). + +use alloc::boxed::Box; +use core::ffi::c_void; + +use uefi::boot; +use uefi::{guid, Guid, Handle, Status}; +use uefi_raw::protocol::network::snp::{ + InterruptStatus, NetworkMode, NetworkState, NetworkStatistics, ReceiveFlags, + SimpleNetworkProtocol, +}; +use uefi_raw::{Boolean, IpAddress, MacAddress}; + +use crate::device::Gvnic; + +const SNP_GUID: Guid = guid!("a19832b9-ac25-11d3-9a2d-0090273fc14d"); +const SNP_REVISION: u64 = 0x0001_0000; + +/// SNP interface + its Mode + the owning gVNIC device. `snp` MUST stay first. +#[repr(C)] +pub struct SnpDev { + snp: SimpleNetworkProtocol, + mode: NetworkMode, + nic: Gvnic, +} + +/// Recover the `SnpDev` from a member-fn `this` pointer (snp is at offset 0). +unsafe fn dev<'a>(this: *const SimpleNetworkProtocol) -> &'a mut SnpDev { + &mut *(this as *mut SnpDev) +} + +/// Build the SNP wrapper for `nic`, install it on `controller`, and leak it (the +/// firmware owns it for the controller's life). EDK2's MNP/IP4/TCP4/UDP4 then bind. +pub fn install(controller: Handle, nic: Gvnic) -> uefi::Result<()> { + // Advertise the device MTU as the max packet size (payload, excluding the 14-byte + // media header) so EDK2's IP4 never builds a frame the device would drop. + let mode = build_mode(nic.mac(), nic.mtu); + let dev = Box::new(SnpDev { + snp: SimpleNetworkProtocol { + revision: SNP_REVISION, + start, + stop, + initialize, + reset, + shutdown, + receive_filters, + station_address, + statistics, + multicast_ip_to_mac, + non_volatile_data, + get_status, + transmit, + receive, + wait_for_packet: core::ptr::null_mut(), + mode: core::ptr::null_mut(), + }, + mode, + nic, + }); + let p = Box::into_raw(dev); + unsafe { + (*p).snp.mode = &mut (*p).mode; + boot::install_protocol_interface( + Some(controller), + &SNP_GUID, + (&(*p).snp as *const SimpleNetworkProtocol).cast(), + )?; + // The device now has a fixed home: arm its ExitBootServices teardown. + crate::device::arm_exit_boot_services(&mut (*p).nic); + } + Ok(()) +} + +fn build_mode(mac: [u8; 6], mtu: u32) -> NetworkMode { + let mut cur = [0u8; 32]; + cur[..6].copy_from_slice(&mac); + let mut bcast = [0u8; 32]; + for b in &mut bcast[..6] { + *b = 0xff; + } + NetworkMode { + state: NetworkState::STOPPED, + hw_address_size: 6, + media_header_size: 14, + max_packet_size: mtu, + nv_ram_size: 0, + nv_ram_access_size: 0, + receive_filter_mask: (ReceiveFlags::UNICAST + | ReceiveFlags::BROADCAST + | ReceiveFlags::MULTICAST) + .bits(), + receive_filter_setting: (ReceiveFlags::UNICAST | ReceiveFlags::BROADCAST).bits(), + max_mcast_filter_count: 0, + mcast_filter_count: 0, + mcast_filter: core::array::from_fn(|_| MacAddress([0u8; 32])), + current_address: MacAddress(cur), + broadcast_address: MacAddress(bcast), + permanent_address: MacAddress(cur), + if_type: 1, // ethernet + mac_address_changeable: Boolean::from(false), + multiple_tx_supported: Boolean::from(false), + media_present_supported: Boolean::from(true), + media_present: Boolean::from(true), + } +} + +unsafe extern "efiapi" fn start(this: *const SimpleNetworkProtocol) -> Status { + let d = dev(this); + if d.mode.state == NetworkState::STOPPED { + d.mode.state = NetworkState::STARTED; + } + Status::SUCCESS +} + +unsafe extern "efiapi" fn stop(this: *const SimpleNetworkProtocol) -> Status { + dev(this).mode.state = NetworkState::STOPPED; + Status::SUCCESS +} + +unsafe extern "efiapi" fn initialize( + this: *const SimpleNetworkProtocol, + _extra_rx: usize, + _extra_tx: usize, +) -> Status { + let d = dev(this); + if d.mode.state == NetworkState::STOPPED { + return Status::NOT_STARTED; + } + d.nic.init_rx(); + d.mode.state = NetworkState::INITIALIZED; + vlog!("SNP initialized (rx posted, link up)"); + Status::SUCCESS +} + +unsafe extern "efiapi" fn reset(_this: *const SimpleNetworkProtocol, _ext: Boolean) -> Status { + Status::SUCCESS +} + +unsafe extern "efiapi" fn shutdown(this: *const SimpleNetworkProtocol) -> Status { + dev(this).mode.state = NetworkState::STARTED; + Status::SUCCESS +} + +unsafe extern "efiapi" fn receive_filters( + _this: *const SimpleNetworkProtocol, + _enable: ReceiveFlags, + _disable: ReceiveFlags, + _reset_mcast: Boolean, + _mcast_count: usize, + _mcast_filter: *const MacAddress, +) -> Status { + // We receive unicast+broadcast already; accept the request without reprogramming. + Status::SUCCESS +} + +unsafe extern "efiapi" fn station_address( + _this: *const SimpleNetworkProtocol, + _reset: Boolean, + _new: *const MacAddress, +) -> Status { + Status::UNSUPPORTED +} + +unsafe extern "efiapi" fn statistics( + _this: *const SimpleNetworkProtocol, + _reset: Boolean, + _size: *mut usize, + _table: *mut NetworkStatistics, +) -> Status { + Status::UNSUPPORTED +} + +unsafe extern "efiapi" fn multicast_ip_to_mac( + _this: *const SimpleNetworkProtocol, + ipv6: Boolean, + ip: *const IpAddress, + mac: *mut MacAddress, +) -> Status { + if ipv6 != Boolean::from(false) || ip.is_null() || mac.is_null() { + return Status::UNSUPPORTED; // IPv4 only + } + let ipb = ip as *const u8; // first 4 bytes are the v4 octets + let m = mac as *mut u8; // MacAddress is a transparent [u8;32] + m.add(0).write(0x01); + m.add(1).write(0x00); + m.add(2).write(0x5e); + m.add(3).write(ipb.add(1).read() & 0x7f); + m.add(4).write(ipb.add(2).read()); + m.add(5).write(ipb.add(3).read()); + Status::SUCCESS +} + +unsafe extern "efiapi" fn non_volatile_data( + _this: *const SimpleNetworkProtocol, + _read: Boolean, + _offset: usize, + _buffer_size: usize, + _buffer: *mut c_void, +) -> Status { + Status::UNSUPPORTED +} + +unsafe extern "efiapi" fn get_status( + this: *const SimpleNetworkProtocol, + interrupt_status: *mut InterruptStatus, + tx_buf: *mut *mut c_void, +) -> Status { + let d = dev(this); + if d.mode.state != NetworkState::INITIALIZED { + return Status::NOT_STARTED; + } + // Reap a TX completion ONLY when the caller asked for it (TxBuf non-NULL): MNP polls + // GetStatus(.., NULL) for media status, and a completion reaped there is lost, so MNP + // never gets that transmit buffer back. + let completed = if tx_buf.is_null() { + None + } else { + d.nic.poll_tx() + }; + if !tx_buf.is_null() { + *tx_buf = completed + .map(|p| p as *mut c_void) + .unwrap_or(core::ptr::null_mut()); + } + if !interrupt_status.is_null() { + let mut s = InterruptStatus::empty(); + if completed.is_some() { + s |= InterruptStatus::TRANSMIT; + } + *interrupt_status = s; + } + Status::SUCCESS +} + +unsafe extern "efiapi" fn transmit( + this: *const SimpleNetworkProtocol, + header_size: usize, + buffer_size: usize, + buffer: *const c_void, + src: *const MacAddress, + dest: *const MacAddress, + protocol: *const u16, +) -> Status { + let d = dev(this); + if d.mode.state != NetworkState::INITIALIZED { + return Status::NOT_STARTED; + } + let buf = buffer as *mut u8; + // If HeaderSize != 0 the SNP must build the media header into the buffer from + // src/dest/protocol; otherwise the buffer is already a complete frame. + if header_size != 0 { + if header_size < 14 || dest.is_null() || protocol.is_null() { + return Status::INVALID_PARAMETER; + } + // MacAddress is a transparent [u8;32]; use the raw pointer directly (taking a + // reference through the raw deref is UB-adjacent and a hard error now). + core::ptr::copy_nonoverlapping(dest as *const u8, buf, 6); + let src6 = if src.is_null() { + d.nic.mac() + } else { + let mut m = [0u8; 6]; + core::ptr::copy_nonoverlapping(src as *const u8, m.as_mut_ptr(), 6); + m + }; + core::ptr::copy_nonoverlapping(src6.as_ptr(), buf.add(6), 6); + let p = *protocol; + buf.add(12).write_volatile((p >> 8) as u8); + buf.add(13).write_volatile((p & 0xff) as u8); + } + match d.nic.transmit(buf, buffer_size, buffer) { + Ok(()) => Status::SUCCESS, + Err(e) => e, + } +} + +unsafe extern "efiapi" fn receive( + this: *const SimpleNetworkProtocol, + header_size: *mut usize, + buffer_size: *mut usize, + buffer: *mut c_void, + src: *mut MacAddress, + dest: *mut MacAddress, + protocol: *mut u16, +) -> Status { + let d = dev(this); + if d.mode.state != NetworkState::INITIALIZED { + return Status::NOT_STARTED; + } + let cap = *buffer_size; + match d.nic.receive(buffer as *mut u8, cap) { + Some(n) => { + *buffer_size = n; + let b = buffer as *const u8; + if !header_size.is_null() { + *header_size = 14; + } + if !dest.is_null() && n >= 6 { + core::ptr::copy_nonoverlapping(b, dest as *mut u8, 6); + } + if !src.is_null() && n >= 12 { + core::ptr::copy_nonoverlapping(b.add(6), src as *mut u8, 6); + } + if !protocol.is_null() && n >= 14 { + *protocol = ((*b.add(12) as u16) << 8) | (*b.add(13) as u16); + } + Status::SUCCESS + } + None => Status::NOT_READY, + } +} diff --git a/crates/stage0-test-payload/src/main.rs b/crates/stage0-test-payload/src/main.rs index eaf8f89..910c3e8 100644 --- a/crates/stage0-test-payload/src/main.rs +++ b/crates/stage0-test-payload/src/main.rs @@ -23,7 +23,8 @@ use uefi::prelude::*; use uefi::println; use uefi::proto::loaded_image::LoadedImage; use uefi::proto::tcg::v2::Tcg; -use uefi::runtime::{self, ResetType}; +use uefi::runtime::{self, ResetType, VariableAttributes, VariableVendor}; +use uefi::CStr16; use vaportpm_attest::{PcrOps, TpmTransport}; struct Tcg2Transport { @@ -54,10 +55,25 @@ fn main() -> Status { uefi::helpers::init().unwrap(); println!("payload: hello from the chain-loaded UEFI payload"); + // Secure Boot mode variables as the firmware reports them this boot (value + attributes, or + // absent): what stage0's gate saw, and whether the firmware implements the UEFI 2.5 modes. + print_mode_vars(); + match print_pcrs() { Ok(()) => {} Err(e) => println!("payload: could not read PCRs: {e}"), } + // Best effort: some firmware (EC2) does not hand out its log; the PCR dump above stands alone. + if let Err(e) = print_event_log() { + println!("payload: could not read TCG2 event log: {e}"); + } + + // Experiment: attempt the User -> Deployed Mode transition from here (pre-ExitBootServices, + // the same position stage0 would do it from), AFTER this boot's PCRs were dumped, so the next + // boot (`--reboot`) shows whether it persisted and whether PCR 7 moved. + if load_options_contains("--set-deployed") { + set_deployed_mode(); + } // EC2's serial console buffer is only flushed periodically; if the payload terminates // immediately the PCR dump above never makes it out. Hold ~60s with a heartbeat so it is @@ -75,9 +91,72 @@ fn main() -> Status { // A test payload never boots an OS, so it never needs to hand control back to stage0. Power // off cleanly instead of returning: a return makes stage0 treat it as an unexpected // fall-through and run its own (~90s) fail-closed drain, needlessly slowing the boot. + // `--reboot` cold-resets instead, for one PCR dump per boot on the same instance (cross-boot + // stability). It loops until the instance is stopped/deleted -- bound it externally (e.g. + // GCP --max-run-duration). + if load_options_contains("--reboot") { + println!("payload: --reboot: cold reset"); + runtime::reset(ResetType::COLD, Status::SUCCESS, None) + } runtime::reset(ResetType::SHUTDOWN, Status::SUCCESS, None) } +/// Read a UEFI global variable: `Some((first byte, attributes))`, or `None` if absent/unreadable. +fn global_var(name: &CStr16) -> Option<(u8, VariableAttributes)> { + let mut buf = [0u8; 8]; + runtime::get_variable(name, &VariableVendor::GLOBAL_VARIABLE, &mut buf) + .ok() + .and_then(|(data, attrs)| data.first().map(|b| (*b, attrs))) +} + +/// One line per mode variable: "payload: mode = attrs=0x" or "=absent". +fn print_mode_vars() { + for name in [ + uefi::cstr16!("SecureBoot"), + uefi::cstr16!("SetupMode"), + uefi::cstr16!("AuditMode"), + uefi::cstr16!("DeployedMode"), + ] { + match global_var(name) { + Some((v, a)) => println!("payload: mode {name}={v} attrs=0x{:02x}", a.bits()), + None => println!("payload: mode {name}=absent"), + } + } +} + +/// Try `DeployedMode = 1`, first with the UEFI-spec attributes (BS|RT), then NV|BS|RT; report +/// each SetVariable status and the read-back. Experiment only: says whether the firmware allows +/// the transition from a pre-ExitBootServices image, not whether it is irreversible. +fn set_deployed_mode() { + if matches!(global_var(uefi::cstr16!("DeployedMode")), Some((1, _))) { + println!("payload: --set-deployed: already DeployedMode=1, nothing to do"); + return; + } + let bs_rt = VariableAttributes::BOOTSERVICE_ACCESS | VariableAttributes::RUNTIME_ACCESS; + for (label, attrs) in [ + ("BS|RT", bs_rt), + ("NV|BS|RT", bs_rt | VariableAttributes::NON_VOLATILE), + ] { + let r = runtime::set_variable( + uefi::cstr16!("DeployedMode"), + &VariableVendor::GLOBAL_VARIABLE, + attrs, + &[1u8], + ); + match r { + Ok(()) => { + println!("payload: --set-deployed: SetVariable({label}) = SUCCESS"); + break; + } + Err(e) => println!( + "payload: --set-deployed: SetVariable({label}) = {:?}", + e.status() + ), + } + } + print_mode_vars(); +} + /// True if this image's UEFI LoadOptions (set by stage0 from `_stage1.args` / a signed manifest) /// contain the ASCII `flag`. Lets the QEMU test harness (`--nosleep`) skip the EC2-only /// serial-flush hold. LoadOptions are UCS-2, so an ASCII flag encodes as each byte followed by @@ -133,3 +212,40 @@ fn print_pcrs() -> Result<()> { println!("payload: ===PCR-DUMP-END==="); Ok(()) } + +/// Dump the firmware's TCG2 (crypto-agile) event log, so the PCR predictor's event sequence can +/// be checked against what the firmware actually measured. Per event, bracketed by stable markers: +/// payload: EV +/// payload: EVD (one per bank) +/// payload: EVX (event data, <= 64 bytes per line, in order) +fn print_event_log() -> Result<()> { + let handle = boot::get_handle_for_protocol::() + .map_err(|e| anyhow!("no EFI_TCG2_PROTOCOL: {:?}", e.status()))?; + let mut tcg = boot::open_protocol_exclusive::(handle) + .map_err(|e| anyhow!("open EFI_TCG2_PROTOCOL: {:?}", e.status()))?; + let log = tcg + .get_event_log_v2() + .map_err(|e| anyhow!("GetEventLog(TCG_2): {:?}", e.status()))?; + + println!("payload: ===EVENTLOG-BEGIN==="); + let mut n = 0usize; + for ev in log.iter() { + println!( + "payload: EV {n} {} {:08x}", + ev.pcr_index().0, + ev.event_type().0 + ); + for (alg, digest) in ev.digests() { + println!("payload: EVD {n} {:04x} {}", alg.0, hex::encode(digest)); + } + for chunk in ev.event_data().chunks(64) { + println!("payload: EVX {n} {}", hex::encode(chunk)); + } + n += 1; + } + println!( + "payload: ===EVENTLOG-END=== events={n} truncated={}", + log.is_truncated() + ); + Ok(()) +} diff --git a/crates/stage0/src/lapic_tick.rs b/crates/stage0/src/lapic_tick.rs new file mode 100644 index 0000000..b1bd2c2 --- /dev/null +++ b/crates/stage0/src/lapic_tick.rs @@ -0,0 +1,348 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! A local-APIC timer tick for firmware whose own tick never arrives. +//! +//! GCE's firmware (the `ovmf_x64_csm` family) drives the UEFI tick from the 8254 PIT through +//! the 8259 PIC (OVMF `8254TimerDxe`; upstream OVMF moved every build to `LocalApicTimerDxe` +//! in 89bd992b1f). An Intel TDX guest receives interrupts only through its virtual x2APIC, so +//! IRQ0 is never delivered: the PIT counts, but no timer event ever fires -- and EDK2's network +//! stack (MNP receive polling, DHCP retransmits, TCP timers) runs on timer events. Measured on +//! GCE c3-standard-4: 0 ticks of a 10 ms periodic event in 300 ms under TDX, 30 on Shielded. +//! +//! [`ensure`] checks whether the firmware tick is alive and, only if it is dead, does what +//! `LocalApicTimerDxe` would: program the local APIC timer periodic at the firmware's own +//! timer period on a free vector, and from its interrupt call the firmware timer driver's +//! `GenerateSoftInterrupt()`, which runs the registered tick handler (`CoreTimerTick`) for one +//! period. The firmware's tick bookkeeping is untouched; it just gets its interrupts. The +//! LAPIC timer is masked again at ExitBootServices, so the OS starts with it as it was. +//! +//! The interrupt handler follows `LocalApicTimerDxe`'s structure, including its use of OVMF's +//! NestedInterruptTplLib (ported below as [`nested_raise_tpl`] / [`nested_restore_tpl`]): +//! RestoreTPL() re-enables interrupts while it dispatches event notifications, so a burst of +//! ticks arriving just as an outer RestoreTPL() finishes would otherwise nest without bound and +//! exhaust the stack. + +use core::arch::asm; +use core::ffi::c_void; +use core::ptr::{self, NonNull}; +use core::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicUsize, Ordering}; + +use uefi::boot::{self, EventType, OpenProtocolAttributes, OpenProtocolParams, Tpl}; +use uefi::proto::unsafe_protocol; +use uefi::{Event, Status}; +use uefi_raw::table::boot::Tpl as RawTpl; + +/// `EFI_TIMER_ARCH_PROTOCOL` (PI spec vol. 2). +#[repr(C)] +struct TimerArchProtocol { + register_handler: usize, + set_timer_period: usize, + get_timer_period: unsafe extern "efiapi" fn(*mut TimerArchProtocol, *mut u64) -> Status, + generate_soft_interrupt: unsafe extern "efiapi" fn(*mut TimerArchProtocol) -> Status, +} + +/// `EFI_CPU_INTERRUPT_HANDLER`: (interrupt type, EFI_SYSTEM_CONTEXT -- a pointer union). +type InterruptHandler = unsafe extern "efiapi" fn(isize, *mut c_void); + +/// `EFI_CPU_ARCH_PROTOCOL` (PI spec vol. 2), up to the member used. +#[repr(C)] +struct CpuArchProtocol { + flush_data_cache: usize, + enable_interrupt: usize, + disable_interrupt: usize, + get_interrupt_state: usize, + init: usize, + register_interrupt_handler: + unsafe extern "efiapi" fn(*mut CpuArchProtocol, isize, Option) -> Status, +} + +#[unsafe_protocol("26baccb3-6f42-11d4-bce7-0080c73c8881")] +struct TimerArch(TimerArchProtocol); + +#[unsafe_protocol("26baccb1-6f42-11d4-bce7-0080c73c8881")] +struct CpuArch(CpuArchProtocol); + +/// Vectors tried for the tick, first free one wins (RegisterInterruptHandler refuses a vector +/// that already has a handler, e.g. the 8259's 0x68..0x77). +const VECTORS: core::ops::RangeInclusive = 0x40..=0xef; + +/// How long the liveness probe waits for one firmware tick. +const PROBE_MS: usize = 50; + +// x2APIC MSRs (Intel SDM vol. 3 10.12.1.2) and their xAPIC MMIO offsets (MSR - 0x800) << 4. +const APIC_BASE_MSR: u32 = 0x1b; +const X2APIC_ENABLE: u64 = 1 << 10; +const REG_EOI: u32 = 0x80b; +const REG_LVT_TIMER: u32 = 0x832; +const REG_INIT_COUNT: u32 = 0x838; +const REG_CUR_COUNT: u32 = 0x839; +const REG_DIVIDE: u32 = 0x83e; +const LVT_MASKED: u32 = 1 << 16; +const LVT_PERIODIC: u32 = 1 << 17; +const DIVIDE_BY_1: u32 = 0b1011; + +/// The timer arch protocol the ISR ticks, and the xAPIC MMIO base (null in x2APIC mode). +static TIMER: AtomicPtr = AtomicPtr::new(ptr::null_mut()); +/// The LAPIC timer registers as the firmware left them, restored at ExitBootServices: +/// LVT timer, initial count, divide configuration. +static SAVED_LVT: AtomicU32 = AtomicU32::new(0); +static SAVED_INIT: AtomicU32 = AtomicU32::new(0); +static SAVED_DIVIDE: AtomicU32 = AtomicU32::new(0); +static ENGAGED: AtomicBool = AtomicBool::new(false); +static XAPIC_MMIO: AtomicPtr = AtomicPtr::new(ptr::null_mut()); +static PROBE_TICKS: AtomicU32 = AtomicU32::new(0); + +unsafe fn rdmsr(msr: u32) -> u64 { + let (lo, hi): (u32, u32); + asm!("rdmsr", in("ecx") msr, out("eax") lo, out("edx") hi, options(nomem, nostack)); + ((hi as u64) << 32) | lo as u64 +} + +unsafe fn wrmsr(msr: u32, v: u64) { + asm!("wrmsr", in("ecx") msr, in("eax") v as u32, in("edx") (v >> 32) as u32, + options(nomem, nostack)); +} + +unsafe fn apic_read(reg: u32) -> u32 { + let mmio = XAPIC_MMIO.load(Ordering::Relaxed); + if mmio.is_null() { + rdmsr(reg) as u32 + } else { + (mmio.add(((reg - 0x800) << 4) as usize) as *const u32).read_volatile() + } +} + +unsafe fn apic_write(reg: u32, v: u32) { + let mmio = XAPIC_MMIO.load(Ordering::Relaxed); + if mmio.is_null() { + wrmsr(reg, v as u64) + } else { + (mmio.add(((reg - 0x800) << 4) as usize) as *mut u32).write_volatile(v) + } +} + +unsafe extern "efiapi" fn probe_tick(_e: Event, _c: Option>) { + PROBE_TICKS.fetch_add(1, Ordering::Relaxed); +} + +/// Count firmware timer ticks of a 10 ms periodic event over `ms` milliseconds of stall. +fn ticks_in(ms: usize) -> Option { + let ev = unsafe { + boot::create_event( + EventType::TIMER | EventType::NOTIFY_SIGNAL, + Tpl::CALLBACK, + Some(probe_tick), + None, + ) + } + .ok()?; + let start = PROBE_TICKS.load(Ordering::Relaxed); + let armed = boot::set_timer(&ev, boot::TimerTrigger::Periodic(100_000)).is_ok(); + boot::stall(ms * 1000); + let n = PROBE_TICKS.load(Ordering::Relaxed).wrapping_sub(start); + let _ = boot::close_event(ev); + armed.then_some(n) +} + +// ---- NestedInterruptTplLib, ported -------------------------------------------------------- +// From EDK2 OvmfPkg/Library/NestedInterruptTplLib (Tpl.c, Iret.c), Copyright (C) 2022, Fen +// Systems Ltd., SPDX-License-Identifier: BSD-2-Clause-Patent. Same algorithm; the shared state +// (NESTED_INTERRUPT_STATE) is only touched with interrupts disabled on the boot CPU. + +/// `IsrState->InProgressRestoreTPL` / `IsrState->DeferredRestoreTPL`. +static IN_PROGRESS_RESTORE_TPL: AtomicUsize = AtomicUsize::new(0); +static DEFERRED_RESTORE_TPL: AtomicBool = AtomicBool::new(false); + +/// The prefix of `EFI_SYSTEM_CONTEXT_X64` up to `Rflags` (MdePkg Protocol/DebugSupport.h). +#[repr(C)] +struct SystemContextX64 { + exception_data: u64, + fx_save_state: [u8; 512], + dr: [u64; 6], // Dr0-3, Dr6, Dr7 + cr: [u64; 6], // Cr0-4, Cr8 + rflags: u64, +} +const RFLAGS_IF: u64 = 1 << 9; + +unsafe fn boot_services() -> *mut uefi_raw::table::boot::BootServices { + match uefi::table::system_table_raw() { + Some(st) => (*st.as_ptr()).boot_services, + None => ptr::null_mut(), + } +} + +/// `NestedInterruptRaiseTPL`: raise to TPL_HIGH_LEVEL from inside an interrupt handler +/// (interrupts are already disabled); returns the TPL the interrupt occurred at. +unsafe fn nested_raise_tpl(bs: *mut uefi_raw::table::boot::BootServices) -> RawTpl { + ((*bs).raise_tpl)(RawTpl::HIGH_LEVEL) +} + +/// `NestedInterruptRestoreTPL`: lower back to `interrupted`, deferring to an outer instance of +/// this handler when that is the only way to avoid an unbounded stack of RestoreTPL() frames. +unsafe fn nested_restore_tpl( + bs: *mut uefi_raw::table::boot::BootServices, + interrupted: RawTpl, + ctx: *mut SystemContextX64, +) { + // The interrupt hit an outer handler's RestoreTPL() at the point it had finished + // dispatching (same TPL): return still at TPL_HIGH_LEVEL with interrupts disabled, and let + // that outer handler perform the RestoreTPL() (the "DEFERRAL INVOCATION POINT"). + if interrupted.0 == IN_PROGRESS_RESTORE_TPL.load(Ordering::Relaxed) { + DEFERRED_RESTORE_TPL.store(true, Ordering::Relaxed); + (*ctx).rflags &= !RFLAGS_IF; // DisableInterruptsOnIret + return; + } + // Otherwise the outer RestoreTPL() (if any) is still dispatching at a lower TPL: restore here, + // as often as inner handlers defer to us. Bounded by the number of distinct TPLs. + loop { + let saved = IN_PROGRESS_RESTORE_TPL.swap(interrupted.0, Ordering::Relaxed); + ((*bs).restore_tpl)(interrupted); // re-enables interrupts below TPL_HIGH_LEVEL + asm!("cli", options(nomem, nostack)); + // DEFERRAL RETURN POINT + IN_PROGRESS_RESTORE_TPL.store(saved, Ordering::Relaxed); + if !DEFERRED_RESTORE_TPL.swap(false, Ordering::Relaxed) { + return; + } + } +} + +/// The LAPIC timer interrupt, shaped like `LocalApicTimerDxe`'s TimerInterruptHandler: raise +/// to TPL_HIGH_LEVEL, EOI, one firmware tick (GenerateSoftInterrupt raises/restores HIGH->HIGH, +/// so it dispatches nothing itself), then the nested-safe restore that dispatches events. +unsafe extern "efiapi" fn on_tick(_vector: isize, ctx: *mut c_void) { + let bs = boot_services(); + if bs.is_null() { + apic_write(REG_EOI, 0); + return; + } + let interrupted = nested_raise_tpl(bs); + apic_write(REG_EOI, 0); + let t = TIMER.load(Ordering::Acquire); + if !t.is_null() { + let _ = ((*t).generate_soft_interrupt)(t); + } + nested_restore_tpl(bs, interrupted, ctx as *mut SystemContextX64); +} + +/// Put the LAPIC timer back before the OS takes over. +unsafe extern "efiapi" fn on_exit_boot_services(_e: Event, _c: Option>) { + restore_lapic(); +} + +/// Stop our tick and put the LAPIC timer registers back exactly as the firmware left them. +unsafe fn restore_lapic() { + if !ENGAGED.swap(false, Ordering::AcqRel) { + return; + } + apic_write(REG_LVT_TIMER, LVT_MASKED); // stop interrupts first + apic_write(REG_DIVIDE, SAVED_DIVIDE.load(Ordering::Relaxed)); + apic_write(REG_LVT_TIMER, SAVED_LVT.load(Ordering::Relaxed)); + apic_write(REG_INIT_COUNT, SAVED_INIT.load(Ordering::Relaxed)); +} + +fn open() -> Option> { + let handle = boot::get_handle_for_protocol::

().ok()?; + unsafe { + boot::open_protocol::

( + OpenProtocolParams { + handle, + agent: boot::image_handle(), + controller: None, + }, + OpenProtocolAttributes::GetProtocol, + ) + } + .ok() +} + +/// Make sure the UEFI timer ticks: a no-op when the firmware's own tick is alive, otherwise +/// supply one from the local APIC timer. Call once, early (before anything event-driven). +pub fn ensure() { + match ticks_in(PROBE_MS) { + Some(n) if n > 0 => return, + Some(_) => {} + None => { + crate::slog!("stage0: timer: cannot probe the firmware tick (create/set_timer failed)"); + return; + } + } + match unsafe { install() } { + Ok(msg) => { + let n = ticks_in(PROBE_MS).unwrap_or(0); + crate::slog!("stage0: timer: firmware tick dead; {msg}: {n} ticks in {PROBE_MS} ms"); + } + Err(why) => crate::slog!("stage0: timer: firmware tick dead and no LAPIC tick: {why}"), + } +} + +unsafe fn install() -> Result { + let mut timer = open::().ok_or("no EFI_TIMER_ARCH_PROTOCOL")?; + let mut cpu = open::().ok_or("no EFI_CPU_ARCH_PROTOCOL")?; + let timer_p: *mut TimerArchProtocol = &mut timer.0; + let cpu_p: *mut CpuArchProtocol = &mut cpu.0; + + // The firmware's tick period (100 ns units); each GenerateSoftInterrupt advances it by this. + let mut period: u64 = 0; + if !((*timer_p).get_timer_period)(timer_p, &mut period).is_success() || period == 0 { + return Err("firmware timer period unavailable or 0"); + } + + let base = rdmsr(APIC_BASE_MSR); + if base & X2APIC_ENABLE == 0 { + XAPIC_MMIO.store((base & 0xffff_f000) as *mut u8, Ordering::Relaxed); + } + + SAVED_LVT.store(apic_read(REG_LVT_TIMER), Ordering::Relaxed); + SAVED_INIT.store(apic_read(REG_INIT_COUNT), Ordering::Relaxed); + SAVED_DIVIDE.store(apic_read(REG_DIVIDE), Ordering::Relaxed); + ENGAGED.store(true, Ordering::Release); + + // Calibrate the LAPIC timer (divide by 1, masked one-shot) against a 10 ms stall. + apic_write(REG_DIVIDE, DIVIDE_BY_1); + apic_write(REG_LVT_TIMER, LVT_MASKED); + apic_write(REG_INIT_COUNT, u32::MAX); + boot::stall(10_000); + let per_10ms = u32::MAX - apic_read(REG_CUR_COUNT); + apic_write(REG_INIT_COUNT, 0); + if per_10ms == 0 { + restore_lapic(); + return Err("LAPIC timer does not count"); + } + let count = (per_10ms as u64 * period / 100_000).clamp(1, u32::MAX as u64) as u32; + + // Arm the ExitBootServices mask before the tick can run. + boot::create_event( + EventType::SIGNAL_EXIT_BOOT_SERVICES, + Tpl::NOTIFY, + Some(on_exit_boot_services), + None, + ) + .map_err(|_| { + restore_lapic(); + "cannot create the ExitBootServices event" + })?; + + TIMER.store(timer_p, Ordering::Release); + let vector = VECTORS + .clone() + .find(|&v| ((*cpu_p).register_interrupt_handler)(cpu_p, v, Some(on_tick)).is_success()) + .ok_or_else(|| { + restore_lapic(); + "no free interrupt vector" + })?; + apic_write(REG_LVT_TIMER, LVT_PERIODIC | vector as u32); + apic_write(REG_INIT_COUNT, count); + + // Both are architectural protocols that live as long as boot services; keep them open. + core::mem::forget(timer); + core::mem::forget(cpu); + Ok(alloc::format!( + "LAPIC tick on vector {vector:#x} ({}, {count} counts per {} us)", + if XAPIC_MMIO.load(Ordering::Relaxed).is_null() { + "x2APIC" + } else { + "xAPIC" + }, + period / 10 + )) +} diff --git a/crates/stage0/src/main.rs b/crates/stage0/src/main.rs index 6348063..58befd6 100644 --- a/crates/stage0/src/main.rs +++ b/crates/stage0/src/main.rs @@ -24,6 +24,8 @@ mod config; mod dns4; mod embedded; mod http; +#[cfg(target_arch = "x86_64")] +mod lapic_tick; mod metadata; mod net; mod secauth; @@ -85,14 +87,19 @@ fn run() -> Result<(), Status> { // Calibrate the boot-relative clock first so every log line below is stamped. timing::init(); crate::slog!("stage0: version: {}", env!("CARGO_PKG_VERSION")); + // Before anything event-driven (the network stack runs on timer events): supply a LAPIC tick + // if the firmware's own never arrives (GCE's PIT-driven firmware under Intel TDX). + #[cfg(target_arch = "x86_64")] + lapic_tick::ensure(); // Fail closed unless the platform is in the state the attestation model assumes: UEFI Secure - // Boot enabled AND Deployed Mode. Enforcing it here means "authentic stage0 ran" -- proven by - // stage0's pinned firmware measurement -- implies the SB/deployed state held, even on firmware - // that does not measure DeployedMode into PCR 7. State only: the release signing cert is - // ephemeral (unknown at build time), so key identity is bound by the per-provider/per-arch - // golden PCR set (PCR 7 == the db), not here. - require_secure_boot_deployed()?; + // Boot enforcing -- SecureBoot on, not in Setup Mode, not in Audit Mode. User and Deployed Mode + // are both accepted (GCP can only provision PK/KEK/db/dbx, so its firmware starts in User + // Mode). Enforcing it here means "authentic stage0 ran" -- proven by stage0's pinned firmware + // measurement -- implies enforcement held. State only: the release signing cert is ephemeral + // (unknown at build time), so key identity is bound by the per-provider/per-arch golden PCR + // set (PCR 7 == SecureBoot/PK/KEK/db/dbx), not here. + require_secure_boot_enforcing()?; // Bring the network up once (DHCP), then fetch metadata. Metadata and payload // both ride the raw-TCP4 HTTP client (http.rs). @@ -145,23 +152,41 @@ fn run() -> Result<(), Status> { Ok(()) } -/// Fail-closed gate: require UEFI Secure Boot enabled AND Deployed Mode, both read straight from -/// the firmware variables (reliable here, pre-ExitBootServices -- unlike later in Linux). Rejects -/// if either is not exactly 1, or the variable is absent (Setup/User/Audit mode, or firmware that -/// does not implement Deployed Mode -- in which case the platform cannot make the guarantee). -fn require_secure_boot_deployed() -> Result<(), Status> { +/// Fail-closed gate on the Secure Boot state, read straight from the firmware variables (reliable +/// here, pre-ExitBootServices -- unlike later in Linux): +/// +/// * `SecureBoot` must be exactly 1; +/// * `SetupMode` must be exactly 0 (absent = cannot tell -> refuse); +/// * `AuditMode` must be 0 or absent (absent: pre-UEFI-2.5 firmware, which has no Audit Mode). +/// +/// That admits User Mode and Deployed Mode, the two modes where signature checks are enforced +/// and the key databases can only change via PK/KEK-signed updates. Setup Mode (no PK, keys +/// writable) and Audit Mode (violations logged, images run) are refused. The mode is logged. +fn require_secure_boot_enforcing() -> Result<(), Status> { if global_var_u8(uefi::cstr16!("SecureBoot")) != Some(1) { crate::slog!("stage0: refusing to boot: UEFI Secure Boot is not enabled"); return Err(Status::SECURITY_VIOLATION); } - if global_var_u8(uefi::cstr16!("DeployedMode")) != Some(1) { - crate::slog!("stage0: refusing to boot: platform is not in UEFI Deployed Mode"); + if global_var_u8(uefi::cstr16!("SetupMode")) != Some(0) { + crate::slog!( + "stage0: refusing to boot: platform is in (or cannot rule out) UEFI Setup Mode" + ); return Err(Status::SECURITY_VIOLATION); } + if !matches!(global_var_u8(uefi::cstr16!("AuditMode")), None | Some(0)) { + crate::slog!("stage0: refusing to boot: platform is in UEFI Audit Mode"); + return Err(Status::SECURITY_VIOLATION); + } + let mode = match global_var_u8(uefi::cstr16!("DeployedMode")) { + Some(1) => "Deployed", + _ => "User", + }; + crate::slog!("stage0: Secure Boot enforcing ({mode} Mode)"); Ok(()) } -/// Read a one-byte UEFI global variable (`SecureBoot` / `DeployedMode` are UINT8). `None` if absent. +/// Read a one-byte UEFI global variable (`SecureBoot` / `SetupMode` / `AuditMode` / +/// `DeployedMode` are UINT8). `None` if absent. fn global_var_u8(name: &CStr16) -> Option { let mut buf = [0u8; 1]; runtime::get_variable(name, &VariableVendor::GLOBAL_VARIABLE, &mut buf) diff --git a/crates/stage0/src/net.rs b/crates/stage0/src/net.rs index c0ac261..3736d37 100644 --- a/crates/stage0/src/net.rs +++ b/crates/stage0/src/net.rs @@ -5,8 +5,9 @@ //! assume the interface is addressed. Nothing here is HTTP-specific. use uefi::boot; +use uefi::proto::loaded_image::LoadedImage; use uefi::proto::network::ip4config2::Ip4Config2; -use uefi::Status; +use uefi::{Handle, Status}; use uefi_raw::protocol::network::ip4_config2::Ip4Config2Policy; /// How often to poll for the DHCP lease. Fine-grained so bring-up returns promptly @@ -16,41 +17,72 @@ const DHCP_POLL_INTERVAL_MS: u64 = 10; /// Give up on DHCP after this long. const DHCP_TIMEOUT_MS: u64 = 30_000; -/// The ENA driver, built per-arch by the Makefile into `build//ena.efi` and -/// embedded unconditionally: stage0 + ena ship as ONE measured unit (the driver is -/// covered by stage0's PCR4, no separate pin). EC2's Nitro firmware ships no ENA -/// driver, so without this there is no SNP for the IP4/TCP4/UDP4 stack to bind. -/// Building stage0 requires `build//ena.efi` to exist (the Makefile builds it -/// first); a missing file is a hard compile error, by design. -#[cfg(target_arch = "x86_64")] -static ENA_DRIVER: &[u8] = include_bytes!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../build/x86_64/ena.efi" -)); -#[cfg(target_arch = "aarch64")] -static ENA_DRIVER: &[u8] = include_bytes!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../build/aarch64/ena.efi" -)); +/// The embedded NIC drivers, built per-arch by the Makefile into `build//*.efi` and +/// embedded unconditionally: stage0 + its drivers ship as ONE measured unit (covered by +/// stage0's PCR4, no separate pin). Each fills a firmware gap: +/// * `ena.efi` -- EC2: Nitro's UEFI firmware ships no ENA driver; +/// * `gvnic.efi` -- GCP: the UEFI firmware ships no gVNIC driver (and GCP requires gVNIC +/// for Confidential VMs and Arm). +/// +/// Without them there is no SNP for the firmware's IP4/TCP4/UDP4 stack to bind. Building +/// stage0 requires the files to exist (the Makefile builds them first); a missing file is a +/// hard compile error, by design. +macro_rules! embedded_driver { + ($name:literal) => {{ + #[cfg(target_arch = "x86_64")] + static D: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../build/x86_64/", + $name + )); + #[cfg(target_arch = "aarch64")] + static D: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../build/aarch64/", + $name + )); + D + }}; +} -/// Load and start any embedded UEFI NIC drivers, before connecting controllers, so a -/// firmware that lacks a driver for its NIC (notably EC2/ENA) still gets an SNP -/// producer. The driver is a well-behaved Driver-Model driver: inert on platforms -/// whose NIC it does not match (GCP virtio-net, local QEMU). +/// Load and start the embedded UEFI NIC drivers, before connecting controllers, so a +/// firmware that lacks a driver for its NIC (EC2/ENA, GCP/gVNIC) still gets an SNP +/// producer. Each is a well-behaved Driver-Model driver: inert on platforms whose NIC it +/// does not match (its Supported() gates on PCI vendor:device). fn load_embedded_drivers() { - crate::slog!( - "stage0: loading embedded ena driver ({} bytes)", - ENA_DRIVER.len() - ); - match crate::secauth::load_image_verified(ENA_DRIVER) { - Ok(handle) => match boot::start_image(handle) { - Ok(()) => crate::slog!("stage0: ena driver started"), - Err(e) => crate::slog!("stage0: ena start_image failed: {:?}", e.status()), - }, - Err(status) => crate::slog!("stage0: ena load_image failed: {status:?}"), + let drivers: [(&str, &[u8]); 2] = [ + ("ena", embedded_driver!("ena.efi")), + ("gvnic", embedded_driver!("gvnic.efi")), + ]; + for (name, image) in drivers { + crate::slog!( + "stage0: loading embedded {name} driver ({} bytes)", + image.len() + ); + // The driver copies the epoch in its entry point, i.e. during start_image, so a local + // buffer outlives its use. + let epoch = crate::timing::epoch(); + match crate::secauth::load_image_verified(image) { + Ok(handle) => { + match set_driver_epoch(handle, &epoch).and_then(|()| boot::start_image(handle)) { + Ok(()) => crate::slog!("stage0: {name} driver started"), + Err(e) => crate::slog!("stage0: {name} start failed: {:?}", e.status()), + } + } + Err(status) => crate::slog!("stage0: {name} load_image failed: {status:?}"), + } } } +/// Hand a loaded driver image stage0's log-timestamp epoch as its LoadOptions. +fn set_driver_epoch(handle: Handle, epoch: &[u8; 16]) -> uefi::Result { + let mut loaded = boot::open_protocol_exclusive::(handle)?; + // SAFETY: `epoch` outlives the driver's read of it (its entry point, run by the + // start_image that follows; the protocol is closed again when `loaded` drops). + unsafe { loaded.set_load_options(epoch.as_ptr(), epoch.len() as u32) }; + Ok(()) +} + /// Bring the network up: connect the firmware's drivers, then obtain a DHCP lease. /// Call once before any networking. pub fn bringup() -> Result<(), Status> { @@ -61,6 +93,7 @@ pub fn bringup() -> Result<(), Status> { "stage0: no EFI_IP4_CONFIG2 (firmware lacks the IPv4 stack?): {:?}", e.status() ); + log_net_inventory(); e.status() })?; let mut ip4 = Ip4Config2::new(nic).map_err(|e| e.status())?; @@ -113,6 +146,54 @@ fn dhcp_up(ip4: &mut Ip4Config2) -> Result<(), Status> { } } +/// Failure-path diagnostic (we are about to fail closed anyway): which layer of the UEFI network +/// stack is missing. Logs how many handles carry each layer's protocol, bottom-up (PCI device -> +/// SNP -> MNP -> ARP/IP4 -> IP4Config2/DHCP4 -> UDP4/TCP4), then the name of every loaded +/// driver (DriverBinding handles, named via ComponentName2/1), so "no SNP on the NIC" (no NIC +/// driver), "SNP but no MNP/IP4" (no NetworkPkg stack), and "stack present but unbound" are +/// distinguishable from the serial log alone. +fn log_net_inventory() { + use uefi::proto::driver::ComponentName; + use uefi::{guid, Guid}; + const LAYERS: [(&str, Guid); 9] = [ + ("PciIo", guid!("4cf5b200-68b8-4ca5-9eec-b23e3f50029a")), + ("SNP", guid!("a19832b9-ac25-11d3-9a2d-0090273fc14d")), + ("MNP-SB", guid!("f36ff770-a7e1-42cf-9ed2-56f0f271f44c")), + ("ARP-SB", guid!("f44c00ee-1f2c-4a00-aa09-1c9f3e0800a3")), + ("IP4-SB", guid!("c51711e7-b4bf-404a-bfb8-0a048ef1ffe4")), + ("IP4Config2", guid!("5b446ed1-e30b-4faa-871a-3654eca36080")), + ("DHCP4-SB", guid!("9d9a39d8-bd42-4a73-a4d5-8ee94be11380")), + ("UDP4-SB", guid!("83f01464-99bd-45e5-b383-af6305d8e9e6")), + ("TCP4-SB", guid!("00720665-67eb-4a99-baf7-d3c33a1c7cc9")), + ]; + let count = |g: &Guid| { + boot::locate_handle_buffer(boot::SearchType::ByProtocol(g)) + .map(|h| h.len()) + .unwrap_or(0) + }; + for (name, g) in LAYERS.iter() { + crate::slog!("stage0: net inventory: {name}={}", count(g)); + } + + const DRIVER_BINDING: Guid = guid!("18a031ab-b443-4d1a-a5c0-0c09261e9f71"); + let Ok(drivers) = boot::locate_handle_buffer(boot::SearchType::ByProtocol(&DRIVER_BINDING)) + else { + crate::slog!("stage0: net inventory: no DriverBinding handles"); + return; + }; + crate::slog!("stage0: net inventory: {} drivers loaded:", drivers.len()); + for h in drivers.iter() { + let named = ComponentName::open(*h).ok().and_then(|cn| { + let lang = cn.supported_languages().ok()?.next()?; + cn.driver_name(lang).ok().map(|n| alloc::format!("{n}")) + }); + crate::slog!( + "stage0: net inventory: driver {}", + named.as_deref().unwrap_or("(unnamed)") + ); + } +} + /// Connect all drivers to all handles (best-effort), forcing the firmware to bind /// its network stack so the TCP4/IP4 service bindings become available even on the /// first boot before BDS has connected everything. diff --git a/crates/stage0/src/timing.rs b/crates/stage0/src/timing.rs index 45be359..5c3fa94 100644 --- a/crates/stage0/src/timing.rs +++ b/crates/stage0/src/timing.rs @@ -72,6 +72,16 @@ pub fn since_boot_ms() -> u64 { raw().wrapping_sub(START.load(Ordering::Relaxed)) / per_ms } +/// This timeline's epoch for an embedded driver's `LoadOptions`: the raw counter value at t = 0 +/// and the calibrated cycles per millisecond, each a little-endian u64. The driver reads the +/// same counter, so its log stamps land on stage0's timeline (gvnic `clock.rs`). +pub fn epoch() -> [u8; 16] { + let mut e = [0u8; 16]; + e[..8].copy_from_slice(&START.load(Ordering::Relaxed).to_le_bytes()); + e[8..].copy_from_slice(&CYCLES_PER_MS.load(Ordering::Relaxed).to_le_bytes()); + e +} + /// A `[ S.mmm]`-style stamp (seconds.milliseconds since [`init`]). Returns a /// `Display` wrapper so the [`slog!`](crate::slog) macro formats without allocating. pub fn stamp() -> Stamp { diff --git a/crates/stage0/src/udp4.rs b/crates/stage0/src/udp4.rs index 270e805..6bc014b 100644 --- a/crates/stage0/src/udp4.rs +++ b/crates/stage0/src/udp4.rs @@ -309,9 +309,10 @@ fn udp_recv(udp_ptr: *mut Udp4Protocol, budget_ms: u64) -> Result, Statu return Err(st); } - // Copy the datagram out of the (possibly fragmented) receive buffer. We do not - // signal RecycleSignal: this child handles one datagram and is then destroyed, - // which reclaims the buffer. + // Copy the datagram out of the (possibly fragmented) receive buffer, then hand it back + // by signalling RecycleSignal, as the UEFI spec requires. Destroying the child does NOT + // stand in for this: EDK2's Udp4Configure(NULL) ASSERTs the delivered-datagram queue is + // empty, and firmware built with ASSERTs enabled (GCP) resets the machine there. let out = unsafe { let rx = token.packet.rx_data; let mut buf = Vec::new(); @@ -332,6 +333,9 @@ fn udp_recv(udp_ptr: *mut Udp4Protocol, budget_ms: u64) -> Result, Statu )); copied += take; } + if let Some(recycle) = uefi::Event::from_ptr((*rx).recycle_signal) { + let _ = boot::signal_event(&recycle); + } } buf }; diff --git a/tools/build.sh b/tools/build.sh index a6e0d37..70cbeec 100755 --- a/tools/build.sh +++ b/tools/build.sh @@ -93,24 +93,21 @@ echo "Disk image created: ${DISK_IMAGE}" ls -lh "${DISK_IMAGE}" # --- Generate Secure Boot variables (OVMF + AWS) from stage0's own keys --- -if [ "${ARCH}" = "x86_64" ]; then - OVMF_VARS_ORIG="/usr/share/OVMF/OVMF_VARS_4M.fd" -else - OVMF_VARS_ORIG="/usr/share/AAVMF/AAVMF_VARS.snakeoil.fd" -fi +# tools/mkvarstore.py builds the whole enrolled varstore (edk2 pflash + AWS +# AMZNUEFI) from scratch in pure-stdlib Python -- no virt-fw-vars, no distro +# firmware template. Only stage0's PK/KEK/db are enrolled, and the output is +# byte-reproducible (auth-variable timestamp fixed from SOURCE_DATE_EPOCH). EFI_VARS_OVMF="${OUTPUT_DIR}/efi-vars.ovmf" EFI_VARS_AWS="${OUTPUT_DIR}/efi-vars.aws" -if [ -f "${OVMF_VARS_ORIG}" ]; then - virt-fw-vars --input "${OVMF_VARS_ORIG}" --output "${EFI_VARS_OVMF}" --output-aws "${EFI_VARS_AWS}" \ - --add-db "$(cat "${KEYDIR}/db.guid")" "${KEYDIR}/db.crt" \ - --add-kek "$(cat "${KEYDIR}/KEK.guid")" "${KEYDIR}/KEK.crt" \ - --set-pk "$(cat "${KEYDIR}/PK.guid")" "${KEYDIR}/PK.crt" \ - --set-true DeployedMode \ - --secure-boot - echo "EFI vars written: ${EFI_VARS_OVMF}" -else - echo "Warning: ${OVMF_VARS_ORIG} not found; skipping EFI vars generation." -fi +python3 "${REPO_ROOT}/tools/mkvarstore.py" --arch "${ARCH}" \ + --pk "${KEYDIR}/PK.crt" --pk-guid "${KEYDIR}/PK.guid" \ + --kek "${KEYDIR}/KEK.crt" --kek-guid "${KEYDIR}/KEK.guid" \ + --db "${KEYDIR}/db.crt" --db-guid "${KEYDIR}/db.guid" \ + --dict "${REPO_ROOT}/tools/firmware/amznuefi-v0.dict" \ + --out-ovmf "${EFI_VARS_OVMF}" --out-aws "${EFI_VARS_AWS}" \ + --out-dbx "${OUTPUT_DIR}/dbx.esl" \ + --out-dbx-auth "${OUTPUT_DIR}/dbx.auth.bin" --kek-key "${KEYDIR}/KEK.crt.key" +echo "EFI vars written: ${EFI_VARS_OVMF}" # Emit os-release so the cloud publishers can name/tag the image. BUILD_ID is # derived from the signed stage0 hash so each build is traceable. @@ -131,6 +128,13 @@ for f in db.cer db.guid PK.cer PK.guid KEK.cer KEK.guid; do [ -f "${KEYDIR}/${f}" ] && cp "${KEYDIR}/${f}" "${OUTPUT_DIR}/" done +# stage0's PCR replay file (pcr-replay/v1: every event from TPM reset to the payload handoff, +# derived from the artifacts above -- BOOT*.EFI, boot.disk, *.cer, *.guid, dbx.esl) and the +# reference PCRs it replays to (pcrs.json, vaportpm layout). See tools/predict-pcrs.py. +python3 "${REPO_ROOT}/tools/predict-pcrs.py" "${OUTPUT_DIR}" \ + --replay "${OUTPUT_DIR}/stage0.replay.json" --out "${OUTPUT_DIR}/pcrs.json" +echo "PCR replay file written: ${OUTPUT_DIR}/stage0.replay.json (reference: pcrs.json)" + if [ -n "${OWNER_UID:-}" ] && [ -n "${OWNER_GID:-}" ]; then chown -R "${OWNER_UID}:${OWNER_GID}" "${OUTPUT_DIR}" fi diff --git a/tools/firmware/amznuefi-v0.dict b/tools/firmware/amznuefi-v0.dict new file mode 100644 index 0000000..058566e Binary files /dev/null and b/tools/firmware/amznuefi-v0.dict differ diff --git a/tools/gen-keys.sh b/tools/gen-keys.sh index 4707698..e267df0 100755 --- a/tools/gen-keys.sh +++ b/tools/gen-keys.sh @@ -18,7 +18,11 @@ for name in PK KEK db; do -keyout "$OUT/$name.crt.key" -new -x509 -sha256 -days 3650 \ -subj "/CN=Lock.Boot/" -out "$OUT/$name.crt" openssl x509 -outform DER -in "$OUT/$name.crt" -out "$OUT/$name.cer" - uuidgen > "$OUT/$name.guid" + # Signature owner GUID: the fixed one GCP stamps on every X.509 cert it wraps into an + # EFI_SIGNATURE_LIST for PK/KEK/db (undocumented; seen in GCE event logs 2022-2026). Using + # it here makes our efi-vars.* ESLs byte-identical to what GCP enrolls from the .cer files, + # so PCR7 is one value on QEMU, EC2 and GCP. Metadata only: never used for verification. + echo d281fad2-8d88-47a4-9792-5baa47bb1b89 > "$OUT/$name.guid" done echo "Secure Boot keys written to $OUT (PK, KEK, db)" diff --git a/tools/mkvarstore.py b/tools/mkvarstore.py new file mode 100644 index 0000000..1d9d633 --- /dev/null +++ b/tools/mkvarstore.py @@ -0,0 +1,351 @@ +#!/usr/bin/env python3 +# Generate UEFI Secure Boot variable stores from x509 certs, in both the edk2 +# (OVMF/AAVMF pflash) and AWS "AMZNUEFI" (EC2 --uefi-data) container formats. +# +# Pure Python standard library only -- this replaces `virt-fw-vars` (the +# virt-firmware package) in stage0's build so the entire enrolled varstore is +# produced by auditable code we own, byte-reproducibly. Every field below is +# derived from the on-disk edk2 structures (EFI_FIRMWARE_VOLUME_HEADER, +# VARIABLE_STORE_HEADER, AUTHENTICATED_VARIABLE_HEADER, EFI_SIGNATURE_LIST) and +# the AMZNUEFI v0 format (awslabs/python-uefivars); see REPRODUCIBLE-BUILDS.md. +# +# Determinism: unlike virt-fw-vars (which stamps wall-clock time into the +# PK/KEK/db authenticated variables, making its output differ every build), the +# authenticated-variable timestamp here is fixed from SOURCE_DATE_EPOCH. + +import argparse +import base64 +import os +import struct +import subprocess +import sys +import tempfile +import uuid + +# --- Well-known GUIDs (constants from the UEFI spec / edk2) ------------------ +EFI_GLOBAL_VARIABLE = uuid.UUID("8be4df61-93ca-11d2-aa0d-00e098032b8c") +IMAGE_SECURITY_DATABASE = uuid.UUID("d719b2cb-3d3a-4596-a3bc-dad00e67656f") +CUSTOM_MODE_GUID = uuid.UUID("c076ec0c-7028-4399-a072-71ee5c448b9f") +SECURE_BOOT_ENABLE_GUID = uuid.UUID("f0a30bc7-af08-4556-99c4-001009c93a44") +EFI_CERT_X509_GUID = uuid.UUID("a5c059a1-94e4-4aa7-87b5-ab155c2bf072") +EFI_CERT_SHA256_GUID = uuid.UUID("c1c41626-504c-4092-aca9-41f936934328") +NV_DATA_FV_GUID = uuid.UUID("fff12b8d-7696-4c8b-a985-2747075b4f50") +AUTH_VAR_STORE_GUID = uuid.UUID("aaf32c78-947b-439a-a180-2e144ec37792") + +# virt-fw-vars adds a placeholder dbx: sha256("") owned by a fixed GUID, stamped +# 2010-01-01. Reproduced verbatim so our output matches the established shape. +DBX_DUMMY_OWNER = uuid.UUID("a0baa8a3-041d-48a8-bc87-c36d121b5e3d") +SHA256_EMPTY = bytes.fromhex( + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") + +# UEFI variable attributes +NV, BS, RT, TIME_AUTH = 0x1, 0x2, 0x4, 0x20 +ATTR_PLAIN = NV | BS # 0x03: NV + boot-services +ATTR_AUTH = NV | BS | RT | TIME_AUTH # 0x27: + runtime + time-based auth + +# edk2 variable-store state/format bytes +VAR_ADDED = 0x3f # AUTHENTICATED_VARIABLE_HEADER.State for a live variable +VS_FORMATTED = 0x5a # VARIABLE_STORE_HEADER.Format +VS_HEALTHY = 0xfe # VARIABLE_STORE_HEADER.State +VAR_START_ID = 0x55aa + + +# --- EFI_TIME --------------------------------------------------------------- +def efi_time(epoch): + """16-byte EFI_TIME from a UNIX epoch (UTC), nanosecond/timezone/daylight 0.""" + import time + t = time.gmtime(epoch) + return struct.pack("> 1) ^ (0x82f63b78 & -(c & 1)) + _CRC32C_TABLE.append(c & 0xffffffff) + for b in data: + crc = _CRC32C_TABLE[(crc ^ b) & 0xff] ^ (crc >> 8) + return crc ^ 0xffffffff + + +def serialize_aws(varlist, dict_path): + import zlib + zdict = open(dict_path, "rb").read() + raw = bytearray() + raw += struct.pack(" [--banks sha256,sha384] --replay F [--out pcrs.json] +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import struct +import sys +import uuid +from typing import Any + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mkvarstore as mv # noqa: E402 + +BOOT_EFI = {"x86_64": "BOOTX64.EFI", "aarch64": "BOOTAA64.EFI"} +SECTOR = 512 +SEPARATOR = b"\0\0\0\0" +CALLING = "Calling EFI Application from Boot Option" + + +# --- event payloads (the data each event's digest is computed over) ----------------------------- +def uefi_variable_data(vendor: uuid.UUID, name: str, data: bytes) -> bytes: + """UEFI_VARIABLE_DATA: VariableName GUID, UnicodeNameLength, VariableDataLength, name, data.""" + return vendor.bytes_le + struct.pack(" bytes: + """Authenticode PE image hash (the digest firmware logs for a loaded image).""" + pe_off = struct.unpack_from(" done: + h.update(pe[done:end]) + return h.digest() + + +def gpt_data(disk_path: str) -> bytes: + """UEFI_GPT_DATA: the primary GPT header, entry count, then the non-empty entries.""" + with open(disk_path, "rb") as f: + f.seek(SECTOR) + hdr = f.read(SECTOR) + if hdr[:8] != b"EFI PART": + raise SystemExit(f"{disk_path}: no GPT header at LBA 1") + hsize, = struct.unpack_from(" bytes: + with open(os.path.join(d, name), "rb") as f: + return f.read() + + +def owner(d: str, role: str) -> uuid.UUID: + return uuid.UUID(read(d, f"{role}.guid").decode().strip()) + + +def detect_arch(d: str) -> str: + found = [a for a, f in BOOT_EFI.items() if os.path.exists(os.path.join(d, f))] + if len(found) != 1: + raise SystemExit(f"{d}: expected exactly one of {sorted(BOOT_EFI.values())}") + return found[0] + + +def replay_file(d: str, banks: list[str]) -> dict[str, Any]: + arch = detect_arch(d) + efi_name = BOOT_EFI[arch] + files = {n: read(d, n) for n in (efi_name, "boot.disk", "PK.cer", "KEK.cer", "db.cer", "dbx.esl")} + gpt = gpt_data(os.path.join(d, "boot.disk")) + own = {r: owner(d, r) for r in ("PK", "KEK", "db")} + + def var(vendor: uuid.UUID, name: str, data_expr: dict[str, Any]) -> dict[str, Any]: + return {"uefi_variable": {"vendor": str(vendor), "name": name, "data": data_expr}} + + def esl(role: str) -> dict[str, Any]: + return {"efi_signature_list": {"type": "x509", "owner": str(own[role]), + "data": {"artifact": f"{role}.cer"}}} + + sep_expr = {"hex": SEPARATOR.hex()} + # (pcr, type, by, about, derivation, digest mode, bytes for the local computation) + G, S = mv.EFI_GLOBAL_VARIABLE, mv.IMAGE_SECURITY_DATABASE + # In the firmware's log order (OVMF and GCE alike), not grouped by PCR: only the order within a + # PCR affects its value, but a platform that routes some of these events into another PCR (GCE + # TDX: GPT and BOOT*.EFI into PCR2) needs them in the order they really reach it. + ev: list[tuple[int, str, str, str, dict[str, Any], str, bytes]] = [ + (7, "EV_EFI_VARIABLE_DRIVER_CONFIG", "firmware", "SecureBoot = 1", + var(G, "SecureBoot", {"hex": "01"}), "hash", uefi_variable_data(G, "SecureBoot", b"\x01")), + ] + for role, vendor in (("PK", G), ("KEK", G), ("db", S)): + ev.append((7, "EV_EFI_VARIABLE_DRIVER_CONFIG", "firmware", f"{role}: one x509 ESL ({role}.cer)", + var(vendor, role, esl(role)), "hash", + uefi_variable_data(vendor, role, mv.sig_list_x509(files[f"{role}.cer"], own[role])))) + ev += [ + (7, "EV_EFI_VARIABLE_DRIVER_CONFIG", "firmware", "dbx (dbx.esl)", + var(S, "dbx", {"artifact": "dbx.esl"}), "hash", uefi_variable_data(S, "dbx", files["dbx.esl"])), + (7, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (4, "EV_EFI_ACTION", "firmware", "boot option dispatch", {"utf8": CALLING}, "hash", CALLING.encode()), + (3, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (4, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (5, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (6, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (7, "EV_EFI_VARIABLE_AUTHORITY", "firmware", "the db entry that verified stage0", + var(S, "db", {"concat": [{"guid": str(own["db"])}, {"artifact": "db.cer"}]}), "hash", + uefi_variable_data(S, "db", own["db"].bytes_le + files["db.cer"])), + (5, "EV_EFI_GPT_EVENT", "firmware", "UEFI_GPT_DATA of boot.disk", + {"gpt": {"artifact": "boot.disk"}}, "hash", gpt), + (4, "EV_EFI_BOOT_SERVICES_APPLICATION", "firmware", f"stage0 ({efi_name}, Authenticode)", + {"artifact": efi_name}, "authenticode", files[efi_name]), + ] + events: list[dict[str, Any]] = [] + for pcr, typ, by, about, expr, mode, data in ev: + e: dict[str, Any] = {"pcr": pcr, "type": typ, "by": by} + if about: + e["about"] = about + e["derive"] = expr + if mode != "hash": + e["digest"] = mode + e["digests"] = {b: (authenticode(data, getattr(hashlib, b)) if mode == "authenticode" + else getattr(hashlib, b)(data).digest()).hex() for b in banks} + events.append(e) + events.append({"pcr": 14, "type": "unlogged", "by": "stage0", + "about": "the payload stage0 verified and runs: H_bank(sha256(payload))", + "derive": {"input": "payload"}}) + return { + "schema": "pcr-replay/v1", + "name": f"stage0 {arch}", + "about": "UEFI firmware and stage0, from TPM reset to the payload handoff (before " + "ExitBootServices). PCR0-2 are the platform's (a platform replay file).", + "artifacts": {n: {"sha256": hashlib.sha256(b).hexdigest()} for n, b in files.items()}, + "entry": efi_name, + "inputs": {"payload": {"about": "sha256 of the payload stage0 runs (the next stage)", + "next_entry": True}}, + "reset": list(range(3, 24)), + "unextended": [0, 1, 2], + "events": events, + } + + +def reference_pcrs(rf: dict[str, Any], banks: list[str]) -> dict[str, Any]: + """Replay the file's embedded digests from reset: every PCR it models except PCR14.""" + out: dict[str, dict[str, str]] = {} + for b in banks: + H = getattr(hashlib, b) + n = H().digest_size + p = {k: (b"\xff" if 17 <= k <= 22 else b"\0") * n for k in rf["reset"] if k != 14} + for e in rf["events"]: + if e["pcr"] in p: + p[e["pcr"]] = H(p[e["pcr"]] + bytes.fromhex(e["digests"][b])).digest() + out[b] = {str(k): v.hex() for k, v in sorted(p.items())} + return {"pcrs": out} + + +def write_json(path: str, doc: dict[str, Any]) -> None: + with open(path, "w") as f: + json.dump(doc, f, indent=2) + f.write("\n") + + +def main() -> None: + ap = argparse.ArgumentParser(description="Write stage0's PCR replay file (and reference PCRs)") + ap.add_argument("dir", help="stage0 build/ or extracted release directory") + ap.add_argument("--banks", default="sha256,sha384", help="comma-separated (default sha256,sha384)") + ap.add_argument("--replay", required=True, help="write the pcr-replay/v1 file here") + ap.add_argument("--out", help="also write the reference pcrs.json here") + a = ap.parse_args() + banks = a.banks.split(",") + rf = replay_file(a.dir, banks) + write_json(a.replay, rf) + if a.out: + write_json(a.out, reference_pcrs(rf, banks)) + + +if __name__ == "__main__": + main() diff --git a/tools/publish/README.md b/tools/publish/README.md index d0e8983..38c1164 100644 --- a/tools/publish/README.md +++ b/tools/publish/README.md @@ -19,8 +19,9 @@ Each publisher reads the per-arch build output: | `build//efi-vars.aws` | EC2 | AWS-format Secure Boot variable store (`--uefi-data`) | | `build//os-release` | both | names/tags the image (`ID`, `VERSION_ID`, `BUILD_ID`) | | `build//{PK,KEK,db}.cer` | GCP | custom Secure Boot keys | +| `build//dbx.auth.bin` | GCP | our dbx (the exact EFI_SIGNATURE_LIST in `efi-vars.*`, also shipped as `dbx.esl`) as a KEK-signed authenticated update -- the only form GCP's `BIN` dbx accepts at VM start | -Produce them with `make build-`. Or pass a `stage0-v*` release tag as the +Produce them with `make build-`. Or pass a `v*` release tag as the `version` argument (instead of the default `local`) to download and attestation-verify the published release artifacts. @@ -46,7 +47,7 @@ ec2/create.sh [--region R] [--public|--private] [--no-verify] [-- gcp/create.sh [--project P] [--region R] [--public|--private] [--no-verify] [--manifest F] [version] ``` -- `` is `x86_64` or `aarch64`; `version` is `local` (default) or a `stage0-v*` tag. +- `` is `x86_64` or `aarch64`; `version` is `local` (default) or a `v*` tag. - `--region` default: `ap-southeast-1` (AWS, Singapore) / `asia-southeast1` (GCP, Singapore). Singapore is the always-on default; KL `ap-southeast-5` works but is an opt-in region you must enable on the account first. @@ -107,15 +108,17 @@ tools/publish/gcp/get-console.sh my-vm asia-southeast1-a --follow ``` Uploads `boot.disk` as a `disk.raw` tarball to GCS and creates a global image with -your custom PK/KEK/db and these guest-OS features (idempotent: an existing GCS upload -is reused): +your custom PK/KEK/db/dbx and these guest-OS features (idempotent: an existing GCS upload +is reused). dbx is our own (`dbx.auth.bin`): left unset, GCP fills in its default Microsoft dbx, +which makes PCR 7 depend on a list we don't control (and that changes over time). +`--default-dbx` does exactly that, for A/B measurement only (separate `-defdbx` image): - `UEFI_COMPATIBLE` — required for UEFI boot. -- `SEV_CAPABLE`, `SEV_SNP_CAPABLE` — x86_64 only; mark the image launchable as an AMD - SEV / SEV-SNP Confidential VM. +- `SEV_CAPABLE`, `SEV_SNP_CAPABLE`, `TDX_CAPABLE` — x86_64 only; mark the image launchable + as an AMD SEV / SEV-SNP or Intel TDX Confidential VM. - `GVNIC` — Google Virtual NIC. -- aarch64 gets `UEFI_COMPATIBLE` + `GVNIC` only (ARM confidential compute needs no - guest-OS feature flag). +- aarch64 gets `UEFI_COMPATIBLE` + `GVNIC` only (GCP documents no Arm Confidential VM + series; t2a launches as a Shielded VM). We create the image directly from GCS rather than `gcloud compute images import` because `import` demands a predefined `--os` (e.g. `ubuntu-2204`) and won't set custom @@ -124,11 +127,15 @@ guest-OS features — stage0 is kernel-less, so there is no OS for it to detect. **Trust-model requirement:** Confidential VMs must run with `--maintenance-policy=TERMINATE` (no live migration — migration would expose decrypted guest memory to the hypervisor). Never enable the `SEV_LIVE_MIGRATABLE` feature. -`launch-instance.sh` bakes this in along with `--confidential-compute`, -`--shielded-secure-boot`, `--shielded-vtpm`, and `--shielded-integrity-monitoring`. - -Confidential VM machine types: `n2d-standard-*` (SEV / SEV-SNP), `c2d-standard-*` -(SEV-SNP, compute-optimized), `c3-standard-*` (Intel TDX), `t2a-standard-*` (ARM64). +`launch-instance.sh` bakes this in along with the per-family `--confidential-compute-type`, +`--shielded-secure-boot`, `--shielded-vtpm`, `--shielded-integrity-monitoring`, and +`--no-service-account --no-scopes` (the guest never calls GCP APIs, so it gets no credentials). + +Machine types `launch-instance.sh` accepts: `n2d-standard-*` (SEV-SNP, pinned to +`--min-cpu-platform="AMD Milan"`), `c2d-standard-*` (SEV), `c3-standard-*` (Intel TDX), +`t2a-standard-*` (ARM64, Shielded VM only; pass e.g. `--confidential-compute-type=CCA` as a +trailing option to experiment). Pass `--manifest ` first to record the instance for +`cleanup.sh` -- GCP instances keep running (and billing) after stage0 powers off. How GCP differs from EC2 here: GCP manages the Secure Boot vars and vTPM itself (no `--uefi-data` / `--tpm-support`), memory is encrypted by SEV/SEV-SNP/TDX, and the diff --git a/tools/publish/cleanup.sh b/tools/publish/cleanup.sh index de5e07f..846aada 100755 --- a/tools/publish/cleanup.sh +++ b/tools/publish/cleanup.sh @@ -5,9 +5,11 @@ # snapshot still settling) are warnings, not fatal, so this is safe to re-run. # # Manifest line format: " " +# aws instance i-xxxx (ec2/launch.sh --manifest) # aws ami ami-xxxx # aws snapshot snap-xxxx # aws s3object s3://bucket/key +# gcp instance / (gcp/launch-instance.sh --manifest) # gcp image image-name # gcp gcsobject gs://bucket/path @@ -27,7 +29,7 @@ Options: --dry-run print the delete commands without running them -h, --help show this help and exit -Handles: aws {ami,snapshot,s3object}, gcp {image,gcsobject}. +Handles: aws {instance,ami,snapshot,s3object}, gcp {instance,image,gcsobject}. EOF } @@ -56,9 +58,11 @@ for (( i=${#LINES[@]}-1; i>=0; i-- )); do [ -n "${id:-}" ] || { warn "malformed line: ${line}"; skipped=$((skipped+1)); continue; } case "${provider} ${kind}" in + "aws instance") cli=aws; cmd=(aws ec2 terminate-instances --instance-ids "${id}" --region "${ctx}") ;; "aws ami") cli=aws; cmd=(aws ec2 deregister-image --image-id "${id}" --region "${ctx}") ;; "aws snapshot") cli=aws; cmd=(aws ec2 delete-snapshot --snapshot-id "${id}" --region "${ctx}") ;; "aws s3object") cli=aws; cmd=(aws s3 rm "${id}") ;; + "gcp instance") cli=gcloud; cmd=(gcloud compute instances delete "${id#*/}" --zone "${id%%/*}" --project "${ctx}" --quiet) ;; "gcp image") cli=gcloud; cmd=(gcloud compute images delete "${id}" --project "${ctx}" --quiet) ;; "gcp gcsobject") cli=gcloud; cmd=(gcloud storage rm "${id}" --project "${ctx}") ;; *) warn "unknown resource: ${line}"; skipped=$((skipped+1)); continue ;; diff --git a/tools/publish/ec2/create.sh b/tools/publish/ec2/create.sh index b46a081..e474fe0 100755 --- a/tools/publish/ec2/create.sh +++ b/tools/publish/ec2/create.sh @@ -22,7 +22,7 @@ Build (or download) a stage0 boot disk and register it as an AMI. Arguments: arch x86_64 | aarch64 - version a stage0-v* release tag, or 'local' (default) for a local build + version a v* release tag, or 'local' (default) for a local build Options: --region AWS region (default: ${DEFAULT_REGION}) @@ -41,7 +41,7 @@ Options: Examples: $(basename "$0") x86_64 # local build -> public AMI in ${DEFAULT_REGION} - $(basename "$0") --region us-east-1 x86_64 stage0-v0.1.0 + $(basename "$0") --region us-east-1 x86_64 v0.1.0 $(basename "$0") --private aarch64 EOF } @@ -101,7 +101,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # Single cleanup hook for every temp path we create. CLEANUP=() -cleanup() { local p; for p in "${CLEANUP[@]:-}"; do [ -n "$p" ] && rm -rf "$p"; done; } +cleanup() { local p; for p in "${CLEANUP[@]:-}"; do [ -z "$p" ] || rm -rf "$p"; done; } trap cleanup EXIT # Save real stdout on fd 3 and route everything else to stderr, so the only thing @@ -181,8 +181,10 @@ else echo "Snapshot created: ${SNAPSHOT_ID}" aws ec2 create-tags --region "${REGION}" --resources "${SNAPSHOT_ID}" \ --tags "Key=Name,Value=${SNAPSHOT_DESC}" "Key=BuildID,Value=${BUILD_ID}" "Key=VersionID,Value=${VERSION_ID}" + # Recorded only when THIS run created it: a reused snapshot/AMI may belong to an earlier + # session and must not be swept by this run's teardown. + record "aws snapshot ${REGION} ${SNAPSHOT_ID}" fi -record "aws snapshot ${REGION} ${SNAPSHOT_ID}" echo "=== Checking for existing AMI ===" EXISTING_AMI=$(aws ec2 describe-images --region "${REGION}" --owners self \ @@ -212,8 +214,8 @@ else echo "AMI registered: ${AMI_ID}" aws ec2 create-tags --region "${REGION}" --resources "${AMI_ID}" \ --tags "Key=Name,Value=${PRETTY_NAME}" "Key=BuildID,Value=${BUILD_ID}" "Key=VersionID,Value=${VERSION_ID}" + record "aws ami ${REGION} ${AMI_ID}" # only when created by this run fi -record "aws ami ${REGION} ${AMI_ID}" # Make the AMI publicly launchable (default; --private opts out): any AWS account # can launch it directly (per-customer config lives in user-data, not the image). diff --git a/tools/publish/ec2/launch.sh b/tools/publish/ec2/launch.sh index d2928b1..534c653 100755 --- a/tools/publish/ec2/launch.sh +++ b/tools/publish/ec2/launch.sh @@ -43,6 +43,11 @@ Options: including a post-mortem drain (EC2's serial buffer lags minutes) --stop STOP (don't terminate) on shutdown, so the instance and its serial console survive for debugging. Default is to terminate. + --tail-timeout with --tail: stop streaming after seconds even if the + instance is still running (default 0 = until it powers off). + The instance is left running; terminate it (or cleanup.sh). + --manifest append the launched instance ("aws instance ") to + for cleanup.sh -h, --help show this help and exit Examples: @@ -57,6 +62,8 @@ INSTANCE_TYPE="" SPOT=false TAIL=false STOP=false +TAIL_TIMEOUT=0 +MANIFEST="" POSITIONAL=() while [ $# -gt 0 ]; do case "$1" in @@ -69,6 +76,10 @@ while [ $# -gt 0 ]; do --spot) SPOT=true; shift ;; --tail) TAIL=true; shift ;; --stop) STOP=true; shift ;; + --tail-timeout) TAIL_TIMEOUT="${2:?--tail-timeout needs a value}"; shift 2 ;; + --tail-timeout=*) TAIL_TIMEOUT="${1#*=}"; shift ;; + --manifest) MANIFEST="${2:?--manifest needs a value}"; shift 2 ;; + --manifest=*) MANIFEST="${1#*=}"; shift ;; -h|--help) usage; exit 0 ;; --) shift; while [ $# -gt 0 ]; do POSITIONAL+=("$1"); shift; done ;; -*) echo "Error: unknown option: $1" >&2; usage; exit 1 ;; @@ -119,7 +130,9 @@ RUN_ARGS=( --instance-type "${INSTANCE_TYPE}" --user-data "file://${CONFIG_FILE}" --instance-initiated-shutdown-behavior "${SHUTDOWN_BEHAVIOR}" - --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${NAME}}]" + # Project=lockboot: the deploy role (workspace tools/deploy/aws-iam.sh) only lets you + # start/stop/reboot instances carrying it. + --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${NAME}},{Key=Project,Value=lockboot}]" ) if [ "${SPOT}" = "true" ]; then RUN_ARGS+=(--instance-market-options '{"MarketType":"spot","SpotOptions":{"SpotInstanceType":"one-time"}}') @@ -130,6 +143,7 @@ echo "=== Launching ${AMI_ID} (${ARCH}) as ${INSTANCE_TYPE} in ${REGION}${MARKET INSTANCE_ID=$(aws ec2 run-instances "${RUN_ARGS[@]}" \ --query 'Instances[0].InstanceId' --output text) || die "run-instances failed" echo "Launched instance ${INSTANCE_ID} (Name=${NAME}, shutdown=${SHUTDOWN_BEHAVIOR})" +if [ -n "${MANIFEST}" ]; then printf '%s\n' "aws instance ${REGION} ${INSTANCE_ID}" >> "${MANIFEST}"; fi if [ "${TAIL}" = "true" ]; then # Do NOT use `aws ec2 wait instance-running`: stage0 can boot, run, and power off @@ -161,6 +175,7 @@ if [ "${TAIL}" = "true" ]; then echo "Watching ${INSTANCE_ID} state only (no console access; Ctrl-C to stop)..." fi PREV="" + TAIL_START=${SECONDS} DRAIN=0 # extra console fetches after the instance is gone (buffer lags) DRAIN_MAX=12 # ~2 min of post-mortem draining at 10s/poll while :; do @@ -201,6 +216,10 @@ if [ "${TAIL}" = "true" ]; then sleep 10 continue ;; esac + if [ "${TAIL_TIMEOUT}" -gt 0 ] && [ $((SECONDS - TAIL_START)) -ge "${TAIL_TIMEOUT}" ]; then + echo "--- --tail-timeout ${TAIL_TIMEOUT}s reached; instance ${INSTANCE_ID} still ${STATE} (left running) ---" + break + fi sleep 10 done fi diff --git a/tools/publish/gcp/create.sh b/tools/publish/gcp/create.sh index 90210c6..8ae815c 100755 --- a/tools/publish/gcp/create.sh +++ b/tools/publish/gcp/create.sh @@ -23,13 +23,15 @@ Build (or download) a stage0 boot disk and create a GCP image from it. Arguments: arch x86_64 | aarch64 - version a stage0-v* release tag, or 'local' (default) for a local build + version a v* release tag, or 'local' (default) for a local build Options: --project

GCP project (default: active gcloud project) --region GCS bucket / zone region (default: ${DEFAULT_REGION}) --public make the image usable by any authenticated GCP user (default) --private keep the image private to this project + --default-dbx TEST ONLY: omit our dbx so GCP fills in its default (Microsoft) dbx; for + dbx A/B measurement runs. Creates a separate '-defdbx' image. --no-verify (release mode) skip gh attestation; fetch the public release asset via curl so no gh install is needed --manifest append created resources to for a teardown script, one per @@ -38,7 +40,7 @@ Options: Examples: $(basename "$0") x86_64 # active project, public image in ${DEFAULT_REGION} - $(basename "$0") --project my-proj x86_64 stage0-v0.1.0 + $(basename "$0") --project my-proj x86_64 v0.1.0 $(basename "$0") --private aarch64 EOF } @@ -49,6 +51,7 @@ PROJECT="" REGION="${DEFAULT_REGION}" PUBLIC=true NO_VERIFY=false +DEFAULT_DBX=false MANIFEST="" POSITIONAL=() while [ $# -gt 0 ]; do @@ -60,6 +63,7 @@ while [ $# -gt 0 ]; do --public) PUBLIC=true; shift ;; --private) PUBLIC=false; shift ;; --no-verify) NO_VERIFY=true; shift ;; + --default-dbx) DEFAULT_DBX=true; shift ;; --manifest) MANIFEST="${2:?--manifest needs a value}"; shift 2 ;; --manifest=*) MANIFEST="${1#*=}"; shift ;; -h|--help) usage; exit 0 ;; @@ -95,7 +99,7 @@ ${GCLOUD} auth list --filter=status:ACTIVE --format="value(account)" 2>/dev/null [ -n "${PROJECT}" ] || die "no project (pass --project or run: ${GCLOUD} config set project )" CLEANUP=() -cleanup() { local p; for p in "${CLEANUP[@]:-}"; do [ -n "$p" ] && rm -rf "$p"; done; } +cleanup() { local p; for p in "${CLEANUP[@]:-}"; do [ -z "$p" ] || rm -rf "$p"; done; } trap cleanup EXIT # Save real stdout on fd 3 and route everything else to stderr, so the only thing @@ -147,6 +151,14 @@ fi for c in PK KEK db; do [ -f "${KEYS_DIR}/${c}.cer" ] || die "Secure Boot cert ${c}.cer not found in ${KEYS_DIR}" done +# dbx: the exact EFI_SIGNATURE_LIST mkvarstore.py enrolls into efi-vars.{ovmf,aws}, delivered to +# GCP as a KEK-signed authenticated variable update (dbx.auth.bin) -- the format GCP's BIN dbx +# takes (cf. uefi.org DBXUpdate.bin); a bare ESL is accepted at image create but kills every VM +# at start. Unset, GCP substitutes its own default (Microsoft) dbx. +DBX_FILE="${WORK_DIR}/dbx.auth.bin" +if [ "${DEFAULT_DBX}" != "true" ]; then + [ -f "${DBX_FILE}" ] || die "dbx.auth.bin not found: ${DBX_FILE} (rebuild: make build-${ARCH})" +fi # os-release provides ID, VERSION_ID, BUILD_ID, NAME, PRETTY_NAME (our own artifact). # shellcheck disable=SC1090 @@ -154,19 +166,25 @@ source "${OS_RELEASE_FILE}" VERSION_DASH=$(echo "${VERSION_ID}" | tr '.' '-') ARCH_DASH=$(echo "${ARCH}" | tr '_' '-') -IMAGE_NAME="${ID}-${ARCH_DASH}-${VERSION_DASH}" # GCP names: lowercase/digits/hyphens +# GCP names: lowercase/digits/hyphens. BUILD_ID is part of the name (as for the EC2 AMI) so +# re-running after a rebuild -- new keys/binary, same VERSION_ID -- makes a new image instead of +# silently reusing a stale one. +IMAGE_NAME="${ID}-${ARCH_DASH}-${VERSION_DASH}-${BUILD_ID}" +[ "${DEFAULT_DBX}" = "true" ] && IMAGE_NAME="${IMAGE_NAME}-defdbx" IMAGE_DESC="${PRETTY_NAME} version: ${VERSION_ID} build: ${BUILD_ID} arch: ${ARCH}" IMAGE_FAMILY="${ID}" if [ "${ARCH}" = "x86_64" ]; then - GUEST_OS_FEATURES="UEFI_COMPATIBLE,SEV_CAPABLE,SEV_SNP_CAPABLE,GVNIC" + GUEST_OS_FEATURES="UEFI_COMPATIBLE,SEV_CAPABLE,SEV_SNP_CAPABLE,TDX_CAPABLE,GVNIC" else GUEST_OS_FEATURES="UEFI_COMPATIBLE,GVNIC" fi echo "=== Checking for existing image ===" -EXISTING_IMAGE=$(${GCLOUD} compute images list --project="${PROJECT}" \ - --filter="name=${IMAGE_NAME}" --format="value(name)" 2>/dev/null || echo "") +# Exact-name lookup: `images list --filter=name=X` is a pattern match, so X would also match +# X-defdbx (or any longer name) and silently reuse the wrong image. +EXISTING_IMAGE=$(${GCLOUD} compute images describe "${IMAGE_NAME}" --project="${PROJECT}" \ + --format="value(name)" 2>/dev/null || echo "") if [ -n "${EXISTING_IMAGE}" ]; then echo "Image already exists: ${EXISTING_IMAGE}" @@ -198,9 +216,19 @@ else ${GCLOUD} storage cp "${TEMP_DIR}/${BUILD_ID}.tar.gz" "${GCS_URI}" --project="${PROJECT}" \ --custom-metadata="version-id=${VERSION_ID},build-id=${BUILD_ID},name=${NAME},pretty-name=${PRETTY_NAME},id=${ID},arch=${ARCH}" \ || die "GCS upload failed" + # Recorded only when THIS run created it: a reused object may belong to an earlier + # session and must not be swept by this run's teardown. + record "gcp gcsobject ${PROJECT} ${GCS_URI}" fi - record "gcp gcsobject ${PROJECT} ${GCS_URI}" + DBX_ARGS=() + if [ "${DEFAULT_DBX}" = "true" ]; then + echo "WARNING: --default-dbx: GCP's default (Microsoft) dbx, not ours -- test image only" + else + # gcloud types a key file by NAME: `*.bin` -> BIN, anything else must be DER X.509 + # (googlecloudsdk/api_lib/compute/image_utils.py GetFileContentAndFileType). + DBX_ARGS=(--forbidden-database-file="${DBX_FILE}") + fi echo "=== Creating image ${IMAGE_NAME} (${GCP_ARCH}, ${GUEST_OS_FEATURES}) ===" ${GCLOUD} compute images create "${IMAGE_NAME}" --project="${PROJECT}" \ --source-uri="${GCS_URI}" --guest-os-features="${GUEST_OS_FEATURES}" \ @@ -208,10 +236,11 @@ else --platform-key-file="${KEYS_DIR}/PK.cer" \ --key-exchange-key-file="${KEYS_DIR}/KEK.cer" \ --signature-database-file="${KEYS_DIR}/db.cer" \ + "${DBX_ARGS[@]}" \ || die "image create failed" IMAGE_FINAL="${IMAGE_NAME}" + record "gcp image ${PROJECT} ${IMAGE_FINAL}" # only when created by this run fi -record "gcp image ${PROJECT} ${IMAGE_FINAL}" # Make the image publicly launchable (default; --private opts out): any authenticated # GCP user can create instances from it (per-customer config lives in user-data). @@ -235,7 +264,7 @@ echo "" DEFAULT_ZONE=$(${GCLOUD} config get-value compute/zone 2>/dev/null || echo "") [ -n "${DEFAULT_ZONE}" ] || DEFAULT_ZONE="${REGION}-a" -if [ "${ARCH}" = "aarch64" ]; then MACHINE_TYPE="t2a-standard-1"; TECH="ARM TrustZone"; else MACHINE_TYPE="n2d-standard-2"; TECH="AMD SEV-SNP"; fi +if [ "${ARCH}" = "aarch64" ]; then MACHINE_TYPE="t2a-standard-1"; TECH="Shielded VM, no confidential type"; else MACHINE_TYPE="n2d-standard-2"; TECH="AMD SEV-SNP"; fi echo "Launch a Confidential VM (${TECH}):" echo " ${SCRIPT_DIR}/launch-instance.sh my-instance ${DEFAULT_ZONE} ${MACHINE_TYPE} ${IMAGE_FINAL} config.json" diff --git a/tools/publish/gcp/get-console.sh b/tools/publish/gcp/get-console.sh index 7245ae9..87dd6a7 100755 --- a/tools/publish/gcp/get-console.sh +++ b/tools/publish/gcp/get-console.sh @@ -54,21 +54,41 @@ case "${MODE}" in echo "Following console output for ${INSTANCE_NAME} (Ctrl+C to stop)..." echo "---" - LAST_LINE=0 - while true; do - OUTPUT=$(${GCLOUD} compute instances get-serial-port-output "${INSTANCE_NAME}" \ + # --start is a BYTE index; resume from the `next` offset each response reports (it also + # stays correct if the serial buffer rolled over and older bytes were dropped). + # Every gcloud call is a full Python start-up (~1s of CPU), so poll every 10s, and only + # when a poll brings nothing new ask for the instance status: once it is no longer + # RUNNING (stage0 powered off / stopped / deleted) do one last read and exit, instead of + # polling a dead instance forever. + command -v jq >/dev/null 2>&1 || { echo "Error: --follow needs jq"; exit 1; } + NEXT=0 + read_once() { + local resp n got=1 + resp=$(${GCLOUD} compute instances get-serial-port-output "${INSTANCE_NAME}" \ --zone="${ZONE}" \ --project="${PROJECT}" \ - --start="${LAST_LINE}" 2>/dev/null || echo "") - - if [ -n "${OUTPUT}" ]; then - echo "${OUTPUT}" - # Count total lines to update start position - NEW_LINES=$(echo "${OUTPUT}" | wc -l) - LAST_LINE=$((LAST_LINE + NEW_LINES)) + --start="${NEXT}" --format=json 2>/dev/null || echo "") + if [ -n "${resp}" ]; then + jq -j '.contents // ""' <<<"${resp}" + n=$(jq -r '.next // empty' <<<"${resp}") + if [ -n "${n}" ] && [ "${n}" != "${NEXT}" ]; then NEXT="${n}"; got=0; fi fi - - sleep 2 + return "${got}" + } + while true; do + if ! read_once; then + STATUS=$(${GCLOUD} compute instances describe "${INSTANCE_NAME}" \ + --zone="${ZONE}" --project="${PROJECT}" \ + --format="value(status)" 2>/dev/null || echo "GONE") + if [ "${STATUS:-GONE}" != "RUNNING" ] && [ "${STATUS}" != "PROVISIONING" ] \ + && [ "${STATUS}" != "STAGING" ]; then + read_once || true + echo + echo "--- ${INSTANCE_NAME} is ${STATUS:-GONE}; stopped following ---" + exit 0 + fi + fi + sleep 10 done ;; diff --git a/tools/publish/gcp/launch-instance.sh b/tools/publish/gcp/launch-instance.sh index 4bc6b63..8c6934c 100755 --- a/tools/publish/gcp/launch-instance.sh +++ b/tools/publish/gcp/launch-instance.sh @@ -19,8 +19,13 @@ else exit 1 fi +# Optional leading --manifest : append the created instance ("gcp instance +# /") for cleanup.sh. GCP instances do NOT self-delete when stage0 powers off. +MANIFEST="" +if [ "${1:-}" = "--manifest" ]; then MANIFEST="${2:?--manifest needs a value}"; shift 2; fi + if [ $# -lt 5 ]; then - echo "Usage: $0 [additional-options...]" + echo "Usage: $0 [--manifest ] [additional-options...]" echo "" echo "Examples:" echo " # Launch x86_64 instance" @@ -30,9 +35,9 @@ if [ $# -lt 5 ]; then echo " $0 my-vm us-central1-a t2a-standard-1 lockboot-aarch64 config.json --network=my-vpc" echo "" echo "Recommended machine types:" - echo " x86_64 SEV-SNP: n2d-standard-2, n2d-standard-4, c2d-standard-*" + echo " x86_64 SEV-SNP: n2d-standard-2, n2d-standard-4 (SEV only: c2d-standard-*)" echo " x86_64 TDX: c3-standard-*" - echo " aarch64: t2a-standard-1, t2a-standard-2, t2a-standard-4" + echo " aarch64: t2a-standard-1, t2a-standard-2, t2a-standard-4 (Shielded VM, not confidential)" echo "" echo "Common zones: us-central1-a, us-east1-b, europe-west1-b" echo "" @@ -77,22 +82,25 @@ echo "Image: ${IMAGE}" echo "User-data: ${USER_DATA_FILE}" echo "" -# Validate machine type supports Confidential Compute -if [[ "${MACHINE_TYPE}" =~ ^n2d- ]] || [[ "${MACHINE_TYPE}" =~ ^c2d- ]]; then - TECH="AMD SEV-SNP" +# Confidential-compute flags per machine family (non-interactive: unknown families are refused). +# n2d -> SEV-SNP: needs an AMD Milan-or-later host, so pin --min-cpu-platform +# c2d -> SEV +# c3 -> TDX +# t2a -> no documented Arm Confidential VM series: Shielded VM only (secure boot + vTPM + +# integrity). To try a confidential type (experiment G2), pass it in the trailing +# options, e.g. --confidential-compute-type=CCA. +# (The deprecated bare --confidential-compute flag means SEV and is not used.) +if [[ "${MACHINE_TYPE}" =~ ^n2d- ]]; then + TECH="AMD SEV-SNP"; CONF_ARGS=(--confidential-compute-type=SEV_SNP --min-cpu-platform="AMD Milan") +elif [[ "${MACHINE_TYPE}" =~ ^c2d- ]]; then + TECH="AMD SEV"; CONF_ARGS=(--confidential-compute-type=SEV) elif [[ "${MACHINE_TYPE}" =~ ^c3- ]]; then - TECH="Intel TDX" + TECH="Intel TDX"; CONF_ARGS=(--confidential-compute-type=TDX) elif [[ "${MACHINE_TYPE}" =~ ^t2a- ]]; then - TECH="ARM TrustZone" + TECH="none (Shielded VM only)"; CONF_ARGS=() else - echo "Warning: Machine type '${MACHINE_TYPE}' may not support Confidential Computing" - echo "Recommended: n2d-*, c2d-*, c3-*, or t2a-*" - read -p "Continue anyway? (y/N) " -n 1 -r - echo - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - exit 1 - fi - TECH="Unknown" + echo "Error: unsupported machine type '${MACHINE_TYPE}' (use n2d-*, c2d-*, c3-*, or t2a-*)" + exit 1 fi echo "Confidential Compute: ${TECH}" @@ -110,8 +118,9 @@ if [ -n "${EXISTING}" ]; then exit 1 fi -echo "Creating instance with REQUIRED Confidential VM settings:" -echo " ✓ --confidential-compute-type (enables memory encryption)" +echo "Creating instance with REQUIRED settings:" +echo " ✓ ${CONF_ARGS[*]:-(no confidential type: Shielded VM only)}" +echo " ✓ --no-service-account --no-scopes (no cloud credentials reachable from the guest)" echo " ✓ --maintenance-policy=TERMINATE (prevents live migration)" echo " ✓ --shielded-secure-boot (UEFI Secure Boot)" echo " ✓ --shielded-vtpm (virtual TPM 2.0)" @@ -120,55 +129,26 @@ echo " ✓ --boot-disk-type=pd-standard (cheapest, loaded once into memory)" echo " ✓ --boot-disk-auto-delete (cleanup on instance delete)" echo "" -# Determine confidential compute type based on machine type -if [[ "${MACHINE_TYPE}" =~ ^c3- ]]; then - CONF_COMPUTE_TYPE="TDX" -elif [[ "${MACHINE_TYPE}" =~ ^(n2d-|c2d-) ]]; then - CONF_COMPUTE_TYPE="SEV" -elif [[ "${MACHINE_TYPE}" =~ ^t2a- ]]; then - # ARM doesn't need explicit type - CONF_COMPUTE_TYPE="" -else - CONF_COMPUTE_TYPE="SEV" # Default to SEV -fi - -# Launch instance with all required Confidential VM settings -if [ -n "${CONF_COMPUTE_TYPE}" ]; then - ${GCLOUD} compute instances create "${INSTANCE_NAME}" \ - --project="${PROJECT}" \ - --zone="${ZONE}" \ - --machine-type="${MACHINE_TYPE}" \ - --image="${IMAGE}" \ - --network-interface=nic-type=GVNIC \ - --boot-disk-type=pd-standard \ - --boot-disk-auto-delete \ - --metadata-from-file=user-data="${USER_DATA_FILE}" \ - --metadata=serial-port-enable=true \ - --confidential-compute-type="${CONF_COMPUTE_TYPE}" \ - --maintenance-policy=TERMINATE \ - --shielded-secure-boot \ - --shielded-vtpm \ - --shielded-integrity-monitoring \ - "$@" -else - # ARM: use old flag for now (TODO: check if ARM needs specific type) - ${GCLOUD} compute instances create "${INSTANCE_NAME}" \ - --project="${PROJECT}" \ - --zone="${ZONE}" \ - --machine-type="${MACHINE_TYPE}" \ - --image="${IMAGE}" \ - --network-interface=nic-type=GVNIC \ - --boot-disk-type=pd-standard \ - --boot-disk-auto-delete \ - --metadata-from-file=user-data="${USER_DATA_FILE}" \ - --metadata=serial-port-enable=true \ - --confidential-compute \ - --maintenance-policy=TERMINATE \ - --shielded-secure-boot \ - --shielded-vtpm \ - --shielded-integrity-monitoring \ - "$@" -fi +# Launch instance with all required settings. No service account / scopes: stage0..stage2 never +# call GCP APIs, so the guest gets no metadata-server credentials to leak. +${GCLOUD} compute instances create "${INSTANCE_NAME}" \ + --project="${PROJECT}" \ + --zone="${ZONE}" \ + --machine-type="${MACHINE_TYPE}" \ + --image="${IMAGE}" \ + --network-interface=nic-type=GVNIC \ + --boot-disk-type=pd-standard \ + --boot-disk-auto-delete \ + --metadata-from-file=user-data="${USER_DATA_FILE}" \ + --metadata=serial-port-enable=true \ + "${CONF_ARGS[@]}" \ + --maintenance-policy=TERMINATE \ + --shielded-secure-boot \ + --shielded-vtpm \ + --shielded-integrity-monitoring \ + --no-service-account --no-scopes \ + "$@" +if [ -n "${MANIFEST}" ]; then printf '%s\n' "gcp instance ${PROJECT} ${ZONE}/${INSTANCE_NAME}" >> "${MANIFEST}"; fi echo "" echo "=== Instance Created Successfully ===" diff --git a/tools/qemu-test.sh b/tools/qemu-test.sh index 2091660..7a11caa 100755 --- a/tools/qemu-test.sh +++ b/tools/qemu-test.sh @@ -20,13 +20,21 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" TMP=/tmp -# EC2 metadata mock (downloaded + sha256-verified on first run; cached next to the -# script, override the cache dir with EC2_MOCK_CACHE). +# Host arch (where QEMU runs), as opposed to ARCH (the guest). Both amd64 and arm64 hosts are +# supported for both guests: KVM when they match, TCG emulation otherwise. +HOST_ARCH="$(uname -m)" +case "${HOST_ARCH}" in + x86_64) AEMM_ARCH=amd64; AEMM_SHA256="4f89ddc71ac53ce540bda1f9c340526d558eed8e41349761f2798acf1b254950" ;; + aarch64) AEMM_ARCH=arm64; AEMM_SHA256="9dae5b5849365dbaa133309da81f49bafe94ec0aa7e6b05ce3eb7a8f151c2217" ;; + *) echo "Error: unsupported host arch ${HOST_ARCH} (need x86_64 or aarch64)" >&2; exit 1 ;; +esac + +# EC2 metadata mock for the host arch (downloaded + sha256-verified on first run; cached next to +# the script, override the cache dir with EC2_MOCK_CACHE). AEMM_VERSION="v1.13.0" -AEMM_URL="https://github.com/aws/amazon-ec2-metadata-mock/releases/download/${AEMM_VERSION}/ec2-metadata-mock-linux-amd64" -AEMM_SHA256="4f89ddc71ac53ce540bda1f9c340526d558eed8e41349761f2798acf1b254950" +AEMM_URL="https://github.com/aws/amazon-ec2-metadata-mock/releases/download/${AEMM_VERSION}/ec2-metadata-mock-linux-${AEMM_ARCH}" EC2_MOCK_CACHE="${EC2_MOCK_CACHE:-${SCRIPT_DIR}}" -AMMM="${EC2_MOCK_CACHE}/ec2-metadata-mock-linux-amd64" +AMMM="${EC2_MOCK_CACHE}/ec2-metadata-mock-linux-${AEMM_ARCH}" usage() { cat <<'EOF' @@ -50,6 +58,10 @@ Options: (a sibling .sig is served too if present). --serve-dir Serve this whole directory at http://10.0.2.1:8000/ instead of a single payload (e.g. UKI + stage2). + --forward Forward a host TCP port to the guest (10.0.2.10). + Repeatable (e.g. --forward 8402 --forward 9090). + --timeout Kill QEMU if the guest has not powered off by then, and + exit 124 (default: 0 = no limit). For unattended runs. --trace Capture guest TCP on tap0 to a pcap (see --trace-file). --trace-file pcap output path (default: ./stage0-trace.pcap). -h, --help Show this help. @@ -69,6 +81,8 @@ PAYLOAD="" SERVE_DIR="" TRACE=0 TRACE_FILE="" +FORWARD_PORTS=() +TIMEOUT=0 while [ $# -gt 0 ]; do case "$1" in @@ -81,6 +95,8 @@ while [ $# -gt 0 ]; do --serve-dir) SERVE_DIR="$2"; shift 2 ;; --trace) TRACE=1; shift ;; --trace-file) TRACE_FILE="$2"; shift 2 ;; + --forward) FORWARD_PORTS+=("$2"); shift 2 ;; + --timeout) TIMEOUT="$2"; shift 2 ;; -h|--help) usage; exit 0 ;; *) echo "Unknown option: $1" >&2; usage; exit 1 ;; esac @@ -144,7 +160,9 @@ provision_tpm() { tpm2_startup -c local NV_ECC_CERT=0x01c10002 NV_ECC_TEMPLATE=0x01c10003 - if tpm2_nvreadpublic ${NV_ECC_TEMPLATE} >/dev/null 2>&1; then + # Probe via the NV handle list: tpm2-tools 5.4's tpm2_nvreadpublic SEGFAULTs on an undefined + # index (exit 139), which dumped a root-owned `core` into the caller's cwd on every fresh boot. + if tpm2_getcap handles-nv-index | grep -qix -- "- $(printf '0x%X' $((NV_ECC_TEMPLATE)))"; then echo "vTPM already provisioned, skipping." tpm2_shutdown; swtpm_ioctl --unix "${sock}.ctrl" -s; rm -rf "${work}"; return fi @@ -182,7 +200,8 @@ if [ "${ARCH}" = "x86_64" ]; then QEMU_CMD="qemu-system-x86_64" QEMU_MACHINE="-machine q35,smm=on" QEMU_CPU="" - QEMU_EXTRA="-enable-kvm" + # KVM on a matching host (unchanged: fails loudly without /dev/kvm); TCG on an arm64 host. + [ "${HOST_ARCH}" = "x86_64" ] && QEMU_EXTRA="-enable-kvm" || QEMU_EXTRA="" QEMU_SERIAL="-serial none" QEMU_SERIAL_DEVICE="-device isa-serial,chardev=char0" TPM_DEVICE="tpm-tis" @@ -190,10 +209,21 @@ if [ "${ARCH}" = "x86_64" ]; then else OVMF_CODE="/usr/share/AAVMF/AAVMF_CODE.fd" QEMU_CMD="qemu-system-aarch64" - QEMU_MACHINE="-machine virt" - QEMU_CPU="-cpu cortex-a72" - QEMU_EXTRA="" - QEMU_SERIAL="-serial none" + if [ "${HOST_ARCH}" = "aarch64" ]; then + # KVM on a matching host: the guest takes the host's CPU + GIC. + QEMU_MACHINE="-machine virt,gic-version=host" + QEMU_CPU="-cpu host" + QEMU_EXTRA="-enable-kvm" + else + QEMU_MACHINE="-machine virt" + QEMU_CPU="-cpu cortex-a72" + QEMU_EXTRA="" + fi + # The virt board's PL011 carries AAVMF's UEFI ConOut (stage0's output). Attach it to the same + # muxed stdio as the pci-serial (ttyS0, where /dev/console lands) so the whole chain -- UEFI, + # kernel, init, userspace -- is captured, as it is on x86 via isa-serial. Kernel printk then + # appears on both (console=ttyAMA0 console=ttyS0), i.e. twice in this log. + QEMU_SERIAL="-serial chardev:char0" QEMU_SERIAL_DEVICE="-device pci-serial,id=serial0,chardev=char0" TPM_DEVICE="tpm-tis-device" PFLASH_SECURE="" @@ -230,10 +260,13 @@ trap cleanup EXIT INT TERM echo "Press Ctrl-A, then X to exit QEMU" -# --- Guest network: tap0 (10.0.2.1 gw + 169.254.169.254 IMDS), NAT out ------ +# --- Guest network: tap0 (gateway + 169.254.169.254 IMDS), NAT out ----------- +GUEST_GW=10.0.2.1 +GUEST_IP=10.0.2.10 + ip tuntap add dev tap0 mode tap ip link set tap0 up -ip addr add 10.0.2.1/24 dev tap0 +ip addr add ${GUEST_GW}/24 dev tap0 ip addr add 169.254.169.254/24 dev tap0 if [ "${TRACE}" = 1 ]; then @@ -265,35 +298,46 @@ fi if [ -n "${SERVE_ROOT}" ]; then # HTTP/1.1 (Content-Length + keep-alive). The stdlib default is HTTP/1.0 # Connection: close, which OVMF's HttpDxe never completes the response token for. - ( cd "${SERVE_ROOT}" && exec python3 -c 'import http.server; http.server.SimpleHTTPRequestHandler.protocol_version="HTTP/1.1"; http.server.ThreadingHTTPServer(("10.0.2.1",8000), http.server.SimpleHTTPRequestHandler).serve_forever()' ) & + ( cd "${SERVE_ROOT}" && exec python3 -c "import http.server; http.server.SimpleHTTPRequestHandler.protocol_version='HTTP/1.1'; http.server.ThreadingHTTPServer(('${GUEST_GW}',8000), http.server.SimpleHTTPRequestHandler).serve_forever()" ) & echo $! > "${TMP}/payload-http.pid" - echo "Serving ${SERVE_ROOT} (HTTP/1.1) at http://10.0.2.1:8000/ :" + echo "Serving ${SERVE_ROOT} (HTTP/1.1) at http://${GUEST_GW}:8000/ :" ls -l "${SERVE_ROOT}" | sed 's/^/ /' fi echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE +for fwd_port in "${FORWARD_PORTS[@]}"; do + iptables -t nat -A PREROUTING -i eth0 -p tcp --dport "${fwd_port}" -j DNAT --to-destination ${GUEST_IP}:"${fwd_port}" + iptables -A FORWARD -i eth0 -p tcp -d ${GUEST_IP} --dport "${fwd_port}" -j ACCEPT + echo "Forwarding port ${fwd_port} -> ${GUEST_IP}:${fwd_port}" +done + # dnsmasq: EC2-style DHCP/DNS (gateway, DNS, classless route to IMDS, hostnames), # plus payload.lockboot.test -> 10.0.2.1 so hostname URLs exercise EFI_DNS4. { - for i in $(seq 10 20); do echo "10.0.2.${i} ip-10-0-2-${i}"; done - echo "10.0.2.1 payload.lockboot.test" + echo "${GUEST_IP} ip-${GUEST_IP//./-}" + echo "${GUEST_GW} payload.lockboot.test" } > "${TMP}/dnsmasq-hosts" dnsmasq --interface=tap0 --bind-interfaces \ - --dhcp-range=10.0.2.10,10.0.2.20,12h \ - --dhcp-option=3,10.0.2.1 \ - --dhcp-option=6,10.0.2.1,8.8.8.8 \ + --dhcp-range=${GUEST_IP},${GUEST_IP},12h \ + --dhcp-option=3,${GUEST_GW} \ + --dhcp-option=6,${GUEST_GW},8.8.8.8 \ --dhcp-option=15,ec2.internal \ - --dhcp-option=option:classless-static-route,169.254.169.254/32,10.0.2.1 \ + --dhcp-option=option:classless-static-route,169.254.169.254/32,${GUEST_GW} \ --dhcp-option=119,ec2.internal,local.compute.internal \ --domain=ec2.internal \ --expand-hosts \ --addn-hosts="${TMP}/dnsmasq-hosts" \ --log-queries +# --timeout: bound an unattended run. A guest that never powers off is a failure, not a hang. +QEMU_WRAP=() +[ "${TIMEOUT}" != 0 ] && QEMU_WRAP=(timeout --foreground --kill-after=10 "${TIMEOUT}") +QEMU_RC=0 + # shellcheck disable=SC2086 -${QEMU_CMD} \ +"${QEMU_WRAP[@]}" ${QEMU_CMD} \ ${QEMU_CPU} \ ${QEMU_EXTRA} \ ${QEMU_MACHINE} \ @@ -313,4 +357,9 @@ ${QEMU_CMD} \ -chardev stdio,mux=on,id=char0 \ ${QEMU_SERIAL_DEVICE} \ -drive "if=pflash,format=raw,unit=0,file=${OVMF_CODE},readonly=on" \ - -drive "if=pflash,format=raw,unit=1,file=${OVMF_VARS}" || true + -drive "if=pflash,format=raw,unit=1,file=${OVMF_VARS}" || QEMU_RC=$? + +if [ "${TIMEOUT}" != 0 ] && { [ "${QEMU_RC}" = 124 ] || [ "${QEMU_RC}" = 137 ]; }; then + echo "qemu-test: TIMEOUT: guest did not power off within ${TIMEOUT}s" >&2 + exit 124 +fi