This commit is contained in:
Christoph
2026-12-03 14:56:54 +01:00
parent 10507d54c3
commit d5a74a10ac
18 changed files with 344 additions and 436 deletions
+40 -136
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"maps"
"os"
"github.com/vishvananda/netlink"
@@ -14,18 +15,16 @@ import (
"github.com/h44z/wg-portal/internal/lowlevel"
)
type AmneziaWGRepo interface {
type amneziaWGRepo interface {
WgCtrlRepo
AmneziaWGOptions(string) (domain.AmneziaWGOptions, error)
ValidateOptions(domain.AmneziaWGOptions) error
ConfigureAmneziaWGDevice(string, wgtypes.Config, domain.AmneziaWGOptions) error
}
// AmneziaWGController manages AmneziaWG kernel interfaces and their obfuscation
// options. Its local helper uses the same AWG client for Linux routing, DNS,
// hooks, and peer lifecycle operations.
// AmneziaWGController shares peer management, hooks, DNS and routing with the local controller.
type AmneziaWGController struct {
awg AmneziaWGRepo
local LocalController
*LocalController
amneziaWGRepo
}
func NewAmneziaWGController(cfg *config.Config) (*AmneziaWGController, error) {
@@ -36,16 +35,10 @@ func NewAmneziaWGController(cfg *config.Config) (*AmneziaWGController, error) {
return newAmneziaWGController(cfg, awg, &lowlevel.NetlinkManager{}), nil
}
func newAmneziaWGController(cfg *config.Config, awg AmneziaWGRepo, nl NetlinkClient) *AmneziaWGController {
func newAmneziaWGController(cfg *config.Config, awg amneziaWGRepo, nl NetlinkClient) *AmneziaWGController {
return &AmneziaWGController{
awg: awg,
local: LocalController{
cfg: cfg,
wg: awg,
nl: nl,
shellCmd: "bash", // we only support bash at the moment
resolvConfIfacePrefix: cfg.Backend.LocalResolvconfPrefix, // WireGuard interfaces have a tun. prefix in resolvconf
},
LocalController: newLocalController(cfg, awg, nl, domain.ControllerTypeAmneziaWG),
amneziaWGRepo: awg,
}
}
@@ -53,59 +46,15 @@ func (c AmneziaWGController) GetId() domain.InterfaceBackend {
return config.AmneziaWGBackendName
}
func (c AmneziaWGController) GetInterfaces(_ context.Context) ([]domain.PhysicalInterface, error) {
devices, err := c.awg.Devices()
if err != nil {
return nil, fmt.Errorf("AmneziaWG device list error: %w", err)
}
interfaces := make([]domain.PhysicalInterface, 0, len(devices))
for _, device := range devices {
iface, err := c.convertInterface(device)
if err != nil {
return nil, err
}
interfaces = append(interfaces, iface)
}
return interfaces, nil
}
func (c AmneziaWGController) GetInterface(_ context.Context, id domain.InterfaceIdentifier) (*domain.PhysicalInterface, error) {
device, err := c.awg.Device(string(id))
if err != nil {
return nil, err
}
iface, err := c.convertInterface(device)
if err != nil {
return nil, err
}
return &iface, nil
}
func (c AmneziaWGController) convertInterface(device *wgtypes.Device) (domain.PhysicalInterface, error) {
iface, err := c.local.convertWireGuardInterface(device)
if err != nil {
return domain.PhysicalInterface{}, err
}
iface.ImportSource = domain.ControllerTypeAmneziaWG
options, err := c.awg.AmneziaWGOptions(device.Name)
if err != nil {
return domain.PhysicalInterface{}, fmt.Errorf("AmneziaWG options for %s: %w", device.Name, err)
}
iface.SetExtras(domain.AmneziaWGInterfaceExtras{Options: options})
return iface, nil
}
func (c AmneziaWGController) SaveInterface(ctx context.Context, id domain.InterfaceIdentifier,
updateFunc func(*domain.PhysicalInterface) (*domain.PhysicalInterface, error),
) error {
) (err error) {
iface, err := c.GetInterface(ctx, id)
if errors.Is(err, os.ErrNotExist) {
if err := c.local.nl.LinkAdd(&netlink.GenericLink{Name: string(id), LinkType: "amneziawg"}); err != nil {
return fmt.Errorf("AmneziaWG link add failed: %w", err)
}
iface, err = c.GetInterface(ctx, id)
}
if err != nil {
create := errors.Is(err, os.ErrNotExist)
if create {
iface = &domain.PhysicalInterface{Identifier: id, ImportSource: domain.ControllerTypeAmneziaWG,
DeviceType: wgtypes.LinuxKernel.String(), PrivateKey: (wgtypes.Key{}).String()}
} else if err != nil {
return err
}
if updateFunc != nil {
@@ -114,29 +63,41 @@ func (c AmneziaWGController) SaveInterface(ctx context.Context, id domain.Interf
return err
}
}
extras := iface.GetExtras().(domain.AmneziaWGInterfaceExtras)
if err := extras.Options.Validate(); err != nil {
extras, _ := iface.GetExtras().(domain.AmneziaWGInterfaceExtras)
if err := c.ValidateOptions(extras.Options); err != nil {
return err
}
privateKey, err := wgtypes.NewKey(iface.KeyPair.GetPrivateKeyBytes())
cfg, err := kernelInterfaceConfig(iface)
if err != nil {
return err
}
var fwMark *int
if iface.FirewallMark != 0 {
value := int(iface.FirewallMark)
fwMark = &value
if create {
link := &netlink.GenericLink{Name: string(id), LinkType: "amneziawg"}
if err := c.nl.LinkAdd(link); err != nil {
return fmt.Errorf("AmneziaWG link add failed: %w", err)
}
defer func() {
if err != nil && link.Index != 0 {
err = errors.Join(err, c.nl.LinkDel(link))
}
}()
}
if err := c.local.updateLowLevelInterface(iface); err != nil {
if err := c.ConfigureAmneziaWGDevice(string(id), cfg, extras.Options); err != nil {
return err
}
return c.awg.ConfigureAmneziaWGDevice(string(id), wgtypes.Config{
PrivateKey: &privateKey, ListenPort: &iface.ListenPort, FirewallMark: fwMark,
}, extras.Options)
if create && extras.Options != nil {
// New links can get kernel defaults that clients also need in their exports.
device, err := c.Device(string(id))
if err != nil {
return err
}
maps.Copy(extras.Options, device.AmneziaWG)
}
return c.updateLowLevelInterface(iface)
}
func (c AmneziaWGController) DeleteInterface(_ context.Context, id domain.InterfaceIdentifier) error {
link, err := c.local.nl.LinkByName(string(id))
link, err := c.nl.LinkByName(string(id))
if err != nil {
if _, ok := errors.AsType[netlink.LinkNotFoundError](err); ok {
return nil
@@ -146,62 +107,5 @@ func (c AmneziaWGController) DeleteInterface(_ context.Context, id domain.Interf
if link.Type() != "amneziawg" {
return fmt.Errorf("interface %s is not an AmneziaWG kernel device", id)
}
return c.local.nl.LinkDel(link)
}
func (c AmneziaWGController) GetPeers(ctx context.Context, id domain.InterfaceIdentifier) ([]domain.PhysicalPeer, error) {
peers, err := c.local.GetPeers(ctx, id)
if err != nil {
return nil, err
}
for i := range peers {
peers[i].ImportSource = domain.ControllerTypeAmneziaWG
}
return peers, nil
}
func (c AmneziaWGController) GetPeer(ctx context.Context, id domain.InterfaceIdentifier, peerID domain.PeerIdentifier) (*domain.PhysicalPeer, error) {
peer, err := c.local.getPeer(id, peerID)
if err != nil {
return nil, err
}
peer.ImportSource = domain.ControllerTypeAmneziaWG
return peer, nil
}
func (c AmneziaWGController) SavePeer(ctx context.Context, id domain.InterfaceIdentifier, peerID domain.PeerIdentifier,
updateFunc func(*domain.PhysicalPeer) (*domain.PhysicalPeer, error),
) error {
return c.local.SavePeer(ctx, id, peerID, func(peer *domain.PhysicalPeer) (*domain.PhysicalPeer, error) {
peer.ImportSource = domain.ControllerTypeAmneziaWG
return updateFunc(peer)
})
}
func (c AmneziaWGController) DeletePeer(ctx context.Context, id domain.InterfaceIdentifier, peerID domain.PeerIdentifier) error {
return c.local.DeletePeer(ctx, id, peerID)
}
func (c AmneziaWGController) ExecuteInterfaceHook(ctx context.Context, id domain.InterfaceIdentifier, command string) error {
return c.local.ExecuteInterfaceHook(ctx, id, command)
}
func (c AmneziaWGController) SetDNS(ctx context.Context, id domain.InterfaceIdentifier, dns, search string) error {
return c.local.SetDNS(ctx, id, dns, search)
}
func (c AmneziaWGController) UnsetDNS(ctx context.Context, id domain.InterfaceIdentifier, dns, search string) error {
return c.local.UnsetDNS(ctx, id, dns, search)
}
func (c AmneziaWGController) SetRoutes(ctx context.Context, info domain.RoutingTableInfo) error {
return c.local.SetRoutes(ctx, info)
}
func (c AmneziaWGController) RemoveRoutes(ctx context.Context, info domain.RoutingTableInfo) error {
return c.local.RemoveRoutes(ctx, info)
}
func (c AmneziaWGController) PingAddresses(ctx context.Context, addr string) (*domain.PingerResult, error) {
return c.local.PingAddresses(ctx, addr)
return c.nl.LinkDel(link)
}
@@ -2,6 +2,8 @@ package wgcontroller
import (
"context"
"errors"
"maps"
"os"
"testing"
"time"
@@ -12,15 +14,21 @@ import (
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain"
"github.com/h44z/wg-portal/internal/lowlevel"
)
type awgControllerNetlink struct {
NetlinkClient
link netlink.Link
deleted bool
upErr error
}
func (n *awgControllerNetlink) LinkAdd(link netlink.Link) error { n.link = link; return nil }
func (n *awgControllerNetlink) LinkAdd(link netlink.Link) error {
link.Attrs().Index = 1
n.link = link
return nil
}
func (n *awgControllerNetlink) LinkByName(string) (netlink.Link, error) {
if n.link == nil {
return nil, netlink.LinkNotFoundError{}
@@ -33,41 +41,40 @@ func (n *awgControllerNetlink) LinkDel(netlink.Link) error {
return nil
}
func (n *awgControllerNetlink) AddrList(netlink.Link) ([]netlink.Addr, error) { return nil, nil }
func (n *awgControllerNetlink) LinkSetUp(netlink.Link) error { return nil }
func (n *awgControllerNetlink) LinkSetUp(netlink.Link) error { return n.upErr }
func (n *awgControllerNetlink) LinkSetDown(netlink.Link) error { return nil }
type awgControllerClient struct {
WgCtrlRepo
nl *awgControllerNetlink
options domain.AmneziaWGOptions
configured domain.AmneziaWGOptions
deleted bool
peer *wgtypes.Peer
nl *awgControllerNetlink
options domain.AmneziaWGOptions
validationErr error
reads int
deleted bool
peer *wgtypes.Peer
}
func (w *awgControllerClient) Devices() ([]*wgtypes.Device, error) {
func (w *awgControllerClient) Devices() ([]lowlevel.WireGuardDevice, error) {
device, err := w.Device("awg0")
if err != nil {
return nil, err
}
return []*wgtypes.Device{device}, nil
return []lowlevel.WireGuardDevice{device}, nil
}
func (w *awgControllerClient) Device(name string) (*wgtypes.Device, error) {
func (w *awgControllerClient) Device(name string) (lowlevel.WireGuardDevice, error) {
w.reads++
if w.nl.link == nil {
return nil, os.ErrNotExist
return lowlevel.WireGuardDevice{}, os.ErrNotExist
}
device := &wgtypes.Device{Name: name, Type: wgtypes.LinuxKernel}
if w.peer != nil {
device.Peers = []wgtypes.Peer{*w.peer}
}
return device, nil
}
func (w *awgControllerClient) AmneziaWGOptions(string) (domain.AmneziaWGOptions, error) {
return w.options, nil
return lowlevel.WireGuardDevice{Device: device, AmneziaWG: maps.Clone(w.options)}, nil
}
func (w *awgControllerClient) ValidateOptions(domain.AmneziaWGOptions) error { return w.validationErr }
func (w *awgControllerClient) ConfigureAmneziaWGDevice(_ string, _ wgtypes.Config, options domain.AmneziaWGOptions) error {
w.configured = options
maps.Copy(w.options, options)
return nil
}
func (w *awgControllerClient) ConfigureDevice(_ string, cfg wgtypes.Config) error {
@@ -85,14 +92,27 @@ func TestAmneziaWGControllerCreatesCorrectLinkAndPreservesOptions(t *testing.T)
controller := newAmneziaWGController(&config.Config{}, wg, nl)
key, err := wgtypes.GeneratePrivateKey()
require.NoError(t, err)
require.NoError(t, controller.SaveInterface(context.Background(), "awg0", func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
require.Equal(t, domain.AmneziaWGInterfaceExtras{Options: wg.options}, pi.GetExtras())
domain.MergeToPhysicalInterface(pi, &domain.Interface{Backend: config.AmneziaWGBackendName, Identifier: "awg0", PrivateKey: key.String(), AmneziaWG: domain.AmneziaWGOptions{"Jc": "6"}})
return pi, nil
}))
update := &domain.Interface{Identifier: "awg0", PrivateKey: key.String(), AmneziaWG: domain.AmneziaWGOptions{"Jc": "6"}}
save := func() error {
return controller.SaveInterface(t.Context(), update.Identifier, func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
domain.MergeToPhysicalInterface(pi, update)
update.AmneziaWG = pi.GetExtras().(domain.AmneziaWGInterfaceExtras).Options
return pi, nil
})
}
wg.validationErr = errors.New("unsupported option")
require.ErrorIs(t, save(), wg.validationErr)
require.Nil(t, nl.link)
wg.validationErr = nil
nl.upErr = errors.New("link setup failed")
require.ErrorIs(t, save(), nl.upErr)
require.Nil(t, nl.link)
nl.upErr = nil
require.NoError(t, save())
require.Equal(t, "amneziawg", nl.link.Type())
require.Equal(t, domain.InterfaceBackend(config.AmneziaWGBackendName), controller.GetId())
require.Equal(t, domain.AmneziaWGOptions{"H1": "100-200", "Jc": "6"}, wg.configured)
require.Equal(t, domain.AmneziaWGOptions{"H1": "100-200", "Jc": "6"}, update.AmneziaWG)
wg.reads = 0
physical, err := controller.GetInterface(context.Background(), "awg0")
require.NoError(t, err)
require.Equal(t, domain.ControllerTypeAmneziaWG, physical.ImportSource)
@@ -102,6 +122,7 @@ func TestAmneziaWGControllerCreatesCorrectLinkAndPreservesOptions(t *testing.T)
require.NoError(t, err)
require.Len(t, interfaces, 1)
require.Equal(t, *physical, interfaces[0])
require.Equal(t, 2, wg.reads, "one device dump for GetInterface and one for GetInterfaces")
}
func TestAmneziaWGDisabledPeersUseLocalDeletion(t *testing.T) {
@@ -112,9 +133,6 @@ func TestAmneziaWGDisabledPeersUseLocalDeletion(t *testing.T) {
wg := &awgControllerClient{nl: nl, peer: &wgtypes.Peer{PublicKey: public}}
controller := newAmneziaWGController(&config.Config{}, wg, nl)
id := domain.PeerIdentifier(public.String())
physical, err := controller.GetPeer(context.Background(), "awg0", id)
require.NoError(t, err)
require.Equal(t, domain.ControllerTypeAmneziaWG, physical.ImportSource)
peers, err := controller.GetPeers(context.Background(), "awg0")
require.NoError(t, err)
require.Len(t, peers, 1)
+45 -19
View File
@@ -5,7 +5,6 @@ import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/exec"
@@ -29,12 +28,30 @@ import (
// WgCtrlRepo is used to control local WireGuard devices via the wgctrl-go library.
type WgCtrlRepo interface {
io.Closer
Devices() ([]*wgtypes.Device, error)
Device(name string) (*wgtypes.Device, error)
Devices() ([]lowlevel.WireGuardDevice, error)
Device(name string) (lowlevel.WireGuardDevice, error)
ConfigureDevice(name string, cfg wgtypes.Config) error
}
type wireGuardClient struct{ *wgctrl.Client }
func (c wireGuardClient) Device(name string) (lowlevel.WireGuardDevice, error) {
device, err := c.Client.Device(name)
return lowlevel.WireGuardDevice{Device: device}, err
}
func (c wireGuardClient) Devices() ([]lowlevel.WireGuardDevice, error) {
devices, err := c.Client.Devices()
if err != nil {
return nil, err
}
result := make([]lowlevel.WireGuardDevice, len(devices))
for i, device := range devices {
result[i].Device = device
}
return result, nil
}
// A NetlinkClient is a type which can control a netlink device.
type NetlinkClient interface {
LinkAdd(link netlink.Link) error
@@ -65,6 +82,8 @@ type LocalController struct {
wg WgCtrlRepo
nl NetlinkClient
importSource string
shellCmd string
resolvConfIfacePrefix string
}
@@ -77,19 +96,20 @@ func NewLocalController(cfg *config.Config) (*LocalController, error) {
return nil, fmt.Errorf("failed to create wgctrl client: %w", err)
}
nl := &lowlevel.NetlinkManager{}
return newLocalController(cfg, wireGuardClient{wg}, &lowlevel.NetlinkManager{}, domain.ControllerTypeLocal), nil
}
repo := &LocalController{
func newLocalController(cfg *config.Config, wg WgCtrlRepo, nl NetlinkClient, source string) *LocalController {
return &LocalController{
cfg: cfg,
wg: wg,
nl: nl,
importSource: source,
shellCmd: "bash", // we only support bash at the moment
resolvConfIfacePrefix: cfg.Backend.LocalResolvconfPrefix, // WireGuard interfaces have a tun. prefix in resolvconf
}
return repo, nil
}
func (c LocalController) GetId() domain.InterfaceBackend {
@@ -123,7 +143,7 @@ func (c LocalController) GetInterface(_ context.Context, id domain.InterfaceIden
return c.getInterface(id)
}
func (c LocalController) convertWireGuardInterface(device *wgtypes.Device) (domain.PhysicalInterface, error) {
func (c LocalController) convertWireGuardInterface(device lowlevel.WireGuardDevice) (domain.PhysicalInterface, error) {
// read data from wgctrl interface
iface := domain.PhysicalInterface{
@@ -135,7 +155,7 @@ func (c LocalController) convertWireGuardInterface(device *wgtypes.Device) (doma
Mtu: 0,
FirewallMark: uint32(device.FirewallMark),
DeviceUp: false,
ImportSource: domain.ControllerTypeLocal,
ImportSource: c.importSource,
DeviceType: device.Type.String(),
BytesUpload: 0,
BytesDownload: 0,
@@ -162,6 +182,9 @@ func (c LocalController) convertWireGuardInterface(device *wgtypes.Device) (doma
iface.BytesDownload = stats.RxBytes
}
if c.importSource == domain.ControllerTypeAmneziaWG {
iface.SetExtras(domain.AmneziaWGInterfaceExtras{Options: device.AmneziaWG})
}
return iface, nil
}
@@ -198,7 +221,7 @@ func (c LocalController) convertWireGuardPeer(peer *wgtypes.Peer) (domain.Physic
ProtocolVersion: peer.ProtocolVersion,
BytesUpload: uint64(peer.ReceiveBytes),
BytesDownload: uint64(peer.TransmitBytes),
ImportSource: domain.ControllerTypeLocal,
ImportSource: c.importSource,
}
// Set local extras - local peers are never disabled in the kernel
@@ -338,10 +361,10 @@ func (c LocalController) updateLowLevelInterface(pi *domain.PhysicalInterface) e
return nil
}
func (c LocalController) updateWireGuardInterface(pi *domain.PhysicalInterface) error {
func kernelInterfaceConfig(pi *domain.PhysicalInterface) (wgtypes.Config, error) {
pKey, err := wgtypes.NewKey(pi.KeyPair.GetPrivateKeyBytes())
if err != nil {
return err
return wgtypes.Config{}, err
}
var fwMark *int
@@ -349,17 +372,19 @@ func (c LocalController) updateWireGuardInterface(pi *domain.PhysicalInterface)
intFwMark := int(pi.FirewallMark)
fwMark = &intFwMark
}
err = c.wg.ConfigureDevice(string(pi.Identifier), wgtypes.Config{
return wgtypes.Config{
PrivateKey: &pKey,
ListenPort: &pi.ListenPort,
FirewallMark: fwMark,
ReplacePeers: false,
})
}, nil
}
func (c LocalController) updateWireGuardInterface(pi *domain.PhysicalInterface) error {
cfg, err := kernelInterfaceConfig(pi)
if err != nil {
return err
}
return nil
return c.wg.ConfigureDevice(string(pi.Identifier), cfg)
}
func (c LocalController) DeleteInterface(_ context.Context, id domain.InterfaceIdentifier) error {
@@ -862,7 +887,8 @@ func (c LocalController) RemoveRoutes(_ context.Context, info domain.RoutingTabl
slog.Debug("removing linux routes", "interface", interfaceId, "table", info.Table, "fwMark", info.FwMark,
"cidrs", info.AllowedIps)
wgDev, err := c.wg.Device(string(interfaceId))
device, err := c.wg.Device(string(interfaceId))
wgDev := device.Device
if err != nil {
slog.Debug("wg device already removed, route cleanup might be incomplete", "interface", interfaceId)
wgDev = nil