From 05f7aa94bbe15af6ef1e2d36144978c0d7e20f66 Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sat, 17 Oct 2026 18:30:27 +0500 Subject: [PATCH 1/3] Manage VLESS client UUIDs from the dashboard Until now the REALITY client list was a comma-joined config value, so revoking a UUID meant editing configuration and restarting the service. A management screen that only takes effect on restart is a trap, so this makes the change real. The list lives in a vless_clients table, one row per client. Precedence is unchanged in spirit: REALITY_CLIENT_IDS still pins the list from configuration and now says so, because accepting edits that quietly do nothing is worse than refusing them. An id left behind by the old comma-joined value is adopted into the table on first run rather than dropped -- otherwise the first dashboard change would revoke a client that is still in the field. Making it live meant teaching the xray supervisor to re-point itself. The reload carries a config that has already passed `xray run --test`, so an invalid change is refused and the running front door keeps serving; the supervisor is the only thing that stops and starts the child, and it answers once the new child is actually accepting connections. Measured live: an add applies in 0.08s. Two refusals worth having. Removing the last client is rejected, because xray with no clients is a front door that rejects everyone and an operator should have to mean it. And a refused change restores the row rather than dropping it, so the database never claims something xray does not do. Verified live against xray on a real port: a UUID added through the API served traffic immediately, the same client failed the moment it was revoked, the untouched client kept working, and xray's own log named the refusal (proxy/vless/encoding: rejected). Covered end to end in tests too, including the case the race detector caught on the way: s.cfg is written under configMu while being read here. --- README.md | 18 +- database.go | 150 ++++++++++++++ main.go | 157 ++++++++++++++- reality.go | 348 +++++++++++++++++++++++++++----- reality_test.go | 14 +- vless_test.go | 526 ++++++++++++++++++++++++++++++++++++++++++++++++ web/index.html | 144 +++++++++++++ 7 files changed, 1300 insertions(+), 57 deletions(-) create mode 100644 vless_test.go diff --git a/README.md b/README.md index 65bf066..2d45693 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Deploys on any PaaS, including the ones that expose only a single HTTP endpoint. - **Single-Port Multiplexing** - SOCKS5, TLS, dashboards and the tunnel share one port, so it runs on Render/Koyeb/Heroku/Northflank where raw TCP never reaches the app - **WebSocket Tunnel** - Carries SOCKS5 over an HTTP upgrade for platforms whose edge terminates TLS; ships with a matching client - **REALITY** - Xray front door that presents a real website's certificate to an active prober; sessions still land in the SOCKS5 pipeline +- **VLESS Client Management** - Add, disable and revoke REALITY UUIDs from the dashboard; xray is reloaded in place, no restart - **Client Mode** - Same binary exposes a local SOCKS5 port that relays through the tunnel - **User Management** - Create, update, delete users with tier-based limits - **Tier System** - Free, Basic, Pro, and Unlimited tiers with connection/data/bandwidth limits @@ -310,8 +311,14 @@ other REALITY-capable client can import the same parameters instead: | Fingerprint | `chrome` | | Flow | none | -Give each device its own UUID (`xray uuid`, then list them in -`REALITY_CLIENT_IDS`) so one can be revoked without disturbing the others. +Give each device its own UUID so one can be revoked without disturbing the +others. The dashboard's **REALITY Clients** panel is the usual way: add a client, +and the UUID reaches xray immediately. Revoking one takes effect within a second +and needs no restart. + +Setting `REALITY_CLIENT_IDS` still works, and pins the list from configuration: +while it is set the panel says so and refuses changes rather than accepting edits +that would quietly do nothing. `REALITY_BIND` defaults to `0.0.0.0:443`, which is IPv4 only. On an IPv6-only host set it to `[::]:443`. @@ -390,7 +397,7 @@ Edit `config.json` or use environment variables (env vars override config file): | `REALITY_SERVER_NAMES` | dest host | SNI values to impersonate, comma separated | | `REALITY_PRIVATE_KEY` | generated | REALITY private key. Generated once and reused from the database when empty; `xray x25519` prints a pair | | `REALITY_SHORT_IDS` | generated | Short ids, comma separated. Up to 16 hex characters; rotating locks out existing clients | -| `REALITY_CLIENT_IDS` | generated | VLESS UUIDs, comma separated, one per device. `xray uuid` prints one | +| `REALITY_CLIENT_IDS` | generated | VLESS UUIDs, comma separated. Pins the list and disables panel management | | `REALITY_PUBLIC_HOST` | empty | This host's IP or domain, written into the generated client config so it is usable as-is | | `XRAY_BIN` | xray | Path to the xray binary | | `REALITY_CLIENT_FILE` | reality-client.json | Where the generated client config is written | @@ -454,8 +461,9 @@ 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. +working**, because the keypair travels with it and the managed VLESS UUIDs live +in the database; 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 diff --git a/database.go b/database.go index 8129ffa..ec18546 100644 --- a/database.go +++ b/database.go @@ -8,6 +8,7 @@ import ( "log/slog" "os" "path/filepath" + "strings" "sync" "time" @@ -121,6 +122,16 @@ func (s *Store) migrate() error { )`, `CREATE INDEX IF NOT EXISTS idx_user_connections_user ON user_connections(user_id)`, `CREATE INDEX IF NOT EXISTS idx_user_connections_time ON user_connections(connected_at)`, + // VLESS client UUIDs for the REALITY front door. One row per client, so + // a revoked id is a deleted or disabled row rather than an edit of a + // comma-joined string, and the dashboard has a name to show for each. + `CREATE TABLE IF NOT EXISTS vless_clients ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + uuid TEXT UNIQUE NOT NULL, + label TEXT NOT NULL DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + )`, } for _, q := range queries { @@ -577,6 +588,145 @@ func (s *Store) ResetUserData(id int64) error { return err } +// ─── VLESS clients ───────────────────────────────────────────────────────── +// +// The UUIDs xray accepts on the REALITY inbound. Only enabled rows reach the +// rendered config, so disabling one revokes it without deleting the record. + +type VlessClient struct { + ID int64 `json:"id"` + UUID string `json:"uuid"` + Label string `json:"label"` + Enabled bool `json:"enabled"` + CreatedAt string `json:"created_at"` +} + +// IsUUID reports whether s looks like a UUID xray would accept. Deliberately +// shape-only: this is the trust boundary between an operator typing into the +// dashboard and the xray config, so the check is cheap and never guesses. +func IsUUID(s string) bool { + if len(s) != 36 { + return false + } + for i, c := range s { + switch i { + case 8, 13, 18, 23: + if c != '-' { + return false + } + default: + if !strings.ContainsRune("0123456789abcdefABCDEF", c) { + return false + } + } + } + return true +} + +func (s *Store) CreateVlessClient(uuid, label string) (*VlessClient, error) { + uuid = strings.TrimSpace(uuid) + if !IsUUID(uuid) { + return nil, fmt.Errorf("%q is not a UUID", uuid) + } + s.mu.Lock() + res, err := s.db.Exec("INSERT INTO vless_clients (uuid, label) VALUES (?, ?)", uuid, label) + if err != nil { + s.mu.Unlock() + return nil, err + } + id, err := res.LastInsertId() + s.mu.Unlock() + if err != nil { + return nil, err + } + // Read the row back rather than echoing the arguments: created_at is a + // database default, and a response that shows it empty is worse than one + // that shows the truth. + return s.GetVlessClient(id) +} + +func (s *Store) ListVlessClients() ([]VlessClient, error) { + s.mu.Lock() + defer s.mu.Unlock() + + rows, err := s.db.Query("SELECT id, uuid, label, enabled, created_at FROM vless_clients ORDER BY id") + if err != nil { + return nil, err + } + defer rows.Close() + + out := []VlessClient{} + for rows.Next() { + var c VlessClient + var enabled int + if err := rows.Scan(&c.ID, &c.UUID, &c.Label, &enabled, &c.CreatedAt); err != nil { + return nil, err + } + c.Enabled = enabled != 0 + out = append(out, c) + } + return out, rows.Err() +} + +// EnabledVlessClientUUIDs is what the xray config is rendered from. +func (s *Store) EnabledVlessClientUUIDs() ([]string, error) { + clients, err := s.ListVlessClients() + if err != nil { + return nil, err + } + out := make([]string, 0, len(clients)) + for _, c := range clients { + if c.Enabled { + out = append(out, c.UUID) + } + } + return out, nil +} + +func (s *Store) GetVlessClient(id int64) (*VlessClient, error) { + s.mu.Lock() + defer s.mu.Unlock() + + var c VlessClient + var enabled int + err := s.db.QueryRow("SELECT id, uuid, label, enabled, created_at FROM vless_clients WHERE id=?", id). + Scan(&c.ID, &c.UUID, &c.Label, &enabled, &c.CreatedAt) + if err != nil { + return nil, err + } + c.Enabled = enabled != 0 + return &c, nil +} + +func (s *Store) UpdateVlessClient(id int64, label *string, enabled *bool) error { + s.mu.Lock() + defer s.mu.Unlock() + + if label != nil { + if _, err := s.db.Exec("UPDATE vless_clients SET label=? WHERE id=?", *label, id); err != nil { + return err + } + } + if enabled != nil { + value := 0 + if *enabled { + value = 1 + } + if _, err := s.db.Exec("UPDATE vless_clients SET enabled=? WHERE id=?", value, id); err != nil { + return err + } + } + return nil +} + +func (s *Store) DeleteVlessClient(id int64) error { + s.mu.Lock() + defer s.mu.Unlock() + + _, err := s.db.Exec("DELETE FROM vless_clients WHERE id=?", id) + return err +} + // ─── Connection Tracking ─────────────────────────────────────────────────── func (s *Store) TrackConnectionStart(userID int64, target string) (int64, error) { diff --git a/main.go b/main.go index 08b4d25..36f7f73 100644 --- a/main.go +++ b/main.go @@ -538,6 +538,14 @@ type ProxyServer struct { // Persistence store *Store + // REALITY front door. The runner is nil unless REALITY_ENABLED is set, and + // realityKeys is the key material its config was rendered from, so a + // dashboard change to the VLESS client list can be re-rendered and swapped + // in without a restart. + realityMu sync.Mutex + reality *realityRunner + realityKeys realityKeys + // Shutdown shutdownOnce sync.Once shutdownCh chan struct{} @@ -1736,6 +1744,150 @@ func (s *ProxyServer) adminHandler() http.Handler { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) }) + // ─── VLESS clients (REALITY) ────────────────────────────────────────── + // + // A UUID added here is accepted by xray within a second, and a deleted or + // disabled one stops working just as fast. Management that only took + // effect on restart would be a trap. + + mux.HandleFunc("/api/vless-clients", func(w http.ResponseWriter, r *http.Request) { + if s.store == nil { + http.Error(w, "database not available", http.StatusServiceUnavailable) + return + } + + switch r.Method { + case http.MethodGet: + clients, err := s.store.ListVlessClients() + if err != nil { + http.Error(w, "list failed: "+err.Error(), http.StatusInternalServerError) + return + } + s.realityMu.Lock() + enabled := s.reality != nil + s.realityMu.Unlock() + s.configMu.RLock() + pinned := len(s.cfg.RealityClientIDs) > 0 + s.configMu.RUnlock() + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{ + "clients": clients, + "reality_enabled": enabled, + "managed_by_config": pinned, + }) + + case http.MethodPost: + if err := s.requireRealityManager(w); err != nil { + return + } + var req struct { + UUID string `json:"uuid"` + Label string `json:"label"` + } + if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { + http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) + return + } + s.configMu.RLock() + xrayBin := s.cfg.RealityXrayBin + s.configMu.RUnlock() + + uuid := strings.TrimSpace(req.UUID) + if uuid == "" { + generated, err := generateVlessUUID(xrayBin) + if err != nil { + http.Error(w, "could not generate a uuid: "+err.Error(), http.StatusInternalServerError) + return + } + uuid = generated + } + client, err := s.store.CreateVlessClient(uuid, req.Label) + if err != nil { + http.Error(w, "create failed: "+err.Error(), http.StatusBadRequest) + return + } + if err := s.applyVlessClients(); err != nil { + // The row is saved, so removing it here keeps the database and + // the running xray telling the same story. + s.store.DeleteVlessClient(client.ID) + http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(client) + + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } + }) + + mux.HandleFunc("/api/vless-clients/", func(w http.ResponseWriter, r *http.Request) { + if s.store == nil { + http.Error(w, "database not available", http.StatusServiceUnavailable) + return + } + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/vless-clients/"), "/") + if len(parts) == 0 || parts[0] == "" { + http.Error(w, "client ID required", http.StatusBadRequest) + return + } + id := parseInt64(parts[0]) + + switch { + case r.Method == http.MethodDelete && len(parts) == 1: + if err := s.requireRealityManager(w); err != nil { + return + } + client, err := s.store.GetVlessClient(id) + if err != nil { + http.Error(w, "client not found", http.StatusNotFound) + return + } + if err := s.store.DeleteVlessClient(id); err != nil { + http.Error(w, "delete failed: "+err.Error(), http.StatusInternalServerError) + return + } + if err := s.applyVlessClients(); err != nil { + // Put the row back: xray never stopped accepting it, so the + // database must not claim otherwise. + if _, rerr := s.store.CreateVlessClient(client.UUID, client.Label); rerr != nil { + s.logger.Error("could not restore a refused vless client", "uuid", client.UUID, "error", rerr) + } + http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"status": "deleted"}) + + case r.Method == http.MethodPut && len(parts) == 1: + if err := s.requireRealityManager(w); err != nil { + return + } + var req struct { + Label *string `json:"label"` + Enabled *bool `json:"enabled"` + } + if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { + http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) + return + } + if err := s.store.UpdateVlessClient(id, req.Label, req.Enabled); err != nil { + http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError) + return + } + if err := s.applyVlessClients(); err != nil { + http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"status": "updated"}) + + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } + }) + // GET /api/tiers - list available tiers mux.HandleFunc("/api/tiers", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { @@ -2079,12 +2231,15 @@ func runServer(logger *slog.Logger, configFile string) { // rather than leaving a front door that never came up. var reality *realityRunner if cfg.RealityEnabled { - runner, err := startRealityForServer(cfg, dbCfg, store, logger) + runner, keys, err := startRealityForServer(cfg, dbCfg, store, logger) if err != nil { logger.Error("failed to start REALITY", "error", err) os.Exit(1) } reality = runner + // Handed to the server so the dashboard can add and revoke VLESS + // clients without a restart. + server.reality, server.realityKeys = runner, keys } // Periodic stats persistence (every 60 seconds) diff --git a/reality.go b/reality.go index 7ef496d..ff590f0 100644 --- a/reality.go +++ b/reality.go @@ -10,6 +10,7 @@ import ( "fmt" "log/slog" "net" + "net/http" "os" "os/exec" "path/filepath" @@ -445,12 +446,22 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l keys.ShortID = hex.EncodeToString(raw) } + // Client UUIDs, in precedence order: + // + // 1. REALITY_CLIENT_IDS. Configuration pinning always wins, which is the + // same promise the rest of the environment handling makes. + // 2. The vless_clients table, which the dashboard manages. + // 3. The legacy comma-joined config value, adopted into the table on first + // run so an upgrade does not revoke anyone's UUID. + // 4. A generated one, which becomes a table row so it survives a restart. keys.ClientIDs = nonEmpty(cfg.RealityClientIDs) - if len(keys.ClientIDs) == 0 && persisted[dbRealityClientIDs] != "" { - keys.ClientIDs = splitList(persisted[dbRealityClientIDs]) + if len(keys.ClientIDs) == 0 && store != nil { + keys.ClientIDs, _ = store.EnabledVlessClientUUIDs() + if len(keys.ClientIDs) == 0 && persisted[dbRealityClientIDs] != "" { + keys.ClientIDs = adoptLegacyClientIDs(store, splitList(persisted[dbRealityClientIDs]), logger) + } } - generatedIDs := len(keys.ClientIDs) == 0 - if generatedIDs { + if len(keys.ClientIDs) == 0 { out, err := runXray(bin, "uuid") if err != nil { return keys, err @@ -461,6 +472,13 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l if len(keys.ClientIDs) == 0 { return keys, errors.New("xray uuid returned no id") } + if store != nil { + // A UUID that changes on every restart would silently break every + // saved client profile, so the generated one is stored. + if _, err := store.CreateVlessClient(keys.ClientIDs[0], "generated"); err != nil { + logger.Warn("could not store the generated VLESS id; it will change on restart", "error", err) + } + } } if keys.ServerName = firstNonEmpty(cfg.RealityServerNames...); keys.ServerName == "" { @@ -478,14 +496,32 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l if generatedShortID { saveRealitySetting(store, logger, dbRealityShortID, keys.ShortID) } - if generatedIDs { - saveRealitySetting(store, logger, dbRealityClientIDs, strings.Join(keys.ClientIDs, ",")) - } } return keys, nil } +// adoptLegacyClientIDs moves an id list from the old comma-joined config value +// into the table. Without this, the first dashboard change would drop the ids +// that upgrade brought with it, because the table would then shadow the config. +func adoptLegacyClientIDs(store *Store, ids []string, logger *slog.Logger) []string { + for _, id := range ids { + if !IsUUID(id) { + continue + } + if _, err := store.CreateVlessClient(id, "migrated"); err != nil { + logger.Warn("could not migrate a REALITY client id; it will be dropped from the managed list", "error", err) + continue + } + } + kept, err := store.EnabledVlessClientUUIDs() + if err != nil { + logger.Warn("could not read the migrated VLESS ids", "error", err) + return nil + } + return kept +} + func saveRealitySetting(store *Store, logger *slog.Logger, key, value string) { if err := store.SaveConfig(key, value); err != nil { // Non-fatal: the value is still in use this run, it just will not @@ -566,73 +602,100 @@ func pruneStaleRealityConfigs(maxAge time.Duration) { // realityRunner owns the xray child process. type realityRunner struct { - bin string - cfgFile string - logger *slog.Logger + bin string + logger *slog.Logger + host string + port int mu sync.Mutex + cfgFile string // owned by supervise() once running; read under mu elsewhere cmd *exec.Cmd stopped bool + reload chan realityReload stop chan struct{} exited chan struct{} } +// realityReload asks the supervisor to swap in a new, already validated config +// file. The supervisor replies on done; a nil error means xray is running on the +// new file. +type realityReload struct { + cfgFile string + done chan error +} + // startReality validates the rendered config before serving, so a broken setup // fails loudly at startup instead of leaving a silent dead front door. func startReality(cfg Config, k realityKeys, logger *slog.Logger) (*realityRunner, error) { - data, err := renderRealityServerConfig(cfg, k) + bin := cfg.RealityXrayBin + if bin == "" { + bin = "xray" + } + cfgFile, err := renderValidatedServerConfig(bin, cfg, k) if err != nil { return nil, err } + pruneStaleRealityConfigs(24 * time.Hour) + + r := &realityRunner{ + bin: bin, + cfgFile: cfgFile, + logger: logger, + reload: make(chan realityReload, 1), + stop: make(chan struct{}), + exited: make(chan struct{}), + } + if host, port, err := splitHostPort(cfg.RealityBind); err == nil { + r.host, r.port = host, port + } + go r.supervise() + + r.waitReady() + return r, nil +} + +// renderValidatedServerConfig writes the config to a private temp file and asks +// xray to parse it. A config that does not validate is deleted and reported, so +// a bad change never takes a working front door down. +func renderValidatedServerConfig(bin string, cfg Config, k realityKeys) (string, error) { + data, err := renderRealityServerConfig(cfg, k) + if err != nil { + return "", err + } + file, err := os.CreateTemp("", "xray-reality-*.json") if err != nil { - return nil, fmt.Errorf("write xray config: %w", err) + return "", fmt.Errorf("write xray config: %w", err) } cfgFile := file.Name() if _, err := file.Write(data); err != nil { file.Close() os.Remove(cfgFile) - return nil, fmt.Errorf("write xray config: %w", err) + return "", fmt.Errorf("write xray config: %w", err) } file.Close() // CreateTemp already opens 0600, which matters: the file holds the REALITY // private key and the proxy credentials. - bin := cfg.RealityXrayBin - if bin == "" { - bin = "xray" - } if _, err := runXray(bin, "run", "-c", cfgFile, "--test"); err != nil { // runXray already carries xray's own complaint, which is the part worth // reading ("failed to listen...", "invalid private key", and so on). os.Remove(cfgFile) - return nil, err - } - - pruneStaleRealityConfigs(24 * time.Hour) - - r := &realityRunner{ - bin: bin, - cfgFile: cfgFile, - logger: logger, - stop: make(chan struct{}), - exited: make(chan struct{}), + return "", err } - go r.supervise() - - if host, port, err := splitHostPort(cfg.RealityBind); err == nil { - r.waitReady(host, port, 10*time.Second) - } - return r, nil + return cfgFile, nil } // waitReady logs whether the REALITY port started answering. A failure here is // not fatal: xray may still be retrying, and its own log carries the reason. -func (r *realityRunner) waitReady(host string, port int, timeout time.Duration) { - target := net.JoinHostPort(host, strconv.Itoa(port)) - deadline := time.Now().Add(timeout) +func (r *realityRunner) waitReady() { + if r.host == "" { + return + } + target := net.JoinHostPort(r.host, strconv.Itoa(r.port)) + deadline := time.Now().Add(10 * time.Second) for time.Now().Before(deadline) { conn, err := net.DialTimeout("tcp", target, 300*time.Millisecond) if err == nil { @@ -646,9 +709,19 @@ func (r *realityRunner) waitReady(host string, port int, timeout time.Duration) // supervise keeps xray alive. Without this a single crash would silently remove // the front door while every dashboard still reported a healthy proxy. +// +// It is also the only place the child is started, stopped and re-pointed, which +// is what makes a config swap safe: the new file is validated by the caller +// before it is ever offered here, and this goroutine does the stop-then-start +// with nothing else touching the process. func (r *realityRunner) supervise() { defer close(r.exited) + // A reload waiting for its new child to come up. It is answered once the + // child is running, so the dashboard's reply means "xray is serving the new + // list", not "xray was asked to". + var answered *realityReload + delay := 5 * time.Second for { if r.isStopped() { @@ -656,25 +729,60 @@ func (r *realityRunner) supervise() { } w := &xrayLogWriter{logger: r.logger} - cmd := exec.Command(r.bin, "run", "-c", r.cfgFile) + cmd := exec.Command(r.bin, "run", "-c", r.configFile()) cmd.Stdout, cmd.Stderr = w, w if err := cmd.Start(); err != nil { r.logger.Error("reality: cannot start xray", "error", err) + if answered != nil { + answered.done <- fmt.Errorf("xray did not start: %w", err) + answered = nil + } } else { r.setCmd(cmd) - waitErr := cmd.Wait() - r.setCmd(nil) - if r.isStopped() { + if answered != nil { + r.waitReady() + answered.done <- nil + answered = nil + } + // Wait runs in its own goroutine so the loop can still act on a + // reload or a stop while the child is running. + exited := make(chan error, 1) + go func() { exited <- cmd.Wait() }() + + select { + case waitErr := <-exited: + r.setCmd(nil) + if r.isStopped() { + return + } + r.logger.Error("reality: xray exited, restarting", "error", waitErr) + case req := <-r.reload: + r.logger.Info("reality: reloading client list") + r.stopChild(exited) + r.swapConfig(req.cfgFile) + answered = &req + // A deliberate reload is not a crash: start the new child at + // once instead of serving the backoff first. + continue + case <-r.stop: + r.setCmd(nil) + r.stopChild(exited) return } - r.logger.Error("reality: xray exited, restarting", "error", waitErr) } select { case <-time.After(delay): case <-r.stop: return + case req := <-r.reload: + // No child is running here, so the reply waits for the next + // successful start. Claiming it is applied now would be a lie the + // dashboard would show as "live". + r.swapConfig(req.cfgFile) + answered = &req + continue } if delay < time.Minute { delay *= 2 @@ -685,6 +793,42 @@ func (r *realityRunner) supervise() { } } +// stopChild ends the running child and waits for the process to actually be +// gone, so the port is free before its replacement starts. +func (r *realityRunner) stopChild(exited chan error) { + r.mu.Lock() + cmd := r.cmd + r.mu.Unlock() + + if cmd == nil || cmd.Process == nil { + return + } + _ = cmd.Process.Signal(syscall.SIGTERM) + select { + case <-exited: + case <-time.After(5 * time.Second): + _ = cmd.Process.Kill() + <-exited + } +} + +// swapConfig installs a new config file and deletes the one it replaces. +func (r *realityRunner) swapConfig(next string) { + r.mu.Lock() + old := r.cfgFile + r.cfgFile = next + r.mu.Unlock() + if old != "" && old != next { + _ = os.Remove(old) + } +} + +func (r *realityRunner) configFile() string { + r.mu.Lock() + defer r.mu.Unlock() + return r.cfgFile +} + func (r *realityRunner) setCmd(cmd *exec.Cmd) { r.mu.Lock() r.cmd = cmd @@ -697,6 +841,34 @@ func (r *realityRunner) isStopped() bool { return r.stopped } +// Reload renders a new config and swaps it in. The config is validated by xray +// first, so an invalid change is refused and the running front door keeps +// serving; the previous file is removed only once the new one is accepted. +func (r *realityRunner) Reload(cfg Config, k realityKeys) error { + bin := cfg.RealityXrayBin + if bin == "" { + bin = r.bin + } + next, err := renderValidatedServerConfig(bin, cfg, k) + if err != nil { + return err + } + + req := realityReload{cfgFile: next, done: make(chan error, 1)} + select { + case r.reload <- req: + case <-time.After(10 * time.Second): + _ = os.Remove(next) + return errors.New("xray supervisor is not responding") + } + select { + case err := <-req.done: + return err + case <-time.After(15 * time.Second): + return errors.New("timed out waiting for xray to reload") + } +} + // Stop asks xray to exit, then removes the config holding the private key. func (r *realityRunner) Stop() { r.mu.Lock() @@ -722,23 +894,23 @@ func (r *realityRunner) Stop() { _ = cmd.Process.Kill() } } - _ = os.Remove(r.cfgFile) + _ = os.Remove(r.configFile()) } // ─── Wiring ───────────────────────────────────────────────────────────────── // startRealityForServer resolves keys, starts the child and writes the client // config operators copy to their own devices. -func startRealityForServer(cfg Config, persisted map[string]string, store *Store, logger *slog.Logger) (*realityRunner, error) { +func startRealityForServer(cfg Config, persisted map[string]string, store *Store, logger *slog.Logger) (*realityRunner, realityKeys, error) { if _, err := exec.LookPath(orDefault(cfg.RealityXrayBin, "xray")); err != nil { if _, statErr := os.Stat(orDefault(cfg.RealityXrayBin, "xray")); statErr != nil { - return nil, fmt.Errorf("reality_enabled is set but the xray binary is missing: set XRAY_BIN or install it (Docker images ship it at /usr/local/bin/xray)") + return nil, realityKeys{}, fmt.Errorf("reality_enabled is set but the xray binary is missing: set XRAY_BIN or install it (Docker images ship it at /usr/local/bin/xray)") } } keys, err := resolveRealityKeys(cfg, persisted, store, logger) if err != nil { - return nil, err + return nil, keys, err } if _, port, err := splitHostPort(cfg.RealityBind); err == nil && port == cfg.SinglePort && cfg.SinglePort != 0 { @@ -747,7 +919,7 @@ func startRealityForServer(cfg Config, persisted map[string]string, store *Store runner, err := startReality(cfg, keys, logger) if err != nil { - return nil, err + return nil, keys, err } address := cfg.RealityPublicHost @@ -777,7 +949,87 @@ func startRealityForServer(cfg Config, persisted map[string]string, store *Store "public_key", keys.PublicKey, "short_id", keys.ShortID, "client_id", strings.Join(keys.ClientIDs, ",")) - return runner, nil + return runner, keys, nil +} + +// ─── Live client-list management ─────────────────────────────────────────── + +// generateVlessUUID asks xray for an id, which is the same generator that +// produced the first one. It runs a subprocess because the binary is already a +// dependency of this feature and rolling our own UUID would be one more thing +// to get wrong. +func generateVlessUUID(bin string) (string, error) { + out, err := runXray(orDefault(bin, "xray"), "uuid") + if err != nil { + return "", err + } + fields := strings.Fields(out) + if len(fields) == 0 || !IsUUID(fields[0]) { + return "", fmt.Errorf("xray uuid returned %q", strings.TrimSpace(out)) + } + return fields[0], nil +} + +// realityManager returns the runner and keys when the dashboard is allowed to +// change the client list. +func (s *ProxyServer) realityManager() (*realityRunner, realityKeys, error) { + s.realityMu.Lock() + defer s.realityMu.Unlock() + + if s.reality == nil { + return nil, realityKeys{}, errors.New("REALITY is not enabled, so there is no xray client list to manage") + } + // REALITY_CLIENT_IDS pins the list from configuration, which outranks the + // database everywhere else in this program. Editing the table would then + // look like it worked and change nothing. + s.configMu.RLock() + pinned := len(s.cfg.RealityClientIDs) > 0 + s.configMu.RUnlock() + if pinned { + return nil, realityKeys{}, errors.New("REALITY_CLIENT_IDS is set, which pins the client list; unset it to manage clients here") + } + return s.reality, s.realityKeys, nil +} + +// requireRealityManager is the handler-side guard for the mutating routes. +func (s *ProxyServer) requireRealityManager(w http.ResponseWriter) error { + if _, _, err := s.realityManager(); err != nil { + http.Error(w, err.Error(), http.StatusConflict) + return err + } + return nil +} + +// applyVlessClients re-renders the xray config from the enabled rows and swaps +// it into the running child. The config is validated before xray is restarted, +// so a rejected change leaves the front door serving what it was serving. +func (s *ProxyServer) applyVlessClients() error { + runner, keys, err := s.realityManager() + if err != nil { + return err + } + s.realityMu.Lock() + keys.ClientIDs, err = s.store.EnabledVlessClientUUIDs() + s.realityMu.Unlock() + if err != nil { + return err + } + if len(keys.ClientIDs) == 0 { + return errors.New("this would leave xray with no clients, so the front door would refuse every connection; add one first") + } + + s.configMu.RLock() + cfg := s.cfg + s.configMu.RUnlock() + + if err := runner.Reload(cfg, keys); err != nil { + return err + } + s.realityMu.Lock() + s.realityKeys = keys + s.realityMu.Unlock() + s.logger.Info("reality client list applied", "clients", len(keys.ClientIDs)) + return nil } func orDefault(v, fallback string) string { diff --git a/reality_test.go b/reality_test.go index 506a50d..a77dce5 100644 --- a/reality_test.go +++ b/reality_test.go @@ -336,8 +336,13 @@ func TestResolveRealityKeysPersistsGeneratedValues(t *testing.T) { if saved[dbRealityShortID] != keys.ShortID { t.Errorf("short id not persisted: %v", saved) } - if saved[dbRealityClientIDs] != strings.Join(keys.ClientIDs, ",") { - t.Errorf("client ids not persisted: %v", saved) + // The uuid belongs in the managed table now, not in a comma-joined string. + clients, err := store.ListVlessClients() + if err != nil { + t.Fatalf("list clients: %v", err) + } + if len(clients) != 1 || clients[0].UUID != keys.ClientIDs[0] || !clients[0].Enabled { + t.Fatalf("generated uuid not stored as a managed client: %+v", clients) } // A restart must reuse the persisted pair rather than rotate it. @@ -348,6 +353,9 @@ func TestResolveRealityKeysPersistsGeneratedValues(t *testing.T) { if again.PrivateKey != keys.PrivateKey || again.ShortID != keys.ShortID { t.Errorf("restart rotated the key material: %q/%q", again.PrivateKey, again.ShortID) } + if len(again.ClientIDs) != 1 || again.ClientIDs[0] != keys.ClientIDs[0] { + t.Errorf("restart rotated the client id: %v, want %v", again.ClientIDs, keys.ClientIDs) + } } func TestResolveRealityKeysPrefersOperatorValues(t *testing.T) { @@ -383,7 +391,7 @@ func TestRealityRefusesWithoutXrayBinary(t *testing.T) { cfg.RealityEnabled = true cfg.RealityXrayBin = filepath.Join(t.TempDir(), "definitely-not-here") - _, err := startRealityForServer(cfg, nil, nil, slog.New(slog.NewTextHandler(io.Discard, nil))) + _, _, err := startRealityForServer(cfg, nil, nil, slog.New(slog.NewTextHandler(io.Discard, nil))) if err == nil { t.Fatal("starting REALITY without the xray binary should fail") } diff --git a/vless_test.go b/vless_test.go new file mode 100644 index 0000000..ebd4f02 --- /dev/null +++ b/vless_test.go @@ -0,0 +1,526 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// ─── Store ────────────────────────────────────────────────────────────────── + +func TestVlessClientCRUD(t *testing.T) { + store := newTestStore(t) + + const uuid = "0cd94710-7290-40da-857d-5f5a7670cd62" + client, err := store.CreateVlessClient(uuid, "alice's phone") + if err != nil { + t.Fatalf("create: %v", err) + } + if !client.Enabled || client.Label != "alice's phone" { + t.Errorf("created client = %+v, want enabled with its label", client) + } + + // The same UUID twice is an error, not a second row: two rows would make + // revocation ambiguous. + if _, err := store.CreateVlessClient(uuid, "impostor"); err == nil { + t.Error("the same uuid was accepted twice") + } + + if _, err := store.CreateVlessClient("not-a-uuid", ""); err == nil { + t.Error("a non-uuid was accepted") + } + + clients, err := store.ListVlessClients() + if err != nil || len(clients) != 1 { + t.Fatalf("list = %+v, %v", clients, err) + } + + disabled := false + if err := store.UpdateVlessClient(client.ID, nil, &disabled); err != nil { + t.Fatalf("disable: %v", err) + } + uuids, err := store.EnabledVlessClientUUIDs() + if err != nil { + t.Fatalf("enabled uuids: %v", err) + } + if len(uuids) != 0 { + t.Errorf("a disabled client is still offered to xray: %v", uuids) + } + + // A label-only edit must not silently re-enable it. + if err := store.UpdateVlessClient(client.ID, stringPtr("renamed"), nil); err != nil { + t.Fatalf("relabel: %v", err) + } + clients, _ = store.ListVlessClients() + if clients[0].Label != "renamed" || clients[0].Enabled { + t.Errorf("relabel changed more than the label: %+v", clients[0]) + } + + if err := store.DeleteVlessClient(client.ID); err != nil { + t.Fatalf("delete: %v", err) + } + if clients, _ := store.ListVlessClients(); len(clients) != 0 { + t.Errorf("delete left rows behind: %+v", clients) + } +} + +func stringPtr(v string) *string { return &v } + +// ─── Where the client list comes from ─────────────────────────────────────── + +func TestResolveRealityKeysUsesManagedClients(t *testing.T) { + bin := fakeXray(t, "private", "public") + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + cfg := DefaultConfig() + cfg.RealityXrayBin = bin + + // An id left behind by an earlier version, in the old comma-joined value. + // Upgrading must adopt it, not drop it: the table would otherwise shadow + // the config and revoke a client that is still in the field. + const legacyID = "11111111-2222-3333-4444-555555555555" + persisted := map[string]string{dbRealityClientIDs: legacyID} + + keys, err := resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Fatalf("client ids = %v, want the legacy id adopted", keys.ClientIDs) + } + clients, _ := store.ListVlessClients() + if len(clients) != 1 || clients[0].Label != "migrated" { + t.Fatalf("legacy id was not adopted into the table: %+v", clients) + } + + // Adding a managed client adds to the list. The adopted id stays: upgrading + // and then adding someone must not quietly revoke the client that was + // already in the field. + const managedID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" + if _, err := store.CreateVlessClient(managedID, "new phone"); err != nil { + t.Fatalf("create managed: %v", err) + } + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve again: %v", err) + } + if len(keys.ClientIDs) != 2 { + t.Errorf("client ids = %v, want the adopted and the new client", keys.ClientIDs) + } + found := false + for _, id := range keys.ClientIDs { + if id == managedID { + found = true + } + } + if !found { + t.Errorf("the new client is missing from %v", keys.ClientIDs) + } + + // Disabling one leaves the other alone. + all, _ := store.ListVlessClients() + for _, c := range all { + if c.UUID == managedID { + off := false + if err := store.UpdateVlessClient(c.ID, nil, &off); err != nil { + t.Fatalf("disable: %v", err) + } + } + } + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve with one disabled: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Errorf("client ids = %v, want only the still-enabled one", keys.ClientIDs) + } + + // Configuration still outranks the table, as it does everywhere else. + cfg.RealityClientIDs = []string{legacyID} + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve with config: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Errorf("client ids = %v, want the configured id to win", keys.ClientIDs) + } +} + +// ─── The API ──────────────────────────────────────────────────────────────── + +// adminRequest drives the admin mux the way the dashboard does. +func adminRequest(t *testing.T, s *ProxyServer, method, path string, body string) *httptest.ResponseRecorder { + t.Helper() + var reader io.Reader + if body != "" { + reader = strings.NewReader(body) + } + req := httptest.NewRequest(method, path, reader) + req.RemoteAddr = "127.0.0.1:5000" + rec := httptest.NewRecorder() + s.adminHandler().ServeHTTP(rec, req) + return rec +} + +func TestVlessClientAPIRequiresReality(t *testing.T) { + cfg := DefaultConfig() + cfg.AdminPort = freePort(t) + cfg.AuthEnabled = false + s := NewProxyServer(cfg) + s.store = newTestStore(t) + + // Listing works without xray, so the dashboard can say why it is empty. + rec := adminRequest(t, s, http.MethodGet, "/api/vless-clients", "") + if rec.Code != http.StatusOK { + t.Fatalf("GET with REALITY off = %d, want 200: %s", rec.Code, rec.Body) + } + var listing struct { + Clients []VlessClient `json:"clients"` + RealityEnabled bool `json:"reality_enabled"` + ManagedByConfig bool `json:"managed_by_config"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &listing); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if listing.RealityEnabled { + t.Error("reality_enabled should be false when REALITY is off") + } + + // Mutating is refused rather than accepted-and-ignored. + for _, tc := range []struct{ method, path, body string }{ + {http.MethodPost, "/api/vless-clients", `{"label":"x"}`}, + {http.MethodPut, "/api/vless-clients/1", `{"enabled":false}`}, + {http.MethodDelete, "/api/vless-clients/1", ""}, + } { + rec := adminRequest(t, s, tc.method, tc.path, tc.body) + if rec.Code != http.StatusConflict { + t.Errorf("%s %s with REALITY off = %d, want 409: %s", tc.method, tc.path, rec.Code, rec.Body) + } + } +} + +func TestVlessClientAPIRejectsPinnedListAndLastRemoval(t *testing.T) { + bin := requireXray(t) + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + cfg := DefaultConfig() + cfg.RealityXrayBin = bin + cfg.RealityBind = fmt.Sprintf("127.0.0.1:%d", freePort(t)) + keys, err := resolveRealityKeys(cfg, nil, store, log) + if err != nil { + t.Fatalf("resolve: %v", err) + } + runner, err := startReality(cfg, keys, log) + if err != nil { + t.Fatalf("start reality: %v", err) + } + defer runner.Stop() + + s := NewProxyServer(cfg) + s.store = store + s.reality, s.realityKeys = runner, keys + + // resolveRealityKeys generated and stored one client, which is now the only + // one there is. + clients, err := store.ListVlessClients() + if err != nil || len(clients) != 1 { + t.Fatalf("expected exactly the generated client: %+v, %v", clients, err) + } + created := clients[0] + + // Removing the last client would leave xray with nobody to serve, which + // looks like a successful edit and breaks every client on the planet. + rec := adminRequest(t, s, http.MethodDelete, fmt.Sprintf("/api/vless-clients/%d", created.ID), "") + if rec.Code != http.StatusInternalServerError { + t.Fatalf("removing the last client = %d, want an error: %s", rec.Code, rec.Body) + } + if !strings.Contains(rec.Body.String(), "no clients") { + t.Errorf("error %q should explain that no client would be left", rec.Body) + } + if clients, _ := store.ListVlessClients(); len(clients) != 1 { + t.Fatalf("a refused removal still deleted the row: %+v", clients) + } + + // A pinned list is refused instead of silently doing nothing. + s.configMu.Lock() + s.cfg.RealityClientIDs = []string{keys.ClientIDs[0]} + s.configMu.Unlock() + rec = adminRequest(t, s, http.MethodPost, "/api/vless-clients", `{"label":"ignored"}`) + if rec.Code != http.StatusConflict { + t.Fatalf("POST with a pinned list = %d, want 409: %s", rec.Code, rec.Body) + } + if !strings.Contains(rec.Body.String(), "REALITY_CLIENT_IDS") { + t.Errorf("error %q should name the variable pinning the list", rec.Body) + } +} + +// ─── End to end ───────────────────────────────────────────────────────────── + +// TestRealityClientRevocationTakesEffect runs the whole loop: a UUID is revoked +// from the database, and a REALITY client still configured with it must stop +// working without the proxy being restarted. A management screen that does not +// revoke anything is worse than no management screen. +func TestRealityClientRevocationTakesEffect(t *testing.T) { + bin := requireXray(t) + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + // An origin the client will actually reach. + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "revocation-e2e-ok") + })) + defer origin.Close() + + proxyCfg := DefaultConfig() + proxyCfg.AuthEnabled = false + proxyCfg.AdminEnabled = false + proxyCfg.SecurityHeadersEnabled = false + proxyCfg.RateLimitEnabled = false + proxyCfg.ProxyPort = freePort(t) + + realityPort := freePort(t) + cfg := proxyCfg + cfg.RealityXrayBin = bin + cfg.RealityEnabled = true + cfg.RealityBind = fmt.Sprintf("127.0.0.1:%d", realityPort) + cfg.RealityPublicHost = "127.0.0.1" + + // One config for the server and the runner: the reload re-renders from + // server.cfg, exactly as runServer does. + server := NewProxyServer(cfg) + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", proxyCfg.ProxyPort)) + if err != nil { + t.Fatalf("listen socks: %v", err) + } + defer ln.Close() + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go server.handleClient(conn, "") + } + }() + + const revokedID = "0cd94710-7290-40da-857d-5f5a7670cd62" + const keptID = "0cd94710-7290-40da-857d-5f5a7670cd63" + for _, id := range []string{revokedID, keptID} { + if _, err := store.CreateVlessClient(id, "test client"); err != nil { + t.Fatalf("seed client %s: %v", id, err) + } + } + + keys, err := resolveRealityKeys(cfg, nil, store, log) + if err != nil { + t.Fatalf("resolve keys: %v", err) + } + if len(keys.ClientIDs) != 2 { + t.Fatalf("client ids = %v, want both managed clients", keys.ClientIDs) + } + + runner, err := startReality(cfg, keys, log) + if err != nil { + t.Fatalf("start reality: %v", err) + } + defer runner.Stop() + + server.store = store + server.reality, server.realityKeys = runner, keys + + // A REALITY client whose config still carries the id about to be revoked. + staleClient := startRealityTestClient(t, bin, cfg, keys, revokedID, freePort(t)) + liveClient := startRealityTestClient(t, bin, cfg, keys, keptID, freePort(t)) + + fetch := func(clientPort int) error { + u, err := url.Parse(fmt.Sprintf("socks5://127.0.0.1:%d", clientPort)) + if err != nil { + return err + } + httpClient := &http.Client{ + Transport: &http.Transport{Proxy: http.ProxyURL(u)}, + Timeout: 25 * time.Second, + } + resp, err := httpClient.Get(origin.URL) + if err != nil { + return err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return err + } + if string(body) != "revocation-e2e-ok" { + return fmt.Errorf("body = %q", body) + } + return nil + } + + // Both work before the change. + if err := fetch(staleClient); err != nil { + t.Fatalf("the client that is about to be revoked should work now: %v", err) + } + if err := fetch(liveClient); err != nil { + t.Fatalf("the client that stays should work now: %v", err) + } + + // Revoke through the same path the dashboard uses. + rec := adminRequest(t, server, http.MethodDelete, fmt.Sprintf("/api/vless-clients/%d", idOfUUID(t, store, revokedID)), "") + if rec.Code != http.StatusOK { + t.Fatalf("revoke = %d: %s", rec.Code, rec.Body) + } + + // No restart, no waiting: the revoked UUID must already be refused. + if err := fetch(staleClient); err == nil { + t.Error("a revoked uuid still works; the dashboard change did not reach xray") + } + // The other client is untouched. + if err := fetch(liveClient); err != nil { + t.Errorf("revoking one client broke another: %v", err) + } +} + +// startRealityTestClient runs a second xray as the client and returns the port +// of its local SOCKS5 inbound. +func startRealityTestClient(t *testing.T, bin string, cfg Config, keys realityKeys, uuid string, clientPort int) int { + t.Helper() + + clientKeys := keys + clientKeys.ClientIDs = []string{uuid} + data, err := renderRealityClientConfig(cfg.RealityPublicHost, portOf(t, cfg.RealityBind), "127.0.0.1", clientPort, clientKeys) + if err != nil { + t.Fatalf("render client: %v", err) + } + file := filepath.Join(t.TempDir(), "client.json") + if err := os.WriteFile(file, data, 0o600); err != nil { + t.Fatalf("write client config: %v", err) + } + + cmd := exec.Command(bin, "run", "-c", file) + // The client's own log is the only place a refusal shows up, and a silent + // skip here would look like a flaky proxy rather than a rejected UUID. + cmd.Stdout, cmd.Stderr = &testWriter{t: t, tag: "client"}, &testWriter{t: t, tag: "client"} + if err := cmd.Start(); err != nil { + t.Fatalf("start client xray: %v", err) + } + t.Cleanup(func() { + cmd.Process.Kill() + cmd.Wait() + }) + + deadline := time.Now().Add(15 * time.Second) + for { + conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", clientPort), 200*time.Millisecond) + if err == nil { + conn.Close() + return clientPort + } + if time.Now().After(deadline) { + t.Fatalf("client socks port %d never opened: %v", clientPort, err) + } + time.Sleep(100 * time.Millisecond) + } +} + +// testWriter routes a subprocess log into the test output. +type testWriter struct { + t *testing.T + tag string + buf string +} + +func (w *testWriter) Write(p []byte) (int, error) { + w.buf += string(p) + for { + i := strings.IndexByte(w.buf, '\n') + if i < 0 { + break + } + w.t.Logf("[%s] %s", w.tag, w.buf[:i]) + w.buf = w.buf[i+1:] + } + return len(p), nil +} + +func portOf(t *testing.T, addr string) int { + t.Helper() + _, port, err := splitHostPort(addr) + if err != nil { + t.Fatalf("split %q: %v", addr, err) + } + return port +} + +func idOfUUID(t *testing.T, store *Store, uuid string) int64 { + t.Helper() + clients, err := store.ListVlessClients() + if err != nil { + t.Fatalf("list clients: %v", err) + } + for _, c := range clients { + if c.UUID == uuid { + return c.ID + } + } + t.Fatalf("no managed client with uuid %s", uuid) + return 0 +} + +// The dashboard is one HTML file with inline script, so the cheapest honest +// check is that the panel is wired to the endpoints this build serves. +func TestDashboardVlessPanelWiring(t *testing.T) { + data, err := os.ReadFile("web/index.html") + if err != nil { + t.Fatalf("read dashboard: %v", err) + } + html := string(data) + + for _, id := range []string{"vless-body", "v-label", "v-uuid", "vless-msg"} { + if !strings.Contains(html, `id="`+id+`"`) { + t.Errorf("dashboard has no element with id %q", id) + } + } + for _, fn := range []string{"loadVlessClients", "createVlessClient", "toggleVlessClient", "deleteVlessClient"} { + if !strings.Contains(html, "function "+fn+"(") { + t.Errorf("dashboard has no %s function", fn) + } + } + if !strings.Contains(html, "/api/vless-clients") { + t.Error("dashboard never talks to /api/vless-clients") + } + // Defined is not wired: the list has to load on startup. + if !strings.Contains(html, "\nloadVlessClients();") { + t.Error("loadVlessClients() is not called on startup") + } + + cfg := DefaultConfig() + cfg.AuthEnabled = false + s := NewProxyServer(cfg) + s.store = newTestStore(t) + rec := adminRequest(t, s, http.MethodGet, "/api/vless-clients", "") + if rec.Code != http.StatusOK { + t.Fatalf("GET /api/vless-clients = %d", rec.Code) + } + var listing struct { + Clients []VlessClient `json:"clients"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &listing); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if listing.Clients == nil { + t.Error("clients must serialise as [], not null, so the panel can loop over it") + } +} diff --git a/web/index.html b/web/index.html index 2b983d3..eb1018c 100644 --- a/web/index.html +++ b/web/index.html @@ -155,6 +155,7 @@ .theme-toggle:hover{color:var(--accent);border-color:var(--accent);box-shadow:0 0 10px var(--shadow)} .theme-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:2px} .actions{display:flex;gap:5px;flex-wrap:wrap} + .uuid{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px} .form-box{background:var(--bg-elevated);border:1px solid var(--border);box-shadow:0 1px 2px var(--shadow);border-radius:12px;padding:20px;position:relative;overflow:hidden} .form-box::before{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:linear-gradient(90deg,transparent,var(--accent),transparent)} .form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:15px} @@ -259,6 +260,46 @@

