From 975d3901ee96f514efa069e28635e835eff41d65 Mon Sep 17 00:00:00 2001 From: Timo Derstappen Date: Tue, 1 Dec 2026 04:36:41 +0100 Subject: [PATCH 1/5] feat(attest): PCRs 1 and 5 are judged by replaying the firmware event log; the partition table must hold the image's installed disk and nothing else, and the boot variables and loader.conf must be those of the VM's first verified boot PCR 1 and 5 differ per VM and have no golden values, so the verifier replays their events from the firmware event log (and the initrd's os-separator from the userspace log) to the quoted values; every event is one a boot vm-manager starts has, bound to its data where the log carries it. The GPT must hold the partitions repart.sysinstall.d lays out (types, labels, attributes, counts). BootOrder, the Boot#### options and systemd-boot's loader.conf must be what the VM's first verified boot measured, which the record keeps (bootConfig). The ACPI and SMBIOS tables QEMU builds are replayed, not compared. --- README.md | 13 +- docs/design.md | 38 +- docs/development.md | 7 +- docs/plan.md | 2 - e2e/boot_config_attestation_test.go | 167 ++++++++ images/README.md | 10 +- internal/attest/bootconfig.go | 362 ++++++++++++++++++ internal/attest/bootconfig_test.go | 275 +++++++++++++ internal/attest/kernelconfig_verifier_test.go | 4 +- internal/attest/policy.go | 21 +- .../attest/testdata/pcr1-5/firstboot-pcr1.hex | 1 + .../attest/testdata/pcr1-5/firstboot-pcr5.hex | 1 + .../attest/testdata/pcr1-5/reboot-pcr1.hex | 1 + .../attest/testdata/pcr1-5/reboot-pcr5.hex | 1 + .../attest/testdata/pcr1-5/tampered-pcr1.hex | 1 + .../attest/testdata/pcr1-5/tampered-pcr5.hex | 1 + internal/attest/verifier.go | 30 +- internal/attest/verifier_test.go | 116 +++++- internal/tpmquote/efi.go | 118 ++++++ internal/tpmquote/efi_test.go | 70 ++++ internal/tpmquote/eventlog.go | 25 ++ internal/tpmquote/quotetest/bootconfig.go | 183 +++++++++ internal/vm/attest_test.go | 52 +++ internal/vm/imds.go | 22 +- internal/vm/types.go | 12 + 25 files changed, 1474 insertions(+), 59 deletions(-) create mode 100644 e2e/boot_config_attestation_test.go create mode 100644 internal/attest/bootconfig.go create mode 100644 internal/attest/bootconfig_test.go create mode 100644 internal/attest/testdata/pcr1-5/firstboot-pcr1.hex create mode 100644 internal/attest/testdata/pcr1-5/firstboot-pcr5.hex create mode 100644 internal/attest/testdata/pcr1-5/reboot-pcr1.hex create mode 100644 internal/attest/testdata/pcr1-5/reboot-pcr5.hex create mode 100644 internal/attest/testdata/pcr1-5/tampered-pcr1.hex create mode 100644 internal/attest/testdata/pcr1-5/tampered-pcr5.hex create mode 100644 internal/tpmquote/efi.go create mode 100644 internal/tpmquote/efi_test.go create mode 100644 internal/tpmquote/quotetest/bootconfig.go diff --git a/README.md b/README.md index f45082a..36f7072 100644 --- a/README.md +++ b/README.md @@ -250,7 +250,8 @@ matches the PCR values sent, and then the values: | 13 (initrd stage) | zero or the os-separator alone | nothing extended the initrd: an extension image added on the ESP fails the quote that releases user-data | | 13 (ready stage) | computed from `policy.json` `sysexts` for the VM's Kubernetes and CNI versions, the os-separator alone for a VM without Kubernetes; never golden | the exact Kubernetes and CNI sysexts, or none | | 15 (ready stage; required when `policy.json` has `"pcr15": "layer-certificates"`, which every image of this repository sets) | replay of `userspace_log`, every record bound to its word (sha256 of a `machine-id:`, `file-system:` or `layer-certificate:` word, anything else rejected); its `layer-certificate:` words against the VM's `layer_certificates`, in order | the installation layer certificates the initrd enrolled, exactly those served | -| 1, 5 | recorded, not compared | SMBIOS tables with per-VM credentials, the boot entry, the GPT with per-install UUIDs | +| 1 | replay of `event_log`: the ACPI and SMBIOS tables QEMU builds from vm-manager's arguments and the SMBIOS structures systemd-boot and systemd-stub measure, which the guest cannot write, replayed; `BootOrder` and the `Boot####` options, each bound to its data, against the VM's first verified boot (`get_vm` `bootConfig`) | the firmware's boot configuration in the VM's variable store: an option root changes fails the next boot | +| 5 | replay of `event_log`: the GPT, bound to its event, holds the partitions of the image's installed disk and nothing else (the ESP, slots A and B of root, verity and verity signature, var: their types, labels, attributes and counts); systemd-boot's `loader.conf` against the VM's first verified boot; the separator and `ExitBootServices` | the partition table and the boot loader's configuration: a partition added, retyped, relabelled or given another attribute, or an edited `loader.conf`, fails the next boot | Every attestation key is certified against the VM's own endorsement key (EK), the first quote of the VM's first boot included. vm-manager reads the EK from the VM's vTPM itself @@ -272,10 +273,12 @@ the same boot (a boot that skipped the agent: a masked unit, a command line that off), and a boot without one by `--boot-timeout`. A rejected initrd quote ends the boot before user-data is released. `start_vm` boots the VM again and judges that boot anew. -Caveats. PCR 1 and 5 cannot be pinned across VMs, because EDK2 measures the SMBIOS tables -(which carry vm-manager's per-VM credential strings) and the boot entry with the ESP's -partition GUID into PCR 1, and PCR 5 holds the installed disk's GPT; both stay in every -quote for forensics. The ESP is writable for root on a node, so the verifier judges what +Caveats. PCR 1 and 5 have no golden values, because EDK2 measures the ACPI and SMBIOS +tables (sized for the VM, carrying vm-manager's per-VM credential strings) and the boot +entry with the ESP's partition GUID into PCR 1, and PCR 5 holds the installed disk's GPT; +the verifier replays the firmware event log against them instead. The boot variables and +`loader.conf` are compared with what the VM's first verified boot measured: before it, +only vm-manager's installer wrote them. The ESP is writable for root on a node, so the verifier judges what the boot took from it: the command line and the archives in PCR 12, an extension image in PCR 13 at the initrd stage; with Secure Boot on, a loader entry's command line does not take effect either. The integrity story rests on PCRs 0, 4, 7 (Secure Boot with the image's keys), diff --git a/docs/design.md b/docs/design.md index 76f9a4d..0897687 100644 --- a/docs/design.md +++ b/docs/design.md @@ -303,19 +303,26 @@ closed it; open follow-ups are scheduled in [plan.md](plan.md). deletes every `kubernetes_*.raw` other than the requested version before it refreshes; exactly one file, one merged extension, one PCR 13 measurement per boot. A changed `/kubernetes-version` takes effect on the next boot (no live switch of a running node). -- **PCR 1 and 5 are per VM.** Implemented by exclusion (#32, `attest.GoldenIndexes`). The - first golden-path boot showed - them differing between two VMs on the same firmware and image: EDK2 measures the SMBIOS - tables into PCR 1 (`SmbiosMeasurementDxe`, type 11 OEM strings are not filtered), and - vm-manager's type 11 strings are per-VM credentials (hostname, machine ID, SSH key, - notify socket), as is the `Boot####` entry whose device path carries the ESP's - partition GUID; PCR 5 holds the GPT of the installed disk with per-install partition - UUIDs. `attest.GoldenIndexes` is therefore 0, 2-4, 6 and 7 (PCR 13 is computed); PCR 1 and 5 stay in - every quote and in `get_vm_attestation` for forensics. The integrity story rests on 0 - (firmware), 4 (boot loader and UKI), 7 (Secure Boot policy), 11 (UKI and phases) and - 13 (sysext). A per-VM prediction of 1 and 5 by replaying the firmware event log the - agent already posts (`event_log`) against what vm-manager itself passed as SMBIOS and - what sysinstall wrote as GPT is the follow-up if they are wanted. +- **PCR 1 and 5 are per VM.** Implemented by event-log replay (#316, + `internal/attest/bootconfig.go`, `e2e/boot_config_attestation_test.go`). They differ + between two VMs on the same firmware and image, so `attest.GoldenIndexes` is 0, 2-4, 6 and + 7: EDK2 measures the ACPI tables (sized for the VM) and the SMBIOS tables into PCR 1 + (`SmbiosMeasurementDxe`, type 11 OEM strings are not filtered, and vm-manager's are per-VM + credentials: hostname, machine ID, SSH key, notify socket), as is the `Boot####` entry + whose device path carries the ESP's partition GUID; PCR 5 holds the GPT of the installed + disk with per-install partition UUIDs. The verifier replays the PCR 1 and 5 events of the + firmware event log (and the initrd's os-separator from the userspace log) to the quoted + values, every event one a boot vm-manager starts has and bound to its data where the log + carries it. What the guest can change is judged: the GPT must hold the partitions of the + image's installed disk and nothing else (`installedDisk`, kept equal to + `repart.sysinstall.d` by a test: types, labels with the image's id and version or + `_empty`, attributes, counts), so a partition added, retyped, relabelled or given another + attribute fails the next boot; `BootOrder`, the `Boot####` options and systemd-boot's + `loader.conf` must be what the VM's first verified boot measured (the record's + `bootConfig`; before that boot only vm-manager's installer wrote them). The ACPI and SMBIOS + tables and the SMBIOS structures systemd-boot and systemd-stub measure come from QEMU and + vm-manager's arguments; the guest cannot write them, they are replayed, not compared, so a + host's QEMU update does not fail its VMs. - **The ESP and the kernel command line.** Implemented (#293, `e2e/kernel_cmdline_attestation_test.go`). The installed ESP is writable for root on a node. With Secure Boot off, systemd-stub used a command line a Type #1 entry's `options` @@ -399,8 +406,9 @@ signature over the quote with `ak_pub`, nonce match, PCR digest matches `pcrs`, PCR 11 equals the value computed with `systemd-measure calculate` for the image's UKI and the stage's phase path (`enter-initrd` for `initrd`, `enter-initrd:leave-initrd:sysinit:ready` for `ready`), PCRs 0, 2-4, 6 and 7 equal the -image policy's golden values recorded by `vm-manager image golden` (PCR 1 and 5 are quoted -and recorded, not compared: see the open point below), and at `ready` PCR 13 equals the +image policy's golden values recorded by `vm-manager image golden` (PCR 1 and 5 differ per +VM: the firmware event log is replayed against them, see the point above), and at `ready` +PCR 13 equals the value computed from the policy's `sysexts` entries of the VM's Kubernetes and CNI versions (written by `images/scripts/verify-sysext`; the os-separator alone when the VM has none). The image's diff --git a/docs/development.md b/docs/development.md index c63cc6c..cb5d391 100644 --- a/docs/development.md +++ b/docs/development.md @@ -58,6 +58,7 @@ below are the last full run on the development host. | `TestAttestation` | servers in turn over a private `policy.json`: without golden values, after `vm-manager image golden` recorded them (also a VM with two `layer_certificates`), on a distribution's Secure Boot build of OVMF in place of vm-manager's | a VM of a policy without golden values killed at its initrd quote (`no golden value`), user-data never released; the recording reproduces the suite's values bit for bit and names `golden_firmware`; verified initrd and ready quotes, user-data applied; both layer certificates and the Giant Swarm one in the sealed `.dm-verity` keyring, both digests in the ready verdict (PCR 15), a further `layer-certificate:` measurement from the root rejected naming the digest and the VM killed; `golden mismatch` on PCR 0 with the other firmware, naming the recorded build, the VM killed before user-data is released | about 3 min | | `TestAttestationSkipped` | MCP | a boot that skips `vm-agent-attest.service` is killed and the VM failed, never ready: a loader entry with `systemd.imds=no`, a loader entry masking the unit on the kernel command line, a mask in the persistent `/etc` (the initrd quote verifies, the ready quote never comes) | three VMs, each installed and rebooted | | `TestAttestationKeyCertified` | MCP, a second server on the same state | every attestation key is certified against the VM's own endorsement key: two VMs' records hold the TCG RSA EK vm-manager read from each vTPM before its first QEMU, another per VM, and every verdict of their first boots names the key certified against it; one VM's record given the other's EK, its next boot recovers no challenge's nonce (the agent's `TPM2_ActivateCredential` fails on the console), posts no quote and is refused, never released its user-data | two VMs to ready, one refused boot | +| `TestBootConfigAttestation` | MCP | PCRs 1 and 5: the first installed boot verifies and records the VM's boot configuration (`bootConfig`: `BootOrder`, the `Boot####` options, `loader.conf`), a `reboot_vm` verifies against it; then a VM per change root makes, each refused at its next boot (killed, `failed`, never ready): the description of the boot option bootctl installed changed through efivarfs, rejected naming the option; an empty B slot retyped with `sfdisk`, rejected as a partition the image does not define; an option added to `loader.conf`, rejected naming it | three VMs, install and two boots each | | `TestKernelCommandLineAttestation` | MCP | The ESP: the first installed boot runs with Secure Boot on (`ignition.firstboot` through the stub's SMBIOS extra) and verifies at both stages, as does a `reboot_vm`. Then a VM per change root makes to the ESP, each refused at its next boot (killed, `failed`, never ready): `options ipe.enforce=0` appended to the loader entry, which the stub ignores under Secure Boot while systemd-boot measures it, rejected naming PCR 12 and the option with PCR 11 unchanged; a credential added to the entry, rejected on PCR 12; an extension image, its initrd quote rejected on PCR 13 | three VMs, install and two boots each | | `TestKubernetesCluster` | MCP plus the host's `kubectl` through `forward_port` 6443 | on the IPE image with kernel lockdown at confidentiality: control plane from CAPI 1.14-shaped Ignition (`ExecStart=/bin/bash /etc/kubeadm.sh`, ordered `After=vm-kubernetes.service`), every image from gsoci through a mirror on the host holding copies signed with the build's key, Cilium from cilium-app, a worker joined with a bootstrap token, two Ready nodes with `giantswarm-vm://` providerIDs, cross-node DNS, clean units and unmanaged CNI links; on the worker a pod of an image signed with the Giant Swarm key (running as a user named in the image's `/etc/passwd`) and one signed with the installation's key (`layer_certificates`) run, every `containerd-erofs-*` dm-verity device backs a running container, the IMDS refuses `/user-data`, `/attest/challenge` and `/report` from a pod's network namespace while the node reaches it, an image with a layer outside its signatures fails at pull naming that layer, and a file of the running pod's layer is refused as a kernel module, firmware and kexec image; every route to executable memory around IPE (`e2e/execroutes`: `/proc/self/mem`, `mprotect` adding write or execute, `READ_IMPLIES_EXEC`, `ptrace`) refused in a pod without a `securityContext` and in a transient host service, with the kubelet's `seccompDefault` from the sysext's drop-in | `cp_ready_seconds`, `worker_join_seconds`, `layer_registry_seconds` | @@ -119,8 +120,10 @@ level there (`systemd.unit-dropin.*` credentials, systemd-debug-generator(8)). AK pinning per VM on the first verified initrd quote (restored from the VM's record after a restart, `Pin`), PCR 11 against the image's `policy.json` phase paths, PCRs 0, 2-4, 6, 7 (and 13 at ready, `SysextPCR`) against its - golden values, a PCR without one rejected; PCR 1 and 5 are recorded, not - compared. `Recorder` is the reference boot of `vm-manager image golden`: + golden values, a PCR without one rejected; PCR 1 and 5 replayed from the + firmware event log, the GPT against the image's installed disk and the boot + variables and `loader.conf` against the VM's first verified boot + (`bootconfig.go`). `Recorder` is the reference boot of `vm-manager image golden`: every check but the golden comparison; serve never builds one. - `internal/host` — the host capability service behind `get_host`: kernel, CPUs, memory, `/dev/kvm` and `/dev/vhost-vsock` access, qemu / swtpm / systemd diff --git a/docs/plan.md b/docs/plan.md index 72e5799..cdd1570 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -23,8 +23,6 @@ Follow-ups recorded by reviews and agents, not yet scheduled: - `vm-kubernetes.service` merges with `systemd-sysext refresh` on the first boot instead of starting `systemd-sysext.service`, so the manager phase does no unmerge there; starting the unit would make the no-pod shutdown fully synchronous. -- PCRs 1 and 5 (SMBIOS credentials, per-install GPT) are quoted but not compared; event-log - replay, as PCR 12 already does, is the proper fix. - A swtpm that is alive but unreachable at reattach is treated as gone (VM runs without TPM). - The caller identity is only logged; VM records carry no `requestedBy` unlike agent-manager. - Nine sequential e2e tests take ~10 min; parallelise or shard when the suite grows. diff --git a/e2e/boot_config_attestation_test.go b/e2e/boot_config_attestation_test.go new file mode 100644 index 0000000..5980b7f --- /dev/null +++ b/e2e/boot_config_attestation_test.go @@ -0,0 +1,167 @@ +//go:build e2e + +package e2e + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/giantswarm/vm-manager/internal/api" + "github.com/giantswarm/vm-manager/internal/attest" + "github.com/giantswarm/vm-manager/internal/vm" +) + +const ( + bootConfigNetwork = "e2e-bootconfig" + bootConfigCIDR = "192.168.152.0/24" + bootConfigVM = "bootconfig-e2e" + // bootConfigTestTimeout covers three VMs, each installed, booted and + // rebooted, the first once more. + bootConfigTestTimeout = 20 * time.Minute + // bootConfigChanged starts the verdict on a boot whose boot variables + // or loader.conf differ from the VM's first verified boot's + // (internal/attest). + bootConfigChanged = "pcr 1 and 5: the boot configuration changed since the vm's first verified boot: " + // efiVars is where the guest's kernel exposes the firmware's variables; + // globalVar is the vendor GUID of BootOrder and the Boot#### options. + efiVars = "/sys/firmware/efi/efivars" + globalVar = "8be4df61-93ca-11d2-aa0d-00e098032b8c" + // linuxGeneric is a partition type the image does not define. + linuxGeneric = "0FC63DAF-8483-4772-8E79-3D69D8477DE4" +) + +// TestBootConfigAttestation proves that PCRs 1 and 5 are judged +// (giantswarm/vm-manager#316): what the guest can change of them, the +// firmware's boot variables in the VM's variable store, the disk's +// partition table and systemd-boot's loader.conf on the ESP, fails the next +// boot when it changes; a boot is refused at its initrd quote, killed and +// never ready. +// +// 1. The first installed boot verifies and records the VM's boot +// configuration (get_vm bootConfig: BootOrder, the Boot#### options, +// loader.conf); a reboot verifies against it. +// 2. Root changes the description of the boot option bootctl installed +// (efivarfs): the next boot is refused naming the option. +// 3. On a VM of its own, root retypes an empty B slot (sfdisk): the next +// boot is refused naming a partition the image does not define. +// 4. On a VM of its own, root adds an option to loader.conf: the next +// boot is refused naming loader.conf. +func TestBootConfigAttestation(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), bootConfigTestTimeout) + defer cancel() + requireHost(t) + image := locateImage(t) + dir := stateDir(t) + + srv := startServer(ctx, t, dir, image.Dir) + m := newMCPClient(ctx, t, srv.URL) + m.call(ctx, api.ToolCreateNetwork, map[string]any{"name": bootConfigNetwork, "cidr": bootConfigCIDR}, nil) + cleanupCtx := context.WithoutCancel(ctx) + t.Cleanup(func() { + var deleted api.DeletedResponse + m.call(cleanupCtx, api.ToolDeleteNetwork, map[string]any{"name": bootConfigNetwork}, &deleted) + srv.stop() + }) + + create := func(t *testing.T, name string) (vm.VM, *guest) { + t.Helper() + var v vm.VM + m.call(ctx, api.ToolCreateVM, map[string]any{ + "name": name, + "hostname": name, + "network": bootConfigNetwork, + "wait_for": string(vm.WaitReady), + }, &v) + require.Equal(t, vm.StateReady, v.State, "create_vm %s with wait_for ready: lastError %q\n%s", name, v.LastError, srv.logTail()) + g := &guest{m: m, id: v.ID} + g.waitSSH(ctx) + return v, g + } + remove := func(t *testing.T, id string) { + t.Helper() + var deleted api.DeletedResponse + m.call(cleanupCtx, api.ToolDeleteVM, map[string]any{"id": id}, &deleted) + assert.True(t, deleted.Deleted) + } + // refused reboots the VM and requires the next boot refused at its + // initrd quote with a verdict that starts with prefix. + refused := func(t *testing.T, v vm.VM, prefix string) { + t.Helper() + require.NotNil(t, v.BootedAt) + before := *v.BootedAt + m.call(ctx, api.ToolRebootVM, map[string]any{"id": v.ID}, &v) + v = waitRefused(ctx, t, m, v.ID, refusedWithin) + require.NotNil(t, v.BootedAt) + assert.True(t, v.BootedAt.After(before), "the refused boot is the one after the change") + assert.True(t, strings.HasPrefix(v.LastError, "initrd attestation rejected: "+prefix), "get_vm names the rejection: %q", v.LastError) + att := getAttestation(ctx, t, m, v.ID) + require.NotNil(t, att.Initrd) + assert.False(t, att.Initrd.Verified) + assert.Nil(t, att.Ready, "the boot ended at its initrd quote") + } + + v, g := create(t, bootConfigVM) + t.Cleanup(func() { remove(t, v.ID) }) + + t.Run("the first boot records the boot configuration and a reboot keeps it", func(t *testing.T) { + att := getAttestation(ctx, t, m, v.ID) + assertVerified(t, att) + assert.Contains(t, att.Initrd.Message, ", pcr 1 and 5 boot configuration recorded, gpt of ") + require.NotEmpty(t, v.BootConfig, "get_vm: the first verified boot's configuration") + assert.True(t, strings.HasPrefix(v.BootConfig[0], "BootOrder="), v.BootConfig[0]) + assert.True(t, strings.HasPrefix(v.BootConfig[len(v.BootConfig)-1], attest.LoaderConf+"="), v.BootConfig) + t.Logf("boot configuration: %v", v.BootConfig) + + before := *v.BootedAt + m.call(ctx, api.ToolRebootVM, map[string]any{"id": v.ID}, &v) + v = waitRebooted(ctx, t, m, v.ID, before) + g.waitSSH(ctx) + att = getAttestation(ctx, t, m, v.ID) + assertVerified(t, att) + for stage, q := range map[string]*vm.Quote{"initrd": att.Initrd, "ready": att.Ready} { + assert.Contains(t, q.Message, ", pcr 1 and 5 boot configuration as on the first verified boot, gpt of ", "the %s verdict", stage) + assert.Equal(t, v.BootConfig, q.BootConfig, "the %s quote measured the recorded configuration", stage) + } + }) + + t.Run("a changed boot option refuses the next boot", func(t *testing.T) { + // The option bootctl installed (systemd-boot on the ESP), which the + // firmware's boot manager leaves alone, else the one BootOrder + // starts with; its description begins after efivarfs' 4 attribute + // bytes, the option's attributes (4) and the length of its device + // paths (2). + out := g.sh(ctx, `n=$(od -An -tx2 -j4 -N2 `+efiVars+`/BootOrder-`+globalVar+` | tr -d ' ' | tr a-f A-F) && `+ + `for o in `+efiVars+`/Boot[0-9A-F][0-9A-F][0-9A-F][0-9A-F]-`+globalVar+`; do `+ + `tr -d '\000' <"$o" | grep -q 'Linux Boot Manager' && n=$(basename "$o" -`+globalVar+` | cut -c5-); done; `+ + `f=`+efiVars+`/Boot$n-`+globalVar+` && cp "$f" /run/bootvar && `+ + `c=X; [ "$(dd if="$f" bs=1 skip=10 count=1 status=none)" = X ] && c=Y; `+ + `printf "$c" | dd of=/run/bootvar bs=1 seek=10 count=1 conv=notrunc status=none && `+ + `{ chattr -i "$f" 2>/dev/null || true; } && cat /run/bootvar >"$f" && echo "Boot$n" && tr -d '\000' <"$f" | head -c 40`) + t.Logf("as root: %s", out) + option, _, _ := strings.Cut(out, "\n") + require.True(t, strings.HasPrefix(option, "Boot"), "the option BootOrder starts with: %q", out) + refused(t, v, bootConfigChanged+option+" changed") + }) + + t.Run("a retyped partition refuses the next boot", func(t *testing.T) { + v, g := create(t, bootConfigVM+"-gpt") + t.Cleanup(func() { remove(t, v.ID) }) + out := g.sh(ctx, `p=$(findmnt -no SOURCE /boot) && d=${p%%[0-9]*} && `+ + `slot=$(sfdisk -d "$d" | grep 'name="_empty"' | grep -i 'type=4F68BCE3' | cut -d' ' -f1) && `+ + `sfdisk --part-type "$d" "${slot#$d}" `+linuxGeneric+` && sync && sfdisk -d "$d" | grep "$slot"`) + t.Logf("as root: %s", out) + refused(t, v, `pcr 5: the partition table holds a partition of type `+strings.ToLower(linuxGeneric)+` ("_empty"), which the image does not define`) + }) + + t.Run("an option added to loader.conf refuses the next boot", func(t *testing.T) { + v, g := create(t, bootConfigVM+"-loader") + t.Cleanup(func() { remove(t, v.ID) }) + t.Logf("as root: %s", g.sh(ctx, `echo "timeout 5" >>/boot/loader/loader.conf && sync && cat /boot/loader/loader.conf`)) + refused(t, v, bootConfigChanged+attest.LoaderConf+" changed") + }) +} diff --git a/images/README.md b/images/README.md index 3a7c5bf..2506a54 100644 --- a/images/README.md +++ b/images/README.md @@ -346,10 +346,12 @@ firmware PCRs a golden value can pin across VMs are 0 (firmware code), 2 and 3 ( ROMs), 4 (boot loader and UKI), 6 (os-separator only) and 7 (Secure Boot policy: Secure Boot on, and PK, KEK and db, which are the image certificate vm-manager enrolls, see [IPE](#ipe): the values belong to an image's signing key as much as to the firmware). PCR 1 -and 5 are quoted and recorded but not compared: EDK2 measures the SMBIOS tables into -PCR 1, and the type 11 strings vm-manager passes are per-VM credentials (hostname, -machine ID, SSH key, notify socket), as is the `Boot####` entry with the ESP's partition -GUID; PCR 5 holds the GPT of the installed disk with its per-install partition UUIDs. +and 5 have no golden values: EDK2 measures the SMBIOS tables into PCR 1, and the type 11 +strings vm-manager passes are per-VM credentials (hostname, machine ID, SSH key, notify +socket), as is the `Boot####` entry with the ESP's partition GUID; PCR 5 holds the GPT of the +installed disk with its per-install partition UUIDs. The verifier replays the firmware event +log against them: the GPT must hold the partitions `repart.sysinstall.d` lays out, the boot +variables and `loader.conf` what the VM's first verified boot measured. A local build or another firmware gets its golden values recorded the way the release pipeline records them: `vm-manager image golden giantswarm-vm-base --image-dir ` boots a reference VM on the firmware the server boots and writes the golden values and diff --git a/internal/attest/bootconfig.go b/internal/attest/bootconfig.go new file mode 100644 index 0000000..8c92b9c --- /dev/null +++ b/internal/attest/bootconfig.go @@ -0,0 +1,362 @@ +package attest + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "regexp" + "slices" + "strings" + + "github.com/google/go-tpm/tpm2" + + "github.com/giantswarm/vm-manager/internal/tpmquote" +) + +// PCRs the firmware measures the platform and boot configuration into +// (TCG PC Client Platform Firmware Profile). Their values differ per VM, so +// they are not golden: the verifier replays the firmware event log against +// them (replayBootConfig). +const ( + // PCRPlatformConfig is PCR 1: the ACPI tables and the SMBIOS tables QEMU + // hands the firmware, the firmware's boot variables (BootOrder and the + // Boot#### options it measures), and the SMBIOS structures + // systemd-boot and systemd-stub measure. + PCRPlatformConfig = 1 + // PCRBootLoaderConfig is PCR 5: the boot disk's partition table (GPT), + // systemd-boot's loader.conf and ExitBootServices. + PCRBootLoaderConfig = 5 +) + +// Tags of the EV_EVENT_TAG events systemd-boot and systemd-stub log into +// PCRs 1 and 5 (src/fundamental/tpm2-pcr.h). +const ( + tagLoaderConf uint32 = 0xf5bc582a + tagSMBIOSType1 uint32 = 0xd5cb7cbc + tagSMBIOSType2 uint32 = 0xe0d47bc8 + tagSMBIOSType11 uint32 = 0xc0b3bd23 +) + +// LoaderConf names systemd-boot's loader.conf in a boot configuration. +const LoaderConf = "loader.conf" + +// exitBootServices are the EV_EFI_ACTION strings the firmware logs into PCR +// 5 around ExitBootServices when it succeeds. +var exitBootServices = []string{"Exit Boot Services Invocation", "Exit Boot Services Returned with Success"} + +// bootVariable is the name of a boot variable the firmware measures into +// PCR 1. +var bootVariable = regexp.MustCompile(`^(BootOrder|Boot[0-9A-F]{4})$`) + +// bootConfig is what PCRs 1 and 5 of a boot measured: the configuration +// the guest can change, the firmware's boot variables (in its variable +// store) and systemd-boot's loader.conf (on the ESP), each as +// "=" in log order; and the boot disk's +// partition table. +type bootConfig struct { + entries []string + gpt tpmquote.GPT +} + +// replayBootConfig replays the PCR 1 and PCR 5 events of the firmware event +// log and then the records of the userspace log in the sha256 bank from +// zero, and returns what they measured once both replays reproduce the +// quoted values; the userspace records stop at the first that reproduces +// the quote, as for PCR 12 (replayKernelConfig). Every event is one the +// firmware, systemd-boot and systemd-stub log into these PCRs in a boot +// vm-manager starts, and is bound to what it claims where its data carries +// it: +// +// - PCR 1: the ACPI tables ("ACPI DATA") and the SMBIOS tables +// (EV_EFI_HANDOFF_TABLES) QEMU builds from vm-manager's arguments and the +// SMBIOS structures systemd-boot and systemd-stub measure, none of which +// the guest can write; BootOrder and the Boot#### options, whose digest +// is that of the variable's data in the event; the separator. +// - PCR 5: the separator; the partition table, whose digest is that of +// the event; loader.conf (its content is not in the log, its digest is +// kept); the ExitBootServices actions, whose digest is that of the +// string. +// - the userspace log: the initrd's OSSeparator, which +// systemd-pcrosseparator.service measures into PCRs 1 and 5 too. +// +// Any other event or record rejects the logs. +func replayBootConfig(firmwareLog, userspaceLog []byte, quoted map[int][]byte) (bootConfig, error) { + if len(firmwareLog) == 0 { + return bootConfig{}, errors.New("pcr 1 and 5: the request has no firmware event log") + } + events, err := tpmquote.ParseEventLog(firmwareLog) + if err != nil { + return bootConfig{}, fmt.Errorf("pcr 1 and 5: %w", err) + } + var bc bootConfig + gpts := 0 + for _, index := range []int{PCRPlatformConfig, PCRBootLoaderConfig} { + pcr := make([]byte, sha256.Size) + n := 0 + for _, ev := range events { + if ev.PCR != index || ev.Type == tpmquote.EventNoAction { + continue + } + n++ + digest, ok := ev.Digests[tpm2.TPMAlgSHA256] + if !ok { + return bootConfig{}, fmt.Errorf("pcr %d: firmware event %d has no %s digest", index, ev.Seq, Bank) + } + if err := bc.add(index, ev, digest); err != nil { + return bootConfig{}, fmt.Errorf("pcr %d: firmware event %d: %v", index, ev.Seq, err) + } + if ev.Type == tpmquote.EventEFIGPT { + gpts++ + } + sum := sha256.Sum256(append(append([]byte(nil), pcr...), digest...)) + pcr = sum[:] + } + if err := replayOSSeparator(userspaceLog, index, pcr, quoted[index], n); err != nil { + return bootConfig{}, err + } + } + if gpts != 1 { + return bootConfig{}, fmt.Errorf("pcr 5: the firmware event log has %d partition tables, a boot from the vm's disk one", gpts) + } + return bc, nil +} + +// replayOSSeparator goes on from pcr, what the n firmware events of PCR +// index replayed to, with the PCR's records of the userspace log, each the +// initrd's OSSeparator, until the replay reproduces quoted. +func replayOSSeparator(userspaceLog []byte, index int, pcr, quoted []byte, n int) error { + for rec, err := range userspaceRecords(userspaceLog, index) { + if bytes.Equal(pcr, quoted) { + return nil + } + if err != nil { + return err + } + n++ + digest, word, err := rec.bound(index) + if err != nil { + return fmt.Errorf("pcr %d: userspace log record %d: %v", index, rec.index, err) + } + if word != OSSeparator { + return fmt.Errorf("pcr %d: userspace log record %d: %s is not a pcr %d measurement of the image (%s)", index, rec.index, quoteWord(word), index, OSSeparator) + } + sum := sha256.Sum256(append(append([]byte(nil), pcr...), digest...)) + pcr = sum[:] + } + if !bytes.Equal(pcr, quoted) { + return fmt.Errorf("pcr %d: the %d pcr %d events of the firmware and userspace logs replay to %x, the quote has %x", index, n, index, pcr, quoted) + } + return nil +} + +// add binds one firmware event of PCR index to what it claims and records +// what the guest can change. +func (bc *bootConfig) add(index int, ev tpmquote.Event, digest []byte) error { + sum := sha256.Sum256(ev.Data) + bound := bytes.Equal(sum[:], digest) + switch { + case ev.Type == tpmquote.EventSeparator: + if !bound || !bytes.Equal(ev.Data, []byte{0, 0, 0, 0}) { + return fmt.Errorf("a separator that is not the digest of four zero bytes (%x): the firmware reported an error", ev.Data) + } + case index == PCRPlatformConfig && ev.Type == tpmquote.EventPlatformConfigFlags: + if string(ev.Data) != "ACPI DATA" { + return fmt.Errorf("platform configuration %q, which the firmware does not measure in a boot vm-manager starts", ev.Data) + } + case index == PCRPlatformConfig && (ev.Type == tpmquote.EventEFIHandoffTables || ev.Type == tpmquote.EventEFIHandoffTables2): + case index == PCRPlatformConfig && (ev.Type == tpmquote.EventEFIVariableBoot || ev.Type == tpmquote.EventEFIVariableBoot2): + v, err := tpmquote.ParseVariable(ev.Data) + if err != nil { + return err + } + if v.GUID != tpmquote.EFIGlobalVariable || !bootVariable.MatchString(v.Name) { + return fmt.Errorf("the variable %s-%s, which is not a boot variable", v.Name, v.GUID) + } + if data := sha256.Sum256(v.Data); ev.Type == tpmquote.EventEFIVariableBoot && !bytes.Equal(data[:], digest) || ev.Type == tpmquote.EventEFIVariableBoot2 && !bound { + return fmt.Errorf("its sha256 digest is not the digest of the variable %s it logs", v.Name) + } + bc.entries = append(bc.entries, v.Name+"="+hex.EncodeToString(digest)) + case index == PCRPlatformConfig && ev.Type == tpmquote.EventTag: + switch tag := eventTag(ev.Data); tag { + case tagSMBIOSType1, tagSMBIOSType2, tagSMBIOSType11: + default: + return fmt.Errorf("a tagged event 0x%08x, which no boot vm-manager starts measures into pcr 1", tag) + } + case index == PCRBootLoaderConfig && ev.Type == tpmquote.EventEFIGPT: + if !bound { + return errors.New("its sha256 digest is not the digest of the partition table it logs") + } + gpt, err := tpmquote.ParseGPT(ev.Data) + if err != nil { + return err + } + bc.gpt = gpt + case index == PCRBootLoaderConfig && ev.Type == tpmquote.EventTag: + if tag := eventTag(ev.Data); tag != tagLoaderConf { + return fmt.Errorf("a tagged event 0x%08x, which no boot vm-manager starts measures into pcr 5", tag) + } + bc.entries = append(bc.entries, LoaderConf+"="+hex.EncodeToString(digest)) + case index == PCRBootLoaderConfig && ev.Type == tpmquote.EventEFIAction: + if !bound || !slices.Contains(exitBootServices, string(ev.Data)) { + return fmt.Errorf("the action %q, which a boot vm-manager starts does not measure into pcr 5", ev.Data) + } + default: + return fmt.Errorf("event type 0x%x, which the firmware does not measure into pcr %d in a boot vm-manager starts", ev.Type, index) + } + return nil +} + +// eventTag is the tag of an EV_EVENT_TAG event, 0 without one. +func eventTag(data []byte) uint32 { + if len(data) < 4 { + return 0 + } + return binary.LittleEndian.Uint32(data) +} + +// check judges the boot configuration against the image's installed disk +// (checkPartitionTable) and against recorded, the configuration the VM's +// first verified boot measured (Policy.BootConfig): the firmware's boot +// variables and loader.conf may not change. Without a record nothing is +// compared; the caller keeps this boot's (BootConfig). +func (bc bootConfig) check(policy Policy) error { + if err := checkPartitionTable(bc.gpt, policy); err != nil { + return err + } + if len(policy.BootConfig) == 0 || slices.Equal(bc.entries, policy.BootConfig) { + return nil + } + return fmt.Errorf("pcr 1 and 5: the boot configuration changed since the vm's first verified boot: %s", diffConfig(policy.BootConfig, bc.entries)) +} + +// summary describes a verified PCR 1 and 5 for the verdict. +func (bc bootConfig) summary(policy Policy) string { + recorded := "recorded" + if len(policy.BootConfig) > 0 { + recorded = "as on the first verified boot" + } + return fmt.Sprintf("pcr 1 and 5 boot configuration %s, gpt of %d partitions", recorded, len(bc.gpt.Partitions)) +} + +// diffConfig names what changed between two boot configurations: an entry +// added, removed or with another content. +func diffConfig(was, is []string) string { + split := func(entries []string) ([]string, map[string]string) { + names, digests := make([]string, 0, len(entries)), make(map[string]string, len(entries)) + for _, e := range entries { + name, digest, _ := strings.Cut(e, "=") + names, digests[name] = append(names, name), digest + } + return names, digests + } + wasNames, wasDigests := split(was) + isNames, isDigests := split(is) + var out []string + for _, name := range isNames { + switch d, ok := wasDigests[name]; { + case !ok: + out = append(out, name+" added") + case d != isDigests[name]: + out = append(out, name+" changed") + } + } + for _, name := range wasNames { + if _, ok := isDigests[name]; !ok { + out = append(out, name+" removed") + } + } + if len(out) == 0 { + out = append(out, "the order of "+strings.Join(isNames, ", ")) + } + return strings.Join(out, ", ") +} + +// Attribute bits of a GPT partition entry (the Discoverable Partitions +// Specification) the image's partitions carry. +const ( + gptReadOnly uint64 = 1 << 60 + gptGrowFS uint64 = 1 << 59 +) + +// emptyLabel is the label of a partition slot sysupdate has not filled yet. +const emptyLabel = "_empty" + +// partitionKind is one kind of partition of the disk systemd-sysinstall +// installs from an image of this repository. +type partitionKind struct { + // name is the repart type name, typ the GPT partition type. + name, typ string + // labels are the labels a partition of the kind may carry; %M_%A + // stands for the image's id and version (repart's specifiers), the + // label of a slot holding this image's file system. + labels []string + // max is how many partitions of the kind the disk holds. + max int + // attributes are the attribute bits a partition of the kind may carry. + attributes uint64 +} + +// installedDisk is the disk an installed VM boots from: what +// images/mkosi.images/base/mkosi.extra/usr/lib/repart.sysinstall.d lays out +// (the ESP, the image's root, verity and verity signature partitions as slot +// A, the empty B slots sysupdate fills, var) and repart.d completes on a +// disk installed before. TestInstalledDiskMatchesRepart keeps them equal. +var installedDisk = []partitionKind{ + {name: "esp", typ: "c12a7328-f81f-11d2-ba4b-00a0c93ec93b", labels: []string{"esp"}, max: 1}, + {name: "root", typ: "4f68bce3-e8cd-4db1-96e7-fbcaf984b709", labels: []string{"%M_%A", emptyLabel}, max: 2, attributes: gptReadOnly | gptGrowFS}, + {name: "root-verity", typ: "2c7357ed-ebd2-46d9-aec1-23d437ec2bf5", labels: []string{"%M_%A_verity", emptyLabel}, max: 2, attributes: gptReadOnly | gptGrowFS}, + {name: "root-verity-sig", typ: "41092b05-9fc8-4523-994f-2def0408b176", labels: []string{"%M_%A_verity_sig", emptyLabel}, max: 2, attributes: gptReadOnly | gptGrowFS}, + {name: "var", typ: "4d21b016-b534-45c2-a9fb-5c16e091fd2d", labels: []string{"var"}, max: 1, attributes: gptGrowFS}, +} + +// checkPartitionTable requires the boot disk's partitions to be those of +// installedDisk for the image of the policy: every partition of a kind the +// disk has, labelled as that kind may be, with no attribute it may not +// carry, no kind more often than the disk has it and no label but +// emptyLabel twice. A partition added, retyped, relabelled or given another +// attribute (no-auto, say) fails the boot. +func checkPartitionTable(gpt tpmquote.GPT, policy Policy) error { + if policy.ImageID == "" || policy.ImageVersion == "" { + return errors.New("pcr 5: the image policy names no image id and version, which the labels of its partitions carry") + } + image := policy.ImageID + "_" + policy.ImageVersion + count := map[string]int{} + seen := map[string]bool{} + for _, p := range gpt.Partitions { + i := slices.IndexFunc(installedDisk, func(k partitionKind) bool { return k.typ == p.Type }) + if i < 0 { + return fmt.Errorf("pcr 5: the partition table holds a partition of type %s (%q), which the image does not define", p.Type, p.Name) + } + kind := installedDisk[i] + var labels []string + for _, l := range kind.labels { + labels = append(labels, strings.ReplaceAll(l, "%M_%A", image)) + } + if !slices.Contains(labels, p.Name) { + return fmt.Errorf("pcr 5: a %s partition is labelled %q, the image's are labelled %s", kind.name, p.Name, strings.Join(quoteAll(labels), " or ")) + } + if extra := p.Attributes &^ kind.attributes; extra != 0 { + return fmt.Errorf("pcr 5: the %s partition %q carries the gpt attributes 0x%016x, which the image's do not", kind.name, p.Name, extra) + } + if count[kind.name]++; count[kind.name] > kind.max { + return fmt.Errorf("pcr 5: the partition table holds %d %s partitions, the image's disk %d", count[kind.name], kind.name, kind.max) + } + if p.Name != emptyLabel && seen[p.Name] { + return fmt.Errorf("pcr 5: two partitions are labelled %q", p.Name) + } + seen[p.Name] = true + } + return nil +} + +// quoteAll quotes each string. +func quoteAll(ss []string) []string { + out := make([]string, len(ss)) + for i, s := range ss { + out[i] = fmt.Sprintf("%q", s) + } + return out +} diff --git a/internal/attest/bootconfig_test.go b/internal/attest/bootconfig_test.go new file mode 100644 index 0000000..b59a129 --- /dev/null +++ b/internal/attest/bootconfig_test.go @@ -0,0 +1,275 @@ +package attest + +import ( + "bufio" + "crypto/sha256" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/google/go-tpm/tpm2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/giantswarm/vm-manager/internal/tpmquote" + "github.com/giantswarm/vm-manager/internal/tpmquote/quotetest" +) + +// testImage is the image the boot configuration fixtures were installed +// from. +var testImage = Policy{ImageID: "giantswarm-vm-base", ImageVersion: "0.1.0"} + +// bootConfigLog is the firmware and userspace logs and the PCR 1 and 5 +// values one VM of the 0.29.1 release had at its ready stage +// (../tpmquote/testdata, testdata/pcr12, testdata/pcr1-5): its first +// installed boot and a reboot. +func bootConfigLog(t *testing.T, boot string) ([]byte, []byte, map[int][]byte) { + t.Helper() + firmware, userspace, _ := bootLogs(t, boot) + quoted := map[int][]byte{} + for _, index := range []int{PCRPlatformConfig, PCRBootLoaderConfig} { + value, err := os.ReadFile(filepath.Join("testdata", "pcr1-5", fmt.Sprintf("%s-pcr%d.hex", boot, index))) // #nosec G304 -- fixed test fixtures + require.NoError(t, err) + quoted[index], err = hex.DecodeString(strings.TrimSpace(string(value))) + require.NoError(t, err) + } + return firmware, userspace, quoted +} + +// TestReplayBootConfigReleasedBoots: a node's first installed boot and its +// reboot replay to their quoted PCR 1 and 5, measure the same boot +// configuration and hold the image's disk, the first boot's before +// systemd-repart added the empty B slots. +func TestReplayBootConfigReleasedBoots(t *testing.T) { + first, err := replayBootConfig(bootConfigLog(t, "firstboot")) + require.NoError(t, err) + reboot, err := replayBootConfig(bootConfigLog(t, "reboot")) + require.NoError(t, err) + tampered, err := replayBootConfig(bootConfigLog(t, "tampered")) + require.NoError(t, err) + assert.Equal(t, reboot, tampered, "a loader entry's options are not boot configuration: pcr 12 judges them") + + var names []string + for _, e := range first.entries { + name, digest, _ := strings.Cut(e, "=") + names = append(names, name) + assert.Len(t, digest, 64) + } + assert.Equal(t, []string{"BootOrder", "Boot0002", "Boot0004", "Boot0000", "Boot0001", "Boot0005", LoaderConf}, names) + assert.Equal(t, first.entries, reboot.entries, "a reboot measures the boot configuration of the first boot") + assert.Len(t, first.gpt.Partitions, 5) + assert.Len(t, reboot.gpt.Partitions, 8) + assert.Equal(t, first.gpt.DiskGUID, reboot.gpt.DiskGUID) + assert.Equal(t, tpmquote.Partition{ + Type: quotetest.TypeRoot, GUID: "3c8143d8-9097-3c35-a47d-254740c6c8d8", FirstLBA: 1050624, LastLBA: 5244927, + Attributes: quotetest.ReadOnly, Name: "giantswarm-vm-base_0.1.0", + }, first.gpt.Partitions[1]) + + require.NoError(t, first.check(testImage)) + recorded := testImage + recorded.BootConfig = first.entries + require.NoError(t, reboot.check(recorded), "the reboot verifies against the first boot's configuration") + assert.Equal(t, "pcr 1 and 5 boot configuration as on the first verified boot, gpt of 8 partitions", reboot.summary(recorded)) + assert.Equal(t, "pcr 1 and 5 boot configuration recorded, gpt of 5 partitions", first.summary(testImage)) + + firmware, userspace, quoted := bootConfigLog(t, "reboot") + quoted[PCRBootLoaderConfig] = quoted[PCRPlatformConfig] + _, err = replayBootConfig(firmware, userspace, quoted) + assert.ErrorContains(t, err, "pcr 5: the 6 pcr 5 events of the firmware and userspace logs replay to ") + _, err = replayBootConfig(firmware, nil, quoted) + assert.ErrorContains(t, err, "pcr 1: the 14 pcr 1 events of the firmware and userspace logs replay to ", "the initrd's os-separator is in the quote") +} + +// replay replays events as the firmware log of a boot whose PCRs hold +// exactly them. +func replay(events ...tpmquote.Event) (bootConfig, error) { + quoted := map[int][]byte{PCRPlatformConfig: make([]byte, sha256.Size), PCRBootLoaderConfig: make([]byte, sha256.Size)} + for _, ev := range events { + if _, ok := quoted[ev.PCR]; ok { + sum := sha256.Sum256(append(quoted[ev.PCR], ev.Digests[tpm2.TPMAlgSHA256]...)) + quoted[ev.PCR] = sum[:] + } + } + return replayBootConfig(quotetest.EncodeEventLog(events...), nil, quoted) +} + +// with is the boot configuration of the test image with the event at i +// replaced by ev, or ev appended when i is negative. +func with(i int, ev tpmquote.Event) []tpmquote.Event { + events := quotetest.BootConfig("giantswarm-vm-base_0.1.0") + if i < 0 { + return append(events, ev) + } + events[i] = ev + return events +} + +func TestReplayBootConfigBindsEvents(t *testing.T) { + bc, err := replay(quotetest.BootConfig("giantswarm-vm-base_0.1.0")...) + require.NoError(t, err) + require.NoError(t, bc.check(testImage)) + loaderConf := sha256.Sum256([]byte(quotetest.LoaderConf)) + assert.Equal(t, LoaderConf+"="+hex.EncodeToString(loaderConf[:]), bc.entries[len(bc.entries)-1]) + + unbound := func(ev tpmquote.Event) tpmquote.Event { + ev.Digests = map[tpm2.TPMAlgID][]byte{tpm2.TPMAlgSHA256: make([]byte, sha256.Size)} + return ev + } + errorSeparator := quotetest.Separator(1) + errorSeparator.Data = []byte{0xff, 0xff, 0xff, 0xff} + notBootVariable := quotetest.BootVariable("SecureBoot", []byte{1}) + notBootVariable.Data = quotetest.Variable("8be4df61-93ca-11d2-aa0d-00e098032b8c", "SecureBoot", []byte{1}) + for name, tc := range map[string]struct { + events []tpmquote.Event + want string + }{ + "a boot variable not bound to its data": {with(4, unbound(quotetest.BootVariable("Boot0001", []byte("x")))), + "pcr 1: firmware event 5: its sha256 digest is not the digest of the variable Boot0001 it logs"}, + "another variable": {with(-1, notBootVariable), "pcr 1: firmware event 15: the variable SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c, which is not a boot variable"}, + "a separator reporting an error": {with(6, errorSeparator), "pcr 1: firmware event 7: a separator that is not the digest of four zero bytes (ffffffff): the firmware reported an error"}, + "other platform configuration": {with(0, quotetest.Tagged(1, 0x13aed6db, "UKI profile", nil)), "pcr 1: firmware event 1: a tagged event 0x13aed6db, which no boot vm-manager starts measures into pcr 1"}, + "an unknown pcr 1 event": {with(0, tpmquote.Event{PCR: 1, Type: tpmquote.EventIPL, Digests: quotetest.Separator(1).Digests}), + "pcr 1: firmware event 1: event type 0xd, which the firmware does not measure into pcr 1 in a boot vm-manager starts"}, + "a partition table not bound to its data": {with(10, unbound(quotetest.GPTEvent())), "pcr 5: firmware event 11: its sha256 digest is not the digest of the partition table it logs"}, + "a second partition table": {with(-1, quotetest.GPTEvent()), "pcr 5: the firmware event log has 2 partition tables, a boot from the vm's disk one"}, + "no partition table": {with(10, quotetest.Action("Exit Boot Services Invocation")), "pcr 5: the firmware event log has 0 partition tables, a boot from the vm's disk one"}, + "another pcr 5 tag": {with(11, quotetest.Tagged(5, quotetest.TagSMBIOSType1, "smbios:type1", nil)), "pcr 5: firmware event 12: a tagged event 0xd5cb7cbc, which no boot vm-manager starts measures into pcr 5"}, + "a failed ExitBootServices": {with(13, quotetest.Action("Exit Boot Services Returned with Failure")), `pcr 5: firmware event 14: the action "Exit Boot Services Returned with Failure", which a boot vm-manager starts does not measure into pcr 5`}, + } { + t.Run(name, func(t *testing.T) { + _, err := replay(tc.events...) + assert.EqualError(t, err, tc.want) + }) + } + + _, err = replayBootConfig(nil, nil, nil) + assert.EqualError(t, err, "pcr 1 and 5: the request has no firmware event log") +} + +func TestCheckPartitionTable(t *testing.T) { + const image = "giantswarm-vm-base_0.1.0" + disk := func(change func([]tpmquote.Partition) []tpmquote.Partition) tpmquote.GPT { + return tpmquote.GPT{Partitions: change(quotetest.InstalledDisk(image))} + } + same := func(p []tpmquote.Partition) []tpmquote.Partition { return p } + require.NoError(t, checkPartitionTable(disk(same), testImage)) + require.NoError(t, checkPartitionTable(disk(func(p []tpmquote.Partition) []tpmquote.Partition { return slices.Delete(p, 4, 7) }), testImage), + "a disk installed before the B slots") + + for name, tc := range map[string]struct { + change func([]tpmquote.Partition) []tpmquote.Partition + want string + }{ + "a partition of another type": {func(p []tpmquote.Partition) []tpmquote.Partition { + p[4].Type = "0fc63daf-8483-4772-8e79-3d69d8477de4" + return p + }, `pcr 5: the partition table holds a partition of type 0fc63daf-8483-4772-8e79-3d69d8477de4 ("_empty"), which the image does not define`}, + "another label": {func(p []tpmquote.Partition) []tpmquote.Partition { + p[0].Name = "boot" + return p + }, `pcr 5: a esp partition is labelled "boot", the image's are labelled "esp"`}, + "another image": {func(p []tpmquote.Partition) []tpmquote.Partition { + p[1].Name = "giantswarm-vm-base_0.0.9" + return p + }, `pcr 5: a root partition is labelled "giantswarm-vm-base_0.0.9", the image's are labelled "giantswarm-vm-base_0.1.0" or "_empty"`}, + "no-auto": {func(p []tpmquote.Partition) []tpmquote.Partition { + p[7].Attributes |= 1 << 63 + return p + }, `pcr 5: the var partition "var" carries the gpt attributes 0x8000000000000000, which the image's do not`}, + "an added partition": {func(p []tpmquote.Partition) []tpmquote.Partition { + return append(p, tpmquote.Partition{Type: quotetest.TypeVar, Name: "var"}) + }, "pcr 5: the partition table holds 2 var partitions, the image's disk 1"}, + "a label twice": {func(p []tpmquote.Partition) []tpmquote.Partition { + p[4].Name = image + return p + }, `pcr 5: two partitions are labelled "giantswarm-vm-base_0.1.0"`}, + } { + t.Run(name, func(t *testing.T) { + assert.EqualError(t, checkPartitionTable(disk(tc.change), testImage), tc.want) + }) + } + assert.EqualError(t, checkPartitionTable(disk(same), Policy{}), "pcr 5: the image policy names no image id and version, which the labels of its partitions carry") +} + +func TestBootConfigChanged(t *testing.T) { + recorded := []string{"BootOrder=00", "Boot0000=01", "Boot0001=02", "loader.conf=03"} + for name, tc := range map[string]struct { + now []string + want string + }{ + "a boot option": {[]string{"BootOrder=00", "Boot0000=01", "Boot0001=ff", "loader.conf=03"}, "Boot0001 changed"}, + "loader.conf": {[]string{"BootOrder=00", "Boot0000=01", "Boot0001=02", "loader.conf=ff"}, "loader.conf changed"}, + "an added option": {[]string{"BootOrder=ff", "Boot0000=01", "Boot0001=02", "Boot0007=07", "loader.conf=03"}, "BootOrder changed, Boot0007 added"}, + "a removed one": {[]string{"BootOrder=ff", "Boot0001=02", "loader.conf=03"}, "BootOrder changed, Boot0000 removed"}, + "the order": {[]string{"BootOrder=00", "Boot0001=02", "Boot0000=01", "loader.conf=03"}, "the order of BootOrder, Boot0001, Boot0000, loader.conf"}, + } { + t.Run(name, func(t *testing.T) { + bc := bootConfig{entries: tc.now, gpt: tpmquote.GPT{Partitions: quotetest.InstalledDisk("giantswarm-vm-base_0.1.0")}} + policy := testImage + policy.BootConfig = recorded + assert.EqualError(t, bc.check(policy), "pcr 1 and 5: the boot configuration changed since the vm's first verified boot: "+tc.want) + }) + } +} + +// TestInstalledDiskMatchesRepart keeps installedDisk in step with the +// definitions systemd-sysinstall installs a disk from and the ones repart +// completes it with at boot: every kind as often as it is defined, with the +// labels and read-only attribute the definitions give it. +func TestInstalledDiskMatchesRepart(t *testing.T) { + const lib = "../../images/mkosi.images/base/mkosi.extra/usr/lib" + for _, dir := range []string{"repart.sysinstall.d", "repart.d"} { + files, err := filepath.Glob(filepath.Join(lib, dir, "*.conf")) + require.NoError(t, err) + require.NotEmpty(t, files, dir) + count := map[string]int{} + for _, f := range files { + def := partitionDefinition(t, f) + i := slices.IndexFunc(installedDisk, func(k partitionKind) bool { return k.name == def["Type"] }) + require.GreaterOrEqual(t, i, 0, "%s: type %s is no kind of installedDisk", f, def["Type"]) + kind := installedDisk[i] + count[kind.name]++ + // A definition without a label takes the type's name, but + // repart.d's slot A definitions only claim the partitions + // systemd-sysinstall created and keep their labels. + label := def["Label"] + if label == "" && dir == "repart.sysinstall.d" { + label = kind.name + } + if label != "" { + assert.Contains(t, kind.labels, label, f) + } + if def["ReadOnly"] == "yes" { + assert.NotZero(t, kind.attributes&gptReadOnly, "%s: read-only", f) + } + } + for _, kind := range installedDisk { + if dir == "repart.sysinstall.d" { + assert.Equal(t, kind.max, count[kind.name], "%s defines %d %s partitions", dir, count[kind.name], kind.name) + } else { + assert.LessOrEqual(t, count[kind.name], kind.max, dir) + } + } + } +} + +// partitionDefinition reads the [Partition] keys of a repart definition. +func partitionDefinition(t *testing.T, path string) map[string]string { + t.Helper() + f, err := os.Open(path) // #nosec G304 -- the repository's definitions + require.NoError(t, err) + defer func() { _ = f.Close() }() + def := map[string]string{} + s := bufio.NewScanner(f) + for s.Scan() { + if k, v, ok := strings.Cut(strings.TrimSpace(s.Text()), "="); ok && !strings.HasPrefix(k, "#") { + def[k] = v + } + } + require.NoError(t, s.Err()) + return def +} diff --git a/internal/attest/kernelconfig_verifier_test.go b/internal/attest/kernelconfig_verifier_test.go index f70b851..e018b59 100644 --- a/internal/attest/kernelconfig_verifier_test.go +++ b/internal/attest/kernelconfig_verifier_test.go @@ -109,7 +109,7 @@ func TestVerifierRejectsLoaderEntryOptions(t *testing.T) { e.firmware = []tpmquote.Event{relabelled, relabelled} res = e.submit(e.request(e.ak, imds.StageInitrd)) assert.False(t, res.Verified) - assert.Equal(t, `pcr 12: firmware event 1: a credential archive loaded from the ESP ("Entry credentials initrd"), which no boot vm-manager starts has`, res.Message) + assert.Equal(t, `pcr 12: firmware event 15: a credential archive loaded from the ESP ("Entry credentials initrd"), which no boot vm-manager starts has`, res.Message) } func TestVerifierRejectsESPArchives(t *testing.T) { @@ -121,7 +121,7 @@ func TestVerifierRejectsESPArchives(t *testing.T) { e.osSeparator() res := e.submit(e.request(e.ak, imds.StageInitrd)) assert.False(t, res.Verified) - assert.Equal(t, `pcr 12: firmware event 1: a credential archive loaded from the ESP ("Entry credentials initrd"), which no boot vm-manager starts has`, res.Message) + assert.Equal(t, `pcr 12: firmware event 15: a credential archive loaded from the ESP ("Entry credentials initrd"), which no boot vm-manager starts has`, res.Message) }) t.Run("an extension image", func(t *testing.T) { diff --git a/internal/attest/policy.go b/internal/attest/policy.go index b243991..e9477be 100644 --- a/internal/attest/policy.go +++ b/internal/attest/policy.go @@ -43,14 +43,13 @@ var firmwarePCRs = []int{0, 1, 2, 3, 4, 5, 6, 7} // goldenFirmwarePCRs are the firmware PCRs a golden value recorded on one // known-good boot can vouch for on every VM of the same firmware and image: // 0 (firmware code), 2 and 3 (option ROMs), 4 (boot loader and UKI), 6 -// (nothing but the os-separator), 7 (Secure Boot policy). PCR 1 and 5 are -// quoted and recorded but differ per VM by construction, so they are not -// compared: EDK2 measures the SMBIOS tables into PCR 1, and vm-manager's type -// 11 strings carry per-VM credentials (hostname, machine ID, SSH key, notify -// socket), as does the Boot#### entry with the ESP's partition GUID; PCR 5 -// holds the GPT of the installed disk with its per-install partition UUIDs. -// Both are in the firmware event log the agent posts (QuoteRequest.EventLog) -// for a replay-based check per VM (docs/design.md, open points). +// (nothing but the os-separator), 7 (Secure Boot policy). PCR 1 and 5 differ +// per VM by construction, so no golden value vouches for them: EDK2 +// measures the ACPI and SMBIOS tables into PCR 1, whose size and type 11 +// strings are the VM's (hostname, machine ID, SSH key, notify socket), as +// is the Boot#### entry with the ESP's partition GUID; PCR 5 holds the GPT +// of the installed disk with its per-install partition UUIDs. The verifier +// replays the firmware event log against both (replayBootConfig). var goldenFirmwarePCRs = []int{0, 2, 3, 4, 6, 7} // GoldenIndexes are the PCRs `vm-manager image golden` records and the @@ -153,6 +152,12 @@ type Policy struct { // this command line and no other. The PolicyProvider sets it; // policy.json does not carry it. KernelCmdlineExtra string `json:"-"` + // BootConfig is the boot configuration the VM's first verified boot + // measured into PCRs 1 and 5 (the firmware's boot variables and + // loader.conf, Result.BootConfig), which every later boot must measure + // again; empty until the VM had one. The PolicyProvider sets it from the + // VM's record; policy.json does not carry it. + BootConfig []string `json:"-"` } // Firmware identifies a build of the firmware code image VMs boot with, as diff --git a/internal/attest/testdata/pcr1-5/firstboot-pcr1.hex b/internal/attest/testdata/pcr1-5/firstboot-pcr1.hex new file mode 100644 index 0000000..38323f0 --- /dev/null +++ b/internal/attest/testdata/pcr1-5/firstboot-pcr1.hex @@ -0,0 +1 @@ +37a4b79952e5686e3052001b918c4e6fbbb4724d5626e16c830fc261f38e4d77 \ No newline at end of file diff --git a/internal/attest/testdata/pcr1-5/firstboot-pcr5.hex b/internal/attest/testdata/pcr1-5/firstboot-pcr5.hex new file mode 100644 index 0000000..a32bd5f --- /dev/null +++ b/internal/attest/testdata/pcr1-5/firstboot-pcr5.hex @@ -0,0 +1 @@ +f110290826f0098219f71653eea0d44494a7cdb9c41c8fbed6f3ec70141632eb \ No newline at end of file diff --git a/internal/attest/testdata/pcr1-5/reboot-pcr1.hex b/internal/attest/testdata/pcr1-5/reboot-pcr1.hex new file mode 100644 index 0000000..53dd936 --- /dev/null +++ b/internal/attest/testdata/pcr1-5/reboot-pcr1.hex @@ -0,0 +1 @@ +a97d43d28e7502a5978fe1fa434a661c9728565ae3205b413f856d61c69b795f \ No newline at end of file diff --git a/internal/attest/testdata/pcr1-5/reboot-pcr5.hex b/internal/attest/testdata/pcr1-5/reboot-pcr5.hex new file mode 100644 index 0000000..535a570 --- /dev/null +++ b/internal/attest/testdata/pcr1-5/reboot-pcr5.hex @@ -0,0 +1 @@ +a8b9798e9ddc956ea0ebf495435fa6a8f582e544c6638792e65cf5775b8d9cf9 \ No newline at end of file diff --git a/internal/attest/testdata/pcr1-5/tampered-pcr1.hex b/internal/attest/testdata/pcr1-5/tampered-pcr1.hex new file mode 100644 index 0000000..53dd936 --- /dev/null +++ b/internal/attest/testdata/pcr1-5/tampered-pcr1.hex @@ -0,0 +1 @@ +a97d43d28e7502a5978fe1fa434a661c9728565ae3205b413f856d61c69b795f \ No newline at end of file diff --git a/internal/attest/testdata/pcr1-5/tampered-pcr5.hex b/internal/attest/testdata/pcr1-5/tampered-pcr5.hex new file mode 100644 index 0000000..535a570 --- /dev/null +++ b/internal/attest/testdata/pcr1-5/tampered-pcr5.hex @@ -0,0 +1 @@ +a8b9798e9ddc956ea0ebf495435fa6a8f582e544c6638792e65cf5775b8d9cf9 \ No newline at end of file diff --git a/internal/attest/verifier.go b/internal/attest/verifier.go index 1df6a36..780bb33 100644 --- a/internal/attest/verifier.go +++ b/internal/attest/verifier.go @@ -38,8 +38,8 @@ // an enrolled AK is rejected); // 6. PCR 11 equals the policy's value for the stage's phase path; // 7. PCRs 0, 2-4, 6 and 7 equal the golden values (PCR 1 and 5 differ per -// VM, see goldenFirmwarePCRs; they are quoted and recorded, not -// compared); PCR 13 is compared at the ready stage against the value +// VM, see goldenFirmwarePCRs, and are judged in step 8); PCR 13 is +// compared at the ready stage against the value // computed from the policy's sysexts entries of the VM's Kubernetes and // CNI versions (or the pcr13 entry of a VM without CNI), or the // os-separator alone for a VM without Kubernetes; it is never golden. A @@ -62,7 +62,15 @@ // other command line that replaced or extended the UKI's own, is // rejected and quoted in the message; at the initrd stage PCR 13 holds // nothing but the os-separator (InitrdSysextPCRs), so an extension image -// from the ESP fails the quote that releases user-data; +// from the ESP fails the quote that releases user-data; the PCR 1 and 5 +// events of the firmware event log replay to the quoted PCR 1 and 5, +// every one an event of a boot vm-manager starts and bound to what it +// claims where the log carries it (replayBootConfig), the boot disk's +// partition table holds the partitions of the image's installed disk and +// nothing else (checkPartitionTable), and the boot configuration the +// guest can change, the firmware's boot variables and systemd-boot's +// loader.conf, is the one the VM's first verified boot measured +// (Policy.BootConfig); // 9. at the ready stage, an image whose policy does not measure layer // certificates (Policy.PCR15) cannot be served any; when the quote // covers PCR 15 (always for an image that measures them, step 4; an @@ -165,6 +173,11 @@ type Result struct { // the ready quote's PCR 15 measured, in order, set once the userspace // log replayed to the quoted value. LayerCertificates []string `json:"layerCertificates,omitempty"` + // BootConfig is the boot configuration PCRs 1 and 5 measured, the + // firmware's boot variables and loader.conf as "=", set + // once the firmware log replayed to the quoted values; the VM service + // records the first verified boot's (Policy.BootConfig). + BootConfig []string `json:"bootConfig,omitempty"` } // pinMismatch is the rejection for a quote signed by another key than the @@ -380,6 +393,14 @@ func (v *Verifier) SubmitQuote(ctx context.Context, vmID string, req imds.QuoteR if err := kc.check(policy.KernelCmdlineExtra); err != nil { return reject("%v", err) } + bc, err := replayBootConfig(req.EventLog, req.UserspaceLog, values) + if err != nil { + return reject("%v", err) + } + res.BootConfig = bc.entries + if err := bc.check(policy); err != nil { + return reject("%v", err) + } if got := res.PCRs[PCRSysext]; req.Stage == imds.StageInitrd && !slices.Contains(InitrdSysextPCRs(), got) { return reject("pcr 13 at the initrd stage is %s, not %s: an extension image extended the initrd%s", got, strings.Join(InitrdSysextPCRs(), " or "), loggedSysexts(req.EventLog)) @@ -405,7 +426,7 @@ func (v *Verifier) SubmitQuote(ctx context.Context, vmID string, req imds.QuoteR verdict = "recorded" } res.Message = fmt.Sprintf("%s: ak %s %s, pcr 11 phase %s", verdict, short(q.AKFingerprint), Certified, phase) - res.Message += ", " + kc.summary() + res.Message += ", " + kc.summary() + ", " + bc.summary(policy) if sysext != "" { res.Message += ", pcr 13 " + sysext } @@ -552,6 +573,7 @@ func (r Result) clone() Result { r.PCRs = pcrs } r.LayerCertificates = append([]string(nil), r.LayerCertificates...) + r.BootConfig = append([]string(nil), r.BootConfig...) return r } diff --git a/internal/attest/verifier_test.go b/internal/attest/verifier_test.go index 3d7411a..0c27c24 100644 --- a/internal/attest/verifier_test.go +++ b/internal/attest/verifier_test.go @@ -12,7 +12,9 @@ import ( "fmt" "io" "log/slog" + "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -53,15 +55,30 @@ type env struct { // records is systemd's userspace measurement log, one record per // element, posted with every quote. records [][]byte - // firmware is the firmware event log, posted with every quote when - // it has events (logFirmware). + // firmware is the firmware event log's events of PCR 12, posted with + // every quote after boot (logFirmware). firmware []tpmquote.Event + // boot is the firmware event log's events of PCRs 1 and 5, the boot + // configuration of an installed VM of the image + // (quotetest.BootConfig), extended when the env is made. + boot []tpmquote.Event } func newEnv(t *testing.T) *env { + t.Helper() + return newEnvBooted(t, quotetest.BootConfig("giantswarm-vm-base_0.1.0")) +} + +// newEnvBooted is newEnv for a VM whose firmware measured boot into PCRs 1 +// and 5. +func newEnvBooted(t *testing.T, boot []tpmquote.Event) *env { t.Helper() e := &env{t: t, ctx: context.Background(), sim: quotetest.Open(t), now: time.Date(2026, 9, 12, 12, 0, 0, 0, time.UTC)} e.ak = e.sim.NewAK(tpmquote.AKTemplate) + e.boot = boot + for _, ev := range e.boot { + e.sim.ExtendDigest(ev.PCR, ev.Digests[tpm2.TPMAlgSHA256]) + } e.sim.Extend(0, "firmware") e.sim.Extend(4, "systemd-boot") e.sim.Extend(7, "secure boot db") @@ -74,9 +91,11 @@ func newEnv(t *testing.T) *env { ready = quotetest.Extended(ready, phase) } e.policy = attest.Policy{ - PCR11: map[string]string{attest.PhaseInitrd: hex.EncodeToString(values[11]), attest.PhaseReady: hex.EncodeToString(ready)}, - PCR15: attest.PCR15LayerCertificates, - Golden: map[string]map[int]string{attest.Bank: {}}, + ImageID: "giantswarm-vm-base", + ImageVersion: "0.1.0", + PCR11: map[string]string{attest.PhaseInitrd: hex.EncodeToString(values[11]), attest.PhaseReady: hex.EncodeToString(ready)}, + PCR15: attest.PCR15LayerCertificates, + Golden: map[string]map[int]string{attest.Bank: {}}, } for i := 0; i <= 7; i++ { e.policy.Golden[attest.Bank][i] = hex.EncodeToString(values[i]) @@ -177,9 +196,7 @@ func (e *env) requestOver(nonce string, ak *quotetest.AK, stage imds.Stage, pcrs } req := imds.QuoteRequest{Stage: stage, Nonce: nonce, AKPub: ak.PubBytes, Quote: quote, Signature: sig, PCRs: map[string]map[string]string{attest.Bank: bank}, UserspaceLog: bytes.Join(e.records, nil)} - if len(e.firmware) > 0 { - req.EventLog = quotetest.EncodeEventLog(e.firmware...) - } + req.EventLog = quotetest.EncodeEventLog(append(append([]tpmquote.Event(nil), e.boot...), e.firmware...)...) return req } @@ -588,9 +605,12 @@ func TestVerifierRejectsBadQuotes(t *testing.T) { // the two halves of the protocol meet on one simulator. func TestVerifierAcceptsAgentQuotes(t *testing.T) { e := newEnv(t) - // No event logs: the host's are not the guest's and may be unreadable. - none := filepath.Join(t.TempDir(), "absent") - agent, err := quote.OpenSession(quote.Options{TPM: e.sim.Transport(), FirmwareLog: none, UserspaceLog: none}) + // The firmware log is the env's boot configuration, not the host's, + // which is not the guest's and may be unreadable; no userspace log. + dir := t.TempDir() + firmware := filepath.Join(dir, "binary_bios_measurements") + require.NoError(t, os.WriteFile(firmware, quotetest.EncodeEventLog(e.boot...), 0o600)) + agent, err := quote.OpenSession(quote.Options{TPM: e.sim.Transport(), FirmwareLog: firmware, UserspaceLog: filepath.Join(dir, "absent")}) require.NoError(t, err) t.Cleanup(func() { _ = agent.Close() }) build := func(stage imds.Stage) imds.QuoteRequest { @@ -874,3 +894,77 @@ func nilIfEmpty(s []string) []string { } return s } + +// TestVerifierBootConfig: the boot configuration a VM's first verified boot +// measured into PCRs 1 and 5 (its boot variables and loader.conf) is in the +// result for the VM service to keep; a later boot that measures another one, +// or a partition table the image's disk does not have, is rejected. +func TestVerifierBootConfig(t *testing.T) { + const image = "giantswarm-vm-base_0.1.0" + var recorded []string + t.Run("the first verified boot", func(t *testing.T) { + e := newEnv(t) + res := e.submit(e.request(e.ak, imds.StageInitrd)) + require.True(t, res.Verified, res.Message) + assert.Contains(t, res.Message, ", pcr 1 and 5 boot configuration recorded, gpt of 8 partitions") + r, ok := e.v.Result(vmID, imds.StageInitrd) + require.True(t, ok) + require.Len(t, r.BootConfig, 4) + assert.True(t, strings.HasPrefix(r.BootConfig[0], "BootOrder="), r.BootConfig[0]) + assert.True(t, strings.HasPrefix(r.BootConfig[3], attest.LoaderConf+"="), r.BootConfig[3]) + recorded = r.BootConfig + + e.policy.BootConfig = recorded + res = e.submit(e.request(e.ak, imds.StageInitrd)) + require.True(t, res.Verified, res.Message) + assert.Contains(t, res.Message, ", pcr 1 and 5 boot configuration as on the first verified boot, gpt of 8 partitions") + }) + require.NotEmpty(t, recorded) + + for name, tc := range map[string]struct { + boot []tpmquote.Event + want string + // same says the boot measured the recorded configuration. + same bool + }{ + "a boot option changed": { + boot: replaceEvent(quotetest.BootConfig(image), 4, quotetest.BootVariable("Boot0001", []byte("Linux Boot Managex"))), + want: "pcr 1 and 5: the boot configuration changed since the vm's first verified boot: Boot0001 changed", + }, + "loader.conf changed": { + boot: replaceEvent(quotetest.BootConfig(image), 11, quotetest.Tagged(5, quotetest.TagLoaderConf, "loader.conf", []byte("editor yes\n"))), + want: "pcr 1 and 5: the boot configuration changed since the vm's first verified boot: loader.conf changed", + }, + "a partition added": { + boot: replaceEvent(quotetest.BootConfig(image), 10, quotetest.GPTEvent(append(quotetest.InstalledDisk(image), + tpmquote.Partition{Type: "0fc63daf-8483-4772-8e79-3d69d8477de4", Name: "data"})...)), + want: `pcr 5: the partition table holds a partition of type 0fc63daf-8483-4772-8e79-3d69d8477de4 ("data"), which the image does not define`, + same: true, + }, + } { + t.Run(name, func(t *testing.T) { + e := newEnvBooted(t, tc.boot) + e.policy.BootConfig = recorded + res := e.submit(e.request(e.ak, imds.StageInitrd)) + assert.False(t, res.Verified) + assert.Equal(t, tc.want, res.Message) + r, ok := e.v.Result(vmID, imds.StageInitrd) + require.True(t, ok) + assert.Equal(t, tc.same, slices.Equal(recorded, r.BootConfig), "the result names what the boot measured: %v", r.BootConfig) + }) + } + + t.Run("the reference boot judges the partition table too", func(t *testing.T) { + e := newEnvBooted(t, replaceEvent(quotetest.BootConfig(image), 10, quotetest.GPTEvent(quotetest.InstalledDisk("giantswarm-vm-base_0.0.9")...))) + e.newRecorder() + res := e.submit(e.request(e.ak, imds.StageInitrd)) + assert.False(t, res.Verified) + assert.Contains(t, res.Message, `pcr 5: a root partition is labelled "giantswarm-vm-base_0.0.9"`) + }) +} + +// replaceEvent is events with the one at i replaced by ev. +func replaceEvent(events []tpmquote.Event, i int, ev tpmquote.Event) []tpmquote.Event { + events[i] = ev + return events +} diff --git a/internal/tpmquote/efi.go b/internal/tpmquote/efi.go new file mode 100644 index 0000000..7f17e19 --- /dev/null +++ b/internal/tpmquote/efi.go @@ -0,0 +1,118 @@ +package tpmquote + +import ( + "encoding/binary" + "fmt" + "strings" + "unicode/utf16" + + "github.com/google/uuid" +) + +// Variable is a UEFI_VARIABLE_DATA, the data of an EV_EFI_VARIABLE_* event: +// the variable's vendor GUID, its name and the data measured. +type Variable struct { + GUID string + Name string + Data []byte +} + +// EFIGlobalVariable is the vendor GUID of BootOrder and the Boot#### +// options. +const EFIGlobalVariable = "8be4df61-93ca-11d2-aa0d-00e098032b8c" + +// ParseVariable decodes a UEFI_VARIABLE_DATA: VariableName (a GUID), +// UnicodeNameLength and VariableDataLength (64 bits each), the UTF-16 name +// without a terminator, then the data. +func ParseVariable(data []byte) (Variable, error) { + const header = 16 + 8 + 8 + if len(data) < header { + return Variable{}, fmt.Errorf("%w: a variable event of %d bytes", ErrEventLog, len(data)) + } + nameLen, dataLen := binary.LittleEndian.Uint64(data[16:]), binary.LittleEndian.Uint64(data[24:]) + rest := uint64(len(data)) - header // #nosec G115 -- a length is not negative + if nameLen > rest/2 || dataLen != rest-2*nameLen { + return Variable{}, fmt.Errorf("%w: a variable event of %d bytes names %d characters and %d bytes of data", ErrEventLog, len(data), nameLen, dataLen) + } + name := make([]uint16, nameLen) + for i := range name { + name[i] = binary.LittleEndian.Uint16(data[header+2*i:]) + } + return Variable{ + GUID: guid(data[:16]), + Name: strings.TrimRight(string(utf16.Decode(name)), "\x00"), + Data: data[header+2*nameLen:], + }, nil +} + +// GPT is the data of an EV_EFI_GPT_EVENT (UEFI_GPT_DATA): the boot disk's +// GPT header and its partitions, the entries whose type is not zero, in +// the order of the partition table. +type GPT struct { + DiskGUID string + Partitions []Partition +} + +// Partition is one GPT partition entry. +type Partition struct { + // Type and GUID are the partition type and the partition's own GUID, + // lowercase. + Type, GUID string + // FirstLBA and LastLBA bound the partition on the disk. + FirstLBA, LastLBA uint64 + // Attributes are the 64 attribute bits. + Attributes uint64 + // Name is the partition label. + Name string +} + +// gptSignature starts a GPT header. +var gptSignature = []byte("EFI PART") + +// ParseGPT decodes UEFI_GPT_DATA: the EFI_PARTITION_TABLE_HEADER (its +// HeaderSize bytes), NumberOfPartitions (64 bits) and that many entries of +// the header's SizeOfPartitionEntry. +func ParseGPT(data []byte) (GPT, error) { + const minHeader = 92 + if len(data) < minHeader || string(data[:8]) != string(gptSignature) { + return GPT{}, fmt.Errorf("%w: a gpt event without a gpt header", ErrEventLog) + } + headerSize := binary.LittleEndian.Uint32(data[12:]) + entrySize := binary.LittleEndian.Uint32(data[84:]) + if headerSize < minHeader || uint64(headerSize)+8 > uint64(len(data)) || entrySize < 128 { + return GPT{}, fmt.Errorf("%w: a gpt header of %d bytes with entries of %d bytes", ErrEventLog, headerSize, entrySize) + } + n := binary.LittleEndian.Uint64(data[headerSize:]) + entries := data[headerSize+8:] + if n > uint64(len(entries))/uint64(entrySize) || uint64(len(entries)) != n*uint64(entrySize) { + return GPT{}, fmt.Errorf("%w: a gpt event of %d bytes with %d partitions of %d bytes", ErrEventLog, len(data), n, entrySize) + } + g := GPT{DiskGUID: guid(data[56:72])} + for i := range n { + e := entries[i*uint64(entrySize):] + name := make([]uint16, 36) + for j := range name { + name[j] = binary.LittleEndian.Uint16(e[56+2*j:]) + } + g.Partitions = append(g.Partitions, Partition{ + Type: guid(e[0:16]), + GUID: guid(e[16:32]), + FirstLBA: binary.LittleEndian.Uint64(e[32:]), + LastLBA: binary.LittleEndian.Uint64(e[40:]), + Attributes: binary.LittleEndian.Uint64(e[48:]), + Name: strings.TrimRight(string(utf16.Decode(name)), "\x00"), + }) + } + return g, nil +} + +// guid formats an EFI GUID, whose first three fields are little-endian, as +// a lowercase string. +func guid(b []byte) string { + var u uuid.UUID + copy(u[:], b[:16]) + u[0], u[1], u[2], u[3] = u[3], u[2], u[1], u[0] + u[4], u[5] = u[5], u[4] + u[6], u[7] = u[7], u[6] + return u.String() +} diff --git a/internal/tpmquote/efi_test.go b/internal/tpmquote/efi_test.go new file mode 100644 index 0000000..394a803 --- /dev/null +++ b/internal/tpmquote/efi_test.go @@ -0,0 +1,70 @@ +package tpmquote_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/giantswarm/vm-manager/internal/tpmquote" + "github.com/giantswarm/vm-manager/internal/tpmquote/quotetest" +) + +// TestParseEFIEventsOVMF decodes the boot variables and the partition table +// OVMF measured on a node's first installed boot. +func TestParseEFIEventsOVMF(t *testing.T) { + events, err := tpmquote.ParseEventLog(readLog(t, "firstboot")) + require.NoError(t, err) + var names []string + var gpt tpmquote.GPT + for _, ev := range events { + switch ev.Type { + case tpmquote.EventEFIVariableBoot: + v, err := tpmquote.ParseVariable(ev.Data) + require.NoError(t, err) + assert.Equal(t, tpmquote.EFIGlobalVariable, v.GUID) + names = append(names, v.Name) + case tpmquote.EventEFIGPT: + gpt, err = tpmquote.ParseGPT(ev.Data) + require.NoError(t, err) + } + } + assert.Equal(t, []string{"BootOrder", "Boot0002", "Boot0004", "Boot0000", "Boot0001", "Boot0005"}, names) + assert.Equal(t, "d30bbac5-6b03-4550-a5a6-5b87a72ea5b6", gpt.DiskGUID) + require.Len(t, gpt.Partitions, 5) + assert.Equal(t, tpmquote.Partition{Type: quotetest.TypeESP, GUID: "5ceac8ff-2490-4c72-8c4f-6c74a296584c", FirstLBA: 2048, LastLBA: 1050623, Name: "esp"}, gpt.Partitions[0]) + assert.Equal(t, tpmquote.Partition{Type: quotetest.TypeVar, GUID: "64fbe0b1-baf2-4b7c-9aa4-310cedcf37c1", FirstLBA: 9701440, LastLBA: 41942999, Attributes: quotetest.GrowFS, Name: "var"}, gpt.Partitions[4]) +} + +func TestParseEFIEventsRoundTrip(t *testing.T) { + v, err := tpmquote.ParseVariable(quotetest.Variable(tpmquote.EFIGlobalVariable, "Boot0007", []byte{1, 2, 3})) + require.NoError(t, err) + assert.Equal(t, tpmquote.Variable{GUID: tpmquote.EFIGlobalVariable, Name: "Boot0007", Data: []byte{1, 2, 3}}, v) + + disk := quotetest.InstalledDisk("image_1") + gpt, err := tpmquote.ParseGPT(quotetest.EncodeGPT(disk...)) + require.NoError(t, err) + assert.Equal(t, disk, gpt.Partitions) +} + +func TestParseEFIEventsMalformed(t *testing.T) { + variable := quotetest.Variable(tpmquote.EFIGlobalVariable, "BootOrder", []byte{1, 0}) + for name, data := range map[string][]byte{ + "short": variable[:20], + "data truncated": variable[:len(variable)-1], + "trailing bytes": append(append([]byte(nil), variable...), 0), + } { + _, err := tpmquote.ParseVariable(data) + assert.ErrorIs(t, err, tpmquote.ErrEventLog, name) + } + gpt := quotetest.EncodeGPT(quotetest.InstalledDisk("image_1")...) + for name, data := range map[string][]byte{ + "short": gpt[:40], + "not a gpt header": append([]byte("NOT PART"), gpt[8:]...), + "entry truncated": gpt[:len(gpt)-1], + "trailing bytes": append(append([]byte(nil), gpt...), 0), + } { + _, err := tpmquote.ParseGPT(data) + assert.ErrorIs(t, err, tpmquote.ErrEventLog, name) + } +} diff --git a/internal/tpmquote/eventlog.go b/internal/tpmquote/eventlog.go index d1208d4..0e74ccc 100644 --- a/internal/tpmquote/eventlog.go +++ b/internal/tpmquote/eventlog.go @@ -14,12 +14,37 @@ import ( const ( // EventNoAction is EV_NO_ACTION: logged, never extended into a PCR. EventNoAction uint32 = 0x03 + // EventSeparator is EV_SEPARATOR: the end of the pre-OS measurements of + // a PCR, the digest of four zero bytes (four 0xff bytes after an error). + EventSeparator uint32 = 0x04 // EventTag is EV_EVENT_TAG: a TCG_PCClientTaggedEvent, the 32-bit tag, // the size and the data; systemd's newer measurements use it. EventTag uint32 = 0x06 + // EventPlatformConfigFlags is EV_PLATFORM_CONFIG_FLAGS; EDK2 logs the + // ACPI tables QEMU hands it as "ACPI DATA". + EventPlatformConfigFlags uint32 = 0x0a // EventIPL is EV_IPL: data of the loaded OS, which systemd-boot and // systemd-stub log with a UTF-16 description. EventIPL uint32 = 0x0d + // EventEFIVariableBoot is EV_EFI_VARIABLE_BOOT: a UEFI_VARIABLE_DATA + // (Variable) of BootOrder or a Boot#### option, its digest that of the + // variable's data. + EventEFIVariableBoot uint32 = 0x80000002 + // EventEFIGPT is EV_EFI_GPT_EVENT: the partition table of the boot disk + // (GPT), its digest that of the event data. + EventEFIGPT uint32 = 0x80000006 + // EventEFIAction is EV_EFI_ACTION: an ASCII string, its digest that of + // the string. + EventEFIAction uint32 = 0x80000007 + // EventEFIHandoffTables is EV_EFI_HANDOFF_TABLES: the pointer to the + // SMBIOS tables, its digest that of the tables. + EventEFIHandoffTables uint32 = 0x80000009 + // EventEFIHandoffTables2 is EV_EFI_HANDOFF_TABLES2, the same with a + // description. + EventEFIHandoffTables2 uint32 = 0x8000000b + // EventEFIVariableBoot2 is EV_EFI_VARIABLE_BOOT2: like + // EventEFIVariableBoot, its digest that of the whole event data. + EventEFIVariableBoot2 uint32 = 0x8000000c ) // ErrEventLog is a firmware event log that does not parse. diff --git a/internal/tpmquote/quotetest/bootconfig.go b/internal/tpmquote/quotetest/bootconfig.go new file mode 100644 index 0000000..1e2b4ed --- /dev/null +++ b/internal/tpmquote/quotetest/bootconfig.go @@ -0,0 +1,183 @@ +package quotetest + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "unicode/utf16" + + "github.com/google/go-tpm/tpm2" + "github.com/google/uuid" + + "github.com/giantswarm/vm-manager/internal/tpmquote" +) + +// Tags of systemd's EV_EVENT_TAG events in PCRs 1 and 5 +// (src/fundamental/tpm2-pcr.h). +const ( + TagLoaderConf uint32 = 0xf5bc582a + TagSMBIOSType1 uint32 = 0xd5cb7cbc + TagSMBIOSType11 uint32 = 0xc0b3bd23 +) + +// Partition types and attribute bits of the disk vm-manager installs. +const ( + TypeESP = "c12a7328-f81f-11d2-ba4b-00a0c93ec93b" + TypeRoot = "4f68bce3-e8cd-4db1-96e7-fbcaf984b709" + TypeRootVerity = "2c7357ed-ebd2-46d9-aec1-23d437ec2bf5" + TypeRootVeritySig = "41092b05-9fc8-4523-994f-2def0408b176" + TypeVar = "4d21b016-b534-45c2-a9fb-5c16e091fd2d" + ReadOnly = uint64(1) << 60 + GrowFS = uint64(1) << 59 +) + +// event is an event of pcr whose sha256 digest is that of content. +func event(pcr int, typ uint32, data, content []byte) tpmquote.Event { + sum := sha256.Sum256(content) + return tpmquote.Event{PCR: pcr, Type: typ, Digests: map[tpm2.TPMAlgID][]byte{tpm2.TPMAlgSHA256: sum[:]}, Data: data} +} + +// Separator is the EV_SEPARATOR of pcr. +func Separator(pcr int) tpmquote.Event { + return event(pcr, tpmquote.EventSeparator, []byte{0, 0, 0, 0}, []byte{0, 0, 0, 0}) +} + +// ACPI is an EV_PLATFORM_CONFIG_FLAGS event of ACPI tables EDK2 logs into +// PCR 1, its digest that of tables. +func ACPI(tables string) tpmquote.Event { + return event(1, tpmquote.EventPlatformConfigFlags, []byte("ACPI DATA"), []byte(tables)) +} + +// SMBIOS is the EV_EFI_HANDOFF_TABLES event of the SMBIOS tables, its +// digest that of tables. +func SMBIOS(tables string) tpmquote.Event { + return event(1, tpmquote.EventEFIHandoffTables, make([]byte, 32), []byte(tables)) +} + +// BootVariable is an EV_EFI_VARIABLE_BOOT event of the EFI global variable +// name holding data, its digest that of data. +func BootVariable(name string, data []byte) tpmquote.Event { + return event(1, tpmquote.EventEFIVariableBoot, Variable(tpmquote.EFIGlobalVariable, name, data), data) +} + +// Variable encodes a UEFI_VARIABLE_DATA. +func Variable(guid, name string, data []byte) []byte { + var b bytes.Buffer + b.Write(efiGUID(guid)) + units := utf16.Encode([]rune(name)) + le(&b, uint64(len(units))) + le(&b, uint64(len(data))) + for _, u := range units { + le(&b, u) + } + b.Write(data) + return b.Bytes() +} + +// Tagged is an EV_EVENT_TAG event of pcr as systemd logs one: the tag, the +// size of the description and the UTF-16 description; its digest that of +// content. +func Tagged(pcr int, tag uint32, description string, content []byte) tpmquote.Event { + desc := UTF16(description) + var b bytes.Buffer + le(&b, tag) + le(&b, uint32(len(desc))) // #nosec G115 -- short descriptions + b.Write(desc) + return event(pcr, tpmquote.EventTag, b.Bytes(), content) +} + +// Action is an EV_EFI_ACTION event of PCR 5. +func Action(s string) tpmquote.Event { + return event(5, tpmquote.EventEFIAction, []byte(s), []byte(s)) +} + +// GPTEvent is the EV_EFI_GPT_EVENT of a disk with the given partitions. +func GPTEvent(partitions ...tpmquote.Partition) tpmquote.Event { + data := EncodeGPT(partitions...) + return event(5, tpmquote.EventEFIGPT, data, data) +} + +// EncodeGPT writes a UEFI_GPT_DATA: a 92-byte header, the number of +// partitions and one 128-byte entry each. +func EncodeGPT(partitions ...tpmquote.Partition) []byte { + header := make([]byte, 92) + copy(header, "EFI PART") + binary.LittleEndian.PutUint32(header[8:], 0x00010000) + binary.LittleEndian.PutUint32(header[12:], 92) + copy(header[56:], efiGUID("d30bbac5-6b03-4550-a5a6-5b87a72ea5b6")) + binary.LittleEndian.PutUint32(header[80:], 128) + binary.LittleEndian.PutUint32(header[84:], 128) + var b bytes.Buffer + b.Write(header) + le(&b, uint64(len(partitions))) + for _, p := range partitions { + entry := make([]byte, 128) + copy(entry[0:], efiGUID(p.Type)) + copy(entry[16:], efiGUID(p.GUID)) + binary.LittleEndian.PutUint64(entry[32:], p.FirstLBA) + binary.LittleEndian.PutUint64(entry[40:], p.LastLBA) + binary.LittleEndian.PutUint64(entry[48:], p.Attributes) + for i, u := range utf16.Encode([]rune(p.Name)) { + binary.LittleEndian.PutUint16(entry[56+2*i:], u) + } + b.Write(entry) + } + return b.Bytes() +} + +// InstalledDisk is the partition table of a disk vm-manager installed +// image (_) on: the ESP, the image's slot A, the empty slot B +// and var. +func InstalledDisk(image string) []tpmquote.Partition { + parts := []tpmquote.Partition{ + {Type: TypeESP, Name: "esp"}, + {Type: TypeRoot, Name: image, Attributes: ReadOnly}, + {Type: TypeRootVerity, Name: image + "_verity", Attributes: ReadOnly}, + {Type: TypeRootVeritySig, Name: image + "_verity_sig", Attributes: ReadOnly}, + {Type: TypeRoot, Name: "_empty", Attributes: GrowFS}, + {Type: TypeRootVerity, Name: "_empty", Attributes: ReadOnly}, + {Type: TypeRootVeritySig, Name: "_empty", Attributes: ReadOnly}, + {Type: TypeVar, Name: "var", Attributes: GrowFS}, + } + for i := range parts { + parts[i].GUID = uuid.NewSHA1(uuid.NameSpaceOID, []byte(image+parts[i].Name+string(rune('a'+i)))).String() + parts[i].FirstLBA, parts[i].LastLBA = uint64(2048*(i+1)), uint64(2048*(i+2)-1) // #nosec G115 -- small test indexes + } + return parts +} + +// LoaderConf is the loader.conf bootctl installs. +const LoaderConf = "#timeout 3\n#console-mode keep\n" + +// BootConfig is what EDK2, systemd-boot and systemd-stub log into PCRs 1 +// and 5 when an installed VM of image boots: the ACPI and SMBIOS tables, +// BootOrder and two boot options, the SMBIOS structures, the separators, +// the disk's partition table, loader.conf and ExitBootServices. +func BootConfig(image string) []tpmquote.Event { + return []tpmquote.Event{ + ACPI("dsdt"), ACPI("facp"), + SMBIOS("smbios"), + BootVariable("BootOrder", []byte{1, 0, 0, 0}), + BootVariable("Boot0001", []byte("Linux Boot Manager")), + BootVariable("Boot0000", []byte("UiApp")), + Separator(1), + Tagged(1, TagSMBIOSType1, "smbios:type1", []byte("type1")), + Tagged(1, TagSMBIOSType11, "smbios:type11", []byte("type11")), + Separator(5), + GPTEvent(InstalledDisk(image)...), + Tagged(5, TagLoaderConf, "loader.conf", []byte(LoaderConf)), + Action("Exit Boot Services Invocation"), + Action("Exit Boot Services Returned with Success"), + } +} + +// efiGUID encodes a GUID string as EFI stores it: the first three fields +// little-endian; an empty string is the zero GUID. +func efiGUID(s string) []byte { + if s == "" { + return make([]byte, 16) + } + u := uuid.MustParse(s) + b := u[:] + return []byte{b[3], b[2], b[1], b[0], b[5], b[4], b[7], b[6], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]} +} diff --git a/internal/vm/attest_test.go b/internal/vm/attest_test.go index c0a2859..c2ef23e 100644 --- a/internal/vm/attest_test.go +++ b/internal/vm/attest_test.go @@ -295,3 +295,55 @@ func TestEndorsementKeyReadBeforeTheGuest(t *testing.T) { assert.Equal(t, 2, h.tpm.EKReads(v.Paths.TPMState)) }) } + +// TestBootConfigRecorded: the boot configuration of a VM's first verified +// initrd quote is kept in its record, survives a restart and is the policy +// every later quote is judged against; a later boot's does not replace it, +// nor does a quote that failed. +func TestBootConfigRecorded(t *testing.T) { + h := newHarness(t) + att := &detailedAttestor{results: map[string]attest.Result{}} + h.attestor = att + h.restart() + v := h.create("bootconfig") + h.install(v.ID) + first := []string{"BootOrder=00", "Boot0001=01", "loader.conf=02"} + + att.Reject = "golden mismatch" + att.results[v.ID+"/initrd"] = attest.Result{BootConfig: []string{"BootOrder=ff"}} + h.quote(v.ID, imds.StageInitrd) + v = h.waitState(v.ID, vm.StateFailed) + assert.Empty(t, v.BootConfig, "a rejected quote records nothing") + + att.Reject = "" + _, err := h.svc.Start(h.ctx, v.ID) + require.NoError(t, err) + att.results[v.ID+"/initrd"] = attest.Result{Verified: true, BootConfig: first} + att.results[v.ID+"/ready"] = attest.Result{Verified: true, BootConfig: first} + v = h.ready(v.ID, v.CID) + assert.Equal(t, first, v.BootConfig) + a, err := h.svc.Attestation(v.ID) + require.NoError(t, err) + assert.Equal(t, first, a.Initrd.BootConfig, "get_vm_attestation shows what each quote measured") + + att.results[v.ID+"/initrd"] = attest.Result{Verified: true, BootConfig: []string{"BootOrder=ff"}} + _, err = h.svc.Stop(h.ctx, v.ID) + require.NoError(t, err) + h.waitState(v.ID, vm.StateStopped) + _, err = h.svc.Start(h.ctx, v.ID) + require.NoError(t, err) + h.waitState(v.ID, vm.StateBooting) + h.quote(v.ID, imds.StageInitrd) + got, err := h.svc.Get(v.ID) + require.NoError(t, err) + assert.Equal(t, first, got.BootConfig, "a later boot does not replace the first verified boot's") + + h.restart() + got, err = h.svc.Get(v.ID) + require.NoError(t, err) + assert.Equal(t, first, got.BootConfig, "kept in the record") + h.restartWithPolicy(`{"image_id":"giantswarm-vm-base","image_version":"0.1.0","pcr11":{"enter-initrd":"` + strings.Repeat("a", 64) + `","enter-initrd:leave-initrd:sysinit:ready":"` + strings.Repeat("b", 64) + `"},"secure_boot":true}`) + p, err := h.svc.PolicyFor(h.ctx, v.ID) + require.NoError(t, err) + assert.Equal(t, first, p.BootConfig, "what pcrs 1 and 5 must measure") +} diff --git a/internal/vm/imds.go b/internal/vm/imds.go index e9d64d4..82da1bb 100644 --- a/internal/vm/imds.go +++ b/internal/vm/imds.go @@ -8,6 +8,7 @@ import ( "net/http" "net/netip" "os" + "slices" "time" "github.com/giantswarm/vm-manager/internal/attest" @@ -96,9 +97,11 @@ func (s *Service) RejectReport(ctx context.Context, vmID, reason string) { // PolicyFor implements attest.PolicyProvider: the policy of the image the // VM was created from, with the VM's Kubernetes version selecting the PCR // 13 entry, the digests of the layer certificates the IMDS serves it as -// what PCR 15 must measure and the command line its current boot passed to -// systemd-stub as what PCR 12 must. Errors wrap attest.ErrNoPolicy when the image or its policy is -// missing or invalid, apierr.ErrNotFound for an unknown VM. +// what PCR 15 must measure, the command line its current boot passed to +// systemd-stub as what PCR 12 must and the boot configuration of its first +// verified boot as what PCRs 1 and 5 must. Errors wrap attest.ErrNoPolicy +// when the image or its policy is missing or invalid, apierr.ErrNotFound +// for an unknown VM. func (s *Service) PolicyFor(_ context.Context, vmID string) (attest.Policy, error) { v, err := s.Get(vmID) if err != nil { @@ -118,6 +121,7 @@ func (s *Service) PolicyFor(_ context.Context, vmID string) (attest.Policy, erro p.KubernetesVersion = v.KubernetesVersion p.CNIVersion = v.CNIVersion p.KernelCmdlineExtra = v.KernelCmdlineExtra + p.BootConfig = v.BootConfig if p.LayerCertificates, err = layercert.Digests(v.LayerCertificates); err != nil { return attest.Policy{}, fmt.Errorf("%w: vm %s: %v", attest.ErrNoPolicy, vmID, err) } @@ -191,7 +195,7 @@ func (a recordingAttestor) SubmitQuote(ctx context.Context, vmID string, req imd q := &Quote{Verified: res.Verified, Message: res.Message, At: a.s.clock.Now()} if src, ok := a.inner.(ResultSource); ok { if r, ok := src.Result(vmID, req.Stage); ok { - q.AKFingerprint, q.PCRs, q.LayerCertificates = r.AKFingerprint, r.PCRs, r.LayerCertificates + q.AKFingerprint, q.PCRs, q.LayerCertificates, q.BootConfig = r.AKFingerprint, r.PCRs, r.LayerCertificates, r.BootConfig } } a.s.recordQuote(vmID, req.Stage, q) @@ -219,8 +223,10 @@ func (s *Service) onNonce(vmID string) { // user-data on a verified initrd quote (imds.ReleasesUserData), consumes it // on a verified ready-stage quote of a boot it was released to (that boot is // past Ignition) and refuses the boot on a rejected quote of any stage: its -// QEMU is killed and the VM fails with the verdict (refuseLocked). A quote -// of a boot that is gone or already refused is dropped. +// QEMU is killed and the VM fails with the verdict (refuseLocked). The boot +// configuration of the VM's first verified initrd quote is kept +// (VM.BootConfig). A quote of a boot that is gone or already refused is +// dropped. func (s *Service) recordQuote(vmID string, stage imds.Stage, q *Quote) { s.mu.Lock() defer s.mu.Unlock() @@ -243,6 +249,10 @@ func (s *Service) recordQuote(vmID string, stage imds.Stage, q *Quote) { if imds.ReleasesUserData(stage, q.Verified) { e.rec.Attestation.UserDataReleased = true } + if stage == imds.StageInitrd && q.Verified && len(e.rec.BootConfig) == 0 && len(q.BootConfig) > 0 { + e.rec.BootConfig = slices.Clone(q.BootConfig) + s.log.Info("boot configuration recorded", "id", vmID, "entries", len(q.BootConfig)) + } if stage == imds.StageReady && q.Verified && e.rec.Attestation.UserDataReleased { s.consumeUserDataLocked(e) } diff --git a/internal/vm/types.go b/internal/vm/types.go index cf5324c..779a37c 100644 --- a/internal/vm/types.go +++ b/internal/vm/types.go @@ -132,6 +132,10 @@ type Quote struct { // LayerCertificates are the sha256 digests of the layer certificates // the ready quote measured into PCR 15, in order. LayerCertificates []string `json:"layerCertificates,omitempty"` + // BootConfig is the boot configuration the quote's PCRs 1 and 5 + // measured: the firmware's boot variables and systemd-boot's + // loader.conf, each as "=". + BootConfig []string `json:"bootConfig,omitempty"` } // Attestation summarizes the current boot's attestation; it is reset on every @@ -224,6 +228,13 @@ type VM struct { // attestation key"). A record from before has none until its next // start reads it, before that start's QEMU. EndorsementKey []byte `json:"endorsementKey,omitempty"` + // BootConfig is the boot configuration the VM's first verified boot + // measured into PCRs 1 and 5 (Quote.BootConfig), kept from its first + // verified initrd quote on: every later boot must measure it again, so + // a boot variable or loader.conf changed in the guest fails the next + // boot (attest.Policy.BootConfig). A record from before has none until + // its next verified boot. + BootConfig []string `json:"bootConfig,omitempty"` // SSHPublicKey is vm-manager's per-VM key, the first root authorized key. SSHPublicKey string `json:"sshPublicKey"` Attestation Attestation `json:"attestation"` @@ -246,6 +257,7 @@ type VM struct { func (v *VM) clone() *VM { c := *v c.LayerCertificates = append([]string(nil), v.LayerCertificates...) + c.BootConfig = append([]string(nil), v.BootConfig...) if v.Metadata != nil { c.Metadata = make(map[string]string, len(v.Metadata)) for k, val := range v.Metadata { From 9b7a182d2541dcd9d2a3ed07f400ba35f9765021 Mon Sep 17 00:00:00 2001 From: Timo Derstappen Date: Tue, 1 Dec 2026 04:40:37 +0100 Subject: [PATCH 2/5] fix(attest): ExitBootServices retried after a failure is part of a boot vm-manager starts --- internal/attest/bootconfig.go | 6 ++++-- internal/attest/bootconfig_test.go | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/internal/attest/bootconfig.go b/internal/attest/bootconfig.go index 8c92b9c..3171358 100644 --- a/internal/attest/bootconfig.go +++ b/internal/attest/bootconfig.go @@ -44,8 +44,10 @@ const ( const LoaderConf = "loader.conf" // exitBootServices are the EV_EFI_ACTION strings the firmware logs into PCR -// 5 around ExitBootServices when it succeeds. -var exitBootServices = []string{"Exit Boot Services Invocation", "Exit Boot Services Returned with Success"} +// 5 around each ExitBootServices call. The kernel's EFI stub calls it again +// when the first call fails on a memory map that changed in between, which +// logs a failure before the success. +var exitBootServices = []string{"Exit Boot Services Invocation", "Exit Boot Services Returned with Failure", "Exit Boot Services Returned with Success"} // bootVariable is the name of a boot variable the firmware measures into // PCR 1. diff --git a/internal/attest/bootconfig_test.go b/internal/attest/bootconfig_test.go index b59a129..588d4be 100644 --- a/internal/attest/bootconfig_test.go +++ b/internal/attest/bootconfig_test.go @@ -112,6 +112,11 @@ func TestReplayBootConfigBindsEvents(t *testing.T) { bc, err := replay(quotetest.BootConfig("giantswarm-vm-base_0.1.0")...) require.NoError(t, err) require.NoError(t, bc.check(testImage)) + retried, err := replay(append(quotetest.BootConfig("giantswarm-vm-base_0.1.0"), + quotetest.Action("Exit Boot Services Invocation"), quotetest.Action("Exit Boot Services Returned with Failure"), + quotetest.Action("Exit Boot Services Invocation"), quotetest.Action("Exit Boot Services Returned with Success"))...) + require.NoError(t, err, "the kernel's EFI stub calls ExitBootServices again after a failure") + assert.Equal(t, bc.entries, retried.entries) loaderConf := sha256.Sum256([]byte(quotetest.LoaderConf)) assert.Equal(t, LoaderConf+"="+hex.EncodeToString(loaderConf[:]), bc.entries[len(bc.entries)-1]) @@ -138,7 +143,7 @@ func TestReplayBootConfigBindsEvents(t *testing.T) { "a second partition table": {with(-1, quotetest.GPTEvent()), "pcr 5: the firmware event log has 2 partition tables, a boot from the vm's disk one"}, "no partition table": {with(10, quotetest.Action("Exit Boot Services Invocation")), "pcr 5: the firmware event log has 0 partition tables, a boot from the vm's disk one"}, "another pcr 5 tag": {with(11, quotetest.Tagged(5, quotetest.TagSMBIOSType1, "smbios:type1", nil)), "pcr 5: firmware event 12: a tagged event 0xd5cb7cbc, which no boot vm-manager starts measures into pcr 5"}, - "a failed ExitBootServices": {with(13, quotetest.Action("Exit Boot Services Returned with Failure")), `pcr 5: firmware event 14: the action "Exit Boot Services Returned with Failure", which a boot vm-manager starts does not measure into pcr 5`}, + "another action": {with(13, quotetest.Action("Calling EFI Application from Boot Option")), `pcr 5: firmware event 14: the action "Calling EFI Application from Boot Option", which a boot vm-manager starts does not measure into pcr 5`}, } { t.Run(name, func(t *testing.T) { _, err := replay(tc.events...) From f86ba637468bb99f7c807b2722207254a654b420 Mon Sep 17 00:00:00 2001 From: Timo Derstappen Date: Tue, 1 Dec 2026 04:43:35 +0100 Subject: [PATCH 3/5] test(e2e): TestBootConfigAttestation names the option among the changes and retypes the slot without re-reading the disk in use --- e2e/boot_config_attestation_test.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/e2e/boot_config_attestation_test.go b/e2e/boot_config_attestation_test.go index 5980b7f..cf5cda5 100644 --- a/e2e/boot_config_attestation_test.go +++ b/e2e/boot_config_attestation_test.go @@ -89,8 +89,9 @@ func TestBootConfigAttestation(t *testing.T) { assert.True(t, deleted.Deleted) } // refused reboots the VM and requires the next boot refused at its - // initrd quote with a verdict that starts with prefix. - refused := func(t *testing.T, v vm.VM, prefix string) { + // initrd quote with a verdict that starts with prefix and contains + // every part. + refused := func(t *testing.T, v vm.VM, prefix string, parts ...string) { t.Helper() require.NotNil(t, v.BootedAt) before := *v.BootedAt @@ -99,6 +100,9 @@ func TestBootConfigAttestation(t *testing.T) { require.NotNil(t, v.BootedAt) assert.True(t, v.BootedAt.After(before), "the refused boot is the one after the change") assert.True(t, strings.HasPrefix(v.LastError, "initrd attestation rejected: "+prefix), "get_vm names the rejection: %q", v.LastError) + for _, p := range parts { + assert.Contains(t, v.LastError, p) + } att := getAttestation(ctx, t, m, v.ID) require.NotNil(t, att.Initrd) assert.False(t, att.Initrd.Verified) @@ -145,7 +149,8 @@ func TestBootConfigAttestation(t *testing.T) { t.Logf("as root: %s", out) option, _, _ := strings.Cut(out, "\n") require.True(t, strings.HasPrefix(option, "Boot"), "the option BootOrder starts with: %q", out) - refused(t, v, bootConfigChanged+option+" changed") + // The firmware may have written BootOrder again too. + refused(t, v, bootConfigChanged, option+" changed") }) t.Run("a retyped partition refuses the next boot", func(t *testing.T) { @@ -153,7 +158,7 @@ func TestBootConfigAttestation(t *testing.T) { t.Cleanup(func() { remove(t, v.ID) }) out := g.sh(ctx, `p=$(findmnt -no SOURCE /boot) && d=${p%%[0-9]*} && `+ `slot=$(sfdisk -d "$d" | grep 'name="_empty"' | grep -i 'type=4F68BCE3' | cut -d' ' -f1) && `+ - `sfdisk --part-type "$d" "${slot#$d}" `+linuxGeneric+` && sync && sfdisk -d "$d" | grep "$slot"`) + `sfdisk --no-reread --no-tell-kernel --part-type "$d" "${slot#$d}" `+linuxGeneric+` && sync && sfdisk -d "$d" | grep "$slot"`) t.Logf("as root: %s", out) refused(t, v, `pcr 5: the partition table holds a partition of type `+strings.ToLower(linuxGeneric)+` ("_empty"), which the image does not define`) }) From ec8fcaf4b7670904246df6d580aac23c5a645eee Mon Sep 17 00:00:00 2001 From: Timo Derstappen Date: Tue, 1 Dec 2026 05:02:52 +0100 Subject: [PATCH 4/5] test(attest): TestVerifierBootConfig derives the recorded configuration from the boot's events, so it skips cleanly without the simulator --- internal/attest/verifier_test.go | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/internal/attest/verifier_test.go b/internal/attest/verifier_test.go index 0c27c24..91fbfa9 100644 --- a/internal/attest/verifier_test.go +++ b/internal/attest/verifier_test.go @@ -901,7 +901,26 @@ func nilIfEmpty(s []string) []string { // or a partition table the image's disk does not have, is rejected. func TestVerifierBootConfig(t *testing.T) { const image = "giantswarm-vm-base_0.1.0" + // What the env's boot measured of its configuration: the boot + // variables and loader.conf, each with its digest. var recorded []string + for _, ev := range quotetest.BootConfig(image) { + name := "" + switch ev.Type { + case tpmquote.EventEFIVariableBoot: + v, err := tpmquote.ParseVariable(ev.Data) + require.NoError(t, err) + name = v.Name + case tpmquote.EventTag: + if ev.PCR == attest.PCRBootLoaderConfig { + name = attest.LoaderConf + } + } + if name != "" { + recorded = append(recorded, name+"="+hex.EncodeToString(ev.Digests[tpm2.TPMAlgSHA256])) + } + } + require.Len(t, recorded, 4) t.Run("the first verified boot", func(t *testing.T) { e := newEnv(t) res := e.submit(e.request(e.ak, imds.StageInitrd)) @@ -909,17 +928,14 @@ func TestVerifierBootConfig(t *testing.T) { assert.Contains(t, res.Message, ", pcr 1 and 5 boot configuration recorded, gpt of 8 partitions") r, ok := e.v.Result(vmID, imds.StageInitrd) require.True(t, ok) - require.Len(t, r.BootConfig, 4) + assert.Equal(t, recorded, r.BootConfig, "the boot variables and loader.conf, in log order") assert.True(t, strings.HasPrefix(r.BootConfig[0], "BootOrder="), r.BootConfig[0]) - assert.True(t, strings.HasPrefix(r.BootConfig[3], attest.LoaderConf+"="), r.BootConfig[3]) - recorded = r.BootConfig e.policy.BootConfig = recorded res = e.submit(e.request(e.ak, imds.StageInitrd)) require.True(t, res.Verified, res.Message) assert.Contains(t, res.Message, ", pcr 1 and 5 boot configuration as on the first verified boot, gpt of 8 partitions") }) - require.NotEmpty(t, recorded) for name, tc := range map[string]struct { boot []tpmquote.Event From f814d55d468ad3ccbff920db9dec500b571579b6 Mon Sep 17 00:00:00 2001 From: Timo Derstappen Date: Tue, 1 Dec 2026 06:11:18 +0100 Subject: [PATCH 5/5] test(e2e): TestBootConfigAttestation finds the disk by its var partition, /boot being an automount --- e2e/boot_config_attestation_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/e2e/boot_config_attestation_test.go b/e2e/boot_config_attestation_test.go index cf5cda5..2fffeaf 100644 --- a/e2e/boot_config_attestation_test.go +++ b/e2e/boot_config_attestation_test.go @@ -156,7 +156,8 @@ func TestBootConfigAttestation(t *testing.T) { t.Run("a retyped partition refuses the next boot", func(t *testing.T) { v, g := create(t, bootConfigVM+"-gpt") t.Cleanup(func() { remove(t, v.ID) }) - out := g.sh(ctx, `p=$(findmnt -no SOURCE /boot) && d=${p%%[0-9]*} && `+ + // The disk is the one holding var (/boot is an automount). + out := g.sh(ctx, `d=/dev/$(lsblk -no PKNAME "$(readlink -f /dev/disk/by-partlabel/var)") && `+ `slot=$(sfdisk -d "$d" | grep 'name="_empty"' | grep -i 'type=4F68BCE3' | cut -d' ' -f1) && `+ `sfdisk --no-reread --no-tell-kernel --part-type "$d" "${slot#$d}" `+linuxGeneric+` && sync && sfdisk -d "$d" | grep "$slot"`) t.Logf("as root: %s", out)