You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
410 lines
13 KiB
Go
410 lines
13 KiB
Go
package hypervisor
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/xml"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const maxDomainCapabilitiesXMLBytes = 4 << 20
|
|
|
|
var (
|
|
// ErrInvalidCapabilitiesXML distinguishes malformed or structurally
|
|
// incomplete domcapabilities output from a valid host that lacks a required
|
|
// feature.
|
|
ErrInvalidCapabilitiesXML = errors.New("invalid libvirt domain capabilities XML")
|
|
// ErrNoNonSecureLoader means the host advertised EFI but did not provide a
|
|
// loader descriptor that can prove Secure Boot is disabled.
|
|
ErrNoNonSecureLoader = errors.New("no non-secure EFI loader is available")
|
|
)
|
|
|
|
// LoaderCapability is one loader descriptor from libvirt's
|
|
// <domainCapabilities><os> section. Secure is normalized to "yes" or "no";
|
|
// a missing secure attribute is treated as "no" only when the path does not
|
|
// carry the conventional secboot marker.
|
|
type LoaderCapability struct {
|
|
Path string `json:"path"`
|
|
Supported bool `json:"supported"`
|
|
Secure string `json:"secure"`
|
|
SecureOptions []string `json:"secure_options,omitempty"`
|
|
}
|
|
|
|
// DomainCapabilities is the binding-neutral subset of virsh
|
|
// domcapabilities XML needed before an EFI/q35 domain definition. It retains
|
|
// loader paths so the Linux adapter can choose one only after this parser has
|
|
// classified it as a non-Secure-Boot descriptor.
|
|
type DomainCapabilities struct {
|
|
Architecture string `json:"architecture"`
|
|
Machines []string `json:"machines"`
|
|
Firmware []string `json:"firmware"`
|
|
Loaders []LoaderCapability `json:"loaders"`
|
|
}
|
|
|
|
type rawDomainCapabilities struct {
|
|
XMLName xml.Name `xml:"domainCapabilities"`
|
|
Arch rawArch `xml:"arch"`
|
|
Machines []rawMachine `xml:"machine"`
|
|
OS []*rawOS `xml:"os"`
|
|
}
|
|
|
|
type rawArch struct {
|
|
Name string `xml:"name,attr"`
|
|
Text string `xml:",chardata"`
|
|
}
|
|
|
|
type rawMachine struct {
|
|
Canonical string `xml:"canonical,attr"`
|
|
Text string `xml:",chardata"`
|
|
}
|
|
|
|
type rawOS struct {
|
|
Supported string `xml:"supported,attr"`
|
|
Enums []rawEnum `xml:"enum"`
|
|
Loaders []rawLoader `xml:"loader"`
|
|
}
|
|
|
|
type rawEnum struct {
|
|
Name string `xml:"name,attr"`
|
|
Values []string `xml:"value"`
|
|
}
|
|
|
|
type rawLoader struct {
|
|
Supported string `xml:"supported,attr"`
|
|
Secure string `xml:"secure,attr"`
|
|
Values []string `xml:"value"`
|
|
Enums []rawEnum `xml:"enum"`
|
|
}
|
|
|
|
// ParseDomainCapabilitiesXML parses one libvirt domcapabilities document
|
|
// without invoking virsh or any host command. It intentionally rejects a
|
|
// namespace-qualified root, trailing XML documents, oversized input, and
|
|
// ambiguous Secure-Boot attributes.
|
|
func ParseDomainCapabilitiesXML(data []byte) (DomainCapabilities, error) {
|
|
if len(data) == 0 || len(data) > maxDomainCapabilitiesXMLBytes {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: size must be between 1 and %d bytes", ErrInvalidCapabilitiesXML, maxDomainCapabilitiesXMLBytes)
|
|
}
|
|
decoder := xml.NewDecoder(bytes.NewReader(data))
|
|
decoder.Strict = true
|
|
var raw rawDomainCapabilities
|
|
if err := decoder.Decode(&raw); err != nil {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: decode: %v", ErrInvalidCapabilitiesXML, err)
|
|
}
|
|
if raw.XMLName.Space != "" || raw.XMLName.Local != "domainCapabilities" {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: root must be <domainCapabilities>", ErrInvalidCapabilitiesXML)
|
|
}
|
|
for {
|
|
token, err := decoder.Token()
|
|
if errors.Is(err, io.EOF) {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: trailing XML: %v", ErrInvalidCapabilitiesXML, err)
|
|
}
|
|
switch value := token.(type) {
|
|
case xml.CharData:
|
|
if strings.TrimSpace(string(value)) == "" {
|
|
continue
|
|
}
|
|
return DomainCapabilities{}, fmt.Errorf("%w: non-whitespace text after root", ErrInvalidCapabilitiesXML)
|
|
case xml.Comment, xml.ProcInst, xml.Directive:
|
|
// XML comments and processing instructions after the root are
|
|
// harmless and are emitted by a few libvirt wrappers.
|
|
default:
|
|
return DomainCapabilities{}, fmt.Errorf("%w: multiple root documents", ErrInvalidCapabilitiesXML)
|
|
}
|
|
}
|
|
if len(raw.OS) != 1 {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: expected exactly one <os>, got %d", ErrInvalidCapabilitiesXML, len(raw.OS))
|
|
}
|
|
os := raw.OS[0]
|
|
if os.Supported != "yes" && os.Supported != "" && os.Supported != "no" {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: <os supported=%q>", ErrInvalidCapabilitiesXML, os.Supported)
|
|
}
|
|
if os.Supported == "no" {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: <os supported=%q>", ErrCapabilityPolicy, os.Supported)
|
|
}
|
|
|
|
caps := DomainCapabilities{
|
|
Architecture: strings.TrimSpace(raw.Arch.Text),
|
|
Machines: nil,
|
|
}
|
|
if caps.Architecture == "" {
|
|
caps.Architecture = strings.TrimSpace(raw.Arch.Name)
|
|
}
|
|
for _, machine := range raw.Machines {
|
|
value := strings.TrimSpace(machine.Text)
|
|
if value == "" {
|
|
value = strings.TrimSpace(machine.Canonical)
|
|
}
|
|
if value != "" && !containsString(caps.Machines, value) {
|
|
caps.Machines = append(caps.Machines, value)
|
|
}
|
|
}
|
|
for _, enum := range os.Enums {
|
|
if strings.TrimSpace(enum.Name) != "firmware" {
|
|
continue
|
|
}
|
|
for _, value := range enum.Values {
|
|
value = strings.TrimSpace(value)
|
|
if value != "" && !containsString(caps.Firmware, value) {
|
|
caps.Firmware = append(caps.Firmware, value)
|
|
}
|
|
}
|
|
}
|
|
for _, loader := range os.Loaders {
|
|
supported := loader.Supported != "no"
|
|
if loader.Supported != "yes" && loader.Supported != "no" && loader.Supported != "" {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: loader supported=%q", ErrInvalidCapabilitiesXML, loader.Supported)
|
|
}
|
|
if !supported {
|
|
continue
|
|
}
|
|
secureAttr := strings.TrimSpace(strings.ToLower(loader.Secure))
|
|
if secureAttr != "" && secureAttr != "yes" && secureAttr != "no" {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: loader secure=%q", ErrInvalidCapabilitiesXML, loader.Secure)
|
|
}
|
|
values := normalizeStrings(loader.Values)
|
|
if len(values) == 0 {
|
|
return DomainCapabilities{}, fmt.Errorf("%w: supported loader has no <value>", ErrInvalidCapabilitiesXML)
|
|
}
|
|
secureOptions, err := secureEnumValues(loader.Enums)
|
|
if err != nil {
|
|
return DomainCapabilities{}, err
|
|
}
|
|
for _, path := range values {
|
|
secure, err := classifyLoaderSecurity(path, secureAttr, secureOptions)
|
|
if err != nil {
|
|
return DomainCapabilities{}, err
|
|
}
|
|
caps.Loaders = append(caps.Loaders, LoaderCapability{
|
|
Path: path,
|
|
Supported: true,
|
|
Secure: secure,
|
|
SecureOptions: append([]string(nil), secureOptions...),
|
|
})
|
|
}
|
|
}
|
|
return caps, nil
|
|
}
|
|
|
|
// ValidatePolicy checks whether the parsed host can satisfy the product's
|
|
// fixed x86_64 + EFI + Q35 + Secure-Boot-disabled contract.
|
|
func (caps DomainCapabilities) ValidatePolicy() error {
|
|
if caps.Architecture != "x86_64" {
|
|
return fmt.Errorf("%w: architecture=%q, expected x86_64", ErrCapabilityPolicy, caps.Architecture)
|
|
}
|
|
if !containsString(caps.Firmware, "efi") {
|
|
return fmt.Errorf("%w: EFI firmware is unavailable", ErrCapabilityPolicy)
|
|
}
|
|
q35 := false
|
|
for _, machine := range caps.Machines {
|
|
if isQ35MachineName(machine) {
|
|
q35 = true
|
|
break
|
|
}
|
|
}
|
|
if !q35 {
|
|
return fmt.Errorf("%w: Q35 machine is unavailable", ErrCapabilityPolicy)
|
|
}
|
|
if !caps.hasNonSecureLoader() {
|
|
return fmt.Errorf("%w: %w", ErrCapabilityPolicy, ErrNoNonSecureLoader)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SupportsMachine reports whether a requested machine value is represented by
|
|
// the host capability document. The shorthand "q35" is considered supported
|
|
// when the host advertises any versioned pc-q35-* machine; a specific version
|
|
// must otherwise match exactly so the agent does not invent an unsupported
|
|
// machine string.
|
|
func (caps DomainCapabilities) SupportsMachine(machine string) bool {
|
|
machine = strings.TrimSpace(machine)
|
|
if machine == "q35" {
|
|
for _, advertised := range caps.Machines {
|
|
if isQ35MachineName(advertised) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
return containsString(caps.Machines, machine)
|
|
}
|
|
|
|
// NonSecureLoaderPaths returns a copy of loader paths that are safe candidates
|
|
// for the product's Secure-Boot-disabled policy. The method does not select a
|
|
// path or mutate the capability snapshot.
|
|
func (caps DomainCapabilities) NonSecureLoaderPaths() []string {
|
|
paths := make([]string, 0)
|
|
for _, loader := range caps.Loaders {
|
|
if loader.Supported && loader.Secure == "no" {
|
|
paths = append(paths, loader.Path)
|
|
}
|
|
}
|
|
return paths
|
|
}
|
|
|
|
// PreferredNonSecureLoaderPath chooses a deterministic ordinary OVMF path
|
|
// from the host's advertised descriptors. Secure-Boot-labelled paths are
|
|
// already excluded by the parser. The plain CODE_4M.fd descriptor is
|
|
// preferred over Microsoft-key and other variants so a copied XML cannot
|
|
// accidentally inherit enrolled Secure-Boot keys.
|
|
func (caps DomainCapabilities) PreferredNonSecureLoaderPath() (string, error) {
|
|
paths := caps.NonSecureLoaderPaths()
|
|
if len(paths) == 0 {
|
|
return "", fmt.Errorf("%w: no non-secure loader path", ErrNoNonSecureLoader)
|
|
}
|
|
sort.SliceStable(paths, func(i, j int) bool {
|
|
return loaderPathRank(paths[i]) < loaderPathRank(paths[j])
|
|
})
|
|
return paths[0], nil
|
|
}
|
|
|
|
func loaderPathRank(path string) int {
|
|
base := strings.ToLower(path)
|
|
switch {
|
|
case strings.HasSuffix(base, "ovmf_code_4m.fd"):
|
|
return 0
|
|
case strings.HasSuffix(base, "ovmf_code.fd"):
|
|
return 1
|
|
case strings.Contains(base, ".ms.fd"):
|
|
return 2
|
|
default:
|
|
return 3
|
|
}
|
|
}
|
|
|
|
// Snapshot converts domcapabilities into the common host capability shape.
|
|
// It does not claim cloud-init, QGA, or snapshot support because those facts
|
|
// are not proven by this XML subset.
|
|
func (caps DomainCapabilities) Snapshot() CapabilitySnapshot {
|
|
snapshot := CapabilitySnapshot{
|
|
Backend: "libvirt-domcapabilities",
|
|
Architecture: caps.Architecture,
|
|
UEFI: containsString(caps.Firmware, "efi"),
|
|
SecureBootCapable: false,
|
|
SecureBootDisabled: caps.hasNonSecureLoader(),
|
|
ObservedAt: time.Now().UTC(),
|
|
}
|
|
for _, machine := range caps.Machines {
|
|
if isQ35MachineName(machine) {
|
|
snapshot.Q35 = true
|
|
}
|
|
}
|
|
for _, loader := range caps.Loaders {
|
|
if loader.Secure == "yes" || containsString(loader.SecureOptions, "yes") {
|
|
snapshot.SecureBootCapable = true
|
|
}
|
|
}
|
|
return snapshot
|
|
}
|
|
|
|
// ParseCapabilitySnapshotXML is the fail-closed convenience API used by a
|
|
// host adapter: malformed XML or a host without a safe EFI loader returns an
|
|
// error instead of a degraded snapshot that might be used for writes.
|
|
func ParseCapabilitySnapshotXML(data []byte) (CapabilitySnapshot, error) {
|
|
caps, err := ParseDomainCapabilitiesXML(data)
|
|
if err != nil {
|
|
return CapabilitySnapshot{}, err
|
|
}
|
|
if err := caps.ValidatePolicy(); err != nil {
|
|
return CapabilitySnapshot{}, err
|
|
}
|
|
snapshot := caps.Snapshot()
|
|
if err := CheckEFIQ35NoSecureBoot(snapshot); err != nil {
|
|
return CapabilitySnapshot{}, err
|
|
}
|
|
return snapshot, nil
|
|
}
|
|
|
|
func (caps DomainCapabilities) hasNonSecureLoader() bool {
|
|
return len(caps.NonSecureLoaderPaths()) != 0
|
|
}
|
|
|
|
func classifyLoaderSecurity(path, secureAttr string, secureOptions []string) (string, error) {
|
|
pathLower := strings.ToLower(path)
|
|
pathLooksSecure := strings.Contains(pathLower, "secboot") ||
|
|
strings.Contains(pathLower, "secureboot") || strings.Contains(pathLower, "secure-boot")
|
|
hasYes := containsString(secureOptions, "yes")
|
|
hasNo := containsString(secureOptions, "no")
|
|
switch secureAttr {
|
|
case "yes":
|
|
if hasNo && !hasYes {
|
|
return "", fmt.Errorf("%w: loader secure=\"yes\" is absent from capability enum", ErrCapabilityPolicy)
|
|
}
|
|
return "yes", nil
|
|
case "no":
|
|
if hasYes && !hasNo {
|
|
return "", fmt.Errorf("%w: loader secure=\"no\" is absent from capability enum", ErrCapabilityPolicy)
|
|
}
|
|
if pathLooksSecure {
|
|
return "", fmt.Errorf("%w: loader secure=no points to a Secure-Boot descriptor", ErrCapabilityPolicy)
|
|
}
|
|
return "no", nil
|
|
case "":
|
|
if hasYes && !hasNo {
|
|
return "yes", nil
|
|
}
|
|
if hasNo && !hasYes {
|
|
if pathLooksSecure {
|
|
return "", fmt.Errorf("%w: secboot loader lacks a secure=yes capability", ErrCapabilityPolicy)
|
|
}
|
|
return "no", nil
|
|
}
|
|
if pathLooksSecure {
|
|
return "yes", nil
|
|
}
|
|
return "no", nil
|
|
default:
|
|
return "", fmt.Errorf("%w: loader secure=%q", ErrInvalidCapabilitiesXML, secureAttr)
|
|
}
|
|
}
|
|
|
|
func secureEnumValues(enums []rawEnum) ([]string, error) {
|
|
var result []string
|
|
for _, enum := range enums {
|
|
if strings.TrimSpace(enum.Name) != "secure" {
|
|
continue
|
|
}
|
|
for _, value := range normalizeStrings(enum.Values) {
|
|
value = strings.ToLower(value)
|
|
if value != "yes" && value != "no" {
|
|
return nil, fmt.Errorf("%w: loader secure enum contains %q", ErrInvalidCapabilitiesXML, value)
|
|
}
|
|
if !containsString(result, value) {
|
|
result = append(result, value)
|
|
}
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func isQ35MachineName(value string) bool {
|
|
return value == "q35" ||
|
|
(strings.HasPrefix(value, "pc-q35-") && len(value) > len("pc-q35-"))
|
|
}
|
|
|
|
func normalizeStrings(values []string) []string {
|
|
result := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
value = strings.TrimSpace(value)
|
|
if value != "" && !containsString(result, value) {
|
|
result = append(result, value)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func containsString(values []string, want string) bool {
|
|
for _, value := range values {
|
|
if value == want {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|