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.
1270 lines
45 KiB
Go
1270 lines
45 KiB
Go
package hypervisor
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/tls"
|
|
"encoding/binary"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/netip"
|
|
"net/url"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.luoli.live/root/virt/agent/cloudinit"
|
|
"git.luoli.live/root/virt/agent/publicnetwork"
|
|
"github.com/GehirnInc/crypt/sha512_crypt"
|
|
"github.com/bgrewell/iso-kit/pkg/iso9660"
|
|
"libvirt.org/go/libvirtxml"
|
|
)
|
|
|
|
const (
|
|
maxSeedImageBytes = 2 << 20
|
|
maxTemplateBytes = int64(4) << 30
|
|
maxUserISOBytes = int64(32) << 30
|
|
maxRescueISOBytes = int64(8) << 30
|
|
minImportBytes = int64(1) << 20
|
|
backupRecoveryOperationMetadata = "virt-cloud-backup-recovery-operation"
|
|
diskGuestIdentityMetadata = cloudinit.GuestIdentityMetadata
|
|
diskGuestIdentityValue = cloudinit.GuestIdentityDisk
|
|
diskSSHAuthorizedKeysPath = "/root/.ssh/authorized_keys"
|
|
diskSSHDirectoryCommand = "install -d -m 0700 -o root -g root /root/.ssh"
|
|
diskSSHRemoveCommand = "rm -f -- /root/.ssh/authorized_keys"
|
|
)
|
|
|
|
var (
|
|
snapshotIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$`)
|
|
catalogIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
|
displayNamePattern = regexp.MustCompile(`^[^\x00-\x1f\x7f]{1,160}$`)
|
|
sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
|
sourceTokenPattern = regexp.MustCompile(`^[A-Za-z0-9._~-]{32,512}$`)
|
|
operationIdentifierPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{8,80}$`)
|
|
)
|
|
|
|
type seedFiles struct {
|
|
UserData []byte
|
|
MetaData []byte
|
|
NetworkConfig []byte
|
|
}
|
|
|
|
func readSeedISO(contents []byte) (seedFiles, error) {
|
|
if len(contents) == 0 || len(contents) > maxSeedImageBytes {
|
|
return seedFiles{}, NewError(ErrConflict, "invalid_seed", "NoCloud seed image has an invalid size", nil)
|
|
}
|
|
image, err := iso9660.Open(bytes.NewReader(contents))
|
|
if err != nil {
|
|
return seedFiles{}, NewError(ErrConflict, "invalid_seed", "NoCloud seed image cannot be read", err)
|
|
}
|
|
result := seedFiles{}
|
|
for name, destination := range map[string]*[]byte{
|
|
"user-data": &result.UserData, "meta-data": &result.MetaData, "network-config": &result.NetworkConfig,
|
|
} {
|
|
value, readErr := image.ReadFile(name)
|
|
if readErr != nil || len(value) == 0 || len(value) > maxSeedImageBytes {
|
|
return seedFiles{}, NewError(ErrConflict, "invalid_seed", "NoCloud seed is missing "+name, readErr)
|
|
}
|
|
*destination = value
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func buildSeedISO(files seedFiles) ([]byte, error) {
|
|
image, err := iso9660.Create("CIDATA")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create NoCloud ISO: %w", err)
|
|
}
|
|
for name, contents := range map[string][]byte{
|
|
"user-data": files.UserData, "meta-data": files.MetaData, "network-config": files.NetworkConfig,
|
|
} {
|
|
if err := image.AddFile(name, contents); err != nil {
|
|
return nil, fmt.Errorf("add NoCloud %s: %w", name, err)
|
|
}
|
|
}
|
|
output := &boundedSeedWriter{limit: maxSeedImageBytes}
|
|
if err := image.Save(output); err != nil {
|
|
return nil, fmt.Errorf("write NoCloud ISO: %w", err)
|
|
}
|
|
if len(output.data) == 0 || len(output.data) > maxSeedImageBytes {
|
|
return nil, errors.New("NoCloud ISO size is invalid")
|
|
}
|
|
return output.data, nil
|
|
}
|
|
|
|
type boundedSeedWriter struct {
|
|
data []byte
|
|
limit int
|
|
}
|
|
|
|
func (w *boundedSeedWriter) WriteAt(p []byte, offset int64) (int, error) {
|
|
if offset < 0 || offset > int64(w.limit) || len(p) > w.limit-int(offset) {
|
|
return 0, errors.New("NoCloud ISO exceeds size limit")
|
|
}
|
|
end := int(offset) + len(p)
|
|
if end > len(w.data) {
|
|
w.data = append(w.data, make([]byte, end-len(w.data))...)
|
|
}
|
|
return copy(w.data[int(offset):], p), nil
|
|
}
|
|
|
|
func mutateSeedSettings(contents []byte, request SettingsRequest, transitionID string) ([]byte, string, error) {
|
|
if !operationIdentifierPattern.MatchString(transitionID) {
|
|
return nil, "", NewError(ErrInvalid, "invalid_operation_id", "settings transition id is invalid", nil)
|
|
}
|
|
files, err := readSeedISO(contents)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
const header = "#cloud-config\n"
|
|
if !bytes.HasPrefix(files.UserData, []byte(header)) {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud user-data is not managed by Virt Cloud", nil)
|
|
}
|
|
var userData map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.UserData[len(header):]), &userData); err != nil {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud user-data is invalid", err)
|
|
}
|
|
var metadata map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.MetaData), &metadata); err != nil {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud meta-data is invalid", err)
|
|
}
|
|
instanceID, ok := metadata["instance-id"].(string)
|
|
if !ok || strings.TrimSpace(instanceID) == "" {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud instance identity is invalid", nil)
|
|
}
|
|
diskAuthoritative := metadata[diskGuestIdentityMetadata] == diskGuestIdentityValue
|
|
var root map[string]any
|
|
if diskAuthoritative {
|
|
// Recovery itself removes every pre-recovery identity instruction.
|
|
// From this point on, however, settings explicitly submitted by the
|
|
// user are new intent and must survive later settings transitions until
|
|
// that same field is changed again. This also prevents a quick second
|
|
// operation from deleting a password/key before cloud-init consumes it.
|
|
if users, exists := userData["users"]; exists {
|
|
parsed, valid := users.([]any)
|
|
if !valid || len(parsed) != 1 {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud root account definition is invalid", nil)
|
|
}
|
|
root, valid = parsed[0].(map[string]any)
|
|
if !valid || root["name"] != "root" {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud root account definition is invalid", nil)
|
|
}
|
|
}
|
|
if request.RootPassword != nil {
|
|
if root == nil {
|
|
root = map[string]any{"name": "root", "shell": "/bin/bash"}
|
|
userData["users"] = []any{root}
|
|
}
|
|
}
|
|
} else {
|
|
users, valid := userData["users"].([]any)
|
|
if !valid || len(users) != 1 {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud root account definition is invalid", nil)
|
|
}
|
|
root, valid = users[0].(map[string]any)
|
|
if !valid || root["name"] != "root" {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud root account definition is invalid", nil)
|
|
}
|
|
}
|
|
if request.SSHPublicKey != nil {
|
|
key := *request.SSHPublicKey
|
|
if err := validateOptionalSSHKey(key); err != nil {
|
|
return nil, "", err
|
|
}
|
|
if diskAuthoritative {
|
|
removeDiskAuthoritativeSSHKeyMutation(userData)
|
|
setDiskAuthoritativeSSHKeyMutation(userData, key)
|
|
} else if key == "" {
|
|
delete(root, "ssh_authorized_keys")
|
|
} else {
|
|
root["ssh_authorized_keys"] = []string{key}
|
|
}
|
|
}
|
|
passwordEnabled := false
|
|
if root != nil {
|
|
if hash, present := root["hashed_passwd"].(string); present && hash != "" {
|
|
passwordEnabled = true
|
|
}
|
|
}
|
|
if request.RootPassword != nil {
|
|
password := *request.RootPassword
|
|
if password == "" {
|
|
delete(root, "hashed_passwd")
|
|
delete(userData, "chpasswd")
|
|
root["lock_passwd"] = true
|
|
passwordEnabled = false
|
|
} else {
|
|
if err := validatePasswordValue(password); err != nil {
|
|
return nil, "", err
|
|
}
|
|
hash, hashErr := hashRootPassword(password)
|
|
if hashErr != nil {
|
|
return nil, "", NewError(ErrUnavailable, "password_hash_failed", "root password could not be hashed", hashErr)
|
|
}
|
|
root["hashed_passwd"] = hash
|
|
root["lock_passwd"] = false
|
|
userData["chpasswd"] = map[string]any{
|
|
"expire": false,
|
|
"users": []map[string]string{{"name": "root", "password": hash, "type": "hash"}},
|
|
}
|
|
passwordEnabled = true
|
|
}
|
|
}
|
|
if diskAuthoritative {
|
|
if request.RootPassword != nil && request.SSHPublicKey != nil &&
|
|
*request.RootPassword == "" && *request.SSHPublicKey == "" {
|
|
return nil, "", NewError(ErrInvalid, "guest_credentials_required", "at least one root login method must remain enabled", nil)
|
|
}
|
|
} else {
|
|
keys, _ := root["ssh_authorized_keys"].([]any)
|
|
stringKeys, _ := root["ssh_authorized_keys"].([]string)
|
|
if root != nil && !passwordEnabled && len(keys) == 0 && len(stringKeys) == 0 {
|
|
return nil, "", NewError(ErrInvalid, "guest_credentials_required", "at least one root login method must remain enabled", nil)
|
|
}
|
|
}
|
|
if !diskAuthoritative || request.RootPassword != nil {
|
|
userData["ssh_pwauth"] = passwordEnabled
|
|
updateSSHDWriteFile(userData, passwordEnabled)
|
|
}
|
|
|
|
hostname := ""
|
|
if request.Hostname != nil {
|
|
hostname = *request.Hostname
|
|
if !hostnamePattern.MatchString(hostname) || hostname != strings.ToLower(hostname) || strings.Contains(hostname, "..") {
|
|
return nil, "", NewError(ErrInvalid, "invalid_hostname", "hostname must be a lower-case DNS name", nil)
|
|
}
|
|
metadata["local-hostname"] = hostname
|
|
if diskAuthoritative {
|
|
userData["preserve_hostname"] = false
|
|
}
|
|
}
|
|
generation, err := newRandomID()
|
|
if err != nil {
|
|
return nil, "", NewError(ErrUnavailable, "entropy_unavailable", "NoCloud settings identity could not be generated", err)
|
|
}
|
|
metadata["instance-id"] = "virt-cloud-settings-" + generation
|
|
metadata["virt-cloud-network-policy"] = "boot-v1"
|
|
metadata["virt-cloud-settings-operation"] = transitionID
|
|
files.MetaData, err = marshalJSONLine(metadata)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
files.UserData, err = marshalCloudConfig(userData)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
updated, err := buildSeedISO(files)
|
|
return updated, hostname, err
|
|
}
|
|
|
|
// setDiskAuthoritativeSSHKeyMutation updates only authorized_keys. In
|
|
// particular it does not use cloud-init's users module: lock_passwd defaults
|
|
// to true there, which would silently lock a password restored from disk when
|
|
// the user only asked to change an SSH key.
|
|
func setDiskAuthoritativeSSHKeyMutation(userData map[string]any, key string) {
|
|
if key == "" {
|
|
appendSeedCommand(userData, "runcmd", diskSSHRemoveCommand)
|
|
return
|
|
}
|
|
appendSeedCommand(userData, "bootcmd", diskSSHDirectoryCommand)
|
|
files, _ := userData["write_files"].([]any)
|
|
files = append(files, map[string]any{
|
|
"path": diskSSHAuthorizedKeysPath, "content": key + "\n",
|
|
"owner": "root:root", "permissions": "0600",
|
|
})
|
|
userData["write_files"] = files
|
|
}
|
|
|
|
func removeDiskAuthoritativeSSHKeyMutation(userData map[string]any) {
|
|
files, _ := userData["write_files"].([]any)
|
|
kept := make([]any, 0, len(files))
|
|
for _, raw := range files {
|
|
entry, ok := raw.(map[string]any)
|
|
if ok && entry["path"] == diskSSHAuthorizedKeysPath {
|
|
continue
|
|
}
|
|
kept = append(kept, raw)
|
|
}
|
|
if len(kept) == 0 {
|
|
delete(userData, "write_files")
|
|
} else {
|
|
userData["write_files"] = kept
|
|
}
|
|
removeSeedCommand(userData, "bootcmd", diskSSHDirectoryCommand)
|
|
removeSeedCommand(userData, "runcmd", diskSSHRemoveCommand)
|
|
}
|
|
|
|
func appendSeedCommand(userData map[string]any, field, script string) {
|
|
commands, _ := userData[field].([]any)
|
|
commands = append(commands, []string{"/bin/sh", "-ec", script})
|
|
userData[field] = commands
|
|
}
|
|
|
|
func removeSeedCommand(userData map[string]any, field, script string) {
|
|
commands, _ := userData[field].([]any)
|
|
kept := make([]any, 0, len(commands))
|
|
for _, raw := range commands {
|
|
parts, ok := raw.([]any)
|
|
if ok && len(parts) == 3 && parts[0] == "/bin/sh" &&
|
|
parts[1] == "-ec" && parts[2] == script {
|
|
continue
|
|
}
|
|
kept = append(kept, raw)
|
|
}
|
|
if len(kept) == 0 {
|
|
delete(userData, field)
|
|
} else {
|
|
userData[field] = kept
|
|
}
|
|
}
|
|
|
|
func sanitizeSeedForDiskAuthoritativeRecovery(contents []byte,
|
|
transitionID string) ([]byte, error) {
|
|
if !operationIdentifierPattern.MatchString(transitionID) {
|
|
return nil, NewError(ErrInvalid, "invalid_operation_id", "backup recovery transition id is invalid", nil)
|
|
}
|
|
files, err := readSeedISO(contents)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
const header = "#cloud-config\n"
|
|
if !bytes.HasPrefix(files.UserData, []byte(header)) {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud user-data is not managed by Virt Cloud", nil)
|
|
}
|
|
var original map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.UserData[len(header):]), &original); err != nil {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud user-data is invalid", err)
|
|
}
|
|
userData := map[string]any{
|
|
"preserve_hostname": true,
|
|
}
|
|
for _, key := range []string{"updates", "bootcmd"} {
|
|
if value, exists := original[key]; exists {
|
|
userData[key] = value
|
|
}
|
|
}
|
|
var metadata map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.MetaData), &metadata); err != nil {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud meta-data is invalid", err)
|
|
}
|
|
instanceID, ok := metadata["instance-id"].(string)
|
|
if !ok || strings.TrimSpace(instanceID) == "" {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud instance identity is invalid", nil)
|
|
}
|
|
delete(metadata, "local-hostname")
|
|
metadata[diskGuestIdentityMetadata] = diskGuestIdentityValue
|
|
metadata[backupRecoveryOperationMetadata] = transitionID
|
|
files.UserData, err = marshalCloudConfig(userData)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
files.MetaData, err = marshalJSONLine(metadata)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return buildSeedISO(files)
|
|
}
|
|
|
|
func updateSSHDWriteFile(userData map[string]any, passwordEnabled bool) {
|
|
content := "PermitRootLogin prohibit-password\nPasswordAuthentication no\nKbdInteractiveAuthentication no\n"
|
|
if passwordEnabled {
|
|
content = "PermitRootLogin yes\nPasswordAuthentication yes\nKbdInteractiveAuthentication no\n"
|
|
}
|
|
files, _ := userData["write_files"].([]any)
|
|
for _, raw := range files {
|
|
entry, ok := raw.(map[string]any)
|
|
if ok && entry["path"] == "/etc/ssh/sshd_config.d/00-virt-cloud-root.conf" {
|
|
entry["content"] = content
|
|
return
|
|
}
|
|
}
|
|
files = append(files, map[string]any{
|
|
"path": "/etc/ssh/sshd_config.d/00-virt-cloud-root.conf", "content": content, "permissions": "0644",
|
|
})
|
|
userData["write_files"] = files
|
|
}
|
|
|
|
func mutateSeedNetwork(contents []byte, public publicnetwork.Intent, transitionID string) ([]byte, string, error) {
|
|
if !operationIdentifierPattern.MatchString(transitionID) {
|
|
return nil, "", NewError(ErrInvalid, "invalid_operation_id", "network transition id is invalid", nil)
|
|
}
|
|
if err := ValidatePublicNetworkIntent(public); err != nil {
|
|
return nil, "", err
|
|
}
|
|
files, err := readSeedISO(contents)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
var network map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.NetworkConfig), &network); err != nil {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud network-config is invalid", err)
|
|
}
|
|
ethernets, err := managedSeedEthernets(network)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
entry, _ := ethernets[seedPublicInterfaceKey].(map[string]any)
|
|
match, _ := entry["match"].(map[string]any)
|
|
mac, _ := match["macaddress"].(string)
|
|
if _, parseErr := net.ParseMAC(mac); parseErr != nil {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud public interface MAC is invalid", parseErr)
|
|
}
|
|
linkLocalCIDR, linkLocalErr := publicnetwork.LinkLocalIPv6CIDR(mac)
|
|
if linkLocalErr != nil {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud public interface MAC cannot derive its link-local IPv6 identity", linkLocalErr)
|
|
}
|
|
entry["addresses"] = []string{public.IPv4.AddressCIDR, public.IPv6.AddressCIDR, linkLocalCIDR}
|
|
entry["link-local"] = []string{}
|
|
entry["routes"] = []map[string]any{
|
|
seedDefaultRoute("0.0.0.0/0", public.IPv4),
|
|
seedDefaultRoute("::/0", public.IPv6),
|
|
}
|
|
entry["nameservers"] = map[string]any{"addresses": append([]string(nil), public.DNSServers...)}
|
|
files.NetworkConfig, err = marshalJSONLine(network)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
var metadata map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.MetaData), &metadata); err != nil {
|
|
return nil, "", NewError(ErrConflict, "invalid_seed", "NoCloud meta-data is invalid", err)
|
|
}
|
|
metadata["virt-cloud-network-operation"] = transitionID
|
|
files.MetaData, err = marshalJSONLine(metadata)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
updated, err := buildSeedISO(files)
|
|
return updated, strings.ToLower(mac), err
|
|
}
|
|
|
|
type seedPublicNetwork struct {
|
|
IPv4AddressCIDR string
|
|
IPv6AddressCIDR string
|
|
IPv6LinkLocalCIDR string
|
|
IPv4Gateway string
|
|
IPv6Gateway string
|
|
IPv4OnLink bool
|
|
IPv6OnLink bool
|
|
DNSServers []string
|
|
}
|
|
|
|
func seedNetwork(contents []byte) (string, seedPublicNetwork, error) {
|
|
files, err := readSeedISO(contents)
|
|
if err != nil {
|
|
return "", seedPublicNetwork{}, err
|
|
}
|
|
var network map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.NetworkConfig), &network); err != nil {
|
|
return "", seedPublicNetwork{}, err
|
|
}
|
|
ethernets, err := managedSeedEthernets(network)
|
|
if err != nil {
|
|
return "", seedPublicNetwork{}, err
|
|
}
|
|
entry, _ := ethernets[seedPublicInterfaceKey].(map[string]any)
|
|
match, _ := entry["match"].(map[string]any)
|
|
mac, _ := match["macaddress"].(string)
|
|
linkLocalMode, linkLocalModeOK := entry["link-local"].([]any)
|
|
if !linkLocalModeOK || len(linkLocalMode) != 0 {
|
|
return "", seedPublicNetwork{}, errors.New("NoCloud public interface must disable automatic link-local address generation")
|
|
}
|
|
addresses := stringSlice(entry["addresses"])
|
|
if len(addresses) != 3 {
|
|
return "", seedPublicNetwork{}, errors.New("NoCloud public interface must have one IPv4, one global IPv6, and one frozen link-local IPv6 address")
|
|
}
|
|
state := seedPublicNetwork{}
|
|
for _, raw := range addresses {
|
|
prefix, parseErr := netip.ParsePrefix(raw)
|
|
if parseErr != nil {
|
|
return "", seedPublicNetwork{}, errors.New("NoCloud public interface has an invalid address")
|
|
}
|
|
if prefix.Addr().Is4() && state.IPv4AddressCIDR == "" {
|
|
state.IPv4AddressCIDR = raw
|
|
} else if prefix.Addr().Is6() && prefix.Addr().IsLinkLocalUnicast() && state.IPv6LinkLocalCIDR == "" {
|
|
state.IPv6LinkLocalCIDR = raw
|
|
} else if prefix.Addr().Is6() && !prefix.Addr().IsLinkLocalUnicast() && state.IPv6AddressCIDR == "" {
|
|
state.IPv6AddressCIDR = raw
|
|
} else {
|
|
return "", seedPublicNetwork{}, errors.New("NoCloud public interface address families are invalid")
|
|
}
|
|
}
|
|
routes, _ := entry["routes"].([]any)
|
|
for _, raw := range routes {
|
|
route, _ := raw.(map[string]any)
|
|
switch route["to"] {
|
|
case "0.0.0.0/0":
|
|
state.IPv4Gateway, _ = route["via"].(string)
|
|
state.IPv4OnLink, _ = route["on-link"].(bool)
|
|
case "::/0":
|
|
state.IPv6Gateway, _ = route["via"].(string)
|
|
state.IPv6OnLink, _ = route["on-link"].(bool)
|
|
}
|
|
}
|
|
if state.IPv4Gateway == "" || state.IPv6Gateway == "" {
|
|
return "", seedPublicNetwork{}, errors.New("NoCloud public interface must have IPv4 and IPv6 default routes")
|
|
}
|
|
nameservers, _ := entry["nameservers"].(map[string]any)
|
|
state.DNSServers = stringSlice(nameservers["addresses"])
|
|
return strings.ToLower(mac), state, nil
|
|
}
|
|
|
|
func seedDefaultRoute(destination string, address publicnetwork.AddressIntent) map[string]any {
|
|
route := map[string]any{"to": destination, "via": address.Gateway}
|
|
if address.GatewayOnLink {
|
|
route["on-link"] = true
|
|
}
|
|
return route
|
|
}
|
|
|
|
func (value seedPublicNetwork) matches(public publicnetwork.Intent, mac string) bool {
|
|
linkLocalCIDR, err := publicnetwork.LinkLocalIPv6CIDR(mac)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if value.IPv4AddressCIDR != public.IPv4.AddressCIDR || value.IPv6AddressCIDR != public.IPv6.AddressCIDR ||
|
|
value.IPv6LinkLocalCIDR != linkLocalCIDR ||
|
|
value.IPv4Gateway != public.IPv4.Gateway || value.IPv6Gateway != public.IPv6.Gateway ||
|
|
value.IPv4OnLink != public.IPv4.GatewayOnLink || value.IPv6OnLink != public.IPv6.GatewayOnLink ||
|
|
len(value.DNSServers) != len(public.DNSServers) {
|
|
return false
|
|
}
|
|
for index := range value.DNSServers {
|
|
if value.DNSServers[index] != public.DNSServers[index] {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
const (
|
|
seedPublicInterfaceKey = "public0"
|
|
seedVPCInterfaceKey = "private0"
|
|
vpcPortOperationMarker = "virt-cloud-vpc-port-operation"
|
|
)
|
|
|
|
type seedVPCNetwork struct {
|
|
MAC string
|
|
PrivateIP string
|
|
CIDR string
|
|
Gateway string
|
|
}
|
|
|
|
func mutateSeedVPCPort(contents []byte, port VPCPortMetadata,
|
|
transitionID string, present bool) ([]byte, error) {
|
|
if !operationIdentifierPattern.MatchString(transitionID) {
|
|
return nil, NewError(ErrInvalid, "invalid_operation_id", "VPC port transition id is invalid", nil)
|
|
}
|
|
files, err := readSeedISO(contents)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var network map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.NetworkConfig), &network); err != nil {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud network-config is invalid", err)
|
|
}
|
|
ethernets, err := managedSeedEthernets(network)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if present {
|
|
if _, exists := ethernets[seedVPCInterfaceKey]; exists {
|
|
return nil, NewError(ErrConflict, "vpc_port_already_attached", "NoCloud already contains a VPC interface", nil)
|
|
}
|
|
ethernets[seedVPCInterfaceKey] = seedVPCInterface(port)
|
|
} else {
|
|
existing, exists := ethernets[seedVPCInterfaceKey]
|
|
if !exists || !seedVPCInterfaceMatches(existing, port) {
|
|
return nil, NewError(ErrConflict, "vpc_port_identity_changed", "NoCloud VPC interface no longer matches the requested port", nil)
|
|
}
|
|
delete(ethernets, seedVPCInterfaceKey)
|
|
}
|
|
files.NetworkConfig, err = marshalJSONLine(network)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var metadata map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.MetaData), &metadata); err != nil {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud meta-data is invalid", err)
|
|
}
|
|
metadata[vpcPortOperationMarker] = transitionID
|
|
files.MetaData, err = marshalJSONLine(metadata)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return buildSeedISO(files)
|
|
}
|
|
|
|
// repairSeedVPCPort rewrites only Virt Cloud's reserved private0 entry. A
|
|
// different valid VPC identity proves that panel intent has moved on and is
|
|
// rejected; a missing or malformed reserved entry is the partial-state case
|
|
// this explicit repair operation exists to converge.
|
|
func repairSeedVPCPort(contents []byte, port VPCPortMetadata,
|
|
transitionID string, present bool) ([]byte, error) {
|
|
if !operationIdentifierPattern.MatchString(transitionID) {
|
|
return nil, NewError(ErrInvalid, "invalid_operation_id", "VPC port transition id is invalid", nil)
|
|
}
|
|
files, err := readSeedISO(contents)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var network map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.NetworkConfig), &network); err != nil {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud network-config is invalid", err)
|
|
}
|
|
ethernets, err := managedSeedEthernets(network)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if existing, exists := ethernets[seedVPCInterfaceKey]; exists {
|
|
if parsed, ok := parseSeedVPCInterface(existing); ok && parsed != (seedVPCNetwork{
|
|
MAC: port.MAC, PrivateIP: port.PrivateIP,
|
|
CIDR: port.CIDR, Gateway: port.Gateway,
|
|
}) {
|
|
return nil, NewError(ErrConflict, "vpc_repair_intent_changed", "NoCloud contains a different VPC identity", nil)
|
|
}
|
|
}
|
|
if present {
|
|
ethernets[seedVPCInterfaceKey] = seedVPCInterface(port)
|
|
} else {
|
|
delete(ethernets, seedVPCInterfaceKey)
|
|
}
|
|
files.NetworkConfig, err = marshalJSONLine(network)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var metadata map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.MetaData), &metadata); err != nil {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud meta-data is invalid", err)
|
|
}
|
|
metadata[vpcPortOperationMarker] = transitionID
|
|
files.MetaData, err = marshalJSONLine(metadata)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return buildSeedISO(files)
|
|
}
|
|
|
|
func seedVPCPort(contents []byte) (*seedVPCNetwork, error) {
|
|
files, err := readSeedISO(contents)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var network map[string]any
|
|
if err := json.Unmarshal(bytes.TrimSpace(files.NetworkConfig), &network); err != nil {
|
|
return nil, err
|
|
}
|
|
ethernets, err := managedSeedEthernets(network)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
raw, exists := ethernets[seedVPCInterfaceKey]
|
|
if !exists {
|
|
return nil, nil
|
|
}
|
|
value, ok := parseSeedVPCInterface(raw)
|
|
if !ok {
|
|
return nil, errors.New("invalid NoCloud VPC interface")
|
|
}
|
|
return &value, nil
|
|
}
|
|
|
|
// preservedVPCCloudInitNetwork binds a regenerated NoCloud seed to the exact
|
|
// private interface already committed in both the seed and domain metadata.
|
|
// Reinstall must not silently add, remove, or repair only one side of that
|
|
// cross-layer identity.
|
|
func preservedVPCCloudInitNetwork(contents []byte,
|
|
metadata *domainVPCPortMetadataXML) (*cloudinit.PrivateNetwork, error) {
|
|
seedPort, err := seedVPCPort(contents)
|
|
if err != nil {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "existing NoCloud VPC interface cannot be preserved", err)
|
|
}
|
|
if metadata == nil {
|
|
if seedPort != nil {
|
|
return nil, NewError(ErrConflict, "vpc_port_identity_changed", "NoCloud contains a VPC interface that is absent from domain metadata", nil)
|
|
}
|
|
return nil, nil
|
|
}
|
|
port := metadata.public()
|
|
if err := validateVPCPortMetadata(port); err != nil {
|
|
return nil, NewError(ErrConflict, "vpc_port_identity_changed", "domain VPC metadata is invalid", err)
|
|
}
|
|
expected := seedVPCNetwork{
|
|
MAC: port.MAC, PrivateIP: port.PrivateIP,
|
|
CIDR: port.CIDR, Gateway: port.Gateway,
|
|
}
|
|
if seedPort == nil || *seedPort != expected {
|
|
return nil, NewError(ErrConflict, "vpc_port_identity_changed", "NoCloud and domain VPC identities no longer match", nil)
|
|
}
|
|
return &cloudinit.PrivateNetwork{
|
|
MAC: port.MAC, PrivateIP: port.PrivateIP, CIDR: port.CIDR,
|
|
Gateway: port.Gateway, InterfaceKey: seedVPCInterfaceKey,
|
|
}, nil
|
|
}
|
|
|
|
func managedSeedEthernets(network map[string]any) (map[string]any, error) {
|
|
ethernets, ok := network["ethernets"].(map[string]any)
|
|
if !ok || len(ethernets) < 1 || len(ethernets) > 2 {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud network-config has an invalid managed interface count", nil)
|
|
}
|
|
for key, raw := range ethernets {
|
|
if key != seedPublicInterfaceKey && key != seedVPCInterfaceKey {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud network-config contains an unmanaged interface", nil)
|
|
}
|
|
if _, ok := raw.(map[string]any); !ok {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud interface definition is invalid", nil)
|
|
}
|
|
}
|
|
if _, exists := ethernets[seedPublicInterfaceKey]; !exists {
|
|
return nil, NewError(ErrConflict, "invalid_seed", "NoCloud public interface is missing", nil)
|
|
}
|
|
return ethernets, nil
|
|
}
|
|
|
|
func seedVPCInterface(port VPCPortMetadata) map[string]any {
|
|
return map[string]any{
|
|
"match": map[string]any{"macaddress": port.MAC},
|
|
"dhcp4": false,
|
|
"dhcp6": false,
|
|
"accept-ra": false,
|
|
"addresses": []string{port.PrivateIP + "/32"},
|
|
"routes": []map[string]any{{
|
|
"to": port.CIDR, "via": port.Gateway, "on-link": true,
|
|
}},
|
|
}
|
|
}
|
|
|
|
func seedVPCInterfaceMatches(raw any, port VPCPortMetadata) bool {
|
|
parsed, ok := parseSeedVPCInterface(raw)
|
|
return ok && parsed == (seedVPCNetwork{
|
|
MAC: port.MAC, PrivateIP: port.PrivateIP,
|
|
CIDR: port.CIDR, Gateway: port.Gateway,
|
|
})
|
|
}
|
|
|
|
func parseSeedVPCInterface(raw any) (seedVPCNetwork, bool) {
|
|
entry, ok := raw.(map[string]any)
|
|
if !ok {
|
|
return seedVPCNetwork{}, false
|
|
}
|
|
match, _ := entry["match"].(map[string]any)
|
|
mac, _ := match["macaddress"].(string)
|
|
addresses := stringSlice(entry["addresses"])
|
|
routes, _ := entry["routes"].([]any)
|
|
if len(addresses) != 1 || len(routes) != 1 {
|
|
return seedVPCNetwork{}, false
|
|
}
|
|
address, err := netip.ParsePrefix(addresses[0])
|
|
route, _ := routes[0].(map[string]any)
|
|
cidr, _ := route["to"].(string)
|
|
gateway, _ := route["via"].(string)
|
|
onLink, _ := route["on-link"].(bool)
|
|
if err != nil || address.Bits() != 32 || !onLink {
|
|
return seedVPCNetwork{}, false
|
|
}
|
|
return seedVPCNetwork{
|
|
MAC: strings.ToLower(mac), PrivateIP: address.Addr().String(),
|
|
CIDR: cidr, Gateway: gateway,
|
|
}, true
|
|
}
|
|
|
|
func stringSlice(raw any) []string {
|
|
switch values := raw.(type) {
|
|
case []string:
|
|
return append([]string(nil), values...)
|
|
case []any:
|
|
result := make([]string, 0, len(values))
|
|
for _, rawValue := range values {
|
|
value, ok := rawValue.(string)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
result = append(result, value)
|
|
}
|
|
return result
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func marshalCloudConfig(value any) ([]byte, error) {
|
|
encoded, err := json.Marshal(value)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("encode NoCloud user-data: %w", err)
|
|
}
|
|
return append(append([]byte("#cloud-config\n"), encoded...), '\n'), nil
|
|
}
|
|
|
|
func marshalJSONLine(value any) ([]byte, error) {
|
|
encoded, err := json.Marshal(value)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return append(encoded, '\n'), nil
|
|
}
|
|
|
|
func validatePasswordValue(value string) error {
|
|
if len(value) < 12 || len(value) > 128 {
|
|
return NewError(ErrInvalid, "invalid_root_password", "root password must contain 12-128 printable ASCII characters", nil)
|
|
}
|
|
var upper, lower, digit, symbol bool
|
|
for _, char := range []byte(value) {
|
|
if char < 0x21 || char > 0x7e {
|
|
return NewError(ErrInvalid, "invalid_root_password", "root password must contain printable ASCII without spaces", nil)
|
|
}
|
|
switch {
|
|
case char >= 'A' && char <= 'Z':
|
|
upper = true
|
|
case char >= 'a' && char <= 'z':
|
|
lower = true
|
|
case char >= '0' && char <= '9':
|
|
digit = true
|
|
default:
|
|
symbol = true
|
|
}
|
|
}
|
|
if !upper || !lower || !digit || !symbol {
|
|
return NewError(ErrInvalid, "invalid_root_password", "root password must contain upper, lower, digit, and symbol characters", nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func hashRootPassword(value string) (string, error) {
|
|
saltBytes := make([]byte, 8)
|
|
if _, err := rand.Read(saltBytes); err != nil {
|
|
return "", err
|
|
}
|
|
salt := hex.EncodeToString(saltBytes)
|
|
return sha512_crypt.New().Generate([]byte(value), []byte("$6$rounds=100000$"+salt+"$"))
|
|
}
|
|
|
|
func validateOptionalSSHKey(value string) error {
|
|
if value == "" {
|
|
return nil
|
|
}
|
|
if len(value) > 16384 || strings.ContainsAny(value, "\r\n\x00") || !strings.HasPrefix(value, "ssh-") {
|
|
return NewError(ErrInvalid, "invalid_ssh_public_key", "guest SSH public key must be one bounded OpenSSH line", nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateFirewallPolicy(policy FirewallPolicy) (FirewallPolicy, error) {
|
|
if policy.Revision == 0 {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_revision", "firewall revision must be positive", nil)
|
|
}
|
|
if policy.DefaultIn != "accept" && policy.DefaultIn != "drop" || policy.DefaultOut != "accept" && policy.DefaultOut != "drop" {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_default", "firewall defaults must be accept or drop", nil)
|
|
}
|
|
if len(policy.Rules) > 100 {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "too_many_firewall_rules", "firewall policy exceeds 100 rules", nil)
|
|
}
|
|
for index, rule := range policy.Rules {
|
|
if rule.Direction != "ingress" && rule.Direction != "egress" {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_rule", fmt.Sprintf("rule %d has an invalid direction", index), nil)
|
|
}
|
|
if rule.Action != "accept" && rule.Action != "drop" {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_rule", fmt.Sprintf("rule %d has an invalid action", index), nil)
|
|
}
|
|
if rule.Protocol != "any" && rule.Protocol != "tcp" && rule.Protocol != "udp" && rule.Protocol != "icmp" {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_rule", fmt.Sprintf("rule %d has an invalid protocol", index), nil)
|
|
}
|
|
prefix, err := netip.ParsePrefix(rule.CIDR)
|
|
if err != nil || (!prefix.Addr().Is4() && !prefix.Addr().Is6()) ||
|
|
prefix != prefix.Masked() || prefix.String() != rule.CIDR {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_rule", fmt.Sprintf("rule %d must contain a canonical IPv4 or IPv6 CIDR", index), err)
|
|
}
|
|
if rule.Protocol == "tcp" || rule.Protocol == "udp" {
|
|
if rule.PortFrom == 0 || rule.PortTo < rule.PortFrom {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_rule", fmt.Sprintf("rule %d has an invalid port range", index), nil)
|
|
}
|
|
} else if rule.PortFrom != 0 || rule.PortTo != 0 {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_rule", fmt.Sprintf("rule %d cannot contain ports", index), nil)
|
|
}
|
|
}
|
|
digestValue := struct {
|
|
Revision uint64 `json:"revision"`
|
|
DefaultIn string `json:"default_in"`
|
|
DefaultOut string `json:"default_out"`
|
|
Rules []FirewallRule `json:"rules"`
|
|
}{policy.Revision, policy.DefaultIn, policy.DefaultOut, policy.Rules}
|
|
encoded, err := json.Marshal(digestValue)
|
|
if err != nil {
|
|
return FirewallPolicy{}, err
|
|
}
|
|
digest := sha256.Sum256(encoded)
|
|
canonical := hex.EncodeToString(digest[:])
|
|
if policy.PolicyDigest != "" && policy.PolicyDigest != canonical {
|
|
return FirewallPolicy{}, NewError(ErrInvalid, "invalid_firewall_digest", "firewall policy digest does not match its content", nil)
|
|
}
|
|
policy.PolicyDigest = canonical
|
|
policy.OperationID = ""
|
|
return policy, nil
|
|
}
|
|
|
|
// NormalizeFirewallPolicy validates a signed panel policy and fills its
|
|
// canonical digest before the operation crosses the durable dispatch boundary.
|
|
func NormalizeFirewallPolicy(policy FirewallPolicy) (FirewallPolicy, error) {
|
|
return validateFirewallPolicy(policy)
|
|
}
|
|
|
|
func buildUserFirewallXML(baseXML string, policy FirewallPolicy) (string, error) {
|
|
policy, err := validateFirewallPolicy(policy)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var filter libvirtxml.NWFilter
|
|
if err := filter.Unmarshal(baseXML); err != nil {
|
|
return "", NewError(ErrConflict, "invalid_firewall_filter", "existing network filter XML is invalid", err)
|
|
}
|
|
entries := make([]libvirtxml.NWFilterEntry, 0, len(filter.Entries)+len(policy.Rules)+2)
|
|
for _, entry := range filter.Entries {
|
|
comment := nwfilterRuleComment(entry.Rule)
|
|
if strings.HasPrefix(comment, "virt-user:") || strings.HasPrefix(comment, "virt-default:") ||
|
|
strings.HasPrefix(comment, "virt-platform-pass:") {
|
|
continue
|
|
}
|
|
entries = append(entries, entry)
|
|
}
|
|
// ARP/RARP are required for the bridged public link itself and must not be
|
|
// consumed by an IPv4/IPv6 default drop. They are project-owned rules, not
|
|
// user-configurable exceptions.
|
|
entries = append(entries, platformRequiredInboundPassEntries()...)
|
|
priority := 100
|
|
for index, rule := range policy.Rules {
|
|
entries = append(entries, libvirtxml.NWFilterEntry{Rule: firewallRuleXML(rule, priority, "virt-user:"+strconv.Itoa(index))})
|
|
priority++
|
|
}
|
|
entries = append(entries, userFirewallDefaultEntries(policy.DefaultIn, policy.DefaultOut)...)
|
|
filter.Entries = entries
|
|
return filter.Marshal()
|
|
}
|
|
|
|
func firewallRuleXML(rule FirewallRule, priority int, comment string) *libvirtxml.NWFilterRule {
|
|
direction := "in"
|
|
if rule.Direction == "egress" {
|
|
direction = "out"
|
|
}
|
|
prefix := netip.MustParsePrefix(rule.CIDR)
|
|
common := libvirtxml.NWFilterRuleCommonIP{}
|
|
if direction == "in" {
|
|
common.SrcIPAddr = libvirtxml.NWFilterField{Str: prefix.Addr().String()}
|
|
common.SrcIPMask = libvirtxml.NWFilterField{Str: strconv.Itoa(prefix.Bits())}
|
|
} else {
|
|
common.DstIPAddr = libvirtxml.NWFilterField{Str: prefix.Addr().String()}
|
|
common.DstIPMask = libvirtxml.NWFilterField{Str: strconv.Itoa(prefix.Bits())}
|
|
}
|
|
// User policy is intentionally stateful. Omitting statematch keeps
|
|
// libvirt's connection tracking enabled so an ingress default-drop does not
|
|
// break replies to guest-initiated traffic. Platform anti-spoof and provider
|
|
// policy rules remain explicitly stateless in domain_xml.go.
|
|
result := &libvirtxml.NWFilterRule{Action: rule.Action, Direction: direction, Priority: priority}
|
|
from, to := uint(rule.PortFrom), uint(rule.PortTo)
|
|
ports := libvirtxml.NWFilterRuleCommonPort{
|
|
DstPortStart: libvirtxml.NWFilterField{Uint: &from}, DstPortEnd: libvirtxml.NWFilterField{Uint: &to},
|
|
}
|
|
ipv6 := prefix.Addr().Is6()
|
|
switch rule.Protocol {
|
|
case "tcp":
|
|
if ipv6 {
|
|
result.TCPIPv6 = &libvirtxml.NWFilterRuleTCPIPv6{NWFilterRuleCommonIP: common, NWFilterRuleCommonPort: ports, Comment: comment}
|
|
} else {
|
|
result.TCP = &libvirtxml.NWFilterRuleTCP{NWFilterRuleCommonIP: common, NWFilterRuleCommonPort: ports, Comment: comment}
|
|
}
|
|
case "udp":
|
|
if ipv6 {
|
|
result.UDPIPv6 = &libvirtxml.NWFilterRuleUDPIPv6{NWFilterRuleCommonIP: common, NWFilterRuleCommonPort: ports, Comment: comment}
|
|
} else {
|
|
result.UDP = &libvirtxml.NWFilterRuleUDP{NWFilterRuleCommonIP: common, NWFilterRuleCommonPort: ports, Comment: comment}
|
|
}
|
|
case "icmp":
|
|
if ipv6 {
|
|
result.ICMPv6 = &libvirtxml.NWFilterRuleICMPIPv6{NWFilterRuleCommonIP: common, Comment: comment}
|
|
} else {
|
|
result.ICMP = &libvirtxml.NWFilterRuleICMP{NWFilterRuleCommonIP: common, Comment: comment}
|
|
}
|
|
default:
|
|
if ipv6 {
|
|
result.IPv6 = &libvirtxml.NWFilterRuleIPv6{SrcIPAddr: common.SrcIPAddr, SrcIPMask: common.SrcIPMask, DstIPAddr: common.DstIPAddr, DstIPMask: common.DstIPMask, Comment: comment}
|
|
} else {
|
|
result.IP = &libvirtxml.NWFilterRuleIP{SrcIPAddr: common.SrcIPAddr, SrcIPMask: common.SrcIPMask, DstIPAddr: common.DstIPAddr, DstIPMask: common.DstIPMask, Comment: comment}
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func nwfilterRuleComment(rule *libvirtxml.NWFilterRule) string {
|
|
if rule == nil {
|
|
return ""
|
|
}
|
|
for _, value := range []string{
|
|
commentOf(rule.ARP), commentOf(rule.RARP), commentOf(rule.MAC), commentOf(rule.IP), commentOf(rule.IPv6),
|
|
commentOf(rule.TCP), commentOf(rule.TCPIPv6), commentOf(rule.UDP), commentOf(rule.UDPIPv6),
|
|
commentOf(rule.ICMP), commentOf(rule.ICMPv6), commentOf(rule.All),
|
|
} {
|
|
if value != "" {
|
|
return value
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func commentOf(value any) string {
|
|
switch typed := value.(type) {
|
|
case *libvirtxml.NWFilterRuleARP:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleRARP:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleMAC:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleIPv6:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleTCP:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleTCPIPv6:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleUDP:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleICMP:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleICMPIPv6:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleUDPIPv6:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleIP:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
case *libvirtxml.NWFilterRuleAll:
|
|
if typed != nil {
|
|
return typed.Comment
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func validateRemoteSource(raw string) (*url.URL, error) {
|
|
parsed, err := url.Parse(raw)
|
|
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" || parsed.User != nil || parsed.Fragment != "" {
|
|
return nil, NewError(ErrInvalid, "invalid_source_url", "source_url must be an HTTPS URL without credentials or fragments", err)
|
|
}
|
|
return parsed, nil
|
|
}
|
|
|
|
func validSourceToken(token string) bool {
|
|
return token == "" || sourceTokenPattern.MatchString(token)
|
|
}
|
|
|
|
func validateExpectedImportSourceSize(expected, maximum int64) error {
|
|
if expected == 0 {
|
|
return nil
|
|
}
|
|
if expected < minImportBytes || expected > maximum {
|
|
return NewError(ErrInvalid, "invalid_source_size", "source image size is invalid or exceeds its limit", nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolveImportSourceSize keeps remote imports strict while allowing a
|
|
// panel-staged upload to survive an intermediary that converts the response
|
|
// to chunked transfer encoding. The expected size is part of the signed,
|
|
// immutable operation request and the streaming path still enforces it byte
|
|
// for byte.
|
|
func resolveImportSourceSize(contentLength, expected, maximum int64) (int64, error) {
|
|
if err := validateExpectedImportSourceSize(expected, maximum); err != nil {
|
|
return 0, err
|
|
}
|
|
if contentLength >= 0 {
|
|
if contentLength < minImportBytes || contentLength > maximum ||
|
|
(expected > 0 && contentLength != expected) {
|
|
return 0, NewError(ErrInvalid, "invalid_source_size", "source image size is invalid or does not match the expected size", nil)
|
|
}
|
|
return contentLength, nil
|
|
}
|
|
if expected > 0 {
|
|
return expected, nil
|
|
}
|
|
return 0, NewError(ErrInvalid, "invalid_source_size", "source image size is missing or exceeds its limit", nil)
|
|
}
|
|
|
|
func remoteHTTPClient(allowRedirects bool) *http.Client {
|
|
dialer := &net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}
|
|
transport := &http.Transport{
|
|
Proxy: nil,
|
|
DisableCompression: true,
|
|
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
|
|
TLSHandshakeTimeout: 15 * time.Second,
|
|
ResponseHeaderTimeout: 30 * time.Second,
|
|
ExpectContinueTimeout: 1 * time.Second,
|
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
|
host, port, err := net.SplitHostPort(address)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
lookupCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
|
resolved, err := net.DefaultResolver.LookupNetIP(lookupCtx, "ip", host)
|
|
cancel()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, candidate := range resolved {
|
|
if remoteAddressAllowed(candidate) {
|
|
return dialer.DialContext(ctx, network, net.JoinHostPort(candidate.String(), port))
|
|
}
|
|
}
|
|
return nil, errors.New("source URL resolved only to blocked addresses")
|
|
},
|
|
}
|
|
client := &http.Client{Transport: transport, Timeout: 2 * time.Hour}
|
|
client.CheckRedirect = func(request *http.Request, via []*http.Request) error {
|
|
if !allowRedirects {
|
|
return errors.New("redirects are disabled for authenticated source downloads")
|
|
}
|
|
if len(via) >= 5 {
|
|
return errors.New("too many source URL redirects")
|
|
}
|
|
_, err := validateRemoteSource(request.URL.String())
|
|
return err
|
|
}
|
|
return client
|
|
}
|
|
|
|
func remoteAddressAllowed(address netip.Addr) bool {
|
|
if !address.IsValid() {
|
|
return false
|
|
}
|
|
address = address.Unmap()
|
|
if !address.IsGlobalUnicast() || address.IsPrivate() || address.IsLoopback() ||
|
|
address.IsLinkLocalUnicast() || address.IsLinkLocalMulticast() || address.IsMulticast() {
|
|
return false
|
|
}
|
|
for _, blocked := range blockedRemotePrefixes {
|
|
if blocked.Contains(address) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
var blockedRemotePrefixes = []netip.Prefix{
|
|
netip.MustParsePrefix("0.0.0.0/8"),
|
|
netip.MustParsePrefix("100.64.0.0/10"),
|
|
netip.MustParsePrefix("192.0.0.0/24"),
|
|
netip.MustParsePrefix("192.0.2.0/24"),
|
|
netip.MustParsePrefix("192.88.99.0/24"),
|
|
netip.MustParsePrefix("198.18.0.0/15"),
|
|
netip.MustParsePrefix("198.51.100.0/24"),
|
|
netip.MustParsePrefix("203.0.113.0/24"),
|
|
netip.MustParsePrefix("240.0.0.0/4"),
|
|
netip.MustParsePrefix("64:ff9b::/96"),
|
|
netip.MustParsePrefix("64:ff9b:1::/48"),
|
|
netip.MustParsePrefix("100::/64"),
|
|
netip.MustParsePrefix("2001:2::/48"),
|
|
netip.MustParsePrefix("2001:db8::/32"),
|
|
netip.MustParsePrefix("2001:10::/28"),
|
|
netip.MustParsePrefix("2001:20::/28"),
|
|
netip.MustParsePrefix("2002::/16"),
|
|
}
|
|
|
|
func newRandomID() (string, error) {
|
|
value := make([]byte, 16)
|
|
if _, err := rand.Read(value); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(value), nil
|
|
}
|
|
|
|
func sortTemplates(values []ImageTemplate) {
|
|
sort.Slice(values, func(i, j int) bool { return values[i].ID < values[j].ID })
|
|
}
|
|
|
|
func sortUserISOs(values []UserISO) {
|
|
sort.Slice(values, func(i, j int) bool { return values[i].ID < values[j].ID })
|
|
}
|
|
|
|
func sortRescueTemplates(values []RescueTemplate) {
|
|
sort.Slice(values, func(i, j int) bool { return values[i].ID < values[j].ID })
|
|
}
|
|
|
|
func copyBounded(destination io.Writer, source io.Reader, maximum int64) (int64, string, error) {
|
|
hash := sha256.New()
|
|
written, err := io.Copy(io.MultiWriter(destination, hash), io.LimitReader(source, maximum+1))
|
|
if err != nil {
|
|
return written, "", err
|
|
}
|
|
if written > maximum {
|
|
return written, "", errors.New("download exceeds configured size limit")
|
|
}
|
|
return written, hex.EncodeToString(hash.Sum(nil)), nil
|
|
}
|
|
|
|
const qcow2HeaderBytes = 104
|
|
|
|
func validateQCOW2Header(header []byte) (uint64, error) {
|
|
if len(header) < qcow2HeaderBytes || !bytes.Equal(header[:4], []byte{'Q', 'F', 'I', 0xfb}) {
|
|
return 0, NewError(ErrInvalid, "invalid_qcow2", "image does not contain a QCOW2 header", nil)
|
|
}
|
|
version := binary.BigEndian.Uint32(header[4:8])
|
|
if version != 2 && version != 3 {
|
|
return 0, NewError(ErrInvalid, "unsupported_qcow2", "QCOW2 version must be 2 or 3", nil)
|
|
}
|
|
if binary.BigEndian.Uint64(header[8:16]) != 0 || binary.BigEndian.Uint32(header[16:20]) != 0 {
|
|
return 0, NewError(ErrInvalid, "qcow2_backing_file_forbidden", "QCOW2 backing files are not allowed", nil)
|
|
}
|
|
clusterBits := binary.BigEndian.Uint32(header[20:24])
|
|
if clusterBits < 9 || clusterBits > 21 {
|
|
return 0, NewError(ErrInvalid, "invalid_qcow2", "QCOW2 cluster size is invalid", nil)
|
|
}
|
|
virtualSize := binary.BigEndian.Uint64(header[24:32])
|
|
if virtualSize == 0 || virtualSize > uint64(4096)<<30 {
|
|
return 0, NewError(ErrInvalid, "invalid_qcow2", "QCOW2 virtual size is outside the supported range", nil)
|
|
}
|
|
if binary.BigEndian.Uint32(header[32:36]) != 0 {
|
|
return 0, NewError(ErrInvalid, "qcow2_encryption_forbidden", "encrypted QCOW2 images are not allowed", nil)
|
|
}
|
|
clusterSize := uint64(1) << clusterBits
|
|
l1Offset := binary.BigEndian.Uint64(header[40:48])
|
|
refcountOffset := binary.BigEndian.Uint64(header[48:56])
|
|
if binary.BigEndian.Uint32(header[36:40]) == 0 || l1Offset == 0 || l1Offset%clusterSize != 0 ||
|
|
refcountOffset == 0 || refcountOffset%clusterSize != 0 || binary.BigEndian.Uint32(header[56:60]) == 0 {
|
|
return 0, NewError(ErrInvalid, "invalid_qcow2", "QCOW2 allocation tables are incomplete", nil)
|
|
}
|
|
if version == 3 {
|
|
if binary.BigEndian.Uint64(header[72:80]) != 0 {
|
|
return 0, NewError(ErrInvalid, "unsupported_qcow2_features", "QCOW2 image uses unsupported incompatible features", nil)
|
|
}
|
|
headerLength := binary.BigEndian.Uint32(header[100:104])
|
|
if headerLength < qcow2HeaderBytes || headerLength > 1<<20 {
|
|
return 0, NewError(ErrInvalid, "invalid_qcow2", "QCOW2 header length is invalid", nil)
|
|
}
|
|
}
|
|
return virtualSize, nil
|
|
}
|