treewide: introduce osbase package and move things around

All except localregistry moved from metropolis/pkg to osbase,
localregistry moved to metropolis/test as its only used there anyway.

Change-Id: If1a4bf377364bef0ac23169e1b90379c71b06d72
Reviewed-on: https://review.monogon.dev/c/monogon/+/3079
Tested-by: Jenkins CI
Reviewed-by: Serge Bazanski <serge@monogon.tech>
diff --git a/osbase/efivarfs/BUILD.bazel b/osbase/efivarfs/BUILD.bazel
new file mode 100644
index 0000000..7f7539f
--- /dev/null
+++ b/osbase/efivarfs/BUILD.bazel
@@ -0,0 +1,32 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "efivarfs",
+    srcs = [
+        "boot.go",
+        "devicepath.go",
+        "efivarfs.go",
+        "variables.go",
+    ],
+    importpath = "source.monogon.dev/osbase/efivarfs",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//osbase/msguid",
+        "@com_github_google_uuid//:uuid",
+        "@org_golang_x_text//encoding/unicode",
+    ],
+)
+
+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/osbase/efivarfs/boot.go b/osbase/efivarfs/boot.go
new file mode 100644
index 0000000..8fe1a55
--- /dev/null
+++ b/osbase/efivarfs/boot.go
@@ -0,0 +1,202 @@
+// MIT License
+//
+// Copyright (c) 2021 Philippe Voinov (philippevoinov@gmail.com)
+// Copyright 2021 The Monogon Project Authors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+package efivarfs
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"math"
+	"strings"
+)
+
+type LoadOptionCategory uint8
+
+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
+)
+
+// 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
+	// ExtraPaths contains additional device paths with vendor-specific
+	// behavior. Can generally be left empty.
+	ExtraPaths []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 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
+	}
+	if !e.Inactive {
+		attrs |= 0x01
+	}
+	data = append32(data, attrs)
+	filePathRaw, err := e.FilePath.Marshal()
+	if err != nil {
+		return nil, fmt.Errorf("failed marshalling FilePath: %w", err)
+	}
+	for _, ep := range e.ExtraPaths {
+		epRaw, err := ep.Marshal()
+		if err != nil {
+			return nil, fmt.Errorf("failed marshalling ExtraPath: %w", err)
+		}
+		filePathRaw = append(filePathRaw, epRaw...)
+	}
+	if len(filePathRaw) > math.MaxUint16 {
+		return nil, fmt.Errorf("failed marshalling FilePath/ExtraPath: value too big (%d)", len(filePathRaw))
+	}
+	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")
+	}
+	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
+}
+
+// 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))
+	}
+	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")
+	}
+	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)
+	}
+	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)
+	}
+	filePathData := data[descriptionEnd : descriptionEnd+int(lenPath)]
+	opt.FilePath, filePathData, err = UnmarshalDevicePath(filePathData)
+	if err != nil {
+		return nil, fmt.Errorf("failed unmarshaling FilePath: %w", err)
+	}
+	for len(filePathData) > 0 {
+		var extraPath DevicePath
+		extraPath, filePathData, err = UnmarshalDevicePath(filePathData)
+		if err != nil {
+			return nil, fmt.Errorf("failed unmarshaling ExtraPath: %w", err)
+		}
+		opt.ExtraPaths = append(opt.ExtraPaths, extraPath)
+	}
+
+	if descriptionEnd+int(lenPath) < len(data) {
+		opt.OptionalData = data[descriptionEnd+int(lenPath):]
+	}
+	return &opt, nil
+}
+
+// BootOrder represents the contents of the BootOrder EFI variable.
+type BootOrder []uint16
+
+// Marshal generates the binary representation of a BootOrder.
+func (t *BootOrder) Marshal() []byte {
+	var out []byte
+	for _, v := range *t {
+		out = append16(out, v)
+	}
+	return out
+}
+
+// UnmarshalBootOrder loads a BootOrder from its binary representation.
+func UnmarshalBootOrder(d []byte) (BootOrder, error) {
+	if len(d)%2 != 0 {
+		return nil, fmt.Errorf("invalid length: %v bytes", len(d))
+	}
+	l := len(d) / 2
+	out := make(BootOrder, l)
+	for i := 0; i < l; i++ {
+		out[i] = uint16(d[2*i]) | uint16(d[2*i+1])<<8
+	}
+	return out, nil
+}
+
+func append16(d []byte, v uint16) []byte {
+	return append(d,
+		byte(v&0xFF),
+		byte(v>>8&0xFF),
+	)
+}
+
+func append32(d []byte, v uint32) []byte {
+	return append(d,
+		byte(v&0xFF),
+		byte(v>>8&0xFF),
+		byte(v>>16&0xFF),
+		byte(v>>24&0xFF),
+	)
+}
diff --git a/osbase/efivarfs/boot_test.go b/osbase/efivarfs/boot_test.go
new file mode 100644
index 0000000..9abd8f9
--- /dev/null
+++ b/osbase/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/osbase/efivarfs/devicepath.go b/osbase/efivarfs/devicepath.go
new file mode 100644
index 0000000..d06960c
--- /dev/null
+++ b/osbase/efivarfs/devicepath.go
@@ -0,0 +1,316 @@
+package efivarfs
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"math"
+	"strings"
+
+	"github.com/google/uuid"
+
+	"source.monogon.dev/osbase/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.ReplaceAll(string(out[:len(out)-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 until it encounters an end
+// device path structure. It returns that device path (excluding the final end
+// device path marker) as well as all all data following the end marker.
+func UnmarshalDevicePath(data []byte) (DevicePath, []byte, error) {
+	rest := data
+	var p DevicePath
+	for {
+		if len(rest) < 4 {
+			if len(rest) != 0 {
+				return nil, 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, nil, fmt.Errorf("path element larger than rest of buffer: %d > %d", dataLen, len(rest))
+		}
+		if dataLen < 4 {
+			return nil, nil, fmt.Errorf("path element must be at least 4 bytes (header), length indicates %d", dataLen)
+		}
+		elemData := rest[4:dataLen]
+		rest = rest[dataLen:]
+
+		// End of Device Path
+		if t == 0x7f && subT == 0xff {
+			return p, rest, nil
+		}
+
+		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, nil, fmt.Errorf("failed decoding path element %d: %w", len(p), err)
+		}
+		p = append(p, elem)
+	}
+	if len(p) == 0 {
+		return nil, nil, errors.New("empty DevicePath without End Of Path element")
+	}
+	return nil, nil, fmt.Errorf("got DevicePath with %d elements, but without End Of Path element", len(p))
+}
diff --git a/osbase/efivarfs/devicepath_test.go b/osbase/efivarfs/devicepath_test.go
new file mode 100644
index 0000000..ad81279
--- /dev/null
+++ b/osbase/efivarfs/devicepath_test.go
@@ -0,0 +1,93 @@
+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)
+			}
+			_, rest, err := UnmarshalDevicePath(got)
+			if err != nil {
+				t.Errorf("failed to unmarshal value again: %v", err)
+			}
+			if len(rest) != 0 {
+				t.Errorf("rest is non-zero after single valid device path: %x", rest)
+			}
+		})
+	}
+}
diff --git a/osbase/efivarfs/efivarfs.go b/osbase/efivarfs/efivarfs.go
new file mode 100644
index 0000000..ab6da26
--- /dev/null
+++ b/osbase/efivarfs/efivarfs.go
@@ -0,0 +1,164 @@
+// 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 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".
+//
+// [1] https://www.kernel.org/doc/html/latest/filesystems/efivarfs.html
+package efivarfs
+
+import (
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"io/fs"
+	"os"
+	"strings"
+
+	"github.com/google/uuid"
+	"golang.org/x/text/encoding/unicode"
+)
+
+const (
+	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
+// Endian. For BMP characters UTF-16 is equivalent to UCS-2. See the UEFI
+// Spec 2.9, Sections 33.2.6 and 1.8.1.
+var Encoding = unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
+
+// 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())
+}
+
+// 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, 0644)
+	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 fmt.Errorf("writing %q in scope %s: %w", varName, scope, e)
+	}
+	// 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
+	}
+	// 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 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)
+	}
+	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
+}
+
+// Delete deletes the given variable name in the given scope. Use with care,
+// some firmware fails to boot if variables it uses are deleted.
+func Delete(scope uuid.UUID, varName string) error {
+	return os.Remove(varPath(scope, varName))
+}
diff --git a/osbase/efivarfs/variables.go b/osbase/efivarfs/variables.go
new file mode 100644
index 0000000..fe59324
--- /dev/null
+++ b/osbase/efivarfs/variables.go
@@ -0,0 +1,146 @@
+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)
+}
+
+// DeleteBootEntry deletes the boot entry at the given index.
+func DeleteBootEntry(idx int) error {
+	err := Delete(ScopeGlobal, fmt.Sprintf("Boot%04X", idx))
+	if errors.Is(err, fs.ErrNotExist) {
+		// Try non-spec-conforming lowercase entry
+		err = Delete(ScopeGlobal, fmt.Sprintf("Boot%04x", idx))
+	}
+	return err
+}
+
+// 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)
+}