Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ jobs:
- name: Make the patched tree
run: spin-machine-dev patched tree ${{ matrix.part }}

- name: What a traced build needs
if: ${{ matrix.build-mode == 'manual' }}
run: go tool task patched-build-deps

# Before the tracer starts: what is built here is not extracted, and the analysis reads only
# what the step under it compiles (the kernel's bzImage, built here when a touched file is one
# only it builds, would be the whole kernel).
- name: Build what compiling the touched files needs, untraced
if: ${{ matrix.build-mode == 'manual' }}
run: spin-machine-dev patched prepare ${{ matrix.part }}

- name: Initialize CodeQL
uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
with:
Expand All @@ -80,10 +91,6 @@ jobs:
source-root: _output/patched/${{ matrix.part }}/src
queries: security-extended

- name: What a traced build needs
if: ${{ matrix.build-mode == 'manual' }}
run: go tool task patched-build-deps

- name: Compile what the patches touch, traced
if: ${{ matrix.build-mode == 'manual' }}
run: spin-machine-dev patched compile ${{ matrix.part }}
Expand Down
13 changes: 11 additions & 2 deletions .github/workflows/compat.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ name: Compat
# machine's record still refuses what QEMU loads silently and accepts the machine's own checkpoint
# (boot:compat, boot:record): on every pull request and push to main that changes what a resumed
# guest is loaded into - the machine's definition, QEMU, the kernel, the firmware and their pins -
# and before every release. And whether that kernel, booted, is locked down (boot:lockdown), and
# whether a guest checkpointed and continued still grows (boot:cpu-plug).
# and before every release. And whether that kernel, booted, is locked down (boot:lockdown) and at
# a random base every boot (boot:kaslr), and whether a guest checkpointed and continued still grows
# (boot:cpu-plug).
#
# How long a checkpoint stops the guest (boot:checkpoint-pause) is a bound, not compatibility: it
# runs on the bench, on each release (release.yml's pause) and at a QEMU bump (versions.yaml).
Expand Down Expand Up @@ -198,6 +199,14 @@ jobs:
- name: The kernel is locked down
run: go tool task boot:lockdown

# The same kernel across ten boots: its virtual base, its physical base and the regions
# RANDOMIZE_MEMORY moves each take more than one value and never the unrandomized one. One
# boot cannot tell a random address from a fixed one, and the vmlinux the machine enters
# through PVH is randomized by kernel/patches/0014-0020 and qemu/patches/0008, none of which
# anything else here would miss (#645).
- name: The kernel is somewhere else every boot
run: go tool task boot:kaslr

# The run passed, or the change does not reach the machine: the one check of this workflow a
# ruleset can require. A `resume` that failed or was cancelled, or a `changed` that could not
# say, is not a pass.
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/lab.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ on:
- bootchart
- ledger
- exits
- check:kaslr
- check:firmware
- check:firmware-stages
- check:waits
Expand Down
2 changes: 1 addition & 1 deletion Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ tasks:
- sudo apt-get install -y -q graphviz

patched-build-deps:
desc: What `spin-machine-dev patched compile` needs to compile the kernel's and QEMU's touched files (codeql.yml runs it by this name).
desc: What `spin-machine-dev patched prepare` and `compile` need to compile the kernel's and QEMU's touched files (codeql.yml runs it by this name).
cmds:
- sudo apt-get update -q
- sudo apt-get install -y -q --no-install-recommends bc bison flex libelf-dev libssl-dev dwarves ninja-build libglib2.0-dev libpixman-1-dev python3-venv
Expand Down
9 changes: 9 additions & 0 deletions boot/Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,15 @@ tasks:
cmds:
- SPIN_LOCKDOWN_TEST=1 go test ./boot/ -run '^TestTheGuestKernelIsLockedDown$' -count=1 -v -timeout 5m

kaslr:
desc: >-
Check the kernel's virtual base, physical base and RANDOMIZE_MEMORY regions each move,
across SPIN_KASLR_BOOTS boots (default 10) in spin's base shape (kaslr_test.go, #645).
Needs a built release and /dev/kvm.
deps: [':tools']
cmds:
- SPIN_KASLR_TEST=1 go test ./boot/ -run '^TestTheKernelMovesEveryBoot$' -count=1 -v -timeout 15m

