diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d1e4998..d290d09 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -142,15 +142,61 @@ jobs: max-layers: "128" source-date-epoch: auto + # Generate the unlock fixtures from this build's own signing artifacts. + # The PCR signing key and the measured kernel/initrd/cmdline are + # build-specific, so release assets from another build cannot prove + # that this image's signed PCR 11 policy unseals MjolnirState. + - name: Generate Secure Boot fixtures + run: | + set -euo pipefail + sudo apt-get install -y -qq python3-cryptography ovmf binutils unzip + # Earlier sudo podman steps leave crun's cache under XDG_RUNTIME_DIR + # owned by root, which breaks the unprivileged `just bst` below. + RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" + sudo chown -R "$(id -u):$(id -g)" "$RUNTIME_DIR/crun" 2>/dev/null || true + just fixtures + + - name: Provision Secure Boot fixtures + env: + FIXTURE_DIR: ${{ github.workspace }}/fixtures-out + run: | + set -euo pipefail + for fixture in OVMF_VARS.enrolled.fd uki-signed.efi uki-unknown.efi; do + test -s "$FIXTURE_DIR/$fixture" + done + (cd "$FIXTURE_DIR" && sha256sum -c SHA256SUMS) + + - name: Upload Secure Boot fixtures + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: mjolnir-secureboot-fixtures + path: fixtures-out/ + retention-days: 90 + # The install checks that bootc accepts the signed digest, and the OVMF # boot checks that the shell-free initramfs actually mounts the composefs # root and reaches user space. A static content check cannot prove that. - name: Install and boot test (OVMF) + env: + FIXTURE_DIR: ${{ github.workspace }}/fixtures-out run: | sudo apt-get update -qq - sudo apt-get install -y -qq qemu-system-x86 ovmf binutils + sudo apt-get install -y -qq qemu-system-x86 ovmf binutils swtpm swtpm-tools systemd-repart just boot-test + - name: Upload Secure Boot serial logs + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: mjolnir-secureboot-serial-logs + path: | + ${{ runner.temp }}/mjolnir-boot-test/secureboot-signed.log + ${{ runner.temp }}/mjolnir-boot-test/secureboot-unknown.log + ${{ runner.temp }}/mjolnir-boot-test/secureboot-*/enroll.log + ${{ runner.temp }}/mjolnir-boot-test/secureboot-*/tpm/swtpm.log + if-no-files-found: warn + retention-days: 90 + - name: Export image for scanning run: sudo podman save --format docker-archive -o /tmp/scan-image.tar localhost/mjolnir:latest @@ -264,27 +310,6 @@ jobs: fi just cache-push - # The unlock fixtures used by Gram's OVMF + swtpm harness. They come - # from the same signing-only artifacts as this image, so uki-signed.efi - # carries the PCR policy that unseals the state of the image built here. - # Generate on every PR so the image gate exercises this code; only the - # publication job below is restricted to testing and manual dispatch. - - name: Generate Secure Boot fixtures - run: | - set -euo pipefail - sudo apt-get install -y -qq python3-cryptography ovmf binutils unzip - # Earlier sudo podman steps leave crun's cache under XDG_RUNTIME_DIR - # owned by root, which breaks the unprivileged `just bst` below. - RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" - sudo chown -R "$(id -u):$(id -g)" "$RUNTIME_DIR/crun" 2>/dev/null || true - just fixtures - - - name: Upload Secure Boot fixtures - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: mjolnir-secureboot-fixtures - path: fixtures-out/ - retention-days: 90 # Publishes the three public fixtures to a stable release tag so Gram's # curl-based provisioning needs no URL changes. Kept separate from `image` diff --git a/Justfile b/Justfile index c42c441..c33312b 100644 --- a/Justfile +++ b/Justfile @@ -89,6 +89,7 @@ test: python3 tests/test_update_pins.py python3 tests/test_pins.py python3 tests/test_secureboot_fixtures.py + python3 tests/test_tpm_support.py python3 tests/test_image_contents.py "{{image_name}}:{{image_tag}}" python3 tests/test_boot_assets.py "{{image_name}}:{{image_tag}}" diff --git a/docs/BUILD.md b/docs/BUILD.md index db5bf26..0c57304 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -8,6 +8,8 @@ - Network access to `gitlab.com`, `github.com`, `dl.k8s.io`, the FSDK BuildStream caches and the pinned FSDK `bst2` container image. - QEMU with KVM for the boot test (optional; requires a real root user namespace). + The Secure Boot cases in `just boot-test` also need `swtpm` and the release + fixtures described in [testsuite/README.md](../testsuite/README.md). BuildStream itself is not installed on the host. Every `bst` invocation runs inside the pinned `bst2` container via `just bst`. diff --git a/docs/SECUREBOOT-FIXTURES.md b/docs/SECUREBOOT-FIXTURES.md index 89168ae..cd18767 100644 --- a/docs/SECUREBOOT-FIXTURES.md +++ b/docs/SECUREBOOT-FIXTURES.md @@ -5,6 +5,14 @@ in [Gram](https://github.com/HuntedRaven7/Gram) (issue #19). They prove that a signed UKI update still unseals `MjolnirState`, while a UKI with an unknown PCR signing key fails the PCR 11 policy. +Mjolnir's own image gate does **not** download these release assets. It +generates fresh fixtures from the same signing artifacts as the image under +test (`just fixtures`) and points `FIXTURE_DIR` at `fixtures-out/`. Dev and CI +builds generate a new PCR signing key and measure a commit-specific kernel, +initramfs and cmdline, so a fixture from another build can never prove this +image's signed PCR 11 policy. The release exists only for the downstream +consumer that provisions against a published image. + ## Stable URLs Set `SECUREBOOT_FIXTURE_BASE_URL` in Gram to: diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 0bb6d5b..a6a514c 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -148,6 +148,21 @@ The initramfs is built with the dracut `crypt` module and the systemd TPM2 cryptsetup token plugin, whose ELF dependencies pull in `tpm2-tss`. It includes the build-time `/etc/crypttab`. +The unlock outcome has a stable serial contract. `mjolnir-state-unlocked.service` +prints `MjolnirState: unlocked` after `var-lib-mjolnir.mount`. An `OnFailure=` +drop-in on `systemd-cryptsetup@mjolnir-state.service` starts +`mjolnir-state-unseal-failed.service`, which prints `PCR policy`, +`Failed to unseal` and the distinctive `MjolnirState: PCR policy miss` and +`MjolnirState: PCR unseal failed`. The distinctive needles are what the boot +assertions check: systemd-tpm2-setup logs a generic `Failed to unseal` and +systemd-pcrlock logs `Calculated new PCR policy` on a healthy boot. The +drop-in and the failure unit are also sealed into the +initramfs, because a PCR policy miss fails cryptsetup before switch-root. No +key material changes and the PCR 7 plus signed PCR 11 binding is untouched. +`testsuite/boot/test-boot.sh` boots two isolated OVMF plus swtpm cases against +the published signed and unknown-key UKIs and asserts those needles; see +[testsuite/README.md](../testsuite/README.md) for the fixture contract. + ## Factory reset `io.mjolnir.Fleet.FactoryReset` requires a `scope` diff --git a/elements/base/os-stack.bst b/elements/base/os-stack.bst index 443b846..c8eadc3 100644 --- a/elements/base/os-stack.bst +++ b/elements/base/os-stack.bst @@ -16,6 +16,9 @@ depends: - freedesktop-sdk.bst:integration/ldconfig.bst - freedesktop-sdk.bst:components/systemd.bst +# systemd's TPM2 units need tpm2-tss after switch-root, not just in the +# initramfs where the cryptsetup token plugin pulls it in. +- freedesktop-sdk.bst:components/tpm2-tss.bst - freedesktop-sdk.bst:components/dbus.bst - freedesktop-sdk.bst:components/dbus-broker.bst - freedesktop-sdk.bst:components/kmod.bst diff --git a/elements/config/files.bst b/elements/config/files.bst index 3d0102d..474cb2f 100644 --- a/elements/config/files.bst +++ b/elements/config/files.bst @@ -43,6 +43,10 @@ config: "${root}/usr/lib/tmpfiles.d/mjolnir-volatile.conf" install -Dm644 /config/systemd/var-lib-mjolnir.mount \ "${root}/usr/lib/systemd/system/var-lib-mjolnir.mount" + # The cryptsetup instance drop-in lives in a directory, so the *.service + # glob below does not copy it. The initramfs stages its own copy. + install -Dm644 /config/systemd/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf \ + "${root}/usr/lib/systemd/system/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf" for m in var-lib-mjolnir var-lib-etcd etc-machine-id \ etc-NetworkManager-system-connections \ var-lib-containerd var-lib-kubelet var-log-journal var-lib-cni \ @@ -56,6 +60,21 @@ config: install -Dm644 /config/crictl.yaml "${root}/etc/crictl.yaml" install -Dm644 /config/presets/80-mjolnir.preset \ "${root}/usr/lib/systemd/system-preset/80-mjolnir.preset" + # systemd.volatile=yes seeds /etc from /usr/share/factory/etc on every + # boot. Preset symlinks created once the manager starts are too late for + # local-fs.target's initial transaction, so stage the state wants here as + # well; otherwise var-lib-mjolnir.mount and the needle units never run. + mkdir -p "${root}/usr/share/factory/etc/systemd/system/local-fs.target.wants" \ + "${root}/usr/share/factory/etc/systemd/system/multi-user.target.wants" + ln -sf /usr/lib/systemd/system/var-lib-mjolnir.mount \ + "${root}/usr/share/factory/etc/systemd/system/local-fs.target.wants/var-lib-mjolnir.mount" + # Enrollment runs at multi-user.target, like the unlock needle. Preset + # symlinks appear after local-fs.target's initial transaction, so an + # enroll unit wanted by local-fs.target never started. + for u in mjolnir-state-enroll.service mjolnir-state-unlocked.service; do + ln -sf "/usr/lib/systemd/system/${u}" \ + "${root}/usr/share/factory/etc/systemd/system/multi-user.target.wants/${u}" + done mkdir -p "${root}/usr/lib/systemd/system" cp /config/systemd/*.service /config/systemd/*.socket /config/systemd/*.timer \ "${root}/usr/lib/systemd/system/" 2>/dev/null || true diff --git a/elements/kernel/initramfs.bst b/elements/kernel/initramfs.bst index ff4891a..d3c566b 100644 --- a/elements/kernel/initramfs.bst +++ b/elements/kernel/initramfs.bst @@ -66,6 +66,15 @@ config: install -Dm644 /config/crypttab /etc/crypttab install -Dm644 /config/dracut/50-mjolnir-tpm2.conf \ /etc/dracut.conf.d/50-mjolnir-tpm2.conf + install -Dm644 /config/tmpfiles.d/mjolnir-initrd-pcr.conf \ + /usr/lib/tmpfiles.d/mjolnir-initrd-pcr.conf + # The PCR policy failure is reported by an OnFailure drop-in on the + # cryptsetup instance. Stage both files for dracut's install_items so the + # wires exist in the initramfs, not just in the booted rootfs. + install -Dm644 /config/systemd/mjolnir-state-unseal-failed.service \ + /usr/lib/systemd/system/mjolnir-state-unseal-failed.service + install -Dm644 /config/systemd/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf \ + /usr/lib/systemd/system/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf # FSDK installs shared libraries in the multiarch libdir but ships an empty # /etc/ld.so.conf. dracut-install resolves DT_NEEDED from that file plus # /lib and /usr/lib, so with an empty config the initramfs contains no libc @@ -132,6 +141,15 @@ config: exit 1 } done + # Prove the PCR failure report travels with the initramfs. A drop-in in + # the rootfs alone cannot fire before switch-root. + for f in usr/lib/systemd/system/mjolnir-state-unseal-failed.service \ + 10-mjolnir-failure.conf usr/bin/echo; do + lsinitrd /initramfs.img | grep -q "$f" || { + echo "initramfs is missing the PCR failure reporter: $f" >&2 + exit 1 + } + done install -Dm644 /initramfs.img \ "%{install-root}/usr/lib/modules/${version}/initramfs.img" depmod -b "%{install-root}/usr" -a "${version}" diff --git a/files/config/dracut/50-mjolnir-tpm2.conf b/files/config/dracut/50-mjolnir-tpm2.conf index 5f5186e..3b1cba2 100644 --- a/files/config/dracut/50-mjolnir-tpm2.conf +++ b/files/config/dracut/50-mjolnir-tpm2.conf @@ -5,3 +5,12 @@ add_dracutmodules+=" crypt " install_items+=" /etc/crypttab " install_optional_items+=" /usr/lib/cryptsetup/libcryptsetup-token-systemd-tpm2.so " +# A PCR policy miss fails cryptsetup in the initramfs, so the failure report +# and its OnFailure drop-in must be present before switch-root. echo is a +# compiled binary; no shell or interpreter enters the initramfs. +install_items+=" /usr/lib/systemd/system/mjolnir-state-unseal-failed.service " +install_items+=" /usr/lib/systemd/system/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf " +install_items+=" /usr/bin/echo " +# Copy the stub's signed PCR artifacts into /run/systemd before switch-root; +# the enroll unit cannot find them after /.extra/ disappears. +install_items+=" /usr/lib/tmpfiles.d/mjolnir-initrd-pcr.conf " diff --git a/files/config/presets/80-mjolnir.preset b/files/config/presets/80-mjolnir.preset index 03c8cd0..c53101f 100644 --- a/files/config/presets/80-mjolnir.preset +++ b/files/config/presets/80-mjolnir.preset @@ -6,6 +6,7 @@ enable mjolnir-join.service enable mjolnir-apply.service enable varlink-httpd.socket enable mjolnir-state-enroll.service +enable mjolnir-state-unlocked.service enable mjolnir-etcd-snapshot.timer enable NetworkManager.service enable systemd-resolved.service diff --git a/files/config/systemd/mjolnir-state-enroll.service b/files/config/systemd/mjolnir-state-enroll.service index d5d90ab..7676cf0 100644 --- a/files/config/systemd/mjolnir-state-enroll.service +++ b/files/config/systemd/mjolnir-state-enroll.service @@ -24,4 +24,4 @@ ReadOnlyPaths=/ ReadWritePaths=/var/lib/mjolnir /run/systemd [Install] -WantedBy=local-fs.target +WantedBy=multi-user.target diff --git a/files/config/systemd/mjolnir-state-unlocked.service b/files/config/systemd/mjolnir-state-unlocked.service new file mode 100644 index 0000000..70904fc --- /dev/null +++ b/files/config/systemd/mjolnir-state-unlocked.service @@ -0,0 +1,22 @@ +[Unit] +Description=Report MjolnirState unlock on the serial console +DefaultDependencies=no +# local-fs.target is reached before preset/factory wants symlinks take effect +# under systemd.volatile=yes. multi-user.target is late enough, and the +# decrypted mapping is the actual proof that the state key unsealed. +After=systemd-cryptsetup@mjolnir-state.service +ConditionPathExists=/dev/disk/by-label/MjolnirState + +[Service] +Type=oneshot +RemainAfterExit=yes +# `console` alone is not a valid systemd output specifier: systemd rejects it +# and silently falls back to the journal, which loses the needle on serial. +# `journal+console` is valid and the signed cmdline enables journald console +# forwarding, so the echo reaches ttyS0. +ExecStart=/usr/bin/echo MjolnirState: unlocked +StandardOutput=journal+console +StandardError=journal+console + +[Install] +WantedBy=multi-user.target diff --git a/files/config/systemd/mjolnir-state-unseal-failed.service b/files/config/systemd/mjolnir-state-unseal-failed.service new file mode 100644 index 0000000..daba7ff --- /dev/null +++ b/files/config/systemd/mjolnir-state-unseal-failed.service @@ -0,0 +1,19 @@ +[Unit] +Description=Report a TPM2 PCR policy unseal failure on the serial console +DefaultDependencies=no + +[Service] +Type=oneshot +# The failure happens in the initramfs, before switch-root. `console` alone is +# not a valid systemd output specifier, so use `journal+console`: journald is +# running in the initramfs and the signed cmdline forwards it to ttyS0. +ExecStart=/usr/bin/echo PCR policy +ExecStart=/usr/bin/echo Failed to unseal +# Distinctive needles: systemd-tpm2-setup logs "Failed to unseal" and +# systemd-pcrlock logs "Calculated new PCR policy" on a healthy boot, so the +# assertions must not match those generic strings. Keep the two lines above +# for the downstream consumer that greps them. +ExecStart=/usr/bin/echo MjolnirState: PCR policy miss +ExecStart=/usr/bin/echo MjolnirState: PCR unseal failed +StandardOutput=journal+console +StandardError=journal+console diff --git a/files/config/systemd/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf b/files/config/systemd/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf new file mode 100644 index 0000000..d40b069 --- /dev/null +++ b/files/config/systemd/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf @@ -0,0 +1,5 @@ +[Unit] +# A PCR policy miss fails the cryptsetup unit in the initramfs. The drop-in is +# installed in both the rootfs and the initramfs so the report fires before and +# after switch-root. +OnFailure=mjolnir-state-unseal-failed.service diff --git a/files/config/tmpfiles.d/mjolnir-initrd-pcr.conf b/files/config/tmpfiles.d/mjolnir-initrd-pcr.conf new file mode 100644 index 0000000..8eb4661 --- /dev/null +++ b/files/config/tmpfiles.d/mjolnir-initrd-pcr.conf @@ -0,0 +1,6 @@ +# systemd-stub exposes the signed PCR artifacts in the initrd at /.extra/. +# Copy them to the paths systemd-cryptenroll searches before switch-root; +# after switch-root the /.extra/ source is gone. The rootfs has the same +# lines in mjolnir-volatile.conf for the case where the artifacts persist. +C /run/systemd/tpm2-pcr-signature.json - - - - /.extra/tpm2-pcr-signature.json +C /run/systemd/tpm2-pcr-public-key.pem - - - - /.extra/tpm2-pcr-public-key.pem diff --git a/tests/test_boot_assets.py b/tests/test_boot_assets.py index e61acdb..832269f 100644 --- a/tests/test_boot_assets.py +++ b/tests/test_boot_assets.py @@ -35,6 +35,9 @@ "/usr/lib/repart.d/20-mjolnir-state.conf", "/etc/crypttab", "/usr/lib/systemd/system/mjolnir-state-enroll.service", + "/usr/lib/systemd/system/mjolnir-state-unlocked.service", + "/usr/lib/systemd/system/mjolnir-state-unseal-failed.service", + "/usr/lib/systemd/system/systemd-cryptsetup@mjolnir-state.service.d/10-mjolnir-failure.conf", "/usr/lib/systemd/system/mjolnir-reset-node-identity.service", "/usr/lib/systemd/system/mjolnir-reset-etcd-data.service", "/usr/lib/systemd/system/mjolnir-reset-full.service", diff --git a/tests/test_secureboot_fixtures.py b/tests/test_secureboot_fixtures.py index e3f1867..33b29ca 100644 --- a/tests/test_secureboot_fixtures.py +++ b/tests/test_secureboot_fixtures.py @@ -57,6 +57,14 @@ def main() -> int: generate_block = generate_block.split(" - name: Upload Secure Boot fixtures", 1)[0] if "if:" in generate_block: errors.append("fixture generation must run on PRs so the image gate exercises it") + provision_block = workflow.split(" - name: Provision Secure Boot fixtures", 1)[1] + provision_block = provision_block.split(" # The install checks", 1)[0] + if "fixtures-out" not in provision_block: + errors.append("the image gate does not use this build's generated fixtures") + if "FIXTURE_BASE_URL" in provision_block: + errors.append("the image gate must not consume stale release fixtures") + if "SHA256SUMS" not in provision_block or "sha256sum -c" not in provision_block: + errors.append("generated fixtures are not verified against SHA256SUMS") docs = read("docs/SECUREBOOT-FIXTURES.md") if BASE_URL not in docs or not all(f in docs for f in ASSETS): diff --git a/tests/test_tpm_support.py b/tests/test_tpm_support.py new file mode 100644 index 0000000..00d1b57 --- /dev/null +++ b/tests/test_tpm_support.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Assert the TPM2 userspace libraries are available in both boot stages. + +FSDK's systemd element does not runtime-depend on tpm2-tss. The initramfs +needs it for the cryptsetup token plugin, and the booted root needs it for +systemd-pcrlock, systemd-tpm2-setup and systemd-cryptenroll. A missing copy in +the root turns TPM-backed state enrollment into a silent fallback to the +empty-key LUKS slot, which the Secure Boot cases cannot distinguish. +""" +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def main() -> int: + errors: list[str] = [] + rootfs = (ROOT / "elements/base/os-stack.bst").read_text() + if "freedesktop-sdk.bst:components/tpm2-tss.bst" not in rootfs: + errors.append("tpm2-tss is missing from the runtime stack") + + initramfs = (ROOT / "elements/kernel/initramfs.bst").read_text() + if "freedesktop-sdk.bst:components/tpm2-tss.bst" not in initramfs: + errors.append("tpm2-tss is missing from the initramfs stack") + + dracut = (ROOT / "files/config/dracut/50-mjolnir-tpm2.conf").read_text() + if "libcryptsetup-token-systemd-tpm2.so" not in dracut: + errors.append("initramfs has no systemd TPM2 cryptsetup token plugin") + if "mjolnir-initrd-pcr.conf" not in dracut: + errors.append("initramfs does not install the PCR artifact tmpfiles rule") + + initrd_pcr = (ROOT / "files/config/tmpfiles.d/mjolnir-initrd-pcr.conf") + if not initrd_pcr.is_file(): + errors.append("missing initramfs PCR artifact tmpfiles rule") + else: + text = initrd_pcr.read_text() + if "/.extra/tpm2-pcr-signature.json" not in text: + errors.append("initramfs rule does not copy the PCR signature") + + initramfs = (ROOT / "elements/kernel/initramfs.bst").read_text() + if "mjolnir-initrd-pcr.conf" not in initramfs: + errors.append("initramfs element does not stage the PCR tmpfiles rule") + + if errors: + for error in errors: + print(f" - {error}") + raise SystemExit(1) + print("TPM2 userspace contract OK") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_units.py b/tests/test_units.py index 5a859c6..29b5446 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -63,6 +63,66 @@ def main() -> int: if "/run/credentials/@system/mjolnir.boot-report" not in report_text: errors.append("mjolnir-boot-report.service: missing dotted boot-report credential gate") + # Secure Boot serial needles are an external contract: Gram greps for the + # exact strings. Check the units, the drop-in that fires on a cryptsetup + # failure, and the boot assertions that consume them. + def text_at(relative: str) -> str: + path = ROOT / relative + return path.read_text() if path.is_file() else "" + + def require(relative: str, needle: str, label: str) -> None: + if needle not in text_at(relative): + errors.append(f"{relative}: missing {label}: {needle!r}") + + unlocked = "files/config/systemd/mjolnir-state-unlocked.service" + failed = "files/config/systemd/mjolnir-state-unseal-failed.service" + dropin = ("files/config/systemd/systemd-cryptsetup@mjolnir-state.service.d/" + "10-mjolnir-failure.conf") + dracut = "files/config/dracut/50-mjolnir-tpm2.conf" + boot = "testsuite/boot/test-boot.sh" + + require(unlocked, "ExecStart=/usr/bin/echo MjolnirState: unlocked", "unlock needle") + require(unlocked, "ConditionPathExists=/dev/disk/by-label/MjolnirState", "unlock condition") + require(unlocked, "WantedBy=multi-user.target", "unlock target") + require("files/config/presets/80-mjolnir.preset", + "enable mjolnir-state-unlocked.service", "unlock preset") + require(failed, "ExecStart=/usr/bin/echo PCR policy", "PCR needle") + require(failed, "ExecStart=/usr/bin/echo Failed to unseal", "unseal failure needle") + require(failed, "ExecStart=/usr/bin/echo MjolnirState: PCR policy miss", + "distinctive PCR needle") + require(failed, "ExecStart=/usr/bin/echo MjolnirState: PCR unseal failed", + "distinctive unseal failure needle") + # A bare `console` is not a valid StandardOutput= specifier: systemd drops + # it and the needle never reaches the serial log. Both units must forward + # through journald *and* the console (enabled by the signed cmdline). + for unit in (unlocked, failed): + require(unit, "StandardOutput=journal+console", "journal+console output") + require(unit, "StandardError=journal+console", "journal+console error output") + for key in ("StandardOutput", "StandardError"): + if re.search(rf"^{key}=console\s*$", text_at(unit), re.MULTILINE): + errors.append(f"{unit}: invalid bare '{key}=console' specifier") + require(dropin, "OnFailure=mjolnir-state-unseal-failed.service", "failure wiring") + require(dracut, "mjolnir-state-unseal-failed.service", "initramfs failure unit") + require(dracut, "10-mjolnir-failure.conf", "initramfs drop-in") + require(dracut, "/usr/bin/echo", "initramfs echo binary") + for needle in ("MjolnirState: unlocked", "MjolnirState: PCR policy miss", + "MjolnirState: PCR unseal failed"): + require(boot, needle, "boot assertion needle") + # The cases start from a disk whose encrypted state partition already + # exists; otherwise repart creates it after cryptsetup has timed out. + require(boot, "provision_state_partition", "state partition provisioning") + # volatile /etc is seeded from factory /etc: the mount must be in + # local-fs.target's wants, and the enrollment and needle units in + # multi-user.target's wants, before their transactions are computed. + files_bst = "elements/config/files.bst" + require(files_bst, "local-fs.target.wants/var-lib-mjolnir.mount", + "factory local-fs wants for the state mount") + require(files_bst, "multi-user.target.wants/${u}", "factory multi-user wants loop") + for unit in ("mjolnir-state-enroll.service", "mjolnir-state-unlocked.service"): + require(files_bst, unit, f"factory multi-user wants for {unit}") + require("files/config/systemd/mjolnir-state-enroll.service", + "WantedBy=multi-user.target", "enrollment target") + # Lid switches must never suspend an unattended node. logind = ROOT / "files/config/logind/50-ignore-lid.conf" logind_text = logind.read_text() if logind.is_file() else "" diff --git a/testsuite/README.md b/testsuite/README.md index ff3e418..b833110 100644 --- a/testsuite/README.md +++ b/testsuite/README.md @@ -12,8 +12,9 @@ clusters and the mTLS Varlink API. `.github/workflows/multinode.yml` on `testing`. - `plugin-smoke.sh` — Console plugin smoke check, run by `.github/workflows/plugin-test.yml`. -- `boot/test-boot.sh` — install + OVMF boot proof, run by the `image` job in - `.github/workflows/build.yml` on pull requests and pushes. +- `boot/test-boot.sh` — install + OVMF boot proof and the two Secure Boot + swtpm cases, run by the `image` job in `.github/workflows/build.yml` on pull + requests and pushes. ## Boot verification @@ -26,4 +27,59 @@ root as a distinct systemd-boot entry. See [docs/ARCHITECTURE.md](../docs/ARCHITECTURE.md). Run it locally with `sudo just boot-test` after `just build`; it needs root, -KVM, QEMU, OVMF and `objcopy`. +KVM, QEMU, OVMF and `objcopy`. The Secure Boot cases additionally need `swtpm`. + +## Secure Boot unlock cases + +`boot/test-boot.sh` appends two cases after the OVMF check above. First it +applies the image's own `repart.d` definition to the installed disk on the host +so `MjolnirState` already has its empty-key LUKS2 slot: repart runs only after +switch-root, so the initramfs cryptsetup cannot see the partition on a disk +that has never been booted. Each case then copies that provisioned disk and +gets its own copy of the enrolled OVMF variable store and its own swtpm state +directory, so a failed unseal in one case cannot leak into the other. The case +VMs receive firstboot settings as SMBIOS systemd credentials (locale, keymap, +timezone, hostname and a throwaway root password) so the interactive firstboot +prompt cannot stall `local-fs.target`. Both cases first boot `uki-signed.efi` to +establish the TPM2 enrollment, then reboot with the case's update: + +| Case | Update installed in the ESP | Required serial evidence | +| --- | --- | --- | +| signed | `uki-signed.efi` | `MjolnirState: unlocked`, no `MjolnirState: PCR unseal failed` | +| unknown | `uki-unknown.efi` | `PCR policy` and `MjolnirState: PCR unseal failed`, no unlock | + +The needles come from image units, not from journal text the guest happens to +emit. `mjolnir-state-unlocked.service` runs at `multi-user.target` when the +decrypted `MjolnirState` mapping exists; `local-fs.target` is reached before +preset wants symlinks take effect under the volatile root. A drop-in for +`systemd-cryptsetup@mjolnir-state.service` +wires `OnFailure=` to `mjolnir-state-unseal-failed.service`; that unit and the +drop-in are installed in both the rootfs and the initramfs because the PCR miss +fails cryptsetup before switch-root. Both units use +`StandardOutput=journal+console` / `StandardError=journal+console`; a bare +`console` specifier is invalid in systemd and is silently dropped. The signed +cmdline enables journald forwarding to `ttyS0`, so the needles reach the serial +log both before and after switch-root. + +### Fixtures + +The three fixtures are generated from the same signing artifacts as the image +under test by `just fixtures` (CI runs this before the boot test). Their PCR +signature and measured kernel/initrd/cmdline therefore belong to this build. +The harness reads them from `FIXTURE_DIR`, which defaults to `fixtures-out/` in +the repository root. The published release assets are for the downstream Gram +harness, not for this gate: + +| File | Meaning | +| --- | --- | +| `OVMF_VARS.enrolled.fd` | Variable store with PK/KEK/db holding the test key, Secure Boot enabled; copied fresh per case | +| `uki-signed.efi` | Signed update that satisfies the existing PCR 11 policy | +| `uki-unknown.efi` | Same boot, signed with an unknown PCR signing key | + +Env overrides: `FIXTURE_DIR`, `SECUREBOOT_FIXTURE_DIR`, `OVMF_VARS_ENROLLED`, +`UKI_SIGNED`, `UKI_UNKNOWN`, `SIGNED_LOG`, `UNKNOWN_LOG`, `SWTPM`, `BOOT_WAIT`, +`GRACE_SECONDS`, and the three needle overrides `UNLOCK_NEEDLE`, `PCR_NEEDLE`, +`UNSEAL_FAIL_NEEDLE`. With no fixtures in `FIXTURE_DIR` the two cases write +SKIP logs and the run stays green; the assertions in the script and the static +checks in `tests/test_units.py` still run on every PR. +Both serial logs are uploaded as the `mjolnir-secureboot-serial-logs` artifact. diff --git a/testsuite/boot/test-boot.sh b/testsuite/boot/test-boot.sh index df18f51..dc6550f 100755 --- a/testsuite/boot/test-boot.sh +++ b/testsuite/boot/test-boot.sh @@ -1,11 +1,15 @@ #!/usr/bin/env bash -# Full install + OVMF boot proof for the signed composefs UKI. +# Full install + OVMF boot proof for the signed composefs UKI, plus two +# Secure Boot + swtpm cases that consume the published UKI/variable-store +# fixtures. # # Runs on the CI runner (root required). There is no shell in the image: the # image is installed with `bootc install to-disk`, the installed UKI is checked # against the composefs digest of the image under test, and the disk is booted # through OVMF/systemd-boot. Readiness is proven by the image's own Varlink -# socket, not by injecting a shell or a login into the target. +# socket, not by injecting a shell or a login into the target. The extra cases +# read serial needles emitted by image units; fixtures are described in +# testsuite/README.md. set -euo pipefail IMAGE="${1:-localhost/mjolnir:latest}" @@ -30,7 +34,19 @@ sudo -n true || fail "passwordless sudo is required for the privileged install a rm -rf "$WORK" mkdir -p "$WORK/rootfs" "$WORK/esp" -trap 'set +e; sudo umount "$WORK/esp" 2>/dev/null; [ -n "${LOOP:-}" ] && sudo losetup -d "$LOOP" 2>/dev/null; kill "${QEMU_PID:-}" 2>/dev/null; sudo podman rm -f mjolnir-boot-src 2>/dev/null' EXIT +cleanup_boot() { + set +e + local l p f + sudo umount "$WORK/esp" 2>/dev/null + [ -n "${LOOP:-}" ] && sudo losetup -d "$LOOP" 2>/dev/null + for l in "${CASE_LOOPS[@]:-}"; do [ -n "$l" ] && sudo losetup -d "$l" 2>/dev/null; done + for p in "${CASE_QEMU_PIDS[@]:-}"; do [ -n "$p" ] && kill "$p" 2>/dev/null; done + for f in "$WORK"/secureboot-*/tpm/swtpm.pid; do + [ -f "$f" ] && kill "$(cat "$f")" 2>/dev/null + done + sudo podman rm -f mjolnir-boot-src 2>/dev/null +} +trap cleanup_boot EXIT echo "==> computing the expected composefs digest from the image under test" # bootc install hashes the OCI layers in container storage, not a flattened tar @@ -155,6 +171,12 @@ openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days -keyout "$WORK/ca.key" -out "$WORK/ca.crt" -subj /CN=MjolnirBootTest >/dev/null 2>&1 \ || fail "could not generate the test client CA" CA_B64=$(base64 -w0 "$WORK/ca.crt") || fail "could not encode the test client CA" +# Firstboot must not wait for a human on the console: an unpopulated volatile +# /etc otherwise leaves systemd-firstboot.service prompting for a timezone and +# blocks the local-fs units (including the state mount and unlock needle). +# These are test-only credentials passed through SMBIOS, never image content. +ROOTPW_B64=$(printf %s 'mjolnir-boot-test' | base64 -w0) || \ + fail "could not encode the firstboot test password" timeout 300 sudo qemu-system-x86_64 \ -m 2048 -smp 2 -enable-kvm -nographic \ @@ -222,3 +244,233 @@ fi pass "booted with OVMF: signed UKI cmdline, live user space, no failed units" echo "Serial console log: $SERIAL" + +# --------------------------------------------------------------------------- +# Secure Boot + swtpm cases. +# +# The fixtures are release assets of the image repository. Each case gets its +# own copy of the installed disk, the enrolled variable store and the swtpm +# state directory. Missing fixtures produce SKIP logs and a green run: the +# existing checks above stay intact, and no assertion is weakened. Set +# FIXTURE_DIR (or the three per-file overrides) to run the cases. +# --------------------------------------------------------------------------- +FIXTURE_DIR="${FIXTURE_DIR:-${SECUREBOOT_FIXTURE_DIR:-${RUNNER_TEMP:-/tmp}/mjolnir-secureboot-fixtures}}" +VARS_ENROLLED="${OVMF_VARS_ENROLLED:-$FIXTURE_DIR/OVMF_VARS.enrolled.fd}" +UKI_SIGNED="${UKI_SIGNED:-$FIXTURE_DIR/uki-signed.efi}" +UKI_UNKNOWN="${UKI_UNKNOWN:-$FIXTURE_DIR/uki-unknown.efi}" +SIGNED_LOG="${SIGNED_LOG:-$WORK/secureboot-signed.log}" +UNKNOWN_LOG="${UNKNOWN_LOG:-$WORK/secureboot-unknown.log}" +SWTPM="${SWTPM:-swtpm}" +SWTPM_SETUP="${SWTPM_SETUP:-swtpm_setup}" +NEEDLE_UNLOCK="${UNLOCK_NEEDLE:-MjolnirState: unlocked}" +NEEDLE_PCR="${PCR_NEEDLE:-MjolnirState: PCR policy miss}" +NEEDLE_FAILED="${UNSEAL_FAIL_NEEDLE:-MjolnirState: PCR unseal failed}" +BOOT_WAIT="${BOOT_WAIT:-180}" +GRACE="${GRACE_SECONDS:-10}" +CASE_LOOPS=() +CASE_QEMU_PIDS=() + +# bootc --run-repart leaves MjolnirState for systemd-repart on first boot, and +# repart only runs after switch-root. The initramfs cryptsetup has already +# timed out by then, so a first boot never mounts state and the unlock needle +# cannot fire. Apply the image's own repart.d definition to the installed disk +# on the host instead: this creates the empty-key LUKS2 partition that each +# case then enrolls with the signed fixture on its first boot. +provision_state_partition() { + local defs="$WORK/repart-state" loop part found=0 + echo "==> provisioning MjolnirState from the image's repart.d definition" + mkdir -p "$defs" + sudo podman cp "mjolnir-boot-src:/usr/lib/repart.d/20-mjolnir-state.conf" \ + "$defs/" || fail "cannot copy the image's MjolnirState definition" + loop=$(sudo losetup -f --show -P "$WORK/disk.raw") || \ + fail "cannot attach the installed disk for provisioning" + CASE_LOOPS+=("$loop") + # On a loop-backed disk repart defaults to dry-run; require it to apply. + # No --key-file: systemd-repart then uses the empty key (documented behavior + # of Encrypt=key-file), exactly as it does on the image's first boot. The + # cases below prove the guest can actually unlock it with try-empty-password. + sudo systemd-repart --definitions="$defs" --dry-run=no --discard=no \ + "$loop" || fail "systemd-repart could not provision MjolnirState" + # The partition table changed underneath the loop device: reattach so the + # new partition node exists before the check below. + sudo losetup -d "$loop" || true + loop=$(sudo losetup -f --show -P "$WORK/disk.raw") || \ + fail "cannot reattach the provisioned disk" + CASE_LOOPS+=("$loop") + for part in "${loop}"p*; do + [ -b "$part" ] || continue + [ "$(sudo blkid -o value -s PARTLABEL "$part" 2>/dev/null || true)" = "MjolnirState" ] || continue + found=1 + [ "$(sudo blkid -p -o value -s TYPE "$part" 2>/dev/null || true)" = "crypto_LUKS" ] || \ + fail "MjolnirState is not a LUKS2 partition" + done + [ "$found" -eq 1 ] || fail "systemd-repart did not create MjolnirState" + pass "MjolnirState provisioned from the image's repart.d definition" +} + +assert_needle() { + local log="$1" needle="$2" label="$3" + grep -aqF "$needle" "$log" || fail "$label: missing serial needle '$needle' in $log" + pass "$label: serial needle '$needle'" +} + +assert_no_needle() { + local log="$1" needle="$2" label="$3" + if grep -aqF "$needle" "$log"; then + fail "$label: unexpected serial needle '$needle' in $log" + fi + pass "$label: no '$needle'" +} + +# Put one fixture UKI on the case disk's ESP. The debug entry is removed from +# the copy so systemd-boot cannot choose it instead of the fixture. +install_case_uki() { + local cd="$1" uki="$2" loop part p count + loop=$(sudo losetup -f --show -P "$cd/disk.raw") || fail "cannot attach $cd/disk.raw" + CASE_LOOPS+=("$loop") + part="" + for p in "${loop}"p*; do + [ -b "$p" ] || continue + [ "$(sudo blkid -o value -s TYPE "$p" 2>/dev/null || true)" = "vfat" ] && part="$p" + done + [ -n "$part" ] || fail "no ESP partition on $cd/disk.raw" + sudo mount "$part" "$WORK/esp" || fail "cannot mount the case ESP" + sudo install -Dm644 "$uki" "$WORK/esp/EFI/Linux/$(basename "$UKI")" || \ + fail "cannot install $uki on the case ESP" + sudo rm -f "$WORK/esp/EFI/Linux/$(basename "$DBG_EFI")" \ + "$WORK/esp/loader/entries/99-mjolnir-debug.conf" + count=$(sudo find "$WORK/esp/EFI/Linux" -maxdepth 1 -name '*.efi' -type f | wc -l) + [ "$count" -eq 1 ] || fail "case ESP has $count UKIs; expected exactly one" + sudo umount "$WORK/esp" || fail "cannot unmount the case ESP" + sudo losetup -d "$loop" || fail "cannot detach $loop" +} + +boot_case() { + local label="$1" log="$2" cd="$3" primary="$4" pid elapsed=0 + SERIAL="$log" + # The log lives in the user-owned WORK dir; root writes through this fd. + # shellcheck disable=SC2024 + sudo qemu-system-x86_64 \ + -m 2048 -smp 2 -enable-kvm -nographic \ + -drive if=pflash,format=raw,unit=0,file="$WORK/code.fd",readonly=on \ + -drive if=pflash,format=raw,unit=1,file="$cd/vars.fd" \ + -drive file="$cd/disk.raw",format=raw,media=disk \ + -chardev "socket,id=chrtpm,path=$cd/tpm/swtpm.sock" \ + -tpmdev emulator,id=tpm0,chardev=chrtpm \ + -device tpm-tis,tpmdev=tpm0 \ + -smbios type=11,value=io.systemd.credential:mjolnir.boot-report=1 \ + -smbios "type=11,value=io.systemd.credential.binary:varlink-httpd.tls.trust=$CA_B64" \ + -smbios type=11,value=io.systemd.credential:firstboot.locale=C.UTF-8 \ + -smbios type=11,value=io.systemd.credential:firstboot.keymap=us \ + -smbios type=11,value=io.systemd.credential:firstboot.timezone=UTC \ + -smbios type=11,value=io.systemd.credential:firstboot.hostname=mjolnir \ + -smbios "type=11,value=io.systemd.credential.binary:passwd.plaintext-password.root=$ROOTPW_B64" \ + -netdev user,id=net0 -device virtio-net-pci,netdev=net0 \ + >"$log" 2>&1 & + pid=$! + CASE_QEMU_PIDS+=("$pid") + while [ "$elapsed" -lt "$BOOT_WAIT" ]; do + if grep -aqF "$primary" "$log" 2>/dev/null; then break; fi + kill -0 "$pid" 2>/dev/null || break + sleep 2 + elapsed=$((elapsed + 2)) + done + # Give late units time to emit a needle before asserting its absence. + sleep "$GRACE" + kill "$pid" 2>/dev/null || true + wait "$pid" 2>/dev/null || true + [ -s "$log" ] || fail "$label: VM produced no serial output" + pass "$label: serial log captured at $log" +} + +# QEMU sends CMD_SHUTDOWN to swtpm when it exits, so the daemon terminates and +# unlinks its control socket. Every boot therefore needs a fresh daemon on the +# same tpmstate dir: the dir keeps enrollment state while the new process +# resets volatile PCRs, which is what a real reboot does. +start_swtpm() { + local cd="$1" tpm label old + tpm="$cd/tpm" + label=${cd##*/} + if [ -f "$tpm/swtpm.pid" ]; then + old=$(cat "$tpm/swtpm.pid") + # The pid file can outlive the daemon QEMU shut down. Never signal a pid + # that the kernel may have recycled for an unrelated process. + if kill -0 "$old" 2>/dev/null && + tr '\0' ' ' <"/proc/$old/cmdline" 2>/dev/null | grep -q swtpm; then + kill "$old" 2>/dev/null || true + fi + fi + rm -f "$tpm/swtpm.pid" "$tpm/swtpm.sock" + "$SWTPM" socket --tpmstate "dir=$tpm" \ + --ctrl "type=unixio,path=$tpm/swtpm.sock" \ + --pid "file=$tpm/swtpm.pid" --flags not-need-init --tpm2 --daemon \ + --log "file=$tpm/swtpm.log" || fail "swtpm did not start for $label" + for _ in $(seq 1 50); do + [ -S "$tpm/swtpm.sock" ] && break + sleep 0.1 + done + [ -S "$tpm/swtpm.sock" ] || fail "swtpm socket did not appear for $label" +} + +secureboot_cases() { + local missing=0 f label cd tpm + for f in "$VARS_ENROLLED" "$UKI_SIGNED" "$UKI_UNKNOWN"; do + if [ ! -s "$f" ]; then + echo " missing fixture: $f" + missing=1 + fi + done + if [ "$missing" -ne 0 ]; then + mkdir -p "$WORK" + for f in "$SIGNED_LOG" "$UNKNOWN_LOG"; do + printf 'SKIP: Secure Boot swtpm cases did not run.\nFixture directory: %s\nThe three fixtures are release assets of the image repository; see testsuite/README.md.\n' \ + "$FIXTURE_DIR" >"$f" + done + echo "SKIP: Secure Boot swtpm cases (fixtures not present in $FIXTURE_DIR)" + return 0 + fi + need "$SWTPM" + need "$SWTPM_SETUP" + provision_state_partition + + for label in signed unknown; do + cd="$WORK/secureboot-$label" + tpm="$cd/tpm" + rm -rf "$cd" + mkdir -p "$tpm" + # A bare swtpm socket on a fresh state dir leaves libtpms in failure mode, + # and the guest sees "AES-128-CFB missing?" instead of a usable TPM. + # Manufacture the state once per case; start_swtpm reuses it for both boots. + "$SWTPM_SETUP" --tpm2 --tpmstate "$tpm" --overwrite --pcr-banks sha256 || + fail "swtpm_setup failed for $label" + cp "$WORK/disk.raw" "$cd/disk.raw" || fail "cannot copy the disk for $label" + cp "$VARS_ENROLLED" "$cd/vars.fd" || fail "cannot copy the variable store for $label" + + echo "==> Secure Boot case $label: enrolling state with the signed UKI" + install_case_uki "$cd" "$UKI_SIGNED" + start_swtpm "$cd" + boot_case "$label-enroll" "$cd/enroll.log" "$cd" "$NEEDLE_UNLOCK" + assert_needle "$cd/enroll.log" "$NEEDLE_UNLOCK" "$label-enroll" + + if [ "$label" = signed ]; then + echo "==> Secure Boot case signed: booting the signed update again" + install_case_uki "$cd" "$UKI_SIGNED" + start_swtpm "$cd" + boot_case signed "$SIGNED_LOG" "$cd" "$NEEDLE_UNLOCK" + assert_needle "$SIGNED_LOG" "$NEEDLE_UNLOCK" signed + assert_no_needle "$SIGNED_LOG" "$NEEDLE_FAILED" signed + else + echo "==> Secure Boot case unknown: booting the unknown PCR-key UKI" + install_case_uki "$cd" "$UKI_UNKNOWN" + start_swtpm "$cd" + boot_case unknown "$UNKNOWN_LOG" "$cd" "$NEEDLE_FAILED" + assert_needle "$UNKNOWN_LOG" "$NEEDLE_PCR" unknown + assert_needle "$UNKNOWN_LOG" "$NEEDLE_FAILED" unknown + assert_no_needle "$UNKNOWN_LOG" "$NEEDLE_UNLOCK" unknown + fi + kill "$(cat "$tpm/swtpm.pid")" 2>/dev/null || true + done + echo "Secure Boot serial logs: $SIGNED_LOG, $UNKNOWN_LOG" +} + +secureboot_cases