User Management

+
+

REALITY Clients (VLESS UUIDs)

+
+
+

+ Each UUID is one client allowed through the REALITY front door. Changes are + applied to xray immediately: a deleted or disabled UUID stops working + within a second, with no restart. +

+
+
+ + +
+
+ + +
+
+ +
+ +
+ + + + + + + + + + + + + +
IDLabelUUIDStatusActions
Loading...
+
+
+

Settings

@@ -537,10 +578,113 @@

Settings

}catch(e){msg.textContent='Network error: '+e.message;msg.className='msg msg-err';msg.style.display='block'} } +function el(tag,text){var e=document.createElement(tag);if(text!==undefined)e.textContent=text;return e} + +async function loadVlessClients(){ + var msg=document.getElementById('vless-msg'); + var tbody=document.getElementById('vless-body'); + try{ + var r=await fetch('/api/vless-clients',{credentials:'same-origin'}); + var data=await r.json(); + if(!data.reality_enabled){ + tbody.innerHTML=''; + var row=el('tr'),cell=el('td',''); + cell.colSpan=5; + cell.style.color='#555'; + cell.textContent='REALITY is not enabled, so there is no client list to manage.'; + row.appendChild(cell);tbody.appendChild(row); + document.querySelector('#v-label').disabled=true; + document.querySelector('#v-uuid').disabled=true; + return; + } + if(data.managed_by_config){ + msg.textContent='REALITY_CLIENT_IDS is set, which pins the list. Unset it to manage clients here.'; + msg.className='msg msg-err';msg.style.display='block'; + } + tbody.innerHTML=''; + if(!data.clients||data.clients.length===0){ + var empty=el('tr'),ecell=el('td','No clients. Add one above.'); + ecell.colSpan=5;ecell.style.color='#555'; + empty.appendChild(ecell);tbody.appendChild(empty); + return; + } + for(var i=0;i Date: Sat, 17 Oct 2026 18:57:49 +0500 Subject: [PATCH 2/3] Store passwords as hashes, and upgrade old rows on login users.password_hash held the password verbatim, so any copy of the database -- a backup, a stray file, a support attachment -- was a list of working credentials, for the service and for whatever else those people reuse the same password on. PBKDF2-HMAC-SHA256 at 600k iterations, which is the OWASP figure for that pair, from the standard library. No new dependency for the one thing in a proxy that must not be improvised, and the cost is paid per login attempt on an endpoint that already rate-limits guesses. The parameters are recorded in each stored hash rather than assumed at verify time, so they can be raised later without invalidating what is on disk. That also means the stored value chooses the cost, so parsing refuses anything implausible instead of letting a corrupt or hostile record turn one login into a memory-exhaustion attack. Existing installs need no migration: a row from before hashing is verified against the value it holds, and rewritten on the next successful login. An install cleans itself up one account at a time. PROXY_USER/PROXY_PASS and the admin pair are untouched -- they come from the environment, not the database, so there is nothing to hash and the file is already a secret the operator controls. Verified against a running server: a user created through the API lands in the file as pbkdf2-sha256$iter=600000$..., the plaintext is absent from the database bytes, the correct password authenticates and a wrong one does not, a seeded pre-hashing row logs in and is rewritten on the spot, and a backup of the result contains neither the old nor the new plaintext -- VACUUM INTO leaves no stale copies behind, though the live WAL keeps the old value until it is checkpointed. --- README.md | 25 ++++-- database.go | 27 +++++- main.go | 14 ++- password.go | 107 +++++++++++++++++++++++ password_test.go | 215 +++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 379 insertions(+), 9 deletions(-) create mode 100644 password.go create mode 100644 password_test.go diff --git a/README.md b/README.md index 2d45693..44cb2f3 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Deploys on any PaaS, including the ones that expose only a single HTTP endpoint. - **User Management** - Create, update, delete users with tier-based limits - **Tier System** - Free, Basic, Pro, and Unlimited tiers with connection/data/bandwidth limits - **Rate Limiting** - Token-bucket rate limiting with configurable RPS +- **Hashed Passwords** - PBKDF2-HMAC-SHA256 in the database; a stolen file is not a list of credentials - **Message Padding** - Optional uniform-size framing so a 2-byte SOCKS5 reply is indistinguishable from bulk traffic - **Security Headers** - CSP, XSS protection, frame options, and more - **Admin Dashboard** - Full management UI with charts and user CRUD @@ -448,8 +449,8 @@ Client flags: `-url` (required; `https://` is accepted and mapped to `wss://`, a # 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. +# Encrypt it. A backup holds password hashes 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. @@ -526,9 +527,19 @@ 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. +- User passwords are stored as **PBKDF2-HMAC-SHA256 hashes** (600k iterations, + per-user salt), never as text, so a database file or a backup does not hand + over working credentials. Accounts created before hashing existed keep + working: their password is verified against the old value and the row is + rewritten on the next successful login, so an install upgrades itself one + account at a time with no migration to run. +- `PROXY_USER`/`PROXY_PASS` and `ADMIN_USER`/`ADMIN_PASS` come from the + environment or config file and stay as they are — there is nothing in the + database to hash, and the file is already a secret you control. +- A backup contains password **hashes**, not passwords, plus the REALITY private + key when it is enabled. The key is the reason to use `-passphrase` for + anything that leaves the machine; 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`, @@ -600,6 +611,10 @@ at `/prometheus` with `basic_auth` configured. | PUT | `/api/users/:id` | Update user | | DELETE | `/api/users/:id` | Delete user | | POST | `/api/users/:id/reset` | Reset a user's data usage | +| GET | `/api/vless-clients` | REALITY client UUIDs, and whether they can be managed | +| POST | `/api/vless-clients` | Add a client; the UUID is generated if omitted | +| PUT | `/api/vless-clients/:id` | Relabel, or enable/disable, a client | +| DELETE | `/api/vless-clients/:id` | Revoke a client, effective immediately | | GET | `/api/top-destinations?n=10` | Most-visited destinations | | GET | `/api/history/stats?n=60` | Historical connection/byte counters | | GET | `/api/history/destinations` | Destination history | diff --git a/database.go b/database.go index ec18546..9c89337 100644 --- a/database.go +++ b/database.go @@ -416,6 +416,14 @@ func (s *Store) CreateUser(username, password, tier string) (*User, error) { return nil, fmt.Errorf("unknown tier: %s", tier) } + // Hash before the row exists, so no code path can write a plaintext + // password by accident. The caller keeps the plaintext it passed in and is + // the one that may show it once. + hashed, err := HashPassword(password) + if err != nil { + return nil, err + } + var expiry *string if t.DaysExpiry > 0 { e := time.Now().AddDate(0, 0, t.DaysExpiry).Format("2006-01-02 15:04:05") @@ -428,7 +436,7 @@ func (s *Store) CreateUser(username, password, tier string) (*User, error) { result, err := s.db.Exec( `INSERT INTO users (username, password_hash, tier, max_connections, bandwidth_mbps, data_limit_bytes, expiry) VALUES (?, ?, ?, ?, ?, ?, ?)`, - username, password, tier, t.MaxConnections, t.BandwidthMbps, t.DataLimitBytes, expiry, + username, hashed, tier, t.MaxConnections, t.BandwidthMbps, t.DataLimitBytes, expiry, ) if err != nil { return nil, fmt.Errorf("insert user: %w", err) @@ -537,7 +545,11 @@ func (s *Store) UpdateUser(id int64, tier *string, password *string, enabled *bo } } if password != nil { - _, err := s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", *password, id) + hashed, err := HashPassword(*password) + if err != nil { + return err + } + _, err = s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", hashed, id) if err != nil { return err } @@ -580,6 +592,17 @@ func (s *Store) DeleteUser(id int64) error { return tx.Commit() } +// UpgradeUserPassword rewrites a row that still holds a pre-hashing password. +// It is called after a successful login, so an install cleans itself up one +// account at a time instead of needing a migration over every credential. +func (s *Store) UpgradeUserPassword(id int64, hash string) error { + s.mu.Lock() + defer s.mu.Unlock() + + _, err := s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", hash, id) + return err +} + func (s *Store) ResetUserData(id int64) error { s.mu.Lock() defer s.mu.Unlock() diff --git a/main.go b/main.go index 36f7f73..5205b2f 100644 --- a/main.go +++ b/main.go @@ -889,8 +889,18 @@ func (s *ProxyServer) authenticateUser(conn net.Conn, cfg *Config) (*User, error return nil, fmt.Errorf("user %s is disabled", string(username)) } - // Constant-time password comparison - if subtle.ConstantTimeCompare(password, []byte(user.PasswordHash)) == 1 { + if ok, legacy := VerifyPassword(user.PasswordHash, string(password)); ok { + // A row from before hashing matched in the clear. Rewrite it now + // that the password has been proven, so the install tidies + // itself up one login at a time. + if legacy { + if hash, herr := HashPassword(string(password)); herr == nil { + if uerr := s.store.UpgradeUserPassword(user.ID, hash); uerr != nil { + s.logger.Warn("could not upgrade a stored password hash", + "user", user.Username, "error", uerr) + } + } + } if _, err := conn.Write([]byte{socksAuthVersion, authStatusSuccess}); err != nil { return nil, fmt.Errorf("write auth success: %w", err) } diff --git a/password.go b/password.go new file mode 100644 index 0000000..993a32e --- /dev/null +++ b/password.go @@ -0,0 +1,107 @@ +package main + +import ( + "crypto/pbkdf2" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "fmt" + "strings" +) + +// ─── Password hashing ────────────────────────────────────────────────────── +// +// The users table used to hold passwords verbatim, which turns any copy of the +// database -- a stolen backup, a stray file, a support ticket attachment -- into +// a list of working credentials, for every deployment that shares one. Those +// are also the passwords operators reuse elsewhere. +// +// PBKDF2-HMAC-SHA256 at 600k iterations, which is the OWASP figure for that +// combination, from the standard library: no new dependency for the one thing +// in a proxy that must not be improvised. It costs about 0.3s per login here, +// which is a feature on an endpoint that accepts password guesses. +// +// The parameters are recorded in every stored hash rather than assumed at +// verify time, so they can be raised later without invalidating what is +// already on disk: each hash keeps verifying at its own cost, and a successful +// login can rewrite it at the new one. +const ( + pbkdf2Iterations = 600_000 + pbkdf2SaltLen = 16 + pbkdf2KeyLen = 32 + + // passwordScheme tags the stored value, so a future scheme is + // distinguishable from this one rather than being guessed at. + passwordScheme = "pbkdf2-sha256" +) + +// HashPassword returns a self-describing PBKDF2 hash. The password itself is +// not retained anywhere. +func HashPassword(plain string) (string, error) { + if plain == "" { + return "", fmt.Errorf("refusing to hash an empty password") + } + salt := make([]byte, pbkdf2SaltLen) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("generate salt: %w", err) + } + key, err := pbkdf2.Key(sha256.New, plain, salt, pbkdf2Iterations, pbkdf2KeyLen) + if err != nil { + return "", fmt.Errorf("hash password: %w", err) + } + return fmt.Sprintf("%s$iter=%d$%s$%s", + passwordScheme, pbkdf2Iterations, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(key)), nil +} + +// VerifyPassword reports whether plain matches the stored value. +// +// legacy is true when the stored value predates hashing, meaning it matched +// because it was the password in the clear. The caller uses that to rewrite the +// row, so an install upgrades one account per login instead of needing a +// migration that has to touch every credential at once. +func VerifyPassword(stored, plain string) (ok bool, legacy bool) { + if stored == "" || plain == "" { + return false, false + } + if !strings.HasPrefix(stored, passwordScheme+"$") { + // Pre-hashing value: the stored text was the password itself. + return subtle.ConstantTimeCompare([]byte(stored), []byte(plain)) == 1, true + } + iter, salt, key, ok := parseHashedPassword(stored) + if !ok { + return false, false + } + got, err := pbkdf2.Key(sha256.New, plain, salt, iter, len(key)) + if err != nil { + return false, false + } + return subtle.ConstantTimeCompare(got, key) == 1, false +} + +func parseHashedPassword(stored string) (iter int, salt, key []byte, ok bool) { + // scheme$iter=..$salt$key + parts := strings.Split(stored, "$") + if len(parts) != 4 || parts[0] != passwordScheme { + return 0, nil, nil, false + } + if _, err := fmt.Sscanf(parts[1], "iter=%d", &iter); err != nil { + return 0, nil, nil, false + } + // The stored value chooses the cost, so a corrupt or hostile record must + // not be able to turn one login into a denial of service. + if iter < 1 || iter > 10_000_000 { + return 0, nil, nil, false + } + salt, err := base64.RawStdEncoding.DecodeString(parts[2]) + if err != nil || len(salt) < 8 { + return 0, nil, nil, false + } + key, err = base64.RawStdEncoding.DecodeString(parts[3]) + if err != nil || len(key) < 16 { + return 0, nil, nil, false + } + return iter, salt, key, true +} diff --git a/password_test.go b/password_test.go new file mode 100644 index 0000000..ba3b855 --- /dev/null +++ b/password_test.go @@ -0,0 +1,215 @@ +package main + +import ( + "fmt" + "net" + "strings" + "testing" + "time" +) + +func TestHashPasswordRoundTrip(t *testing.T) { + const secret = "correct horse battery staple" + + hash, err := HashPassword(secret) + if err != nil { + t.Fatalf("hash: %v", err) + } + if strings.Contains(hash, secret) { + t.Fatal("the hash contains the password") + } + if !strings.HasPrefix(hash, passwordScheme+"$") { + t.Errorf("hash %q does not name its scheme and parameters", hash) + } + if !strings.Contains(hash, "iter=600000") { + t.Errorf("hash %q does not record its cost", hash) + } + + if ok, legacy := VerifyPassword(hash, secret); !ok || legacy { + t.Errorf("verify(correct) = %v, legacy=%v; want true, false", ok, legacy) + } + if ok, _ := VerifyPassword(hash, "wrong password"); ok { + t.Error("a wrong password verified") + } + if ok, _ := VerifyPassword(hash, ""); ok { + t.Error("an empty password verified") + } + + // Two hashes of the same password must differ, or the salt is not doing + // its job and one rainbow table would open every account. + other, err := HashPassword(secret) + if err != nil { + t.Fatalf("hash again: %v", err) + } + if other == hash { + t.Error("hashing is deterministic; the salt is not being applied") + } + if ok, _ := VerifyPassword(other, secret); !ok { + t.Error("a hash made with a different salt did not verify") + } + + if _, err := HashPassword(""); err == nil { + t.Error("an empty password was hashed") + } +} + +// A password stored before hashing existed must keep working, and must be +// reported as legacy so the caller can upgrade it. +func TestVerifyPasswordAcceptsLegacyPlaintext(t *testing.T) { + if ok, legacy := VerifyPassword("oldpassword", "oldpassword"); !ok || !legacy { + t.Errorf("legacy verify = %v, legacy=%v; want true, true", ok, legacy) + } + if ok, legacy := VerifyPassword("oldpassword", "guess"); ok || !legacy { + t.Errorf("wrong password against a legacy row = %v, legacy=%v; want false, true", ok, legacy) + } + // An empty stored value must never verify, whatever is offered. + if ok, _ := VerifyPassword("", ""); ok { + t.Error("an empty stored password verified against an empty offer") + } +} + +// A corrupt or hostile record must be refused rather than believed. The stored +// value chooses the iteration count, so an absurd one would turn a login into a +// denial of service. +func TestVerifyPasswordRejectsCorruptHashes(t *testing.T) { + good, err := HashPassword("secret") + if err != nil { + t.Fatalf("hash: %v", err) + } + parts := strings.Split(good, "$") + + for _, bad := range []string{ + "", + "pbkdf2-sha256", + "pbkdf2-sha256$", + "pbkdf2-sha256$iter=0$" + parts[2] + "$" + parts[3], + "pbkdf2-sha256$iter=99999999$" + parts[2] + "$" + parts[3], + "pbkdf2-sha256$iter=" + parts[2] + "$" + parts[3], + "pbkdf2-sha256$iter=600000$!!!$" + parts[3], + "pbkdf2-sha256$iter=600000$" + parts[2] + "$", + "pbkdf2-sha512$iter=600000$" + parts[2] + "$" + parts[3], + "scrypt$N=32768,r=8,p=1$" + parts[2] + "$" + parts[3], + parts[0] + "$iter=600000$" + parts[2] + "$" + parts[3] + "$extra", + } { + if ok, legacy := VerifyPassword(bad, "secret"); ok { + t.Errorf("corrupt hash %q verified (legacy=%v)", bad, legacy) + } + } +} + +// The point of the whole change: what lands in the database is not the password. +func TestStoredPasswordIsNotThePassword(t *testing.T) { + store := newTestStore(t) + + user, err := store.CreateUser("alice", "swordfish-123", "pro") + if err != nil { + t.Fatalf("create user: %v", err) + } + stored, err := store.GetUser(user.Username) + if err != nil { + t.Fatalf("get user: %v", err) + } + if strings.Contains(stored.PasswordHash, "swordfish-123") { + t.Fatal("the password is stored in the clear") + } + if ok, legacy := VerifyPassword(stored.PasswordHash, "swordfish-123"); !ok || legacy { + t.Errorf("the stored hash does not verify: ok=%v legacy=%v", ok, legacy) + } + + // Changing a password through the admin path must hash as well. + newPass := "a different one" + if err := store.UpdateUser(user.ID, nil, &newPass, nil); err != nil { + t.Fatalf("update password: %v", err) + } + stored, _ = store.GetUser(user.Username) + if strings.Contains(stored.PasswordHash, newPass) { + t.Fatal("the new password is stored in the clear") + } + if ok, _ := VerifyPassword(stored.PasswordHash, newPass); !ok { + t.Error("the new password does not verify against its stored hash") + } + if ok, _ := VerifyPassword(stored.PasswordHash, "swordfish-123"); ok { + t.Error("the old password still verifies after a change") + } +} + +// A row written before hashing existed authenticates, and is rewritten on the +// way through -- which is how an existing install cleans itself up without a +// migration that has to touch every credential at once. +func TestLoginUpgradesLegacyPasswordRow(t *testing.T) { + store := newTestStore(t) + + user, err := store.CreateUser("legacy", "still-works", "basic") + if err != nil { + t.Fatalf("create user: %v", err) + } + // Put the row back the way an older release would have left it. + store.mu.Lock() + _, err = store.db.Exec("UPDATE users SET password_hash=? WHERE id=?", "still-works", user.ID) + store.mu.Unlock() + if err != nil { + t.Fatalf("seed legacy row: %v", err) + } + + cfg := DefaultConfig() + cfg.AuthEnabled = true + cfg.AdminEnabled = false + cfg.SecurityHeadersEnabled = false + cfg.RateLimitEnabled = false + cfg.ProxyPort = freePort(t) + // Credentials that are not the user's, so success can only come from the + // database path. + cfg.Username = "nobody" + cfg.Password = "nothing" + + s := NewProxyServer(cfg) + s.store = store + + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", cfg.ProxyPort)) + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go s.handleClient(conn, "") + } + }() + + conn, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(30 * time.Second)) + + if err := socks5ConnectAndAuth(t, conn, "legacy", "still-works", "example.com", 80); err != nil { + t.Fatalf("a pre-hashing password no longer authenticates: %v", err) + } + + stored, err := store.GetUser("legacy") + if err != nil { + t.Fatalf("get user: %v", err) + } + if stored.PasswordHash == "still-works" { + t.Fatal("the row still holds the password in the clear after a successful login") + } + if ok, legacy := VerifyPassword(stored.PasswordHash, "still-works"); !ok || legacy { + t.Errorf("upgraded row does not verify: ok=%v legacy=%v", ok, legacy) + } + + // And the upgraded row still authenticates on the next connection. + conn2, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("dial again: %v", err) + } + defer conn2.Close() + conn2.SetDeadline(time.Now().Add(30 * time.Second)) + if err := socks5ConnectAndAuth(t, conn2, "legacy", "still-works", "example.com", 80); err != nil { + t.Fatalf("the upgraded row no longer authenticates: %v", err) + } +} From 78a47d8d7edac4b2af09dfb75404e2e61d3899e7 Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sat, 17 Oct 2026 19:46:53 +0500 Subject: [PATCH 3/3] Speak MTProto, so Telegram works as a front door Telegram speaks neither SOCKS5 nor HTTP, so the other protocols here were of no use to it. Unlike REALITY, this cannot be handed to xray -- I checked, and xray has an mtproto outbound but no inbound -- so the protocol is implemented here and the stream relayed to the datacenter the client asked for. The primitives are AES-256-CTR and SHA-256 from the standard library. The layout is Telegram's, and rather than trust my reading of it, the tests run the handshake against gotd/td, an independent implementation, in both directions: our server handshake against their client, and ours against their server. A proxy that is merely self-consistent connects to nothing. gotd is a test-only dependency; the binary's dependency tree is unchanged. Four bugs, three of which only a live run or a careful test would show: - A short TCP write silently truncated messages. Telegram traffic is far larger than a socket buffer, so this is the difference between working and appearing intermittently broken. Sessions now write in full, and a test pushes 200KB through a pipe that accepts 64 bytes at a time. - The listener kept a snapshot copy of the secrets, so revoking one in the dashboard changed nothing until a restart. - Deleting the last secret quietly minted a replacement, handing out a credential the operator had just refused. Generation now happens at startup only. - With a single secret configured I had skipped the transport tag check, reasoning there was nothing to disambiguate -- which meant serving anyone at all. The tag is the proof that the client knows the secret, so it is always checked now; a test asserts a junk tag is refused. The transport tag doubles as the multi-secret check: 64 random bytes decrypted with the wrong secret do not produce a recognisable tag, so one read identifies which secret a client is using. Verified live against a real Telegram client implementation: the handshake completes, the proxy dials Telegram's own DC2, and revoking the secret stops the next connection from being relayed at all. Fake TLS is not in here. It is a separate wrapper around this stream, and shipping obfuscated2 first means the thing Telegram apps actually accept is working before the camouflage layer is attempted. --- .env.example | 9 + README.md | 35 ++- config.json | 3 + database.go | 105 +++++++++ go.mod | 14 +- go.sum | 71 +++++- main.go | 150 ++++++++++++ mtproto.go | 592 ++++++++++++++++++++++++++++++++++++++++++++++++ mtproto_test.go | 528 ++++++++++++++++++++++++++++++++++++++++++ web/index.html | 129 +++++++++++ 10 files changed, 1622 insertions(+), 14 deletions(-) create mode 100644 mtproto.go create mode 100644 mtproto_test.go diff --git a/.env.example b/.env.example index 6424e8b..d03fae7 100644 --- a/.env.example +++ b/.env.example @@ -31,6 +31,15 @@ IDLE_TIMEOUT_SECONDS=300 # Set false to allow TCP connections only. UDP_ENABLED=true +# ─── Telegram (MTProto) ───────────────────────────────────────────────────── +# Telegram's own protocol, served on its own port because it is not SOCKS5. +# Needs a port of its own: 443 is normally taken by REALITY. +# Add secrets in the dashboard; it generates the first one on first start. +MTPROTO_ENABLED=false +MTPROTO_BIND=0.0.0.0:8443 +# Only needed if Telegram's own addresses are unreachable from this host: +# MTPROTO_DCS=2=10.0.0.1:443,4=10.0.0.2:443 + # ─── Security ────────────────────────────────────────────────────────────── SECURITY_HEADERS_ENABLED=true diff --git a/README.md b/README.md index 44cb2f3..486d10d 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Deploys on any PaaS, including the ones that expose only a single HTTP endpoint. - **Single-Port Multiplexing** - SOCKS5, TLS, dashboards and the tunnel share one port, so it runs on Render/Koyeb/Heroku/Northflank where raw TCP never reaches the app - **WebSocket Tunnel** - Carries SOCKS5 over an HTTP upgrade for platforms whose edge terminates TLS; ships with a matching client - **REALITY** - Xray front door that presents a real website's certificate to an active prober; sessions still land in the SOCKS5 pipeline +- **MTProto** - Telegram's own protocol on its own port, with per-phone secrets managed in the dashboard - **VLESS Client Management** - Add, disable and revoke REALITY UUIDs from the dashboard; xray is reloaded in place, no restart - **Client Mode** - Same binary exposes a local SOCKS5 port that relays through the tunnel - **User Management** - Create, update, delete users with tier-based limits @@ -147,6 +148,7 @@ separately on port 443 via xray. | **HTTP proxy** — `CONNECT` and absolute-form | single port | Browsers and any HTTP client with proxy support | | **HTTPS** | single port | TLS-wrapped access to any of the above | | **VLESS + REALITY** | `:443` via xray | Clients on a VPS where the front door must look like a website | +| **MTProto** | `$MTPROTO_BIND` (default `:8443`) | Telegram, which speaks neither SOCKS5 nor HTTP | Authentication is username/password throughout, taken from `PROXY_USER` and `PROXY_PASS` for the proxy protocols, and `ADMIN_USER`/`ADMIN_PASS` for the @@ -177,6 +179,26 @@ tunnel gets TCP only. And a client that asks to be told an address of `0.0.0.0` must send to the proxy host it is already connected to, which every mainstream SOCKS5 client does. +## Telegram (MTProto) + +Telegram does not speak SOCKS5 or HTTP, so it needs a front door of its own. +Set `MTPROTO_ENABLED=true`, leave the first secret to be generated, and paste it +into the phone: **Settings → Data and Storage → Proxy**. + +Each secret is one phone. The dashboard's **Telegram** panel adds, disables and +revokes them, and a change applies immediately — a revoked phone stops working +at once, with no restart. + +This is obfuscated2 (the `dd` secret Telegram apps expect). Two honest limits: + +- **The camouflage here is Telegram's, not ours.** The transport looks like + random bytes, which is what every Telegram proxy looks like on the wire. If you + need the port to look like a website to an active prober, that is REALITY's + job — and Telegram does not speak VLESS. +- **Telegram's addresses are compiled in**, which is what every MTProxy does. + If they are unreachable from your network, `MTPROTO_DCS` points them + somewhere else. + ## Why the tunnel exists Render forwards inbound traffic to **one HTTP port** and terminates TLS at its load balancer. Koyeb, Heroku and Northflank behave the same way. A SOCKS5 client opening a raw socket against those hosts never reaches the container, and an in-process reverse proxy cannot help: the edge rejects the bytes before any process sees them. @@ -377,6 +399,9 @@ Edit `config.json` or use environment variables (env vars override config file): | `PROXY_PASS` | changeme | SOCKS5 password, also the HTTP proxy password | | `AUTH_ENABLED` | true | Enable SOCKS5 and HTTP proxy authentication | | `UDP_ENABLED` | true | SOCKS5 `UDP ASSOCIATE`. Set false for TCP only | +| `MTPROTO_ENABLED` | false | Telegram front door; generates its first secret on first start | +| `MTPROTO_BIND` | 0.0.0.0:8443 | Telegram port. Avoid 443 when REALITY has it | +| `MTPROTO_DCS` | unset | `dc=address,dc=address`, only when Telegram's own addresses are unreachable | | `MAX_CONNECTIONS` | 1000 | Max simultaneous connections | | `ADMIN_USER` | admin | Admin dashboard username | | `ADMIN_PASS` | changeme | Admin dashboard password | @@ -462,9 +487,9 @@ 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 and the managed VLESS UUIDs live -in the database; restoring an older or different one invalidates every client you -have imported. +working**, because the keypair travels with it and the managed VLESS UUIDs and +MTProto secrets live in the database; 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 @@ -611,6 +636,10 @@ at `/prometheus` with `basic_auth` configured. | PUT | `/api/users/:id` | Update user | | DELETE | `/api/users/:id` | Delete user | | POST | `/api/users/:id/reset` | Reset a user's data usage | +| GET | `/api/mtproto-secrets` | Telegram secrets, with the listener's bind address | +| POST | `/api/mtproto-secrets` | Add a secret; it is generated for you | +| PUT | `/api/mtproto-secrets/:id` | Relabel, or enable/disable, a secret | +| DELETE | `/api/mtproto-secrets/:id` | Revoke a phone, effective immediately | | GET | `/api/vless-clients` | REALITY client UUIDs, and whether they can be managed | | POST | `/api/vless-clients` | Add a client; the UUID is generated if omitted | | PUT | `/api/vless-clients/:id` | Relabel, or enable/disable, a client | diff --git a/config.json b/config.json index 13507d6..335a382 100644 --- a/config.json +++ b/config.json @@ -5,6 +5,9 @@ "max_connections": 1000, "auth_enabled": true, "udp_enabled": true, + "mtproto_enabled": false, + "mtproto_bind": "0.0.0.0:8443", + "mtproto_dcs": "", "username": "changeme", "password": "changeme", "whitelist": [], diff --git a/database.go b/database.go index 9c89337..bdf7be7 100644 --- a/database.go +++ b/database.go @@ -132,6 +132,16 @@ func (s *Store) migrate() error { enabled INTEGER NOT NULL DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP )`, + // MTProto secrets for the Telegram front door. The stored value is the + // shareable form, dd followed by 32 hex characters, so it can be pasted + // into a phone without editing. + `CREATE TABLE IF NOT EXISTS mtproto_secrets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + secret TEXT UNIQUE NOT NULL, + label TEXT NOT NULL DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + )`, } for _, q := range queries { @@ -750,6 +760,101 @@ func (s *Store) DeleteVlessClient(id int64) error { return err } +// ─── MTProto secrets ──────────────────────────────────────────────────────── + +type MtprotoSecret struct { + ID int64 `json:"id"` + Secret string `json:"secret"` + Label string `json:"label"` + Enabled bool `json:"enabled"` + CreatedAt string `json:"created_at"` +} + +func (s *Store) CreateMtprotoSecret(secret, label string) (*MtprotoSecret, error) { + secret = strings.TrimSpace(strings.ToLower(secret)) + if _, err := parseMTProtoSecret(secret); err != nil { + return nil, err + } + s.mu.Lock() + res, err := s.db.Exec("INSERT INTO mtproto_secrets (secret, label) VALUES (?, ?)", secret, label) + s.mu.Unlock() + if err != nil { + return nil, err + } + id, err := res.LastInsertId() + if err != nil { + return nil, err + } + return s.GetMtprotoSecret(id) +} + +func (s *Store) GetMtprotoSecret(id int64) (*MtprotoSecret, error) { + s.mu.Lock() + defer s.mu.Unlock() + + var sec MtprotoSecret + var enabled int + err := s.db.QueryRow("SELECT id, secret, label, enabled, created_at FROM mtproto_secrets WHERE id=?", id). + Scan(&sec.ID, &sec.Secret, &sec.Label, &enabled, &sec.CreatedAt) + if err != nil { + return nil, err + } + sec.Enabled = enabled != 0 + return &sec, nil +} + +func (s *Store) ListMtprotoSecrets() ([]MtprotoSecret, error) { + s.mu.Lock() + defer s.mu.Unlock() + + rows, err := s.db.Query("SELECT id, secret, label, enabled, created_at FROM mtproto_secrets ORDER BY id") + if err != nil { + return nil, err + } + defer rows.Close() + + out := []MtprotoSecret{} + for rows.Next() { + var sec MtprotoSecret + var enabled int + if err := rows.Scan(&sec.ID, &sec.Secret, &sec.Label, &enabled, &sec.CreatedAt); err != nil { + return nil, err + } + sec.Enabled = enabled != 0 + out = append(out, sec) + } + return out, rows.Err() +} + +func (s *Store) UpdateMtprotoSecret(id int64, label *string, enabled *bool) error { + s.mu.Lock() + defer s.mu.Unlock() + + if label != nil { + if _, err := s.db.Exec("UPDATE mtproto_secrets SET label=? WHERE id=?", *label, id); err != nil { + return err + } + } + if enabled != nil { + value := 0 + if *enabled { + value = 1 + } + if _, err := s.db.Exec("UPDATE mtproto_secrets SET enabled=? WHERE id=?", value, id); err != nil { + return err + } + } + return nil +} + +func (s *Store) DeleteMtprotoSecret(id int64) error { + s.mu.Lock() + defer s.mu.Unlock() + + _, err := s.db.Exec("DELETE FROM mtproto_secrets WHERE id=?", id) + return err +} + // ─── Connection Tracking ─────────────────────────────────────────────────── func (s *Store) TrackConnectionStart(userID int64, target string) (int64, error) { diff --git a/go.mod b/go.mod index e7ea0c7..816f000 100644 --- a/go.mod +++ b/go.mod @@ -1,19 +1,24 @@ module socks5-enterprise -go 1.24 +go 1.24.0 require ( github.com/coder/websocket v1.8.15 + github.com/gotd/td v0.140.0 github.com/prometheus/client_golang v1.16.0 modernc.org/sqlite v1.34.5 ) require ( github.com/beorn7/perks v1.0.1 // indirect - github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-faster/errors v0.7.1 // indirect + github.com/go-faster/jx v1.2.0 // indirect + github.com/go-faster/xor v1.0.0 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/gotd/ige v0.2.2 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect @@ -21,7 +26,10 @@ require ( github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.10.1 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect - golang.org/x/sys v0.22.0 // indirect + github.com/segmentio/asm v1.2.1 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.27.1 // indirect + golang.org/x/sys v0.41.0 // indirect google.golang.org/protobuf v1.30.0 // indirect modernc.org/libc v1.55.3 // indirect modernc.org/mathutil v1.6.0 // indirect diff --git a/go.sum b/go.sum index 504e7f4..21db7d8 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,28 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= -github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= +github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= +github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-faster/errors v0.7.1 h1:MkJTnDoEdi9pDabt1dpWf7AA8/BaSYZqibYyhZ20AYg= +github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo= +github.com/go-faster/jx v1.2.0 h1:T2YHJPrFaYu21fJtUxC9GzmluKu8rVIFDwwGBKTDseI= +github.com/go-faster/jx v1.2.0/go.mod h1:UWLOVDmMG597a5tBFPLIWJdUxz5/2emOpfsj9Neg0PE= +github.com/go-faster/xor v0.3.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ= +github.com/go-faster/xor v1.0.0 h1:2o8vTOgErSGHP3/7XwA5ib1FTtUsNtwCoLLBjl31X38= +github.com/go-faster/xor v1.0.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ= +github.com/go-faster/yaml v0.4.6 h1:lOK/EhI04gCpPgPhgt0bChS6bvw7G3WwI8xxVe0sw9I= +github.com/go-faster/yaml v0.4.6/go.mod h1:390dRIvV4zbnO7qC9FGo6YYutc+wyyUSHBgbXL52eXk= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= @@ -19,12 +34,24 @@ github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlG github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gotd/ige v0.2.2 h1:XQ9dJZwBfDnOGSTxKXBGP4gMud3Qku2ekScRjDWWfEk= +github.com/gotd/ige v0.2.2/go.mod h1:tuCRb+Y5Y3eNTo3ypIfNpQ4MFjrnONiL2jN2AKZXmb0= +github.com/gotd/neo v0.1.5 h1:oj0iQfMbGClP8xI59x7fE/uHoTJD7NZH9oV1WNuPukQ= +github.com/gotd/neo v0.1.5/go.mod h1:9A2a4bn9zL6FADufBdt7tZt+WMhvZoc5gWXihOPoiBQ= +github.com/gotd/td v0.140.0 h1:trNBzTnhNtNwHsFp5qwKnNxQRAZJ6/BRE+uH3Lojauk= +github.com/gotd/td v0.140.0/go.mod h1:0ZkRxG7N+5ooG7/zdRXcnGautGPM6IKmyPQvdsAeF20= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/ogen-go/ogen v1.19.0 h1:YvdNpeQJ8A8dLLpS6Vs4WxXL53BT6tBPxH0VSjfALhA= +github.com/ogen-go/ogen v1.19.0/go.mod h1:DeShwO+TEpLYXNCuZliSAedphphXsJaTGGbmSomWUjE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8= github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= github.com/prometheus/client_model v0.4.0 h1:5lQXD3cAg1OXBf4Wq03gTrXHeaV0TQvGfUooCfx1yqY= @@ -35,19 +62,47 @@ github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+Pymzi github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= -golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= -golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0= +github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= +github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= +github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms= +go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g= +go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g= +go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +golang.org/x/exp v0.0.0-20230725093048-515e97ebf090 h1:Di6/M8l0O2lCLc6VVRWhgCiApHV8MnQurBnFSHsQtNY= +golang.org/x/exp v0.0.0-20230725093048-515e97ebf090/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= +golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= +golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= +golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60= +golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= -golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= -golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= +golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= diff --git a/main.go b/main.go index 5205b2f..362791a 100644 --- a/main.go +++ b/main.go @@ -77,6 +77,14 @@ type Config struct { TLSCertFile string `json:"tls_cert_file"` TLSKeyFile string `json:"tls_key_file"` + // MTProto front door for Telegram. Its own protocol, so it is spoken here + // rather than by xray, and it needs a port of its own: 443 is usually taken + // by REALITY. + MTProtoEnabled bool `json:"mtproto_enabled"` + MTProtoBind string `json:"mtproto_bind"` + // Datacenter overrides, as dc=address,dc=address. + MTProtoDCs string `json:"mtproto_dcs"` + // SOCKS5 UDP ASSOCIATE. TCP-only was the original behaviour, and a proxy // that cannot carry UDP breaks DNS lookups and QUIC unless the client falls // back. The WebSocket tunnel is TCP-only by nature and cannot offer it. @@ -125,6 +133,7 @@ func DefaultConfig() Config { TunnelPadding: 256, TunnelRateRPS: 5, UDPEnabled: true, + MTProtoBind: defaultMTProtoBind, RealityBind: defaultRealityBind, RealityDest: defaultRealityDest, RealityXrayBin: "xray", @@ -281,6 +290,16 @@ func LoadConfig(filename string) (Config, error) { cfg.UDPEnabled = v == "true" || v == "1" } + if v := os.Getenv("MTPROTO_ENABLED"); v != "" { + cfg.MTProtoEnabled = v == "true" || v == "1" + } + if v := os.Getenv("MTPROTO_BIND"); v != "" { + cfg.MTProtoBind = v + } + if v := os.Getenv("MTPROTO_DCS"); v != "" { + cfg.MTProtoDCs = v + } + // REALITY. Comma-separated lists accept more than one SNI, short id or // VLESS id so a rotation does not need a restart. if v := os.Getenv("REALITY_ENABLED"); v != "" { @@ -546,6 +565,13 @@ type ProxyServer struct { reality *realityRunner realityKeys realityKeys + // MTProto front door. The secrets are kept in memory because they are read + // on every connection; the database holds them so the dashboard can manage + // them across restarts. + mtprotoMu sync.RWMutex + mtprotoSecrets mtprotoSecrets + mtprotoListener net.Listener + // Shutdown shutdownOnce sync.Once shutdownCh chan struct{} @@ -1898,6 +1924,120 @@ func (s *ProxyServer) adminHandler() http.Handler { } }) + // ─── MTProto secrets (Telegram) ─────────────────────────────────────── + // + // The live set lives in memory and is consulted on every connection, so + // adding or revoking a secret takes effect at once with nothing to restart. + mux.HandleFunc("/api/mtproto-secrets", func(w http.ResponseWriter, r *http.Request) { + if s.store == nil { + http.Error(w, "database not available", http.StatusServiceUnavailable) + return + } + + switch r.Method { + case http.MethodGet: + secrets, err := s.store.ListMtprotoSecrets() + if err != nil { + http.Error(w, "list failed: "+err.Error(), http.StatusInternalServerError) + return + } + s.configMu.RLock() + enabled := s.cfg.MTProtoEnabled + s.configMu.RUnlock() + s.mtprotoMu.RLock() + live := len(s.mtprotoSecrets) + bind := "" + if s.mtprotoListener != nil { + bind = s.mtprotoListener.Addr().String() + } + s.mtprotoMu.RUnlock() + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{ + "secrets": secrets, + "mtproto_enabled": enabled, + "bind": bind, + "live_secrets": live, + }) + + case http.MethodPost: + s.configMu.RLock() + enabled := s.cfg.MTProtoEnabled + s.configMu.RUnlock() + if !enabled { + http.Error(w, "MTPROTO_ENABLED is false, so there is no listener for a secret to work on", http.StatusConflict) + return + } + var req struct { + Label string `json:"label"` + } + if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { + http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) + return + } + secret, err := generateMTProtoSecret() + if err != nil { + http.Error(w, "could not generate a secret: "+err.Error(), http.StatusInternalServerError) + return + } + created, err := s.store.CreateMtprotoSecret(secret, req.Label) + if err != nil { + http.Error(w, "create failed: "+err.Error(), http.StatusInternalServerError) + return + } + s.setMTProtoSecrets(s.loadMTProtoSecrets(nil, false)) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(created) + + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } + }) + + mux.HandleFunc("/api/mtproto-secrets/", func(w http.ResponseWriter, r *http.Request) { + if s.store == nil { + http.Error(w, "database not available", http.StatusServiceUnavailable) + return + } + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/mtproto-secrets/"), "/") + if len(parts) == 0 || parts[0] == "" { + http.Error(w, "secret ID required", http.StatusBadRequest) + return + } + id := parseInt64(parts[0]) + + switch { + case r.Method == http.MethodDelete && len(parts) == 1: + if err := s.store.DeleteMtprotoSecret(id); err != nil { + http.Error(w, "delete failed: "+err.Error(), http.StatusInternalServerError) + return + } + s.setMTProtoSecrets(s.loadMTProtoSecrets(nil, false)) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"status": "deleted"}) + + case r.Method == http.MethodPut && len(parts) == 1: + var req struct { + Label *string `json:"label"` + Enabled *bool `json:"enabled"` + } + if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { + http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) + return + } + if err := s.store.UpdateMtprotoSecret(id, req.Label, req.Enabled); err != nil { + http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError) + return + } + s.setMTProtoSecrets(s.loadMTProtoSecrets(nil, false)) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"status": "updated"}) + + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } + }) + // GET /api/tiers - list available tiers mux.HandleFunc("/api/tiers", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { @@ -2252,6 +2392,15 @@ func runServer(logger *slog.Logger, configFile string) { server.reality, server.realityKeys = runner, keys } + // MTProto speaks its own protocol rather than SOCKS5, so it is served here. + // A failure is not fatal: the other protocols keep working, and an operator + // who did not ask for this should not find the service refusing to start. + if cfg.MTProtoEnabled { + if err := server.startMTProto(nil); err != nil { + logger.Error("failed to start the MTProto front door", "error", err) + } + } + // Periodic stats persistence (every 60 seconds) go func() { ticker := time.NewTicker(60 * time.Second) @@ -2357,6 +2506,7 @@ func runServer(logger *slog.Logger, configFile string) { if reality != nil { reality.Stop() } + server.stopMTProto() httpCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() diff --git a/mtproto.go b/mtproto.go new file mode 100644 index 0000000..b1cc4cb --- /dev/null +++ b/mtproto.go @@ -0,0 +1,592 @@ +package main + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "log/slog" + "net" + "strconv" + "strings" + "sync" + "time" +) + +// ─── MTProto obfuscated2 ─────────────────────────────────────────────────── +// +// Telegram clients do not speak SOCKS5 or HTTP. They speak MTProto, wrapped in +// the "obfuscated2" transport, and they expect to be able to carry that stream +// to Telegram unchanged. So unlike REALITY -- where xray in front of this +// service speaks VLESS and hands us plain SOCKS5 -- MTProto has to be spoken +// here: the client's obfuscated stream is unwrapped, and a second one is wrapped +// onto the connection to the real Telegram datacenter. +// +// The transport is a stream cipher keyed by the client's opening 64 bytes, mixed +// with a shared 16-byte secret. That secret is the whole of the access control: +// whoever knows it can use the proxy, and the protocol tag riding inside the +// encrypted tail is what proves the reader knew the secret too. +// +// The primitives are AES-256-CTR and SHA-256, both standard library. The layout +// is the one Telegram documents; gotd/td's obfuscated2 package is the +// independent implementation this is tested against, byte for byte, because a +// proxy that is merely self-consistent connects to nothing. + +const ( + mtprotoInitLen = 64 + mtprotoSecretLen = 16 + + // defaultMTProtoBind avoids 443, which belongs to REALITY on a host that has + // both, and avoids 80 for the same reason. + defaultMTProtoBind = "0.0.0.0:8443" + + // abridgedIntermediate is what we announce to the datacenter. It is the + // transport Telegram clients use through a proxy, so the datacenter behaves + // towards us exactly as it would towards a client. + abridgedIntermediate = 0xdddd516d +) + +// mtprotoProtocolOK reports whether p is a transport tag a Telegram client can +// actually be using. A stream decrypted with the wrong secret yields 32 random +// bytes, so a recognisable tag is what distinguishes "this is the right secret" +// from "this is noise" when several secrets are configured. +func mtprotoProtocolOK(p [4]byte) bool { + // The tag travels as four literal bytes, so it is compared as bytes rather + // than as the little-endian integer the datacenter id is. + switch p { + case [4]byte{0xee, 0xee, 0xee, 0xee}: // intermediate + return true + case [4]byte{0xdd, 0xdd, 0x51, 0x6d}: // abridged intermediate + return true + case [4]byte{0xdd, 0xdd, 0x51, 0x6e}: // padded intermediate + return true + case [4]byte{0x02, 0x01, 0x03, 0x16}: // used by some clients + return true + } + return false +} + +// mtprotoStreams derives the two directions from the client's opening bytes and +// the shared secret. fromPeer reads what the peer sends, toPeer writes what we +// send. +// +// The reversed copy of the client's bytes is the other direction's key material, +// which is why a stream can be read and written by two peers that never +// exchanged anything else. +func mtprotoStreams(init []byte, secret []byte) (toPeer, fromPeer cipher.Stream, err error) { + if len(init) < mtprotoInitLen { + return nil, nil, fmt.Errorf("mtproto init is %d bytes, want %d", len(init), mtprotoInitLen) + } + + toKey := append([]byte(nil), init[8:40]...) + toIV := append([]byte(nil), init[40:56]...) + + fromRev := make([]byte, 48) + copy(fromRev, init[8:56]) + reverse(fromRev) + fromKey := append([]byte(nil), fromRev[:32]...) + fromIV := append([]byte(nil), fromRev[32:48]...) + + if len(secret) > 0 { + if len(secret) < mtprotoSecretLen { + return nil, nil, fmt.Errorf("mtproto secret is %d bytes, want %d", len(secret), mtprotoSecretLen) + } + shared := secret[:mtprotoSecretLen] + toKey = sha256Concat(toKey, shared) + fromKey = sha256Concat(fromKey, shared) + } + + toStream, err := aesCTR(toKey, toIV) + if err != nil { + return nil, nil, err + } + fromStream, err := aesCTR(fromKey, fromIV) + if err != nil { + return nil, nil, err + } + return toStream, fromStream, nil +} + +func aesCTR(key, iv []byte) (cipher.Stream, error) { + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + return cipher.NewCTR(block, iv), nil +} + +func sha256Concat(parts ...[]byte) []byte { + n := 0 + for _, p := range parts { + n += len(p) + } + joined := make([]byte, 0, n) + for _, p := range parts { + joined = append(joined, p...) + } + sum := sha256.Sum256(joined) + return sum[:] +} + +func reverse(b []byte) { + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } +} + +// mtprotoSession is one leg of a proxied conversation: an obfuscated stream in +// each direction. +type mtprotoSession struct { + conn net.Conn + toPeer cipher.Stream + from cipher.Stream +} + +// Close ends the underlying connection. The session is not reused, so closing +// twice is harmless. +func (s *mtprotoSession) Close() error { return s.conn.Close() } + +func (s *mtprotoSession) Read(p []byte) (int, error) { + n, err := s.conn.Read(p) + if n > 0 { + s.from.XORKeyStream(p[:n], p[:n]) + } + return n, err +} + +func (s *mtprotoSession) Write(p []byte) (int, error) { + buf := make([]byte, len(p)) + s.toPeer.XORKeyStream(buf, p) + + // TCP is free to accept less than it was given, and a short write here means + // the tail of a message is lost with no error reported anywhere -- which + // looks to Telegram like a broken proxy rather than a busy socket. + written := 0 + for written < len(buf) { + n, err := s.conn.Write(buf[written:]) + written += n + if err != nil { + return written, err + } + } + return len(p), nil +} + +// mtprotoAccept performs the server half of the handshake: it reads the client's +// opening 64 bytes, derives the streams from them and the shared secret, and +// returns the deobfuscated connection plus the datacenter the client asked for. +// +// With several secrets configured, a stream whose decrypted tag is not one a +// Telegram client uses means the secret was wrong, and the caller should try the +// next one. +func mtprotoAccept(conn net.Conn, secret []byte, strictTag bool) (*mtprotoSession, int, error) { + init := make([]byte, mtprotoInitLen) + if _, err := io.ReadFull(conn, init); err != nil { + return nil, 0, fmt.Errorf("read mtproto init: %w", err) + } + + toPeer, fromPeer, err := mtprotoStreams(init, secret) + if err != nil { + return nil, 0, err + } + + // The reader's view is the mirror image of the writer's. + toPeer, fromPeer = fromPeer, toPeer + + // Decrypting all 64 bytes advances the stream to the same offset the client + // reached, which is what lets the next read line up. + decrypted := make([]byte, mtprotoInitLen) + fromPeer.XORKeyStream(decrypted, init) + + var protocol [4]byte + copy(protocol[:], decrypted[56:60]) + dc := int(binary.LittleEndian.Uint16(decrypted[60:62])) + + if strictTag && !mtprotoProtocolOK(protocol) { + return nil, 0, fmt.Errorf("not a Telegram transport tag (%x): wrong secret?", protocol) + } + + return &mtprotoSession{conn: conn, toPeer: toPeer, from: fromPeer}, dc, nil +} + +// mtprotoDial performs the client half towards a Telegram datacenter: send the +// opening bytes, then return the session to relay over. +func mtprotoDial(dc int, dialTimeout time.Duration, overrides map[int]string) (*mtprotoSession, error) { + addr := mtprotoDCAddress(dc, overrides) + conn, err := net.DialTimeout("tcp", addr, dialTimeout) + if err != nil { + return nil, fmt.Errorf("dial dc %d (%s): %w", dc, addr, err) + } + + init := make([]byte, mtprotoInitLen) + if _, err := io.ReadFull(rand.Reader, init); err != nil { + conn.Close() + return nil, err + } + toPeer, fromPeer, err := mtprotoStreams(init, nil) + if err != nil { + conn.Close() + return nil, err + } + + // The transport tag is four literal bytes; the datacenter id is a + // little-endian integer. Getting that backwards still produces a stream that + // looks random, so it is worth saying which is which. + copy(init[56:60], []byte{0xdd, 0xdd, 0x51, 0x6d}) + binary.LittleEndian.PutUint16(init[60:62], uint16(dc)) + + encrypted := make([]byte, mtprotoInitLen) + toPeer.XORKeyStream(encrypted, init) + + // First 56 bytes travel as sent; the last 8 carry the transport tag and the + // datacenter, and only make sense to a holder of the keys. + header := append(append([]byte(nil), init[:56]...), encrypted[56:]...) + if _, err := conn.Write(header); err != nil { + conn.Close() + return nil, fmt.Errorf("write mtproto init: %w", err) + } + return &mtprotoSession{conn: conn, toPeer: toPeer, from: fromPeer}, nil +} + +// ─── Telegram datacenters ────────────────────────────────────────────────── +// +// The addresses below are the production datacenters, which are stable and +// documented rather than discovered. MTPROTO_DCS overrides them for anyone whose +// network cannot reach these directly; the format is dc=address,dc=address. +var mtprotoDefaultDCs = map[int]string{ + 1: "149.154.175.50:443", + 2: "149.154.167.51:443", + 3: "149.154.175.100:443", + 4: "149.154.167.91:443", + 5: "91.108.56.130:443", +} + +// parseMTProtoDCOverrides reads dc=address,dc=address, letting an operator whose +// network cannot reach Telegram directly point at a mirror. Parsed once at +// startup rather than per connection: reading the environment from several +// connection goroutines at once is a data race, and the answer cannot change +// without a restart anyway. +func parseMTProtoDCOverrides(raw string) map[int]string { + raw = strings.TrimSpace(raw) + if raw == "" { + return nil + } + parsed := map[int]string{} + var ignored []string + for _, entry := range strings.Split(raw, ",") { + entry = strings.TrimSpace(entry) + if entry == "" { + continue + } + dcText, addr, found := strings.Cut(entry, "=") + if !found { + ignored = append(ignored, entry) + continue + } + dc, err := strconv.Atoi(strings.TrimSpace(dcText)) + if err != nil || dc < 1 || dc > 20 { + ignored = append(ignored, entry) + continue + } + parsed[dc] = strings.TrimSpace(addr) + } + if len(ignored) > 0 { + slog.Warn("ignoring unreadable MTPROTO_DCS entries", "entries", ignored) + } + if len(parsed) == 0 { + return nil + } + return parsed +} + +// mtprotoDCAddress returns where to reach a datacenter, preferring an override. +func mtprotoDCAddress(dc int, overrides map[int]string) string { + if addr, ok := overrides[dc]; ok { + return addr + } + if addr, ok := mtprotoDefaultDCs[dc]; ok { + return addr + } + // An unknown id is almost always a client asking for a datacenter that does + // not exist; DC2 is the documented fallback and is reachable everywhere. + return mtprotoDefaultDCs[2] +} + +// ─── The proxy ────────────────────────────────────────────────────────────── + +// mtprotoSecrets is the set of shared secrets the listener will accept, keyed by +// their hex form so the dashboard and the database speak the same identifier. +type mtprotoSecrets map[string][]byte + +// mtprotoServer accepts Telegram clients and relays them to a datacenter. +type mtprotoServer struct { + cfg Config + // secrets is a getter, not a map: the set is replaced when the dashboard + // changes it, and a copy taken at startup would keep serving secrets that + // have since been revoked. + secrets func() mtprotoSecrets + overrides map[int]string + log *slog.Logger + track func(net.Conn) + untrack func(net.Conn) + listener net.Listener +} + +// serveMTProto runs until the listener is closed. Each connection is handed to +// handleMTProto. +func (m *mtprotoServer) serve() { + for { + conn, err := m.listener.Accept() + if err != nil { + if isTemporary(err) { + time.Sleep(50 * time.Millisecond) + continue + } + // The listener was closed, which is how this loop ends. + return + } + go m.handle(conn) + } +} + +func isTemporary(err error) bool { + var ne net.Error + return errors.As(err, &ne) && ne.Timeout() +} + +func (m *mtprotoServer) handle(conn net.Conn) { + log := m.log.With("client", remoteIP(conn)) + m.track(conn) + defer m.untrack(conn) + + idle := time.Duration(m.cfg.IdleTimeout) * time.Second + if idle <= 0 { + idle = 300 * time.Second + } + dialTimeout := time.Duration(m.cfg.ReadTimeout) * time.Second + if dialTimeout <= 0 { + dialTimeout = 10 * time.Second + } + + // Every secret is tried in turn, and the transport tag is always checked. + secrets := m.secrets() + session, dc, err := m.acceptWithAnySecret(conn, secrets) + if err != nil { + log.Debug("mtproto handshake refused", "error", err) + return + } + + upstream, err := mtprotoDial(dc, dialTimeout, m.overrides) + if err != nil { + log.Warn("cannot reach the datacenter", "dc", dc, "error", err) + return + } + defer upstream.Close() + + var once sync.Once + closeBoth := func() { + once.Do(func() { + session.Close() + upstream.Close() + }) + } + // Telegram holds connections open, so neither leg closes on its own; the + // first side to go takes the other with it. + go func() { + defer closeBoth() + copyStream(upstream, session, log) + }() + go func() { + defer closeBoth() + copyStream(session, upstream, log) + }() + + log.Info("mtproto session relayed", "dc", dc, "address", mtprotoDCAddress(dc, m.overrides)) + <-time.After(idle) + closeBoth() +} + +// acceptWithAnySecret finds the secret the client is using. Each attempt reads +// from the same connection, so a wrong secret only costs the client opening +// bytes: the server has consumed exactly the same 64 bytes either way, and the +// stream is discarded between attempts. +func (m *mtprotoServer) acceptWithAnySecret(conn net.Conn, secrets mtprotoSecrets) (*mtprotoSession, int, error) { + if len(secrets) == 0 { + return nil, 0, errors.New("no MTProto secret is configured") + } + init := make([]byte, mtprotoInitLen) + if _, err := io.ReadFull(conn, init); err != nil { + return nil, 0, err + } + + var lastErr error + for _, secret := range secrets { + toPeer, fromPeer, err := mtprotoStreams(init, secret) + if err != nil { + lastErr = err + continue + } + toPeer, fromPeer = fromPeer, toPeer + + // Decrypt a copy, never the opening bytes themselves: a wrong secret must + // not consume the stream the next attempt needs. + probe := make([]byte, mtprotoInitLen) + fromPeer.XORKeyStream(probe, init) + + // Only a reader who knows the secret gets a recognisable tag out of the + // encrypted tail, so this rejects a wrong secret rather than a valid one. + var protocol [4]byte + copy(protocol[:], probe[56:60]) + if !mtprotoProtocolOK(protocol) { + lastErr = fmt.Errorf("no configured secret matched (decrypted tag %x)", protocol) + continue + } + dc := int(binary.LittleEndian.Uint16(probe[60:62])) + return &mtprotoSession{conn: conn, toPeer: toPeer, from: fromPeer}, dc, nil + } + if lastErr == nil { + lastErr = errors.New("no configured secret matched") + } + return nil, 0, lastErr +} + +// copyStream moves bytes until one side stops or the idle window closes. +func copyStream(dst io.Writer, src io.Reader, log *slog.Logger) { + // io.Copy rather than a hand-rolled loop: it deals with short writes, which + // a relay that drops them turns into silent truncation. + if _, err := io.CopyBuffer(dst, src, make([]byte, 32*1024)); err != nil { + log.Debug("mtproto relay ended", "error", err) + } +} + +// ─── Secrets ──────────────────────────────────────────────────────────────── + +// generateMTProtoSecret returns a shareable proxy secret: the dd prefix marks it +// as an obfuscated2 secret, which is what the Telegram apps expect to paste. +func generateMTProtoSecret() (string, error) { + raw := make([]byte, mtprotoSecretLen) + if _, err := rand.Read(raw); err != nil { + return "", err + } + return "dd" + hex.EncodeToString(raw), nil +} + +// parseMTProtoSecret turns a stored secret into its 16 key bytes. The dd prefix +// is Telegram's, not ours, and takes no part in the cryptography. +func parseMTProtoSecret(stored string) ([]byte, error) { + key, err := hex.DecodeString(strings.TrimPrefix(stored, "dd")) + if err != nil { + return nil, fmt.Errorf("%q is not a hex secret", stored) + } + if len(key) != mtprotoSecretLen { + return nil, fmt.Errorf("secret is %d bytes, want %d", len(key), mtprotoSecretLen) + } + return key, nil +} + +// startMTProto brings up the Telegram front door. Secrets come from the +// database, so a fresh install gets one generated and can start serving +// immediately rather than refusing to start and waiting to be configured. +func (s *ProxyServer) startMTProto(secrets mtprotoSecrets) error { + secrets = s.loadMTProtoSecrets(secrets, true) + if len(secrets) == 0 { + return errors.New("no MTProto secret is configured; add one in the dashboard") + } + + listener, err := net.Listen("tcp", s.cfg.MTProtoBind) + if err != nil { + return fmt.Errorf("listen on %s: %w", s.cfg.MTProtoBind, err) + } + + s.mtprotoMu.Lock() + s.mtprotoSecrets = secrets + s.mtprotoListener = listener + s.mtprotoMu.Unlock() + + server := &mtprotoServer{ + cfg: s.cfg, + secrets: s.mtprotoLiveSecrets, + overrides: parseMTProtoDCOverrides(s.cfg.MTProtoDCs), + log: s.logger, + track: s.trackConn, + untrack: s.untrackConn, + listener: listener, + } + go server.serve() + + s.logger.Info("MTProto enabled", "bind", s.cfg.MTProtoBind, "secrets", len(secrets), + "edit", "in the dashboard, or Telegram: Settings -> Data and Storage -> Proxy") + return nil +} + +// loadMTProtoSecrets rebuilds the live set from the database. +// +// generateIfEmpty is only ever true at startup. After a dashboard change it must +// be false: revoking the last secret has to leave the proxy refusing everyone, +// because quietly minting a replacement would undo the operator's decision and +// hand out a working credential they never asked for. +func (s *ProxyServer) loadMTProtoSecrets(fallback mtprotoSecrets, generateIfEmpty bool) mtprotoSecrets { + out := mtprotoSecrets{} + if s.store != nil { + if stored, err := s.store.ListMtprotoSecrets(); err != nil { + s.logger.Warn("could not read MTProto secrets", "error", err) + } else { + for _, sec := range stored { + if !sec.Enabled { + continue + } + if key, err := parseMTProtoSecret(sec.Secret); err == nil { + out[sec.Secret] = key + } + } + } + } + if len(out) == 0 { + for name, key := range fallback { + out[name] = key + } + } + if len(out) == 0 && generateIfEmpty && s.store != nil { + secret, err := generateMTProtoSecret() + if err == nil { + if _, err := s.store.CreateMtprotoSecret(secret, "generated"); err == nil { + if key, kerr := parseMTProtoSecret(secret); kerr == nil { + out[secret] = key + } + s.logger.Info("generated the first MTProto secret", "secret", secret) + } + } + } + return out +} + +// setMTProtoSecrets replaces the live set after a dashboard change. Nothing has +// to be restarted: the set is consulted on every connection. +func (s *ProxyServer) setMTProtoSecrets(secrets mtprotoSecrets) { + s.mtprotoMu.Lock() + s.mtprotoSecrets = secrets + s.mtprotoMu.Unlock() +} + +// mtprotoLiveSecrets is the set currently being served. +func (s *ProxyServer) mtprotoLiveSecrets() mtprotoSecrets { + s.mtprotoMu.RLock() + defer s.mtprotoMu.RUnlock() + return s.mtprotoSecrets +} + +// stopMTProto closes the listener, which ends the accept loop. +func (s *ProxyServer) stopMTProto() { + s.mtprotoMu.Lock() + listener := s.mtprotoListener + s.mtprotoListener = nil + s.mtprotoMu.Unlock() + if listener != nil { + listener.Close() + } +} diff --git a/mtproto_test.go b/mtproto_test.go new file mode 100644 index 0000000..a0f7632 --- /dev/null +++ b/mtproto_test.go @@ -0,0 +1,528 @@ +package main + +import ( + "bytes" + "crypto/rand" + "fmt" + "io" + "net" + "strconv" + "strings" + "testing" + "time" + + "github.com/gotd/td/mtproxy" + "github.com/gotd/td/mtproxy/obfuscated2" +) + +// These tests check our obfuscated2 implementation against gotd/td, an +// independent one. A proxy that is only self-consistent connects to nothing, so +// every handshake here has the peer on the other side written by somebody else. + +// The real proof: a client that speaks gotd's obfuscated2 connects to our +// listener, and every byte either way survives. +func TestMTProtoAcceptInteropWithGotdClient(t *testing.T) { + secret := make([]byte, 16) + if _, err := rand.Read(secret); err != nil { + t.Fatalf("rand: %v", err) + } + + client, server := net.Pipe() + defer client.Close() + defer server.Close() + + const dc = 2 + clientObf := obfuscated2.NewObfuscated2(rand.Reader, client) + go func() { + _ = clientObf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, dc, mtproxy.Secret{Secret: secret}) + }() + + if err := server.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { + t.Fatalf("deadline: %v", err) + } + + session, gotDC, err := mtprotoAccept(server, secret, true) + if err != nil { + t.Fatalf("our server handshake refused a gotd client: %v", err) + } + if gotDC != dc { + t.Errorf("datacenter = %d, want %d", gotDC, dc) + } + + payloads := [][]byte{[]byte("hello from the client"), bytes.Repeat([]byte{0xAB}, 4096), []byte("tail")} + go func() { + for _, p := range payloads { + if _, err := clientObf.Write(p); err != nil { + return + } + } + }() + + for i, want := range payloads { + got := make([]byte, len(want)) + if _, err := io.ReadFull(session, got); err != nil { + t.Fatalf("payload %d: %v", i, err) + } + if !bytes.Equal(got, want) { + t.Errorf("payload %d = %x, want %x", i, got, want) + } + } +} + +// And the other direction: when we are the client to a datacenter, a peer running +// gotd's server side must be able to read what we write. +func TestMTProtoDialInteropWithGotdServer(t *testing.T) { + const dc = 4 + const fromProxy, fromDC = "from our dial", "from the dc" + + // Stand in for the datacenter: gotd's server-side Accept with no secret. + tcp, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer tcp.Close() + + served := make(chan error, 1) + go func() { + conn, aerr := tcp.Accept() + if aerr != nil { + served <- aerr + return + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(10 * time.Second)) + session, meta, aerr := obfuscated2.Accept(conn, nil) + if aerr != nil { + served <- aerr + return + } + if meta.DC != dc { + served <- errUnexpectedDC{int(meta.DC)} + return + } + buf := make([]byte, len(fromProxy)) + if _, rerr := io.ReadFull(session, buf); rerr != nil { + served <- rerr + return + } + if string(buf) != fromProxy { + served <- fmt.Errorf("payload came back as %q", buf) + return + } + _, werr := session.Write([]byte("from the dc")) + served <- werr + }() + + // Point the dialer at our stand-in rather than a real datacenter. + overrides := map[int]string{dc: "127.0.0.1:" + strconv.Itoa(tcp.Addr().(*net.TCPAddr).Port)} + session, err := mtprotoDial(dc, 5*time.Second, overrides) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer session.conn.Close() + + if _, err := session.Write([]byte(fromProxy)); err != nil { + t.Fatalf("write: %v", err) + } + got := make([]byte, len(fromDC)) + if _, err := io.ReadFull(session, got); err != nil { + t.Fatalf("read: %v (stand-in said: %v)", err, <-served) + } + if string(got) != fromDC { + t.Errorf("read %q, want %q", got, fromDC) + } + if err := <-served; err != nil { + t.Errorf("the stand-in datacenter reported: %v", err) + } +} + +// A client that does not know the secret must be refused, and a stream decrypted +// with the wrong secret must not look like a real transport. +func TestMTProtoWrongSecretIsRefused(t *testing.T) { + secret := make([]byte, 16) + other := make([]byte, 16) + rand.Read(secret) + rand.Read(other) + secret[0], other[0] = secret[0]^0xff, secret[0]^0xff + + client, server := net.Pipe() + defer client.Close() + defer server.Close() + + obf := obfuscated2.NewObfuscated2(rand.Reader, client) + go func() { + _ = obf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 2, mtproxy.Secret{Secret: secret}) + }() + server.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, _, err := mtprotoAccept(server, other, true); err == nil { + t.Fatal("a client with the wrong secret was accepted") + } +} + +// The tag check is the only thing standing between a single-secret proxy and +// serving anyone at all, so it runs even when there is just one secret. +func TestMTProtoSingleSecretStillChecksTheTag(t *testing.T) { + secret := make([]byte, 16) + rand.Read(secret) + + // A real transport tag is accepted, and the datacenter comes through. + client, server := net.Pipe() + defer client.Close() + defer server.Close() + obf := obfuscated2.NewObfuscated2(rand.Reader, client) + go func() { + _ = obf.Handshake([4]byte{0xee, 0xee, 0xee, 0xee}, 1, mtproxy.Secret{Secret: secret}) + }() + server.SetDeadline(time.Now().Add(5 * time.Second)) + if _, dc, err := mtprotoAccept(server, secret, true); err != nil { + t.Fatalf("a client using a real transport tag was refused: %v", err) + } else if dc != 1 { + t.Errorf("dc = %d, want 1", dc) + } + + // Junk in the same position is not. + client2, server2 := net.Pipe() + defer client2.Close() + defer server2.Close() + go func() { + _, _ = client2.Write(make([]byte, 64)) + }() + server2.SetDeadline(time.Now().Add(5 * time.Second)) + if _, _, err := mtprotoAccept(server2, secret, true); err == nil { + t.Error("random bytes were accepted as a client") + } +} + +func TestMTProtoProtocolTags(t *testing.T) { + for _, tag := range [][4]byte{{0xee, 0xee, 0xee, 0xee}, {0xdd, 0xdd, 0x51, 0x6d}, {0xdd, 0xdd, 0x51, 0x6e}, {0x02, 0x01, 0x03, 0x16}} { + if !mtprotoProtocolOK(tag) { + t.Errorf("transport tag %x was rejected", tag) + } + } + for _, tag := range [][4]byte{{0xde, 0xad, 0xbe, 0xef}, {0, 0, 0, 0}, {0x48, 0x45, 0x41, 0x44}} { // HEAD + if mtprotoProtocolOK(tag) { + t.Errorf("junk tag %x was accepted", tag) + } + } +} + +func TestMTProtoDCOverrides(t *testing.T) { + overrides := parseMTProtoDCOverrides("4=127.0.0.1:9999, 2=127.0.0.1:8888, nonsense, x=127.0.0.1:1") + + if got := mtprotoDCAddress(4, overrides); got != "127.0.0.1:9999" { + t.Errorf("dc 4 = %q, want the override", got) + } + if got := mtprotoDCAddress(2, overrides); got != "127.0.0.1:8888" { + t.Errorf("dc 2 = %q, want the override", got) + } + if got := mtprotoDCAddress(1, overrides); got != mtprotoDefaultDCs[1] { + t.Errorf("dc 1 = %q, want the default", got) + } + // An unknown datacenter must still produce a dialable address. + if got := mtprotoDCAddress(77, overrides); got == "" { + t.Error("an unknown datacenter produced no address") + } + if parseMTProtoDCOverrides("") != nil { + t.Error("an empty setting should produce no overrides") + } +} + +// ─── helpers ──────────────────────────────────────────────────────────────── + +type errUnexpectedDC struct{ dc int } + +func (e errUnexpectedDC) Error() string { return "unexpected datacenter " + strconv.Itoa(e.dc) } + +// TestMTProtoRelayEndToEnd runs the whole feature: a client speaking gotd's +// obfuscated2 connects to our listener with a secret from the database, and the +// bytes arrive at the datacenter it asked for. +func TestMTProtoRelayEndToEnd(t *testing.T) { + secret, err := generateMTProtoSecret() + if err != nil { + t.Fatalf("generate secret: %v", err) + } + key, err := parseMTProtoSecret(secret) + if err != nil { + t.Fatalf("parse secret: %v", err) + } + + // A datacenter that echoes whatever it is sent, so the test can prove the + // payload crossed both obfuscation layers intact. + dcListener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen dc: %v", err) + } + defer dcListener.Close() + go func() { + for { + conn, aerr := dcListener.Accept() + if aerr != nil { + return + } + go func() { + defer conn.Close() + // The datacenter side is stood in for with our own handshake: the + // independent implementation is already on the client side, which + // is where the compatibility claim actually is. + session, _, herr := mtprotoAccept(conn, nil, false) + if herr != nil { + return + } + buf := make([]byte, 4096) + for { + n, rerr := session.Read(buf) + if n > 0 { + if _, werr := session.Write(buf[:n]); werr != nil { + return + } + } + if rerr != nil { + return + } + } + }() + } + }() + + cfg := DefaultConfig() + cfg.MTProtoEnabled = true + cfg.MTProtoBind = "127.0.0.1:" + strconv.Itoa(freePort(t)) + cfg.MTProtoDCs = "3=127.0.0.1:" + strconv.Itoa(dcListener.Addr().(*net.TCPAddr).Port) + + s := NewProxyServer(cfg) + s.store = newTestStore(t) + if _, err := s.store.CreateMtprotoSecret(secret, "test phone"); err != nil { + t.Fatalf("store secret: %v", err) + } + if err := s.startMTProto(nil); err != nil { + t.Fatalf("start mtproto: %v", err) + } + defer s.stopMTProto() + + client, err := net.Dial("tcp", s.mtprotoListener.Addr().String()) + if err != nil { + t.Fatalf("dial mtproto: %v", err) + } + defer client.Close() + client.SetDeadline(time.Now().Add(15 * time.Second)) + + obf := obfuscated2.NewObfuscated2(rand.Reader, client) + if err := obf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 3, mtproxy.Secret{Secret: key}); err != nil { + t.Fatalf("client handshake: %v", err) + } + + payload := []byte("a message that has to survive two obfuscation layers") + if _, err := obf.Write(payload); err != nil { + t.Fatalf("write: %v", err) + } + echoed := make([]byte, len(payload)) + if _, err := io.ReadFull(obf, echoed); err != nil { + t.Fatalf("read: %v", err) + } + if !bytes.Equal(echoed, payload) { + t.Errorf("echoed %q, want %q", echoed, payload) + } + + // Several chunks in a row, to exercise the relay the way a session does. + // Sent in modest pieces because the reference client writes a whole buffer + // in one call and would short-write a large one, which is a property of the + // harness rather than of this relay. + for round := 0; round < 8; round++ { + chunk := bytes.Repeat([]byte{byte('A' + round)}, 4096) + if _, err := obf.Write(chunk); err != nil { + t.Fatalf("write round %d: %v", round, err) + } + echo := make([]byte, len(chunk)) + if _, err := io.ReadFull(obf, echo); err != nil { + t.Fatalf("read round %d: %v", round, err) + } + if !bytes.Equal(echo, chunk) { + for i := range chunk { + if echo[i] != chunk[i] { + t.Fatalf("round %d diverges at byte %d: got %02x want %02x (first 40: %q)", round, i, echo[i], chunk[i], string(echo[:min(40, len(echo))])) + } + } + t.Fatalf("round %d differs but not byte-wise", round) + } + } +} + +// A session must not lose the tail of a write when the socket takes less than +// it was offered. Telegram traffic is far larger than a socket buffer, so this +// is the difference between working and appearing intermittently broken. +func TestMTProtoWriteSurvivesShortWrites(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + + toPeer, fromPeer, err := mtprotoStreams(make([]byte, 64), nil) + if err != nil { + t.Fatalf("streams: %v", err) + } + session := &mtprotoSession{conn: server, toPeer: toPeer, from: fromPeer} + + payload := bytes.Repeat([]byte{0x7E}, 200_000) + go func() { _, _ = session.Write(payload) }() + + got := make([]byte, len(payload)) + if _, err := io.ReadFull(client, got); err != nil { + t.Fatalf("read: %v", err) + } + // Decrypt what the peer received and compare. + peerTo, peerFrom, err := mtprotoStreams(make([]byte, 64), nil) + if err != nil { + t.Fatalf("streams: %v", err) + } + peerFrom.XORKeyStream(got, got) + _ = peerTo + if !bytes.Equal(got, payload) { + t.Errorf("a short-writing socket lost data: %d bytes back, %d sent", len(got), len(payload)) + } +} + +// A client without a configured secret must get nowhere, and the listener must +// stay up for the next one. +func TestMTProtoUnknownSecretRefused(t *testing.T) { + secret, err := generateMTProtoSecret() + if err != nil { + t.Fatalf("generate: %v", err) + } + stranger := make([]byte, 16) + rand.Read(stranger) + + cfg := DefaultConfig() + cfg.MTProtoEnabled = true + cfg.MTProtoBind = "127.0.0.1:" + strconv.Itoa(freePort(t)) + cfg.MTProtoDCs = "2=127.0.0.1:1" // unreachable: the handshake is what is under test + + s := NewProxyServer(cfg) + s.store = newTestStore(t) + if _, err := s.store.CreateMtprotoSecret(secret, "the only one"); err != nil { + t.Fatalf("store secret: %v", err) + } + if err := s.startMTProto(nil); err != nil { + t.Fatalf("start: %v", err) + } + defer s.stopMTProto() + + client, err := net.Dial("tcp", s.mtprotoListener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer client.Close() + client.SetDeadline(time.Now().Add(5 * time.Second)) + + obf := obfuscated2.NewObfuscated2(rand.Reader, client) + _ = obf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 2, mtproxy.Secret{Secret: stranger}) + _, _ = obf.Write([]byte("let me in")) + + // Dropped rather than answered, and quickly: a served client would be + // waiting on the unreachable datacenter. + buf := make([]byte, 32) + client.SetReadDeadline(time.Now().Add(2 * time.Second)) + start := time.Now() + if _, err := obf.Read(buf); err == nil { + t.Error("a client with an unknown secret got a reply") + } + if waited := time.Since(start); waited > time.Second { + t.Errorf("the refusal took %v, so the connection was being relayed", waited) + } +} + +func TestMTProtoSecretFormat(t *testing.T) { + secret, err := generateMTProtoSecret() + if err != nil { + t.Fatalf("generate: %v", err) + } + if !strings.HasPrefix(secret, "dd") { + t.Errorf("secret %q does not carry the dd prefix the Telegram apps expect", secret) + } + if len(secret) != 34 { + t.Errorf("secret %q is %d characters, want 34", secret, len(secret)) + } + if key, err := parseMTProtoSecret(secret); err != nil || len(key) != 16 { + t.Errorf("parse(%q) = %v, %v", secret, key, err) + } + // The prefix is Telegram's, so a secret without it must still work. + if key, err := parseMTProtoSecret(secret[2:]); err != nil || len(key) != 16 { + t.Errorf("a secret without the prefix did not parse: %v, %v", key, err) + } + for _, bad := range []string{"", "zz", "dd", "ddzz", "dd" + strings.Repeat("00", 15)} { + if _, err := parseMTProtoSecret(bad); err == nil { + t.Errorf("parse(%q) was accepted", bad) + } + } + // Two secrets must differ, or one would be shared by everyone. + other, _ := generateMTProtoSecret() + if other == secret { + t.Error("generated the same secret twice") + } +} + +// Revoking the last secret must leave the proxy refusing everyone. Quietly +// minting a replacement would undo the decision and hand out a credential the +// operator never asked for -- and the dashboard change would look like it worked. +func TestMTProtoRevokingLastSecretDoesNotMintOne(t *testing.T) { + secret, err := generateMTProtoSecret() + if err != nil { + t.Fatalf("generate: %v", err) + } + key, _ := parseMTProtoSecret(secret) + + cfg := DefaultConfig() + cfg.MTProtoEnabled = true + cfg.MTProtoBind = "127.0.0.1:" + strconv.Itoa(freePort(t)) + cfg.MTProtoDCs = "2=127.0.0.1:1" + + s := NewProxyServer(cfg) + s.store = newTestStore(t) + row, err := s.store.CreateMtprotoSecret(secret, "the only phone") + if err != nil { + t.Fatalf("store: %v", err) + } + if err := s.startMTProto(nil); err != nil { + t.Fatalf("start: %v", err) + } + defer s.stopMTProto() + + if live := s.mtprotoLiveSecrets(); len(live) != 1 { + t.Fatalf("live secrets = %d, want 1", len(live)) + } + + if err := s.store.DeleteMtprotoSecret(row.ID); err != nil { + t.Fatalf("delete: %v", err) + } + s.setMTProtoSecrets(s.loadMTProtoSecrets(nil, false)) + + if live := s.mtprotoLiveSecrets(); len(live) != 0 { + t.Fatalf("live secrets = %d after revoking the last one; a new one was minted", len(live)) + } + if stored, _ := s.store.ListMtprotoSecrets(); len(stored) != 0 { + t.Errorf("stored secrets = %d, want 0", len(stored)) + } + + // And the listener now turns a client away. + client, err := net.Dial("tcp", s.mtprotoListener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer client.Close() + client.SetDeadline(time.Now().Add(5 * time.Second)) + obf := obfuscated2.NewObfuscated2(rand.Reader, client) + _ = obf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 2, mtproxy.Secret{Secret: key}) + _, _ = obf.Write([]byte("let me in")) + + // A served client would sit waiting for an unreachable datacenter, so the + // connection being closed quickly is what proves it was turned away. Merely + // "some error eventually" would not distinguish the two. + buf := make([]byte, 16) + client.SetReadDeadline(time.Now().Add(2 * time.Second)) + start := time.Now() + if _, err := obf.Read(buf); err == nil { + t.Fatal("a client was served after every secret was revoked") + } + if waited := time.Since(start); waited > time.Second { + t.Errorf("the refusal took %v, so the connection was being relayed rather than refused", waited) + } +} diff --git a/web/index.html b/web/index.html index eb1018c..b1f07bb 100644 --- a/web/index.html +++ b/web/index.html @@ -260,6 +260,42 @@

User Management

+
+

Telegram (MTProto)

+
+
+

+ Each secret is one Telegram client. Add one, then paste it into the phone + under Settings → Data and Storage → Proxy. Changes take effect at + once; nothing restarts. +

+
+
+ + +
+
+ +
+ +
+ + + + + + + + + + + + + +
IDLabelSecretStatusActions
Loading...
+
+
+

REALITY Clients (VLESS UUIDs)

@@ -580,6 +616,98 @@

Settings

function el(tag,text){var e=document.createElement(tag);if(text!==undefined)e.textContent=text;return e} +async function loadMtprotoSecrets(){ + var msg=document.getElementById('mtproto-msg'); + var tbody=document.getElementById('mtproto-body'); + try{ + var r=await fetch('/api/mtproto-secrets',{credentials:'same-origin'}); + var data=await r.json(); + if(!data.mtproto_enabled){ + tbody.innerHTML=''; + var row=el('tr'),cell=el('td','MTPROTO_ENABLED is false, so there is no Telegram listener.'); + cell.colSpan=5;cell.style.color='#555'; + row.appendChild(cell);tbody.appendChild(row); + return; + } + tbody.innerHTML=''; + if(!data.secrets||data.secrets.length===0){ + var empty=el('tr'),ecell=el('td','No secrets yet. Add one above.'); + ecell.colSpan=5;ecell.style.color='#555'; + empty.appendChild(ecell);tbody.appendChild(empty); + return; + } + for(var i=0;iSettings poll(); pollHistory(); loadUsers(); +loadMtprotoSecrets(); loadVlessClients(); loadConfig(); setInterval(poll,2000);