diff --git a/README.md b/README.md index 5b61331..8872f42 100644 --- a/README.md +++ b/README.md @@ -371,6 +371,23 @@ 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. +### Billing a client to a user of its own + +By default every REALITY session arrives on the service's shared SOCKS +credentials, so no tier, limit or counter applies to it. The **Meter it** button +on a client creates a SOCKS user for that client alone and routes its sessions +there through an xray rule keyed on the client's email. From then on its traffic +is metered, limited and counted like anyone else's, and the user shows up in the +user list where its tier can be changed like any other. + +The credentials xray needs are **derived**, not stored: a per-install secret +produces them on every render, so only the hash sits in the users table and no +readable password is kept anywhere. + +One cost to know about: each linked client adds an outbound and a routing rule to +the xray config, so a very large number of clients makes that config big. A few +hundred is fine; beyond that, this wants rethinking rather than growing. + `REALITY_BIND` defaults to `0.0.0.0:443`, which is IPv4 only. On an IPv6-only host set it to `[::]:443`. @@ -681,7 +698,7 @@ at `/prometheus` with `basic_auth` configured. | 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 | +| PUT | `/api/vless-clients/:id` | Relabel, enable/disable, or bill a client to a SOCKS user of its own | | 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 | diff --git a/database.go b/database.go index 1178fed..01597b4 100644 --- a/database.go +++ b/database.go @@ -1,7 +1,9 @@ package main import ( + "crypto/hmac" "crypto/rand" + "crypto/sha256" "database/sql" "encoding/hex" "fmt" @@ -132,6 +134,15 @@ func (s *Store) migrate() error { enabled INTEGER NOT NULL DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP )`, + // The SOCKS user a REALITY client's traffic is billed to. Empty means the + // client falls back to the shared credentials, which is how every client + // behaved before this existed. + `CREATE TABLE IF NOT EXISTS vless_links ( + client_id INTEGER PRIMARY KEY, + username TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (client_id) REFERENCES vless_clients(id) ON DELETE CASCADE + )`, // 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. @@ -163,6 +174,92 @@ func (s *Store) migrate() error { return nil } +// ─── REALITY client links ─────────────────────────────────────────────────── + +const dbVlessLinkSecret = "vless_link_secret" + +// EnsureVlessLinkSecret returns this install's link secret, generating it the +// first time it is asked for. +// +// It exists so a REALITY client's proxy password can be put in an xray config +// without storing a readable password anywhere: the value is derived from this +// secret, and only its hash is kept in the users table. +func (s *Store) EnsureVlessLinkSecret() ([]byte, error) { + if saved := s.LoadConfig()[dbVlessLinkSecret]; saved != "" { + if secret, err := hex.DecodeString(saved); err == nil && len(secret) == 32 { + return secret, nil + } + } + + secret := make([]byte, 32) + if _, err := rand.Read(secret); err != nil { + return nil, err + } + if err := s.SaveConfig(dbVlessLinkSecret, hex.EncodeToString(secret)); err != nil { + return nil, err + } + return secret, nil +} + +// VlessLinkCredentials derives the SOCKS username and password for a linked +// REALITY client. Both are a function of this install's link secret and the +// client id, so xray's config can carry them and the database can keep only the +// password's hash. +func VlessLinkCredentials(secret []byte, clientID int64) (username, password string) { + mac := hmac.New(sha256.New, secret) + fmt.Fprintf(mac, "vless:%d", clientID) + return fmt.Sprintf("xr%d", clientID), hex.EncodeToString(mac.Sum(nil)) +} + +// VlessLink says which SOCKS user a REALITY client's traffic belongs to. +type VlessLink struct { + ClientID int64 `json:"client_id"` + Username string `json:"username"` +} + +func (s *Store) LinkVlessClient(clientID int64, username string) error { + s.mu.Lock() + defer s.mu.Unlock() + + _, err := s.db.Exec( + `INSERT INTO vless_links (client_id, username) VALUES (?, ?) + ON CONFLICT(client_id) DO UPDATE SET username=excluded.username`, + clientID, username) + return err +} + +func (s *Store) UnlinkVlessClient(clientID int64) error { + s.mu.Lock() + defer s.mu.Unlock() + + _, err := s.db.Exec("DELETE FROM vless_links WHERE client_id=?", clientID) + return err +} + +// ListVlessLinks is keyed by client id, so the renderer can look a client up +// without scanning. +func (s *Store) ListVlessLinks() (map[int64]string, error) { + s.mu.Lock() + defer s.mu.Unlock() + + rows, err := s.db.Query("SELECT client_id, username FROM vless_links") + if err != nil { + return nil, err + } + defer rows.Close() + + out := map[int64]string{} + for rows.Next() { + var id int64 + var username string + if err := rows.Scan(&id, &username); err != nil { + return nil, err + } + out[id] = username + } + return out, rows.Err() +} + // ─── Config persistence ──────────────────────────────────────────────────── func (s *Store) LoadConfig() map[string]string { @@ -530,7 +627,7 @@ func (s *Store) ListUsers() ([]User, error) { } defer rows.Close() - var users []User + users := []User{} for rows.Next() { var u User var enabled int @@ -643,6 +740,9 @@ type VlessClient struct { Label string `json:"label"` Enabled bool `json:"enabled"` CreatedAt string `json:"created_at"` + // Linked is the SOCKS user this client's traffic is billed to, empty when + // it falls through on the shared credentials. + Linked string `json:"linked,omitempty"` } // IsUUID reports whether s looks like a UUID xray would accept. Deliberately diff --git a/main.go b/main.go index 95788cc..354830d 100644 --- a/main.go +++ b/main.go @@ -1859,6 +1859,14 @@ func (s *ProxyServer) adminHandler() http.Handler { s.realityMu.Lock() enabled := s.reality != nil s.realityMu.Unlock() + if links, lerr := s.store.ListVlessLinks(); lerr == nil && len(links) > 0 { + for i := range clients { + if name, ok := links[clients[i].ID]; ok { + linked := name + clients[i].Linked = linked + } + } + } s.configMu.RLock() pinned := len(s.cfg.RealityClientIDs) > 0 s.configMu.RUnlock() @@ -1960,11 +1968,28 @@ func (s *ProxyServer) adminHandler() http.Handler { var req struct { Label *string `json:"label"` Enabled *bool `json:"enabled"` + // Link bills this client's traffic to a SOCKS user of its own, so + // its tier, limits and accounting apply. False unlinks. + Link *bool `json:"link"` + Tier *string `json:"tier"` } if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) return } + if req.Link != nil { + if err := s.linkVlessClient(id, *req.Link, req.Tier); err != nil { + http.Error(w, "link failed: "+err.Error(), http.StatusBadRequest) + return + } + if *req.Link { + if links, lerr := s.store.ListVlessLinks(); lerr == nil { + if name, ok := links[id]; ok { + w.Header().Set("X-Linked-User", name) + } + } + } + } if err := s.store.UpdateVlessClient(id, req.Label, req.Enabled); err != nil { http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError) return diff --git a/reality.go b/reality.go index ff590f0..72b4384 100644 --- a/reality.go +++ b/reality.go @@ -69,9 +69,30 @@ type realityKeys struct { PublicKey string ShortID string ClientIDs []string + // Links are the clients that are billed to a SOCKS user, keyed by UUID. + // Without one, a client's traffic lands on the shared credentials and no + // tier applies to it. + Links map[string]realityLinkedClient ServerName string } +// realityLinkedClient is one client with a SOCKS user behind it. The password is +// derived rather than stored, so it can be put in an xray config without keeping +// a readable one anywhere. +type realityLinkedClient struct { + ID int64 + Username string + Password string +} + +// vlessClientEmail is the name xray knows a client by, and what a routing rule +// matches on. It has to stay stable across re-renders: a client whose email +// moved would lose its route without anything looking wrong. +func vlessClientEmail(id int64) string { return fmt.Sprintf("vless-%d", id) } + +// vlessOutboundTag names the per-client socks outbound. +func vlessOutboundTag(id int64) string { return fmt.Sprintf("proxy-%d", id) } + // ─── Config rendering ─────────────────────────────────────────────────────── // // Typed structs rather than string templates: a malformed field then fails to @@ -93,6 +114,7 @@ type realityRoutingConfig struct { type realityRoutingRule struct { Type string `json:"type"` InboundTag []string `json:"inboundTag"` + User []string `json:"user,omitempty"` OutboundTag string `json:"outboundTag"` } @@ -216,9 +238,35 @@ func renderRealityServerConfig(cfg Config, k realityKeys) ([]byte, error) { out := realityServerConfig{} out.Log.LogLevel = "warning" + // A client linked to a SOCKS user gets an email, and xray routes its + // sessions by that email to an outbound carrying that user's credentials. + // An unlinked client falls through to the shared outbound, exactly as before. clients := make([]realityClient, 0, len(k.ClientIDs)) + perUserOutbounds := make([]realityOutbound, 0, len(k.Links)) + rules := make([]realityRoutingRule, 0, len(k.Links)+1) for _, id := range k.ClientIDs { - clients = append(clients, realityClient{ID: id}) + entry := realityClient{ID: id} + link, linked := k.Links[id] + if linked { + entry.Email = vlessClientEmail(link.ID) + perUserOutbounds = append(perUserOutbounds, realityOutbound{ + Tag: vlessOutboundTag(link.ID), + Protocol: "socks", + Settings: &realityOutboundSettings{ + Servers: []realitySocksServer{{ + Address: "127.0.0.1", + Port: cfg.ProxyPort, + Users: []realityUser{{User: link.Username, Pass: link.Password}}, + }}, + }, + }) + rules = append(rules, realityRoutingRule{ + Type: "field", + User: []string{entry.Email}, + OutboundTag: vlessOutboundTag(link.ID), + }) + } + clients = append(clients, entry) } inbound := realityInbound{ @@ -262,17 +310,17 @@ func renderRealityServerConfig(cfg Config, k realityKeys) ([]byte, error) { socksOut.Settings.Servers[0].Users = []realityUser{{User: cfg.Username, Pass: cfg.Password}} } - out.Outbounds = []realityOutbound{ - socksOut, - {Tag: realityDirectTag, Protocol: "freedom"}, - } - out.Routing = realityRoutingConfig{ - Rules: []realityRoutingRule{{ - Type: "field", - InboundTag: []string{realityInboundTag}, - OutboundTag: realitySocksTag, - }}, - } + out.Outbounds = append([]realityOutbound{socksOut}, perUserOutbounds...) + out.Outbounds = append(out.Outbounds, realityOutbound{Tag: realityDirectTag, Protocol: "freedom"}) + + // The shared outbound stays the fallback, so a client that is not linked + // keeps working rather than being refused. + rules = append(rules, realityRoutingRule{ + Type: "field", + InboundTag: []string{realityInboundTag}, + OutboundTag: realitySocksTag, + }) + out.Routing = realityRoutingConfig{Rules: rules} return json.MarshalIndent(out, "", " ") } @@ -489,6 +537,8 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l } } + keys.Links = loadRealityLinks(store, logger) + if store != nil { if generatedKey { saveRealitySetting(store, logger, dbRealityPrivateKey, keys.PrivateKey) @@ -501,6 +551,49 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l return keys, nil } +// loadRealityLinks reads which clients are billed to a SOCKS user, and derives +// the password xray needs to authenticate as them. +func loadRealityLinks(store *Store, logger *slog.Logger) map[string]realityLinkedClient { + out := map[string]realityLinkedClient{} + if store == nil { + return out + } + links, err := store.ListVlessLinks() + if err != nil { + logger.Warn("could not read the REALITY client links", "error", err) + return out + } + secret, err := store.EnsureVlessLinkSecret() + if err != nil { + logger.Warn("could not read the link secret", "error", err) + return out + } + + clients, err := store.ListVlessClients() + if err != nil { + logger.Warn("could not read the managed VLESS clients", "error", err) + return out + } + byID := map[int64]VlessClient{} + for _, c := range clients { + byID[c.ID] = c + } + + for clientID, username := range links { + client, ok := byID[clientID] + if !ok || !client.Enabled { + continue + } + _, password := VlessLinkCredentials(secret, clientID) + out[client.UUID] = realityLinkedClient{ + ID: clientID, + Username: username, + Password: password, + } + } + return out +} + // 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. @@ -1010,6 +1103,7 @@ func (s *ProxyServer) applyVlessClients() error { } s.realityMu.Lock() keys.ClientIDs, err = s.store.EnabledVlessClientUUIDs() + keys.Links = loadRealityLinks(s.store, s.logger) s.realityMu.Unlock() if err != nil { return err @@ -1119,3 +1213,60 @@ func runRealityClient(args []string) error { cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr return cmd.Run() } + +// linkVlessClient bills a REALITY client's traffic to a SOCKS user of its own, +// or stops doing so. +// +// The username and password xray needs are derived from this install's link +// secret rather than stored: only the hash goes into the users table, the +// plaintext is recomputed on every render, and nothing readable is ever kept. +func (s *ProxyServer) linkVlessClient(clientID int64, link bool, tier *string) error { + if !link { + if err := s.store.UnlinkVlessClient(clientID); err != nil { + return err + } + } else { + secret, err := s.store.EnsureVlessLinkSecret() + if err != nil { + return err + } + derived, password := VlessLinkCredentials(secret, clientID) + + // An existing user keeps its own tier; a new one is created at the tier + // asked for, defaulting to the shared credentials' behaviour. + existing, err := s.store.GetUser(derived) + switch { + case err == nil && existing != nil: + // Already created on a previous link. + case s.store != nil && tier != nil && *tier != "": + if _, err := s.store.CreateUser(derived, password, *tier); err != nil { + return err + } + default: + if _, err := s.store.CreateUser(derived, password, defaultLinkedUserTier); err != nil { + return err + } + } + if err := s.store.LinkVlessClient(clientID, derived); err != nil { + return err + } + s.logger.Info("reality client linked to a socks user", + "client", clientID, "username", derived, "tier", tierName(tier)) + } + + // Put it in front of xray straight away, the same as any other client change. + return s.applyVlessClients() +} + +// defaultLinkedUserTier is what a linked client gets when no tier is named: the +// service's own credentials, so linking does not quietly change what someone +// gets until an operator says so. +const defaultLinkedUserTier = "unlimited" + +// tierName names the tier for a log line, without dereferencing a nil pointer. +func tierName(tier *string) string { + if tier == nil || *tier == "" { + return defaultLinkedUserTier + } + return *tier +} diff --git a/reality_test.go b/reality_test.go index a77dce5..da6b8ae 100644 --- a/reality_test.go +++ b/reality_test.go @@ -579,3 +579,174 @@ func TestRealityEndToEnd(t *testing.T) { t.Error("the REALITY session never reached the SOCKS5 pipeline") } } + +// A linked REALITY client must have its traffic billed to the SOCKS user it was +// linked to. Without this, xray forwards everything through the shared +// credentials and every REALITY session is unmetered no matter what the account +// is on. +func TestRealityLinkedClientIsBilledToItsUser(t *testing.T) { + bin := requireXray(t) + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "linked-ok") + })) + defer origin.Close() + + proxyCfg := DefaultConfig() + proxyCfg.AuthEnabled = true + proxyCfg.AdminEnabled = false + proxyCfg.SecurityHeadersEnabled = false + proxyCfg.RateLimitEnabled = false + proxyCfg.Username = "shared" + proxyCfg.Password = "sharedpass" + proxyCfg.ProxyPort = freePort(t) + + server := NewProxyServer(proxyCfg) + 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, "") + } + }() + server.store = store + + cfg := proxyCfg + cfg.RealityXrayBin = bin + cfg.RealityEnabled = true + cfg.RealityBind = fmt.Sprintf("127.0.0.1:%d", freePort(t)) + cfg.RealityPublicHost = "127.0.0.1" + + client, err := store.CreateVlessClient("0cd94710-7290-40da-857d-5f5a7670cd62", "linked phone") + if err != nil { + t.Fatalf("create vless client: %v", err) + } + + keys, err := resolveRealityKeys(cfg, nil, store, log) + if err != nil { + t.Fatalf("resolve keys: %v", err) + } + runner, err := startReality(cfg, keys, log) + if err != nil { + t.Fatalf("start reality: %v", err) + } + defer runner.Stop() + server.reality, server.realityKeys = runner, keys + + // Link it to a user of its own, at a tier that is easy to spot in the data. + free := "free" + if err := server.linkVlessClient(client.ID, true, &free); err != nil { + t.Fatalf("link: %v", err) + } + + linked, err := store.ListVlessLinks() + if err != nil || linked[client.ID] == "" { + t.Fatalf("the link was not recorded: %v, %v", linked, err) + } + username := linked[client.ID] + + // The linked user must exist as an ordinary SOCKS user, on the tier asked + // for, with a password only this install can reproduce. + user, err := store.GetUser(username) + if err != nil { + t.Fatalf("the linked user does not exist: %v", err) + } + if user.Tier != free { + t.Errorf("linked user tier = %q, want %q", user.Tier, free) + } + secret, err := store.EnsureVlessLinkSecret() + if err != nil { + t.Fatalf("link secret: %v", err) + } + _, password := VlessLinkCredentials(secret, client.ID) + if ok, _ := VerifyPassword(user.PasswordHash, password); !ok { + t.Error("the derived password does not verify against the stored hash") + } + + // And the rendered config must route that client's email to its own outbound. + server.realityMu.Lock() + reloaded := server.realityKeys + server.realityMu.Unlock() + rendered, err := renderRealityServerConfig(cfg, reloaded) + if err != nil { + t.Fatalf("render: %v", err) + } + var parsed struct { + Inbounds []struct { + Settings struct { + Clients []struct{ ID, Email string } + } `json:"settings"` + } `json:"inbounds"` + Outbounds []struct{ Tag, Protocol string } `json:"outbounds"` + Routing struct { + Rules []struct { + User []string `json:"user"` + OutboundTag string `json:"outboundTag"` + } `json:"rules"` + } `json:"routing"` + } + if err := json.Unmarshal(rendered, &parsed); err != nil { + t.Fatalf("unmarshal config: %v", err) + } + + email := vlessClientEmail(client.ID) + if got := parsed.Inbounds[0].Settings.Clients[0].Email; got != email { + t.Errorf("client email = %q, want %q", got, email) + } + tag := vlessOutboundTag(client.ID) + found := false + for _, o := range parsed.Outbounds { + if o.Tag == tag && o.Protocol == "socks" { + found = true + } + } + if !found { + t.Errorf("no per-user socks outbound %q in the config", tag) + } + routed := false + for _, r := range parsed.Routing.Rules { + for _, u := range r.User { + if u == email && r.OutboundTag == tag { + routed = true + } + } + } + if !routed { + t.Errorf("no rule routes %q to %q", email, tag) + } + + // The config xray is actually running must accept all of it. + if _, err := runXray(bin, "run", "-c", mustWriteConfig(t, rendered), "--test"); err != nil { + t.Errorf("xray rejected the linked-client config: %v", err) + } + + // Unlinking puts it back on the shared credentials. + if err := server.linkVlessClient(client.ID, false, nil); err != nil { + t.Fatalf("unlink: %v", err) + } + after, err := store.ListVlessLinks() + if err != nil { + t.Fatalf("links after unlink: %v", err) + } + if _, still := after[client.ID]; still { + t.Error("the client is still linked after being unlinked") + } +} + +func mustWriteConfig(t *testing.T, data []byte) string { + t.Helper() + path := filepath.Join(t.TempDir(), "xray.json") + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatalf("write config: %v", err) + } + return path +} diff --git a/web/index.html b/web/index.html index f2ac506..8f16d9c 100644 --- a/web/index.html +++ b/web/index.html @@ -797,13 +797,19 @@