cpu-plug:
desc: >-
A workspace checkpointed with memory and continued still grows: spin's shape booted to
Expand Down
97 changes: 97 additions & 0 deletions boot/kaslr_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// SPDX-License-Identifier: Apache-2.0

package boot_test

import (
"cmp"
"os"
"regexp"
"strconv"
"testing"

"github.com/spin-stack/machine/machine"
)

// KASLR moves three things, and a kernel that boots says nothing when one of them stays put: the
// kernel's virtual base (_text), its physical base ("Kernel code" in /proc/iomem), and with
// RANDOMIZE_MEMORY the direct map, vmalloc and vmemmap regions. Each is read in SPIN_KASLR_BOOTS
// guests (default 10) of spin's base shape, 1 vCPU and 128 MiB, the least memory the physical
// base is chosen in, and each must take more than one value.
// One boot cannot tell a fixed address from a random one, and a vmlinux entered through PVH moved
// neither base nor the regions, with CONFIG_RANDOMIZE_BASE and RANDOMIZE_MEMORY both =y (#645).
//
// The regions are seen through the lowest vmalloc address and the lowest unix socket, a direct
// map object, each rounded down to the 1 GiB that kernel_randomize_memory aligns a region to.
// Unrandomized they sit at the region's fixed base whatever the boot allocated. A %p hash, which
// an earlier version of this check compared, differs every boot whatever the layout, and is
// refused as not a kernel address. vmemmap moves with the other two or not at all: one test of
// KASLR_FLAG gates all three (kernel/patches/0019).
func TestTheKernelMovesEveryBoot(t *testing.T) {
if os.Getenv("SPIN_KASLR_TEST") != "1" {
t.Skip("set SPIN_KASLR_TEST=1 to boot a built release repeatedly and compare where its kernel is")
}
boots, err := strconv.Atoi(cmp.Or(os.Getenv("SPIN_KASLR_BOOTS"), "10"))
if err != nil || boots < 2 {
t.Fatalf("SPIN_KASLR_BOOTS=%q: two boots at least", os.Getenv("SPIN_KASLR_BOOTS"))
}
out := releaseTree(t)
rel, err := machine.OpenRelease(out)
if err != nil {
t.Fatal(err)
}
base, err := rel.Rootfs()
if err != nil {
t.Fatal(err)
}
root := newRawRoot(t, out, base)
oneshotAtBoot(t, root, "kaslr-check", "kaslr-check.sh", "")

line := regexp.MustCompile(`KASLR text=([0-9a-f]+) phys=([0-9a-f]+) vmalloc=([0-9a-f]+) directmap=([0-9a-f]+)`)
// Where a region is unrandomized, with 4-level paging and with 5-level. A randomized region
// lands there about once in thousands of boots. The bases are not checked so: a random
// kernel is at its linked _text about once in 480 boots, and at its linked physical base in
// 128 MiB about once in 36, so their check is only that they moved.
fixed := map[string][]uint64{
"vmalloc": {0xffffc90000000000, 0xffa0000000000000},
"directmap": {0xffff888000000000, 0xff11000000000000},
}
what := []string{"text", "phys", "vmalloc", "directmap"}
seen := map[string]map[uint64]bool{}
for _, w := range what {
seen[w] = map[uint64]bool{}
}
for i := range boots {
console := checkGuest(t, rel, root, "KASLR_CHECK_OK", "KASLR_CHECK_FAILED", func(s *machine.Spec) {
s.BootCPUs = 1
s.Memory.BaseMB = 128
}, func(*machine.QEMU, string) {})
m := line.FindStringSubmatch(console)
if m == nil {
t.Fatalf("boot %d: no KASLR line on the console:\n%s", i+1, console)
}
t.Logf("boot %d: _text %s, Kernel code at %s, lowest vmalloc %s, lowest unix socket %s", i+1, m[1], m[2], m[3], m[4])
for j, what := range what {
v, err := strconv.ParseUint(m[j+1], 16, 64)
if err != nil {
t.Fatalf("boot %d: %s %q: %v", i+1, what, m[j+1], err)
}
if what == "vmalloc" || what == "directmap" {
if v < 0xff00000000000000 {
t.Fatalf("boot %d: %s %#x is not a kernel address: a hash, or a pointer kptr_restrict hid", i+1, what, v)
}
v &^= 1<<30 - 1
}
seen[what][v] = true
}
}
for _, w := range what {
for _, a := range fixed[w] {
if seen[w][a] {
t.Errorf("%s was at %#x, where it is unrandomized, in a boot", w, a)
}
}
if len(seen[w]) < 2 {
t.Errorf("%s took one value in %d boots (the boots above)", w, boots)
}
}
}
24 changes: 24 additions & 0 deletions boot/testdata/kaslr-check.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/bin/sh
# SPDX-License-Identifier: Apache-2.0
set -eu
trap 'echo KASLR_CHECK_FAILED' EXIT

