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.
virt/agent/hypervisor/storage_configuration.go

202 lines
6.4 KiB
Go

package hypervisor
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"os"
"path/filepath"
"strings"
)
const (
StorageRoleManaged = "managed"
StorageRoleTemplate = "template"
StorageRoleSeed = "seed"
StorageRoleUserISO = "user_iso"
StorageRoleRescue = "rescue"
maximumStoragePathBytes = 4096
)
type storageRolePath struct {
Role string
Path string
}
type storageConfigurationNotAppliedError struct{ cause error }
func (e *storageConfigurationNotAppliedError) Error() string { return e.cause.Error() }
func (e *storageConfigurationNotAppliedError) Unwrap() error { return e.cause }
func (e *storageConfigurationNotAppliedError) FailureSemantics() (bool, bool) {
return false, true
}
func storageConfigurationNotApplied(err error) error {
if err == nil {
return nil
}
return &storageConfigurationNotAppliedError{cause: err}
}
func storageRoles() []string {
return []string{StorageRoleManaged, StorageRoleTemplate, StorageRoleSeed, StorageRoleUserISO, StorageRoleRescue}
}
func validateStorageDirectories(request StorageConfigurationRequest, allowedRoots []string) error {
if err := ValidateStorageConfigurationRequest(request); err != nil {
return err
}
if len(allowedRoots) == 0 {
return NewError(ErrUnavailable, "storage_path_roots_not_configured", "Agent storage path roots are not configured", nil)
}
for _, root := range allowedRoots {
if storagePathIsDangerous(root) {
return NewError(ErrUnavailable, "storage_path_root_unsafe", "an Agent storage path root targets a protected system location", nil)
}
if _, err := validateRealDirectory(root); err != nil {
return NewError(ErrUnavailable, "storage_path_root_unavailable", "an Agent storage path root is unavailable", err)
}
}
directoryInfos := make([]os.FileInfo, 0, len(storageRolePaths(request)))
for _, item := range storageRolePaths(request) {
if storagePathIsDangerous(item.Path) {
return NewError(ErrInvalid, "storage_path_unsafe", "a storage directory targets a protected system location", nil)
}
info, err := validateRealDirectory(item.Path)
if err != nil {
return NewError(ErrInvalid, "storage_directory_invalid", "a storage directory is missing, not a directory, or contains a symbolic link", err)
}
if storageFileInfoAlreadyUsed(directoryInfos, info) {
return NewError(ErrInvalid, "invalid_storage_configuration", "storage directories must not resolve to the same filesystem object", nil)
}
directoryInfos = append(directoryInfos, info)
allowed := false
for _, root := range allowedRoots {
relative, err := filepath.Rel(root, item.Path)
if err == nil && relative != "." && relative != ".." &&
!strings.HasPrefix(relative, ".."+string(filepath.Separator)) && !filepath.IsAbs(relative) {
allowed = true
break
}
}
if !allowed {
return NewError(ErrInvalid, "storage_path_not_allowed", "a storage directory is outside the Agent allow-list", nil)
}
}
return nil
}
func storageFileInfoAlreadyUsed(existing []os.FileInfo, candidate os.FileInfo) bool {
for _, item := range existing {
if os.SameFile(item, candidate) {
return true
}
}
return false
}
func storagePathIsDangerous(path string) bool {
protectedTrees := []string{
"/bin", "/boot", "/dev", "/etc", "/lib", "/lib64", "/proc", "/root",
"/run", "/sbin", "/sys", "/usr", "/var/lib/virt-agent", "/var/log",
}
separator := string(filepath.Separator)
for _, protected := range protectedTrees {
if path == protected || strings.HasPrefix(path, protected+separator) {
return true
}
}
for _, broad := range []string{"/var", "/var/lib", "/var/lib/libvirt", "/var/lib/libvirt/images"} {
if path == broad {
return true
}
}
return false
}
func validateRealDirectory(path string) (os.FileInfo, error) {
info, err := os.Lstat(path)
if err != nil {
return nil, err
}
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return nil, errors.New("path is not a real directory")
}
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
return nil, err
}
if resolved != path {
return nil, errors.New("path contains a symbolic link")
}
return info, nil
}
func storageRolePaths(request StorageConfigurationRequest) []storageRolePath {
return []storageRolePath{
{Role: StorageRoleManaged, Path: request.ManagedDirectory},
{Role: StorageRoleTemplate, Path: request.TemplateDirectory},
{Role: StorageRoleSeed, Path: request.SeedDirectory},
{Role: StorageRoleUserISO, Path: request.UserISODirectory},
{Role: StorageRoleRescue, Path: request.RescueDirectory},
}
}
// configureStorageRoles deliberately retains all completed role mutations if
// a later role fails. A new operation can then reuse and finish the same fixed
// pool mapping without any rollback racing a late worker.
func configureStorageRoles(ctx context.Context, request StorageConfigurationRequest, resolve func(string, string) error) error {
for _, desired := range storageRolePaths(request) {
if err := ctx.Err(); err != nil {
return err
}
if err := resolve(desired.Role, desired.Path); err != nil {
return err
}
}
return nil
}
func ValidateStorageConfigurationRequest(request StorageConfigurationRequest) error {
paths := storageRolePaths(request)
for _, item := range paths {
if item.Path == "" || len(item.Path) > maximumStoragePathBytes ||
strings.TrimSpace(item.Path) != item.Path || strings.ContainsRune(item.Path, 0) ||
!filepath.IsAbs(item.Path) || filepath.Clean(item.Path) != item.Path ||
item.Path == string(filepath.Separator) {
return NewError(ErrInvalid, "invalid_storage_configuration", "storage directories must be clean absolute non-root paths", nil)
}
}
for index, left := range paths {
for _, right := range paths[index+1:] {
if storagePathsOverlap(left.Path, right.Path) {
return NewError(ErrInvalid, "invalid_storage_configuration", "storage directories must be distinct and non-overlapping", nil)
}
}
}
return nil
}
func storagePathsOverlap(left, right string) bool {
if left == right {
return true
}
separator := string(filepath.Separator)
return strings.HasPrefix(left, right+separator) || strings.HasPrefix(right, left+separator)
}
func storagePathDigest(path string) string {
sum := sha256.Sum256([]byte(path))
return hex.EncodeToString(sum[:])
}
func StorageConfigurationPathDigests(request StorageConfigurationRequest) map[string]string {
result := make(map[string]string, 5)
for _, item := range storageRolePaths(request) {
result[item.Role] = storagePathDigest(item.Path)
}
return result
}