Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion cmd/wgsimple/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"flag"
"fmt"
"net/netip"
"os"
"os/signal"
"path/filepath"
Expand All @@ -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")
Expand Down Expand Up @@ -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.")
}
Expand Down Expand Up @@ -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
}
Expand Down
84 changes: 83 additions & 1 deletion internal/app/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io/fs"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"path/filepath"
"strings"
Expand All @@ -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)
}
Expand Down Expand Up @@ -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()
Expand Down
36 changes: 28 additions & 8 deletions internal/app/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net"
"net/http"
"net/netip"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down
43 changes: 43 additions & 0 deletions internal/app/client_options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)}},
Expand Down Expand Up @@ -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())
Expand Down
12 changes: 7 additions & 5 deletions internal/app/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"io/fs"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"path/filepath"
Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
21 changes: 17 additions & 4 deletions internal/app/internet.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import (
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"time"
)

const internetTable = "wgsimple_internet"
Expand All @@ -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()
Expand Down Expand Up @@ -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 {
Expand All @@ -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")
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading