-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbootloader_efi.go
More file actions
executable file
·242 lines (210 loc) · 6.23 KB
/
bootloader_efi.go
File metadata and controls
executable file
·242 lines (210 loc) · 6.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package imageinspect
import (
"bytes"
"debug/pe"
"fmt"
"sort"
"strings"
)
func ParsePEFromBytes(p string, blob []byte) (EFIBinaryEvidence, error) {
ev := EFIBinaryEvidence{
Path: p,
Size: int64(len(blob)),
SectionSHA256: map[string]string{},
OSReleaseSorted: []KeyValue{},
Kind: BootloaderUnknown, // set after we have more evidence
}
ev.SHA256 = sha256Hex(blob)
r := bytes.NewReader(blob)
f, err := pe.NewFile(r)
if err != nil {
return ev, err
}
defer f.Close()
ev.Arch = peMachineToArch(f.FileHeader.Machine)
for _, s := range f.Sections {
name := strings.TrimRight(s.Name, "\x00")
ev.Sections = append(ev.Sections, name)
}
signed, sigSize, sigNote := peSignatureInfo(f)
ev.Signed = signed
ev.SignatureSize = sigSize
if sigNote != "" {
ev.Notes = append(ev.Notes, sigNote)
}
ev.HasSBAT = hasSection(ev.Sections, ".sbat")
isUKI := hasSection(ev.Sections, ".linux") &&
(hasSection(ev.Sections, ".cmdline") || hasSection(ev.Sections, ".osrel") || hasSection(ev.Sections, ".uname"))
ev.IsUKI = isUKI
if isUKI {
ev.Kind = BootloaderUKI
} else {
ev.Kind = classifyBootloaderKind(p, ev.Sections)
}
// Hash & extract interesting sections
// Note: s.Data() reads section contents from underlying ReaderAt.
// For large payloads (.linux, .initrd), this is still OK because blob is already in memory.
for _, s := range f.Sections {
name := strings.TrimRight(s.Name, "\x00")
data, err := s.Data()
if err != nil {
ev.Notes = append(ev.Notes, fmt.Sprintf("read section %s: %v", name, err))
continue
}
ev.SectionSHA256[name] = sha256Hex(data)
switch name {
case ".linux":
ev.KernelSHA256 = ev.SectionSHA256[name]
case ".initrd":
ev.InitrdSHA256 = ev.SectionSHA256[name]
case ".cmdline":
ev.CmdlineSHA256 = ev.SectionSHA256[name]
ev.Cmdline = strings.TrimSpace(string(bytes.Trim(data, "\x00")))
case ".uname":
ev.UnameSHA256 = ev.SectionSHA256[name]
ev.Uname = strings.TrimSpace(string(bytes.Trim(data, "\x00")))
case ".osrel":
ev.OSRelSHA256 = ev.SectionSHA256[name]
raw := strings.TrimSpace(string(bytes.Trim(data, "\x00")))
ev.OSReleaseRaw = raw
ev.OSRelease, ev.OSReleaseSorted = parseOSRelease(raw)
}
}
return ev, nil
}
// peSignatureInfo checks for the presence of an Authenticode signature in the PE file
func peSignatureInfo(f *pe.File) (signed bool, sigSize int, note string) {
// IMAGE_DIRECTORY_ENTRY_SECURITY = 4
const secDir = 4
// OptionalHeader can be OptionalHeader32 or OptionalHeader64.
switch oh := f.OptionalHeader.(type) {
case *pe.OptionalHeader32:
if len(oh.DataDirectory) > secDir {
sz := oh.DataDirectory[secDir].Size
va := oh.DataDirectory[secDir].VirtualAddress // file offset for security dir
if sz > 0 && va > 0 {
return true, int(sz), ""
}
}
case *pe.OptionalHeader64:
if len(oh.DataDirectory) > secDir {
sz := oh.DataDirectory[secDir].Size
va := oh.DataDirectory[secDir].VirtualAddress
if sz > 0 && va > 0 {
return true, int(sz), ""
}
}
default:
return false, 0, "unknown optional header type"
}
return false, 0, ""
}
// classifyBootloaderKind classifies the bootloader kind based on path and sections.
// It intentionally avoids content-string heuristics for stability.
// For `EFI/BOOT/BOOTX64.EFI` copies/aliases, rely on SHA-inheritance post-pass.
func classifyBootloaderKind(p string, sections []string) BootloaderKind {
lp := strings.ToLower(p)
// Deterministic first:
if sections != nil && hasSection(sections, ".linux") {
return BootloaderUKI
}
// Path / filename heuristics:
if strings.Contains(lp, "mmx64.efi") || strings.Contains(lp, "mmia32.efi") {
return BootloaderMokManager
}
if strings.Contains(lp, "shim") {
return BootloaderShim
}
if strings.Contains(lp, "systemd") && strings.Contains(lp, "boot") {
return BootloaderSystemdBoot
}
if strings.Contains(lp, "grub") {
return BootloaderGrub
}
return BootloaderUnknown
}
// hasSection checks if the given section name is present in the list (case-insensitive)
func hasSection(secs []string, want string) bool {
want = strings.ToLower(want)
for _, s := range secs {
if strings.ToLower(strings.TrimSpace(s)) == want {
return true
}
}
return false
}
// inheritBootloaderKindBySHA assigns a kind to "unknown" EFI binaries when they
// are byte-identical to another EFI binary already classified as a known kind.
// This reliably handles fallback paths like `EFI/BOOT/BOOTX64.EFI`.
func inheritBootloaderKindBySHA(evs []EFIBinaryEvidence) {
known := make(map[string]BootloaderKind) // sha256 -> kind
// First pass: record known kinds by hash.
for _, ev := range evs {
if ev.SHA256 == "" || ev.Kind == BootloaderUnknown {
continue
}
if _, ok := known[ev.SHA256]; !ok {
known[ev.SHA256] = ev.Kind
}
}
// Second pass: upgrade unknowns when a known hash exists.
for i := range evs {
if evs[i].Kind != BootloaderUnknown || evs[i].SHA256 == "" {
continue
}
if k, ok := known[evs[i].SHA256]; ok {
evs[i].Kind = k
evs[i].Notes = append(evs[i].Notes, "bootloader kind inherited from identical EFI binary (sha256 match)")
}
}
}
// peMachineToArch maps PE machine types to architecture strings
func peMachineToArch(m uint16) string {
switch m {
case pe.IMAGE_FILE_MACHINE_AMD64:
return "x86_64"
case pe.IMAGE_FILE_MACHINE_I386:
return "x86"
case pe.IMAGE_FILE_MACHINE_ARM64:
return "arm64"
case pe.IMAGE_FILE_MACHINE_ARM:
return "arm"
default:
return fmt.Sprintf("unknown(0x%x)", m)
}
}
// parseOSRelease parses os-release style key=value data.
func parseOSRelease(raw string) (map[string]string, []KeyValue) {
m := map[string]string{}
for _, line := range strings.Split(raw, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
k, v, ok := strings.Cut(line, "=")
if !ok {
continue
}
k = strings.TrimSpace(k)
v = strings.TrimSpace(v)
// os-release allows quoted values.
v = strings.Trim(v, `"'`)
if k != "" {
m[k] = v
}
}
// deterministic ordering
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
sorted := make([]KeyValue, 0, len(keys))
for _, k := range keys {
sorted = append(sorted, KeyValue{
Key: k,
Value: m[k],
})
}
return m, sorted
}