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.
1042 lines
34 KiB
Go
1042 lines
34 KiB
Go
// Package domainxml owns the small, security-sensitive portion of a libvirt
|
|
// domain definition that describes the guest firmware platform.
|
|
//
|
|
// The agent deliberately keeps this package independent from a libvirt
|
|
// binding. A domain definition can therefore be normalized and verified
|
|
// before it crosses the host API boundary, and the same checks can be used on
|
|
// create, reinstall, and rescue XML copied from a previous definition.
|
|
package domainxml
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/xml"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"path"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
requiredFirmware = "efi"
|
|
requiredArch = "x86_64"
|
|
requiredMachine = "q35"
|
|
requiredOSType = "hvm"
|
|
requiredLoaderType = "pflash"
|
|
requiredLoaderRO = "yes"
|
|
maxDomainXMLBytes = 4 << 20
|
|
)
|
|
|
|
var (
|
|
// ErrInvalidXML means that the input is not one complete libvirt domain
|
|
// document. It is intentionally distinct from a policy error so callers
|
|
// can report malformed input without suggesting a host capability issue.
|
|
ErrInvalidXML = errors.New("invalid libvirt domain XML")
|
|
// ErrUnsupportedPlatform means an existing, explicit platform choice is
|
|
// incompatible with the agent's UEFI/q35 policy. Normalize never silently
|
|
// changes one architecture or machine type into another.
|
|
ErrUnsupportedPlatform = errors.New("unsupported libvirt guest platform")
|
|
// ErrPolicyViolation means that a normalized document does not satisfy the
|
|
// no-Secure-Boot policy (or contains an ambiguous policy node).
|
|
ErrPolicyViolation = errors.New("libvirt firmware policy violation")
|
|
)
|
|
|
|
// Normalize returns a canonical domain definition for the agent's firmware
|
|
// policy.
|
|
//
|
|
// Missing policy nodes are added. Existing explicit values are checked before
|
|
// they are changed: an existing non-EFI firmware, non-x86_64 architecture,
|
|
// non-q35 machine, or non-hvm OS type is rejected instead of being silently
|
|
// replaced. Secure Boot is the one intentional policy migration: an existing
|
|
// secure-boot feature is explicitly rewritten to enabled="no" because this
|
|
// agent never provisions Secure Boot. The returned pre-host document must be
|
|
// passed through NormalizeWithLoader before it is sent to libvirt; that
|
|
// host-bound form is the one that must pass Validate.
|
|
func Normalize(input []byte) ([]byte, error) {
|
|
doc, err := parse(input)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
root := doc.root
|
|
if root.name.Local != "domain" || root.name.Space != "" {
|
|
return nil, fmt.Errorf("%w: root element must be <domain>", ErrInvalidXML)
|
|
}
|
|
|
|
osNodes := root.childrenNamed("os")
|
|
if len(osNodes) > 1 {
|
|
return nil, fmt.Errorf("%w: domain contains %d <os> elements", ErrPolicyViolation, len(osNodes))
|
|
}
|
|
var osNode *element
|
|
if len(osNodes) == 1 {
|
|
osNode = osNodes[0]
|
|
} else {
|
|
osNode = &element{name: xml.Name{Local: "os"}}
|
|
// Keep the document in libvirt's conventional top-level order. Appending
|
|
// <os> after <devices> can make an otherwise valid copied definition
|
|
// fail libvirt's XML schema validation.
|
|
root.insertBeforeFirst(osNode, "features", "cpu", "clock", "on_poweroff", "on_reboot", "on_crash", "devices")
|
|
}
|
|
|
|
if err := normalizeOS(osNode); err != nil {
|
|
return nil, err
|
|
}
|
|
// Normalize is the pre-host form: it may still omit the host-selected
|
|
// loader. NormalizeWithLoader performs the strict, host-bound form below.
|
|
if err := validateRoot(root, false); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var out bytes.Buffer
|
|
if err := doc.write(&out); err != nil {
|
|
return nil, fmt.Errorf("encode normalized domain XML: %w", err)
|
|
}
|
|
return out.Bytes(), nil
|
|
}
|
|
|
|
// NormalizeWithLoader applies the same platform and Secure-Boot policy as
|
|
// Normalize and, when the input does not name a firmware loader, pins the
|
|
// definition to one host-advertised non-secure loader path. A caller must
|
|
// obtain loaderPath from a fresh capability probe; this function never
|
|
// guesses a path or silently replaces an explicit one.
|
|
func NormalizeWithLoader(input []byte, loaderPath string) ([]byte, error) {
|
|
normalized, err := Normalize(input)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
loaderPath = strings.TrimSpace(loaderPath)
|
|
if loaderPath == "" {
|
|
return nil, fmt.Errorf("%w: host loader path is required", ErrPolicyViolation)
|
|
}
|
|
if err := validateLoaderPath(loaderPath); err != nil {
|
|
return nil, err
|
|
}
|
|
doc, err := parse(normalized)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
osNodes := doc.root.childrenNamed("os")
|
|
if len(osNodes) != 1 {
|
|
return nil, fmt.Errorf("%w: normalized domain must contain one <os>", ErrPolicyViolation)
|
|
}
|
|
osNode := osNodes[0]
|
|
loaders := osNode.childrenNamed("loader")
|
|
if len(loaders) > 1 {
|
|
return nil, fmt.Errorf("%w: os contains %d <loader> elements", ErrPolicyViolation, len(loaders))
|
|
}
|
|
if len(loaders) == 0 {
|
|
loader := &element{name: xml.Name{Local: "loader"}}
|
|
loader.setAttr("readonly", "yes")
|
|
loader.setAttr("type", "pflash")
|
|
loader.replaceText(loaderPath)
|
|
// The loader belongs before nvram/boot so libvirt sees the conventional
|
|
// firmware ordering even when the source XML omitted both nodes.
|
|
osNode.insertBeforeFirst(loader, "nvram", "boot")
|
|
} else {
|
|
loader := loaders[0]
|
|
existing := strings.TrimSpace(loader.text())
|
|
if existing != "" && existing != loaderPath {
|
|
return nil, fmt.Errorf("%w: explicit loader %q differs from host-selected %q", ErrPolicyViolation, existing, loaderPath)
|
|
}
|
|
loader.replaceText(loaderPath)
|
|
if err := normalizeLoaderAttributes(loader); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
var out bytes.Buffer
|
|
if err := doc.write(&out); err != nil {
|
|
return nil, fmt.Errorf("encode normalized domain XML: %w", err)
|
|
}
|
|
if err := Validate(out.Bytes()); err != nil {
|
|
return nil, err
|
|
}
|
|
return out.Bytes(), nil
|
|
}
|
|
|
|
// Machine returns the normalized machine name from one complete domain
|
|
// document. It is used to intersect caller intent with the host capability
|
|
// document instead of accepting the generic q35 family blindly.
|
|
func Machine(input []byte) (string, error) {
|
|
doc, err := parse(input)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
osNodes := doc.root.childrenNamed("os")
|
|
if len(osNodes) != 1 {
|
|
return "", fmt.Errorf("%w: domain must contain exactly one <os>", ErrPolicyViolation)
|
|
}
|
|
types := osNodes[0].childrenNamed("type")
|
|
if len(types) != 1 {
|
|
return "", fmt.Errorf("%w: os must contain exactly one <type>", ErrPolicyViolation)
|
|
}
|
|
machine, err := types[0].requiredAttr("machine", "os/type")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return strings.TrimSpace(machine), nil
|
|
}
|
|
|
|
// Validate checks that input already contains the exact firmware policy used
|
|
// by the agent. Unlike Normalize, Validate never changes the document and
|
|
// therefore is suitable for a read-back assertion after defineXML.
|
|
func Validate(input []byte) error {
|
|
doc, err := parse(input)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := validateHostPathPolicyDocument(doc.root); err != nil {
|
|
return err
|
|
}
|
|
return validateRoot(doc.root, true)
|
|
}
|
|
|
|
// ValidateHostPathPolicy rejects host-facing XML constructs that are not part
|
|
// of the v1 typed storage/network contract. The generic libvirt XML format is
|
|
// much wider than the Agent API: a caller can otherwise smuggle a remote disk
|
|
// protocol, a block device, a host interface, a firmware NVRAM path, or a
|
|
// socket/file-backed device through an otherwise valid domain definition.
|
|
//
|
|
// File-backed disks are the one intentional exception. Their source must be
|
|
// exactly a `file` attribute; the host adapter applies the configured storage
|
|
// allowlist immediately before handing the XML to libvirt. Network devices,
|
|
// console channels, filesystems and other host path carriers remain reserved
|
|
// for future typed operations with their own ownership/read-back contracts.
|
|
func ValidateHostPathPolicy(input []byte) error {
|
|
doc, err := parse(input)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return validateHostPathPolicyDocument(doc.root)
|
|
}
|
|
|
|
// validateHostPathPolicyDocument is the parser-level form used after a
|
|
// document has already been parsed and normalized. Keeping the parser type
|
|
// private prevents callers from constructing an unchecked syntax tree.
|
|
func validateHostPathPolicyDocument(root *element) error {
|
|
if root == nil {
|
|
return fmt.Errorf("%w: domain document is empty", ErrInvalidXML)
|
|
}
|
|
return validateHostPathElements(root)
|
|
}
|
|
|
|
func validateHostPathElements(node *element) error {
|
|
if node == nil {
|
|
return nil
|
|
}
|
|
if node.name.Space != "" {
|
|
return fmt.Errorf("%w: namespaced host XML element <%s> is not allowed", ErrPolicyViolation, node.name.Local)
|
|
}
|
|
for _, attr := range node.attrs {
|
|
if attr.Name.Space != "" {
|
|
return fmt.Errorf("%w: namespaced attribute on <%s> is not allowed", ErrPolicyViolation, node.name.Local)
|
|
}
|
|
}
|
|
name := strings.ToLower(node.name.Local)
|
|
switch name {
|
|
case "interface":
|
|
return fmt.Errorf("%w: network interfaces require a typed network operation", ErrPolicyViolation)
|
|
case "filesystem":
|
|
return fmt.Errorf("%w: host filesystems are not allowed", ErrPolicyViolation)
|
|
case "nvram", "emulator":
|
|
return fmt.Errorf("%w: host firmware/emulator paths require an agent-owned resolver", ErrPolicyViolation)
|
|
case "serial", "parallel", "console", "channel", "shmem", "rng", "tpm", "redirdev", "smartcard":
|
|
if elementContainsHostSource(node) {
|
|
return fmt.Errorf("%w: host-backed device <%s> is not allowed", ErrPolicyViolation, name)
|
|
}
|
|
}
|
|
if name == "disk" {
|
|
if err := validateFileDiskSource(node); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for _, child := range node.children {
|
|
if child.kind != contentElement {
|
|
continue
|
|
}
|
|
if strings.EqualFold(child.elem.name.Local, "source") && name != "disk" && elementContainsHostSource(child.elem) {
|
|
return fmt.Errorf("%w: host source under <%s> is not allowed", ErrPolicyViolation, name)
|
|
}
|
|
if err := validateHostPathElements(child.elem); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateFileDiskSource(node *element) error {
|
|
diskType, ok := attributeValue(node, "type")
|
|
if ok && diskType != "file" {
|
|
return fmt.Errorf("%w: disk type %q is not an allowlisted file-backed disk", ErrPolicyViolation, diskType)
|
|
}
|
|
// XML element names are case-sensitive to libvirt, but rejecting a
|
|
// case-variant explicitly is safer than letting it fall through the
|
|
// case-sensitive childrenNamed helper and then missing a host path.
|
|
sources := make([]*element, 0, 1)
|
|
for _, child := range node.children {
|
|
if child.kind != contentElement || !strings.EqualFold(child.elem.name.Local, "source") {
|
|
continue
|
|
}
|
|
if child.elem.name.Local != "source" {
|
|
return fmt.Errorf("%w: disk source element name must be exactly <source>", ErrPolicyViolation)
|
|
}
|
|
sources = append(sources, child.elem)
|
|
}
|
|
if len(sources) > 1 {
|
|
return fmt.Errorf("%w: disk contains multiple source elements", ErrPolicyViolation)
|
|
}
|
|
if len(sources) == 0 {
|
|
return nil
|
|
}
|
|
source := sources[0]
|
|
filePath := ""
|
|
for _, attr := range source.attrs {
|
|
if attr.Name.Space != "" {
|
|
return fmt.Errorf("%w: namespaced disk source attributes are not allowed", ErrPolicyViolation)
|
|
}
|
|
switch attr.Name.Local {
|
|
case "file":
|
|
if filePath != "" {
|
|
return fmt.Errorf("%w: disk source contains duplicate file attributes", ErrPolicyViolation)
|
|
}
|
|
filePath = strings.TrimSpace(attr.Value)
|
|
default:
|
|
return fmt.Errorf("%w: disk source attribute %q is not an allowlisted local file", ErrPolicyViolation, attr.Name.Local)
|
|
}
|
|
}
|
|
if filePath == "" {
|
|
return fmt.Errorf("%w: disk source must name a local file", ErrPolicyViolation)
|
|
}
|
|
if source.hasElementChildren() || strings.TrimSpace(source.text()) != "" {
|
|
return fmt.Errorf("%w: disk source must contain only a file attribute", ErrPolicyViolation)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func elementContainsHostSource(node *element) bool {
|
|
if node == nil {
|
|
return false
|
|
}
|
|
if strings.EqualFold(node.name.Local, "source") {
|
|
return true
|
|
}
|
|
for _, attr := range node.attrs {
|
|
switch strings.ToLower(attr.Name.Local) {
|
|
case "file", "path", "dev", "dir", "protocol", "socket", "volume", "pool":
|
|
return true
|
|
}
|
|
}
|
|
if strings.TrimSpace(node.text()) != "" {
|
|
return true
|
|
}
|
|
for _, child := range node.children {
|
|
if child.kind == contentElement && elementContainsHostSource(child.elem) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// FileBackedDiskPaths returns the host paths used by file-backed disk
|
|
// sources. It is intentionally a parser-level operation rather than a
|
|
// regexp: XML escaping, element ordering and namespace-qualified elements
|
|
// must not let a path skip the storage policy. The returned paths are still
|
|
// untrusted strings; callers must pass them through a host storage allowlist
|
|
// before invoking libvirt.
|
|
func FileBackedDiskPaths(input []byte) ([]string, error) {
|
|
doc, err := parse(input)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
paths := make([]string, 0, 1)
|
|
var walk func(*element) error
|
|
walk = func(node *element) error {
|
|
if node == nil {
|
|
return nil
|
|
}
|
|
if node.name.Space == "" && node.name.Local == "disk" {
|
|
diskType, err := node.singleAttr("type", "disk")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
sources := node.childrenNamed("source")
|
|
if len(sources) > 1 {
|
|
return fmt.Errorf("%w: disk contains %d <source> elements", ErrPolicyViolation, len(sources))
|
|
}
|
|
if len(sources) == 1 {
|
|
filePath, err := sources[0].singleAttr("file", "disk/source")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if strings.TrimSpace(filePath) != "" {
|
|
if diskType != "" && diskType != "file" {
|
|
return fmt.Errorf("%w: disk type=%q cannot contain a file-backed source", ErrPolicyViolation, diskType)
|
|
}
|
|
if strings.TrimSpace(filePath) != filePath {
|
|
return fmt.Errorf("%w: disk source path has surrounding whitespace", ErrPolicyViolation)
|
|
}
|
|
paths = append(paths, filePath)
|
|
}
|
|
}
|
|
}
|
|
for _, child := range node.children {
|
|
if child.kind == contentElement {
|
|
if err := walk(child.elem); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if err := walk(doc.root); err != nil {
|
|
return nil, err
|
|
}
|
|
return paths, nil
|
|
}
|
|
|
|
func normalizeOS(osNode *element) error {
|
|
firmware, err := osNode.singleAttr("firmware", "os")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if firmware == "" {
|
|
osNode.setAttr("firmware", requiredFirmware)
|
|
} else if firmware != requiredFirmware {
|
|
return fmt.Errorf("%w: os firmware=%q, expected %q", ErrUnsupportedPlatform, firmware, requiredFirmware)
|
|
}
|
|
|
|
types := osNode.childrenNamed("type")
|
|
if len(types) > 1 {
|
|
return fmt.Errorf("%w: os contains %d <type> elements", ErrUnsupportedPlatform, len(types))
|
|
}
|
|
var typeNode *element
|
|
if len(types) == 1 {
|
|
typeNode = types[0]
|
|
} else {
|
|
typeNode = &element{name: xml.Name{Local: "type"}}
|
|
// libvirt's conventional order is <type>, then firmware/boot. Keeping
|
|
// the insertion local also means copied reinstall/rescue devices remain
|
|
// byte-for-byte represented apart from the policy nodes.
|
|
osNode.insertChild(0, typeNode)
|
|
}
|
|
if err := normalizeType(typeNode); err != nil {
|
|
return err
|
|
}
|
|
// A libvirt domain can request Secure Boot through the loader itself
|
|
// (`secure="yes"`) even when the firmware feature node is absent or says
|
|
// `enabled="no"`. Reject that conflicting signal instead of rewriting the
|
|
// attribute: a secboot OVMF descriptor cannot be made safe by changing one
|
|
// XML flag after the fact.
|
|
if err := validateLoaderPolicy(osNode, false); err != nil {
|
|
return err
|
|
}
|
|
|
|
firmwares := osNode.childrenNamed("firmware")
|
|
if len(firmwares) > 1 {
|
|
return fmt.Errorf("%w: os contains %d <firmware> elements", ErrPolicyViolation, len(firmwares))
|
|
}
|
|
var firmwareNode *element
|
|
if len(firmwares) == 1 {
|
|
firmwareNode = firmwares[0]
|
|
} else {
|
|
firmwareNode = &element{name: xml.Name{Local: "firmware"}}
|
|
// Put firmware directly after type where possible. This is cosmetic,
|
|
// but makes read-back XML stable across create/reinstall/rescue paths.
|
|
osNode.insertAfter(typeNode, firmwareNode)
|
|
}
|
|
features := firmwareNode.childrenNamed("feature")
|
|
var secureBoot []*element
|
|
for _, feature := range features {
|
|
name, err := feature.singleAttr("name", "firmware/feature")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if name == "secure-boot" {
|
|
secureBoot = append(secureBoot, feature)
|
|
}
|
|
}
|
|
if len(secureBoot) > 1 {
|
|
return fmt.Errorf("%w: firmware contains %d secure-boot features", ErrPolicyViolation, len(secureBoot))
|
|
}
|
|
if len(secureBoot) == 0 {
|
|
feature := &element{name: xml.Name{Local: "feature"}}
|
|
feature.setAttr("name", "secure-boot")
|
|
feature.setAttr("enabled", "no")
|
|
firmwareNode.children = append(firmwareNode.children, content{kind: contentElement, elem: feature})
|
|
} else {
|
|
// Disabling Secure Boot is an explicit product policy, not a host
|
|
// capability fallback. Preserve unrelated attributes on the feature.
|
|
secureBoot[0].setAttr("enabled", "no")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func normalizeType(typeNode *element) error {
|
|
arch, err := typeNode.singleAttr("arch", "os/type")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if arch == "" {
|
|
typeNode.setAttr("arch", requiredArch)
|
|
} else if arch != requiredArch {
|
|
return fmt.Errorf("%w: os/type arch=%q, expected %q", ErrUnsupportedPlatform, arch, requiredArch)
|
|
}
|
|
|
|
machine, err := typeNode.singleAttr("machine", "os/type")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if machine == "" {
|
|
typeNode.setAttr("machine", requiredMachine)
|
|
} else if !isQ35Machine(machine) {
|
|
return fmt.Errorf("%w: os/type machine=%q, expected %q", ErrUnsupportedPlatform, machine, requiredMachine)
|
|
}
|
|
|
|
if typeNode.hasElementChildren() {
|
|
return fmt.Errorf("%w: os/type must contain only hvm text", ErrUnsupportedPlatform)
|
|
}
|
|
typeText := strings.TrimSpace(typeNode.text())
|
|
if typeText == "" {
|
|
typeNode.replaceText(requiredOSType)
|
|
} else if typeText != requiredOSType {
|
|
return fmt.Errorf("%w: os/type=%q, expected %q", ErrUnsupportedPlatform, typeText, requiredOSType)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateRoot(root *element, requireLoader bool) error {
|
|
if root == nil || root.name.Local != "domain" || root.name.Space != "" {
|
|
return fmt.Errorf("%w: root element must be <domain>", ErrInvalidXML)
|
|
}
|
|
osNodes := root.childrenNamed("os")
|
|
if len(osNodes) != 1 {
|
|
return fmt.Errorf("%w: domain must contain exactly one <os> element", ErrPolicyViolation)
|
|
}
|
|
osNode := osNodes[0]
|
|
firmware, err := osNode.requiredAttr("firmware", "os")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if firmware != requiredFirmware {
|
|
return fmt.Errorf("%w: os firmware=%q, expected %q", ErrUnsupportedPlatform, firmware, requiredFirmware)
|
|
}
|
|
types := osNode.childrenNamed("type")
|
|
if len(types) != 1 {
|
|
return fmt.Errorf("%w: os must contain exactly one <type> element", ErrPolicyViolation)
|
|
}
|
|
typeNode := types[0]
|
|
arch, err := typeNode.requiredAttr("arch", "os/type")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if arch != requiredArch {
|
|
return fmt.Errorf("%w: os/type arch=%q, expected %q", ErrUnsupportedPlatform, arch, requiredArch)
|
|
}
|
|
machine, err := typeNode.requiredAttr("machine", "os/type")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !isQ35Machine(machine) {
|
|
return fmt.Errorf("%w: os/type machine=%q, expected %q", ErrUnsupportedPlatform, machine, requiredMachine)
|
|
}
|
|
if typeNode.hasElementChildren() || strings.TrimSpace(typeNode.text()) != requiredOSType {
|
|
return fmt.Errorf("%w: os/type must be %q", ErrUnsupportedPlatform, requiredOSType)
|
|
}
|
|
if err := validateLoaderPolicy(osNode, requireLoader); err != nil {
|
|
return err
|
|
}
|
|
|
|
firmwares := osNode.childrenNamed("firmware")
|
|
if len(firmwares) != 1 {
|
|
return fmt.Errorf("%w: os must contain exactly one <firmware> element", ErrPolicyViolation)
|
|
}
|
|
features := firmwares[0].childrenNamed("feature")
|
|
secureBoot := make([]*element, 0, 1)
|
|
for _, feature := range features {
|
|
name, err := feature.singleAttr("name", "firmware/feature")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if name == "secure-boot" {
|
|
secureBoot = append(secureBoot, feature)
|
|
}
|
|
}
|
|
if len(secureBoot) != 1 {
|
|
return fmt.Errorf("%w: exactly one secure-boot feature is required", ErrPolicyViolation)
|
|
}
|
|
enabled, err := secureBoot[0].requiredAttr("enabled", "firmware/feature")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if enabled != "no" {
|
|
return fmt.Errorf("%w: secure-boot enabled=%q, expected no", ErrPolicyViolation, enabled)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// libvirt may expand the shorthand machine="q35" to a versioned
|
|
// pc-q35-* value on XML read-back. Both forms are the same Q35 platform;
|
|
// i440fx and other machine families are never accepted.
|
|
func isQ35Machine(machine string) bool {
|
|
return machine == requiredMachine ||
|
|
(strings.HasPrefix(machine, "pc-q35-") && len(machine) > len("pc-q35-"))
|
|
}
|
|
|
|
// validateLoaderPolicy rejects the second libvirt Secure Boot spelling. The
|
|
// normal OVMF loader has no secure attribute (or explicitly says "no"); a
|
|
// loader path containing the conventional secboot marker is treated as secure
|
|
// too, because otherwise a copied XML could silently select the host's
|
|
// Secure-Boot descriptor while the feature node claims it is disabled.
|
|
func validateLoaderPolicy(osNode *element, requireAttributes bool) error {
|
|
loaders := osNode.childrenNamed("loader")
|
|
if len(loaders) > 1 {
|
|
return fmt.Errorf("%w: os contains %d <loader> elements", ErrPolicyViolation, len(loaders))
|
|
}
|
|
if len(loaders) == 0 {
|
|
if requireAttributes {
|
|
return fmt.Errorf("%w: os must contain exactly one <loader> element", ErrPolicyViolation)
|
|
}
|
|
return nil
|
|
}
|
|
loader := loaders[0]
|
|
loaderType, err := loader.singleAttr("type", "os/loader")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
readonly, err := loader.singleAttr("readonly", "os/loader")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if requireAttributes {
|
|
if loaderType != requiredLoaderType {
|
|
return fmt.Errorf("%w: os/loader type=%q, expected %q", ErrPolicyViolation, loaderType, requiredLoaderType)
|
|
}
|
|
if readonly != requiredLoaderRO {
|
|
return fmt.Errorf("%w: os/loader readonly=%q, expected %q", ErrPolicyViolation, readonly, requiredLoaderRO)
|
|
}
|
|
} else {
|
|
if loaderType != "" && loaderType != requiredLoaderType {
|
|
return fmt.Errorf("%w: os/loader type=%q, expected %q", ErrPolicyViolation, loaderType, requiredLoaderType)
|
|
}
|
|
if readonly != "" && readonly != requiredLoaderRO {
|
|
return fmt.Errorf("%w: os/loader readonly=%q, expected %q", ErrPolicyViolation, readonly, requiredLoaderRO)
|
|
}
|
|
}
|
|
secure, err := loader.singleAttr("secure", "os/loader")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if loader.hasElementChildren() {
|
|
return fmt.Errorf("%w: os/loader must contain only path text", ErrPolicyViolation)
|
|
}
|
|
pathValue := strings.TrimSpace(loader.text())
|
|
if pathValue == "" {
|
|
return fmt.Errorf("%w: os/loader path is required", ErrPolicyViolation)
|
|
}
|
|
if err := validateLoaderPath(pathValue); err != nil {
|
|
return err
|
|
}
|
|
loaderPathLower := strings.ToLower(pathValue)
|
|
pathLooksSecure := strings.Contains(loaderPathLower, "secboot") ||
|
|
strings.Contains(loaderPathLower, "secureboot") || strings.Contains(loaderPathLower, "secure-boot")
|
|
switch secure {
|
|
case "", "no":
|
|
if pathLooksSecure {
|
|
return fmt.Errorf("%w: os/loader points to a Secure-Boot descriptor", ErrPolicyViolation)
|
|
}
|
|
return nil
|
|
case "yes":
|
|
return fmt.Errorf("%w: os/loader secure=\"yes\" is forbidden", ErrPolicyViolation)
|
|
default:
|
|
return fmt.Errorf("%w: os/loader secure=%q is ambiguous", ErrPolicyViolation, secure)
|
|
}
|
|
}
|
|
|
|
// normalizeLoaderAttributes makes the host-bound form explicit. Missing
|
|
// attributes are safe to fill because the selected path came from a fresh
|
|
// host capability probe; explicit conflicting values are rejected rather than
|
|
// silently rewritten.
|
|
func normalizeLoaderAttributes(loader *element) error {
|
|
loaderType, err := loader.singleAttr("type", "os/loader")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if loaderType != "" && loaderType != requiredLoaderType {
|
|
return fmt.Errorf("%w: os/loader type=%q, expected %q", ErrPolicyViolation, loaderType, requiredLoaderType)
|
|
}
|
|
loader.setAttr("type", requiredLoaderType)
|
|
|
|
readonly, err := loader.singleAttr("readonly", "os/loader")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if readonly != "" && readonly != requiredLoaderRO {
|
|
return fmt.Errorf("%w: os/loader readonly=%q, expected %q", ErrPolicyViolation, readonly, requiredLoaderRO)
|
|
}
|
|
loader.setAttr("readonly", requiredLoaderRO)
|
|
return nil
|
|
}
|
|
|
|
func validateLoaderPath(loaderPath string) error {
|
|
loaderPath = strings.TrimSpace(loaderPath)
|
|
if loaderPath == "" {
|
|
return fmt.Errorf("%w: loader path is required", ErrPolicyViolation)
|
|
}
|
|
if !strings.HasPrefix(loaderPath, "/") || strings.ContainsAny(loaderPath, "\x00\r\n\t\\") {
|
|
return fmt.Errorf("%w: loader path must be an absolute host path", ErrPolicyViolation)
|
|
}
|
|
// Reject ambiguous paths instead of relying on filepath.Clean or a later
|
|
// libvirt canonicalization. In particular, a capability value containing
|
|
// `..` must not be able to escape the intended firmware directory.
|
|
if path.Clean(loaderPath) != loaderPath {
|
|
return fmt.Errorf("%w: loader path must be canonical", ErrPolicyViolation)
|
|
}
|
|
for _, component := range strings.Split(loaderPath, "/") {
|
|
if component == "." || component == ".." {
|
|
return fmt.Errorf("%w: loader path contains a traversal component", ErrPolicyViolation)
|
|
}
|
|
}
|
|
pathLower := strings.ToLower(loaderPath)
|
|
if strings.Contains(pathLower, "secboot") ||
|
|
strings.Contains(pathLower, "secureboot") ||
|
|
strings.Contains(pathLower, "secure-boot") {
|
|
return fmt.Errorf("%w: loader path points to a Secure-Boot descriptor", ErrPolicyViolation)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type contentKind uint8
|
|
|
|
const (
|
|
contentElement contentKind = iota
|
|
contentCharData
|
|
contentComment
|
|
contentDirective
|
|
contentProcInst
|
|
)
|
|
|
|
type content struct {
|
|
kind contentKind
|
|
elem *element
|
|
data []byte
|
|
procInst xml.ProcInst
|
|
}
|
|
|
|
type element struct {
|
|
name xml.Name
|
|
attrs []xml.Attr
|
|
children []content
|
|
}
|
|
|
|
type document struct {
|
|
prefix []content
|
|
root *element
|
|
suffix []content
|
|
}
|
|
|
|
func parse(input []byte) (*document, error) {
|
|
if len(bytes.TrimSpace(input)) == 0 {
|
|
return nil, fmt.Errorf("%w: document is empty", ErrInvalidXML)
|
|
}
|
|
if len(input) > maxDomainXMLBytes {
|
|
return nil, fmt.Errorf("%w: document exceeds %d bytes", ErrInvalidXML, maxDomainXMLBytes)
|
|
}
|
|
decoder := xml.NewDecoder(bytes.NewReader(input))
|
|
decoder.Strict = true
|
|
doc := &document{}
|
|
stack := make([]*element, 0, 8)
|
|
seenRoot := false
|
|
for {
|
|
token, err := decoder.Token()
|
|
if errors.Is(err, io.EOF) {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%w: %v", ErrInvalidXML, err)
|
|
}
|
|
switch value := token.(type) {
|
|
case xml.StartElement:
|
|
node := &element{name: value.Name, attrs: cloneAttrs(value.Attr)}
|
|
if len(stack) == 0 {
|
|
if seenRoot {
|
|
return nil, fmt.Errorf("%w: multiple root elements", ErrInvalidXML)
|
|
}
|
|
seenRoot = true
|
|
doc.root = node
|
|
} else {
|
|
stack[len(stack)-1].children = append(stack[len(stack)-1].children, content{kind: contentElement, elem: node})
|
|
}
|
|
stack = append(stack, node)
|
|
case xml.EndElement:
|
|
if len(stack) == 0 || stack[len(stack)-1].name != value.Name {
|
|
return nil, fmt.Errorf("%w: mismatched closing element %q", ErrInvalidXML, value.Name.Local)
|
|
}
|
|
stack = stack[:len(stack)-1]
|
|
case xml.CharData:
|
|
data := append([]byte(nil), value...)
|
|
if len(stack) == 0 {
|
|
if strings.TrimSpace(string(data)) != "" {
|
|
return nil, fmt.Errorf("%w: text outside root element", ErrInvalidXML)
|
|
}
|
|
if seenRoot {
|
|
doc.suffix = append(doc.suffix, content{kind: contentCharData, data: data})
|
|
} else {
|
|
doc.prefix = append(doc.prefix, content{kind: contentCharData, data: data})
|
|
}
|
|
continue
|
|
}
|
|
stack[len(stack)-1].children = append(stack[len(stack)-1].children, content{kind: contentCharData, data: data})
|
|
case xml.Comment:
|
|
item := content{kind: contentComment, data: append([]byte(nil), value...)}
|
|
if len(stack) == 0 {
|
|
if seenRoot {
|
|
doc.suffix = append(doc.suffix, item)
|
|
} else {
|
|
doc.prefix = append(doc.prefix, item)
|
|
}
|
|
} else {
|
|
stack[len(stack)-1].children = append(stack[len(stack)-1].children, item)
|
|
}
|
|
case xml.Directive:
|
|
// Do not carry a DOCTYPE or any other XML directive through to
|
|
// libvirt. This keeps entity/host-file semantics out of the agent
|
|
// policy boundary and avoids parser-dependent external references.
|
|
return nil, fmt.Errorf("%w: XML directives are not allowed", ErrInvalidXML)
|
|
case xml.ProcInst:
|
|
item := content{kind: contentProcInst, procInst: xml.ProcInst{Target: value.Target, Inst: append([]byte(nil), value.Inst...)}}
|
|
if len(stack) == 0 {
|
|
if seenRoot {
|
|
doc.suffix = append(doc.suffix, item)
|
|
} else {
|
|
doc.prefix = append(doc.prefix, item)
|
|
}
|
|
} else {
|
|
stack[len(stack)-1].children = append(stack[len(stack)-1].children, item)
|
|
}
|
|
}
|
|
}
|
|
if len(stack) != 0 || !seenRoot || doc.root == nil {
|
|
return nil, fmt.Errorf("%w: incomplete document", ErrInvalidXML)
|
|
}
|
|
if err := validateUnsafeElements(doc.root); err != nil {
|
|
return nil, err
|
|
}
|
|
return doc, nil
|
|
}
|
|
|
|
// validateUnsafeElements rejects parser-level escape constructs before the
|
|
// firmware and host-path policies run. The latter deliberately applies a
|
|
// stricter greenfield rule: ordinary libvirt network interfaces and all other
|
|
// host-backed devices remain reserved for typed Agent operations with explicit
|
|
// ownership and read-back contracts.
|
|
func validateUnsafeElements(root *element) error {
|
|
if root == nil {
|
|
return nil
|
|
}
|
|
if root.name.Local == "hostdev" ||
|
|
(root.name.Space != "" && strings.Contains(strings.ToLower(root.name.Space), "qemu") && root.name.Local != "domain") ||
|
|
root.name.Local == "commandline" {
|
|
return fmt.Errorf("%w: unsafe host passthrough element <%s> is not allowed", ErrPolicyViolation, root.name.Local)
|
|
}
|
|
switch root.name.Local {
|
|
case "disk":
|
|
if diskType, ok := attributeValue(root, "type"); ok && diskType == "block" {
|
|
return fmt.Errorf("%w: raw block disks are not allowed", ErrPolicyViolation)
|
|
}
|
|
case "interface":
|
|
if interfaceType, ok := attributeValue(root, "type"); ok && interfaceType == "hostdev" {
|
|
return fmt.Errorf("%w: host-device interfaces are not allowed", ErrPolicyViolation)
|
|
}
|
|
case "filesystem":
|
|
if filesystemType, ok := attributeValue(root, "type"); ok && (filesystemType == "mount" || filesystemType == "block") {
|
|
return fmt.Errorf("%w: host filesystem passthrough is not allowed", ErrPolicyViolation)
|
|
}
|
|
}
|
|
for _, child := range root.children {
|
|
if child.kind == contentElement {
|
|
if err := validateUnsafeElements(child.elem); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func attributeValue(node *element, name string) (string, bool) {
|
|
for _, attr := range node.attrs {
|
|
if attr.Name.Space == "" && attr.Name.Local == name {
|
|
return strings.ToLower(strings.TrimSpace(attr.Value)), true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
func (d *document) write(w io.Writer) error {
|
|
encoder := xml.NewEncoder(w)
|
|
writeContent := func(items []content) error {
|
|
for _, item := range items {
|
|
if err := item.write(encoder); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if err := writeContent(d.prefix); err != nil {
|
|
return err
|
|
}
|
|
if err := d.root.write(encoder); err != nil {
|
|
return err
|
|
}
|
|
if err := writeContent(d.suffix); err != nil {
|
|
return err
|
|
}
|
|
return encoder.Flush()
|
|
}
|
|
|
|
func (c content) write(encoder *xml.Encoder) error {
|
|
switch c.kind {
|
|
case contentElement:
|
|
return c.elem.write(encoder)
|
|
case contentCharData:
|
|
return encoder.EncodeToken(xml.CharData(c.data))
|
|
case contentComment:
|
|
return encoder.EncodeToken(xml.Comment(c.data))
|
|
case contentDirective:
|
|
return encoder.EncodeToken(xml.Directive(c.data))
|
|
case contentProcInst:
|
|
return encoder.EncodeToken(c.procInst)
|
|
default:
|
|
return fmt.Errorf("unknown XML content kind %d", c.kind)
|
|
}
|
|
}
|
|
|
|
func (e *element) write(encoder *xml.Encoder) error {
|
|
if err := encoder.EncodeToken(xml.StartElement{Name: e.name, Attr: e.attrs}); err != nil {
|
|
return err
|
|
}
|
|
for _, child := range e.children {
|
|
if err := child.write(encoder); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return encoder.EncodeToken(xml.EndElement{Name: e.name})
|
|
}
|
|
|
|
func cloneAttrs(attrs []xml.Attr) []xml.Attr {
|
|
cloned := make([]xml.Attr, len(attrs))
|
|
copy(cloned, attrs)
|
|
return cloned
|
|
}
|
|
|
|
func (e *element) childrenNamed(name string) []*element {
|
|
result := make([]*element, 0, 1)
|
|
for _, child := range e.children {
|
|
if child.kind == contentElement && child.elem.name.Space == "" && child.elem.name.Local == name {
|
|
result = append(result, child.elem)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func (e *element) insertChild(index int, child *element) {
|
|
if index < 0 {
|
|
index = 0
|
|
}
|
|
if index > len(e.children) {
|
|
index = len(e.children)
|
|
}
|
|
e.children = append(e.children, content{})
|
|
copy(e.children[index+1:], e.children[index:])
|
|
e.children[index] = content{kind: contentElement, elem: child}
|
|
}
|
|
|
|
func (e *element) insertAfter(after, child *element) {
|
|
for index, item := range e.children {
|
|
if item.kind == contentElement && item.elem == after {
|
|
e.insertChild(index+1, child)
|
|
return
|
|
}
|
|
}
|
|
e.children = append(e.children, content{kind: contentElement, elem: child})
|
|
}
|
|
|
|
func (e *element) insertBeforeFirst(child *element, names ...string) {
|
|
for index, item := range e.children {
|
|
if item.kind != contentElement {
|
|
continue
|
|
}
|
|
for _, name := range names {
|
|
if item.elem.name.Space == "" && item.elem.name.Local == name {
|
|
e.insertChild(index, child)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
e.children = append(e.children, content{kind: contentElement, elem: child})
|
|
}
|
|
|
|
func (e *element) hasElementChildren() bool {
|
|
for _, child := range e.children {
|
|
if child.kind == contentElement {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (e *element) text() string {
|
|
var builder strings.Builder
|
|
for _, child := range e.children {
|
|
if child.kind == contentCharData {
|
|
builder.Write(child.data)
|
|
}
|
|
}
|
|
return builder.String()
|
|
}
|
|
|
|
func (e *element) replaceText(value string) {
|
|
filtered := make([]content, 0, len(e.children)+1)
|
|
for _, child := range e.children {
|
|
if child.kind != contentCharData {
|
|
filtered = append(filtered, child)
|
|
}
|
|
}
|
|
filtered = append(filtered, content{kind: contentCharData, data: []byte(value)})
|
|
e.children = filtered
|
|
}
|
|
|
|
func (e *element) setAttr(name, value string) {
|
|
for index := range e.attrs {
|
|
if e.attrs[index].Name.Space == "" && e.attrs[index].Name.Local == name {
|
|
e.attrs[index].Value = value
|
|
return
|
|
}
|
|
}
|
|
e.attrs = append(e.attrs, xml.Attr{Name: xml.Name{Local: name}, Value: value})
|
|
}
|
|
|
|
func (e *element) singleAttr(name, path string) (string, error) {
|
|
var value string
|
|
found := false
|
|
for _, attr := range e.attrs {
|
|
if attr.Name.Space != "" || attr.Name.Local != name {
|
|
continue
|
|
}
|
|
if found {
|
|
return "", fmt.Errorf("%w: %s contains duplicate %q attributes", ErrPolicyViolation, path, name)
|
|
}
|
|
found = true
|
|
value = attr.Value
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
func (e *element) requiredAttr(name, path string) (string, error) {
|
|
value, err := e.singleAttr(name, path)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if value == "" {
|
|
return "", fmt.Errorf("%w: %s is missing %q", ErrPolicyViolation, path, name)
|
|
}
|
|
return value, nil
|
|
}
|