mirror of
https://github.com/h44z/wg-portal.git
synced 2026-12-05 11:46:09 +01:00
cleanup
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -118,9 +118,6 @@ func (s InterfaceService) Update(ctx context.Context, id domain.InterfaceIdentif
|
||||
iface.IsDynamic = existingInterface.IsDynamic
|
||||
iface.DriverType = existingInterface.DriverType
|
||||
iface.LdapAllowedUsers = existingInterface.LdapAllowedUsers
|
||||
if iface.AmneziaWG == nil {
|
||||
iface.AmneziaWG = existingInterface.AmneziaWG
|
||||
}
|
||||
|
||||
updatedInterface, updatedPeers, err := s.interfaces.UpdateInterface(ctx, iface)
|
||||
if err != nil {
|
||||
|
||||
@@ -12,36 +12,6 @@ import (
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
func TestAmneziaWGConfigTemplates(t *testing.T) {
|
||||
tpl, err := newTemplateHandler()
|
||||
require.NoError(t, err)
|
||||
options := domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4", "I1": "<b 0x1234>"}
|
||||
iface := &domain.Interface{Identifier: "awg0", Backend: config.AmneziaWGBackendName, AmneziaWG: options, PrivateKey: "private"}
|
||||
reader, err := tpl.GetInterfaceConfig(iface, nil)
|
||||
require.NoError(t, err)
|
||||
contents, err := io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(contents), "PrivateKey = private\nH1 = 100-200\nI1 = <b 0x1234>\nJc = 4\n")
|
||||
require.Contains(t, string(contents), "\nAddress = ")
|
||||
peer := &domain.Peer{AmneziaWG: options}
|
||||
peer.Interface.PrivateKey = "private"
|
||||
for _, style := range []string{domain.ConfigStyleWgQuick, domain.ConfigStyleRaw} {
|
||||
reader, err := tpl.GetPeerConfig(peer, style)
|
||||
require.NoError(t, err)
|
||||
contents, err := io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(contents), "PrivateKey = private\nH1 = 100-200\nI1 = <b 0x1234>\nJc = 4\n")
|
||||
require.True(t, strings.Index(string(contents), "H1 =") < strings.Index(string(contents), "[Peer]"))
|
||||
}
|
||||
peer.AmneziaWG = nil
|
||||
reader, err = tpl.GetPeerConfig(peer, domain.ConfigStyleWgQuick)
|
||||
require.NoError(t, err)
|
||||
contents, err = io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(contents), "H1 =")
|
||||
require.Contains(t, string(contents), "PrivateKey = private\nAddress =")
|
||||
}
|
||||
|
||||
type amneziaConfigRepo struct {
|
||||
iface domain.Interface
|
||||
peer domain.Peer
|
||||
@@ -58,30 +28,40 @@ func (r *amneziaConfigRepo) GetInterfaceAndPeers(context.Context, domain.Interfa
|
||||
return &r.iface, []domain.Peer{r.peer}, nil
|
||||
}
|
||||
|
||||
func TestAmneziaWGDownloadsAndQRUseParentOptions(t *testing.T) {
|
||||
func TestAmneziaWGConfigExports(t *testing.T) {
|
||||
tpl, err := newTemplateHandler()
|
||||
require.NoError(t, err)
|
||||
repo := &amneziaConfigRepo{
|
||||
iface: domain.Interface{Identifier: "awg0", Backend: config.AmneziaWGBackendName, AmneziaWG: domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"}},
|
||||
peer: domain.Peer{Identifier: "peer", InterfaceIdentifier: "awg0"},
|
||||
iface: domain.Interface{Identifier: "awg0", Backend: config.AmneziaWGBackendName, PrivateKey: "private",
|
||||
AmneziaWG: domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4", "I1": "<b 0x1234>"}},
|
||||
peer: domain.Peer{Identifier: "peer", InterfaceIdentifier: "awg0", Interface: domain.PeerInterfaceConfig{PrivateKey: "private"}},
|
||||
}
|
||||
manager := Manager{wg: repo, tplHandler: tpl}
|
||||
ctx := domain.SetUserInfo(context.Background(), domain.SystemAdminContextUserInfo())
|
||||
reader, err := manager.GetPeerConfig(ctx, "peer", domain.ConfigStyleWgQuick)
|
||||
require.NoError(t, err)
|
||||
contents, err := io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(contents), "H1 = 100-200")
|
||||
reader, err = manager.GetPeerConfigQrCode(ctx, "peer", domain.ConfigStyleWgQuick)
|
||||
require.NoError(t, err)
|
||||
contents, err = io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, contents)
|
||||
// Changing parent options affects the next download without editing peers.
|
||||
ctx := domain.SetUserInfo(t.Context(), domain.SystemAdminContextUserInfo())
|
||||
read := func(reader io.Reader, err error) string {
|
||||
t.Helper()
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
return string(data)
|
||||
}
|
||||
const options = "PrivateKey = private\nH1 = 100-200\nI1 = <b 0x1234>\nJc = 4\n"
|
||||
server := read(manager.GetInterfaceConfig(ctx, "awg0"))
|
||||
require.Contains(t, server, options)
|
||||
require.Contains(t, server, "\nAddress = ")
|
||||
for _, style := range []string{domain.ConfigStyleWgQuick, domain.ConfigStyleRaw} {
|
||||
client := read(manager.GetPeerConfig(ctx, "peer", style))
|
||||
beforePeers, _, found := strings.Cut(client, "[Peer]")
|
||||
require.True(t, found)
|
||||
require.Contains(t, beforePeers, options)
|
||||
}
|
||||
firstQR := read(manager.GetPeerConfigQrCode(ctx, "peer", domain.ConfigStyleWgQuick))
|
||||
require.NotEmpty(t, firstQR)
|
||||
repo.iface.AmneziaWG["H1"] = "300-400"
|
||||
reader, err = manager.GetPeerConfig(ctx, "peer", domain.ConfigStyleWgQuick)
|
||||
require.NoError(t, err)
|
||||
contents, err = io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(contents), "H1 = 300-400")
|
||||
require.Contains(t, read(manager.GetPeerConfig(ctx, "peer", domain.ConfigStyleWgQuick)), "H1 = 300-400")
|
||||
require.NotEqual(t, firstQR, read(manager.GetPeerConfigQrCode(ctx, "peer", domain.ConfigStyleWgQuick)))
|
||||
repo.iface.AmneziaWG = nil
|
||||
client := read(manager.GetPeerConfig(ctx, "peer", domain.ConfigStyleWgQuick))
|
||||
require.Contains(t, client, "PrivateKey = private\nAddress =")
|
||||
require.NotContains(t, client, "H1 =")
|
||||
}
|
||||
|
||||
@@ -195,8 +195,12 @@ func (m Manager) GetPeerConfig(ctx context.Context, id domain.PeerIdentifier, st
|
||||
if err := domain.ValidateUserAccessRights(ctx, peer.UserIdentifier); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := m.loadAmneziaWGOptions(ctx, peer); err != nil {
|
||||
return nil, err
|
||||
iface, err := m.wg.GetInterface(ctx, peer.InterfaceIdentifier)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load parent interface: %w", err)
|
||||
}
|
||||
if iface.Backend == config.AmneziaWGBackendName {
|
||||
peer.Interface.AmneziaWG = iface.AmneziaWG
|
||||
}
|
||||
|
||||
return m.tplHandler.GetPeerConfig(peer, style)
|
||||
@@ -204,19 +208,7 @@ func (m Manager) GetPeerConfig(ctx context.Context, id domain.PeerIdentifier, st
|
||||
|
||||
// GetPeerConfigQrCode returns a QR code image containing the configuration for the given peer.
|
||||
func (m Manager) GetPeerConfigQrCode(ctx context.Context, id domain.PeerIdentifier, style string) (io.Reader, error) {
|
||||
peer, err := m.wg.GetPeer(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch peer %s: %w", id, err)
|
||||
}
|
||||
|
||||
if err := domain.ValidateUserAccessRights(ctx, peer.UserIdentifier); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := m.loadAmneziaWGOptions(ctx, peer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfgData, err := m.tplHandler.GetPeerConfig(peer, style)
|
||||
cfgData, err := m.GetPeerConfig(ctx, id, style)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get peer config for %s: %w", id, err)
|
||||
}
|
||||
@@ -256,17 +248,6 @@ func (m Manager) GetPeerConfigQrCode(ctx context.Context, id domain.PeerIdentifi
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func (m Manager) loadAmneziaWGOptions(ctx context.Context, peer *domain.Peer) error {
|
||||
iface, err := m.wg.GetInterface(ctx, peer.InterfaceIdentifier)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load parent interface: %w", err)
|
||||
}
|
||||
if iface.Backend == config.AmneziaWGBackendName {
|
||||
peer.Interface.AmneziaWG = iface.AmneziaWG
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PersistInterfaceConfig writes the configuration file for the given interface to the file system.
|
||||
func (m Manager) PersistInterfaceConfig(ctx context.Context, id domain.InterfaceIdentifier) error {
|
||||
iface, peers, err := m.wg.GetInterfaceAndPeers(ctx, id)
|
||||
|
||||
@@ -40,8 +40,20 @@ func (c *ControllerManager) init() error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := c.registerAmneziaWGController(); err != nil {
|
||||
return err
|
||||
if awg := c.cfg.Backend.AmneziaWG; awg.Enabled {
|
||||
controller, err := wgcontroller.NewAmneziaWGController(c.cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create AmneziaWG controller: %w", err)
|
||||
}
|
||||
c.controllers[config.AmneziaWGBackendName] = backendInstance{
|
||||
Config: config.BackendBase{
|
||||
Id: config.AmneziaWGBackendName,
|
||||
DisplayName: "AmneziaWG",
|
||||
Type: config.AmneziaWGBackendName,
|
||||
IgnoredInterfaces: awg.IgnoredInterfaces,
|
||||
},
|
||||
Implementation: controller,
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.registerMikrotikControllers(); err != nil {
|
||||
@@ -140,26 +152,6 @@ func (c *ControllerManager) registerOpnsenseControllers() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ControllerManager) registerAmneziaWGController() error {
|
||||
if !c.cfg.Backend.AmneziaWG.Enabled {
|
||||
return nil
|
||||
}
|
||||
controller, err := wgcontroller.NewAmneziaWGController(c.cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create AmneziaWG controller: %w", err)
|
||||
}
|
||||
c.controllers[config.AmneziaWGBackendName] = backendInstance{
|
||||
Config: config.BackendBase{
|
||||
Id: config.AmneziaWGBackendName,
|
||||
DisplayName: "AmneziaWG",
|
||||
Type: "amneziawg",
|
||||
IgnoredInterfaces: c.cfg.Backend.AmneziaWG.IgnoredInterfaces,
|
||||
},
|
||||
Implementation: controller,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ControllerManager) logRegisteredControllers() {
|
||||
for backend, controller := range c.controllers {
|
||||
slog.Debug("backend controller registered",
|
||||
@@ -186,7 +178,8 @@ func (c *ControllerManager) getController(
|
||||
}
|
||||
|
||||
controller, exists := c.controllers[backend]
|
||||
if !exists {
|
||||
// A disabled AmneziaWG backend must never dispatch to ordinary WireGuard.
|
||||
if !exists && backend != config.AmneziaWGBackendName {
|
||||
controller, exists = c.controllers[config.LocalBackendName] // Fallback to local controller
|
||||
if !exists {
|
||||
// If the local controller is also not found, panic
|
||||
|
||||
@@ -116,7 +116,11 @@ func (c *StatisticsCollector) collectInterfaceData(ctx context.Context) {
|
||||
}
|
||||
|
||||
for _, in := range interfaces {
|
||||
physicalInterface, err := c.wg.GetController(in).GetInterface(ctx, in.Identifier)
|
||||
controller := c.wg.GetController(in)
|
||||
if controller == nil {
|
||||
continue
|
||||
}
|
||||
physicalInterface, err := controller.GetInterface(ctx, in.Identifier)
|
||||
if err != nil {
|
||||
slog.Warn("failed to load physical interface for data collection", "interface", in.Identifier,
|
||||
"error", err)
|
||||
@@ -181,7 +185,11 @@ func (c *StatisticsCollector) collectPeerData(ctx context.Context) {
|
||||
}
|
||||
|
||||
for _, in := range interfaces {
|
||||
peers, err := c.wg.GetController(in).GetPeers(ctx, in.Identifier)
|
||||
controller := c.wg.GetController(in)
|
||||
if controller == nil {
|
||||
continue
|
||||
}
|
||||
peers, err := controller.GetPeers(ctx, in.Identifier)
|
||||
if err != nil {
|
||||
slog.Warn("failed to fetch peers for data collection", "interface", in.Identifier, "error", err)
|
||||
continue
|
||||
@@ -331,6 +339,10 @@ func (c *StatisticsCollector) enqueuePingChecks(ctx context.Context) {
|
||||
}
|
||||
|
||||
for _, in := range interfaces {
|
||||
controller := c.wg.GetController(in)
|
||||
if controller == nil {
|
||||
continue
|
||||
}
|
||||
peers, err := c.db.GetInterfacePeers(ctx, in.Identifier)
|
||||
if err != nil {
|
||||
slog.Warn("failed to fetch peers for ping checks", "interface", in.Identifier, "error", err)
|
||||
@@ -411,7 +423,11 @@ func (c *StatisticsCollector) isPeerPingable(
|
||||
return false
|
||||
}
|
||||
|
||||
stats, err := c.wg.GetControllerByName(backend).PingAddresses(ctx, checkAddr)
|
||||
controller := c.wg.GetControllerByName(backend)
|
||||
if controller == nil {
|
||||
return false
|
||||
}
|
||||
stats, err := controller.PingAddresses(ctx, checkAddr)
|
||||
if err != nil {
|
||||
slog.Debug("failed to ping peer", "peer", peer.Identifier, "error", err)
|
||||
return false
|
||||
|
||||
@@ -219,13 +219,16 @@ func (m Manager) RestoreInterfaceState(
|
||||
continue // ignore filtered interface
|
||||
}
|
||||
|
||||
controller := m.wg.GetController(iface)
|
||||
if controller == nil {
|
||||
slog.Warn("skipping restore for disabled backend", "interface", iface.Identifier, "backend", iface.Backend)
|
||||
continue
|
||||
}
|
||||
peers, err := m.db.GetInterfacePeers(ctx, iface.Identifier)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load peers for %s: %w", iface.Identifier, err)
|
||||
}
|
||||
|
||||
controller := m.wg.GetController(iface)
|
||||
|
||||
_, err = controller.GetInterface(ctx, iface.Identifier)
|
||||
if err != nil && !iface.IsDisabled() {
|
||||
slog.Debug("creating missing interface", "interface", iface.Identifier, "backend", controller.GetId())
|
||||
@@ -485,6 +488,11 @@ func (m Manager) DeleteInterface(ctx context.Context, id domain.InterfaceIdentif
|
||||
return fmt.Errorf("deletion not allowed: %w", err)
|
||||
}
|
||||
|
||||
controller := m.wg.GetController(*existingInterface)
|
||||
if controller == nil {
|
||||
return fmt.Errorf("backend %s is disabled", existingInterface.Backend)
|
||||
}
|
||||
|
||||
m.bus.Publish(app.TopicRouteRemove, domain.RoutingTableInfo{
|
||||
Interface: *existingInterface,
|
||||
AllowedIps: existingInterface.GetAllowedIPs(existingPeers),
|
||||
@@ -507,11 +515,11 @@ func (m Manager) DeleteInterface(ctx context.Context, id domain.InterfaceIdentif
|
||||
return fmt.Errorf("pre-delete actions failed: %w", err)
|
||||
}
|
||||
|
||||
if err := m.deleteInterfacePeers(ctx, existingInterface, existingPeers); err != nil {
|
||||
if err := m.deleteInterfacePeers(ctx, controller, existingInterface, existingPeers); err != nil {
|
||||
return fmt.Errorf("peer deletion failure: %w", err)
|
||||
}
|
||||
|
||||
if err := m.wg.GetController(*existingInterface).DeleteInterface(ctx, id); err != nil {
|
||||
if err := controller.DeleteInterface(ctx, id); err != nil {
|
||||
return fmt.Errorf("wireguard deletion failure: %w", err)
|
||||
}
|
||||
|
||||
@@ -543,6 +551,18 @@ func (m Manager) saveInterface(ctx context.Context, iface *domain.Interface) (
|
||||
return nil, fmt.Errorf("interface validation failed: %w", err)
|
||||
}
|
||||
|
||||
controller := m.wg.GetController(*iface)
|
||||
if controller == nil {
|
||||
return nil, fmt.Errorf("backend %s is disabled", iface.Backend)
|
||||
}
|
||||
if awg, ok := controller.(interface {
|
||||
ValidateOptions(domain.AmneziaWGOptions) error
|
||||
}); ok {
|
||||
if err := awg.ValidateOptions(iface.AmneziaWG); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
oldEnabled, newEnabled, routeTableChanged := false, !iface.IsDisabled(), false // if the interface did not exist, we assume it was not enabled
|
||||
oldInterface, err := m.db.GetInterface(ctx, iface.Identifier)
|
||||
if err == nil {
|
||||
@@ -560,8 +580,12 @@ func (m Manager) saveInterface(ctx context.Context, iface *domain.Interface) (
|
||||
err = m.db.SaveInterface(ctx, iface.Identifier, func(i *domain.Interface) (*domain.Interface, error) {
|
||||
iface.CopyCalculatedAttributes(i)
|
||||
|
||||
err := m.wg.GetController(*iface).SaveInterface(ctx, iface.Identifier,
|
||||
err := controller.SaveInterface(ctx, iface.Identifier,
|
||||
func(pi *domain.PhysicalInterface) (*domain.PhysicalInterface, error) {
|
||||
// Only a recreated link needs saved defaults. Existing links supply their current options.
|
||||
if pi.ImportSource == domain.ControllerTypeAmneziaWG && pi.GetExtras() == nil {
|
||||
pi.SetExtras(domain.AmneziaWGInterfaceExtras{Options: i.AmneziaWG})
|
||||
}
|
||||
domain.MergeToPhysicalInterface(pi, iface)
|
||||
if extras, ok := pi.GetExtras().(domain.AmneziaWGInterfaceExtras); ok {
|
||||
iface.AmneziaWG = extras.Options
|
||||
@@ -642,7 +666,7 @@ func (m Manager) saveInterface(ctx context.Context, iface *domain.Interface) (
|
||||
return nil, fmt.Errorf("failed to load peers for interface %s: %w", iface.Identifier, err)
|
||||
}
|
||||
for _, peer := range peers {
|
||||
saveErr := m.wg.GetController(*iface).SavePeer(ctx, iface.Identifier, peer.Identifier,
|
||||
saveErr := controller.SavePeer(ctx, iface.Identifier, peer.Identifier,
|
||||
func(pp *domain.PhysicalPeer) (*domain.PhysicalPeer, error) {
|
||||
domain.MergeToPhysicalPeer(pp, &peer)
|
||||
return pp, nil
|
||||
@@ -1070,9 +1094,9 @@ func (m Manager) importPeer(ctx context.Context, in *domain.Interface, p *domain
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m Manager) deleteInterfacePeers(ctx context.Context, iface *domain.Interface, allPeers []domain.Peer) error {
|
||||
func (m Manager) deleteInterfacePeers(ctx context.Context, controller domain.InterfaceController, iface *domain.Interface, allPeers []domain.Peer) error {
|
||||
for _, peer := range allPeers {
|
||||
err := m.wg.GetController(*iface).DeletePeer(ctx, iface.Identifier, peer.Identifier)
|
||||
err := controller.DeletePeer(ctx, iface.Identifier, peer.Identifier)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("wireguard peer deletion failure for %s: %w", peer.Identifier, err)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/app/api/v1/backend"
|
||||
"github.com/h44z/wg-portal/internal/config"
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
@@ -18,28 +19,30 @@ type amneziaWGExtrasController struct {
|
||||
func (c *amneziaWGExtrasController) SaveInterface(_ context.Context, _ domain.InterfaceIdentifier,
|
||||
update func(*domain.PhysicalInterface) (*domain.PhysicalInterface, error),
|
||||
) error {
|
||||
physical, err := update(&c.physical)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.physical = *physical
|
||||
return nil
|
||||
_, err := update(&c.physical)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestSaveInterfacePersistsAmneziaWGExtras(t *testing.T) {
|
||||
for name, options := range map[string]domain.AmneziaWGOptions{
|
||||
"omitted options": nil,
|
||||
"partial update": {"Jc": "6"},
|
||||
live := domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"}
|
||||
stored := domain.AmneziaWGOptions{"H1": "99", "Jc": "1"}
|
||||
patch := domain.AmneziaWGOptions{"Jc": "6"}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
kernel, update, want domain.AmneziaWGOptions
|
||||
}{
|
||||
{"omitted options", live, nil, live},
|
||||
{"partial update", live, patch, domain.AmneziaWGOptions{"H1": "100-200", "Jc": "6"}},
|
||||
{"recreated link", nil, patch, domain.AmneziaWGOptions{"H1": "99", "Jc": "6"}},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
controller := &amneziaWGExtrasController{physical: domain.PhysicalInterface{
|
||||
Identifier: "awg0", ImportSource: domain.ControllerTypeAmneziaWG,
|
||||
}}
|
||||
controller.physical.SetExtras(domain.AmneziaWGInterfaceExtras{
|
||||
Options: domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"},
|
||||
})
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
controller := &amneziaWGExtrasController{physical: domain.PhysicalInterface{ImportSource: domain.ControllerTypeAmneziaWG}}
|
||||
if tc.kernel != nil {
|
||||
controller.physical.SetExtras(domain.AmneziaWGInterfaceExtras{Options: tc.kernel})
|
||||
}
|
||||
db := &mockDB{iface: &domain.Interface{
|
||||
Identifier: "awg0", Backend: config.AmneziaWGBackendName, Type: domain.InterfaceTypeServer,
|
||||
AmneziaWG: stored,
|
||||
}}
|
||||
manager := Manager{
|
||||
cfg: &config.Config{}, db: db, bus: &mockBus{},
|
||||
@@ -48,17 +51,25 @@ func TestSaveInterfacePersistsAmneziaWGExtras(t *testing.T) {
|
||||
}},
|
||||
}
|
||||
update := *db.iface
|
||||
update.AmneziaWG = options
|
||||
ctx := domain.SetUserInfo(context.Background(), domain.SystemAdminContextUserInfo())
|
||||
saved, err := manager.saveInterface(ctx, &update)
|
||||
update.AmneziaWG = tc.update
|
||||
ctx := domain.SetUserInfo(t.Context(), domain.SystemAdminContextUserInfo())
|
||||
manager.cfg.Backend.AmneziaWG.Enabled = true
|
||||
saved, _, err := backend.NewInterfaceService(manager.cfg, &manager).Update(ctx, update.Identifier, &update)
|
||||
require.NoError(t, err)
|
||||
expected := domain.AmneziaWGOptions{"H1": "100-200", "Jc": "4"}
|
||||
if options != nil {
|
||||
expected["Jc"] = "6"
|
||||
}
|
||||
require.Equal(t, expected, saved.AmneziaWG)
|
||||
require.Equal(t, expected, db.iface.AmneziaWG)
|
||||
require.Equal(t, domain.AmneziaWGInterfaceExtras{Options: expected}, controller.physical.GetExtras())
|
||||
require.Equal(t, tc.want, saved.AmneziaWG)
|
||||
require.Equal(t, tc.want, db.iface.AmneziaWG)
|
||||
require.Equal(t, domain.AmneziaWGInterfaceExtras{Options: tc.want}, controller.physical.GetExtras())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreSkipsDisabledAmneziaWG(t *testing.T) {
|
||||
iface := &domain.Interface{Identifier: "awg0", Backend: config.AmneziaWGBackendName}
|
||||
db := &mockDB{iface: iface}
|
||||
manager := Manager{db: db, wg: newBareControllerManager(&config.Config{})}
|
||||
manager.wg.controllers[config.LocalBackendName] = backendInstance{Implementation: &mockController{}}
|
||||
ctx := domain.SetUserInfo(t.Context(), domain.SystemAdminContextUserInfo())
|
||||
require.NoError(t, manager.RestoreInterfaceState(ctx, true))
|
||||
require.Nil(t, manager.wg.GetController(*iface))
|
||||
require.Nil(t, db.iface.Disabled)
|
||||
}
|
||||
|
||||
@@ -433,7 +433,11 @@ func (m Manager) DeletePeer(ctx context.Context, id domain.PeerIdentifier) error
|
||||
return fmt.Errorf("unable to find interface %s: %w", peer.InterfaceIdentifier, err)
|
||||
}
|
||||
|
||||
err = m.wg.GetController(*iface).DeletePeer(ctx, peer.InterfaceIdentifier, id)
|
||||
controller := m.wg.GetController(*iface)
|
||||
if controller == nil {
|
||||
return fmt.Errorf("backend %s is disabled", iface.Backend)
|
||||
}
|
||||
err = controller.DeletePeer(ctx, peer.InterfaceIdentifier, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("wireguard failed to delete peer %s: %w", id, err)
|
||||
}
|
||||
@@ -517,13 +521,17 @@ func (m Manager) savePeers(ctx context.Context, peers ...*domain.Peer) error {
|
||||
}
|
||||
|
||||
iface := interfaces[peer.InterfaceIdentifier]
|
||||
controller := m.wg.GetController(iface)
|
||||
if controller == nil {
|
||||
return fmt.Errorf("backend %s is disabled", iface.Backend)
|
||||
}
|
||||
|
||||
// Always save the peer to the backend, regardless of disabled/expired state
|
||||
// The backend will handle the disabled state appropriately
|
||||
err := m.db.SavePeer(ctx, peer.Identifier, func(p *domain.Peer) (*domain.Peer, error) {
|
||||
peer.CopyCalculatedAttributes(p)
|
||||
|
||||
err := m.wg.GetController(iface).SavePeer(ctx, peer.InterfaceIdentifier, peer.Identifier,
|
||||
err := controller.SavePeer(ctx, peer.InterfaceIdentifier, peer.Identifier,
|
||||
func(pp *domain.PhysicalPeer) (*domain.PhysicalPeer, error) {
|
||||
domain.MergeToPhysicalPeer(pp, peer)
|
||||
return pp, nil
|
||||
|
||||
@@ -16,9 +16,6 @@ type AmneziaWGOptions map[string]string
|
||||
|
||||
// Validate checks the custom parameters against the official limits.
|
||||
func (o AmneziaWGOptions) Validate() error {
|
||||
if len(o) == 0 {
|
||||
return nil
|
||||
}
|
||||
for key, value := range o {
|
||||
if strings.ContainsAny(value, "\r\n\x00#") || len(value) > 4096 {
|
||||
return fmt.Errorf("invalid AmneziaWG option %s: %w", key, ErrInvalidData)
|
||||
@@ -28,9 +25,9 @@ func (o AmneziaWGOptions) Validate() error {
|
||||
case "Jc", "Jmin", "Jmax", "S1", "S2", "S3", "S4":
|
||||
_, err = strconv.ParseUint(value, 10, 16)
|
||||
case "H1", "H2", "H3", "H4":
|
||||
err = validateAmneziaWGRange(value, 32)
|
||||
_, _, err = ParseAmneziaWGRange(value, 32)
|
||||
case "ContentPaddingAddition", "RekeyAfterTime", "RekeyTimeout", "RejectAfterTime", "KeepaliveTimeout", "MaxHandshakeAttempts":
|
||||
err = validateAmneziaWGRange(value, 16)
|
||||
_, _, err = ParseAmneziaWGRange(value, 16)
|
||||
case "I1", "I2", "I3", "I4", "I5":
|
||||
// The kernel validates the CPS description; it must stay on one line.
|
||||
if value == "" {
|
||||
@@ -49,34 +46,28 @@ func (o AmneziaWGOptions) Validate() error {
|
||||
return fmt.Errorf("invalid AmneziaWG option %s: %w", key, ErrInvalidData)
|
||||
}
|
||||
}
|
||||
if min, ok := o["Jmin"]; ok {
|
||||
if max, ok := o["Jmax"]; ok {
|
||||
lo, _ := strconv.ParseUint(min, 10, 16)
|
||||
hi, _ := strconv.ParseUint(max, 10, 16)
|
||||
if lo > hi {
|
||||
return fmt.Errorf("AmneziaWG Jmin exceeds Jmax: %w", ErrInvalidData)
|
||||
}
|
||||
if min, max := o["Jmin"], o["Jmax"]; min != "" && max != "" {
|
||||
lo, _ := strconv.ParseUint(min, 10, 16)
|
||||
hi, _ := strconv.ParseUint(max, 10, 16)
|
||||
if lo > hi {
|
||||
return fmt.Errorf("AmneziaWG Jmin exceeds Jmax: %w", ErrInvalidData)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAmneziaWGRange(value string, bits int) error {
|
||||
parts := strings.Split(value, "-")
|
||||
if len(parts) > 2 {
|
||||
return fmt.Errorf("invalid range")
|
||||
// ParseAmneziaWGRange parses a single unsigned value or an inclusive low-high range.
|
||||
func ParseAmneziaWGRange(value string, bits int) (uint64, uint64, error) {
|
||||
low, high, hasRange := strings.Cut(value, "-")
|
||||
lo, err := strconv.ParseUint(low, 10, bits)
|
||||
if err != nil || !hasRange {
|
||||
return lo, lo, err
|
||||
}
|
||||
lo, err := strconv.ParseUint(parts[0], 10, bits)
|
||||
if err != nil {
|
||||
return err
|
||||
hi, err := strconv.ParseUint(high, 10, bits)
|
||||
if err != nil || lo > hi {
|
||||
return 0, 0, fmt.Errorf("invalid range")
|
||||
}
|
||||
if len(parts) == 2 {
|
||||
hi, err := strconv.ParseUint(parts[1], 10, bits)
|
||||
if err != nil || lo > hi {
|
||||
return fmt.Errorf("invalid range")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return lo, hi, nil
|
||||
}
|
||||
|
||||
// ConfigLines is deterministic so saved files and QR codes use the same options.
|
||||
|
||||
@@ -422,12 +422,11 @@ func MergeToPhysicalInterface(pi *PhysicalInterface, i *Interface) {
|
||||
}
|
||||
pi.SetExtras(extras)
|
||||
case ControllerTypeAmneziaWG:
|
||||
extras := AmneziaWGInterfaceExtras{Options: AmneziaWGOptions{}}
|
||||
if existing, ok := pi.GetExtras().(AmneziaWGInterfaceExtras); ok && existing.Options != nil {
|
||||
extras.Options = maps.Clone(existing.Options)
|
||||
}
|
||||
maps.Copy(extras.Options, i.AmneziaWG)
|
||||
pi.SetExtras(extras)
|
||||
existing, _ := pi.GetExtras().(AmneziaWGInterfaceExtras)
|
||||
options := make(AmneziaWGOptions, len(existing.Options))
|
||||
maps.Copy(options, existing.Options)
|
||||
maps.Copy(options, i.AmneziaWG)
|
||||
pi.SetExtras(AmneziaWGInterfaceExtras{Options: options})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,9 +51,6 @@ func amneziaWGFamily(lookup func(string) (*netlink.GenlFamily, error)) (*netlink
|
||||
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 {
|
||||
@@ -68,12 +65,12 @@ func (c *AmneziaWGClient) kernelLink(name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) Devices() ([]*wgtypes.Device, error) {
|
||||
func (c *AmneziaWGClient) Devices() ([]WireGuardDevice, error) {
|
||||
links, err := c.links()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var devices []*wgtypes.Device
|
||||
var devices []WireGuardDevice
|
||||
for _, link := range links {
|
||||
if link.Type() != "amneziawg" {
|
||||
continue
|
||||
@@ -90,38 +87,33 @@ func (c *AmneziaWGClient) Devices() ([]*wgtypes.Device, error) {
|
||||
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) {
|
||||
func (c *AmneziaWGClient) Device(name string) (WireGuardDevice, error) {
|
||||
if err := c.kernelLink(name); err != nil {
|
||||
return nil, nil, err
|
||||
return WireGuardDevice{}, 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
|
||||
return WireGuardDevice{}, os.ErrNotExist
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("AmneziaWG device read: %w", err)
|
||||
return WireGuardDevice{}, fmt.Errorf("AmneziaWG device read: %w", err)
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
return nil, nil, os.ErrNotExist
|
||||
return WireGuardDevice{}, os.ErrNotExist
|
||||
}
|
||||
device, options, err := parseAmneziaWGDevice(messages, c.version)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid AmneziaWG device response: %w", err)
|
||||
return WireGuardDevice{}, fmt.Errorf("invalid AmneziaWG device response: %w", err)
|
||||
}
|
||||
if device.Name != name {
|
||||
return nil, nil, fmt.Errorf("unexpected AmneziaWG interface in response")
|
||||
return WireGuardDevice{}, fmt.Errorf("unexpected AmneziaWG interface in response")
|
||||
}
|
||||
return device, options, nil
|
||||
return WireGuardDevice{Device: device, AmneziaWG: options}, nil
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) ValidateOptions(options domain.AmneziaWGOptions) error {
|
||||
_, err := encodeAmneziaWGOptions(options, c.version)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *AmneziaWGClient) ConfigureDevice(name string, cfg wgtypes.Config) error {
|
||||
|
||||
@@ -35,13 +35,13 @@ func amneziaWGConfigBatches(name string, cfg wgtypes.Config, options domain.Amne
|
||||
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)))
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_LISTEN_PORT, nl.Uint16Attr(uint16(*cfg.ListenPort))))
|
||||
}
|
||||
if cfg.FirewallMark != nil {
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_FWMARK, awgNumber(uint64(uint32(*cfg.FirewallMark)), 4)))
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_FWMARK, nl.Uint32Attr(uint32(*cfg.FirewallMark))))
|
||||
}
|
||||
if cfg.ReplacePeers {
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_FLAGS, awgNumber(unix.WGDEVICE_F_REPLACE_PEERS, 4)))
|
||||
attrs = append(attrs, nl.NewRtAttr(unix.WGDEVICE_A_FLAGS, nl.Uint32Attr(unix.WGDEVICE_F_REPLACE_PEERS)))
|
||||
}
|
||||
custom, err := encodeAmneziaWGOptions(options, version)
|
||||
if err != nil {
|
||||
@@ -103,7 +103,7 @@ func encodeAmneziaWGPeer(peer wgtypes.PeerConfig, ips []net.IPNet, first bool, v
|
||||
flags |= unix.WGPEER_F_REPLACE_ALLOWEDIPS
|
||||
}
|
||||
if flags != 0 {
|
||||
attr.AddRtAttr(unix.WGPEER_A_FLAGS, awgNumber(uint64(flags), 4))
|
||||
attr.AddRtAttr(unix.WGPEER_A_FLAGS, nl.Uint32Attr(flags))
|
||||
}
|
||||
if first {
|
||||
if peer.PresharedKey != nil {
|
||||
@@ -121,18 +121,18 @@ func encodeAmneziaWGPeer(peer wgtypes.PeerConfig, ips []net.IPNet, first bool, v
|
||||
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
|
||||
seconds := uint16(interval / time.Second)
|
||||
value := nl.Uint16Attr(seconds)
|
||||
if version >= 3 {
|
||||
value |= value << 16
|
||||
size = 4
|
||||
value = nl.Uint32Attr(uint32(seconds) | uint32(seconds)<<16)
|
||||
}
|
||||
attr.AddRtAttr(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, awgNumber(value, size))
|
||||
attr.AddRtAttr(unix.WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, value)
|
||||
}
|
||||
}
|
||||
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
|
||||
address, family, bits := ip.IP.To4(), uint16(unix.AF_INET), 32
|
||||
if address == nil {
|
||||
address, family, bits = ip.IP.To16(), unix.AF_INET6, 128
|
||||
}
|
||||
@@ -141,7 +141,7 @@ func encodeAmneziaWGPeer(peer wgtypes.PeerConfig, ips []net.IPNet, first bool, v
|
||||
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_FAMILY, nl.Uint16Attr(family))
|
||||
entry.AddRtAttr(unix.WGALLOWEDIP_A_IPADDR, address)
|
||||
entry.AddRtAttr(unix.WGALLOWEDIP_A_CIDR_MASK, []byte{byte(ones)})
|
||||
}
|
||||
|
||||
@@ -72,9 +72,9 @@ 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
|
||||
return nl.Uint16Attr(uint16(v)), err
|
||||
case awgOptionHeader:
|
||||
lo, hi, err := awgRange(value, 32)
|
||||
lo, hi, err := domain.ParseAmneziaWGRange(value, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -83,11 +83,11 @@ func (o awgOption) encode(value string, version uint8) ([]byte, error) {
|
||||
if lo != hi {
|
||||
return nil, fmt.Errorf("header ranges require AmneziaWG v2 or newer")
|
||||
}
|
||||
return awgNumber(lo, 4), nil
|
||||
return nl.Uint32Attr(uint32(lo)), nil
|
||||
case 2:
|
||||
return nl.ZeroTerminated(awgRangeString(lo, hi)), nil
|
||||
default:
|
||||
return awgNumber(lo|hi<<32, 8), nil
|
||||
return nl.Uint64Attr(lo | hi<<32), nil
|
||||
}
|
||||
case awgOptionString:
|
||||
return nl.ZeroTerminated(value), nil
|
||||
@@ -95,8 +95,8 @@ func (o awgOption) encode(value string, version uint8) ([]byte, error) {
|
||||
key, err := wgtypes.ParseKey(value)
|
||||
return key[:], err
|
||||
case awgOptionRange16:
|
||||
lo, hi, err := awgRange(value, 16)
|
||||
return awgNumber(lo|hi<<16, 4), err
|
||||
lo, hi, err := domain.ParseAmneziaWGRange(value, 16)
|
||||
return nl.Uint32Attr(uint32(lo | hi<<16)), err
|
||||
case awgOptionBool:
|
||||
if value == "1" || value == "on" {
|
||||
return []byte{1}, nil
|
||||
@@ -121,7 +121,7 @@ func (o awgOption) decode(data []byte, version uint8) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
lo, hi, err := awgRange(value, 32)
|
||||
lo, hi, err := domain.ParseAmneziaWGRange(value, 32)
|
||||
return awgRangeString(lo, hi), err
|
||||
default:
|
||||
v, err := awgReadNumber(data, 8)
|
||||
@@ -145,21 +145,6 @@ func (o awgOption) decode(data []byte, version uint8) (string, error) {
|
||||
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")
|
||||
@@ -184,25 +169,6 @@ func awgString(data []byte) (string, error) {
|
||||
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)
|
||||
|
||||
@@ -26,11 +26,7 @@ func awgKernelLink(name string) (netlink.Link, error) {
|
||||
}
|
||||
|
||||
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
|
||||
return append([]byte{0, version, 0, 0}, awgTestSerialize(attrs)...)
|
||||
}
|
||||
|
||||
func awgTestAttrMap(t *testing.T, data []byte) map[uint16][]byte {
|
||||
@@ -139,13 +135,11 @@ func TestAmneziaWGNativeDeviceVersionsAndMultipartDump(t *testing.T) {
|
||||
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)
|
||||
require.Equal(t, domain.AmneziaWGOptions{"H1": header, "Jc": "4"}, device.AmneziaWG)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"io"
|
||||
|
||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/domain"
|
||||
)
|
||||
|
||||
// A WireGuardClient is a type which can control a WireGuard device.
|
||||
@@ -13,3 +15,9 @@ type WireGuardClient interface {
|
||||
Device(name string) (*wgtypes.Device, error)
|
||||
ConfigureDevice(name string, cfg wgtypes.Config) error
|
||||
}
|
||||
|
||||
// WireGuardDevice carries the device and its backend options from the same read.
|
||||
type WireGuardDevice struct {
|
||||
*wgtypes.Device
|
||||
AmneziaWG domain.AmneziaWGOptions
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user