m/p/efivarfs: refactor

This accomplishes three things:

First, split out the variable access layer from the rest of the code.
This cleans up the attribute handling, which is now done centrally as
well as making the high-level functions very short and clean. They now
also return better errors.

Second this introduces proper types for LoadOption, which can now also
be unmarshaled which was a requirement for A/B updates. This required
implementation of EFI's DevicePath structure.
While refactoring the higher-level functions for this, this also
fixes a bug where the variable index (the 4 hex nibbles at the end) were
improperly generated as lowercase hex.

Third, this adds new high-level functions for interacting with more
boot-related variables needed for the A/B effort.

Change-Id: I53490fa4898a5e7a5498ecc05a9078bd2d66c26e
Reviewed-on: https://review.monogon.dev/c/monogon/+/1855
Tested-by: Jenkins CI
Reviewed-by: Serge Bazanski <serge@monogon.tech>
diff --git a/cloud/agent/install.go b/cloud/agent/install.go
index e05a57c..656f258 100644
--- a/cloud/agent/install.go
+++ b/cloud/agent/install.go
@@ -120,7 +120,7 @@
 	if err != nil {
 		return err
 	}
-	bootEntryIdx, err := efivarfs.CreateBootEntry(be)
+	bootEntryIdx, err := efivarfs.AddBootEntry(be)
 	if err != nil {
 		return fmt.Errorf("error creating EFI boot entry: %w", err)
 	}
diff --git a/metropolis/installer/main.go b/metropolis/installer/main.go
index 7dc1da9..2515f53 100644
--- a/metropolis/installer/main.go
+++ b/metropolis/installer/main.go
@@ -315,7 +315,7 @@
 	}
 
 	// Create an EFI boot entry for Metropolis.
-	en, err := efivarfs.CreateBootEntry(be)
+	en, err := efivarfs.AddBootEntry(be)
 	if err != nil {
 		panicf("While creating a boot entry: %v", err)
 	}
diff --git a/metropolis/node/build/mkimage/osimage/osimage.go b/metropolis/node/build/mkimage/osimage/osimage.go
index d730e68..97fa7c0 100644
--- a/metropolis/node/build/mkimage/osimage/osimage.go
+++ b/metropolis/node/build/mkimage/osimage/osimage.go
@@ -302,7 +302,7 @@
 // argument. In case a regular file already exists at params.OutputPath,
 // the function will fail. It returns nil on success or an error, if one
 // did occur.
