mirror of
https://github.com/h44z/wg-portal.git
synced 2026-12-05 11:46:09 +01:00
feat: add support for AmneziaWG (#649)
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
package lowlevel
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
"github.com/vishvananda/netlink/nl"
|
||||
"golang.org/x/sys/unix"
|
||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
// AmneziaWGClient implements the wgctrl client contract using the AmneziaWG
|
||||
// kernel's Generic Netlink family.
|
||||
type AmneziaWGClient struct {
|
||||
version uint8
|
||||
exchange func(command uint8, flags uint16, attrs []*nl.RtAttr) ([][]byte, error)
|
||||
linkByName func(string) (netlink.Link, error)
|
||||
links func() ([]netlink.Link, error)
|
||||
}
|
||||
|
||||
func NewAmneziaWGClient() (*AmneziaWGClient, error) {
|
||||
family, err := amneziaWGFamily(netlink.GenlFamilyGet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &AmneziaWGClient{
|
||||
version: uint8(family.Version), linkByName: netlink.LinkByName, links: netlink.LinkList,
|
||||
exchange: func(command uint8, flags uint16, attrs []*nl.RtAttr) ([][]byte, error) {
|
||||
req := nl.NewNetlinkRequest(int(family.ID), int(flags))
|
||||
req.AddData(&nl.Genlmsg{Command: command, Version: uint8(family.Version)})
|
||||
for _, attr := range attrs {
|
||||
req.AddData(attr)
|
||||
}
|
||||
return req.Execute(unix.NETLINK_GENERIC, family.ID)
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func amneziaWGFamily(lookup func(string) (*netlink.GenlFamily, error)) (*netlink.GenlFamily, error) {
|
||||
family, err := lookup("amneziawg")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AmneziaWG kernel support is unavailable; install and load the amneziawg module on the host (modprobe amneziawg): %w", err)
|
||||
}
|
||||
if family == nil || family.Version < 1 || family.Version > 3 {
|
||||
return nil, fmt.Errorf("unsupported AmneziaWG Generic Netlink version (supported: 1, 2, 3)")
|
||||
}
|
||||
return family, nil
|
||||
}
|
||||
|
||||
// Requests use their own short-lived sockets, which the netlink library closes.
|
||||
func (c *AmneziaWGClient) Close() error { return nil }
|
||||
|
||||
func (c *AmneziaWGClient) kernelLink(name string) error {
|
||||
link, err := c.linkByName(name)
|
||||
if err != nil {
|
||||
if _, ok := errors.AsType[netlink.LinkNotFoundError](err); ok {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
return err
|
||||
}
|
||||
if link.Type() != "amneziawg" {
|
||||
return fmt.Errorf("interface %s is not an AmneziaWG kernel device", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) Devices() ([]*wgtypes.Device, error) {
|
||||
links, err := c.links()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var devices []*wgtypes.Device
|
||||
for _, link := range links {
|
||||
if link.Type() != "amneziawg" {
|
||||
continue
|
||||
}
|
||||
device, err := c.Device(link.Attrs().Name)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
devices = append(devices, device)
|
||||
}
|
||||
return devices, nil
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) Device(name string) (*wgtypes.Device, error) {
|
||||
device, _, err := c.readDevice(name)
|
||||
return device, err
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) AmneziaWGOptions(name string) (domain.AmneziaWGOptions, error) {
|
||||
_, options, err := c.readDevice(name)
|
||||
return options, err
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) readDevice(name string) (*wgtypes.Device, domain.AmneziaWGOptions, error) {
|
||||
if err := c.kernelLink(name); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
messages, err := c.exchange(awgGetDevice, unix.NLM_F_DUMP, []*nl.RtAttr{nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, nl.ZeroTerminated(name))})
|
||||
if errors.Is(err, unix.ENODEV) || errors.Is(err, unix.ENOENT) {
|
||||
return nil, nil, os.ErrNotExist
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("AmneziaWG device read: %w", err)
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
return nil, nil, os.ErrNotExist
|
||||
}
|
||||
device, options, err := parseAmneziaWGDevice(messages, c.version)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid AmneziaWG device response: %w", err)
|
||||
}
|
||||
if device.Name != name {
|
||||
return nil, nil, fmt.Errorf("unexpected AmneziaWG interface in response")
|
||||
}
|
||||
return device, options, nil
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) ConfigureDevice(name string, cfg wgtypes.Config) error {
|
||||
return c.ConfigureAmneziaWGDevice(name, cfg, nil)
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) ConfigureAmneziaWGDevice(name string, cfg wgtypes.Config, options domain.AmneziaWGOptions) error {
|
||||
// Encode every batch before changing the device, so invalid input cannot
|
||||
// leave an otherwise valid prefix of the configuration applied.
|
||||
batches, err := amneziaWGConfigBatches(name, cfg, options, c.version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.kernelLink(name); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, attrs := range batches {
|
||||
if _, err := c.exchange(awgSetDevice, unix.NLM_F_ACK, attrs); err != nil {
|
||||
if errors.Is(err, unix.ENODEV) || errors.Is(err, unix.ENOENT) {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
return fmt.Errorf("AmneziaWG device configuration: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
package lowlevel
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/vishvananda/netlink/nl"
|
||||
"golang.org/x/sys/unix"
|
||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
awgGetDevice uint8 = 0
|
||||
awgSetDevice uint8 = 1
|
||||
awgMaxPayload = 60000
|
||||
awgIPChunk = 256
|
||||
)
|
||||
|
||||
func amneziaWGConfigBatches(name string, cfg wgtypes.Config, options domain.AmneziaWGOptions, version uint8) ([][]*nl.RtAttr, error) {
|
||||
if len(name) == 0 || len(name) >= unix.IFNAMSIZ || strings.ContainsRune(name, 0) {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG interface name")
|
||||
}
|
||||
attrs := []*nl.RtAttr{nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, nl.ZeroTerminated(name))}
|
||||
if cfg.PrivateKey != nil {
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_PRIVATE_KEY, cfg.PrivateKey[:]))
|
||||
}
|
||||
if cfg.ListenPort != nil {
|
||||
if *cfg.ListenPort < 0 || *cfg.ListenPort > 65535 {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG listen port")
|
||||
}
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_LISTEN_PORT, awgNumber(uint64(*cfg.ListenPort), 2)))
|
||||
}
|
||||
if cfg.FirewallMark != nil {
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_FWMARK, awgNumber(uint64(uint32(*cfg.FirewallMark)), 4)))
|
||||
}
|
||||
if cfg.ReplacePeers {
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_FLAGS, awgNumber(unix.WGDEVICE_F_REPLACE_PEERS, 4)))
|
||||
}
|
||||
custom, err := encodeAmneziaWGOptions(options, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attrs = append(attrs, custom...)
|
||||
var batches [][]*nl.RtAttr
|
||||
var peers *nl.RtAttr
|
||||
size := nl.SizeofGenlmsg
|
||||
for _, attr := range attrs {
|
||||
size += len(attr.Serialize())
|
||||
}
|
||||
flush := func() {
|
||||
if peers != nil {
|
||||
attrs = append(attrs, peers)
|
||||
}
|
||||
batches = append(batches, attrs)
|
||||
// Destructive replacement flags and interface options belong only in
|
||||
// the first message. Later messages append peer/IP continuations.
|
||||
attrs = []*nl.RtAttr{nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, nl.ZeroTerminated(name))}
|
||||
size = nl.SizeofGenlmsg + len(attrs[0].Serialize())
|
||||
peers = nil
|
||||
}
|
||||
for _, peer := range cfg.Peers {
|
||||
for start, first := 0, true; first || start < len(peer.AllowedIPs); first = false {
|
||||
end := min(start+awgIPChunk, len(peer.AllowedIPs))
|
||||
chunk, err := encodeAmneziaWGPeer(peer, peer.AllowedIPs[start:end], first, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
length := len(chunk.Serialize())
|
||||
if size+length+unix.SizeofRtAttr > awgMaxPayload {
|
||||
flush()
|
||||
}
|
||||
if peers == nil {
|
||||
peers = nl.NewRtAttr(unix.WGDEVICE_A_PEERS|unix.NLA_F_NESTED, nil)
|
||||
size += unix.SizeofRtAttr
|
||||
}
|
||||
peers.AddChild(chunk)
|
||||
size += length
|
||||
start = end
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return batches, nil
|
||||
}
|
||||
|
||||
func encodeAmneziaWGPeer(peer wgtypes.PeerConfig, ips []net.IPNet, first bool, version uint8) (*nl.RtAttr, error) {
|
||||
attr := nl.NewRtAttr(unix.NLA_F_NESTED, nil)
|
||||
attr.AddRtAttr(unix.WGPEER_A_PUBLIC_KEY, peer.PublicKey[:])
|
||||
var flags uint32
|
||||
if peer.Remove {
|
||||
flags |= unix.WGPEER_F_REMOVE_ME
|
||||
}
|
||||
if peer.UpdateOnly {
|
||||
flags |= unix.WGPEER_F_UPDATE_ONLY
|
||||
}
|
||||
if first && peer.ReplaceAllowedIPs {
|
||||
flags |= unix.WGPEER_F_REPLACE_ALLOWEDIPS
|
||||
}
|
||||
if flags != 0 {
|
||||
attr.AddRtAttr(unix.WGPEER_A_FLAGS, awgNumber(uint64(flags), 4))
|
||||
}
|
||||
if first {
|
||||
if peer.PresharedKey != nil {
|
||||
attr.AddRtAttr(unix.WGPEER_A_PRESHARED_KEY, peer.PresharedKey[:])
|
||||
}
|
||||
if peer.Endpoint != nil {
|
||||
data, err := encodeAmneziaWGSockaddr(peer.Endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attr.AddRtAttr(unix.WGPEER_A_ENDPOINT, data)
|
||||
}
|
||||
if peer.PersistentKeepaliveInterval != nil {
|
||||
interval := *peer.PersistentKeepaliveInterval
|
||||
if interval < 0 || interval > 65535*time.Second || interval%time.Second != 0 {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG keepalive interval")
|
||||
}
|
||||
value, size := uint64(interval/time.Second), 2
|
||||
if version >= 3 {
|
||||
value |= value << 16
|
||||
size = 4
|
||||
}
|
||||
attr.AddRtAttr(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, awgNumber(value, size))
|
||||
}
|
||||
}
|
||||
if len(ips) != 0 {
|
||||
allowed := attr.AddRtAttr(unix.WGPEER_A_ALLOWEDIPS|unix.NLA_F_NESTED, nil)
|
||||
for _, ip := range ips {
|
||||
address, family, bits := ip.IP.To4(), uint64(unix.AF_INET), 32
|
||||
if address == nil {
|
||||
address, family, bits = ip.IP.To16(), unix.AF_INET6, 128
|
||||
}
|
||||
ones, maskBits := ip.Mask.Size()
|
||||
if address == nil || maskBits != bits {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG allowed IP")
|
||||
}
|
||||
entry := allowed.AddRtAttr(unix.NLA_F_NESTED, nil)
|
||||
entry.AddRtAttr(unix.WGALLOWEDIP_A_FAMILY, awgNumber(family, 2))
|
||||
entry.AddRtAttr(unix.WGALLOWEDIP_A_IPADDR, address)
|
||||
entry.AddRtAttr(unix.WGALLOWEDIP_A_CIDR_MASK, []byte{byte(ones)})
|
||||
}
|
||||
}
|
||||
return attr, nil
|
||||
}
|
||||
|
||||
func encodeAmneziaWGSockaddr(endpoint *net.UDPAddr) ([]byte, error) {
|
||||
if endpoint.Port < 0 || endpoint.Port > 65535 {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG endpoint port")
|
||||
}
|
||||
if ip := endpoint.IP.To4(); ip != nil {
|
||||
data := make([]byte, unix.SizeofSockaddrInet4)
|
||||
nl.NativeEndian().PutUint16(data, unix.AF_INET)
|
||||
binary.BigEndian.PutUint16(data[2:], uint16(endpoint.Port))
|
||||
copy(data[4:], ip)
|
||||
return data, nil
|
||||
}
|
||||
ip := endpoint.IP.To16()
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG endpoint IP")
|
||||
}
|
||||
data := make([]byte, unix.SizeofSockaddrInet6)
|
||||
nl.NativeEndian().PutUint16(data, unix.AF_INET6)
|
||||
binary.BigEndian.PutUint16(data[2:], uint16(endpoint.Port))
|
||||
copy(data[8:], ip)
|
||||
if endpoint.Zone != "" {
|
||||
index, err := strconv.ParseUint(endpoint.Zone, 10, 32)
|
||||
if err != nil {
|
||||
iface, err := net.InterfaceByName(endpoint.Zone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG endpoint zone")
|
||||
}
|
||||
index = uint64(iface.Index)
|
||||
}
|
||||
nl.NativeEndian().PutUint32(data[24:], uint32(index))
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Validate lengths before using netlink's attribute decoder, including padding
|
||||
// that would otherwise let a truncated attribute panic during decoding.
|
||||
func amneziaWGAttrs(data []byte) ([]syscall.NetlinkRouteAttr, error) {
|
||||
for rest := data; len(rest) != 0; {
|
||||
if len(rest) < unix.SizeofRtAttr {
|
||||
return nil, fmt.Errorf("truncated AmneziaWG attribute")
|
||||
}
|
||||
length := int(nl.NativeEndian().Uint16(rest))
|
||||
padded := (length + 3) &^ 3
|
||||
if length < unix.SizeofRtAttr || padded > len(rest) {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG attribute length")
|
||||
}
|
||||
rest = rest[padded:]
|
||||
}
|
||||
return nl.ParseRouteAttr(data)
|
||||
}
|
||||
|
||||
func parseAmneziaWGDevice(messages [][]byte, version uint8) (*wgtypes.Device, domain.AmneziaWGOptions, error) {
|
||||
device := &wgtypes.Device{Type: wgtypes.LinuxKernel}
|
||||
options := domain.AmneziaWGOptions{}
|
||||
known := make(map[wgtypes.Key]int)
|
||||
for _, message := range messages {
|
||||
if len(message) < nl.SizeofGenlmsg || message[0] != awgGetDevice {
|
||||
return nil, nil, fmt.Errorf("invalid AmneziaWG message header")
|
||||
}
|
||||
attrs, err := amneziaWGAttrs(message[nl.SizeofGenlmsg:])
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, attr := range attrs {
|
||||
kind, data := attr.Attr.Type&0x3fff, attr.Value
|
||||
switch kind {
|
||||
case unix.WGDEVICE_A_IFNAME:
|
||||
var name string
|
||||
name, err = awgString(data)
|
||||
if device.Name != "" && name != device.Name {
|
||||
return nil, nil, fmt.Errorf("mixed AmneziaWG interfaces in dump")
|
||||
}
|
||||
device.Name = name
|
||||
case unix.WGDEVICE_A_PRIVATE_KEY:
|
||||
device.PrivateKey, err = wgtypes.NewKey(data)
|
||||
case unix.WGDEVICE_A_PUBLIC_KEY:
|
||||
device.PublicKey, err = wgtypes.NewKey(data)
|
||||
case unix.WGDEVICE_A_LISTEN_PORT:
|
||||
var v uint64
|
||||
v, err = awgReadNumber(data, 2)
|
||||
device.ListenPort = int(v)
|
||||
case unix.WGDEVICE_A_FWMARK:
|
||||
var v uint64
|
||||
v, err = awgReadNumber(data, 4)
|
||||
device.FirewallMark = int(v)
|
||||
case unix.WGDEVICE_A_PEERS:
|
||||
var peers []syscall.NetlinkRouteAttr
|
||||
peers, err = amneziaWGAttrs(data)
|
||||
for _, raw := range peers {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
var peer wgtypes.Peer
|
||||
peer, err = parseAmneziaWGPeer(raw.Value, version)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if index, ok := known[peer.PublicKey]; ok {
|
||||
device.Peers[index].AllowedIPs = append(device.Peers[index].AllowedIPs, peer.AllowedIPs...)
|
||||
} else {
|
||||
known[peer.PublicKey] = len(device.Peers)
|
||||
device.Peers = append(device.Peers, peer)
|
||||
}
|
||||
}
|
||||
default:
|
||||
for _, spec := range awgOptions {
|
||||
if int(kind) == spec.attr {
|
||||
options[spec.name], err = spec.decode(data, version)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid AmneziaWG attribute %d", kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := options.Validate(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return device, options, nil
|
||||
}
|
||||
|
||||
func parseAmneziaWGPeer(data []byte, version uint8) (wgtypes.Peer, error) {
|
||||
peer := wgtypes.Peer{ProtocolVersion: 1}
|
||||
attrs, err := amneziaWGAttrs(data)
|
||||
if err != nil {
|
||||
return peer, err
|
||||
}
|
||||
keyFound := false
|
||||
for _, attr := range attrs {
|
||||
kind, value := attr.Attr.Type&0x3fff, attr.Value
|
||||
switch kind {
|
||||
case unix.WGPEER_A_PUBLIC_KEY:
|
||||
peer.PublicKey, err = wgtypes.NewKey(value)
|
||||
keyFound = true
|
||||
case unix.WGPEER_A_PRESHARED_KEY:
|
||||
peer.PresharedKey, err = wgtypes.NewKey(value)
|
||||
case unix.WGPEER_A_ENDPOINT:
|
||||
peer.Endpoint, err = parseAmneziaWGSockaddr(value)
|
||||
case unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL:
|
||||
size := 2
|
||||
if version >= 3 {
|
||||
size = 4
|
||||
}
|
||||
var v uint64
|
||||
v, err = awgReadNumber(value, size)
|
||||
// The portal exposes a single interval; report a range's lower bound.
|
||||
peer.PersistentKeepaliveInterval = time.Duration(v&0xffff) * time.Second
|
||||
case unix.WGPEER_A_LAST_HANDSHAKE_TIME:
|
||||
peer.LastHandshakeTime, err = parseAmneziaWGTime(value)
|
||||
case unix.WGPEER_A_RX_BYTES:
|
||||
var v uint64
|
||||
v, err = awgReadNumber(value, 8)
|
||||
peer.ReceiveBytes = int64(v)
|
||||
case unix.WGPEER_A_TX_BYTES:
|
||||
var v uint64
|
||||
v, err = awgReadNumber(value, 8)
|
||||
peer.TransmitBytes = int64(v)
|
||||
case unix.WGPEER_A_PROTOCOL_VERSION:
|
||||
var v uint64
|
||||
v, err = awgReadNumber(value, 4)
|
||||
peer.ProtocolVersion = int(v)
|
||||
case unix.WGPEER_A_ALLOWEDIPS:
|
||||
peer.AllowedIPs, err = parseAmneziaWGAllowedIPs(value)
|
||||
}
|
||||
if err != nil {
|
||||
return peer, fmt.Errorf("invalid AmneziaWG peer attribute %d", kind)
|
||||
}
|
||||
}
|
||||
if !keyFound {
|
||||
return peer, fmt.Errorf("missing AmneziaWG peer public key")
|
||||
}
|
||||
return peer, nil
|
||||
}
|
||||
|
||||
func parseAmneziaWGAllowedIPs(data []byte) ([]net.IPNet, error) {
|
||||
entries, err := amneziaWGAttrs(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ips []net.IPNet
|
||||
for _, entry := range entries {
|
||||
attrs, err := amneziaWGAttrs(entry.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var family, prefix uint64
|
||||
var address net.IP
|
||||
familyFound, prefixFound := false, false
|
||||
for _, attr := range attrs {
|
||||
switch attr.Attr.Type & 0x3fff {
|
||||
case unix.WGALLOWEDIP_A_FAMILY:
|
||||
family, err = awgReadNumber(attr.Value, 2)
|
||||
familyFound = true
|
||||
case unix.WGALLOWEDIP_A_CIDR_MASK:
|
||||
prefix, err = awgReadNumber(attr.Value, 1)
|
||||
prefixFound = true
|
||||
case unix.WGALLOWEDIP_A_IPADDR:
|
||||
address = append(net.IP(nil), attr.Value...)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
bits := 0
|
||||
if family == unix.AF_INET && len(address) == net.IPv4len {
|
||||
bits = 32
|
||||
}
|
||||
if family == unix.AF_INET6 && len(address) == net.IPv6len {
|
||||
bits = 128
|
||||
}
|
||||
if !familyFound || !prefixFound || bits == 0 || prefix > uint64(bits) {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG allowed IP")
|
||||
}
|
||||
ips = append(ips, net.IPNet{IP: address, Mask: net.CIDRMask(int(prefix), bits)})
|
||||
}
|
||||
return ips, nil
|
||||
}
|
||||
|
||||
func parseAmneziaWGSockaddr(data []byte) (*net.UDPAddr, error) {
|
||||
if len(data) < 4 {
|
||||
return nil, fmt.Errorf("truncated AmneziaWG endpoint")
|
||||
}
|
||||
family := nl.NativeEndian().Uint16(data)
|
||||
endpoint := &net.UDPAddr{Port: int(binary.BigEndian.Uint16(data[2:]))}
|
||||
switch {
|
||||
case family == unix.AF_INET && len(data) == unix.SizeofSockaddrInet4:
|
||||
endpoint.IP = append(net.IP(nil), data[4:8]...)
|
||||
case family == unix.AF_INET6 && len(data) == unix.SizeofSockaddrInet6:
|
||||
endpoint.IP = append(net.IP(nil), data[8:24]...)
|
||||
if zone := nl.NativeEndian().Uint32(data[24:]); zone != 0 {
|
||||
endpoint.Zone = strconv.FormatUint(uint64(zone), 10)
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid AmneziaWG endpoint")
|
||||
}
|
||||
return endpoint, nil
|
||||
}
|
||||
|
||||
func parseAmneziaWGTime(data []byte) (time.Time, error) {
|
||||
var seconds, nanos int64
|
||||
switch len(data) {
|
||||
case 8:
|
||||
seconds = int64(int32(nl.NativeEndian().Uint32(data)))
|
||||
nanos = int64(int32(nl.NativeEndian().Uint32(data[4:])))
|
||||
case 16:
|
||||
seconds = int64(nl.NativeEndian().Uint64(data))
|
||||
nanos = int64(nl.NativeEndian().Uint64(data[8:]))
|
||||
default:
|
||||
return time.Time{}, fmt.Errorf("invalid AmneziaWG handshake timestamp")
|
||||
}
|
||||
if seconds < 0 || nanos < 0 || nanos >= int64(time.Second) {
|
||||
return time.Time{}, fmt.Errorf("invalid AmneziaWG handshake timestamp")
|
||||
}
|
||||
if seconds == 0 && nanos == 0 {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
return time.Unix(seconds, nanos), nil
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package lowlevel
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/vishvananda/netlink/nl"
|
||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
// Attribute numbers follow the official AmneziaWG UAPI, which extends the
|
||||
// WireGuard attributes without changing their IDs.
|
||||
// https://github.com/amnezia-vpn/amneziawg-tools/blob/ee0f0a9aa34ff0a0da4b3433b9512781cfe02843/src/uapi/linux/linux/wireguard.h
|
||||
const (
|
||||
awgOptionU16 = iota
|
||||
awgOptionHeader
|
||||
awgOptionString
|
||||
awgOptionKey
|
||||
awgOptionRange16
|
||||
awgOptionBool
|
||||
)
|
||||
|
||||
type awgOption struct {
|
||||
name string
|
||||
attr int
|
||||
kind int
|
||||
minVersion uint8
|
||||
}
|
||||
|
||||
var awgOptions = []awgOption{
|
||||
{"Jc", 9, awgOptionU16, 1}, {"Jmin", 10, awgOptionU16, 1}, {"Jmax", 11, awgOptionU16, 1},
|
||||
{"S1", 12, awgOptionU16, 1}, {"S2", 13, awgOptionU16, 1},
|
||||
{"H1", 14, awgOptionHeader, 1}, {"H2", 15, awgOptionHeader, 1},
|
||||
{"H3", 16, awgOptionHeader, 1}, {"H4", 17, awgOptionHeader, 1},
|
||||
// Attribute 18 describes an unknown peer notification, not an option.
|
||||
{"S3", 19, awgOptionU16, 2}, {"S4", 20, awgOptionU16, 2},
|
||||
{"I1", 21, awgOptionString, 2}, {"I2", 22, awgOptionString, 2},
|
||||
{"I3", 23, awgOptionString, 2}, {"I4", 24, awgOptionString, 2}, {"I5", 25, awgOptionString, 2},
|
||||
{"HeaderProtectionKey", 26, awgOptionKey, 3},
|
||||
{"ContentPaddingAddition", 27, awgOptionRange16, 3}, {"RekeyAfterTime", 28, awgOptionRange16, 3},
|
||||
{"RekeyTimeout", 29, awgOptionRange16, 3}, {"RejectAfterTime", 30, awgOptionRange16, 3},
|
||||
{"KeepaliveTimeout", 31, awgOptionRange16, 3}, {"MaxHandshakeAttempts", 32, awgOptionRange16, 3},
|
||||
{"RandomTrailers", 33, awgOptionBool, 3}, {"DisableCookies", 34, awgOptionBool, 3},
|
||||
}
|
||||
|
||||
func encodeAmneziaWGOptions(options domain.AmneziaWGOptions, version uint8) ([]*nl.RtAttr, error) {
|
||||
if err := options.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var attrs []*nl.RtAttr
|
||||
for _, spec := range awgOptions {
|
||||
value, ok := options[spec.name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if version < spec.minVersion {
|
||||
return nil, fmt.Errorf("AmneziaWG option %s requires kernel netlink version %d: %w", spec.name, spec.minVersion, domain.ErrInvalidData)
|
||||
}
|
||||
data, err := spec.encode(value, version)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid AmneziaWG option %s: %v: %w", spec.name, err, domain.ErrInvalidData)
|
||||
}
|
||||
attrs = append(attrs, nl.NewRtAttr(spec.attr, data))
|
||||
}
|
||||
return attrs, nil
|
||||
}
|
||||
|
||||
func (o awgOption) encode(value string, version uint8) ([]byte, error) {
|
||||
switch o.kind {
|
||||
case awgOptionU16:
|
||||
v, err := strconv.ParseUint(value, 10, 16)
|
||||
return awgNumber(v, 2), err
|
||||
case awgOptionHeader:
|
||||
lo, hi, err := awgRange(value, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch version {
|
||||
case 1:
|
||||
if lo != hi {
|
||||
return nil, fmt.Errorf("header ranges require AmneziaWG v2 or newer")
|
||||
}
|
||||
return awgNumber(lo, 4), nil
|
||||
case 2:
|
||||
return nl.ZeroTerminated(awgRangeString(lo, hi)), nil
|
||||
default:
|
||||
return awgNumber(lo|hi<<32, 8), nil
|
||||
}
|
||||
case awgOptionString:
|
||||
return nl.ZeroTerminated(value), nil
|
||||
case awgOptionKey:
|
||||
key, err := wgtypes.ParseKey(value)
|
||||
return key[:], err
|
||||
case awgOptionRange16:
|
||||
lo, hi, err := awgRange(value, 16)
|
||||
return awgNumber(lo|hi<<16, 4), err
|
||||
case awgOptionBool:
|
||||
if value == "1" || value == "on" {
|
||||
return []byte{1}, nil
|
||||
}
|
||||
return []byte{0}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unknown AmneziaWG option kind")
|
||||
}
|
||||
|
||||
func (o awgOption) decode(data []byte, version uint8) (string, error) {
|
||||
switch o.kind {
|
||||
case awgOptionU16:
|
||||
v, err := awgReadNumber(data, 2)
|
||||
return strconv.FormatUint(v, 10), err
|
||||
case awgOptionHeader:
|
||||
switch version {
|
||||
case 1:
|
||||
v, err := awgReadNumber(data, 4)
|
||||
return strconv.FormatUint(v, 10), err
|
||||
case 2:
|
||||
value, err := awgString(data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
lo, hi, err := awgRange(value, 32)
|
||||
return awgRangeString(lo, hi), err
|
||||
default:
|
||||
v, err := awgReadNumber(data, 8)
|
||||
return awgRangeString(v&0xffffffff, v>>32), err
|
||||
}
|
||||
case awgOptionString:
|
||||
return awgString(data)
|
||||
case awgOptionKey:
|
||||
key, err := wgtypes.NewKey(data)
|
||||
return key.String(), err
|
||||
case awgOptionRange16:
|
||||
v, err := awgReadNumber(data, 4)
|
||||
return awgRangeString(v&0xffff, v>>16), err
|
||||
case awgOptionBool:
|
||||
v, err := awgReadNumber(data, 1)
|
||||
if v != 0 {
|
||||
return "on", err
|
||||
}
|
||||
return "off", err
|
||||
}
|
||||
return "", fmt.Errorf("unknown AmneziaWG option kind")
|
||||
}
|
||||
|
||||
func awgNumber(v uint64, size int) []byte {
|
||||
b := make([]byte, size)
|
||||
switch size {
|
||||
case 1:
|
||||
b[0] = byte(v)
|
||||
case 2:
|
||||
nl.NativeEndian().PutUint16(b, uint16(v))
|
||||
case 4:
|
||||
nl.NativeEndian().PutUint32(b, uint32(v))
|
||||
case 8:
|
||||
nl.NativeEndian().PutUint64(b, v)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func awgReadNumber(b []byte, size int) (uint64, error) {
|
||||
if len(b) != size {
|
||||
return 0, fmt.Errorf("invalid AmneziaWG numeric attribute size")
|
||||
}
|
||||
switch size {
|
||||
case 1:
|
||||
return uint64(b[0]), nil
|
||||
case 2:
|
||||
return uint64(nl.NativeEndian().Uint16(b)), nil
|
||||
case 4:
|
||||
return uint64(nl.NativeEndian().Uint32(b)), nil
|
||||
case 8:
|
||||
return nl.NativeEndian().Uint64(b), nil
|
||||
}
|
||||
return 0, fmt.Errorf("invalid AmneziaWG numeric size")
|
||||
}
|
||||
|
||||
func awgString(data []byte) (string, error) {
|
||||
if len(data) == 0 || data[len(data)-1] != 0 || strings.IndexByte(string(data[:len(data)-1]), 0) >= 0 {
|
||||
return "", fmt.Errorf("invalid AmneziaWG string attribute")
|
||||
}
|
||||
return string(data[:len(data)-1]), nil
|
||||
}
|
||||
|
||||
func awgRange(value string, bits int) (uint64, uint64, error) {
|
||||
parts := strings.Split(value, "-")
|
||||
if len(parts) > 2 {
|
||||
return 0, 0, fmt.Errorf("invalid range")
|
||||
}
|
||||
lo, err := strconv.ParseUint(parts[0], 10, bits)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
hi := lo
|
||||
if len(parts) == 2 {
|
||||
hi, err = strconv.ParseUint(parts[1], 10, bits)
|
||||
}
|
||||
if err != nil || lo > hi {
|
||||
return 0, 0, fmt.Errorf("invalid range")
|
||||
}
|
||||
return lo, hi, nil
|
||||
}
|
||||
|
||||
func awgRangeString(lo, hi uint64) string {
|
||||
if lo == hi {
|
||||
return strconv.FormatUint(lo, 10)
|
||||
}
|
||||
return fmt.Sprintf("%d-%d", lo, hi)
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
package lowlevel
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/vishvananda/netlink"
|
||||
"github.com/vishvananda/netlink/nl"
|
||||
"golang.org/x/sys/unix"
|
||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
const awgTestPrivateKey = "gI6EdUSYvn8ugXOt8QQD6Yc+JyiZxIhp3GInSWRfWGE="
|
||||
const awgTestPublicKey = "HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw="
|
||||
|
||||
func awgKernelLink(name string) (netlink.Link, error) {
|
||||
return &netlink.GenericLink{Name: name, LinkType: "amneziawg"}, nil
|
||||
}
|
||||
|
||||
func awgTestReply(version uint8, attrs ...*nl.RtAttr) []byte {
|
||||
data := []byte{0, version, 0, 0}
|
||||
for _, attr := range attrs {
|
||||
data = append(data, attr.Serialize()...)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func awgTestAttrMap(t *testing.T, data []byte) map[uint16][]byte {
|
||||
t.Helper()
|
||||
attrs, err := nl.ParseRouteAttr(data)
|
||||
require.NoError(t, err)
|
||||
result := map[uint16][]byte{}
|
||||
for _, attr := range attrs {
|
||||
result[attr.Attr.Type&0x3fff] = attr.Value
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func awgTestSerialize(attrs []*nl.RtAttr) []byte {
|
||||
var data []byte
|
||||
for _, attr := range attrs {
|
||||
data = append(data, attr.Serialize()...)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func awgTestIPs(address string, prefix byte) *nl.RtAttr {
|
||||
allowed := nl.NewRtAttr(unix.WGPEER_A_ALLOWEDIPS|unix.NLA_F_NESTED, nil)
|
||||
entry := allowed.AddRtAttr(unix.NLA_F_NESTED, nil)
|
||||
ip, family := net.ParseIP(address).To4(), uint16(unix.AF_INET)
|
||||
if ip == nil {
|
||||
ip, family = net.ParseIP(address).To16(), unix.AF_INET6
|
||||
}
|
||||
entry.AddRtAttr(unix.WGALLOWEDIP_A_FAMILY, binary.NativeEndian.AppendUint16(nil, family))
|
||||
entry.AddRtAttr(unix.WGALLOWEDIP_A_IPADDR, ip)
|
||||
entry.AddRtAttr(unix.WGALLOWEDIP_A_CIDR_MASK, []byte{prefix})
|
||||
return allowed
|
||||
}
|
||||
|
||||
func awgTestDeviceReplies(t *testing.T, version uint8) [][]byte {
|
||||
t.Helper()
|
||||
private, err := wgtypes.ParseKey(awgTestPrivateKey)
|
||||
require.NoError(t, err)
|
||||
public, err := wgtypes.ParseKey(awgTestPublicKey)
|
||||
require.NoError(t, err)
|
||||
peers := nl.NewRtAttr(unix.WGDEVICE_A_PEERS|unix.NLA_F_NESTED, nil)
|
||||
peer := peers.AddRtAttr(unix.NLA_F_NESTED, nil)
|
||||
peer.AddRtAttr(unix.WGPEER_A_PUBLIC_KEY, public[:])
|
||||
peer.AddRtAttr(unix.WGPEER_A_RX_BYTES, binary.NativeEndian.AppendUint64(nil, 123))
|
||||
peer.AddRtAttr(unix.WGPEER_A_TX_BYTES, binary.NativeEndian.AppendUint64(nil, 456))
|
||||
peer.AddRtAttr(unix.WGPEER_A_LAST_HANDSHAKE_TIME, append(binary.NativeEndian.AppendUint64(nil, 1700000000), binary.NativeEndian.AppendUint64(nil, 42)...))
|
||||
keepalive := binary.NativeEndian.AppendUint16(nil, 25)
|
||||
if version >= 3 {
|
||||
keepalive = binary.NativeEndian.AppendUint32(nil, 35<<16|25)
|
||||
}
|
||||
peer.AddRtAttr(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, keepalive)
|
||||
endpoint := make([]byte, 28)
|
||||
binary.NativeEndian.PutUint16(endpoint, unix.AF_INET6)
|
||||
binary.BigEndian.PutUint16(endpoint[2:], 1234)
|
||||
copy(endpoint[8:], net.ParseIP("2001:db8::1").To16())
|
||||
peer.AddRtAttr(unix.WGPEER_A_ENDPOINT, endpoint)
|
||||
peer.AddChild(awgTestIPs("10.0.0.2", 32))
|
||||
header := binary.NativeEndian.AppendUint32(nil, 100)
|
||||
if version == 2 {
|
||||
header = []byte("100-200\x00")
|
||||
}
|
||||
if version == 3 {
|
||||
header = binary.NativeEndian.AppendUint64(nil, 200<<32|100)
|
||||
}
|
||||
first := awgTestReply(version,
|
||||
nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, []byte("awg0\x00")),
|
||||
nl.NewRtAttr(unix.WGDEVICE_A_PRIVATE_KEY, private[:]),
|
||||
nl.NewRtAttr(unix.WGDEVICE_A_PUBLIC_KEY, public[:]),
|
||||
nl.NewRtAttr(unix.WGDEVICE_A_LISTEN_PORT, binary.NativeEndian.AppendUint16(nil, 51820)),
|
||||
nl.NewRtAttr(unix.WGDEVICE_A_FWMARK, binary.NativeEndian.AppendUint32(nil, 0xca6c)),
|
||||
nl.NewRtAttr(9, binary.NativeEndian.AppendUint16(nil, 4)), nl.NewRtAttr(14, header), peers,
|
||||
nl.NewRtAttr(255, []byte("future attribute")),
|
||||
)
|
||||
continuation := nl.NewRtAttr(unix.WGDEVICE_A_PEERS|unix.NLA_F_NESTED, nil)
|
||||
peer = continuation.AddRtAttr(unix.NLA_F_NESTED, nil)
|
||||
peer.AddRtAttr(unix.WGPEER_A_PUBLIC_KEY, public[:])
|
||||
peer.AddChild(awgTestIPs("fd00::2", 128))
|
||||
return [][]byte{first, awgTestReply(version, nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, []byte("awg0\x00")), continuation)}
|
||||
}
|
||||
|
||||
func TestAmneziaWGNativeDeviceVersionsAndMultipartDump(t *testing.T) {
|
||||
for version := uint8(1); version <= 3; version++ {
|
||||
t.Run(fmt.Sprint(version), func(t *testing.T) {
|
||||
client := &AmneziaWGClient{version: version, linkByName: awgKernelLink,
|
||||
exchange: func(command uint8, flags uint16, attrs []*nl.RtAttr) ([][]byte, error) {
|
||||
require.Equal(t, uint8(0), command)
|
||||
require.Equal(t, uint16(unix.NLM_F_DUMP), flags)
|
||||
require.Equal(t, []byte("awg0\x00"), awgTestAttrMap(t, awgTestSerialize(attrs))[unix.WGDEVICE_A_IFNAME])
|
||||
return awgTestDeviceReplies(t, version), nil
|
||||
},
|
||||
}
|
||||
device, err := client.Device("awg0")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, awgTestPrivateKey, device.PrivateKey.String())
|
||||
require.Equal(t, awgTestPublicKey, device.PublicKey.String())
|
||||
require.Equal(t, wgtypes.LinuxKernel, device.Type)
|
||||
require.Equal(t, 51820, device.ListenPort)
|
||||
require.Equal(t, 51820, device.FirewallMark)
|
||||
require.Len(t, device.Peers, 1)
|
||||
peer := device.Peers[0]
|
||||
require.Len(t, peer.AllowedIPs, 2)
|
||||
require.Equal(t, "10.0.0.2/32", peer.AllowedIPs[0].String())
|
||||
require.Equal(t, "fd00::2/128", peer.AllowedIPs[1].String())
|
||||
require.Equal(t, "[2001:db8::1]:1234", peer.Endpoint.String())
|
||||
require.Equal(t, time.Unix(1700000000, 42), peer.LastHandshakeTime)
|
||||
require.Equal(t, int64(123), peer.ReceiveBytes)
|
||||
require.Equal(t, int64(456), peer.TransmitBytes)
|
||||
require.Equal(t, 25*time.Second, peer.PersistentKeepaliveInterval)
|
||||
options, err := client.AmneziaWGOptions("awg0")
|
||||
require.NoError(t, err)
|
||||
header := "100"
|
||||
if version >= 2 {
|
||||
header = "100-200"
|
||||
}
|
||||
require.Equal(t, domain.AmneziaWGOptions{"H1": header, "Jc": "4"}, options)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAmneziaWGKernelSupportWithoutTools(t *testing.T) {
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
missing := errors.New("family not found")
|
||||
_, err := amneziaWGFamily(func(name string) (*netlink.GenlFamily, error) {
|
||||
require.Equal(t, "amneziawg", name)
|
||||
return nil, missing
|
||||
})
|
||||
require.ErrorIs(t, err, missing)
|
||||
require.ErrorContains(t, err, "modprobe amneziawg")
|
||||
for _, version := range []uint32{1, 2, 3} {
|
||||
family, err := amneziaWGFamily(func(string) (*netlink.GenlFamily, error) { return &netlink.GenlFamily{ID: 42, Version: version}, nil })
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, version, family.Version)
|
||||
}
|
||||
_, err = amneziaWGFamily(func(string) (*netlink.GenlFamily, error) { return &netlink.GenlFamily{Version: 4}, nil })
|
||||
require.ErrorContains(t, err, "unsupported")
|
||||
}
|
||||
|
||||
func TestAmneziaWGNativeConfigurationFlagsAndExplicitZeroes(t *testing.T) {
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
key, err := wgtypes.ParseKey(awgTestPublicKey)
|
||||
require.NoError(t, err)
|
||||
private, err := wgtypes.ParseKey(awgTestPrivateKey)
|
||||
require.NoError(t, err)
|
||||
var captured []byte
|
||||
client := &AmneziaWGClient{version: 3, linkByName: awgKernelLink,
|
||||
exchange: func(command uint8, flags uint16, attrs []*nl.RtAttr) ([][]byte, error) {
|
||||
require.Equal(t, uint8(1), command, "configuration must not read and rewrite existing peers")
|
||||
require.Equal(t, uint16(unix.NLM_F_ACK), flags)
|
||||
captured = awgTestSerialize(attrs)
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
zero, mark, keepalive := 0, -1, time.Duration(0)
|
||||
require.NoError(t, client.ConfigureAmneziaWGDevice("awg0", wgtypes.Config{
|
||||
PrivateKey: &private, ListenPort: &zero, FirewallMark: &mark,
|
||||
Peers: []wgtypes.PeerConfig{{PublicKey: key, UpdateOnly: true, ReplaceAllowedIPs: true, PresharedKey: &wgtypes.Key{}, PersistentKeepaliveInterval: &keepalive}},
|
||||
}, domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"}))
|
||||
attrs := awgTestAttrMap(t, captured)
|
||||
require.Equal(t, private[:], attrs[unix.WGDEVICE_A_PRIVATE_KEY])
|
||||
require.Equal(t, []byte{0, 0}, attrs[unix.WGDEVICE_A_LISTEN_PORT])
|
||||
require.Equal(t, []byte{255, 255, 255, 255}, attrs[unix.WGDEVICE_A_FWMARK])
|
||||
require.NotContains(t, attrs, uint16(unix.WGDEVICE_A_FLAGS))
|
||||
peers, err := nl.ParseRouteAttr(attrs[unix.WGDEVICE_A_PEERS])
|
||||
require.NoError(t, err)
|
||||
require.Len(t, peers, 1)
|
||||
peer := awgTestAttrMap(t, peers[0].Value)
|
||||
require.Equal(t, uint32(unix.WGPEER_F_UPDATE_ONLY|unix.WGPEER_F_REPLACE_ALLOWEDIPS), binary.NativeEndian.Uint32(peer[unix.WGPEER_A_FLAGS]))
|
||||
require.Equal(t, make([]byte, 32), peer[unix.WGPEER_A_PRESHARED_KEY])
|
||||
require.Equal(t, make([]byte, 4), peer[unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL])
|
||||
require.NotContains(t, peer, uint16(unix.WGPEER_A_ALLOWEDIPS))
|
||||
// Removal is a native peer flag, and needs no extra process or state read.
|
||||
require.NoError(t, client.ConfigureDevice("awg0", wgtypes.Config{Peers: []wgtypes.PeerConfig{{PublicKey: key, Remove: true}}}))
|
||||
peers, err = nl.ParseRouteAttr(awgTestAttrMap(t, captured)[unix.WGDEVICE_A_PEERS])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint32(unix.WGPEER_F_REMOVE_ME), binary.NativeEndian.Uint32(awgTestAttrMap(t, peers[0].Value)[unix.WGPEER_A_FLAGS]))
|
||||
}
|
||||
|
||||
func TestAmneziaWGNativeBatchingPreservesReplacementSemantics(t *testing.T) {
|
||||
key, err := wgtypes.ParseKey(awgTestPublicKey)
|
||||
require.NoError(t, err)
|
||||
ips := make([]net.IPNet, 4096)
|
||||
for i := range ips {
|
||||
ips[i] = net.IPNet{IP: net.ParseIP(fmt.Sprintf("fd00::%x", i)), Mask: net.CIDRMask(128, 128)}
|
||||
}
|
||||
interval := 25 * time.Second
|
||||
cfg := wgtypes.Config{ReplacePeers: true, Peers: []wgtypes.PeerConfig{{PublicKey: key, UpdateOnly: true, ReplaceAllowedIPs: true, PersistentKeepaliveInterval: &interval, AllowedIPs: ips}}}
|
||||
batches, err := amneziaWGConfigBatches("awg0", cfg, domain.AmneziaWGOptions{"Jc": "4"}, 3)
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, len(batches), 1)
|
||||
firstPeer, count := true, 0
|
||||
for i, batch := range batches {
|
||||
data := awgTestSerialize(batch)
|
||||
require.LessOrEqual(t, len(data)+4, awgMaxPayload)
|
||||
attrs := awgTestAttrMap(t, data)
|
||||
if i == 0 {
|
||||
require.Equal(t, uint32(unix.WGDEVICE_F_REPLACE_PEERS), binary.NativeEndian.Uint32(attrs[unix.WGDEVICE_A_FLAGS]))
|
||||
require.Contains(t, attrs, uint16(9))
|
||||
} else {
|
||||
require.NotContains(t, attrs, uint16(unix.WGDEVICE_A_FLAGS))
|
||||
require.NotContains(t, attrs, uint16(9))
|
||||
}
|
||||
peers, err := nl.ParseRouteAttr(attrs[unix.WGDEVICE_A_PEERS])
|
||||
require.NoError(t, err)
|
||||
for _, raw := range peers {
|
||||
peer := awgTestAttrMap(t, raw.Value)
|
||||
flags := binary.NativeEndian.Uint32(peer[unix.WGPEER_A_FLAGS])
|
||||
require.NotZero(t, flags&unix.WGPEER_F_UPDATE_ONLY)
|
||||
require.Equal(t, firstPeer, flags&unix.WGPEER_F_REPLACE_ALLOWEDIPS != 0)
|
||||
if firstPeer {
|
||||
require.Equal(t, uint32(25<<16|25), binary.NativeEndian.Uint32(peer[unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL]))
|
||||
} else {
|
||||
require.NotContains(t, peer, uint16(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL))
|
||||
}
|
||||
entries, err := nl.ParseRouteAttr(peer[unix.WGPEER_A_ALLOWEDIPS])
|
||||
require.NoError(t, err)
|
||||
count += len(entries)
|
||||
firstPeer = false
|
||||
}
|
||||
}
|
||||
require.Equal(t, len(ips), count)
|
||||
require.True(t, cfg.ReplacePeers)
|
||||
require.True(t, cfg.Peers[0].ReplaceAllowedIPs)
|
||||
require.Len(t, cfg.Peers[0].AllowedIPs, 4096)
|
||||
}
|
||||
|
||||
func TestAmneziaWGNativeLinkIsolationAndErrors(t *testing.T) {
|
||||
for _, kind := range []string{"wireguard", "tun"} {
|
||||
client := &AmneziaWGClient{version: 3,
|
||||
linkByName: func(name string) (netlink.Link, error) {
|
||||
return &netlink.GenericLink{Name: name, LinkType: kind}, nil
|
||||
},
|
||||
exchange: func(uint8, uint16, []*nl.RtAttr) ([][]byte, error) {
|
||||
t.Fatal("must not touch other link types")
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
_, err := client.Device("wg0")
|
||||
require.ErrorContains(t, err, "not an AmneziaWG kernel device")
|
||||
require.Error(t, client.ConfigureDevice("wg0", wgtypes.Config{}))
|
||||
}
|
||||
client := &AmneziaWGClient{version: 3, linkByName: awgKernelLink,
|
||||
exchange: func(uint8, uint16, []*nl.RtAttr) ([][]byte, error) { return nil, unix.ENODEV },
|
||||
}
|
||||
_, err := client.Device("missing")
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
require.ErrorIs(t, client.ConfigureDevice("missing", wgtypes.Config{}), os.ErrNotExist)
|
||||
client.links = func() ([]netlink.Link, error) {
|
||||
wg, _ := awgKernelLink("gone")
|
||||
return []netlink.Link{&netlink.Dummy{Name: "ordinary"}, wg}, nil
|
||||
}
|
||||
devices, err := client.Devices()
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, devices)
|
||||
}
|
||||
|
||||
func TestAmneziaWGRejectsInvalidConfigurationBeforeSending(t *testing.T) {
|
||||
client := &AmneziaWGClient{version: 1, linkByName: awgKernelLink,
|
||||
exchange: func(uint8, uint16, []*nl.RtAttr) ([][]byte, error) {
|
||||
t.Fatal("invalid input sent to kernel")
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
for _, options := range []domain.AmneziaWGOptions{{"H1": "100-200"}, {"I1": "<b 0x12>"}, {"RekeyTimeout": "5"}, {"Jc": "65536"}, {"I1": "bad\n[Peer]"}} {
|
||||
require.Error(t, client.ConfigureAmneziaWGDevice("awg0", wgtypes.Config{}, options))
|
||||
}
|
||||
badPort := 65536
|
||||
require.Error(t, client.ConfigureDevice("awg0", wgtypes.Config{ListenPort: &badPort}))
|
||||
require.Error(t, client.ConfigureDevice("awg0", wgtypes.Config{Peers: []wgtypes.PeerConfig{{Endpoint: &net.UDPAddr{IP: nil, Port: 1}}}}))
|
||||
}
|
||||
|
||||
func TestAmneziaWGNativeOptionEncodings(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
version uint8
|
||||
value string
|
||||
wire []byte
|
||||
}{
|
||||
{1, "305419896", binary.NativeEndian.AppendUint32(nil, 0x12345678)},
|
||||
{2, "100-200", []byte("100-200\x00")},
|
||||
{3, "100-200", binary.NativeEndian.AppendUint64(nil, 200<<32|100)},
|
||||
} {
|
||||
attrs, err := encodeAmneziaWGOptions(domain.AmneziaWGOptions{"H1": test.value}, test.version)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, test.wire, awgTestAttrMap(t, awgTestSerialize(attrs))[14])
|
||||
}
|
||||
options := domain.AmneziaWGOptions{"Jc": "4", "S3": "16", "I1": "<b 0x1234>", "ContentPaddingAddition": "10-20", "RekeyTimeout": "5", "RandomTrailers": "on", "DisableCookies": "off", "HeaderProtectionKey": awgTestPrivateKey}
|
||||
attrs, err := encodeAmneziaWGOptions(options, 3)
|
||||
require.NoError(t, err)
|
||||
_, parsed, err := parseAmneziaWGDevice([][]byte{awgTestReply(3, attrs...)}, 3)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, options, parsed)
|
||||
encoded := awgTestAttrMap(t, awgTestSerialize(attrs))
|
||||
require.Equal(t, uint32(20<<16|10), binary.NativeEndian.Uint32(encoded[27]))
|
||||
require.Equal(t, uint32(5<<16|5), binary.NativeEndian.Uint32(encoded[29]))
|
||||
}
|
||||
|
||||
func TestAmneziaWGSockaddrsAndTimes(t *testing.T) {
|
||||
for _, endpoint := range []*net.UDPAddr{
|
||||
{IP: net.ParseIP("192.0.2.1"), Port: 51820},
|
||||
{IP: net.ParseIP("2001:db8::1"), Port: 1234},
|
||||
{IP: net.ParseIP("fe80::1"), Port: 1234, Zone: "3"},
|
||||
} {
|
||||
data, err := encodeAmneziaWGSockaddr(endpoint)
|
||||
require.NoError(t, err)
|
||||
parsed, err := parseAmneziaWGSockaddr(data)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, endpoint.String(), parsed.String())
|
||||
}
|
||||
zero, err := parseAmneziaWGTime(make([]byte, 16))
|
||||
require.NoError(t, err)
|
||||
require.True(t, zero.IsZero())
|
||||
parsed, err := parseAmneziaWGTime(append(binary.NativeEndian.AppendUint32(nil, 1700000000), binary.NativeEndian.AppendUint32(nil, 42)...))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, time.Unix(1700000000, 42), parsed)
|
||||
}
|
||||
|
||||
func TestAmneziaWGMalformedMessages(t *testing.T) {
|
||||
for _, data := range [][]byte{
|
||||
{}, {0, 1, 0}, {0, 1, 0, 0, 1}, {0, 1, 0, 0, 3, 0, 0, 0},
|
||||
awgTestReply(1, nl.NewRtAttr(unix.WGDEVICE_A_PRIVATE_KEY, []byte{1})),
|
||||
awgTestReply(3, nl.NewRtAttr(14, []byte{1})),
|
||||
} {
|
||||
_, _, err := parseAmneziaWGDevice([][]byte{data}, 3)
|
||||
require.Error(t, err)
|
||||
require.NotContains(t, err.Error(), awgTestPrivateKey)
|
||||
}
|
||||
_, err := parseAmneziaWGPeer(nil, 3)
|
||||
require.ErrorContains(t, err, "public key")
|
||||
_, err = parseAmneziaWGAllowedIPs(nl.NewRtAttr(unix.NLA_F_NESTED, nil).Serialize())
|
||||
require.Error(t, err)
|
||||
_, err = parseAmneziaWGTime([]byte{1})
|
||||
require.Error(t, err)
|
||||
_, err = parseAmneziaWGSockaddr([]byte{1})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func FuzzAmneziaWGDeviceDecoder(f *testing.F) {
|
||||
f.Add([]byte{0, 3, 0, 0})
|
||||
f.Add(awgTestReply(3, nl.NewRtAttr(unix.WGDEVICE_A_IFNAME, []byte("awg0\x00"))))
|
||||
f.Fuzz(func(t *testing.T, data []byte) { _, _, _ = parseAmneziaWGDevice([][]byte{data}, 3) })
|
||||
}
|
||||
Reference in New Issue
Block a user