mirror of
https://github.com/h44z/wg-portal.git
synced 2026-12-05 19:56:06 +01:00
feat: add support for AmneziaWG (#649)
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||
)
|
||||
|
||||
// AmneziaWGOptions contains [Interface] options understood by the official awg tool.
|
||||
// See: https://docs.amnezia.org/documentation/amnezia-wg#configuration-parameters
|
||||
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)
|
||||
}
|
||||
var err error
|
||||
switch key {
|
||||
case "Jc", "Jmin", "Jmax", "S1", "S2", "S3", "S4":
|
||||
_, err = strconv.ParseUint(value, 10, 16)
|
||||
case "H1", "H2", "H3", "H4":
|
||||
err = validateAmneziaWGRange(value, 32)
|
||||
case "ContentPaddingAddition", "RekeyAfterTime", "RekeyTimeout", "RejectAfterTime", "KeepaliveTimeout", "MaxHandshakeAttempts":
|
||||
err = validateAmneziaWGRange(value, 16)
|
||||
case "I1", "I2", "I3", "I4", "I5":
|
||||
// The kernel validates the CPS description; it must stay on one line.
|
||||
if value == "" {
|
||||
err = fmt.Errorf("empty CPS description")
|
||||
}
|
||||
case "HeaderProtectionKey":
|
||||
_, err = wgtypes.ParseKey(value)
|
||||
case "RandomTrailers", "DisableCookies":
|
||||
if value != "on" && value != "off" && value != "0" && value != "1" {
|
||||
err = fmt.Errorf("expected on/off or 0/1")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown AmneziaWG option %q: %w", key, ErrInvalidData)
|
||||
}
|
||||
if err != nil {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAmneziaWGRange(value string, bits int) error {
|
||||
parts := strings.Split(value, "-")
|
||||
if len(parts) > 2 {
|
||||
return fmt.Errorf("invalid range")
|
||||
}
|
||||
lo, err := strconv.ParseUint(parts[0], 10, bits)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(parts) == 2 {
|
||||
hi, err := strconv.ParseUint(parts[1], 10, bits)
|
||||
if err != nil || lo > hi {
|
||||
return fmt.Errorf("invalid range")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ConfigLines is deterministic so saved files and QR codes use the same options.
|
||||
func (o AmneziaWGOptions) ConfigLines() string {
|
||||
var result strings.Builder
|
||||
for _, key := range slices.Sorted(maps.Keys(o)) {
|
||||
_, _ = fmt.Fprintf(&result, "%s = %s\n", key, o[key])
|
||||
}
|
||||
return result.String()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/h44z/wg-portal/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAmneziaWGOptionsValidation(t *testing.T) {
|
||||
require.NoError(t, (AmneziaWGOptions{"Jc": "4", "Jmin": "40", "Jmax": "70", "H1": "100-200", "S4": "16", "I1": "<b 0x1234>", "ContentPaddingAddition": "0-16", "RandomTrailers": "on"}).Validate())
|
||||
for _, options := range []AmneziaWGOptions{
|
||||
{"H1": "4294967296"}, {"H1": "200-100"}, {"Jc": "-1"}, {"Jc": "65536"},
|
||||
{"Jmin": "71", "Jmax": "70"}, {"RekeyTimeout": "x"}, {"PreUp": "evil"},
|
||||
{"I1": "abc\n[Peer]"}, {"I1": "abc#comment"}, {"RandomTrailers": "bad"}, {"HeaderProtectionKey": "bad"},
|
||||
} {
|
||||
require.ErrorIs(t, options.Validate(), ErrInvalidData)
|
||||
}
|
||||
iface := &Interface{Backend: config.LocalBackendName, AmneziaWG: AmneziaWGOptions{"Jc": "4"}}
|
||||
require.ErrorIs(t, iface.Validate(), ErrInvalidData)
|
||||
iface.Backend = config.AmneziaWGBackendName
|
||||
require.NoError(t, iface.Validate())
|
||||
}
|
||||
|
||||
func TestAmneziaWGInterfaceImportMergeAndRouting(t *testing.T) {
|
||||
options := AmneziaWGOptions{"H1": "100-200", "Jc": "4"}
|
||||
physical := &PhysicalInterface{ImportSource: ControllerTypeAmneziaWG}
|
||||
physical.SetExtras(AmneziaWGInterfaceExtras{Options: options})
|
||||
iface := ConvertPhysicalInterface(physical)
|
||||
require.Equal(t, options, iface.AmneziaWG)
|
||||
iface.AmneziaWG["Jc"] = "5"
|
||||
require.Equal(t, "4", options["Jc"], "imported settings must not mutate physical extras")
|
||||
iface.Backend = config.AmneziaWGBackendName
|
||||
iface.AmneziaWG = AmneziaWGOptions{"Jc": "6"}
|
||||
MergeToPhysicalInterface(physical, iface)
|
||||
require.Equal(t, AmneziaWGInterfaceExtras{Options: AmneziaWGOptions{"H1": "100-200", "Jc": "6"}}, physical.GetExtras())
|
||||
require.Equal(t, "4", options["Jc"], "merging must not mutate the previous extras snapshot")
|
||||
iface.RoutingTable = "12345"
|
||||
require.Equal(t, 12345, iface.GetRoutingTable())
|
||||
iface.RoutingTable = "0x1234"
|
||||
require.Equal(t, 0x1234, iface.GetRoutingTable())
|
||||
}
|
||||
|
||||
func TestAmneziaWGInterfaceMergeInitializesExtras(t *testing.T) {
|
||||
for _, existing := range []any{nil, AmneziaWGInterfaceExtras{}} {
|
||||
physical := &PhysicalInterface{ImportSource: ControllerTypeAmneziaWG}
|
||||
if existing != nil {
|
||||
physical.SetExtras(existing)
|
||||
}
|
||||
iface := &Interface{Backend: config.AmneziaWGBackendName, AmneziaWG: AmneziaWGOptions{"Jc": "4"}}
|
||||
MergeToPhysicalInterface(physical, iface)
|
||||
require.Equal(t, AmneziaWGInterfaceExtras{Options: iface.AmneziaWG}, physical.GetExtras())
|
||||
iface.AmneziaWG["Jc"] = "6"
|
||||
require.Equal(t, "4", physical.GetExtras().(AmneziaWGInterfaceExtras).Options["Jc"])
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,11 @@ package domain
|
||||
// ControllerType defines the type of controller used to manage interfaces.
|
||||
|
||||
const (
|
||||
ControllerTypeMikrotik = "mikrotik"
|
||||
ControllerTypeLocal = "wgctrl"
|
||||
ControllerTypePfsense = "pfsense"
|
||||
ControllerTypeOpnsense = "opnsense"
|
||||
ControllerTypeMikrotik = "mikrotik"
|
||||
ControllerTypeLocal = "wgctrl"
|
||||
ControllerTypeAmneziaWG = "amneziawg"
|
||||
ControllerTypePfsense = "pfsense"
|
||||
ControllerTypeOpnsense = "opnsense"
|
||||
)
|
||||
|
||||
// Controller extras can be used to store additional information available for specific controllers only.
|
||||
@@ -17,6 +18,10 @@ type MikrotikInterfaceExtras struct {
|
||||
Disabled bool
|
||||
}
|
||||
|
||||
type AmneziaWGInterfaceExtras struct {
|
||||
Options AmneziaWGOptions
|
||||
}
|
||||
|
||||
type MikrotikPeerExtras struct {
|
||||
Id string // internal mikrotik ID
|
||||
Name string
|
||||
|
||||
@@ -3,6 +3,7 @@ package domain
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"math"
|
||||
"net"
|
||||
"regexp"
|
||||
@@ -29,6 +30,12 @@ type InterfaceIdentifier string
|
||||
type InterfaceType string
|
||||
type InterfaceBackend string
|
||||
|
||||
// IsLocal includes both kernel backends, which share Linux routing and peer
|
||||
// disable/restore behavior. The empty backend is the legacy local backend.
|
||||
func (b InterfaceBackend) IsLocal() bool {
|
||||
return b == "" || b == config.LocalBackendName || b == config.AmneziaWGBackendName
|
||||
}
|
||||
|
||||
type Interface struct {
|
||||
BaseModel
|
||||
|
||||
@@ -37,6 +44,7 @@ type Interface struct {
|
||||
Identifier InterfaceIdentifier `gorm:"primaryKey"` // device name, for example: wg0
|
||||
KeyPair // private/public Key of the server interface
|
||||
ListenPort int // the listening port, for example: 51820
|
||||
AmneziaWG AmneziaWGOptions `gorm:"serializer:json"` // AmneziaWG obfuscation options, nil for ordinary WireGuard.
|
||||
|
||||
Addresses []Cidr `gorm:"many2many:interface_addresses;"` // the interface ip addresses
|
||||
DnsStr string // the dns server that should be set if the interface is up, comma separated
|
||||
@@ -121,6 +129,12 @@ func (i *Interface) PublicInfo() Interface {
|
||||
|
||||
// Validate performs checks to ensure that the interface is valid.
|
||||
func (i *Interface) Validate() error {
|
||||
if len(i.AmneziaWG) > 0 && i.Backend != config.AmneziaWGBackendName {
|
||||
return fmt.Errorf("AmneziaWG options require the amneziawg backend: %w", ErrInvalidData)
|
||||
}
|
||||
if err := i.AmneziaWG.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
// validate peer default endpoint, add port if needed
|
||||
if i.PeerDefEndpoint != "" {
|
||||
host, port, err := net.SplitHostPort(i.PeerDefEndpoint)
|
||||
@@ -210,7 +224,7 @@ func (i *Interface) GetRoutingTable() int {
|
||||
case routingTableStr == "off":
|
||||
return -1
|
||||
case strings.HasPrefix(routingTableStr, "0x"):
|
||||
if i.Backend != config.LocalBackendName {
|
||||
if !i.Backend.IsLocal() {
|
||||
return 0 // ignore numeric routing table numbers for non-local controllers
|
||||
}
|
||||
numberStr := strings.ReplaceAll(routingTableStr, "0x", "")
|
||||
@@ -225,7 +239,7 @@ func (i *Interface) GetRoutingTable() int {
|
||||
}
|
||||
return int(routingTable)
|
||||
default:
|
||||
if i.Backend != config.LocalBackendName {
|
||||
if !i.Backend.IsLocal() {
|
||||
return 0 // ignore numeric routing table numbers for non-local controllers
|
||||
}
|
||||
routingTable, err := strconv.Atoi(routingTableStr)
|
||||
@@ -283,7 +297,8 @@ func (p *PhysicalInterface) SetExtras(extras any) {
|
||||
case MikrotikInterfaceExtras: // OK
|
||||
case PfsenseInterfaceExtras: // OK
|
||||
case OpnsenseInterfaceExtras: // OK
|
||||
default: // we only support Mikrotik, Pfsense and Opnsense interface extras for now
|
||||
case AmneziaWGInterfaceExtras: // OK
|
||||
default:
|
||||
panic(fmt.Sprintf("unsupported interface backend extras type %T", extras))
|
||||
}
|
||||
|
||||
@@ -362,6 +377,9 @@ func ConvertPhysicalInterface(pi *PhysicalInterface) *Interface {
|
||||
} else {
|
||||
iface.Disabled = nil
|
||||
}
|
||||
case ControllerTypeAmneziaWG:
|
||||
extras := pi.GetExtras().(AmneziaWGInterfaceExtras)
|
||||
iface.AmneziaWG = maps.Clone(extras.Options)
|
||||
}
|
||||
|
||||
return iface
|
||||
@@ -403,6 +421,13 @@ func MergeToPhysicalInterface(pi *PhysicalInterface, i *Interface) {
|
||||
extras.Instance = existing.Instance
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -167,6 +167,8 @@ type PeerInterfaceConfig struct {
|
||||
PostUp ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_post_up_"` // action that is executed after the device is up
|
||||
PreDown ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_pre_down_"` // action that is executed before the device is down
|
||||
PostDown ConfigOption[string] `gorm:"embedded;embeddedPrefix:iface_post_down_"` // action that is executed after the device is down
|
||||
|
||||
AmneziaWG AmneziaWGOptions `gorm:"-" json:"-"` // Filled from the parent interface when exporting a client configuration.
|
||||
}
|
||||
|
||||
func (p *PeerInterfaceConfig) AddressStr() string {
|
||||
@@ -298,7 +300,7 @@ func ConvertPhysicalPeer(pp *PhysicalPeer) *Peer {
|
||||
peer.Disabled = nil
|
||||
peer.DisabledReason = ""
|
||||
}
|
||||
case ControllerTypeLocal:
|
||||
case ControllerTypeLocal, ControllerTypeAmneziaWG:
|
||||
extras := pp.GetExtras().(LocalPeerExtras)
|
||||
if extras.Disabled {
|
||||
peer.Disabled = &now
|
||||
@@ -397,7 +399,7 @@ func MergeToPhysicalPeer(pp *PhysicalPeer, p *Peer) {
|
||||
Dynamic: p.IsDynamic,
|
||||
}
|
||||
pp.SetExtras(extras)
|
||||
case ControllerTypeLocal:
|
||||
case ControllerTypeLocal, ControllerTypeAmneziaWG:
|
||||
extras := LocalPeerExtras{
|
||||
Disabled: p.IsDisabled(),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user