if grep -qw nokaslr /proc/cmdline; then
echo "the kernel was booted with nokaslr: $(cat /proc/cmdline)"
exit 1
fi
# 1 and not 0: at 0, %pK prints a hash that differs every boot whatever the layout, and only
# kallsyms printed a real address. At 1 root, holding CAP_SYSLOG, reads every address as it is.
echo 1 > /proc/sys/kernel/kptr_restrict
text=$(awk '$3 == "_text" { print $1 }' /proc/kallsyms)
phys=$(awk -F'[- :]+' '/Kernel code/ { print $2; exit }' /proc/iomem)
# The lowest vmalloc address, near vmalloc_base, and the lowest unix socket, an object in the
# direct map near page_offset_base: the two regions RANDOMIZE_MEMORY moves that root can see.
vmalloc=$(awk 'NR == 1 { split($1, a, "-"); sub("^0x", "", a[1]); print a[1] }' /proc/vmallocinfo)
directmap=$(awk -F: 'NR > 1 { print $1 }' /proc/net/unix | sort | head -1)
test -n "$text" && test -n "$phys" && test -n "$vmalloc" && test -n "$directmap"
test "$phys" != 00000000

trap - EXIT
echo "KASLR text=$text phys=$phys vmalloc=$vmalloc directmap=$directmap"
echo KASLR_CHECK_OK
7 changes: 4 additions & 3 deletions boot/testdata/lockdown-check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ if echo none > /sys/kernel/security/lockdown 2>/dev/null; then
fi
grep -q '\[confidentiality\]' /sys/kernel/security/lockdown

# The kernel is at a random address (KASLR). It is the bzImage's decompressor that picks one.
# Until 2026-11-19 the machine entered vmlinux through PVH, which skips it, and the kernel ran
# where it was linked, ffffffff81000000, with CONFIG_RANDOMIZE_BASE=y all the same. So the address
# The kernel is at a random address (KASLR). Until 2026-11-19 the machine entered a vmlinux
# through PVH that could not move, and the kernel ran where it was linked, ffffffff81000000, with
# CONFIG_RANDOMIZE_BASE=y all the same. The vmlinux entered now moves itself (#645), and
# boot:kaslr asks where across boots; this asks one boot. So the address
# is asked of the kernel: _text, readable to root once kptr_restrict is 0, and not the linked
# one. A randomized kernel lands on that one 2 MiB slot about once in 480 boots (the slots of a
# 1 GiB kernel image space, less the first 16 MiB and the kernel's own size), so a failure here
Expand Down
6 changes: 3 additions & 3 deletions cmd/spin-machine-dev/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ every one when none is named, with what a named part is made with.
A part is built when it is missing or stale. Each one leaves a manifest in _output/manifest naming a
digest of its inputs - the build arguments versions.yaml gives its Dockerfile and every file under
its directory - and one whose inputs have not moved, and whose output still verifies, is left as it
is. Every part is verified after it is built: the binaries run here, the kernel is a relocatable
bzImage, the tools are the pinned version (verify says what each checks).
is. Every part is verified after it is built: the binaries run here, the kernel is a vmlinux that
randomizes itself, the tools are the pinned version (verify says what each checks).

