diff --git a/INSTALL.md b/INSTALL.md index 37f85fc..3f4cae8 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -117,6 +117,8 @@ In **Settings → Panel access**, choose **Public access**, **This server only** The policy takes effect on every new request, including sign-in, static files, metrics, and health checks. Fresh installations default to Public access, including VPN clients. This server only rejects VPN clients even when their TCP connection reaches the panel. Private networks only accepts the default private VPN addresses, subject to any allowlist. For a tunneled request, allowlist entries must match the client VPN IP (for example `10.64.0.2`), not the server public IP shown by an Internet IP-check website. It is stored in `/var/lib/wgsimple/panel-access.json` with private permissions and persists through restart/upgrade. Blocking sources returns HTTP 403; it does not close the listening socket or change firewall rules. Source IP comes from the TCP connection; forwarded headers are ignored. A local reverse proxy therefore appears as loopback: enforce source restrictions in the proxy itself. +Authentication rate limits are shared by each IPv4 address or IPv6 /64 subnet. If the panel is behind a reverse proxy, set `--trusted-proxy` to the exact IP address from which the proxy connects. Configure the proxy to overwrite `X-Real-IP` with the client's address. In NGINX, use `proxy_set_header X-Real-IP $remote_addr;`. Enable this option only when untrusted callers cannot connect to the panel from the trusted address. A missing, invalid, or repeated header uses the socket IP. Panel access rules continue to use the socket IP. + If you lock yourself out, run over SSH: ```bash diff --git a/cmd/wgsimple/main.go b/cmd/wgsimple/main.go index a482eb3..8975231 100644 --- a/cmd/wgsimple/main.go +++ b/cmd/wgsimple/main.go @@ -4,6 +4,7 @@ import ( "context" "flag" "fmt" + "net/netip" "os" "os/signal" "path/filepath" @@ -23,6 +24,8 @@ func run() error { iface := flag.String("interface", "wg0", "managed WireGuard interface") configDir := flag.String("config-dir", "/etc/wireguard", "WireGuard configuration directory (live Linux only)") origin := flag.String("origin", "", "canonical panel origin, e.g. https://vpn.example.com") + var trustedProxy netip.Addr + flag.TextVar(&trustedProxy, "trusted-proxy", netip.Addr{}, "trusted reverse proxy IP for authentication rate limiting (sets X-Real-IP)") cert := flag.String("tls-cert", "", "TLS certificate file") key := flag.String("tls-key", "", "TLS private key file") allowHTTP := flag.Bool("allow-http", false, "deprecated compatibility flag; non-loopback listeners always use HTTPS") @@ -57,6 +60,9 @@ func run() error { if err := app.ValidatePanelOrigin(*origin, loopback); err != nil { return err } + if trustedProxy.Zone() != "" || trustedProxy.Unmap().IsUnspecified() || trustedProxy.Unmap().IsMulticast() { + return fmt.Errorf("trusted proxy must be a single unicast IP address without an IPv6 zone") + } if *allowHTTP && !loopback { fmt.Fprintln(os.Stderr, "--allow-http is deprecated: public panel access now uses HTTPS.") } @@ -130,7 +136,7 @@ func run() error { if err != nil { return err } - server, err := app.NewHTTP(service, web.Files(), *origin, *cert != "" || len(*origin) >= 8 && (*origin)[:8] == "https://") + server, err := app.NewHTTP(service, web.Files(), *origin, *cert != "" || len(*origin) >= 8 && (*origin)[:8] == "https://", trustedProxy) if err != nil { return err } diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 01e6601..862d186 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -9,6 +9,7 @@ import ( "io/fs" "net/http" "net/http/httptest" + "net/netip" "os" "path/filepath" "strings" @@ -30,7 +31,7 @@ func fixture(t *testing.T, mode string) (*Store, *Service, *HTTPServer) { t.Fatal(err) } var files fs.FS = fstest.MapFS{"index.html": {Data: []byte("hello")}, "app.js": {Data: []byte("app")}} - h, err := NewHTTP(service, files, "", false) + h, err := NewHTTP(service, files, "", false, netip.Addr{}) if err != nil { t.Fatal(err) } @@ -212,6 +213,87 @@ func TestLoginRateLimit(t *testing.T) { t.Fatal("login rate limit absent") } } +func TestTrustedProxySeparatesLoginAttempts(t *testing.T) { + _, _, server := fixture(t, "live") + server.trustedProxy = netip.MustParseAddr("127.0.0.1") + const password = "test-password-only-123" + handler := server.Handler() + if w := request(handler, "POST", "/api/setup", map[string]string{"token": server.setupToken, "username": "admin", "password": password}, nil, ""); w.Code != 201 { + t.Fatal(w.Code, w.Body.String()) + } + login := func(remote, password, header string) int { + body, _ := json.Marshal(map[string]string{"username": "admin", "password": password}) + r := httptest.NewRequest("POST", "http://127.0.0.1:8787/api/login", bytes.NewReader(body)) + r.RemoteAddr = remote + r.Header.Set("Content-Type", "application/json") + r.Header.Set("X-Real-IP", header) + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + return w.Code + } + const proxy = "127.0.0.1:30001" + for range 5 { + if status := login(proxy, "wrong", "198.51.100.10"); status != 401 { + t.Fatal("unexpected status before hitting rate limit", status) + } + } + if status := login(proxy, password, "::ffff:198.51.100.10"); status != 429 { + t.Fatal("the mapped IP bypassed the client rate limit", status) + } + if status := login(proxy, password, "198.51.100.11"); status != 200 { + t.Fatal("one proxied client locked out another client", status) + } + + const direct = "198.51.100.20:30002" + for i := range 5 { + if status := login(direct, "wrong", fmt.Sprintf("203.0.113.%d", i+1)); status != 401 { + t.Fatal("unexpected direct login status", status) + } + } + if status := login(direct, password, "203.0.113.100"); status != 429 { + t.Fatal("an untrusted socket peer bypassed its rate limit", status) + } +} + +func TestAuthRateKeyFallsBackToSocketPeer(t *testing.T) { + for _, tc := range []struct { + trusted netip.Addr + headers []string + }{ + {netip.Addr{}, []string{"198.51.100.9"}}, + {netip.MustParseAddr("127.0.0.1"), nil}, + {netip.MustParseAddr("127.0.0.1"), []string{"198.51.100.9", "198.51.100.10"}}, + {netip.MustParseAddr("127.0.0.1"), []string{"198.51.100.9, 198.51.100.10"}}, + {netip.MustParseAddr("127.0.0.1"), []string{"fe80::1%zone"}}, + } { + s := &HTTPServer{trustedProxy: tc.trusted} + r := httptest.NewRequest("POST", "http://127.0.0.1:8787/api/login", nil) + r.RemoteAddr = "127.0.0.1:30001" + for _, header := range tc.headers { + r.Header.Add("X-Real-IP", header) + } + if got := s.authRateKey(r); got != "127.0.0.1" { + t.Errorf("expected socket IP for headers %q, got %s", tc.headers, got) + } + } +} + +func TestProxyIPv6AddressesShareOneSubnetBudget(t *testing.T) { + s := &HTTPServer{auth: NewAuth(false), trustedProxy: netip.MustParseAddr("127.0.0.1")} + r := httptest.NewRequest("POST", "http://127.0.0.1:8787/api/login", nil) + r.RemoteAddr = "127.0.0.1:30001" + for i := range 1024 { + r.Header.Set("X-Real-IP", fmt.Sprintf("2001:db8:1::%x", i+1)) + if allowed := s.auth.allowed(s.authRateKey(r)); allowed != (i < 5) { + t.Fatalf("unexpected admission for address %d", i+1) + } + } + r.Header.Set("X-Real-IP", "2001:db8:2::1") + if !s.auth.allowed(s.authRateKey(r)) { + t.Fatal("one IPv6 subnet locked out another") + } +} + func TestTelemetryBudgetRetentionAndClear(t *testing.T) { store, _, _ := fixture(t, "demo") cfg := DefaultSettings() diff --git a/internal/app/auth.go b/internal/app/auth.go index f218753..2399140 100644 --- a/internal/app/auth.go +++ b/internal/app/auth.go @@ -9,6 +9,7 @@ import ( "fmt" "net" "net/http" + "net/netip" "strconv" "strings" "sync" @@ -41,18 +42,18 @@ func (a *Auth) allowed(ip string) bool { defer a.mu.Unlock() now := time.Now() for k, v := range a.attempts { - if now.Sub(v.Start) > 10*time.Minute { + if now.Sub(v.Start) > time.Minute { delete(a.attempts, k) } } - v := a.attempts[ip] - if now.Sub(v.Start) > time.Minute { + v, found := a.attempts[ip] + if !found { + if len(a.attempts) >= 1024 { + return false + } v = attempt{Start: now} } v.Count++ - if len(a.attempts) >= 1024 && v.Count == 1 { - return false - } a.attempts[ip] = v return v.Count <= 5 } @@ -100,12 +101,31 @@ func (a *Auth) logout(w http.ResponseWriter, r *http.Request) { } http.SetCookie(w, &http.Cookie{Name: "wgs_session", Value: "", Path: "/", HttpOnly: true, Secure: a.Secure, SameSite: http.SameSiteStrictMode, MaxAge: -1}) } -func remoteIP(r *http.Request) string { +func (s *HTTPServer) authRateKey(r *http.Request) string { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return r.RemoteAddr } - return host + peer, err := netip.ParseAddr(host) + if err != nil { + return host + } + peer = peer.Unmap() + source := peer + if s.trustedProxy.IsValid() && peer == s.trustedProxy { + // The configured proxy must overwrite the header with one address. + values := r.Header.Values("X-Real-IP") + if len(values) == 1 { + if client, err := netip.ParseAddr(strings.TrimSpace(values[0])); err == nil && client.Zone() == "" { + source = client.Unmap() + } + } + } + if source.Is6() { + // One IPv6 subnet can supply enough addresses to exhaust the table. + return netip.PrefixFrom(source, 64).Masked().String() + } + return source.String() } func hashPassword(password string) (string, error) { if len(password) < 12 || len(password) > 256 { diff --git a/internal/app/client_options_test.go b/internal/app/client_options_test.go index dda2d24..257d20e 100644 --- a/internal/app/client_options_test.go +++ b/internal/app/client_options_test.go @@ -60,6 +60,7 @@ func TestAdvancedClientOptionsRejectInvalidInput(t *testing.T) { for _, opts := range []CreatePeerOptions{ {Address: "10.64.0.1/32"}, {Address: "10.64.0.0/32"}, {Address: "10.64.0.255/32"}, {Address: "10.64.0.2/32"}, {Address: "192.168.1.2/32"}, {Address: "10.64.0.40/24"}, {ClientConfigOptions: ClientConfigOptions{DNS: ptr("9.9.9.9\nPostUp = bad")}}, + {ClientConfigOptions: ClientConfigOptions{DNS: ptr("fe80::1%eth0\nPreUp = bad")}}, {ClientConfigOptions: ClientConfigOptions{Endpoint: "bad\nPostUp=bad"}}, {ClientConfigOptions: ClientConfigOptions{AllowedIPs: "0.0.0.0/0\nPostUp=bad"}}, {ClientConfigOptions: ClientConfigOptions{Port: ptr(0)}}, @@ -89,6 +90,48 @@ func TestAdvancedClientOptionsRejectInvalidInput(t *testing.T) { } } +func TestClientExportsRejectStoredDNSWithLineBreaks(t *testing.T) { + store, _, h := fixture(t, "demo") + handler := h.Handler() + cookie, csrf := demoLogin(t, handler) + server, err := store.Server() + if err != nil { + t.Fatal(err) + } + peers, err := store.Peers() + if err != nil { + t.Fatal(err) + } + malicious := "fe80::1%eth0\r\nPreUp = false" + server.DNS = malicious + if w := request(handler, "PUT", "/api/server", server, cookie, csrf); w.Code != 400 { + t.Fatal("server DNS accepted a configuration directive", w.Code) + } + if err := server.validateInterfaceConfig(); err != nil { + t.Fatal("legacy client DNS should not block the managed VPN", err) + } + + for _, useOverride := range []bool{false, true} { + if useOverride { + server.DNS = "9.9.9.9, fe80::1%eth0" + peers[0].ClientConfig = &ClientConfigOptions{DNS: &malicious} + } + // Simulate settings persisted by an older version. + if err := store.SaveControl(server, peers); err != nil { + t.Fatal(err) + } + for _, format := range []string{"config", "qr"} { + if w := request(handler, "GET", "/api/peers/"+peers[0].ID+"/"+format, nil, cookie, ""); w.Code != 400 { + t.Errorf("stored DNS was exported as %s (override=%t), status %d", format, useOverride, w.Code) + } + } + } + w := request(handler, "GET", "/api/peers/"+peers[1].ID+"/config", nil, cookie, "") + if w.Code != 200 || !strings.Contains(w.Body.String(), "DNS = "+server.DNS+"\n") { + t.Fatal("ordinary IPv4 and scoped IPv6 DNS should still export", w.Code) + } +} + func TestCreateAdvancedClientAPI(t *testing.T) { store, _, h := fixture(t, "demo") cookie, csrf := demoLogin(t, h.Handler()) diff --git a/internal/app/http.go b/internal/app/http.go index e0c33ae..f166ec5 100644 --- a/internal/app/http.go +++ b/internal/app/http.go @@ -12,6 +12,7 @@ import ( "io/fs" "net" "net/http" + "net/netip" "net/url" "os" "path/filepath" @@ -28,10 +29,11 @@ type HTTPServer struct { mode, setupToken, origin string files fs.FS access panelPolicy + trustedProxy netip.Addr } -func NewHTTP(service *Service, files fs.FS, origin string, secure bool) (*HTTPServer, error) { - s := &HTTPServer{service: service, store: service.store, auth: NewAuth(secure), mode: service.mode, origin: origin, files: files} +func NewHTTP(service *Service, files fs.FS, origin string, secure bool, trustedProxy netip.Addr) (*HTTPServer, error) { + s := &HTTPServer{service: service, store: service.store, auth: NewAuth(secure), mode: service.mode, origin: origin, files: files, trustedProxy: trustedProxy.Unmap()} policy, err := readPanelAccess(s.store.dir) if err != nil { return nil, err @@ -174,7 +176,7 @@ func (s *HTTPServer) setup(w http.ResponseWriter, r *http.Request) { apiError(w, 409, "Setup already completed") return } - if !s.auth.allowed(remoteIP(r)) { + if !s.auth.allowed(s.authRateKey(r)) { apiError(w, 429, "Too many attempts; wait one minute") return } @@ -216,7 +218,7 @@ func (s *HTTPServer) setup(w http.ResponseWriter, r *http.Request) { jsonResponse(w, 201, map[string]string{"csrf": user.CSRF}) } func (s *HTTPServer) login(w http.ResponseWriter, r *http.Request) { - if !s.auth.allowed(remoteIP(r)) { + if !s.auth.allowed(s.authRateKey(r)) { apiError(w, 429, "Too many attempts; wait one minute") return } @@ -451,7 +453,7 @@ func (s *HTTPServer) password(w http.ResponseWriter, r *http.Request) { apiError(w, 409, "Password cannot be changed in demo mode") return } - if !s.auth.allowed(remoteIP(r)) { + if !s.auth.allowed(s.authRateKey(r)) { apiError(w, 429, "Wait one minute") return } diff --git a/internal/app/internet.go b/internal/app/internet.go index 60be9e7..db47d2b 100644 --- a/internal/app/internet.go +++ b/internal/app/internet.go @@ -10,7 +10,9 @@ import ( "os/exec" "path/filepath" "runtime" + "slices" "strings" + "time" ) const internetTable = "wgsimple_internet" @@ -25,7 +27,7 @@ func PrepareInternet(ctx context.Context, store *Store, configDir string) (resul if err != nil { return err } - if err = s.Validate(); err != nil { + if err = s.validateInterfaceConfig(); err != nil { return err } peers, err := store.Peers() @@ -74,6 +76,8 @@ func PrepareInternet(ctx context.Context, store *Store, configDir string) (resul return errors.New("NAT preflight failed; no network changes applied") } engine := &LiveEngine{ConfigDir: configDir} + now := time.Now() + activePeers := unexpiredPeers(peers, now) // A stopped configuration may be restored only when it matches our database. path := filepath.Join(configDir, s.Interface+".conf") if st, e := os.Lstat(path); e == nil { @@ -85,15 +89,15 @@ func PrepareInternet(ctx context.Context, store *Store, configDir string) (resul if e != nil { return e } - if string(b) != serverConfig(s, peers, true) { + if !matchesStoppedConfig(string(b), s, peers, now) { return errors.New("Stopped WireGuard configuration differs from saved settings; import/reconcile it before automatic startup") } - if e = startManagedInterface(ctx, s, peers, command); e != nil { + if e = startManagedInterface(ctx, s, activePeers, command); e != nil { return e } } } - if err = engine.Apply(ctx, s, peers); err != nil { + if err = engine.Apply(ctx, s, activePeers); err != nil { return err } oldForward, err := os.ReadFile("/proc/sys/net/ipv4/ip_forward") @@ -138,6 +142,15 @@ func PrepareInternet(ctx context.Context, store *Store, configDir string) (resul return nil } +func matchesStoppedConfig(raw string, s Server, peers []Peer, now time.Time) bool { + // The previous run may have omitted expired peers before the panel + // recorded their expiry. Every other byte still has to match. + peers = slices.DeleteFunc(slices.Clone(peers), func(p Peer) bool { + return p.expiredAt(now) && !strings.Contains(raw, "\nPublicKey = "+p.PublicKey+"\n") + }) + return raw == serverConfig(s, peers, true) +} + // nftables 1.0.2 omits table comments from JSON even when the kernel stores // them. Recover only the reserved table's ownership marker from its read-only // native listing; never infer ownership from a table name alone. diff --git a/internal/app/model.go b/internal/app/model.go index 1eb6df2..35103e8 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -70,6 +70,14 @@ func validName(s string) bool { } func (s Server) Validate() error { + if err := s.validateInterfaceConfig(); err != nil { + return err + } + return validateDNS(s.DNS) +} + +// DNS is used only in client exports, never in the managed interface config. +func (s Server) validateInterfaceConfig() error { if !validName(s.Name) || !ValidInterface(s.Interface) { return errors.New("Invalid server or interface name") } @@ -97,14 +105,6 @@ func (s Server) Validate() error { } } } - for _, d := range strings.Split(s.DNS, ",") { - if s.DNS == "" { - break - } - if _, err := netip.ParseAddr(strings.TrimSpace(d)); err != nil { - return errors.New("DNS addresses must be IP addresses") - } - } if err := validateCIDRs(s.AllowedIPs); err != nil { return err } @@ -117,6 +117,23 @@ func (s Server) Validate() error { return nil } +func validateDNS(dns string) error { + if dns == "" { + return nil + } + // ParseAddr permits arbitrary characters in IPv6 zones. Exports require + // each setting to stay on a single line. + if strings.ContainsAny(dns, "\r\n\x00") { + return errors.New("DNS addresses must be IP addresses") + } + for _, value := range strings.Split(dns, ",") { + if _, err := netip.ParseAddr(strings.TrimSpace(value)); err != nil { + return errors.New("DNS addresses must be IP addresses") + } + } + return nil +} + type Peer struct { ID string `json:"id"` Name string `json:"name"` @@ -130,6 +147,10 @@ type Peer struct { ClientConfig *ClientConfigOptions `json:"clientConfig,omitempty"` } +func (p Peer) expiredAt(now time.Time) bool { + return p.ExpiresAt != nil && !p.ExpiresAt.After(now) +} + type PeerView struct { ID string `json:"id"` Name string `json:"name"` @@ -262,6 +283,9 @@ func clientConfig(s Server, p Peer) (string, error) { if s.Endpoint == "" { return "", errors.New("Set the server endpoint first") } + if err := validateDNS(s.DNS); err != nil { + return "", err + } psk := "" if p.PresharedKey != "" { psk = "PresharedKey = " + p.PresharedKey + "\n" diff --git a/internal/app/service.go b/internal/app/service.go index c6a0663..6ea6d3c 100644 --- a/internal/app/service.go +++ b/internal/app/service.go @@ -390,7 +390,7 @@ func (s *Service) ChangePeer(ctx context.Context, id string, enabled *bool, remo continue } if enabled != nil { - if *enabled && p.ExpiresAt != nil && p.ExpiresAt.Before(time.Now()) { + if *enabled && p.expiredAt(time.Now()) { return errors.New("An expired client cannot be enabled") } p.Enabled = *enabled @@ -461,7 +461,7 @@ func (s *Service) expire(ctx context.Context) { return } for _, p := range peers { - if p.Enabled && p.ExpiresAt != nil && p.ExpiresAt.Before(time.Now()) { + if p.Enabled && p.expiredAt(time.Now()) { off := false if err = s.ChangePeer(ctx, p.ID, &off, false); err == nil { s.Event("info", "peer.expire", "Client expired: "+p.Name) diff --git a/internal/app/tls_test.go b/internal/app/tls_test.go index 39adb48..6257ed3 100644 --- a/internal/app/tls_test.go +++ b/internal/app/tls_test.go @@ -13,6 +13,7 @@ import ( "net" "net/http" "net/http/httptest" + "net/netip" "os" "path/filepath" "runtime" @@ -178,7 +179,7 @@ func TestServeHTTPSSetupLoginAndPlaintextRejection(t *testing.T) { transport := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}} defer transport.CloseIdleConnections() client := &http.Client{Transport: transport, Timeout: time.Second} - handler, err := NewHTTP(service, base.files, "", cert != "") + handler, err := NewHTTP(service, base.files, "", cert != "", netip.Addr{}) if err != nil { t.Fatal(err) } diff --git a/internal/app/wireguard.go b/internal/app/wireguard.go index 776dda0..26a2ecc 100644 --- a/internal/app/wireguard.go +++ b/internal/app/wireguard.go @@ -11,6 +11,7 @@ import ( "os/exec" "path/filepath" "runtime" + "slices" "strconv" "strings" "time" @@ -147,11 +148,18 @@ func serverConfig(s Server, peers []Peer, quick bool) string { } return b.String() } + +func unexpiredPeers(peers []Peer, now time.Time) []Peer { + return slices.DeleteFunc(slices.Clone(peers), func(p Peer) bool { + return p.expiredAt(now) + }) +} + func (l *LiveEngine) Apply(ctx context.Context, s Server, peers []Peer) error { if runtime.GOOS != "linux" { return errors.New("WireGuard changes are disabled on this computer") } - if err := s.Validate(); err != nil { + if err := s.validateInterfaceConfig(); err != nil { return err } if !ValidInterface(s.Interface) { @@ -199,6 +207,7 @@ func (l *LiveEngine) Apply(ctx context.Context, s Server, peers []Peer) error { return errors.New("Change the running interface address/MTU during maintenance") } } + peers = unexpiredPeers(peers, time.Now()) if err := atomicFile(path, []byte(serverConfig(s, peers, true)), 0600); err != nil { return errors.New("Could not save WireGuard configuration") } @@ -231,6 +240,7 @@ func (l *LiveEngine) Apply(ctx context.Context, s Server, peers []Peer) error { // Invoke each tool directly: wg-quick's nested AppArmor profile transitions can // fail under NoNewPrivileges on Ubuntu. Keep the service's protections intact. func startManagedInterface(ctx context.Context, s Server, peers []Peer, run func(context.Context, string, []string, string) ([]byte, error)) error { + peers = unexpiredPeers(peers, time.Now()) prefix, err := netip.ParsePrefix(s.Address) if err != nil { return err @@ -254,7 +264,7 @@ func startManagedInterface(ctx context.Context, s Server, peers []Peer, run func args []string input string }{ - {"wg", []string{"setconf", s.Interface, "/dev/stdin"}, serverConfig(s, peers, false)}, + {"wg", []string{"setconf", s.Interface, "/dev/stdin"}, serverConfig(s, unexpiredPeers(peers, time.Now()), false)}, {"ip", []string{"address", "add", s.Address, "dev", s.Interface}, ""}, {"ip", []string{"link", "set", "mtu", strconv.Itoa(s.MTU), "up", "dev", s.Interface}, ""}, } diff --git a/internal/app/wireguard_start_test.go b/internal/app/wireguard_start_test.go index f7189a0..970b2ab 100644 --- a/internal/app/wireguard_start_test.go +++ b/internal/app/wireguard_start_test.go @@ -6,6 +6,7 @@ import ( "reflect" "strings" "testing" + "time" ) func TestManagedStartAndPartialFailureCleanup(t *testing.T) { @@ -42,6 +43,60 @@ func TestManagedStartAndPartialFailureCleanup(t *testing.T) { } } } + +func TestManagedStartOmitsExpiredPeers(t *testing.T) { + s := DefaultServer("wg0") + past := time.Now().Add(-time.Hour) + future := time.Now().Add(time.Hour) + expiresDuringStart := future + peers := []Peer{ + {Enabled: true, Address: "192.168.0.0/24", PublicKey: "expired", ExpiresAt: &past}, + {Enabled: true, Address: "10.64.0.2/32", PublicKey: "active", ExpiresAt: &future}, + {Enabled: false, Address: "10.64.0.3/32", PublicKey: "disabled"}, + {Enabled: true, Address: "10.64.0.4/32", PublicKey: "expires-during-start", ExpiresAt: &expiresDuringStart}, + } + var config string + err := startManagedInterface(context.Background(), s, peers, func(_ context.Context, name string, args []string, input string) ([]byte, error) { + if name == "ip" && args[0] == "link" && args[1] == "add" { + expiresDuringStart = past + } + if name == "wg" { + config = input + } + return nil, nil + }) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(config, "PublicKey = active\n") || strings.Contains(config, "PublicKey = expired\n") || strings.Contains(config, "PublicKey = disabled\n") || strings.Contains(config, "PublicKey = expires-during-start\n") { + t.Fatal("managed start installed the wrong peer set") + } +} + +func TestStoppedConfigMatchesAcrossExpiryWindows(t *testing.T) { + s := DefaultServer("wg0") + now := time.Now() + first := now.Add(-2 * time.Hour) + second := now.Add(-time.Hour) + peers := []Peer{ + {Enabled: true, Address: "10.64.0.2/32", PublicKey: "first", ExpiresAt: &first}, + {Enabled: true, Address: "10.64.0.3/32", PublicKey: "second", ExpiresAt: &second}, + {Enabled: true, Address: "10.64.0.4/32", PublicKey: "active"}, + } + for _, saved := range [][]Peer{peers, peers[1:], peers[2:]} { + if !matchesStoppedConfig(serverConfig(s, saved, true), s, peers, now) { + t.Errorf("canonical config with %d peers was rejected", len(saved)) + } + } + for _, raw := range []string{ + serverConfig(s, peers[:2], true), + strings.Replace(serverConfig(s, peers, true), "10.64.0.4/32", "10.64.0.5/32", 1), + } { + if matchesStoppedConfig(raw, s, peers, now) { + t.Error("stopped configuration with unrelated drift was accepted") + } + } +} func TestManagedStartDoesNotSilentlyOmitRoutedSubnets(t *testing.T) { s := DefaultServer("wg0") err := startManagedInterface(context.Background(), s, []Peer{{Enabled: true, Address: "192.168.0.0/24"}}, func(context.Context, string, []string, string) ([]byte, error) {