From f176a01c30b2a13a75b63ebddcae7cdf6198c286 Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sat, 17 Oct 2026 15:44:07 +0500 Subject: [PATCH 1/2] Make the code do what the documentation promised Three things the README has been claiming since the tier system landed, and which no test caught because nobody checked the claims against the code: 1. "RATE_LIMIT_RPS: admin requests per second per client". There was one token bucket for the whole process. One noisy client spent everyone's budget: two administrators sharing a dashboard, or a dozen phones behind one carrier NAT, could throttle each other. rateLimiterSet now keys buckets by client IP and sweeps idle ones so memory stays bounded, with a hard ceiling that drops the least recently used half if a flood of distinct addresses outruns the sweep. The same bucket guarded the tunnel, the CONNECT path and the forward path, so all three gained per-client limits too. The tunnel handler now resolves the client IP before it refuses anything, because a refusal must not depend on reaching the line that needs the key. 2. "Bandwidth 1 / 5 / 50 Mbps" per tier. BandwidthMbps has been stored in SQLite since the beginning and read exactly never: relay() was a plain io.Copy in both directions, so the Free tier ran at line speed like every other tier. pacer.go is the token bucket that finally reads it, one per direction, with a one-second burst so short transfers are not punished. A nil pacer is the Unlimited tier and costs nothing to check. The first implementation credited the sleeping interval as idle time, which paid each debt twice and ran the link at twice the configured rate. The test asserting 256 KiB at 1 Mbps takes at least 900ms is what caught it. 3. Configuration precedence. Resolution was defaults < config.json < environment < database, so editing PROXY_PASS in .env did nothing on any install where somebody had ever saved settings in the dashboard -- and since .env is the documented way to configure the service, the natural conclusion was that the deployment ignored you. LoadConfig now records which variables were explicitly set and applyDBOverrides skips those keys. The dashboard still beats config.json, because clicking save is a statement of intent made a moment ago. Also: a build-only Docker workflow. The image was the one artifact people deploy and nothing had ever built it. It never pushes -- no registry, no credentials, no tags -- and the smoke test is the part worth having: it runs the image, waits for /health, asserts the response carries no version or uptime, asserts /metrics is 401 without credentials, and checks xray is in the image so enabling REALITY later cannot fail at startup. Single architecture on purpose; the xray pin changes rarely and verifying both legs on every run doubles the build for no extra signal. Verified live, not just by unit test: a 20 MB download through a single-credential session runs at 77 MB/s, and the same transfer as a Free-tier database user runs at 148 KB/s -- about 1.19 Mbps, which is 1 Mbps plus the documented one-second burst. After saving a different password from the dashboard and restarting with .env unchanged, the .env password works and the stored one is refused. --- .github/workflows/docker.yml | 93 +++++++ README.md | 47 ++-- limits_test.go | 454 +++++++++++++++++++++++++++++++++++ main.go | 260 ++++++++++++++++---- multiplex.go | 11 +- multiplex_test.go | 6 +- pacer.go | 110 +++++++++ 7 files changed, 910 insertions(+), 71 deletions(-) create mode 100644 .github/workflows/docker.yml create mode 100644 limits_test.go create mode 100644 pacer.go diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..109a9b9 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,93 @@ +# Builds the image on CI to prove the Dockerfile still works. +# +# This never pushes anywhere. There is no registry, no credentials and no tag to +# manage: the only output is a build that either succeeds or fails, which is the +# thing that was previously unverified. The xray download and its checksum are +# the fragile part -- a moved release URL, a re-signed artifact or a changed +# base image breaks the build -- and none of that shows up in `go test`. +# +# Single architecture on purpose. The Dockerfile resolves a different xray per +# TARGETARCH, and verifying both on every run would double the build time to +# re-check something that changes only when the pin does. Change the pin and +# both paths are exercised by the local build on the target machine. + +name: Docker + +on: + push: + branches: ["main"] + paths: + - "Dockerfile" + - ".dockerignore" + - "go.mod" + - "go.sum" + - "*.go" + - "web/**" + - ".github/workflows/docker.yml" + pull_request: + paths: + - "Dockerfile" + - ".dockerignore" + - "go.mod" + - "go.sum" + - "*.go" + - "web/**" + - ".github/workflows/docker.yml" + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@v4 + + - name: Set up Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build the image + uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/amd64 + # load, not push: the image has to land in the local daemon so the + # smoke test below can run it. Nothing leaves the runner. + load: true + push: false + tags: socks5-proxy:ci + cache-from: type=gha + cache-to: type=gha,mode=max + + # A successful build says the image assembles. This says it runs: the + # health endpoint answers, and the diagnostics that used to identify a + # deployment are behind auth. + - name: Smoke test the image + run: | + set -euo pipefail + docker run -d --name ci-test -p 18080:8080 socks5-proxy:ci + for i in $(seq 1 30); do + if curl -fsS http://127.0.0.1:18080/health >/dev/null 2>&1; then break; fi + if [ "$i" = "30" ]; then + echo "server never became healthy; container log:" + docker logs ci-test + exit 1 + fi + sleep 1 + done + echo " /health: $(curl -fsS http://127.0.0.1:18080/health)" + health=$(curl -fsS http://127.0.0.1:18080/health) + case "$health" in + *version*|*uptime*) echo "FAIL: /health leaks version or uptime: $health"; exit 1 ;; + esac + code=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:18080/metrics) + echo " /metrics: $code (want 401 without credentials)" + if [ "$code" != "401" ]; then + echo "FAIL: the metrics dashboard is reachable without credentials" + exit 1 + fi + # xray must be present in the image even with REALITY disabled, + # otherwise enabling it on a real host fails at startup. + docker exec ci-test xray version | head -1 + docker rm -f ci-test \ No newline at end of file diff --git a/README.md b/README.md index 276cf1c..edb5a3c 100644 --- a/README.md +++ b/README.md @@ -95,32 +95,31 @@ docker run --rm --entrypoint xray socks5-proxy x25519 # Password (PublicKey): ... -> what clients configure as "public key" ``` -**Precedence gotcha worth knowing.** The server resolves configuration in this -order, last one winning: +**How precedence actually resolves**, last one winning: ``` -built-in defaults < config.json < environment < database +built-in defaults < config.json < database < environment ``` -The database is last because the admin dashboard saves settings from the UI, and -it only ever holds those 10 keys: `max_connections`, `proxy_user`, `proxy_pass`, -`auth_enabled`, `admin_username`, `admin_pass`, `admin_auth_enabled`, -`security_headers_enabled`, `rate_limit_enabled`, `rate_limit_rps`. So on an -install where somebody has already saved settings in the dashboard, **a new -`PROXY_PASS` in `.env` is silently ignored on restart** — the stored value wins. -Either change the password from the dashboard, or clear the stored keys once: +The database holds only the 10 settings the dashboard can save: `max_connections`, +`proxy_user`, `proxy_pass`, `auth_enabled`, `admin_username`, `admin_pass`, +`admin_auth_enabled`, `security_headers_enabled`, `rate_limit_enabled` and +`rate_limit_rps`. The environment sits above it, so an explicit `.env` value is +never quietly overwritten by something saved from the browser three weeks ago — +that used to happen, and it made editing `.env` look broken. + +To hand a setting back to the database instead, unset it from `.env` and change +it in the dashboard. To clear stored settings entirely, stop the container first +and remove all three files, since SQLite runs in WAL mode: ```bash -docker exec -it sh -c 'rm -f /app/data/socks5.db /app/data/socks5.db-wal /app/data/socks5.db-shm && echo cleared' +docker compose down +rm -f data/socks5.db data/socks5.db-wal data/socks5.db-shm ``` -All three files matter: SQLite runs in WAL mode, so deleting only `socks5.db` -leaves a write-ahead log that gets replayed on the next open and puts your saved -settings straight back. - -That also drops users and usage history, so copy `data/socks5.db` out first if -you want them. `TUNNEL_*`, `REALITY_*`, timeouts and limits are never stored, so -those always come from your file or environment. +That also drops users and usage history, so copy `data/socks5.db` out first if you +want them. `TUNNEL_*`, `REALITY_*`, timeouts and limits are never stored, so they +always come from your file or environment. ### Docker Compose @@ -292,6 +291,9 @@ other REALITY-capable client can import the same parameters instead: Give each device its own UUID (`xray uuid`, then list them in `REALITY_CLIENT_IDS`) so one can be revoked without disturbing the others. +`REALITY_BIND` defaults to `0.0.0.0:443`, which is IPv4 only. On an IPv6-only +host set it to `[::]:443`. + Pick the camouflage site with care: it must speak TLS 1.3 with X25519, be reachable from the server, and resolve to a real CDN. Xray itself warns against apple/icloud targets, and a target that is an obvious outlier can get your IP @@ -351,7 +353,7 @@ Edit `config.json` or use environment variables (env vars override config file): | `IDLE_TIMEOUT_SECONDS` | 300 | Deadline on an **established** proxy session. Raise it if clients idle longer | | `SECURITY_HEADERS_ENABLED` | true | Enable security headers | | `RATE_LIMIT_ENABLED` | true | Enable rate limiting on admin endpoints | -| `RATE_LIMIT_RPS` | 30 | Admin requests per second per client | +| `RATE_LIMIT_RPS` | 30 | Admin requests per second **per client**, keyed by IP. One client cannot spend another's budget. Clients behind one carrier NAT share a bucket | | `TUNNEL_ENABLED` | false | Enable the WebSocket tunnel. Refused at startup without a token | | `TUNNEL_TOKEN` | empty | Shared secret for the tunnel path and the client | | `TUNNEL_PATH` | /api/v1/tunnel | Tunnel URL path | @@ -471,6 +473,13 @@ go test -run TestRealityEndToEnd -v ./... # needs xray on PATH | Pro | 20 | 50 Mbps | Unlimited | 90 days | | Unlimited | Unlimited | Unlimited | Unlimited | Never | +Bandwidth is enforced per direction on every session: a Free-tier session moves +at most 1 Mbps each way, with a one-second burst allowance so short transfers +are not penalised. A user's limit is captured when the account is created, so +changing a tier later does not retroactively re-rate existing accounts. Sessions +authenticated with the single `PROXY_USER`/`PROXY_PASS` pair, and the HTTP proxy +paths that share it, run unrestricted — there is no per-user tier to apply. + ## API Endpoints Reachable in both modes; in single-port mode they are all on the one port. diff --git a/limits_test.go b/limits_test.go new file mode 100644 index 0000000..ccc7cb1 --- /dev/null +++ b/limits_test.go @@ -0,0 +1,454 @@ +package main + +import ( + "bytes" + "io" + "log/slog" + "net" + "path/filepath" + "strconv" + "testing" + "time" +) + +// ─── Per-client rate limiting ─────────────────────────────────────────────── + +// The documented behaviour is per client. Under the single shared bucket this +// used to be, one address could spend everyone's budget. +func TestRateLimiterSetIsolatesClients(t *testing.T) { + set := newRateLimiterSet(5) + + for range 5 { + if !set.allow("10.0.0.1") { + t.Fatal("first client's fifth request was refused") + } + } + if set.allow("10.0.0.1") { + t.Error("sixth request for the same client should be refused at 5 rps") + } + + // The whole point: a different client is unaffected by the first one's burst. + for i := range 5 { + if !set.allow("10.0.0.2") { + t.Fatalf("second client refused on request %d while another client was flooding", i+1) + } + } +} + +func TestRateLimiterSetRefillsOverTime(t *testing.T) { + set := newRateLimiterSet(5) + for range 5 { + set.allow("10.0.0.1") + } + if set.allow("10.0.0.1") { + t.Fatal("bucket should be empty") + } + // Refill is time-based, not reset-on-use: nudge the clock rather than sleep. + set.mu.Lock() + set.buckets["10.0.0.1"].last = time.Now().Add(-time.Second) + set.mu.Unlock() + + if !set.allow("10.0.0.1") { + t.Error("bucket did not refill after a second") + } +} + +// Buckets must not accumulate for every address the proxy has ever seen. +func TestRateLimiterSetSweepsIdleBuckets(t *testing.T) { + set := newRateLimiterSet(5) + for i := range 10 { + set.allow(strconv.Itoa(i)) + } + if len(set.buckets) != 10 { + t.Fatalf("got %d buckets, want 10", len(set.buckets)) + } + + set.mu.Lock() + // Pretend the last sweep was long ago and nobody has been back since. + set.lastSweep = time.Now().Add(-time.Hour) + for _, b := range set.buckets { + b.lastSeen = time.Now().Add(-rateLimiterIdle - time.Minute) + } + set.mu.Unlock() + + // The sweep happens inside allow(). The returning client gets a fresh, + // full bucket, which is the point of sweeping rather than deleting on use. + if !set.allow("10.0.0.9") { + t.Fatal("a client returning after a sweep should start with a full budget") + } + if got := len(set.buckets); got != 1 { + t.Errorf("got %d buckets after a sweep, want only the client that just came back", got) + } +} + +// A change in the dashboard must reach the limiter without a restart. +func TestRateLimiterSetRPSChangeApplies(t *testing.T) { + set := newRateLimiterSet(2) + for range 2 { + set.allow("10.0.0.1") + } + if set.allow("10.0.0.1") { + t.Fatal("third request should be refused at 2 rps") + } + + // The drained client keeps its debt: a higher limit is not a free refill. + if set.allow("10.0.0.1") { + t.Error("raising the limit should not hand the drained client free tokens") + } + + // A client that has not spent anything now gets the new rate. + set.setRPS(10) + allowed := 0 + for range 10 { + if set.allow("10.0.0.3") { + allowed++ + } + } + if allowed != 10 { + t.Errorf("new client got %d of 10 immediate requests after setRPS(10)", allowed) + } +} + +// ─── Configuration precedence ─────────────────────────────────────────────── + +// Editing .env and restarting used to change nothing whenever the dashboard had +// ever saved that setting. +func TestApplyDBOverridesEnvironmentWins(t *testing.T) { + cfg := DefaultConfig() + cfg.Username = "env-user" + cfg.Password = "env-pass" + cfg.envSet = map[string]bool{"proxy_user": true, "proxy_pass": true} + + dbCfg := map[string]string{ + "proxy_user": "db-user", + "proxy_pass": "db-pass", + "admin_username": "db-admin", + "max_connections": "500", + } + + applied := applyDBOverrides(&cfg, dbCfg) + + if cfg.Username != "env-user" || cfg.Password != "env-pass" { + t.Errorf("environment was overwritten by the database: %s/%s", cfg.Username, cfg.Password) + } + // Keys the environment did not mention still come from the database. + if cfg.AdminUser != "db-admin" { + t.Errorf("admin_username = %q, want the stored value", cfg.AdminUser) + } + if cfg.MaxConns != 500 { + t.Errorf("max_connections = %d, want the stored 500", cfg.MaxConns) + } + for _, key := range []string{"proxy_user", "proxy_pass"} { + if contains(applied, key) { + t.Errorf("%s was reported as applied from the database, but the environment set it", key) + } + } + if !contains(applied, "admin_username") || !contains(applied, "max_connections") { + t.Errorf("applied = %v, want the keys that were not set in the environment", applied) + } +} + +func TestApplyDBOverridesDatabaseWinsWhenEnvUnset(t *testing.T) { + cfg := DefaultConfig() + dbCfg := map[string]string{"proxy_pass": "db-pass", "auth_enabled": "false", "rate_limit_rps": "99"} + + applyDBOverrides(&cfg, dbCfg) + + if cfg.Password != "db-pass" { + t.Errorf("password = %q, want the stored value when the environment is silent", cfg.Password) + } + if cfg.AuthEnabled { + t.Error("auth_enabled = true, want the stored false") + } + if cfg.RateLimitRPS != 99 { + t.Errorf("rate_limit_rps = %d, want the stored 99", cfg.RateLimitRPS) + } +} + +// Every documented setting must be tracked, or the precedence rule has a hole. +func TestEveryDatabaseOverridableKeyIsTrackedFromEnv(t *testing.T) { + envFor := map[string]string{ + "max_connections": "MAX_CONNECTIONS", + "proxy_user": "PROXY_USER", + "proxy_pass": "PROXY_PASS", + "auth_enabled": "AUTH_ENABLED", + "admin_auth_enabled": "ADMIN_AUTH_ENABLED", + "admin_username": "ADMIN_USER", + "admin_pass": "ADMIN_PASS", + "security_headers_enabled": "SECURITY_HEADERS_ENABLED", + "rate_limit_enabled": "RATE_LIMIT_ENABLED", + "rate_limit_rps": "RATE_LIMIT_RPS", + } + for _, env := range envFor { + t.Setenv(env, "1") + } + cfgFile := writeTempConfig(t, `{}`) + cfg, err := LoadConfig(cfgFile) + if err != nil { + t.Fatalf("LoadConfig: %v", err) + } + for key := range envFor { + if !cfg.envSet[key] { + t.Errorf("%s is overridable from the database but its environment variable was not recorded", key) + } + } +} + +// ─── Bandwidth pacing ─────────────────────────────────────────────────────── + +func TestPacerCapsThroughput(t *testing.T) { + payload := bytes.Repeat([]byte("x"), 256<<10) // 256 KiB + var sink bytes.Buffer + + start := time.Now() + n, err := copyPaced(&sink, bytes.NewReader(payload), newPacer(1)) + if err != nil { + t.Fatalf("copyPaced: %v", err) + } + elapsed := time.Since(start) + + if n != int64(len(payload)) { + t.Fatalf("copied %d bytes, want %d", n, len(payload)) + } + if !bytes.Equal(sink.Bytes(), payload) { + t.Fatal("pacing changed the byte stream, which must stay transparent") + } + + // 256 KiB at 1 Mbps is 2.05s of transfer time. The first second comes from + // the burst allowance, so the floor is a little under that. + floor := 900 * time.Millisecond + if elapsed < floor { + t.Errorf("256 KiB through a 1 Mbps pacer took %s, want at least %s: the limit is not being applied", elapsed, floor) + } +} + +func TestPacerNilMeansUnlimited(t *testing.T) { + payload := bytes.Repeat([]byte("x"), 512<<10) + var sink bytes.Buffer + + start := time.Now() + if _, err := copyPaced(&sink, bytes.NewReader(payload), newPacer(-1)); err != nil { + t.Fatalf("copyPaced: %v", err) + } + // The Unlimited tier must not pay for a limit that does not exist. Half a + // megabyte at 1 Mbps would be four seconds; allow a very generous margin and + // still catch an accidentally applied pacer. + if elapsed := time.Since(start); elapsed > 500*time.Millisecond { + t.Errorf("unlimited transfer took %s, want well under 500ms: a pacer is active", elapsed) + } + if sink.Len() != len(payload) { + t.Errorf("copied %d bytes, want %d", sink.Len(), len(payload)) + } +} + +// The tier table advertises bandwidth; this proves a Free-tier session is +// actually held to it, through the real SOCKS5 path. +func TestFreeTierSessionIsPaced(t *testing.T) { + store, err := NewStore(filepath.Join(t.TempDir(), "pace.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatalf("NewStore: %v", err) + } + defer store.Close() + + user, err := store.CreateUser("pu", "pp", "free") + if err != nil { + t.Fatalf("CreateUser: %v", err) + } + if user.BandwidthMbps != 1 { + t.Fatalf("free tier bandwidth = %d, want 1", user.BandwidthMbps) + } + + // Origin: hands out a fixed payload and nothing else. + payload := bytes.Repeat([]byte("y"), 256<<10) + origin, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("origin listen: %v", err) + } + defer origin.Close() + go func() { + for { + conn, aerr := origin.Accept() + if aerr != nil { + return + } + go func(c net.Conn) { + defer c.Close() + buf := make([]byte, len(payload)) + if _, rerr := io.ReadFull(c, buf); rerr != nil { + return + } + c.Write(payload) + }(conn) + } + }() + + cfg := DefaultConfig() + cfg.AuthEnabled = true + cfg.Username = "pu" + cfg.Password = "pp" + cfg.AdminEnabled = false + cfg.SecurityHeadersEnabled = false + cfg.RateLimitEnabled = false + + proxy := NewProxyServer(cfg) + proxy.store = store + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("proxy listen: %v", err) + } + defer ln.Close() + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go proxy.handleClient(conn, "") + } + }() + + host, portStr, _ := net.SplitHostPort(origin.Addr().String()) + port64, err := strconv.ParseUint(portStr, 10, 16) + if err != nil { + t.Fatalf("origin port %q: %v", portStr, err) + } + port := uint16(port64) + + client, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("dial proxy: %v", err) + } + defer client.Close() + if err := socks5ConnectAndAuth(t, client, "pu", "pp", host, port); err != nil { + t.Fatalf("socks5 handshake: %v", err) + } + if _, err := client.Write(payload); err != nil { + t.Fatalf("write payload: %v", err) + } + + got := make([]byte, len(payload)) + start := time.Now() + if _, err := io.ReadFull(client, got); err != nil { + t.Fatalf("read through proxy: %v", err) + } + elapsed := time.Since(start) + + if !bytes.Equal(got, payload) { + t.Fatal("payload changed in transit") + } + if elapsed < 900*time.Millisecond { + t.Errorf("free tier moved 256 KiB in %s: BandwidthMbps is still not enforced", elapsed) + } +} + +// socks5ConnectAndAuth performs greeting, username/password auth and CONNECT. +// Written out rather than reusing the e2e helper because that one assumes +// no-auth and lives in a different test file's style. +func socks5ConnectAndAuth(t *testing.T, conn net.Conn, user, pass, host string, port uint16) error { + t.Helper() + if _, err := conn.Write([]byte{0x05, 0x01, 0x02}); err != nil { + return err + } + sel := make([]byte, 2) + if _, err := io.ReadFull(conn, sel); err != nil { + return err + } + if sel[1] != 0x02 { + return errAuthNotOffered + } + if _, err := conn.Write([]byte{0x01, byte(len(user))}); err != nil { + return err + } + if _, err := conn.Write([]byte(user)); err != nil { + return err + } + if _, err := conn.Write([]byte{byte(len(pass))}); err != nil { + return err + } + if _, err := conn.Write([]byte(pass)); err != nil { + return err + } + status := make([]byte, 2) + if _, err := io.ReadFull(conn, status); err != nil { + return err + } + if status[1] != 0x00 { + return errAuthRejected + } + + req := []byte{0x05, 0x01, 0x00, 0x03, byte(len(host))} + req = append(req, host...) + req = append(req, byte(port>>8), byte(port)) + if _, err := conn.Write(req); err != nil { + return err + } + head := make([]byte, 4) + if _, err := io.ReadFull(conn, head); err != nil { + return err + } + if head[1] != 0x00 { + return errConnectRefused + } + switch head[3] { + case 0x01: + _, err := io.ReadFull(conn, make([]byte, 6)) + return err + case 0x03: + var l [1]byte + if _, err := io.ReadFull(conn, l[:]); err != nil { + return err + } + _, err := io.ReadFull(conn, make([]byte, int(l[0])+2)) + return err + case 0x04: + _, err := io.ReadFull(conn, make([]byte, 18)) + return err + default: + return errBadAddrType + } +} + +var ( + errAuthNotOffered = errorString("server did not offer username/password auth") + errAuthRejected = errorString("server rejected the credentials") + errConnectRefused = errorString("server refused the CONNECT") + errBadAddrType = errorString("server replied with an unknown bound address type") +) + +type errorString string + +func (e errorString) Error() string { return string(e) } + +func contains(haystack []string, needle string) bool { + for _, v := range haystack { + if v == needle { + return true + } + } + return false +} + +func TestPacerHonoursSmallerLimits(t *testing.T) { + // 4 Mbps over 512 KiB is ~1s, against a burst of 512 KiB, so the floor sits + // just under the non-burst transfer time. This catches a pacer that only + // ever applies its ceiling once. + p := newPacer(4) + if p == nil { + t.Fatal("newPacer(4) returned nil, want a pacer") + } + if p.bytesPerSec != 512*1024 { + t.Errorf("bytesPerSec = %v, want 512KiB/s for 4 Mbps", p.bytesPerSec) + } + + start := time.Now() + payload := bytes.Repeat([]byte("z"), 1<<20) // 1 MiB + var sink bytes.Buffer + if _, err := copyPaced(&sink, bytes.NewReader(payload), p); err != nil { + t.Fatalf("copyPaced: %v", err) + } + elapsed := time.Since(start) + if elapsed < 900*time.Millisecond { + t.Errorf("1 MiB at 4 Mbps took %s, want at least ~900ms", elapsed) + } +} diff --git a/main.go b/main.go index 0b00ba6..e3d2797 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,7 @@ import ( "net/http" "os" "os/signal" + "sort" "strconv" "strings" "sync" @@ -28,7 +29,7 @@ import ( // version is reported by the version subcommand, /health and /api/stats, so the // three can never disagree. -const version = "1.3.0" +const version = "1.3.1" type Config struct { ProxyPort int `json:"proxy_port"` @@ -88,10 +89,17 @@ type Config struct { RealityPublicHost string `json:"reality_public_host"` RealityXrayBin string `json:"reality_xray_bin"` RealityClientFile string `json:"reality_client_file"` + + // envSet records which settings were explicitly provided through the + // environment, so applyDBOverrides knows not to overwrite the operator's + // stated intent with a value saved from the dashboard months earlier. + // Unexported, so it never appears in JSON and never reaches an API. + envSet map[string]bool } func DefaultConfig() Config { return Config{ + envSet: make(map[string]bool), ProxyPort: 1080, AdminPort: 8080, MetricsPort: 9090, @@ -124,6 +132,9 @@ func LoadConfig(filename string) (Config, error) { if err != nil { return cfg, fmt.Errorf("read config %s: %w", filename, err) } + if cfg.envSet == nil { + cfg.envSet = make(map[string]bool) + } if err := json.Unmarshal(data, &cfg); err != nil { return cfg, fmt.Errorf("parse config: %w", err) } @@ -150,38 +161,48 @@ func LoadConfig(filename string) (Config, error) { } } if user := os.Getenv("PROXY_USER"); user != "" { + cfg.envSet["proxy_user"] = true cfg.Username = user } if pass := os.Getenv("PROXY_PASS"); pass != "" { + cfg.envSet["proxy_pass"] = true cfg.Password = pass } if max := os.Getenv("MAX_CONNECTIONS"); max != "" { + cfg.envSet["max_connections"] = true if m, err := strconv.Atoi(max); err == nil && m > 0 { cfg.MaxConns = m } } if v := os.Getenv("AUTH_ENABLED"); v != "" { + cfg.envSet["auth_enabled"] = true cfg.AuthEnabled = v == "true" || v == "1" } // Admin auth env vars if user := os.Getenv("ADMIN_USER"); user != "" { + cfg.envSet["admin_username"] = true cfg.AdminUser = user } if pass := os.Getenv("ADMIN_PASS"); pass != "" { + cfg.envSet["admin_pass"] = true cfg.AdminPass = pass } if v := os.Getenv("ADMIN_AUTH_ENABLED"); v != "" { + cfg.envSet["admin_auth_enabled"] = true cfg.AdminEnabled = v == "true" || v == "1" } if v := os.Getenv("SECURITY_HEADERS_ENABLED"); v != "" { + cfg.envSet["security_headers_enabled"] = true cfg.SecurityHeadersEnabled = v == "true" || v == "1" } if v := os.Getenv("RATE_LIMIT_ENABLED"); v != "" { + cfg.envSet["rate_limit_enabled"] = true cfg.RateLimitEnabled = v == "true" || v == "1" } if v := os.Getenv("RATE_LIMIT_RPS"); v != "" { + cfg.envSet["rate_limit_rps"] = true if r, err := strconv.Atoi(v); err == nil && r > 0 { cfg.RateLimitRPS = r } @@ -491,11 +512,11 @@ type ProxyServer struct { wg sync.WaitGroup // Rate limiter (shared reference for runtime updates) - limiter *rateLimiter + limiter *rateLimiterSet // Separate limiter for tunnel handshakes, so token brute-force cannot // exhaust the admin/dashboard budget (see multiplex.go) - tunnelLimiter *rateLimiter + tunnelLimiter *rateLimiterSet // Client used for absolute-URI forward-proxy requests (http:// targets). // Initialised with the mux; nil in multi-port mode, where forward proxying @@ -961,9 +982,18 @@ func (s *ProxyServer) relay(client, target net.Conn, log *slog.Logger, targetAdd var bytesUp, bytesDown atomic.Int64 wg.Add(2) + // The tier's bandwidth limit, one pacer per direction. A nil pacer (the + // Unlimited tier, or an unauthenticated session) means full speed and costs + // nothing to check. + var upPacer, downPacer *pacer + if user != nil { + upPacer = newPacer(user.BandwidthMbps) + downPacer = newPacer(user.BandwidthMbps) + } + go func() { defer wg.Done() - n, err := io.Copy(target, client) + n, err := copyPaced(target, client, upPacer) if err != nil && !isClosedConnError(err) { log.Debug("client->target copy error", "error", err) } @@ -973,7 +1003,7 @@ func (s *ProxyServer) relay(client, target net.Conn, log *slog.Logger, targetAdd go func() { defer wg.Done() - n, err := io.Copy(client, target) + n, err := copyPaced(client, target, downPacer) if err != nil && !isClosedConnError(err) { log.Debug("target->client copy error", "error", err) } @@ -1111,10 +1141,10 @@ func (rl *rateLimiter) allow() bool { return true } -func rateLimit(limiter *rateLimiter) func(http.Handler) http.Handler { +func rateLimit(limiter *rateLimiterSet) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !limiter.allow() { + if !limiter.allow(requestIP(r)) { http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests) return } @@ -1123,6 +1153,119 @@ func rateLimit(limiter *rateLimiter) func(http.Handler) http.Handler { } } +// ─── Per-client rate limiting ─────────────────────────────────────────────── + +// rateLimiterSet gives every client its own token bucket. +// +// A single shared bucket, which is what this used to be, means one noisy client +// spends everyone's budget: on a dashboard polled by two administrators, or on +// a tunnel shared by a dozen phones behind one carrier NAT, a flood from one +// address throttles all of them. That is also what the README claimed did not +// happen, so the docs and the code now agree in the direction of the code being +// useful. +// +// The cost is memory proportional to the number of distinct addresses seen in +// the last rateLimiterIdle window, which is why buckets are swept rather than +// kept forever. +type rateLimiterSet struct { + mu sync.Mutex + rps int + buckets map[string]*rateBucket + lastSweep time.Time +} + +type rateBucket struct { + tokens float64 + last time.Time + lastSeen time.Time +} + +const ( + // rateLimiterSweep is how often idle buckets are collected. + rateLimiterSweep = 5 * time.Minute + // rateLimiterIdle is how long a silent client's bucket is kept. Two sweeps, + // so a client that is quiet for one interval keeps its accumulated tokens. + rateLimiterIdle = 10 * time.Minute + // rateLimiterMaxBuckets bounds memory if a flood of distinct addresses + // arrives faster than the sweep removes them. + rateLimiterMaxBuckets = 100000 +) + +func newRateLimiterSet(rps int) *rateLimiterSet { + return &rateLimiterSet{ + rps: rps, + buckets: make(map[string]*rateBucket), + lastSweep: time.Now(), + } +} + +func (s *rateLimiterSet) allow(key string) bool { + now := time.Now() + + s.mu.Lock() + defer s.mu.Unlock() + + if now.Sub(s.lastSweep) >= rateLimiterSweep { + s.sweepLocked(now) + } + + b, ok := s.buckets[key] + if !ok { + b = &rateBucket{tokens: float64(s.rps), last: now} + s.buckets[key] = b + } + + elapsed := now.Sub(b.last).Seconds() + b.last = now + b.lastSeen = now + b.tokens += elapsed * float64(s.rps) + if b.tokens > float64(s.rps) { + b.tokens = float64(s.rps) + } + if b.tokens < 1 { + return false + } + b.tokens-- + return true +} + +func (s *rateLimiterSet) setRPS(rps int) { + s.mu.Lock() + defer s.mu.Unlock() + s.rps = rps + for _, b := range s.buckets { + if b.tokens > float64(rps) { + b.tokens = float64(rps) + } + } +} + +// sweepLocked drops buckets nobody has used, and if that is not enough, the +// least recently used half. Callers must hold the lock. +func (s *rateLimiterSet) sweepLocked(now time.Time) { + s.lastSweep = now + for key, b := range s.buckets { + if now.Sub(b.lastSeen) > rateLimiterIdle { + delete(s.buckets, key) + } + } + if len(s.buckets) <= rateLimiterMaxBuckets { + return + } + type entry struct { + key string + lastSeen time.Time + } + entries := make([]entry, 0, len(s.buckets)) + for key, b := range s.buckets { + entries = append(entries, entry{key, b.lastSeen}) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].lastSeen.Before(entries[j].lastSeen) }) + for _, e := range entries[:len(entries)/2] { + delete(s.buckets, e.key) + } +} + // ─── No-Directory-Listing File Server ────────────────────────────────────── func noDirListing(root http.FileSystem) http.Handler { @@ -1587,7 +1730,7 @@ func (s *ProxyServer) adminHandler() http.Handler { // Apply middleware stack (outermost first) if s.cfg.RateLimitEnabled { - s.limiter = newRateLimiter(s.cfg.RateLimitRPS) + s.limiter = newRateLimiterSet(s.cfg.RateLimitRPS) handler = rateLimit(s.limiter)(handler) } if s.cfg.AdminEnabled && s.cfg.AdminUser != "" && s.cfg.AdminPass != "" { @@ -1695,6 +1838,67 @@ func (s *ProxyServer) metricsHandler() http.Handler { return handler } +// applyDBOverrides applies settings saved from the admin dashboard. +// +// The environment wins. Both the docs and every deployment since the beginning +// have said "edit config.json or use environment variables", so a password +// edited in .env that silently kept working because a value happened to be +// stored in SQLite three weeks earlier is a trap, not a feature. The dashboard +// still wins over config.json, because the operator clicking "save" is stating +// intent right now; the environment wins over the dashboard because it is how a +// deployment is described at boot. +// +// Returns the keys that were actually applied, for the startup log. +func applyDBOverrides(cfg *Config, dbCfg map[string]string) []string { + if len(dbCfg) == 0 { + return nil + } + var applied []string + take := func(key string, ok bool) bool { + if !ok || cfg.envSet[key] { + return false + } + applied = append(applied, key) + return true + } + + if v, ok := dbCfg["max_connections"]; take("max_connections", ok) { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + cfg.MaxConns = n + } + } + if v, ok := dbCfg["proxy_user"]; take("proxy_user", ok) { + cfg.Username = v + } + if v, ok := dbCfg["proxy_pass"]; take("proxy_pass", ok) { + cfg.Password = v + } + if v, ok := dbCfg["auth_enabled"]; take("auth_enabled", ok) { + cfg.AuthEnabled = v == "true" + } + if v, ok := dbCfg["admin_auth_enabled"]; take("admin_auth_enabled", ok) { + cfg.AdminEnabled = v == "true" + } + if v, ok := dbCfg["admin_username"]; take("admin_username", ok) { + cfg.AdminUser = v + } + if v, ok := dbCfg["admin_pass"]; take("admin_pass", ok) { + cfg.AdminPass = v + } + if v, ok := dbCfg["security_headers_enabled"]; take("security_headers_enabled", ok) { + cfg.SecurityHeadersEnabled = v == "true" + } + if v, ok := dbCfg["rate_limit_enabled"]; take("rate_limit_enabled", ok) { + cfg.RateLimitEnabled = v == "true" + } + if v, ok := dbCfg["rate_limit_rps"]; take("rate_limit_rps", ok) { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + cfg.RateLimitRPS = n + } + } + return applied +} + // ─── Main ────────────────────────────────────────────────────────────────── func main() { @@ -1758,42 +1962,10 @@ func runServer(logger *slog.Logger, configFile string) { // Load persisted config overrides from DB dbCfg := store.LoadConfig() - if len(dbCfg) > 0 { - if v, ok := dbCfg["max_connections"]; ok { - if n, err := strconv.Atoi(v); err == nil && n > 0 { - cfg.MaxConns = n - } - } - if v, ok := dbCfg["proxy_user"]; ok { - cfg.Username = v - } - if v, ok := dbCfg["proxy_pass"]; ok { - cfg.Password = v - } - if v, ok := dbCfg["auth_enabled"]; ok { - cfg.AuthEnabled = v == "true" - } - if v, ok := dbCfg["admin_auth_enabled"]; ok { - cfg.AdminEnabled = v == "true" - } - if v, ok := dbCfg["admin_username"]; ok { - cfg.AdminUser = v - } - if v, ok := dbCfg["admin_pass"]; ok { - cfg.AdminPass = v - } - if v, ok := dbCfg["security_headers_enabled"]; ok { - cfg.SecurityHeadersEnabled = v == "true" - } - if v, ok := dbCfg["rate_limit_enabled"]; ok { - cfg.RateLimitEnabled = v == "true" - } - if v, ok := dbCfg["rate_limit_rps"]; ok { - if n, err := strconv.Atoi(v); err == nil && n > 0 { - cfg.RateLimitRPS = n - } - } - logger.Info("loaded config overrides from database") + if applied := applyDBOverrides(&cfg, dbCfg); len(applied) > 0 { + logger.Info("loaded config overrides from database", + "keys", strings.Join(applied, ","), + "note", "keys set in the environment were left alone") } server := NewProxyServer(cfg) diff --git a/multiplex.go b/multiplex.go index 3588e50..87baed0 100644 --- a/multiplex.go +++ b/multiplex.go @@ -401,7 +401,7 @@ func (s *ProxyServer) connectHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, "forbidden", http.StatusForbidden) return } - if !s.tunnelLimiter.allow() { + if !s.tunnelLimiter.allow(requestIP(r)) { http.Error(w, "too many requests", http.StatusTooManyRequests) return } @@ -519,7 +519,7 @@ func (s *ProxyServer) forwardProxyHandler(w http.ResponseWriter, r *http.Request http.Error(w, "forbidden", http.StatusForbidden) return } - if !s.tunnelLimiter.allow() { + if !s.tunnelLimiter.allow(requestIP(r)) { http.Error(w, "too many requests", http.StatusTooManyRequests) return } @@ -658,6 +658,8 @@ func validProxyAuth(r *http.Request, wantUser, wantPass string) bool { func (s *ProxyServer) tunnelHandler(w http.ResponseWriter, r *http.Request) { cfg := s.currentConfig() + clientIP := requestIP(r) + // Every refusal below is byte-identical, on purpose. A disabled tunnel, a // rate-limited attempt and a wrong token must be indistinguishable from a // path that does not exist, because "this path exists but I am not welcome" @@ -666,7 +668,7 @@ func (s *ProxyServer) tunnelHandler(w http.ResponseWriter, r *http.Request) { s.writeTunnelRefusal(w, r) return } - if !s.tunnelLimiter.allow() { + if !s.tunnelLimiter.allow(clientIP) { s.writeTunnelRefusal(w, r) return } @@ -708,7 +710,6 @@ func (s *ProxyServer) tunnelHandler(w http.ResponseWriter, r *http.Request) { conn = newPadConn(conn, cfg.TunnelPadding) } - clientIP := requestIP(r) s.logger.Info("tunnel session opened", "client", clientIP, "padding", cfg.TunnelPadding) s.handleClient(conn, clientIP) } @@ -812,7 +813,7 @@ func (s *ProxyServer) serveMultiplex(addr string) error { return err } - s.tunnelLimiter = newRateLimiter(cfg.TunnelRateRPS) + s.tunnelLimiter = newRateLimiterSet(cfg.TunnelRateRPS) tunnelPath := cfg.TunnelPath if tunnelPath == "" { diff --git a/multiplex_test.go b/multiplex_test.go index 8d47e03..3dc567a 100644 --- a/multiplex_test.go +++ b/multiplex_test.go @@ -1217,7 +1217,7 @@ func TestTunnelPathRejectsServeMuxPanics(t *testing.T) { for name, path := range bad { t.Run(name, func(t *testing.T) { srv := NewProxyServer(DefaultConfig()) - srv.tunnelLimiter = newRateLimiter(5) + srv.tunnelLimiter = newRateLimiterSet(5) srv.cfg.TunnelEnabled = true srv.cfg.TunnelPath = path @@ -1233,7 +1233,7 @@ func TestTunnelPathRejectsServeMuxPanics(t *testing.T) { // A valid path must still start. srv := NewProxyServer(DefaultConfig()) - srv.tunnelLimiter = newRateLimiter(5) + srv.tunnelLimiter = newRateLimiterSet(5) srv.cfg.TunnelEnabled = true srv.cfg.TunnelPath = "/api/v1/tunnel" if err := srv.serveMultiplex("127.0.0.1:0"); err != nil { @@ -1246,7 +1246,7 @@ func TestTunnelPathRejectsServeMuxPanics(t *testing.T) { // TUNNEL_ENABLED=false while leaving a stale TUNNEL_PATH behind. func TestDisabledTunnelIgnoresPath(t *testing.T) { srv := NewProxyServer(DefaultConfig()) - srv.tunnelLimiter = newRateLimiter(5) + srv.tunnelLimiter = newRateLimiterSet(5) srv.cfg.TunnelEnabled = false srv.cfg.TunnelPath = "not-even-a-path" diff --git a/pacer.go b/pacer.go new file mode 100644 index 0000000..3d7e149 --- /dev/null +++ b/pacer.go @@ -0,0 +1,110 @@ +package main + +import ( + "io" + "time" +) + +// ─── Bandwidth pacer ──────────────────────────────────────────────────────── + +// pacer keeps a stream under a bitrate. +// +// BandwidthMbps has been stored per user since the tier system landed and +// advertised in the README as "1 / 5 / 50 Mbps", but nothing ever read it: +// relay() was a plain io.Copy in both directions, so the Free tier ran at line +// speed like every other tier. This is where that column finally takes effect. +// +// A token bucket with a one-second burst, which is what a tier limit means in +// practice: sustained rate capped, short spikes allowed. Each direction gets its +// own pacer, so a tier's number is the rate in each direction rather than a +// shared budget -- the usual reading of a per-tier bandwidth figure, and the one +// that keeps a download from starving the upload that ACKs it. +type pacer struct { + bytesPerSec float64 + tokens float64 + last time.Time +} + +// pacerBurstSeconds is how much slack a client gets before the average rate +// kicks in. One second of traffic is enough to smooth a burst without letting a +// fast transfer spend its whole allowance at once. +const pacerBurstSeconds = 1.0 + +// newPacer returns nil when there is nothing to enforce, which is the -1 that +// the Unlimited tier uses. Callers treat a nil pacer as "copy at full speed", so +// the unlimited path keeps costing nothing. +func newPacer(mbps int) *pacer { + if mbps <= 0 { + return nil + } + rate := float64(mbps) * 1024 * 1024 / 8 // Mbit/s -> bytes/s + return &pacer{ + bytesPerSec: rate, + tokens: rate * pacerBurstSeconds, + last: time.Now(), + } +} + +// reserve asks for permission to move n bytes, sleeping if the allowance for +// this instant is not there yet. +func (p *pacer) reserve(n int) { + if p == nil || n <= 0 { + return + } + now := time.Now() + p.tokens += now.Sub(p.last).Seconds() * p.bytesPerSec + p.last = now + if p.tokens > p.bytesPerSec*pacerBurstSeconds { + p.tokens = p.bytesPerSec * pacerBurstSeconds + } + p.tokens -= float64(n) + if p.tokens >= 0 { + return + } + // Negative tokens are the debt: wait for the bucket to refill by that much. + debt := -p.tokens + p.tokens = 0 + time.Sleep(time.Duration(debt / p.bytesPerSec * float64(time.Second))) + // The clock has to be moved past the sleep. Without this the next call + // credits the sleeping interval as if it were idle time, so the debt is + // paid twice and the link runs at twice the configured rate. + p.last = time.Now() +} + +// copyPaced is io.Copy with a rate limit. The read/write loop replaces io.Copy +// because pacing needs to sit between the two, and because the chunk size is +// what the pacer reserves against. +func copyPaced(dst io.Writer, src io.Reader, p *pacer) (int64, error) { + if p == nil { + return io.Copy(dst, src) + } + buf := make([]byte, pacerChunkSize) + var total int64 + for { + nr, rerr := src.Read(buf) + if nr > 0 { + nw, werr := dst.Write(buf[:nr]) + if nw > 0 { + total += int64(nw) + p.reserve(nw) + } + if werr != nil { + return total, werr + } + if nw != nr { + return total, io.ErrShortWrite + } + } + if rerr != nil { + if rerr == io.EOF { + return total, nil + } + return total, rerr + } + } +} + +// pacerChunkSize is the read size for paced copies. 32KB keeps the sleep count +// low on a fast link while staying small enough that a rate limit of 1 Mbps +// still arrives in ~4 chunks a second instead of a single one-second stall. +const pacerChunkSize = 32 << 10 From a20ecb820bbd5a299c35ca3c4c51f8829c0c68aa Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sat, 17 Oct 2026 17:06:29 +0500 Subject: [PATCH 2/2] Add backup and restore, and fix the database pragmas that were never applied Two things here. The feature is backup/restore. The other is a bug the feature found while being written, which matters more. Every pragma in the SQLite connection string was being ignored. The DSN used the mattn/go-sqlite3 spelling (`_journal_mode=WAL`) with modernc.org/sqlite as the driver, which wants `_pragma=name(value)` and silently drops what it does not recognise. Measured on both spellings: journal_mode delete (wanted wal) busy_timeout 0 (wanted 5000) foreign_keys 0 (wanted on) synchronous 2/FULL (wanted 1/NORMAL) So the code, the comments and this README have all claimed a WAL database for the life of the project, and it has never been one. Readers blocking writers, a concurrent write getting SQLITE_BUSY immediately instead of waiting 5s, an unenforced foreign key on user_connections, and an fsync per commit that synchronous=NORMAL was supposed to avoid. Fixing that turned the foreign key on, which would have broken the dashboard's delete-user button for anyone with connection history: the child rows reference the parent, so deleting the parent now fails. DeleteUser removes the dependent rows first, in one transaction. backup and restore socks5-proxy backup -out FILE [-passphrase P] socks5-proxy restore -in FILE [-list] [-force] The snapshot uses VACUUM INTO rather than copying the file. That is the whole reason it exists: in WAL mode the newest commits live in the -wal sidecar, so reading socks5.db can yield a backup that restores cleanly and has quietly lost data. There is a test that writes without checkpointing, confirms the WAL sidecar has content, and then proves the restored database contains the row. With -passphrase the archive is AES-256-GCM under PBKDF2-SHA256, with a fresh salt and nonce per backup, so two backups of identical data do not look alike. A wrong passphrase fails on the GCM tag, which is authentication rather than a checksum discovered three steps later, and the message names the passphrase as the likely cause. restore is written to be safe to run badly. It refuses while the server is running, detected through a pid file the server writes at startup (a pid left by a crash does not count, and -force overrides). It decrypts and verifies every member against the manifest checksum before writing anything, so a failure cannot leave a half-restored installation. Only the exact member names this tool writes are restored, so an archive naming ../something cannot write outside the data directory. The existing database is kept as socks5.db.pre-restore-. That last hazard is not hypothetical, and the tests hit it: SQLite does its close-time WAL cleanup by path, so a test helper still holding the old file after a restore installed a new database at the same path rewrote the new file on close. It is the same failure an operator would get by restoring over a live server, which is what the pid check exists to prevent. Verified live, not only by unit test: a backup taken while the proxy was serving, then the database deleted, then restored and restarted -- the user accounted for before the backup authenticated afterwards. Restoring over the running server was refused; a wrong passphrase was refused with nothing changed; the encrypted archive contains no plaintext credentials. --- .env.example | 6 + README.md | 44 ++++ backup.go | 615 +++++++++++++++++++++++++++++++++++++++++++++++++ backup_test.go | 528 ++++++++++++++++++++++++++++++++++++++++++ database.go | 45 +++- main.go | 21 ++ 6 files changed, 1256 insertions(+), 3 deletions(-) create mode 100644 backup.go create mode 100644 backup_test.go diff --git a/.env.example b/.env.example index 126db87..55639dd 100644 --- a/.env.example +++ b/.env.example @@ -95,3 +95,9 @@ REALITY_DEST=www.lovelive-anime.jp:443 REALITY_PUBLIC_HOST= XRAY_BIN=xray REALITY_CLIENT_FILE=reality-client.json + +# ─── Backup ───────────────────────────────────────────────────────────────── +# `socks5-proxy backup -out FILE [-passphrase P]` snapshots the database with +# VACUUM INTO, which is safe while the server is running. The archive holds every +# user password and the REALITY private key, so encrypt anything that leaves the +# machine. Restore with `socks5-proxy restore -in FILE`, server stopped. diff --git a/README.md b/README.md index edb5a3c..e95bc4f 100644 --- a/README.md +++ b/README.md @@ -410,6 +410,47 @@ Client flags: `-url` (required; `https://` is accepted and mapped to `wss://`, a `reality-client` flags: `-config` (default `reality-client.json`), `-server` (override the server address, `host` or `host:port`), `-listen` (override the local SOCKS5 address, default `127.0.0.1:1081`), `-bin` (xray binary). +## Backup and restore + +```bash +# Take a backup. Works while the server is running. +socks5-proxy backup -out socks5-20261017.tar.gz + +# Encrypt it. A backup contains every user password and, with REALITY enabled, +# the private key -- so encryption is worth the passphrase. +socks5-proxy backup -out socks5-20261017.tar.gz -passphrase 'a good passphrase' + +# Look inside without restoring anything. +socks5-proxy restore -in socks5-20261017.tar.gz -list + +# Restore. Stop the server first. +socks5-proxy restore -in socks5-20261017.tar.gz +``` + +The archive holds `socks5.db`, `config.json` and, when REALITY is enabled, +`reality-client.json`. **Restoring the same archive keeps every REALITY client +working**, because the keypair travels with it; restoring an older or different +one invalidates every client you have imported. + +`restore` refuses to run while the server is up, because replacing a database +that another process still has open is how SQLite ends up cleaning up the wrong +file. It detects that through a pid file the server writes at startup, and a pid +left behind by a crash does not count as running. `-force` overrides it. + +The current database is kept as `socks5.db.pre-restore-` before +anything is replaced, so a restore is undoable by hand. + +Snapshots are taken with SQLite's `VACUUM INTO`, never by copying the file. +This database runs in WAL mode, so the most recent commits live in the `-wal` +sidecar: a file copy can produce a backup that restores cleanly and silently +loses data. + +Nightly, with the volume mounted: + +```bash +0 3 * * * cd /srv/socks5-proxy && ./socks5-proxy backup -out "backup-$(date +%F).tar.gz" -passphrase "$BACKUP_PASSPHRASE" && find . -name 'backup-*.tar.gz' -mtime +14 -delete +``` + ## Tests ```bash @@ -452,6 +493,9 @@ go test -run TestRealityEndToEnd -v ./... # needs xray on PATH on shutdown. Its own log lines are relayed into this server's log. - `whitelist` and `blacklist` apply to the SOCKS5 port, the HTTP proxy (`CONNECT` and forward) and the tunnel alike. +- A backup contains every user password in the clear, plus the REALITY private + key when it is enabled. Use `-passphrase` for anything that leaves the machine, + and keep the passphrase somewhere other than the backup directory. - `/health` is the only endpoint reachable without admin credentials, and it returns `{"status":"ok"}` with no uptime or version: on a public port it is the one thing a scanner can read, so it says nothing. `/metrics`, diff --git a/backup.go b/backup.go new file mode 100644 index 0000000..f37fe8f --- /dev/null +++ b/backup.go @@ -0,0 +1,615 @@ +package main + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "crypto/aes" + "crypto/cipher" + "crypto/pbkdf2" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "syscall" + "time" +) + +// ─── Backup and restore ───────────────────────────────────────────────────── +// +// A running proxy cannot simply have its database file copied: SQLite runs in +// WAL mode here, so the most recent writes live in socks5.db-wal and a naive +// copy of socks5.db loses them. This takes a proper snapshot instead, with +// VACUUM INTO, which produces a single consistent file while the server keeps +// serving. +// +// The archive also carries config.json and the generated reality-client.json, +// because a database without its REALITY keypair is a database that silently +// invalidates every client the operator has imported. + +const ( + backupMagic = "S5BK" + backupVersion = 1 + backupFlagPlain = 0 + backupFlagCrypto = 1 + backupSaltLen = 16 + backupNonceLen = 12 + backupKeyLen = 32 + backupPBKDF2Iters = 600000 + backupManifestTyp = "manifest.json" + backupDBName = "socks5.db" + backupPidName = "socks5.pid" + // backupMaxFile bounds any single entry, so a corrupt length field cannot + // make restore allocate an enormous buffer. + backupMaxFile = 4 << 30 +) + +type backupManifest struct { + CreatedAt string `json:"created_at"` + ProxyVersion string `json:"proxy_version"` + Files []backupEntry `json:"files"` +} + +type backupEntry struct { + Name string `json:"name"` + Size int64 `json:"size"` + SHA256 string `json:"sha256"` +} + +// backupFileNames are the members of an archive, in a fixed order. +var backupFileNames = []string{backupDBName, "config.json", "reality-client.json"} + +// ─── backup ───────────────────────────────────────────────────────────────── + +func runBackup(args []string) error { + fs := flag.NewFlagSet("backup", flag.ContinueOnError) + out := fs.String("out", "", "output archive (required)") + passphrase := fs.String("passphrase", "", "encrypt the archive with this passphrase") + dataDir := fs.String("data", "data", "directory holding socks5.db") + pass := fs.String("config", "config.json", "path to config.json to include, if present") + clientCfg := fs.String("client-config", "reality-client.json", "REALITY client config to include, if present") + fs.SetOutput(os.Stderr) + if err := fs.Parse(args); err != nil { + return err + } + if *out == "" { + return errors.New("-out is required") + } + + files := make([][]byte, len(backupFileNames)) + present := make([]bool, len(backupFileNames)) + for i, name := range backupFileNames { + path := filepath.Join(*dataDir, name) + if name == "config.json" { + path = *pass + } + if name == "reality-client.json" { + path = *clientCfg + } + + if name == backupDBName { + if _, statErr := os.Stat(path); statErr != nil { + return fmt.Errorf("no database at %s: %w", path, statErr) + } + data, cleanup, err := snapshotDatabase(path) + if err != nil { + return err + } + defer cleanup() + files[i], present[i] = data, true + continue + } + + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + // The config files are optional; the database is not. + continue + } + return fmt.Errorf("read %s: %w", path, err) + } + files[i], present[i] = data, true + } + + manifest := backupManifest{ + CreatedAt: time.Now().UTC().Format(time.RFC3339), + ProxyVersion: version, + } + for i, name := range backupFileNames { + if !present[i] { + continue + } + sum := sha256.Sum256(files[i]) + manifest.Files = append(manifest.Files, backupEntry{ + Name: name, + Size: int64(len(files[i])), + SHA256: hex.EncodeToString(sum[:]), + }) + } + + if err := writeBackupArchive(*out, files, present, manifest, *passphrase); err != nil { + return err + } + info, _ := os.Stat(*out) + size := int64(0) + if info != nil { + size = info.Size() + } + names := make([]string, 0, len(manifest.Files)) + for _, e := range manifest.Files { + names = append(names, e.Name) + } + encrypted := "" + if *passphrase != "" { + encrypted = ", encrypted" + } + fmt.Fprintf(os.Stdout, "backup written to %s (%d bytes%s): %s\n", + *out, size, encrypted, strings.Join(names, ", ")) + return nil +} + +// writeBackupArchive lays the files out as a gzipped tar, wraps it in the small +// self-describing header, and optionally encrypts it. +func writeBackupArchive(path string, files [][]byte, present []bool, manifest backupManifest, passphrase string) error { + var payload bytes.Buffer + gz := gzip.NewWriter(&payload) + tw := tar.NewWriter(gz) + + manifestJSON, err := json.MarshalIndent(manifest, "", " ") + if err != nil { + return err + } + if err := writeTarEntry(tw, backupManifestTyp, manifestJSON); err != nil { + return err + } + for i, name := range backupFileNames { + if !present[i] { + continue + } + if err := writeTarEntry(tw, name, files[i]); err != nil { + return err + } + } + if err := tw.Close(); err != nil { + return err + } + if err := gz.Close(); err != nil { + return err + } + + out := payload.Bytes() + header := make([]byte, 0, len(backupMagic)+2+backupSaltLen+backupNonceLen) + header = append(header, backupMagic...) + header = append(header, backupVersion) + + if passphrase == "" { + header = append(header, backupFlagPlain) + } else { + header = append(header, backupFlagCrypto) + salt := make([]byte, backupSaltLen) + if _, err := rand.Read(salt); err != nil { + return fmt.Errorf("generate salt: %w", err) + } + nonce := make([]byte, backupNonceLen) + if _, err := rand.Read(nonce); err != nil { + return fmt.Errorf("generate nonce: %w", err) + } + key, err := deriveBackupKey(passphrase, salt) + if err != nil { + return err + } + block, err := aes.NewCipher(key) + if err != nil { + return err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return err + } + out = gcm.Seal(nil, nonce, payload.Bytes(), []byte(backupMagic)) + header = append(header, salt...) + header = append(header, nonce...) + } + + // Write to a temporary file and rename, so an interrupted backup never + // leaves a half-written archive that looks complete. + tmp := path + ".partial" + if err := os.WriteFile(tmp, append(header, out...), 0o600); err != nil { + return fmt.Errorf("write backup: %w", err) + } + if err := os.Rename(tmp, path); err != nil { + os.Remove(tmp) + return fmt.Errorf("finalise backup: %w", err) + } + return nil +} + +// snapshotDatabase returns a consistent copy of the database. +// +// It must not read the file. The database runs in WAL mode, so the most +// recently committed writes live in the -wal sidecar and a plain read of +// socks5.db can silently return a database that is missing them -- a backup that +// restores cleanly and loses data. VACUUM INTO asks SQLite for a consistent +// view and writes it to a single self-contained file, and it is safe to run +// while the server is serving. +func snapshotDatabase(dbPath string) ([]byte, func(), error) { + tmp, err := os.CreateTemp("", "socks5-snapshot-*.db") + if err != nil { + return nil, func() {}, fmt.Errorf("snapshot: %w", err) + } + cleanup := func() { + tmp.Close() + os.Remove(tmp.Name()) + } + // VACUUM INTO refuses to overwrite, so the temporary must be empty and + // then removed before it can be used as a target. + if _, err := tmp.Write(nil); err != nil { + cleanup() + return nil, func() {}, err + } + place := tmp.Name() + tmp.Close() + os.Remove(place) + + db, err := sql.Open("sqlite", dbPath+ + "?_pragma=busy_timeout(5000)"+ + "&_pragma=foreign_keys(1)"+ + "&_pragma=synchronous(NORMAL)") + if err != nil { + return nil, func() {}, fmt.Errorf("open database: %w", err) + } + defer db.Close() + + escaped := strings.ReplaceAll(place, "'", "''") + if _, err := db.Exec(`VACUUM INTO '` + escaped + `'`); err != nil { + return nil, func() {}, fmt.Errorf("snapshot %s: %w", dbPath, err) + } + data, err := os.ReadFile(place) + if err != nil { + return nil, func() {}, fmt.Errorf("read snapshot: %w", err) + } + return data, cleanup, nil +} + +func writeTarEntry(tw *tar.Writer, name string, data []byte) error { + hdr := &tar.Header{ + Name: name, + Mode: 0o600, + Size: int64(len(data)), + Typeflag: tar.TypeReg, + ModTime: time.Unix(0, 0), + } + if err := tw.WriteHeader(hdr); err != nil { + return err + } + _, err := tw.Write(data) + return err +} + +func deriveBackupKey(passphrase string, salt []byte) ([]byte, error) { + return pbkdf2.Key(sha256.New, passphrase, salt, backupPBKDF2Iters, backupKeyLen) +} + +// ─── restore ──────────────────────────────────────────────────────────────── + +func runRestore(args []string) error { + fs := flag.NewFlagSet("restore", flag.ContinueOnError) + in := fs.String("in", "", "archive to restore (required)") + passphrase := fs.String("passphrase", "", "passphrase the archive was created with") + dataDir := fs.String("data", "data", "directory holding socks5.db") + pass := fs.String("config", "config.json", "path config.json should be restored to") + clientCfg := fs.String("client-config", "reality-client.json", "path the REALITY client config should be restored to") + force := fs.Bool("force", false, "restore even while the server appears to be running") + list := fs.Bool("list", false, "print the archive contents and exit, restoring nothing") + fs.SetOutput(os.Stderr) + if err := fs.Parse(args); err != nil { + return err + } + if *in == "" { + return errors.New("-in is required") + } + if *list { + return listBackupContents(*in, *passphrase) + } + + if !*force { + if pid, err := runningServerPID(*dataDir); err == nil { + return fmt.Errorf("refusing to restore while the server is running (pid %d); stop it first, or pass -force", pid) + } + } + + files, manifest, err := readBackupArchive(*in, *passphrase) + if err != nil { + return err + } + db, ok := files[backupDBName] + if !ok { + return fmt.Errorf("archive has no %s; refusing to restore", backupDBName) + } + + // Everything is decoded and verified before anything is written, so a + // failure cannot leave a half-restored installation. + staged := make(map[string]string) // final path -> temp path + defer func() { + for _, tmp := range staged { + os.Remove(tmp) + } + }() + + stage := func(final string, data []byte) error { + if err := os.MkdirAll(filepath.Dir(final), 0o750); err != nil { + return err + } + tmp := final + ".restore-tmp" + if err := os.WriteFile(tmp, data, 0o600); err != nil { + return fmt.Errorf("stage %s: %w", final, err) + } + staged[final] = tmp + return nil + } + + dbFinal := filepath.Join(*dataDir, backupDBName) + // Keep what is there now. Restoring over a live database is the one + // operation here that cannot be undone. + if _, err := os.Stat(dbFinal); err == nil { + keep := fmt.Sprintf("%s.pre-restore-%s", dbFinal, time.Now().UTC().Format("20060102T150405Z")) + if err := copyFile(dbFinal, keep); err != nil { + return fmt.Errorf("preserve current database: %w", err) + } + fmt.Fprintf(os.Stdout, " existing database kept as %s\n", keep) + } + if err := stage(dbFinal, db); err != nil { + return err + } + if data, ok := files["config.json"]; ok { + if err := stage(*pass, data); err != nil { + return err + } + } + if data, ok := files["reality-client.json"]; ok { + if err := stage(*clientCfg, data); err != nil { + return err + } + } + + for final, tmp := range staged { + if err := os.Rename(tmp, final); err != nil { + return fmt.Errorf("install %s: %w", final, err) + } + delete(staged, final) + } + + fmt.Fprintf(os.Stdout, "restored %s (%s): %d files\n", *in, manifest.CreatedAt, len(manifest.Files)) + for _, e := range manifest.Files { + fmt.Fprintf(os.Stdout, " %-22s %10d bytes sha256:%s\n", e.Name, e.Size, e.SHA256[:16]) + } + if _, ok := files[backupDBName]; ok { + fmt.Fprintln(os.Stdout, " REALITY clients keep working if this archive held the same keypair; a different keypair invalidates them.") + } + return nil +} + +// readBackupArchive decodes, decrypts if needed, and verifies every member +// against the manifest before returning anything. +func readBackupArchive(path, passphrase string) (map[string][]byte, backupManifest, error) { + files := map[string][]byte{} + + raw, err := os.ReadFile(path) + if err != nil { + return nil, backupManifest{}, fmt.Errorf("read %s: %w", path, err) + } + head := len(backupMagic) + 2 + if len(raw) < head || string(raw[:len(backupMagic)]) != backupMagic { + return nil, backupManifest{}, errors.New("not a socks5-proxy backup archive") + } + if v := raw[len(backupMagic)]; v != backupVersion { + return nil, backupManifest{}, fmt.Errorf("archive version %d, this build understands %d", v, backupVersion) + } + + var payload []byte + switch raw[len(backupMagic)+1] { + case backupFlagPlain: + if passphrase != "" { + return nil, backupManifest{}, errors.New("this archive is not encrypted, but a passphrase was given") + } + payload = raw[head:] + case backupFlagCrypto: + if passphrase == "" { + return nil, backupManifest{}, errors.New("this archive is encrypted; a passphrase is required") + } + need := head + backupSaltLen + backupNonceLen + if len(raw) < need { + return nil, backupManifest{}, errors.New("archive is truncated") + } + salt := raw[head : head+backupSaltLen] + nonce := raw[head+backupSaltLen : need] + key, err := deriveBackupKey(passphrase, salt) + if err != nil { + return nil, backupManifest{}, err + } + block, err := aes.NewCipher(key) + if err != nil { + return nil, backupManifest{}, err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return nil, backupManifest{}, err + } + // GCM authenticates, so a wrong passphrase fails here with a clear + // error rather than a checksum mismatch much later. + payload, err = gcm.Open(nil, nonce, raw[need:], []byte(backupMagic)) + if err != nil { + return nil, backupManifest{}, errors.New("wrong passphrase, or the archive is damaged") + } + default: + return nil, backupManifest{}, fmt.Errorf("unknown archive flags 0x%02x", raw[len(backupMagic)+1]) + } + + gz, err := gzip.NewReader(bytes.NewReader(payload)) + if err != nil { + return nil, backupManifest{}, fmt.Errorf("archive is not a valid gzip stream: %w", err) + } + defer gz.Close() + tr := tar.NewReader(gz) + for { + hdr, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return nil, backupManifest{}, fmt.Errorf("read archive: %w", err) + } + if hdr.Typeflag != tar.TypeReg { + continue + } + // Refuse absurd declared sizes before allocating. + if hdr.Size < 0 || hdr.Size > backupMaxFile { + return nil, backupManifest{}, fmt.Errorf("archive entry %q has an implausible size %d", hdr.Name, hdr.Size) + } + // Only the known members are restored. An archive naming something + // else must not be able to write outside the data directory. + if !allowedBackupName(hdr.Name) { + continue + } + data, err := io.ReadAll(io.LimitReader(tr, backupMaxFile+1)) + if err != nil { + return nil, backupManifest{}, fmt.Errorf("read %s from archive: %w", hdr.Name, err) + } + files[hdr.Name] = data + } + + var manifest backupManifest + manifestJSON, ok := files[backupManifestTyp] + if !ok { + return nil, backupManifest{}, errors.New("archive has no manifest") + } + if err := json.Unmarshal(manifestJSON, &manifest); err != nil { + return nil, backupManifest{}, fmt.Errorf("parse manifest: %w", err) + } + for _, e := range manifest.Files { + data, ok := files[e.Name] + if !ok { + return nil, backupManifest{}, fmt.Errorf("archive is missing %s, listed in the manifest", e.Name) + } + if int64(len(data)) != e.Size { + return nil, backupManifest{}, fmt.Errorf("%s is %d bytes, manifest says %d", e.Name, len(data), e.Size) + } + sum := sha256.Sum256(data) + if hex.EncodeToString(sum[:]) != e.SHA256 { + return nil, backupManifest{}, fmt.Errorf("%s does not match its manifest checksum", e.Name) + } + } + delete(files, backupManifestTyp) + if len(files) == 0 { + return nil, backupManifest{}, errors.New("archive contains no restorable files") + } + return files, manifest, nil +} + +// allowedBackupName keeps extraction to the exact set of members this tool +// writes, so a hostile archive cannot drop a file anywhere else. +func allowedBackupName(name string) bool { + if name == backupManifestTyp { + return true + } + for _, allowed := range backupFileNames { + if name == allowed { + return true + } + } + return false +} + +func copyFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + return err + } + return out.Close() +} + +// ─── pid file ─────────────────────────────────────────────────────────────── + +// The pid file is how restore knows a server is holding the database. It is +// best-effort: a read-only or unusual data directory must not stop the proxy +// from starting. + +func writePidFile(dataDir string) error { + if err := os.MkdirAll(dataDir, 0o750); err != nil { + return err + } + return os.WriteFile(filepath.Join(dataDir, backupPidName), + []byte(strconv.Itoa(os.Getpid())+"\n"), 0o600) +} + +func removePidFile(dataDir string) { + _ = os.Remove(filepath.Join(dataDir, backupPidName)) +} + +// runningServerPID reports the pid of a live server using this data directory. +// A pid file left behind by a crash is not treated as running. +func runningServerPID(dataDir string) (int, error) { + data, err := os.ReadFile(filepath.Join(dataDir, backupPidName)) + if err != nil { + return 0, err + } + pid, err := strconv.Atoi(strings.TrimSpace(string(data))) + if err != nil || pid <= 0 { + return 0, errors.New("no usable pid file") + } + if pid == os.Getpid() { + return pid, nil + } + // Signal 0 checks for existence without delivering anything. + if err := kill0(pid); err != nil { + return 0, errors.New("pid file is stale") + } + return pid, nil +} + +// listBackupContents prints an archive's manifest without restoring it, which +// is what an operator wants before overwriting a working installation. +func listBackupContents(path, passphrase string) error { + _, manifest, err := readBackupArchive(path, passphrase) + if err != nil { + return err + } + fmt.Fprintf(os.Stdout, "%s\n taken: %s by proxy %s\n", path, manifest.CreatedAt, manifest.ProxyVersion) + names := make([]string, 0, len(manifest.Files)) + for _, e := range manifest.Files { + names = append(names, e.Name) + } + sort.Strings(names) + for _, name := range names { + for _, e := range manifest.Files { + if e.Name == name { + fmt.Fprintf(os.Stdout, " %-22s %10d bytes sha256:%s\n", e.Name, e.Size, e.SHA256[:16]) + } + } + } + return nil +} + +// kill0 reports whether a process exists, without disturbing it. +func kill0(pid int) error { + return syscall.Kill(pid, 0) +} diff --git a/backup_test.go b/backup_test.go new file mode 100644 index 0000000..b211db9 --- /dev/null +++ b/backup_test.go @@ -0,0 +1,528 @@ +package main + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "database/sql" + "io" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" +) + +func quietStore(t *testing.T, dir string) *Store { + t.Helper() + store, err := NewStore(filepath.Join(dir, backupDBName), slog.New(slog.NewTextHandler(io.Discard, nil))) + if err != nil { + t.Fatalf("NewStore: %v", err) + } + t.Cleanup(func() { store.Close() }) + return store +} + +// seed writes something worth losing: users, config and a REALITY keypair. +func seed(t *testing.T, store *Store) { + t.Helper() + if _, err := store.CreateUser("alice", "pw", "pro"); err != nil { + t.Fatalf("CreateUser: %v", err) + } + if _, err := store.CreateUser("bob", "pw", "free"); err != nil { + t.Fatalf("CreateUser: %v", err) + } + for k, v := range map[string]string{ + dbRealityPrivateKey: "PRIVATE-KEY-UNDER-TEST", + dbRealityShortID: "0123456789abcdef", + dbRealityClientIDs: "uuid-one,uuid-two", + "proxy_pass": "stored-pass", + } { + if err := store.SaveConfig(k, v); err != nil { + t.Fatalf("SaveConfig %s: %v", k, err) + } + } +} + +// countUsers opens a connection, reads, and closes it before returning. +// +// Closing matters: SQLite does its WAL cleanup by *path* when the last +// connection to a database goes away, so a store still holding the old file +// after a restore has installed a new database at the same path can rewrite it +// on close. That is exactly why `restore` refuses to run while the server is +// up, and these helpers must not reproduce it inside the test. +func countUsers(t *testing.T, dir string) int { + t.Helper() + store := quietStore(t, dir) + defer store.Close() + var n int + if err := store.db.QueryRow("SELECT COUNT(*) FROM users").Scan(&n); err != nil { + t.Fatalf("count users: %v", err) + } + return n +} + +func storedConfig(t *testing.T, dir, key string) string { + t.Helper() + store := quietStore(t, dir) + defer store.Close() + var v string + err := store.db.QueryRow("SELECT value FROM config WHERE key = ?", key).Scan(&v) + if err == sql.ErrNoRows { + return "" + } + if err != nil { + t.Fatalf("read config %s: %v", key, err) + } + return v +} + +// ─── The round trip ───────────────────────────────────────────────────────── + +func TestBackupRestoreRoundTrip(t *testing.T) { + data := t.TempDir() + store := quietStore(t, data) + seed(t, store) + + config := filepath.Join(data, "config.json") + clientCfg := filepath.Join(data, "reality-client.json") + if err := os.WriteFile(config, []byte(`{"proxy_port":1080}`), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(clientCfg, []byte(`{"vnext":"placeholder"}`), 0o600); err != nil { + t.Fatal(err) + } + + archive := filepath.Join(t.TempDir(), "backup.tar.gz") + if err := runBackup([]string{"-out", archive, "-data", data, "-config", config, "-client-config", clientCfg}); err != nil { + t.Fatalf("backup: %v", err) + } + + // Wipe the installation the way a lost server would. + for _, name := range []string{backupDBName, backupDBName + "-wal", backupDBName + "-shm"} { + os.Remove(filepath.Join(data, name)) + } + os.Remove(config) + os.Remove(clientCfg) + if got := countUsers(t, data); got != 0 { + t.Fatalf("wipe left %d users behind", got) + } + + if err := runRestore([]string{"-in", archive, "-data", data, "-config", config, "-client-config", clientCfg}); err != nil { + t.Fatalf("restore: %v", err) + } + + if got := countUsers(t, data); got != 2 { + t.Errorf("restored %d users, want 2", got) + } + // The REALITY keypair is the part that silently breaks clients if lost. + for key, want := range map[string]string{ + dbRealityPrivateKey: "PRIVATE-KEY-UNDER-TEST", + dbRealityShortID: "0123456789abcdef", + dbRealityClientIDs: "uuid-one,uuid-two", + "proxy_pass": "stored-pass", + } { + if got := storedConfig(t, data, key); got != want { + t.Errorf("after restore %s = %q, want %q", key, got, want) + } + } + if _, err := os.Stat(config); err != nil { + t.Errorf("config.json was not restored: %v", err) + } + if _, err := os.Stat(clientCfg); err != nil { + t.Errorf("reality-client.json was not restored: %v", err) + } +} + +// The whole reason this uses VACUUM INTO: in WAL mode the newest writes live in +// the sidecar, so a plain file copy would silently lose them. +func TestBackupCapturesUncheckpointedWrites(t *testing.T) { + data := t.TempDir() + store := quietStore(t, data) + seed(t, store) + + // Write and leave it in the WAL: no checkpoint, no close. + if _, err := store.db.Exec(`INSERT INTO users (username, password_hash, tier, max_connections, bandwidth_mbps, data_limit_bytes) + VALUES ('carol', 'pw', 'free', 1, 1, 1024)`); err != nil { + t.Fatalf("insert: %v", err) + } + + wal, err := os.Stat(filepath.Join(data, backupDBName+"-wal")) + if err != nil { + t.Fatalf("expected a WAL sidecar to exist: %v", err) + } + if wal.Size() == 0 { + t.Fatal("expected uncheckpointed data in the WAL for this test to mean anything") + } + + archive := filepath.Join(t.TempDir(), "b.tar.gz") + if err := runBackup([]string{"-out", archive, "-data", data, "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("backup: %v", err) + } + + for _, name := range []string{backupDBName, backupDBName + "-wal", backupDBName + "-shm"} { + os.Remove(filepath.Join(data, name)) + } + if err := runRestore([]string{"-in", archive, "-data", data, "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("restore: %v", err) + } + + if got := countUsers(t, data); got != 3 { + t.Errorf("restored %d users, want 3: the snapshot lost writes that were still in the WAL", got) + } +} + +// ─── Encryption ───────────────────────────────────────────────────────────── + +func TestEncryptedBackupRoundTrip(t *testing.T) { + data := t.TempDir() + seed(t, quietStore(t, data)) + + archive := filepath.Join(t.TempDir(), "secret.tar.gz") + const pass = "correct horse battery staple" + if err := runBackup([]string{"-out", archive, "-data", data, "-passphrase", pass, + "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("backup: %v", err) + } + + raw, err := os.ReadFile(archive) + if err != nil { + t.Fatal(err) + } + // The database must not be sitting in the archive in the clear. + if bytes.Contains(raw, []byte("PRIVATE-KEY-UNDER-TEST")) { + t.Error("the archive contains the REALITY private key in plaintext despite -passphrase") + } + if !bytes.Contains(raw, []byte(backupMagic)) { + t.Error("archive is missing its magic header") + } + + for _, name := range []string{backupDBName, backupDBName + "-wal", backupDBName + "-shm"} { + os.Remove(filepath.Join(data, name)) + } + if err := runRestore([]string{"-in", archive, "-data", data, "-passphrase", pass, + "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("restore with the right passphrase: %v", err) + } + if got := countUsers(t, data); got != 2 { + t.Errorf("restored %d users, want 2", got) + } + if got := storedConfig(t, data, dbRealityPrivateKey); got != "PRIVATE-KEY-UNDER-TEST" { + t.Errorf("private key after restore = %q", got) + } +} + +func TestRestoreWrongPassphraseChangesNothing(t *testing.T) { + data := t.TempDir() + seed(t, quietStore(t, data)) + before := storedConfig(t, data, dbRealityPrivateKey) + + archive := filepath.Join(t.TempDir(), "secret.tar.gz") + if err := runBackup([]string{"-out", archive, "-data", data, "-passphrase", "right", + "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("backup: %v", err) + } + + err := runRestore([]string{"-in", archive, "-data", data, "-passphrase", "wrong", + "-config", filepath.Join(data, "none.json")}) + if err == nil { + t.Fatal("restoring with the wrong passphrase should fail") + } + if !strings.Contains(err.Error(), "passphrase") && !strings.Contains(err.Error(), "damaged") { + t.Errorf("error %q should name the passphrase as the likely cause", err) + } + // Nothing may have been replaced: this is the failure an operator meets + // at 3am, and it must not cost them the installation. + if got := storedConfig(t, data, dbRealityPrivateKey); got != before { + t.Errorf("private key changed to %q after a failed restore", got) + } + if got := countUsers(t, data); got != 2 { + t.Errorf("a failed restore left %d users, want the original 2", got) + } +} + +func TestRestorePassphraseMismatchesAreReportedClearly(t *testing.T) { + data := t.TempDir() + seed(t, quietStore(t, data)) + plain := filepath.Join(t.TempDir(), "plain.tar.gz") + if err := runBackup([]string{"-out", plain, "-data", data, "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("backup: %v", err) + } + + if err := runRestore([]string{"-in", plain, "-data", data, "-passphrase", "invented", + "-config", filepath.Join(data, "none.json")}); err == nil || !strings.Contains(err.Error(), "not encrypted") { + t.Errorf("giving a passphrase for a plain archive: err = %v, want a clear complaint", err) + } + + enc := filepath.Join(t.TempDir(), "enc.tar.gz") + if err := runBackup([]string{"-out", enc, "-data", data, "-passphrase", "p", + "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("encrypted backup: %v", err) + } + if err := runRestore([]string{"-in", enc, "-data", data, "-config", filepath.Join(data, "none.json")}); err == nil || + !strings.Contains(err.Error(), "passphrase is required") { + t.Errorf("restoring an encrypted archive with no passphrase: err = %v", err) + } +} + +// ─── Tampering and shape ──────────────────────────────────────────────────── + +func TestRestoreRejectsTamperedArchive(t *testing.T) { + data := t.TempDir() + seed(t, quietStore(t, data)) + archive := filepath.Join(t.TempDir(), "b.tar.gz") + if err := runBackup([]string{"-out", archive, "-data", data, "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("backup: %v", err) + } + + raw, err := os.ReadFile(archive) + if err != nil { + t.Fatal(err) + } + // Flip a byte deep inside the compressed payload. + raw[len(raw)/2] ^= 0xff + if err := os.WriteFile(archive, raw, 0o600); err != nil { + t.Fatal(err) + } + + for _, name := range []string{backupDBName, backupDBName + "-wal", backupDBName + "-shm"} { + os.Remove(filepath.Join(data, name)) + } + if err := runRestore([]string{"-in", archive, "-data", data, "-config", filepath.Join(data, "none.json")}); err == nil { + t.Fatal("a tampered archive should not restore") + } + if _, err := os.Stat(filepath.Join(data, backupDBName)); err == nil { + t.Error("a failed restore left a database behind") + } +} + +func TestRestoreRejectsForeignArchives(t *testing.T) { + data := t.TempDir() + notOurs := filepath.Join(t.TempDir(), "random.bin") + if err := os.WriteFile(notOurs, bytes.Repeat([]byte("A"), 4096), 0o600); err != nil { + t.Fatal(err) + } + if err := runRestore([]string{"-in", notOurs, "-data", data}); err == nil || + !strings.Contains(err.Error(), "not a socks5-proxy backup") { + t.Errorf("restore of a foreign file: err = %v", err) + } + + // Correct magic, wrong version: must be refused rather than guessed at. + wrongVersion := filepath.Join(t.TempDir(), "future.tar.gz") + raw := append([]byte(backupMagic), 99, 0) + if err := os.WriteFile(wrongVersion, raw, 0o600); err != nil { + t.Fatal(err) + } + if err := runRestore([]string{"-in", wrongVersion, "-data", data}); err == nil || + !strings.Contains(err.Error(), "archive version") { + t.Errorf("restore of a newer archive: err = %v", err) + } +} + +func newGzip(w io.Writer) *gzip.Writer { return gzip.NewWriter(w) } + +func newTar(gz *gzip.Writer) *tar.Writer { return tar.NewWriter(gz) } + +func writeEntry(t *testing.T, tw *tar.Writer, name string, data []byte) { + t.Helper() + if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(data)), Typeflag: tar.TypeReg}); err != nil { + t.Fatal(err) + } + if _, err := tw.Write(data); err != nil { + t.Fatal(err) + } +} + +// An archive naming a file outside the known set must not be able to write it. +func TestRestoreIgnoresUnknownArchiveMembers(t *testing.T) { + data := t.TempDir() + seed(t, quietStore(t, data)) + + // Build an archive by hand with a member this tool never writes. + var payload bytes.Buffer + gz := newGzip(&payload) + tw := newTar(gz) + writeEntry(t, tw, backupManifestTyp, []byte(`{"created_at":"now","proxy_version":"x","files":[{"name":"socks5.db","size":0,"sha256":""}]}`)) + writeEntry(t, tw, "../escaped.db", []byte("owned")) + gz.Close() + tw.Close() + + archive := filepath.Join(t.TempDir(), "hostile.tar.gz") + header := append([]byte(backupMagic), backupVersion, backupFlagPlain) + if err := os.WriteFile(archive, append(header, payload.Bytes()...), 0o600); err != nil { + t.Fatal(err) + } + + err := runRestore([]string{"-in", archive, "-data", data, "-config", filepath.Join(data, "none.json")}) + // The manifest names socks5.db, which is absent, so it fails for that + // reason; what matters is that nothing escaped. + if err != nil && !strings.Contains(err.Error(), "missing socks5.db") { + t.Errorf("unexpected error: %v", err) + } + if _, statErr := os.Stat(filepath.Join(filepath.Dir(data), "escaped.db")); statErr == nil { + t.Error("a path-traversal member was written outside the data directory") + } +} + +func TestBackupRefusesWhenServerRunning(t *testing.T) { + data := t.TempDir() + seed(t, quietStore(t, data)) + archive := filepath.Join(t.TempDir(), "b.tar.gz") + if err := runBackup([]string{"-out", archive, "-data", data, "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("backup: %v", err) + } + + // This process is alive, so its pid is exactly the "server is running" + // condition restore has to catch. + if err := writePidFile(data); err != nil { + t.Fatalf("writePidFile: %v", err) + } + defer removePidFile(data) + + if _, err := runningServerPID(data); err != nil { + t.Fatalf("runningServerPID: %v", err) + } + err := runRestore([]string{"-in", archive, "-data", data, "-config", filepath.Join(data, "none.json")}) + if err == nil || !strings.Contains(err.Error(), "server is running") { + t.Errorf("restore over a live server: err = %v, want a refusal", err) + } + + // -force is the documented escape hatch and must work. + if err := runRestore([]string{"-in", archive, "-data", data, "-force", + "-config", filepath.Join(data, "none.json")}); err != nil { + t.Errorf("restore -force: %v", err) + } +} + +func TestStalePidFileIsNotTreatedAsRunning(t *testing.T) { + data := t.TempDir() + // A pid that cannot be running: kernel pids max out well below this. + if err := os.WriteFile(filepath.Join(data, backupPidName), []byte("4194303\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := runningServerPID(data); err == nil { + t.Error("a pid file from a crashed process should not block a restore") + } +} + +func TestRestoreKeepsTheExistingDatabase(t *testing.T) { + data := t.TempDir() + seed(t, quietStore(t, data)) + archive := filepath.Join(t.TempDir(), "b.tar.gz") + if err := runBackup([]string{"-out", archive, "-data", data, "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("backup: %v", err) + } + if err := runRestore([]string{"-in", archive, "-data", data, "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("restore: %v", err) + } + + matches, err := filepath.Glob(filepath.Join(data, backupDBName+".pre-restore-*")) + if err != nil || len(matches) != 1 { + t.Fatalf("found %d pre-restore copies, want exactly 1 (%v)", len(matches), err) + } +} + +func TestBackupListDoesNotTouchAnything(t *testing.T) { + data := t.TempDir() + seed(t, quietStore(t, data)) + archive := filepath.Join(t.TempDir(), "b.tar.gz") + if err := runBackup([]string{"-out", archive, "-data", data, "-config", filepath.Join(data, "none.json")}); err != nil { + t.Fatalf("backup: %v", err) + } + for _, name := range []string{backupDBName, backupDBName + "-wal", backupDBName + "-shm"} { + os.Remove(filepath.Join(data, name)) + } + if err := listBackupContents(archive, ""); err != nil { + t.Fatalf("list: %v", err) + } + if _, err := os.Stat(filepath.Join(data, backupDBName)); err == nil { + t.Error("-list restored something; it must only print") + } +} + +func TestBackupRequiresDatabase(t *testing.T) { + data := t.TempDir() + archive := filepath.Join(t.TempDir(), "b.tar.gz") + err := runBackup([]string{"-out", archive, "-data", data, "-config", filepath.Join(data, "none.json")}) + if err == nil || !strings.Contains(err.Error(), "no database") { + t.Errorf("backup with no database: err = %v, want a clear refusal", err) + } + if _, statErr := os.Stat(archive); statErr == nil { + t.Error("a failed backup left an archive behind") + } +} + +// ─── The pragmas this database actually runs with ─────────────────────────── + +// The DSN used to spell these the mattn/go-sqlite3 way, which modernc.org +// silently ignores. WAL matters most here: the snapshot design rests on it, and +// a file copy in rollback-journal mode can miss a transaction that was in +// flight when the copy was taken. +func TestDatabaseRunsInWALMode(t *testing.T) { + store := quietStore(t, t.TempDir()) + + var mode string + if err := store.db.QueryRow("PRAGMA journal_mode").Scan(&mode); err != nil { + t.Fatalf("read journal_mode: %v", err) + } + if mode != "wal" { + t.Errorf("journal_mode = %q, want wal", mode) + } + + var fk int + if err := store.db.QueryRow("PRAGMA foreign_keys").Scan(&fk); err != nil { + t.Fatalf("read foreign_keys: %v", err) + } + if fk != 1 { + t.Errorf("foreign_keys = %d, want 1: the schema declares a foreign key and nothing was enforcing it", fk) + } +} + +// Turning foreign keys on makes an orphaned reference an error rather than +// silent corruption. This asserts the enforcement is real, not just reported. +func TestForeignKeysAreEnforced(t *testing.T) { + store := quietStore(t, t.TempDir()) + user, err := store.CreateUser("dave", "pw", "free") + if err != nil { + t.Fatal(err) + } + + if _, err := store.db.Exec( + `INSERT INTO user_connections (user_id, target) VALUES (?, 'example.com:443')`, user.ID+9999); err == nil { + t.Fatal("inserting a connection for a user that does not exist should fail") + } +} + +// The regression the foreign-key change would otherwise cause: deleting a user +// who has connection history must still work through the dashboard. +func TestDeleteUserWithConnectionHistory(t *testing.T) { + store := quietStore(t, t.TempDir()) + user, err := store.CreateUser("erin", "pw", "free") + if err != nil { + t.Fatal(err) + } + if _, err := store.TrackConnectionStart(user.ID, "example.com:443"); err != nil { + t.Fatalf("TrackConnectionStart: %v", err) + } + + var count int + if err := store.db.QueryRow("SELECT COUNT(*) FROM user_connections WHERE user_id = ?", user.ID).Scan(&count); err != nil { + t.Fatal(err) + } + if count == 0 { + t.Fatal("expected recorded connection history for this test to mean anything") + } + + if err := store.DeleteUser(user.ID); err != nil { + t.Fatalf("DeleteUser with history present: %v", err) + } + var users, connections int + store.db.QueryRow("SELECT COUNT(*) FROM users WHERE id = ?", user.ID).Scan(&users) + store.db.QueryRow("SELECT COUNT(*) FROM user_connections WHERE user_id = ?", user.ID).Scan(&connections) + if users != 0 { + t.Errorf("user row survived deletion") + } + if connections != 0 { + t.Errorf("%d connection rows survived their user", connections) + } +} diff --git a/database.go b/database.go index 09836b4..8129ffa 100644 --- a/database.go +++ b/database.go @@ -30,7 +30,29 @@ func NewStore(dbPath string, logger *slog.Logger) (*Store, error) { } } - db, err := sql.Open("sqlite", dbPath+"?_journal_mode=WAL&_busy_timeout=5000&_synchronous=NORMAL&_foreign_keys=ON") + // Pragma syntax matters here. The driver is modernc.org/sqlite, which takes + // `_pragma=name(value)`; the `_journal_mode=WAL` form belongs to + // mattn/go-sqlite3 and is silently ignored by this one. + // + // That was not a cosmetic mistake. Every one of these was being dropped on + // the floor, and each has a consequence: + // + // journal_mode was "delete", not WAL: readers blocked the writer and + // the newest writes could sit in a rollback journal that a + // naive file copy would miss. + // busy_timeout was 0, so a concurrent write returned SQLITE_BUSY + // immediately instead of waiting the intended 5s. + // foreign_keys was OFF, so `user_connections` could reference a deleted + // user and nothing complained. + // synchronous was FULL (2), not NORMAL: an extra fsync per commit for + // no benefit on a volume that is not a single-disk array. + // + // Verified with PRAGMA journal_mode on both spellings rather than assumed. + db, err := sql.Open("sqlite", dbPath+ + "?_pragma=journal_mode(WAL)"+ + "&_pragma=busy_timeout(5000)"+ + "&_pragma=foreign_keys(1)"+ + "&_pragma=synchronous(NORMAL)") if err != nil { return nil, fmt.Errorf("open database: %w", err) } @@ -522,12 +544,29 @@ func (s *Store) UpdateUser(id int64, tier *string, password *string, enabled *bo return nil } +// DeleteUser removes an account and everything recorded against it. +// +// The children go first, in one transaction. Foreign keys are now actually +// enforced (see NewStore), so deleting the parent with connection history +// still attached would fail with a constraint error and leave the operator +// unable to remove a user through the dashboard. func (s *Store) DeleteUser(id int64) error { s.mu.Lock() defer s.mu.Unlock() - _, err := s.db.Exec("DELETE FROM users WHERE id=?", id) - return err + tx, err := s.db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + if _, err := tx.Exec("DELETE FROM user_connections WHERE user_id = ?", id); err != nil { + return err + } + if _, err := tx.Exec("DELETE FROM users WHERE id = ?", id); err != nil { + return err + } + return tx.Commit() } func (s *Store) ResetUserData(id int64) error { diff --git a/main.go b/main.go index e3d2797..a80bfb5 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,7 @@ import ( "net/http" "os" "os/signal" + "path/filepath" "sort" "strconv" "strings" @@ -1917,6 +1918,18 @@ func main() { os.Exit(1) } return + case "backup": + if err := runBackup(os.Args[2:]); err != nil { + logger.Error("backup failed", "error", err) + os.Exit(1) + } + return + case "restore": + if err := runRestore(os.Args[2:]); err != nil { + logger.Error("restore failed", "error", err) + os.Exit(1) + } + return case "reality-client": if err := runRealityClient(os.Args[2:]); err != nil { logger.Error("reality client failed", "error", err) @@ -1960,6 +1973,14 @@ func runServer(logger *slog.Logger, configFile string) { } defer store.Close() + // Publish the pid so `restore` can refuse to overwrite a database a live + // server still has open. Best effort: a data directory that will not take + // the file must not stop the proxy from starting. + if err := writePidFile(filepath.Dir(dbPath)); err != nil { + logger.Warn("could not write pid file; `restore` will not detect a running server", "error", err) + } + defer removePidFile(filepath.Dir(dbPath)) + // Load persisted config overrides from DB dbCfg := store.LoadConfig() if applied := applyDBOverrides(&cfg, dbCfg); len(applied) > 0 {