In a workflow it writes what each part is to the run's summary, and qemu_version to the step's
outputs.`,
Expand Down Expand Up @@ -172,7 +172,7 @@ func verifyCmd() *cobra.Command {
the machine type every checkpoint is saved on (a newer one is said, not failed), and
the TCG binary's query-qmp-schema has every QMP command and event the module
defines, as the module defines it
kernel a bzImage whose setup header says relocatable, and the vmlinux it was made from
kernel a vmlinux with both Xen notes and a filled .data.reloc, and a relocatable bzImage
e2fsprogs the four tools and mke2fs.conf, and mkfs.ext4 answers the pinned version
systemd the packages the image installs
openssh the packages the image installs
Expand Down
22 changes: 9 additions & 13 deletions cmd/spin-machine-dev/edges_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,34 +17,30 @@ import (
"github.com/spf13/cobra"

"github.com/spin-stack/machine/internal/build"
"github.com/spin-stack/machine/internal/elftest"
"github.com/spin-stack/machine/machine"
)

// kernelFixture is a relocatable bzImage and a vmlinux carrying a Xen note, as kernel/Dockerfile
// kernelFixture is a relocatable bzImage and a vmlinux that randomizes itself, as kernel/Dockerfile
// leaves them.
func kernelFixture(t *testing.T, out string) {
t.Helper()
bz := make([]byte, 0x300)
copy(bz[0x202:], "HdrS")
bz[0x234] = 1
put(t, filepath.Join(out, "kernel/bzImage"), string(bz), 0o644)
var note bytes.Buffer
_ = binary.Write(&note, binary.LittleEndian, []uint32{4, 4, 18})
note.WriteString("Xen\x00\x00\x00\x00\x01")
var b bytes.Buffer
h := elf.Header64{Type: uint16(elf.ET_EXEC), Machine: uint16(elf.EM_X86_64), Version: uint32(elf.EV_CURRENT),
Phoff: 64, Ehsize: 64, Phentsize: 56, Phnum: 1, Shentsize: 64}
copy(h.Ident[:], elf.ELFMAG)
h.Ident[elf.EI_CLASS], h.Ident[elf.EI_DATA], h.Ident[elf.EI_VERSION] = byte(elf.ELFCLASS64), byte(elf.ELFDATA2LSB), byte(elf.EV_CURRENT)
_ = binary.Write(&b, binary.LittleEndian, h)
_ = binary.Write(&b, binary.LittleEndian, elf.Prog64{Type: uint32(elf.PT_NOTE), Off: 120, Filesz: uint64(note.Len()), Memsz: uint64(note.Len())})
b.Write(note.Bytes())
put(t, filepath.Join(out, "kernel/vmlinux"), b.String(), 0o644)
put(t, filepath.Join(out, "kernel/vmlinux"), string(vmlinuxFixture()), 0o644)
for _, f := range []string{"kernel/kernel-config", "kernel/sources", "kernel/patches/0001-k.patch"} {
put(t, filepath.Join(out, f), f, 0o644)
}
}

// vmlinuxFixture is a vmlinux that verify kernel takes for one that randomizes itself: both Xen
// notes and a filled .data.reloc.
func vmlinuxFixture() []byte {
return elftest.Kernel([]uint32{18, 19}, []byte{0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0x10, 0, 0, 0})
}

// everything is a whole built _output: what every part's build leaves, and spin-machine.
func everything(t *testing.T, dir string) string {
t.Helper()
Expand Down
22 changes: 20 additions & 2 deletions cmd/spin-machine-dev/patched.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,29 @@ in <out>/patched/<part>. Parts: ` + strings.Join(patched.Names(), ", ") + `.`,
say(c, "%s: %s", p.Name, filepath.Join(dir, "src"))
return nil
},
}, &cobra.Command{
Use: "prepare <part>",
Short: "Build what compiling a part's touched C files needs, before an analysis traces the compiler",
Long: `Build in <out>/patched/<part>/src, which tree made, what compile needs, so that only the touched
files are compiled under CodeQL's tracer: the kernel configured from kernel/, with its bzImage when
a touched file is one only the bzImage builds. codeql.yml runs it before the tracer starts.`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
w, p, dir, err := patchedPart(args[0])
if err != nil {
return err
}
if err := patched.Prepare(c.Context(), w.root, p, dir, c.ErrOrStderr()); err != nil {
return couldNot(err)
}
say(c, "%s: prepared", p.Name)
return nil
},
}, &cobra.Command{
Use: "compile <part>",
Short: "Compile the C files a part's patches touch in its tree, for an analysis tracing the compiler",
Long: `Compile the C files the part's patches touch in <out>/patched/<part>/src, which tree made, as
the part's build would: the kernel from its configuration in kernel/, QEMU for x86_64-softmmu.
Long: `Compile the C files the part's patches touch in <out>/patched/<part>/src, which prepare readied,
as the part's build would: the kernel from its configuration in kernel/, QEMU for x86_64-softmmu.
codeql.yml runs it under CodeQL's tracer for the parts whose files include headers only their
builds generate. Parts that have it: ` + strings.Join(traced(), ", ") + `.`,
Args: cobra.ExactArgs(1),
Expand Down
3 changes: 3 additions & 0 deletions cmd/spin-machine-dev/patched_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ func TestPatchedCompileRefusesAPartWithNothingToCompile(t *testing.T) {
if _, stderr, status := verb(t, "patched", "compile", "qboot"); status != 2 || !strings.Contains(stderr, "without a build") {
t.Errorf("status %d, %s", status, stderr)
}
if _, stderr, status := verb(t, "patched", "prepare", "qboot"); status != 2 || !strings.Contains(stderr, "nothing to prepare") {
t.Errorf("prepare: status %d, %s", status, stderr)
}
}

func TestPatchedCompileNamesThePartsItCompiles(t *testing.T) {
Expand Down
12 changes: 11 additions & 1 deletion cmd/spin-machine-dev/verbs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -206,14 +207,23 @@ func kernelDocker(extra string) string {
mkdir -p "$dest/kernel"; head -c 1024 /dev/zero > "$dest/kernel/bzImage"
printf HdrS | dd of="$dest/kernel/bzImage" bs=1 seek=514 conv=notrunc 2>/dev/null
printf '\001' | dd of="$dest/kernel/bzImage" bs=1 seek=564 conv=notrunc 2>/dev/null
cp /proc/self/exe "$dest/kernel/vmlinux"
printf '` + printfEscaped(vmlinuxFixture()) + `' > "$dest/kernel/vmlinux"
if [ "$lockdown" = none ]; then
printf '# CONFIG_LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY is not set\nCONFIG_LOCK_DOWN_KERNEL_FORCE_NONE=y\nCONFIG_BPF_LSM=y\n` + extra + `' > "$dest/kernel/kernel-config"
else
printf 'CONFIG_LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY=y\n# CONFIG_LOCK_DOWN_KERNEL_FORCE_NONE is not set\nCONFIG_BPF_LSM=y\n' > "$dest/kernel/kernel-config"
fi`
}

