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/publicnetwork/intent.go

211 lines
7.3 KiB
Go

package publicnetwork
import (
"errors"
"fmt"
"net"
"net/netip"
"regexp"
"strings"
)
const ContractVersion uint64 = 1
var poolKeyPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
var networkSelectorPattern = regexp.MustCompile(`^(?:bridge:[A-Za-z0-9][A-Za-z0-9_.-]{0,14}|network:[A-Za-z0-9][A-Za-z0-9_.-]{0,63})$`)
// AddressIntent is one address-family member of an immutable public-network
// identity. PoolCIDR and AddressCIDR always use canonical CIDR notation.
type AddressIntent struct {
PoolKey string `json:"pool_key"`
PoolCIDR string `json:"pool_cidr"`
AddressCIDR string `json:"address_cidr"`
Gateway string `json:"gateway"`
GatewayOnLink bool `json:"gateway_on_link"`
}
// Intent is the only public-network contract shared by the panel, Agent,
// NoCloud seed and libvirt metadata. New instances are always dual stack.
type Intent struct {
Contract uint64 `json:"contract"`
NetworkSelector string `json:"network_selector"`
IPv4 AddressIntent `json:"ipv4"`
IPv6 AddressIntent `json:"ipv6"`
DNSServers []string `json:"dns_servers"`
}
// Canonical validates the complete dual-stack identity and returns the only
// representation that callers may persist, sign or compare.
func (value Intent) Canonical() (Intent, error) {
if value.Contract != ContractVersion {
return Intent{}, fmt.Errorf("public network contract must be %d", ContractVersion)
}
if !networkSelectorPattern.MatchString(value.NetworkSelector) {
return Intent{}, errors.New("network selector is required")
}
ipv4, err := canonicalAddress(value.IPv4, 4)
if err != nil {
return Intent{}, fmt.Errorf("ipv4: %w", err)
}
ipv6, err := canonicalAddress(value.IPv6, 6)
if err != nil {
return Intent{}, fmt.Errorf("ipv6: %w", err)
}
dns, err := canonicalDNS(value.DNSServers)
if err != nil {
return Intent{}, err
}
value.IPv4 = ipv4
value.IPv6 = ipv6
value.DNSServers = dns
return value, nil
}
func (value Intent) IdentityCIDRs() []string {
return []string{value.IPv4.AddressCIDR, value.IPv6.AddressCIDR}
}
// LinkLocalIPv6 derives the one frozen IPv6 link-local identity used by the
// NoCloud seed and libvirt anti-spoof filter. The modified EUI-64 derivation
// is deterministic from the immutable interface MAC, so it does not introduce
// another panel/IPAM field that can drift across reinstall or migration.
func LinkLocalIPv6(mac string) (netip.Addr, error) {
hardware, err := net.ParseMAC(mac)
if err != nil || len(hardware) != 6 || hardware[0]&1 != 0 {
return netip.Addr{}, errors.New("public interface MAC is invalid")
}
zero := true
for _, item := range hardware {
zero = zero && item == 0
}
if zero || strings.ToLower(hardware.String()) != strings.ToLower(mac) {
return netip.Addr{}, errors.New("public interface MAC is invalid")
}
var raw [16]byte
raw[0], raw[1] = 0xfe, 0x80
raw[8] = hardware[0] ^ 0x02
raw[9], raw[10] = hardware[1], hardware[2]
raw[11], raw[12] = 0xff, 0xfe
raw[13], raw[14], raw[15] = hardware[3], hardware[4], hardware[5]
return netip.AddrFrom16(raw), nil
}
func LinkLocalIPv6CIDR(mac string) (string, error) {
address, err := LinkLocalIPv6(mac)
if err != nil {
return "", err
}
return netip.PrefixFrom(address, 64).String(), nil
}
func canonicalAddress(value AddressIntent, family int) (AddressIntent, error) {
if !poolKeyPattern.MatchString(value.PoolKey) {
return AddressIntent{}, errors.New("pool key must contain 32 lowercase hexadecimal characters")
}
pool, err := netip.ParsePrefix(value.PoolCIDR)
if err != nil || pool != pool.Masked() || familyOf(pool.Addr()) != family {
return AddressIntent{}, errors.New("pool CIDR is not a canonical address-family network")
}
if family == 4 && (pool.Bits() < 1 || pool.Bits() > 30) {
return AddressIntent{}, errors.New("IPv4 pool prefix must be between /1 and /30")
}
if family == 6 && (pool.Bits() < 1 || pool.Bits() > 120) {
return AddressIntent{}, errors.New("IPv6 pool prefix must be between /1 and /120")
}
requested, err := netip.ParsePrefix(value.AddressCIDR)
if err != nil || familyOf(requested.Addr()) != family || requested.Bits() != pool.Bits() ||
!pool.Contains(requested.Addr()) || requested.Addr() == pool.Addr() {
return AddressIntent{}, errors.New("address CIDR must be a usable host inside its pool")
}
if family == 4 && requested.Addr() == lastIPv4(pool) {
return AddressIntent{}, errors.New("IPv4 address cannot be the broadcast address")
}
if !validPublicAddress(requested.Addr()) {
return AddressIntent{}, errors.New("address must be globally routable unicast")
}
gateway, err := netip.ParseAddr(value.Gateway)
if err != nil || familyOf(gateway) != family || !validPublicAddress(gateway) {
return AddressIntent{}, errors.New("gateway is invalid")
}
if family == 4 && (gateway == pool.Addr() || gateway == lastIPv4(pool)) {
return AddressIntent{}, errors.New("gateway cannot select the network or broadcast address")
}
if gateway == requested.Addr() {
return AddressIntent{}, errors.New("gateway cannot equal the assigned address")
}
if !pool.Contains(gateway) && !value.GatewayOnLink {
return AddressIntent{}, errors.New("off-prefix gateway requires gateway_on_link")
}
value.PoolCIDR = pool.String()
value.AddressCIDR = netip.PrefixFrom(requested.Addr(), requested.Bits()).String()
value.Gateway = gateway.String()
return value, nil
}
func canonicalDNS(values []string) ([]string, error) {
if len(values) < 1 || len(values) > 4 {
return nil, errors.New("dns_servers must contain one to four addresses")
}
result := make([]string, 0, len(values))
seen := make(map[netip.Addr]struct{}, len(values))
for _, raw := range values {
address, err := netip.ParseAddr(raw)
if err != nil || address.Is4In6() || !validPublicAddress(address) {
return nil, errors.New("dns_servers contains an invalid address")
}
if _, exists := seen[address]; exists {
return nil, errors.New("dns_servers contains a duplicate address")
}
seen[address] = struct{}{}
result = append(result, address.String())
}
return result, nil
}
func familyOf(address netip.Addr) int {
if address.Is4() {
return 4
}
if address.Is6() {
return 6
}
return 0
}
func validPublicAddress(address netip.Addr) bool {
if !address.IsGlobalUnicast() || address.IsPrivate() || address.IsLinkLocalUnicast() {
return false
}
if address.Is4() {
for _, prefix := range []netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"),
netip.MustParsePrefix("10.0.0.0/8"),
netip.MustParsePrefix("100.64.0.0/10"),
netip.MustParsePrefix("127.0.0.0/8"),
netip.MustParsePrefix("169.254.0.0/16"),
netip.MustParsePrefix("172.16.0.0/12"),
netip.MustParsePrefix("192.0.0.0/24"),
netip.MustParsePrefix("192.0.2.0/24"),
netip.MustParsePrefix("192.168.0.0/16"),
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("198.51.100.0/24"),
netip.MustParsePrefix("203.0.113.0/24"),
netip.MustParsePrefix("224.0.0.0/4"),
netip.MustParsePrefix("240.0.0.0/4"),
} {
if prefix.Contains(address) {
return false
}
}
}
return true
}
func lastIPv4(prefix netip.Prefix) netip.Addr {
address := prefix.Masked().Addr().As4()
bits := uint32(address[0])<<24 | uint32(address[1])<<16 | uint32(address[2])<<8 | uint32(address[3])
bits |= ^uint32(0) >> prefix.Bits()
return netip.AddrFrom4([4]byte{byte(bits >> 24), byte(bits >> 16), byte(bits >> 8), byte(bits)})
}