blob: 81325799ce66ee909b24aecdc8d771de30242233 [file] [log] [blame]
Mateusz Zalegac6c092b2021-11-09 13:09:37 +01001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17// This package was written with the aim of easing efivarfs integration.
18//
19// https://www.kernel.org/doc/html/latest/filesystems/efivarfs.html
20package efivarfs
21
22import (
23 "bytes"
24 "fmt"
Mateusz Zalega5b60e582021-11-10 19:57:17 +010025 "os"
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010026 "path/filepath"
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010027
Lorenz Brunca9cfcf2023-05-02 19:29:14 +020028 "github.com/google/uuid"
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010029 "golang.org/x/text/encoding/unicode"
30)
31
32const (
33 Path = "/sys/firmware/efi/efivars"
34 GlobalGuid = "8be4df61-93ca-11d2-aa0d-00e098032b8c"
35)
36
Mateusz Zalega6cefe512021-11-08 18:19:42 +010037// Encoding defines the Unicode encoding used by UEFI, which is UCS-2 Little
38// Endian. For BMP characters UTF-16 is equivalent to UCS-2. See the UEFI
39// Spec 2.9, Sections 33.2.6 and 1.8.1.
40var Encoding = unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
41
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010042// ExtractString returns EFI variable data based on raw variable file contents.
43// It returns string-represented data, or an error.
44func ExtractString(contents []byte) (string, error) {
45 // Fail if total length is shorter than attribute length.
46 if len(contents) < 4 {
47 return "", fmt.Errorf("contents too short.")
48 }
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010049 // Skip attributes, see @linux//Documentation/filesystems:efivarfs.rst for format
50 efiVarData := contents[4:]
Mateusz Zalega6cefe512021-11-08 18:19:42 +010051 espUUIDNullTerminated, err := Encoding.NewDecoder().Bytes(efiVarData)
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010052 if err != nil {
53 // Pass the decoding error unwrapped.
54 return "", err
55 }
56 // Remove the null suffix.
57 return string(bytes.TrimSuffix(espUUIDNullTerminated, []byte{0})), nil
58}
59
60// ReadLoaderDevicePartUUID reads the ESP UUID from an EFI variable. It
Lorenz Brunca9cfcf2023-05-02 19:29:14 +020061// depends on efivarfs being already mounted.
62func ReadLoaderDevicePartUUID() (uuid.UUID, error) {
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010063 // Read the EFI variable file containing the ESP UUID.
64 espUuidPath := filepath.Join(Path, "LoaderDevicePartUUID-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f")
Lorenz Brun764a2de2021-11-22 16:26:36 +010065 efiVar, err := os.ReadFile(espUuidPath)
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010066 if err != nil {
Lorenz Brunca9cfcf2023-05-02 19:29:14 +020067 return uuid.Nil, fmt.Errorf("couldn't read the LoaderDevicePartUUID file at %q: %w", espUuidPath, err)
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010068 }
69 contents, err := ExtractString(efiVar)
70 if err != nil {
Lorenz Brunca9cfcf2023-05-02 19:29:14 +020071 return uuid.Nil, fmt.Errorf("couldn't decode an EFI variable: %w", err)
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010072 }
Lorenz Brunca9cfcf2023-05-02 19:29:14 +020073 out, err := uuid.Parse(contents)
74 if err != nil {
75 return uuid.Nil, fmt.Errorf("value in LoaderDevicePartUUID could not be parsed as UUID: %w", err)
76 }
77 return out, nil
Mateusz Zalegac6c092b2021-11-09 13:09:37 +010078}
Mateusz Zalega5b60e582021-11-10 19:57:17 +010079
80// CreateBootEntry creates an EFI boot entry variable and returns its
81// non-negative index on success. It may return an io error.
82func CreateBootEntry(be *BootEntry) (int, error) {
83 // Find the index by looking up the first empty slot.
84 var ep string
85 var n int
86 for ; ; n++ {
87 en := fmt.Sprintf("Boot%04x-%s", n, GlobalGuid)
88 ep = filepath.Join(Path, en)
89 _, err := os.Stat(ep)
90 if os.IsNotExist(err) {
91 break
92 }
93 if err != nil {
94 return -1, err
95 }
96 }
97
98 // Create the boot variable.
99 bem, err := be.Marshal()
100 if err != nil {
101 return -1, fmt.Errorf("while marshaling the EFI boot entry: %w", err)
102 }
Lorenz Brun764a2de2021-11-22 16:26:36 +0100103 if err := os.WriteFile(ep, bem, 0644); err != nil {
Mateusz Zalega5b60e582021-11-10 19:57:17 +0100104 return -1, fmt.Errorf("while creating a boot entry variable: %w", err)
105 }
106 return n, nil
107}
108
109// SetBootOrder replaces contents of the boot order variable with the order
110// specified in ord. It may return an io error.
111func SetBootOrder(ord *BootOrder) error {
112 op := filepath.Join(Path, fmt.Sprintf("BootOrder-%s", GlobalGuid))
Lorenz Brun764a2de2021-11-22 16:26:36 +0100113 if err := os.WriteFile(op, ord.Marshal(), 0644); err != nil {
Mateusz Zalega5b60e582021-11-10 19:57:17 +0100114 return fmt.Errorf("while creating a boot order variable: %w", err)
115 }
116 return nil
117}