-func Create(params *Params) (*efivarfs.BootEntry, error) {
+func Create(params *Params) (*efivarfs.LoadOption, error) {
 	// Validate each parameter before use.
 	if params.OutputPath == "" {
 		return nil, fmt.Errorf("image output path must be set")
@@ -377,13 +377,19 @@
 	if err != nil {
 		return nil, fmt.Errorf("couldn't parse the GPT GUID: %w", err)
 	}
-	be := efivarfs.BootEntry{
-		Description:     "Metropolis",
-		Path:            EFIPayloadPath,
-		PartitionGUID:   guid,
-		PartitionNumber: 1,
-		PartitionStart:  esp.Start,
-		PartitionSize:   esp.End - esp.Start + 1,
+	be := efivarfs.LoadOption{
+		Description: "Metropolis",
+		FilePath: efivarfs.DevicePath{
+			&efivarfs.HardDrivePath{
+				PartitionNumber:     1,
+				PartitionStartBlock: esp.Start,
+				PartitionSizeBlocks: esp.End - esp.Start + 1,
+				PartitionMatch: efivarfs.PartitionGPT{
+					PartitionUUID: guid,
+				},
+			},
+			efivarfs.FilePath(EFIPayloadPath),
+		},
 	}
 	// Close the image and return the EFI boot entry.
 	if err := diskImg.File.Close(); err != nil {
diff --git a/metropolis/pkg/efivarfs/BUILD.bazel b/metropolis/pkg/efivarfs/BUILD.bazel
index 33b0685..3e5339c 100644
--- a/metropolis/pkg/efivarfs/BUILD.bazel
+++ b/metropolis/pkg/efivarfs/BUILD.bazel
@@ -1,17 +1,32 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library")
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
 
 go_library(
     name = "efivarfs",
     srcs = [
         "boot.go",
+        "devicepath.go",
         "efivarfs.go",
-        "format.go",
+        "variables.go",
     ],
     importpath = "source.monogon.dev/metropolis/pkg/efivarfs",
     visibility = ["//visibility:public"],
     deps = [
+        "//metropolis/pkg/msguid",
         "@com_github_google_uuid//:uuid",
         "@org_golang_x_text//encoding/unicode",
-        "@org_golang_x_text//transform",
+    ],
+)
+
+go_test(
+    name = "efivarfs_test",
+    srcs = [
+        "boot_test.go",
+        "devicepath_test.go",
+    ],
+    embed = [":efivarfs"],
+    gc_goopts = ["-d=libfuzzer"],
+    deps = [
+        "@com_github_google_go_cmp//cmp",
+        "@com_github_google_uuid//:uuid",
     ],
 )
diff --git a/metropolis/pkg/efivarfs/boot.go b/metropolis/pkg/efivarfs/boot.go
index 4178c8d..92b8ac9 100644
--- a/metropolis/pkg/efivarfs/boot.go
+++ b/metropolis/pkg/efivarfs/boot.go
@@ -24,159 +24,121 @@
 package efivarfs
 
 import (
+	"bytes"
+	"encoding/binary"
+	"errors"
 	"fmt"
 	"math"
 	"strings"
-
-	"github.com/google/uuid"
-	"golang.org/x/text/transform"
 )
 
-// Note on binary format of EFI variables:
-// This code follows Section 3 "Boot Manager" of version 2.6 of the UEFI Spec:
-// http://www.uefi.org/sites/default/files/resources/UEFI%20Spec%202_6.pdf
-// It uses the binary representation from the Linux "efivars" filesystem.
-// Specifically, all binary data that is marshaled and unmarshaled is preceded by
-// 4 bytes of "Variable Attributes".
-// All binary data must have exactly the correct length and may not be padded
-// with extra bytes while reading or writing.
+type LoadOptionCategory uint8
 
-// Note on EFI variable attributes:
-// This code ignores all EFI variable attributes when reading.
-// This code always writes variables with the following attributes:
-//   - EFI_VARIABLE_NON_VOLATILE (0x00000001)
-//   - EFI_VARIABLE_BOOTSERVICE_ACCESS (0x00000002)
-//   - EFI_VARIABLE_RUNTIME_ACCESS (0x00000004)
-const defaultAttrsByte0 uint8 = 7
+const (
+	// Boot entries belonging to the Boot category are normal boot entries.
+	LoadOptionCategoryBoot LoadOptionCategory = 0x0
+	// Boot entries belonging to the App category are not booted as part of
+	// the normal boot order, but are only launched via menu or hotkey.
+	// This category is optional for bootloaders to support, before creating
+	// new boot entries of this category firmware support needs to be
+	// confirmed.
+	LoadOptionCategoryApp LoadOptionCategory = 0x1
+)
 
-// BootEntry represents a subset of the contents of a Boot#### EFI variable.
-type BootEntry struct {
-	Description     string // eg. "Linux Boot Manager"
-	Path            string // eg. `\EFI\systemd\systemd-bootx64.efi`
-	PartitionGUID   uuid.UUID
-	PartitionNumber uint32 // Starts with 1
-	PartitionStart  uint64 // LBA
-	PartitionSize   uint64 // LBA
+// LoadOption contains information on a payload to be loaded by EFI.
+type LoadOption struct {
+	// Human-readable description of what this load option loads.
+	// This is what's being shown by the firmware when selecting a boot option.
+	Description string
+	// If set, firmware will skip this load option when it is in BootOrder.
+	// It is unspecificed whether this prevents the user from booting the entry
+	// manually.
+	Inactive bool
+	// If set, this load option will not be shown in any menu for load option
+	// selection. This does not affect other functionality.
+	Hidden bool
+	// Category contains the category of the load entry. The selected category
+	// affects various firmware behaviors, see the individual value
+	// descriptions for more information.
+	Category LoadOptionCategory
+	// Path to the UEFI PE executable to execute when this load option is being
+	// loaded.
+	FilePath DevicePath
+	// OptionalData gets passed as an argument to the executed PE executable.
+	// If zero-length a NULL value is passed to the executable.
+	OptionalData []byte
 }
 
-// Marshal generates the binary representation of a BootEntry (EFI_LOAD_OPTION).
-// Description, DiskGUID and Path must be set.
-// Attributes of the boot entry (EFI_LOAD_OPTION.Attributes, not the same
-// as attributes of an EFI variable) are always set to LOAD_OPTION_ACTIVE.
-func (t *BootEntry) Marshal() ([]byte, error) {
-	if t.Description == "" ||
-		t.PartitionGUID.String() == "00000000-0000-0000-0000-000000000000" ||
-		t.Path == "" ||
-		t.PartitionNumber == 0 ||
-		t.PartitionStart == 0 ||
-		t.PartitionSize == 0 {
-		return nil, fmt.Errorf("missing field, all are required: %+v", *t)
+// Marshal encodes a LoadOption into a binary EFI_LOAD_OPTION.
+func (e *LoadOption) Marshal() ([]byte, error) {
+	var data []byte
+	var attrs uint32
+	attrs |= (uint32(e.Category) & 0x1f) << 8
+	if e.Hidden {
+		attrs |= 0x08
 	}
-
-	// EFI_LOAD_OPTION.FilePathList
-	var dp []byte
-
-	// EFI_LOAD_OPTION.FilePathList[0]
-	dp = append(dp,
-		0x04,       // Type ("Media Device Path")
-		0x01,       // Sub-Type ("Hard Drive")
-		0x2a, 0x00, // Length (always 42 bytes for this type)
-	)
-	dp = append32(dp, t.PartitionNumber)
-	dp = append64(dp, t.PartitionStart)
-	dp = append64(dp, t.PartitionSize)
-	// Append the partition GUID in the EFI format.
-	dp = append(dp, MarshalEFIGUID(t.PartitionGUID)...)
-
-	dp = append(dp,
-		0x02, // Partition Format ("GUID Partition Table")
-		0x02, // Signature Type ("GUID signature")
-	)
-
-	// EFI_LOAD_OPTION.FilePathList[1]
-	enc := Encoding.NewEncoder()
-	bsp := strings.ReplaceAll(t.Path, "/", "\\")
-	path, _, e := transform.Bytes(enc, []byte(bsp))
-	if e != nil {
-		return nil, fmt.Errorf("while encoding Path: %v", e)
+	if !e.Inactive {
+		attrs |= 0x01
 	}
-	path = append16(path, 0) // null terminate string
-	filePathLen := len(path) + 4
-	dp = append(dp,
-		0x04, // Type ("Media Device Path")
-		0x04, // Sub-Type ("File Path")
-	)
-	dp = append16(dp, uint16(filePathLen))
-	dp = append(dp, path...)
-
-	// EFI_LOAD_OPTION.FilePathList[2] ("Device Path End Structure")
-	dp = append(dp,
-		0x7F,       // Type ("End of Hardware Device Path")
-		0xFF,       // Sub-Type ("End Entire Device Path")
-		0x04, 0x00, // Length (always 4 bytes for this type)
-	)
-
-	out := []byte{
-		// EFI variable attributes
-		defaultAttrsByte0, 0x00, 0x00, 0x00,
-
-		// EFI_LOAD_OPTION.Attributes (only LOAD_OPTION_ACTIVE)
-		0x01, 0x00, 0x00, 0x00,
+	data = append32(data, attrs)
+	filePathRaw, err := e.FilePath.Marshal()
+	if err != nil {
+		return nil, fmt.Errorf("failed marshalling FilePath: %w", err)
 	}
-
-	// EFI_LOAD_OPTION.FilePathListLength
-	if len(dp) > math.MaxUint16 {
-		// No need to also check for overflows for Path length field explicitly,
-		// since if that overflows, this field will definitely overflow as well.
-		// There is no explicit length field for Description, so no special
-		// handling is required.
-		return nil, fmt.Errorf("variable too large, use shorter strings")
+	if len(filePathRaw) > math.MaxUint16 {
+		return nil, fmt.Errorf("failed marshalling FilePath: value too big (%d)", len(filePathRaw))
 	}
-	out = append16(out, uint16(len(dp)))
-
-	// EFI_LOAD_OPTION.Description
-	desc, _, e := transform.Bytes(enc, []byte(t.Description))
-	if e != nil {
-		return nil, fmt.Errorf("while encoding Description: %v", e)
+	data = append16(data, uint16(len(filePathRaw)))
+	if strings.IndexByte(e.Description, 0x00) != -1 {
+		return nil, fmt.Errorf("failed to encode Description: contains invalid null bytes")
 	}
-	desc = append16(desc, 0) // null terminate string
-	out = append(out, desc...)
-
-	// EFI_LOAD_OPTION.FilePathList
-	out = append(out, dp...)
-
-	// EFI_LOAD_OPTION.OptionalData is always empty
-
-	return out, nil
+	encodedDesc, err := Encoding.NewEncoder().Bytes([]byte(e.Description))
+	if err != nil {
+		return nil, fmt.Errorf("failed to encode Description: %w", err)
+	}
+	data = append(data, encodedDesc...)
+	data = append(data, 0x00, 0x00) // Final UTF-16/UCS-2 null code
+	data = append(data, filePathRaw...)
+	data = append(data, e.OptionalData...)
+	return data, nil
 }
 
-// UnmarshalBootEntry loads a BootEntry from its binary representation.
-// WARNING: UnmarshalBootEntry only loads the Description field.
-// Everything else is ignored (and not validated if possible)
-func UnmarshalBootEntry(d []byte) (*BootEntry, error) {
-	descOffset := 4 /* EFI Var Attrs */ + 4 /* EFI_LOAD_OPTION.Attributes */ + 2 /*FilePathListLength*/
-	if len(d) < descOffset {
-		return nil, fmt.Errorf("too short: %v bytes", len(d))
+// UnmarshalLoadOption decodes a binary EFI_LOAD_OPTION into a LoadOption.
+func UnmarshalLoadOption(data []byte) (*LoadOption, error) {
+	if len(data) < 6 {
+		return nil, fmt.Errorf("invalid load option: minimum 6 bytes are required, got %d", len(data))
 	}
-	descBytes := []byte{}
-	var foundNull bool
-	for i := descOffset; i+1 < len(d); i += 2 {
-		a := d[i]
-		b := d[i+1]
-		if a == 0 && b == 0 {
-			foundNull = true
-			break
-		}
-		descBytes = append(descBytes, a, b)
+	var opt LoadOption
+	attrs := binary.LittleEndian.Uint32(data[:4])
+	opt.Category = LoadOptionCategory((attrs >> 8) & 0x1f)
+	opt.Hidden = attrs&0x08 != 0
+	opt.Inactive = attrs&0x01 == 0
+	lenPath := binary.LittleEndian.Uint16(data[4:6])
+	// Search for UTF-16 null code
+	nullIdx := bytes.Index(data[6:], []byte{0x00, 0x00})
+	if nullIdx == -1 {
+		return nil, errors.New("no null code point marking end of Description found")
 	}
-	if !foundNull {
-		return nil, fmt.Errorf("didn't find null terminator for Description")
+	descriptionEnd := 6 + nullIdx + 1
+	descriptionRaw := data[6:descriptionEnd]
+	description, err := Encoding.NewDecoder().Bytes(descriptionRaw)
+	if err != nil {
+		return nil, fmt.Errorf("error decoding UTF-16 in Description: %w", err)
 	}
-	descDecoded, _, e := transform.Bytes(Encoding.NewDecoder(), descBytes)
-	if e != nil {
-		return nil, fmt.Errorf("while decoding Description: %v", e)
+	descriptionEnd += 2 // 2 null bytes terminating UTF-16 string
+	opt.Description = string(description)
+	if descriptionEnd+int(lenPath) > len(data) {
+		return nil, fmt.Errorf("declared length of FilePath (%d) overruns available data (%d)", lenPath, len(data)-descriptionEnd)
 	}
-	return &BootEntry{Description: string(descDecoded)}, nil
+	filePathData := data[descriptionEnd : descriptionEnd+int(lenPath)]
+	opt.FilePath, err = UnmarshalDevicePath(filePathData)
+	if err != nil {
+		return nil, fmt.Errorf("failed unmarshaling FilePath: %w", err)
+	}
+	if descriptionEnd+int(lenPath) < len(data) {
+		opt.OptionalData = data[descriptionEnd+int(lenPath):]
+	}
+	return &opt, nil
 }
 
 // BootOrder represents the contents of the BootOrder EFI variable.
@@ -184,7 +146,7 @@
 
 // Marshal generates the binary representation of a BootOrder.
 func (t *BootOrder) Marshal() []byte {
-	out := []byte{defaultAttrsByte0, 0x00, 0x00, 0x00}
+	var out []byte
 	for _, v := range *t {
 		out = append16(out, v)
 	}
@@ -193,10 +155,10 @@
 
 // UnmarshalBootOrder loads a BootOrder from its binary representation.
 func UnmarshalBootOrder(d []byte) (*BootOrder, error) {
-	if len(d) < 4 || len(d)%2 != 0 {
+	if len(d)%2 != 0 {
 		return nil, fmt.Errorf("invalid length: %v bytes", len(d))
 	}
-	l := (len(d) - 4) / 2
+	l := len(d) / 2
 	out := make(BootOrder, l)
 	for i := 0; i < l; i++ {
 		out[i] = uint16(d[4+2*i]) | uint16(d[4+2*i+1])<<8
@@ -219,16 +181,3 @@
 		byte(v>>24&0xFF),
 	)
 }
-
-func append64(d []byte, v uint64) []byte {
-	return append(d,
-		byte(v&0xFF),
-		byte(v>>8&0xFF),
-		byte(v>>16&0xFF),
-		byte(v>>24&0xFF),
-		byte(v>>32&0xFF),
-		byte(v>>40&0xFF),
-		byte(v>>48&0xFF),
-		byte(v>>56&0xFF),
-	)
-}
diff --git a/metropolis/pkg/efivarfs/boot_test.go b/metropolis/pkg/efivarfs/boot_test.go
new file mode 100644
index 0000000..9abd8f9
--- /dev/null
+++ b/metropolis/pkg/efivarfs/boot_test.go
@@ -0,0 +1,58 @@
+package efivarfs
+
+import (
+	"bytes"
+	"encoding/hex"
+	"testing"
+
+	"github.com/google/go-cmp/cmp"
+	"github.com/google/uuid"
+)
+
+// Generated with old working marshaler and manually double-checked
+var ref, _ = hex.DecodeString(
+	"010000004a004500780061006d0070006c006500000004012a00010000000" +
+		"500000000000000080000000000000014b8a76bad9dd11180b400c04fd430" +
+		"c8020204041c005c0074006500730074005c0061002e00650066006900000" +
+		"07fff0400",
+)
+
+func TestEncoding(t *testing.T) {
+	opt := LoadOption{
+		Description: "Example",
+		FilePath: DevicePath{
+			&HardDrivePath{
+				PartitionNumber:     1,
+				PartitionStartBlock: 5,
+				PartitionSizeBlocks: 8,
+				PartitionMatch: PartitionGPT{
+					PartitionUUID: uuid.NameSpaceX500,
+				},
+			},
+			FilePath("/test/a.efi"),
+		},
+	}
+	got, err := opt.Marshal()
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !bytes.Equal(ref, got) {
+		t.Fatalf("expected %x, got %x", ref, got)
+	}
+	got2, err := UnmarshalLoadOption(got)
+	if err != nil {
+		t.Fatalf("failed to unmarshal marshaled LoadOption: %v", err)
+	}
+	diff := cmp.Diff(&opt, got2)
+	if diff != "" {
+		t.Errorf("marshal/unmarshal wasn't transparent: %v", diff)
+	}
+}
+
+func FuzzDecode(f *testing.F) {
+	f.Add(ref)
+	f.Fuzz(func(t *testing.T, a []byte) {
+		// Just try to see if it crashes
+		_, _ = UnmarshalLoadOption(a)
+	})
+}
diff --git a/metropolis/pkg/efivarfs/devicepath.go b/metropolis/pkg/efivarfs/devicepath.go
new file mode 100644
index 0000000..1606fd6
--- /dev/null
+++ b/metropolis/pkg/efivarfs/devicepath.go
@@ -0,0 +1,323 @@
+package efivarfs
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"math"
+	"strings"
+
+	"github.com/google/uuid"
+
+	"source.monogon.dev/metropolis/pkg/msguid"
+)
+
+// DevicePath represents a path consisting of one or more elements to an
+// entity implementing an EFI protocol. It's very broadly used inside EFI
+// for representing all sorts of abstract paths. In the context of this
+// package it is used to represent paths to EFI loaders.
+// See https://uefi.org/specs/UEFI/2.10/10_Protocols_Device_Path_Protocol.html
+// for more information.
+type DevicePath []DevicePathElem
+
+// DevicePathElem is a common interface for all UEFI device path elements.
+type DevicePathElem interface {
+	typ() uint8
+	subType() uint8
+	data() ([]byte, error)
+}
+
+type pathElemUnmarshalFunc func([]byte) (DevicePathElem, error)
+
+// PartitionMBR matches a drive or partition formatted with legacy MBR
+// (Master Boot Record).
+type PartitionMBR struct {
+	// DiskSignature contains a 4-byte signature identifying the drive, located
+	// just after the 440 bytes of boot sector loading code.
+	// Note that since MBR does not have per-partition signatures, this is
+	// combined with PartitionNumber to select a partition.
+	DiskSignature [4]byte
+}
+
+func (p PartitionMBR) partitionSignature() (sig [16]byte) {
+	copy(sig[:4], p.DiskSignature[:])
+	return
+}
+
+func (p PartitionMBR) partitionFormat() uint8 {
+	return 0x01
+}
+
+func (p PartitionMBR) signatureType() uint8 {
+	return 0x01
+}
+
+// PartitionGPT matches a partition on a drive formatted with GPT.
+type PartitionGPT struct {
+	// UUID of the partition to be matched. Conversion into mixed-endian format
+	// is taken care of, a standard big-endian UUID can be put in here.
+	PartitionUUID uuid.UUID
+}
+
+func (p PartitionGPT) partitionSignature() [16]byte {
+	return msguid.From(p.PartitionUUID)
+}
+
+func (p PartitionGPT) partitionFormat() uint8 {
+	return 0x02
+}
+
+func (p PartitionGPT) signatureType() uint8 {
+	return 0x02
+}
+
+// PartitionUnknown is being used to represent unknown partitioning schemas or
+// combinations of PartitionFormat/SignatureType. It contains raw uninterpreted
+// data.
+type PartitionUnknown struct {
+	PartitionSignature [16]byte
+	PartitionFormat    uint8
+	SignatureType      uint8
+}
+
+func (p PartitionUnknown) partitionSignature() [16]byte {
+	return p.PartitionSignature
+}
+
+func (p PartitionUnknown) partitionFormat() uint8 {
+	return p.PartitionFormat
+}
+
+func (p PartitionUnknown) signatureType() uint8 {
+	return p.SignatureType
+}
+
+type PartitionMatch interface {
+	partitionSignature() [16]byte
+	partitionFormat() uint8
+	signatureType() uint8
+}
+
+// HardDrivePath matches whole drives or partitions on GPT/MBR formatted
+// drives.
+type HardDrivePath struct {
+	// Partition number, starting at 1. If zero or unset, the whole drive is
+	// selected.
+	PartitionNumber uint32
+	// Block address at which the partition starts. Not used for matching
+	// partitions in EDK2.
+	PartitionStartBlock uint64
+	// Number of blocks occupied by the partition starting from the
+	// PartitionStartBlock. Not used for matching partitions in EDK2.
+	PartitionSizeBlocks uint64
+	// PartitionMatch is used to match drive or partition signatures.
+	// Use PartitionMBR and PartitionGPT types here.
+	PartitionMatch PartitionMatch
+}
+
+func (h *HardDrivePath) typ() uint8 {
+	return 4
+}
+
+func (h *HardDrivePath) subType() uint8 {
+	return 1
+}
+
+func (h *HardDrivePath) data() ([]byte, error) {
+	out := make([]byte, 38)
+	le := binary.LittleEndian
+	le.PutUint32(out[0:4], h.PartitionNumber)
+	le.PutUint64(out[4:12], h.PartitionStartBlock)
+	le.PutUint64(out[12:20], h.PartitionSizeBlocks)
+	if h.PartitionMatch == nil {
+		return nil, errors.New("PartitionMatch needs to be set")
+	}
+	sig := h.PartitionMatch.partitionSignature()
+	copy(out[20:36], sig[:])
+	out[36] = h.PartitionMatch.partitionFormat()
+	out[37] = h.PartitionMatch.signatureType()
+	return out, nil
+}
+
+func unmarshalHardDrivePath(data []byte) (DevicePathElem, error) {
+	var h HardDrivePath
+	if len(data) != 38 {
+		return nil, fmt.Errorf("invalid HardDrivePath element, expected 38 bytes, got %d", len(data))
+	}
+	le := binary.LittleEndian
+	h.PartitionNumber = le.Uint32(data[0:4])
+	h.PartitionStartBlock = le.Uint64(data[4:12])
+	h.PartitionSizeBlocks = le.Uint64(data[12:20])
+	partitionFormat := data[36]
+	signatureType := data[37]
+	var rawSig [16]byte
+	copy(rawSig[:], data[20:36])
+	switch {
+	case partitionFormat == 1 && signatureType == 1:
+		// MBR
+		var mbr PartitionMBR
+		copy(mbr.DiskSignature[:], rawSig[:4])
+		h.PartitionMatch = mbr
+	case partitionFormat == 2 && signatureType == 2:
+		// GPT
+		h.PartitionMatch = PartitionGPT{
+			PartitionUUID: msguid.To(rawSig),
+		}
+	default:
+		// Unknown
+		h.PartitionMatch = PartitionUnknown{
+			PartitionSignature: rawSig,
+			PartitionFormat:    partitionFormat,
+			SignatureType:      signatureType,
+		}
+	}
+	return &h, nil
+}
+
+// FilePath contains a backslash-separated path or part of a path to a file on
+// a filesystem.
+type FilePath string
+
+func (f FilePath) typ() uint8 {
+	return 4
+}
+
+func (f FilePath) subType() uint8 {
+	return 4
+}
+
+func (f FilePath) data() ([]byte, error) {
+	if strings.IndexByte(string(f), 0x00) != -1 {
+		return nil, fmt.Errorf("contains invalid null bytes")
+	}
+	withBackslashes := bytes.ReplaceAll([]byte(f), []byte(`/`), []byte(`\`))
+	out, err := Encoding.NewEncoder().Bytes(withBackslashes)
+	if err != nil {
+		return nil, fmt.Errorf("failed to encode FilePath to UTF-16: %w", err)
+	}
+	return append(out, 0x00, 0x00), nil
+}
+
+func unmarshalFilePath(data []byte) (DevicePathElem, error) {
+	if len(data) < 2 {
+		return nil, fmt.Errorf("FilePath must be at least 2 bytes because of UTF-16 null terminator")
+	}
+	out, err := Encoding.NewDecoder().Bytes(data)
+	if err != nil {
+		return nil, fmt.Errorf("error decoding FilePath UTF-16 string: %w", err)
+	}
+	nullIdx := bytes.IndexByte(out, 0x00)
+	if nullIdx != len(out)-1 {
+		return nil, fmt.Errorf("FilePath not properly null-terminated")
+	}
+	withoutBackslashes := strings.Replace(string(out[:len(out)-1]), `\`, `/`, -1)
+	return FilePath(withoutBackslashes), nil
+}
+
+// Map key contains type and subtype
+var pathElementUnmarshalMap = map[[2]byte]pathElemUnmarshalFunc{
+	{4, 1}: unmarshalHardDrivePath,
+	{4, 4}: unmarshalFilePath,
+}
+
+// UnknownPath is a generic structure for all types of path elements not
+// understood by this library. The UEFI-specified set of path element
+// types is vast and mostly unused, this generic type allows for parsing as
+// well as pass-through of not-understood path elements.
+type UnknownPath struct {
+	TypeVal    uint8
+	SubTypeVal uint8
+	DataVal    []byte
+}
+
+func (u UnknownPath) typ() uint8 {
+	return u.TypeVal
+}
+
+func (u UnknownPath) subType() uint8 {
+	return u.SubTypeVal
+}
+
+func (u UnknownPath) data() ([]byte, error) {
+	return u.DataVal, nil
+}
+
+// Marshal encodes the device path in binary form.
+func (d DevicePath) Marshal() ([]byte, error) {
+	var buf []byte
+	for _, p := range d {
+		buf = append(buf, p.typ(), p.subType())
+		elemBuf, err := p.data()
+		if err != nil {
+			return nil, fmt.Errorf("failed marshaling path element: %w", err)
+		}
+		// 4 is size of header which is included in length field
+		if len(elemBuf)+4 > math.MaxUint16 {
+			return nil, fmt.Errorf("path element payload over maximum size")
+		}
+		buf = append16(buf, uint16(len(elemBuf)+4))
+		buf = append(buf, elemBuf...)
+	}
+	// End of device path (Type 0x7f, SubType 0xFF)
+	buf = append(buf, 0x7f, 0xff, 0x04, 0x00)
+	return buf, nil
+}
+
+// UnmarshalDevicePath parses a binary device path.
+func UnmarshalDevicePath(data []byte) (DevicePath, error) {
+	rest := data
+	var p DevicePath
+	for {
+		if len(rest) < 4 {
+			if len(rest) != 0 {
+				return nil, fmt.Errorf("dangling bytes at the end of device path: %x", rest)
+			}
+			break
+		}
+		t := rest[0]
+		subT := rest[1]
+		dataLen := binary.LittleEndian.Uint16(rest[2:4])
+		if int(dataLen) > len(rest) {
+			return nil, fmt.Errorf("path element larger than rest of buffer: %d > %d", dataLen, len(rest))
+		}
+		if dataLen < 4 {
+			return nil, fmt.Errorf("path element must be at least 4 bytes (header), length indicates %d", dataLen)
+		}
+		elemData := rest[4:dataLen]
+		rest = rest[dataLen:]
+
+		unmarshal, ok := pathElementUnmarshalMap[[2]byte{t, subT}]
+		if !ok {
+			p = append(p, &UnknownPath{
+				TypeVal:    t,
+				SubTypeVal: subT,
+				DataVal:    elemData,
+			})
+			continue
+		}
+		elem, err := unmarshal(elemData)
+		if err != nil {
+			return nil, fmt.Errorf("failed decoding path element %d: %w", len(p), err)
+		}
+		p = append(p, elem)
+	}
+	var endOfPathIdx int
+	for i, e := range p {
+		if e.typ() == 0x7f && e.subType() == 0xff {
+			endOfPathIdx = i
+			break
+		}
+	}
+	switch {
+	case len(p) == 0:
+		return nil, errors.New("empty DevicePath without End Of Path element")
+	case endOfPathIdx == -1:
+		return nil, fmt.Errorf("got DevicePath with %d elements, but without End Of Path element", len(p))
+	case endOfPathIdx != len(p)-1:
+		return nil, fmt.Errorf("got DevicePath with %d elements with End Of Path element at %d (wanted as last element)", len(p), endOfPathIdx)
+	}
+	p = p[:len(p)-1]
+
+	return p, nil
+}
diff --git a/metropolis/pkg/efivarfs/devicepath_test.go b/metropolis/pkg/efivarfs/devicepath_test.go
new file mode 100644
index 0000000..b5823ac
--- /dev/null
+++ b/metropolis/pkg/efivarfs/devicepath_test.go
@@ -0,0 +1,89 @@
+package efivarfs
+
+import (
+	"bytes"
+	"testing"
+
+	"github.com/google/uuid"
+)
+
+func TestMarshalExamples(t *testing.T) {
+	cases := []struct {
+		name        string
+		path        DevicePath
+		expected    []byte
+		expectError bool
+	}{
+		{
+			name: "TestNone",
+			path: DevicePath{},
+			expected: []byte{
+				0x7f, 0xff, // End of HW device path
+				0x04, 0x00, // Length: 4 bytes
+			},
+		},
+		{
+			// From UEFI Device Path Examples, extracted single entry
+			name: "TestHD",
+			path: DevicePath{
+				&HardDrivePath{
+					PartitionNumber:     1,
+					PartitionStartBlock: 0x22,
+					PartitionSizeBlocks: 0x2710000,
+					PartitionMatch: PartitionGPT{
+						PartitionUUID: uuid.MustParse("15E39A00-1DD2-1000-8D7F-00A0C92408FC"),
+					},
+				},
+			},
+			expected: []byte{
+				0x04, 0x01, // Hard Disk type
+				0x2a, 0x00, // Length
+				0x01, 0x00, 0x00, 0x00, // Partition Number
+				0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Part Start
+				0x00, 0x00, 0x71, 0x02, 0x00, 0x00, 0x00, 0x00, // Part Size
+				0x00, 0x9a, 0xe3, 0x15, 0xd2, 0x1d, 0x00, 0x10,
+				0x8d, 0x7f, 0x00, 0xa0, 0xc9, 0x24, 0x08, 0xfc, // Signature
+				0x02,       // Part Format GPT
+				0x02,       // Signature GPT
+				0x7f, 0xff, // End of HW device path
+				0x04, 0x00, // Length: 4 bytes
+			},
+		},
+		{
+			name: "TestFilePath",
+			path: DevicePath{
+				FilePath("asdf"),
+			},
+			expected: []byte{
+				0x04, 0x04, // File Path type
+				0x0e, 0x00, // Length
+				'a', 0x00, 's', 0x00, 'd', 0x00, 'f', 0x00,
+				0x00, 0x00,
+				0x7f, 0xff, // End of HW device path
+				0x04, 0x00, // Length: 4 bytes
+			},
+		},
+	}
+
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			got, err := c.path.Marshal()
+			if err != nil && !c.expectError {
+				t.Fatalf("unexpected error: %v", err)
+			}
+			if err == nil && c.expectError {
+				t.Fatalf("expected error, got %x", got)
+			}
+			if err != nil && c.expectError {
+				// Do not compare result in case error is expected
+				return
+			}
+			if !bytes.Equal(got, c.expected) {
+				t.Fatalf("expected %x, got %x", c.expected, got)
+			}
+			if _, err := UnmarshalDevicePath(got); err != nil {
+				t.Errorf("failed to unmarshal value again: %v", err)
+			}
+		})
+	}
+}
diff --git a/metropolis/pkg/efivarfs/efivarfs.go b/metropolis/pkg/efivarfs/efivarfs.go
index 8132579..e751145 100644
--- a/metropolis/pkg/efivarfs/efivarfs.go
+++ b/metropolis/pkg/efivarfs/efivarfs.go
@@ -14,24 +14,36 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-// This package was written with the aim of easing efivarfs integration.
+// Package efivarfs provides functions to read and manipulate UEFI runtime
+// variables. It uses Linux's efivarfs [1] to access the variables and all
+// functions generally require that this is mounted at
+// "/sys/firmware/efi/efivars".
 //
-// https://www.kernel.org/doc/html/latest/filesystems/efivarfs.html
+// [1] https://www.kernel.org/doc/html/latest/filesystems/efivarfs.html
 package efivarfs
 
 import (
-	"bytes"
+	"encoding/binary"
+	"errors"
 	"fmt"
+	"io/fs"
 	"os"
-	"path/filepath"
+	"strings"
 
 	"github.com/google/uuid"
 	"golang.org/x/text/encoding/unicode"
 )
 
 const (
-	Path       = "/sys/firmware/efi/efivars"
-	GlobalGuid = "8be4df61-93ca-11d2-aa0d-00e098032b8c"
+	Path = "/sys/firmware/efi/efivars"
+)
+
+var (
+	// ScopeGlobal is the scope of variables defined by the EFI specification
+	// itself.
+	ScopeGlobal = uuid.MustParse("8be4df61-93ca-11d2-aa0d-00e098032b8c")
+	// ScopeSystemd is the scope of variables defined by Systemd/bootspec.
+	ScopeSystemd = uuid.MustParse("4a67b082-0a4c-41cf-b6c7-440b29bb8c4f")
 )
 
 // Encoding defines the Unicode encoding used by UEFI, which is UCS-2 Little
@@ -39,79 +51,108 @@
 // Spec 2.9, Sections 33.2.6 and 1.8.1.
 var Encoding = unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
 
-// ExtractString returns EFI variable data based on raw variable file contents.
-// It returns string-represented data, or an error.
-func ExtractString(contents []byte) (string, error) {
-	// Fail if total length is shorter than attribute length.
-	if len(contents) < 4 {
-		return "", fmt.Errorf("contents too short.")
-	}
-	// Skip attributes, see @linux//Documentation/filesystems:efivarfs.rst for format
-	efiVarData := contents[4:]
-	espUUIDNullTerminated, err := Encoding.NewDecoder().Bytes(efiVarData)
-	if err != nil {
-		// Pass the decoding error unwrapped.
-		return "", err
-	}
-	// Remove the null suffix.
-	return string(bytes.TrimSuffix(espUUIDNullTerminated, []byte{0})), nil
+// Attribute contains a bitset of EFI variable attributes.
+type Attribute uint32
+
+const (
+	// If set the value of the variable is is persistent across resets and
+	// power cycles. Variables without this set cannot be created or modified
+	// after UEFI boot services are terminated.
+	AttrNonVolatile Attribute = 1 << iota
+	// If set allows access to this variable from UEFI boot services.
+	AttrBootserviceAccess
+	// If set allows access to this variable from an operating system after
+	// UEFI boot services are terminated. Variables setting this must also
+	// set AttrBootserviceAccess. This is automatically taken care of by Write
+	// in this package.
+	AttrRuntimeAccess
+	// Marks a variable as being a hardware error record. See UEFI 2.10 section
+	// 8.2.8 for more information about this.
+	AttrHardwareErrorRecord
+	// Deprecated, should not be used for new variables.
+	AttrAuthenticatedWriteAccess
+	// Variable requires special authentication to write. These variables
+	// cannot be written with this package.
+	AttrTimeBasedAuthenticatedWriteAccess
+	// If set in a Write() call, tries to append the data instead of replacing
+	// it completely.
+	AttrAppendWrite
+	// Variable requires special authentication to access and write. These
+	// variables cannot be accessed with this package.
+	AttrEnhancedAuthenticatedAccess
+)
+
+func varPath(scope uuid.UUID, varName string) string {
+	return fmt.Sprintf("/sys/firmware/efi/efivars/%s-%s", varName, scope.String())
 }
 
-// ReadLoaderDevicePartUUID reads the ESP UUID from an EFI variable. It
-// depends on efivarfs being already mounted.
-func ReadLoaderDevicePartUUID() (uuid.UUID, error) {
-	// Read the EFI variable file containing the ESP UUID.
-	espUuidPath := filepath.Join(Path, "LoaderDevicePartUUID-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f")
-	efiVar, err := os.ReadFile(espUuidPath)
+// Write writes the value of the named variable in the given scope.
+func Write(scope uuid.UUID, varName string, attrs Attribute, value []byte) error {
+	// Write attributes, see @linux//Documentation/filesystems:efivarfs.rst for format
+	f, err := os.OpenFile(varPath(scope, varName), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
 	if err != nil {
-		return uuid.Nil, fmt.Errorf("couldn't read the LoaderDevicePartUUID file at %q: %w", espUuidPath, err)
-	}
-	contents, err := ExtractString(efiVar)
-	if err != nil {
-		return uuid.Nil, fmt.Errorf("couldn't decode an EFI variable: %w", err)
-	}
-	out, err := uuid.Parse(contents)
-	if err != nil {
-		return uuid.Nil, fmt.Errorf("value in LoaderDevicePartUUID could not be parsed as UUID: %w", err)
-	}
-	return out, nil
-}
-
-// CreateBootEntry creates an EFI boot entry variable and returns its
-// non-negative index on success. It may return an io error.
-func CreateBootEntry(be *BootEntry) (int, error) {
-	// Find the index by looking up the first empty slot.
-	var ep string
-	var n int
-	for ; ; n++ {
-		en := fmt.Sprintf("Boot%04x-%s", n, GlobalGuid)
-		ep = filepath.Join(Path, en)
-		_, err := os.Stat(ep)
-		if os.IsNotExist(err) {
-			break
+		e := err
+		// Unwrap PathError here as we wrap our own parameter message around it
+		var perr *fs.PathError
+		if errors.As(err, &perr) {
+			e = perr.Err
 		}
-		if err != nil {
-			return -1, err
-		}
+		return fmt.Errorf("writing %q in scope %s: %w", varName, scope, e)
 	}
-
-	// Create the boot variable.
-	bem, err := be.Marshal()
-	if err != nil {
-		return -1, fmt.Errorf("while marshaling the EFI boot entry: %w", err)
+	// Required by UEFI 2.10 Section 8.2.3:
+	// Runtime access to a data variable implies boot service access. Attributes
+	// that have EFI_VARIABLE_RUNTIME_ACCESS set must also have
+	// EFI_VARIABLE_BOOTSERVICE_ACCESS set. The caller is responsible for
+	// following this rule.
+	if attrs&AttrRuntimeAccess != 0 {
+		attrs |= AttrBootserviceAccess
 	}
-	if err := os.WriteFile(ep, bem, 0644); err != nil {
-		return -1, fmt.Errorf("while creating a boot entry variable: %w", err)
+	// Linux wants everything in on write, so assemble an intermediate buffer
+	buf := make([]byte, len(value)+4)
+	binary.LittleEndian.PutUint32(buf[:4], uint32(attrs))
+	copy(buf[4:], value)
+	_, err = f.Write(buf)
+	if err1 := f.Close(); err1 != nil && err == nil {
+		err = err1
 	}
-	return n, nil
+	return err
 }
 
-// SetBootOrder replaces contents of the boot order variable with the order
-// specified in ord. It may return an io error.
-func SetBootOrder(ord *BootOrder) error {
-	op := filepath.Join(Path, fmt.Sprintf("BootOrder-%s", GlobalGuid))
-	if err := os.WriteFile(op, ord.Marshal(), 0644); err != nil {
-		return fmt.Errorf("while creating a boot order variable: %w", err)
+// Read reads the value of the named variable in the given scope.
+func Read(scope uuid.UUID, varName string) ([]byte, Attribute, error) {
+	val, err := os.ReadFile(varPath(scope, varName))
+	if err != nil {
+		e := err
+		// Unwrap PathError here as we wrap our own parameter message around it
+		var perr *fs.PathError
+		if errors.As(err, &perr) {
+			e = perr.Err
+		}
+		return nil, Attribute(0), fmt.Errorf("reading %q in scope %s: %w", varName, scope, e)
 	}
-	return nil
+	if len(val) < 4 {
+		return nil, Attribute(0), fmt.Errorf("reading %q in scope %s: malformed, less than 4 bytes long", varName, scope)
+	}
+	return val[4:], Attribute(binary.LittleEndian.Uint32(val[:4])), nil
+}
+
+// List lists all variable names present for a given scope sorted by their names
+// in Go's "native" string sort order.
+func List(scope uuid.UUID) ([]string, error) {
+	vars, err := os.ReadDir(Path)
+	if err != nil {
+		return nil, fmt.Errorf("failed to list variable directory: %w", err)
+	}
+	var outVarNames []string
+	suffix := fmt.Sprintf("-%v", scope)
+	for _, v := range vars {
+		if v.IsDir() {
+			continue
+		}
+		if !strings.HasSuffix(v.Name(), suffix) {
+			continue
+		}
+		outVarNames = append(outVarNames, strings.TrimSuffix(v.Name(), suffix))
+	}
+	return outVarNames, nil
 }
diff --git a/metropolis/pkg/efivarfs/format.go b/metropolis/pkg/efivarfs/format.go
deleted file mode 100644
index a71dbf9..0000000
--- a/metropolis/pkg/efivarfs/format.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2020 The Monogon Project Authors.
-//
-// SPDX-License-Identifier: Apache-2.0
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package efivarfs
-
-import (
-	"github.com/google/uuid"
-)
-
-// MarshalEFIGUID returns src represented in the EFI GUID format, as defined in
-// UEFI specification, version 2.9, appendix A:
-// https://uefi.org/sites/default/files/resources/UEFI_Spec_2_9_2021_03_18.pdf
-func MarshalEFIGUID(src uuid.UUID) []byte {
-	efi := make([]byte, 16)
-	transform := []int{3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15}
-	for dest, from := range transform {
-		efi[dest] = src[from]
-	}
-	return efi
-}
diff --git a/metropolis/pkg/efivarfs/variables.go b/metropolis/pkg/efivarfs/variables.go
new file mode 100644
index 0000000..876173c
--- /dev/null
+++ b/metropolis/pkg/efivarfs/variables.go
@@ -0,0 +1,136 @@
+package efivarfs
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io/fs"
+	"math"
+	"regexp"
+	"strconv"
+
+	"github.com/google/uuid"
+)
+
+func decodeString(varData []byte) (string, error) {
+	efiStringRaw, err := Encoding.NewDecoder().Bytes(varData)
+	if err != nil {
+		// Pass the decoding error unwrapped.
+		return "", err
+	}
+	// Remove the null suffix.
+	return string(bytes.TrimSuffix(efiStringRaw, []byte{0})), nil
+}
+
+// ReadLoaderDevicePartUUID reads the ESP UUID from an EFI variable.
+func ReadLoaderDevicePartUUID() (uuid.UUID, error) {
+	efiVar, _, err := Read(ScopeSystemd, "LoaderDevicePartUUID")
+	if err != nil {
+		return uuid.Nil, err
+	}
+	strContent, err := decodeString(efiVar)
+	if err != nil {
+		return uuid.Nil, fmt.Errorf("decoding string failed: %w", err)
+	}
+	out, err := uuid.Parse(strContent)
+	if err != nil {
+		return uuid.Nil, fmt.Errorf("value in LoaderDevicePartUUID could not be parsed as UUID: %w", err)
+	}
+	return out, nil
+}
+
+// Technically UEFI mandates that only upper-case hex indices are valid, but in
+// practice even vendors themselves ship firmware with lowercase hex indices,
+// thus accept these here as well.
+var bootVarRegexp = regexp.MustCompile(`^Boot([0-9A-Fa-f]{4})$`)
+
+// AddBootEntry creates an new EFI boot entry variable and returns its
+// non-negative index on success.
+func AddBootEntry(be *LoadOption) (int, error) {
+	varNames, err := List(ScopeGlobal)
+	if err != nil {
+		return -1, fmt.Errorf("failed to list EFI variables: %w", err)
+	}
+	presentEntries := make(map[int]bool)
+	// Technically these are sorted, but due to the lower/upper case issue
+	// we cannot rely on this fact.
+	for _, varName := range varNames {
+		s := bootVarRegexp.FindStringSubmatch(varName)
+		if s == nil {
+			continue
+		}
+		idx, err := strconv.ParseUint(s[1], 16, 16)
+		if err != nil {
+			// This cannot be hit as all regexp matches are parseable.
+			// A quick fuzz run agrees.
+			panic(err)
+		}
+		presentEntries[int(idx)] = true
+	}
+	idx := -1
+	for i := 0; i < math.MaxUint16; i++ {
+		if !presentEntries[i] {
+			idx = i
+			break
+		}
+	}
+	if idx == -1 {
+		return -1, errors.New("all 2^16 boot entry variables are occupied")
+	}
+
+	err = SetBootEntry(idx, be)
+	if err != nil {
+		return -1, fmt.Errorf("failed to set new boot entry: %w", err)
+	}
+	return idx, nil
+}
+
+// GetBootEntry returns the boot entry at the given index.
+func GetBootEntry(idx int) (*LoadOption, error) {
+	raw, _, err := Read(ScopeGlobal, fmt.Sprintf("Boot%04X", idx))
+	if errors.Is(err, fs.ErrNotExist) {
+		// Try non-spec-conforming lowercase entry
+		raw, _, err = Read(ScopeGlobal, fmt.Sprintf("Boot%04x", idx))
+	}
+	if err != nil {
+		return nil, err
+	}
+	return UnmarshalLoadOption(raw)
+}
+
+// SetBootEntry writes the given boot entry to the given index.
+func SetBootEntry(idx int, be *LoadOption) error {
+	bem, err := be.Marshal()
+	if err != nil {
+		return fmt.Errorf("while marshaling the EFI boot entry: %w", err)
+	}
+	return Write(ScopeGlobal, fmt.Sprintf("Boot%04X", idx), AttrNonVolatile|AttrRuntimeAccess, bem)
+}
+
+// SetBootOrder replaces contents of the boot order variable with the order
+// specified in ord.
+func SetBootOrder(ord *BootOrder) error {
+	return Write(ScopeGlobal, "BootOrder", AttrNonVolatile|AttrRuntimeAccess, ord.Marshal())
+}
+
+// GetBootOrder returns the current boot order of the system.
+func GetBootOrder() (*BootOrder, error) {
+	raw, _, err := Read(ScopeGlobal, "BootOrder")
+	if err != nil {
+		return nil, err
+	}
+	ord, err := UnmarshalBootOrder(raw)
+	if err != nil {
+		return nil, fmt.Errorf("invalid boot order structure: %w", err)
+	}
+	return ord, nil
+}
+
+// SetBootNext sets the boot entry used for the next boot only. It automatically
+// resets after the next boot.
+func SetBootNext(entryIdx uint16) error {
+	data := make([]byte, 2)
+	binary.LittleEndian.PutUint16(data, entryIdx)
+	return Write(ScopeGlobal, "BootNext", AttrNonVolatile|AttrRuntimeAccess, data)
+}