// printfEscaped is b as a printf format of octal escapes, which sh's printf writes back as b.
func printfEscaped(b []byte) string {
var s strings.Builder
for _, c := range b {
fmt.Fprintf(&s, "\\%03o", c)
}
return s.String()
}

// The traceable kernel is the release kernel with lockdown forced to none and nothing else: it is
// put beside the release only then, and an option that moved with it is refused by name.
func TestTheTraceableKernelIsTheReleaseKernelLessLockdown(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion cmd/spin-machine/commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func TestFlagsAreTheSpec(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), "not a bzImage") {
if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), "neither a bzImage") {
t.Errorf("a --kernel that is not a bzImage: %v", err)
}
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/spin-machine/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ type machineFlags struct {
func (o *machineFlags) register(fs *flag.FlagSet) {
fs.StringVar(&o.release, "release", "_output", "an unpacked release tree; every path below defaults out of it")
fs.StringVar(&o.qemu, "qemu", "", "QEMU binary (default: <release>/bin/qemu-system-x86_64)")
fs.StringVar(&o.kernel, "kernel", "", "kernel image, a bzImage (default: <release>/kernel/bzImage)")
fs.StringVar(&o.kernel, "kernel", "", "kernel image, a vmlinux entered through PVH or a bzImage (default: the one the release boots, its vmlinux when it randomizes itself)")
fs.StringVar(&o.initrd, "initrd", "", "initrd (default: none)")
fs.StringVar(&o.firmware, "firmware", "", "firmware directory (default: <release>/qemu)")
fs.StringVar(&o.bios, "bios", "", "the BIOS, a file in the firmware directory (default: "+machine.DefaultBIOS+"; bios-256k.bin is SeaBIOS)")
Expand Down
Loading
Loading