blob: 90c451917a8db7da60291c11c5f34aceea433c0e [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"
25 "io/ioutil"
26 "path/filepath"
27 "strings"
28
29 "golang.org/x/text/encoding/unicode"
30)
31
32const (
33 Path = "/sys/firmware/efi/efivars"
34 GlobalGuid = "8be4df61-93ca-11d2-aa0d-00e098032b8c"
35)
36
37// ExtractString returns EFI variable data based on raw variable file contents.
38// It returns string-represented data, or an error.
39func ExtractString(contents []byte) (string, error) {
40 // Fail if total length is shorter than attribute length.
41 if len(contents) < 4 {
42 return "", fmt.Errorf("contents too short.")
43 }
44 // efiUnicode defines the Unicode encoding used by UEFI which is UCS-2
45 // Little Endian. For BMP characters UTF-16 is equivalent to UCS-2.
46 // See the UEFI Spec 2.9, Sections 33.2.6 and 1.8.1.
47 efiUnicode := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
48 // Skip attributes, see @linux//Documentation/filesystems:efivarfs.rst for format
49 efiVarData := contents[4:]
50 espUUIDNullTerminated, err := efiUnicode.NewDecoder().Bytes(efiVarData)
51 if err != nil {
52 // Pass the decoding error unwrapped.
53 return "", err
54 }
55 // Remove the null suffix.
56 return string(bytes.TrimSuffix(espUUIDNullTerminated, []byte{0})), nil
57}
58
59// ReadLoaderDevicePartUUID reads the ESP UUID from an EFI variable. It
60// depends on efivarfs being already mounted. It returns a correct lowercase
61// UUID, or an error.
62func ReadLoaderDevicePartUUID() (string, error) {
63 // Read the EFI variable file containing the ESP UUID.
64 espUuidPath := filepath.Join(Path, "LoaderDevicePartUUID-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f")
65 efiVar, err := ioutil.ReadFile(espUuidPath)
66 if err != nil {
67 return "", fmt.Errorf("couldn't read the LoaderDevicePartUUID file at %q: %w", espUuidPath, err)
68 }
69 contents, err := ExtractString(efiVar)
70 if err != nil {
71 return "", fmt.Errorf("couldn't decode an EFI variable: %w", err)
72 }
73 return strings.ToLower(contents), nil
74}