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 {