feat: WireGuard (server + client + peers + QR) + shared UI components

WireGuard
---------
* Migration 0013: wireguard_interfaces (server|client mode, key envelope-
  encrypted) + wireguard_peers (per-server roster). Drop old empty
  0005-Schema (Option-A peer_type, kein Iface-FK), neuer Aufbau mit
  zwei Tabellen + FK.
* internal/services/secrets: Box mit AES-256-GCM, Master-Key in
  /var/lib/edgeguard/.master_key (lazy-create, 0600). Sealed/Open
  für PrivateKey + PSK.
* internal/services/wireguard: KeyGen (Curve25519 mit clamping),
  PublicFromPrivate (für Import), InterfacesRepo, PeersRepo, Importer
  (parst /etc/wireguard/*.conf, server vs. client heuristisch nach
  ListenPort + Peer-Anzahl).
* internal/wireguard: Renderer schreibt /etc/edgeguard/wireguard/<iface>.conf
  (0600), restartet wg-quick@<iface> via sudo (sudoers im postinst
  erweitert). Idempotent — re-render nur wenn content geändert.
* internal/handlers/wireguard.go: REST CRUD für interfaces+peers,
  /generate-keypair, /peers/:id/config (text/plain wg-quick conf),
  /peers/:id/qr (PNG via go-qrcode). Auto-reload nach Mutation.
* edgeguard-ctl wg-import [--path /etc/wireguard]: liest existierende
  conf-Files in die DB. Idempotent (überspringt vorhandene Iface-Namen).

Shared UI components (proxy-lb-waf design pattern)
--------------------------------------------------
* PageHeader: icon + title + subtitle + extras row, einheitlich oben
  auf jeder Page.
* ActionButtons: Edit + Delete combo mit Popconfirm + Tooltip.
* StatusDot: AntD Badge pattern statt "Yes/No" — schneller scanbar
  in dichten Tabellen.
* DataTable: pageSizeOptions [20,50,100,200] + extraActions-Alias +
  optional renderMobileCard für Card-Liste auf < md Breakpoint.
* enterprise.css: .page-header* + .datatable-toolbar Klassen.

Frontend WireGuard
------------------
* /vpn/wireguard mit zwei Tabs (Server / Client) im neuen Pattern.
* Server-Tab: Modal mit Generate-Keypair-Toggle, Peer-Roster im
  Drawer per Server. Pro Peer: QR-Code-Modal + .conf-Download.
* Client-Tab: Upstream-Card im Modal, full-tunnel-Default
  (0.0.0.0/0,::/0), Keepalive 25.
* i18n DE/EN für wg.* Block + common.* Erweiterung.

Misc
----
* Sidebar: WireGuard unter Security-Sektion.
* Nav-i18n: "Firewall (v2)" → "Firewall".
* Version 1.0.8 → 1.0.11.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Debian
2026-05-10 20:51:25 +02:00
parent 3545b8422b
commit 85904d0c36
33 changed files with 3046 additions and 40 deletions

View File

@@ -0,0 +1,346 @@
package wireguard
import (
"bufio"
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"git.netcell-it.de/projekte/edgeguard-native/internal/models"
"git.netcell-it.de/projekte/edgeguard-native/internal/services/secrets"
)
// ImportResult summarises what an Import call did so the CLI can
// report it back to the operator.
type ImportResult struct {
IfacesAdded int `json:"ifaces_added"`
PeersAdded int `json:"peers_added"`
Skipped []string `json:"skipped,omitempty"` // ifaces already present, with reason
}
// Importer takes existing /etc/wireguard/*.conf files and translates
// them into wireguard_interfaces + wireguard_peers rows so the
// operator can keep their pre-EdgeGuard tunnels live across the
// migration. Heuristics:
//
// - Iface name = filename without .conf (so wg0.conf → wg0)
// - One [Interface] block becomes the wireguard_interfaces row
// - [Peer] blocks with Endpoint+ no AllowedIPs/0.0.0.0/0 → mode=client
// (rare — a wg conf usually has many peers in server mode)
// - >1 [Peer] block → mode=server, peers go to the peer roster
// - Single [Peer] with Endpoint set → mode=client (the peer is the
// upstream we dial)
//
// Existing iface names in the DB are skipped (idempotent re-run).
type Importer struct {
Ifaces *InterfacesRepo
Peers *PeersRepo
Box *secrets.Box
}
func NewImporter(ifaces *InterfacesRepo, peers *PeersRepo, box *secrets.Box) *Importer {
return &Importer{Ifaces: ifaces, Peers: peers, Box: box}
}
func (im *Importer) ImportDir(ctx context.Context, dir string) (*ImportResult, error) {
res := &ImportResult{}
entries, err := os.ReadDir(dir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return res, nil
}
return nil, err
}
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".conf") {
continue
}
path := filepath.Join(dir, e.Name())
ifaceName := strings.TrimSuffix(e.Name(), ".conf")
// Skip names that violate our regex — operator can rename
// the file and re-run.
if !validIfaceName(ifaceName) {
res.Skipped = append(res.Skipped, ifaceName+" (invalid name)")
continue
}
if err := im.importFile(ctx, ifaceName, path, res); err != nil {
res.Skipped = append(res.Skipped, ifaceName+": "+err.Error())
}
}
return res, nil
}
func (im *Importer) importFile(ctx context.Context, ifaceName, path string, res *ImportResult) error {
// Skip if already present.
all, err := im.Ifaces.List(ctx)
if err != nil {
return err
}
for _, x := range all {
if x.Name == ifaceName {
res.Skipped = append(res.Skipped, ifaceName+" (already in DB)")
return nil
}
}
parsed, err := parseWGConf(path)
if err != nil {
return err
}
if parsed.PrivateKey == "" {
return errors.New("no PrivateKey in [Interface]")
}
if parsed.Address == "" {
return errors.New("no Address in [Interface]")
}
// Mode heuristic: an [Interface] without ListenPort plus a single
// [Peer] with Endpoint set is a client tunnel. Anything else
// (multiple peers, ListenPort set, peers without Endpoint) we
// treat as server.
mode := "server"
if parsed.ListenPort == 0 && len(parsed.Peers) == 1 && parsed.Peers[0].Endpoint != "" {
mode = "client"
}
pub, err := PublicFromPrivate(parsed.PrivateKey)
if err != nil {
return fmt.Errorf("derive pubkey: %w", err)
}
encPriv, err := im.Box.Seal([]byte(parsed.PrivateKey))
if err != nil {
return fmt.Errorf("seal: %w", err)
}
ifc := models.WireguardInterface{
Name: ifaceName,
Mode: mode,
AddressCIDR: parsed.Address,
PublicKey: pub,
PrivateKeyEnc: encPriv,
Role: "wan",
Active: true,
MTU: intPtrIfNonzero(parsed.MTU),
}
if mode == "server" {
port := parsed.ListenPort
if port == 0 {
port = 51820
}
ifc.ListenPort = &port
} else {
// client mode → fold the single peer into the iface row.
p := parsed.Peers[0]
ep := p.Endpoint
pk := p.PublicKey
ifc.PeerEndpoint = &ep
ifc.PeerPublicKey = &pk
if p.AllowedIPs != "" {
ai := p.AllowedIPs
ifc.AllowedIPs = &ai
}
if p.Keepalive > 0 {
k := p.Keepalive
ifc.PersistentKeepalive = &k
}
if p.PSK != "" {
pskEnc, err := im.Box.Seal([]byte(p.PSK))
if err != nil {
return fmt.Errorf("seal psk: %w", err)
}
ifc.PeerPSKEnc = pskEnc
}
}
created, err := im.Ifaces.Create(ctx, ifc)
if err != nil {
return fmt.Errorf("insert iface: %w", err)
}
res.IfacesAdded++
if mode == "server" {
for i, p := range parsed.Peers {
if p.PublicKey == "" {
res.Skipped = append(res.Skipped, fmt.Sprintf("%s peer #%d (no PublicKey)", ifaceName, i))
continue
}
peer := models.WireguardPeer{
InterfaceID: created.ID,
Name: p.Name,
PublicKey: p.PublicKey,
AllowedIPs: p.AllowedIPs,
Enabled: true,
}
if peer.Name == "" {
peer.Name = fmt.Sprintf("imported-%d", i+1)
}
if peer.AllowedIPs == "" {
peer.AllowedIPs = "0.0.0.0/0"
}
if p.Keepalive > 0 {
k := p.Keepalive
peer.Keepalive = &k
}
if p.PSK != "" {
pskEnc, err := im.Box.Seal([]byte(p.PSK))
if err != nil {
return fmt.Errorf("seal peer psk: %w", err)
}
peer.PSKEnc = pskEnc
}
if _, err := im.Peers.Create(ctx, peer); err != nil {
res.Skipped = append(res.Skipped, fmt.Sprintf("%s peer %s: %v", ifaceName, peer.Name, err))
continue
}
res.PeersAdded++
}
}
return nil
}
// parsedConf is the intermediate shape of a parsed wg-quick file.
type parsedConf struct {
Address string
ListenPort int
PrivateKey string
MTU int
Peers []parsedPeer
}
type parsedPeer struct {
Name string
PublicKey string
Endpoint string
AllowedIPs string
Keepalive int
PSK string
}
// parseWGConf is intentionally lenient — it accepts anything wg-quick
// would accept, ignores PostUp/PostDown/Table/SaveConfig since
// edgeguard owns runtime, and collapses comment lines starting with
// '#' into the next [Peer]'s Name (mirrors the wg-easy convention).
func parseWGConf(path string) (*parsedConf, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var (
out parsedConf
section string
currentPeer *parsedPeer
nextName string
)
flushPeer := func() {
if currentPeer != nil {
if currentPeer.Name == "" && nextName != "" {
currentPeer.Name = nextName
}
out.Peers = append(out.Peers, *currentPeer)
currentPeer = nil
}
nextName = ""
}
sc := bufio.NewScanner(f)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" {
continue
}
if strings.HasPrefix(line, "#") {
// Comment line; if the next thing we see is a [Peer],
// use this as the peer's name.
nextName = strings.TrimSpace(strings.TrimPrefix(line, "#"))
continue
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
flushPeer()
section = strings.ToLower(strings.Trim(line, "[]"))
if section == "peer" {
currentPeer = &parsedPeer{}
}
continue
}
idx := strings.Index(line, "=")
if idx < 0 {
continue
}
key := strings.TrimSpace(strings.ToLower(line[:idx]))
val := strings.TrimSpace(line[idx+1:])
switch section {
case "interface":
switch key {
case "address":
out.Address = strings.Split(val, ",")[0] // first addr only
case "listenport":
if n, err := strconv.Atoi(val); err == nil {
out.ListenPort = n
}
case "privatekey":
out.PrivateKey = val
case "mtu":
if n, err := strconv.Atoi(val); err == nil {
out.MTU = n
}
}
case "peer":
if currentPeer == nil {
continue
}
switch key {
case "publickey":
currentPeer.PublicKey = val
case "endpoint":
currentPeer.Endpoint = val
case "allowedips":
currentPeer.AllowedIPs = val
case "persistentkeepalive":
if n, err := strconv.Atoi(val); err == nil {
currentPeer.Keepalive = n
}
case "presharedkey":
currentPeer.PSK = val
}
}
}
flushPeer()
if err := sc.Err(); err != nil {
return nil, err
}
return &out, nil
}
func validIfaceName(s string) bool {
if len(s) < 2 || len(s) > 15 {
return false
}
if !strings.HasPrefix(s, "wg") {
return false
}
for _, r := range s[2:] {
switch {
case r >= 'a' && r <= 'z',
r >= '0' && r <= '9',
r == '-':
default:
return false
}
}
return true
}
func intPtrIfNonzero(n int) *int {
if n == 0 {
return nil
}
return &n
}

View File

@@ -0,0 +1,118 @@
package wireguard
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"git.netcell-it.de/projekte/edgeguard-native/internal/models"
)
var ErrIfaceNotFound = errors.New("wireguard interface not found")
type InterfacesRepo struct {
Pool *pgxpool.Pool
}
func NewInterfacesRepo(pool *pgxpool.Pool) *InterfacesRepo { return &InterfacesRepo{Pool: pool} }
const ifaceBaseSelect = `
SELECT id, name, mode, address_cidr, listen_port, public_key, private_key_enc,
peer_endpoint, peer_public_key, peer_psk_enc, allowed_ips, persistent_keepalive,
mtu, role, active, description, created_at, updated_at
FROM wireguard_interfaces
`
func (r *InterfacesRepo) List(ctx context.Context) ([]models.WireguardInterface, error) {
rows, err := r.Pool.Query(ctx, ifaceBaseSelect+" ORDER BY name ASC")
if err != nil {
return nil, err
}
defer rows.Close()
out := make([]models.WireguardInterface, 0, 4)
for rows.Next() {
i, err := scanIface(rows)
if err != nil {
return nil, err
}
out = append(out, *i)
}
return out, rows.Err()
}
func (r *InterfacesRepo) Get(ctx context.Context, id int64) (*models.WireguardInterface, error) {
row := r.Pool.QueryRow(ctx, ifaceBaseSelect+" WHERE id = $1", id)
i, err := scanIface(row)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrIfaceNotFound
}
return nil, err
}
return i, nil
}
func (r *InterfacesRepo) Create(ctx context.Context, i models.WireguardInterface) (*models.WireguardInterface, error) {
row := r.Pool.QueryRow(ctx, `
INSERT INTO wireguard_interfaces (
name, mode, address_cidr, listen_port, public_key, private_key_enc,
peer_endpoint, peer_public_key, peer_psk_enc, allowed_ips, persistent_keepalive,
mtu, role, active, description
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)
RETURNING id, name, mode, address_cidr, listen_port, public_key, private_key_enc,
peer_endpoint, peer_public_key, peer_psk_enc, allowed_ips, persistent_keepalive,
mtu, role, active, description, created_at, updated_at`,
i.Name, i.Mode, i.AddressCIDR, i.ListenPort, i.PublicKey, i.PrivateKeyEnc,
i.PeerEndpoint, i.PeerPublicKey, i.PeerPSKEnc, i.AllowedIPs, i.PersistentKeepalive,
i.MTU, i.Role, i.Active, i.Description)
return scanIface(row)
}
func (r *InterfacesRepo) Update(ctx context.Context, id int64, i models.WireguardInterface) (*models.WireguardInterface, error) {
row := r.Pool.QueryRow(ctx, `
UPDATE wireguard_interfaces SET
name = $1, mode = $2, address_cidr = $3, listen_port = $4, public_key = $5,
private_key_enc = $6, peer_endpoint = $7, peer_public_key = $8, peer_psk_enc = $9,
allowed_ips = $10, persistent_keepalive = $11, mtu = $12, role = $13,
active = $14, description = $15, updated_at = NOW()
WHERE id = $16
RETURNING id, name, mode, address_cidr, listen_port, public_key, private_key_enc,
peer_endpoint, peer_public_key, peer_psk_enc, allowed_ips, persistent_keepalive,
mtu, role, active, description, created_at, updated_at`,
i.Name, i.Mode, i.AddressCIDR, i.ListenPort, i.PublicKey, i.PrivateKeyEnc,
i.PeerEndpoint, i.PeerPublicKey, i.PeerPSKEnc, i.AllowedIPs, i.PersistentKeepalive,
i.MTU, i.Role, i.Active, i.Description, id)
out, err := scanIface(row)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrIfaceNotFound
}
return nil, err
}
return out, nil
}
func (r *InterfacesRepo) Delete(ctx context.Context, id int64) error {
tag, err := r.Pool.Exec(ctx, `DELETE FROM wireguard_interfaces WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrIfaceNotFound
}
return nil
}
func scanIface(row interface{ Scan(...any) error }) (*models.WireguardInterface, error) {
var i models.WireguardInterface
if err := row.Scan(
&i.ID, &i.Name, &i.Mode, &i.AddressCIDR, &i.ListenPort, &i.PublicKey, &i.PrivateKeyEnc,
&i.PeerEndpoint, &i.PeerPublicKey, &i.PeerPSKEnc, &i.AllowedIPs, &i.PersistentKeepalive,
&i.MTU, &i.Role, &i.Active, &i.Description, &i.CreatedAt, &i.UpdatedAt,
); err != nil {
return nil, err
}
return &i, nil
}

View File

@@ -0,0 +1,77 @@
// Package wireguard implements the persistence + lifecycle of
// WireGuard tunnels (server + client mode) and their peer roster.
// Sub-files split by concern:
//
// keys.go — Curve25519 keypair generation + parse helpers
// interfaces.go — wireguard_interfaces CRUD
// peers.go — wireguard_peers CRUD
// import.go — read /etc/wireguard/*.conf into the DB
package wireguard
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"golang.org/x/crypto/curve25519"
)
// Keypair holds a base64-encoded WireGuard keypair (the wire format
// wg-quick prints — 32 raw bytes, base64 standard padding included).
type Keypair struct {
Private string
Public string
}
// GenerateKeypair returns a fresh Curve25519 keypair, clamped per
// WireGuard's spec, base64-encoded.
func GenerateKeypair() (*Keypair, error) {
priv := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, priv); err != nil {
return nil, fmt.Errorf("rand: %w", err)
}
// WireGuard / curve25519 clamping: clear the lowest 3 bits of
// priv[0], clear the highest bit and set the second-highest of
// priv[31]. Required to make the scalar a valid Curve25519
// private key.
priv[0] &= 248
priv[31] &= 127
priv[31] |= 64
pub, err := curve25519.X25519(priv, curve25519.Basepoint)
if err != nil {
return nil, fmt.Errorf("derive pub: %w", err)
}
return &Keypair{
Private: base64.StdEncoding.EncodeToString(priv),
Public: base64.StdEncoding.EncodeToString(pub),
}, nil
}
// GeneratePresharedKey returns a fresh 32-byte PSK as base64.
func GeneratePresharedKey() (string, error) {
psk := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, psk); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(psk), nil
}
// PublicFromPrivate derives the matching pubkey for a base64 private
// key — used by the import path where the operator hands us a
// private key from an existing wg-quick config.
func PublicFromPrivate(privB64 string) (string, error) {
priv, err := base64.StdEncoding.DecodeString(privB64)
if err != nil {
return "", fmt.Errorf("decode private key: %w", err)
}
if len(priv) != 32 {
return "", errors.New("private key must be 32 bytes")
}
pub, err := curve25519.X25519(priv, curve25519.Basepoint)
if err != nil {
return "", fmt.Errorf("derive pub: %w", err)
}
return base64.StdEncoding.EncodeToString(pub), nil
}

View File

@@ -0,0 +1,132 @@
package wireguard
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"git.netcell-it.de/projekte/edgeguard-native/internal/models"
)
var ErrPeerNotFound = errors.New("wireguard peer not found")
type PeersRepo struct {
Pool *pgxpool.Pool
}
func NewPeersRepo(pool *pgxpool.Pool) *PeersRepo { return &PeersRepo{Pool: pool} }
const peerBaseSelect = `
SELECT id, interface_id, name, public_key, private_key_enc, psk_enc,
allowed_ips, keepalive, last_handshake, transfer_rx, transfer_tx,
enabled, description, created_at, updated_at
FROM wireguard_peers
`
func (r *PeersRepo) ListForInterface(ctx context.Context, ifaceID int64) ([]models.WireguardPeer, error) {
rows, err := r.Pool.Query(ctx, peerBaseSelect+" WHERE interface_id = $1 ORDER BY name ASC", ifaceID)
if err != nil {
return nil, err
}
defer rows.Close()
out := make([]models.WireguardPeer, 0, 8)
for rows.Next() {
p, err := scanPeer(rows)
if err != nil {
return nil, err
}
out = append(out, *p)
}
return out, rows.Err()
}
func (r *PeersRepo) ListAll(ctx context.Context) ([]models.WireguardPeer, error) {
rows, err := r.Pool.Query(ctx, peerBaseSelect+" ORDER BY interface_id, name ASC")
if err != nil {
return nil, err
}
defer rows.Close()
out := make([]models.WireguardPeer, 0, 16)
for rows.Next() {
p, err := scanPeer(rows)
if err != nil {
return nil, err
}
out = append(out, *p)
}
return out, rows.Err()
}
func (r *PeersRepo) Get(ctx context.Context, id int64) (*models.WireguardPeer, error) {
row := r.Pool.QueryRow(ctx, peerBaseSelect+" WHERE id = $1", id)
p, err := scanPeer(row)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrPeerNotFound
}
return nil, err
}
return p, nil
}
func (r *PeersRepo) Create(ctx context.Context, p models.WireguardPeer) (*models.WireguardPeer, error) {
row := r.Pool.QueryRow(ctx, `
INSERT INTO wireguard_peers (
interface_id, name, public_key, private_key_enc, psk_enc, allowed_ips,
keepalive, enabled, description
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
RETURNING id, interface_id, name, public_key, private_key_enc, psk_enc,
allowed_ips, keepalive, last_handshake, transfer_rx, transfer_tx,
enabled, description, created_at, updated_at`,
p.InterfaceID, p.Name, p.PublicKey, p.PrivateKeyEnc, p.PSKEnc, p.AllowedIPs,
p.Keepalive, p.Enabled, p.Description)
return scanPeer(row)
}
func (r *PeersRepo) Update(ctx context.Context, id int64, p models.WireguardPeer) (*models.WireguardPeer, error) {
row := r.Pool.QueryRow(ctx, `
UPDATE wireguard_peers SET
name = $1, public_key = $2, private_key_enc = $3, psk_enc = $4,
allowed_ips = $5, keepalive = $6, enabled = $7, description = $8,
updated_at = NOW()
WHERE id = $9
RETURNING id, interface_id, name, public_key, private_key_enc, psk_enc,
allowed_ips, keepalive, last_handshake, transfer_rx, transfer_tx,
enabled, description, created_at, updated_at`,
p.Name, p.PublicKey, p.PrivateKeyEnc, p.PSKEnc,
p.AllowedIPs, p.Keepalive, p.Enabled, p.Description, id)
out, err := scanPeer(row)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrPeerNotFound
}
return nil, err
}
return out, nil
}
func (r *PeersRepo) Delete(ctx context.Context, id int64) error {
tag, err := r.Pool.Exec(ctx, `DELETE FROM wireguard_peers WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrPeerNotFound
}
return nil
}
func scanPeer(row interface{ Scan(...any) error }) (*models.WireguardPeer, error) {
var p models.WireguardPeer
if err := row.Scan(
&p.ID, &p.InterfaceID, &p.Name, &p.PublicKey, &p.PrivateKeyEnc, &p.PSKEnc,
&p.AllowedIPs, &p.Keepalive, &p.LastHandshake, &p.TransferRX, &p.TransferTX,
&p.Enabled, &p.Description, &p.CreatedAt, &p.UpdatedAt,
); err != nil {
return nil, err
}
p.HasPrivateKey = len(p.PrivateKeyEnc) > 0
return &p, nil
}