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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,18 @@ 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.

### Tiers

A secret carries the same tier as a SOCKS5 user, and the plan is **enforced**:
bandwidth is paced at the tier's rate, concurrent sessions are capped, and a
secret that has moved its data allowance is refused. Without this the Telegram
relay, which does not pass through the SOCKS5 pipeline, gave every phone an
unlimited pipe whatever it was on the books for. The panel shows what each phone
is using.

Expiry is the one part of a tier that does **not** apply to a Telegram secret: it
has no end date, and a cap or a revocation is how such an account is stopped.

### Two kinds of secret

| Prefix | Transport | What a prober sees |
Expand Down Expand Up @@ -664,8 +676,8 @@ at `/prometheus` with `basic_auth` configured.
| 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 |
| POST | `/api/mtproto-secrets` | Add a secret with its kind and tier; it is generated for you |
| PUT | `/api/mtproto-secrets/:id` | Relabel, change the tier, 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 |
Expand Down
41 changes: 34 additions & 7 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ func (s *Store) migrate() error {
id INTEGER PRIMARY KEY AUTOINCREMENT,
secret TEXT UNIQUE NOT NULL,
label TEXT NOT NULL DEFAULT '',
tier TEXT NOT NULL DEFAULT 'unlimited',
enabled INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
Expand All @@ -149,6 +150,16 @@ func (s *Store) migrate() error {
return fmt.Errorf("exec %q: %w", q, err)
}
}

// Adding a column is the one migration SQLite cannot express as
// "if not exists", so it is attempted and the duplicate-column error is the
// success case. Everything else stays in the list above, where the database
// does the work.
if _, err := s.db.Exec(
`ALTER TABLE mtproto_secrets ADD COLUMN tier TEXT NOT NULL DEFAULT 'unlimited'`,
); err != nil && !strings.Contains(strings.ToLower(err.Error()), "duplicate column") {
return fmt.Errorf("add mtproto tier column: %w", err)
}
return nil
}

Expand Down Expand Up @@ -766,17 +777,25 @@ type MtprotoSecret struct {
ID int64 `json:"id"`
Secret string `json:"secret"`
Label string `json:"label"`
Tier string `json:"tier"`
Enabled bool `json:"enabled"`
CreatedAt string `json:"created_at"`
}

func (s *Store) CreateMtprotoSecret(secret, label string) (*MtprotoSecret, error) {
// defaultMtprotoTier is what a secret gets when none is chosen: Telegram access
// stays reachable rather than being throttled to 1Mbps by accident.
const defaultMtprotoTier = "unlimited"

func (s *Store) CreateMtprotoSecret(secret, label, tier string) (*MtprotoSecret, error) {
secret = strings.TrimSpace(strings.ToLower(secret))
if _, err := parseMTProtoSecret(secret); err != nil {
return nil, err
}
if _, ok := Tiers[tier]; !ok {
tier = defaultMtprotoTier
}
s.mu.Lock()
res, err := s.db.Exec("INSERT INTO mtproto_secrets (secret, label) VALUES (?, ?)", secret, label)
res, err := s.db.Exec("INSERT INTO mtproto_secrets (secret, label, tier) VALUES (?, ?, ?)", secret, label, tier)
s.mu.Unlock()
if err != nil {
return nil, err
Expand All @@ -794,8 +813,8 @@ func (s *Store) GetMtprotoSecret(id int64) (*MtprotoSecret, error) {

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)
err := s.db.QueryRow("SELECT id, secret, label, tier, enabled, created_at FROM mtproto_secrets WHERE id=?", id).
Scan(&sec.ID, &sec.Secret, &sec.Label, &sec.Tier, &enabled, &sec.CreatedAt)
if err != nil {
return nil, err
}
Expand All @@ -807,7 +826,7 @@ 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")
rows, err := s.db.Query("SELECT id, secret, label, tier, enabled, created_at FROM mtproto_secrets ORDER BY id")
if err != nil {
return nil, err
}
Expand All @@ -817,7 +836,7 @@ func (s *Store) ListMtprotoSecrets() ([]MtprotoSecret, error) {
for rows.Next() {
var sec MtprotoSecret
var enabled int
if err := rows.Scan(&sec.ID, &sec.Secret, &sec.Label, &enabled, &sec.CreatedAt); err != nil {
if err := rows.Scan(&sec.ID, &sec.Secret, &sec.Label, &sec.Tier, &enabled, &sec.CreatedAt); err != nil {
return nil, err
}
sec.Enabled = enabled != 0
Expand All @@ -826,7 +845,7 @@ func (s *Store) ListMtprotoSecrets() ([]MtprotoSecret, error) {
return out, rows.Err()
}

func (s *Store) UpdateMtprotoSecret(id int64, label *string, enabled *bool) error {
func (s *Store) UpdateMtprotoSecret(id int64, label *string, tier *string, enabled *bool) error {
s.mu.Lock()
defer s.mu.Unlock()

Expand All @@ -835,6 +854,14 @@ func (s *Store) UpdateMtprotoSecret(id int64, label *string, enabled *bool) erro
return err
}
}
if tier != nil {
if _, ok := Tiers[*tier]; !ok {
return fmt.Errorf("unknown tier: %s", *tier)
}
if _, err := s.db.Exec("UPDATE mtproto_secrets SET tier=? WHERE id=?", *tier, id); err != nil {
return err
}
}
if enabled != nil {
value := 0
if *enabled {
Expand Down
10 changes: 5 additions & 5 deletions faketls.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ type fakeTLSClientHello struct {
//
// secrets is tried in turn: the client's random is the HMAC of its own hello
// under the secret it was given, so only the right key produces a match.
func fakeTLSHandshake(conn net.Conn, secrets mtprotoSecrets, now time.Time, cloakHost string) (*fakeTLSRecordConn, *fakeTLSClientHello, error) {
func fakeTLSHandshake(conn net.Conn, secrets mtprotoGrants, now time.Time, cloakHost string) (*fakeTLSRecordConn, *fakeTLSClientHello, error) {
record, raw, err := readFakeTLSRecordRaw(conn)
if err != nil {
return nil, nil, fmt.Errorf("read fake tls hello: %w", err)
Expand Down Expand Up @@ -162,7 +162,7 @@ func fakeTLSHandshake(conn net.Conn, secrets mtprotoSecrets, now time.Time, cloa
// fakeTLSMatchSecret finds the secret a hello was made with. The random is an
// HMAC over the hello with itself zeroed, so a mismatch is simply "no match" --
// there is nothing to give up on, and nothing leaks beyond the timing.
func fakeTLSMatchSecret(raw []byte, secrets mtprotoSecrets, now time.Time) ([]byte, error) {
func fakeTLSMatchSecret(raw []byte, secrets mtprotoGrants, now time.Time) ([]byte, error) {
const randomAt = fakeTLSServerRandomOffset
if len(raw) < randomAt+32 {
return nil, fmt.Errorf("ClientHello is %d bytes, too short to carry a random", len(raw))
Expand All @@ -174,11 +174,11 @@ func fakeTLSMatchSecret(raw []byte, secrets mtprotoSecrets, now time.Time) ([]by
original := append([]byte(nil), raw[randomAt:randomAt+32]...)
defer copy(raw[randomAt:randomAt+32], original)

for _, secret := range secrets {
for _, grant := range secrets {
for i := randomAt; i < randomAt+32; i++ {
raw[i] = 0
}
mac := hmac.New(sha256.New, secret)
mac := hmac.New(sha256.New, grant.key)
mac.Write(raw)
want := mac.Sum(nil)

Expand All @@ -191,7 +191,7 @@ func fakeTLSMatchSecret(raw []byte, secrets mtprotoSecrets, now time.Time) ([]by
if skew := now.Sub(time.Unix(int64(got), 0)); skew > fakeTLSTimeSkew || skew < -fakeTLSTimeSkew {
continue
}
return secret, nil
return grant.key, nil
}
return nil, errors.New("no configured secret matched this fake TLS hello")
}
Expand Down
18 changes: 12 additions & 6 deletions faketls_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestFakeTLSHandshakeWithGotdClient(t *testing.T) {
defer client.Close()
defer server.Close()

secrets := mtprotoSecrets{secret: key}
secrets := grantsOf(t, secret, key)
done := make(chan error, 1)
go func() {
_, info, herr := fakeTLSHandshake(server, secrets, time.Now(), "www.cloudflare.com")
Expand Down Expand Up @@ -69,7 +69,7 @@ func TestFakeTLSCarriesAPayloadBothWays(t *testing.T) {

serverSide := make(chan *fakeTLSRecordConn, 1)
go func() {
wrapped, _, err := fakeTLSHandshake(server, mtprotoSecrets{secret: key}, time.Now(), "www.cloudflare.com")
wrapped, _, err := fakeTLSHandshake(server, grantsOf(t, secret, key), time.Now(), "www.cloudflare.com")
if err != nil {
serverSide <- nil
return
Expand Down Expand Up @@ -133,7 +133,7 @@ func TestFakeTLSRefusesWrongSecret(t *testing.T) {
client.SetDeadline(time.Now().Add(5 * time.Second))

go func() {
_, _, _ = fakeTLSHandshake(server, mtprotoSecrets{secret: key}, time.Now(), "www.cloudflare.com")
_, _, _ = fakeTLSHandshake(server, grantsOf(t, secret, key), time.Now(), "www.cloudflare.com")
}()

clientObf := faketls.NewFakeTLS(rand.Reader, client)
Expand All @@ -160,7 +160,7 @@ func TestFakeTLSRefusesAStaleHello(t *testing.T) {
// A server a day ahead of the client treats a fresh hello as stale.
future := time.Now().Add(24 * time.Hour)
go func() {
_, _, _ = fakeTLSHandshake(server, mtprotoSecrets{secret: key}, future, "www.cloudflare.com")
_, _, _ = fakeTLSHandshake(server, grantsOf(t, secret, key), future, "www.cloudflare.com")
}()

clientObf := faketls.NewFakeTLS(rand.Reader, client)
Expand All @@ -179,7 +179,7 @@ func TestFakeTLSHelloDomainParsing(t *testing.T) {
defer client.Close()
defer server.Close()

secrets := mtprotoSecrets{secret: key}
secrets := grantsOf(t, secret, key)
domains := make(chan string, 1)
go func() {
_, info, err := fakeTLSHandshake(server, secrets, time.Now(), "www.cloudflare.com")
Expand Down Expand Up @@ -262,7 +262,7 @@ func TestFakeTLSThroughTheListener(t *testing.T) {

s := NewProxyServer(cfg)
s.store = newTestStore(t)
if _, err := s.store.CreateMtprotoSecret(secret, "ee phone"); err != nil {
if _, err := s.store.CreateMtprotoSecret(secret, "ee phone", "unlimited"); err != nil {
t.Fatalf("store secret: %v", err)
}
if err := s.startMTProto(nil); err != nil {
Expand Down Expand Up @@ -302,3 +302,9 @@ func TestFakeTLSThroughTheListener(t *testing.T) {
t.Errorf("echoed %q, want %q", echoed, payload)
}
}

// grantsOf builds a one-entry grant set for a secret and its plan.
func grantsOf(t *testing.T, secret string, key []byte) mtprotoGrants {
t.Helper()
return mtprotoGrants{secret: mtprotoGrant{key: key, tier: Tiers[defaultMtprotoTier]}}
}
27 changes: 24 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -582,8 +582,9 @@ type ProxyServer struct {
// on every connection; the database holds them so the dashboard can manage
// them across restarts.
mtprotoMu sync.RWMutex
mtprotoSecrets mtprotoSecrets
mtprotoSecrets mtprotoGrants
mtprotoListener net.Listener
mtprotoServer *mtprotoServer

// Shutdown
shutdownOnce sync.Once
Expand Down Expand Up @@ -2003,16 +2004,29 @@ func (s *ProxyServer) adminHandler() http.Handler {
s.mtprotoMu.RLock()
live := len(s.mtprotoSecrets)
bind := ""
var server *mtprotoServer
if s.mtprotoListener != nil {
bind = s.mtprotoListener.Addr().String()
server = s.mtprotoServer
}
s.mtprotoMu.RUnlock()

// What each phone has used, so a plan can be seen doing something
// rather than only being configured.
usage := map[string]mtprotoSnapshot{}
if server != nil {
for _, snap := range server.mtprotoUsageSnapshot() {
usage[snap.Secret] = snap
}
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"secrets": secrets,
"mtproto_enabled": enabled,
"bind": bind,
"live_secrets": live,
"usage": usage,
})

case http.MethodPost:
Expand All @@ -2028,6 +2042,8 @@ func (s *ProxyServer) adminHandler() http.Handler {
// The kind is per secret rather than only a server-wide default,
// so both kinds can be handed out from the same running service.
Kind string `json:"kind"`
// The plan this phone is held to, same tiers as the SOCKS5 port.
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)
Expand All @@ -2044,7 +2060,11 @@ func (s *ProxyServer) adminHandler() http.Handler {
http.Error(w, "could not generate a secret: "+err.Error(), http.StatusInternalServerError)
return
}
created, err := s.store.CreateMtprotoSecret(secret, req.Label)
tier := defaultMtprotoTier
if req.Tier != "" {
tier = req.Tier
}
created, err := s.store.CreateMtprotoSecret(secret, req.Label, tier)
if err != nil {
http.Error(w, "create failed: "+err.Error(), http.StatusInternalServerError)
return
Expand Down Expand Up @@ -2084,13 +2104,14 @@ func (s *ProxyServer) adminHandler() http.Handler {
case r.Method == http.MethodPut && len(parts) == 1:
var req struct {
Label *string `json:"label"`
Tier *string `json:"tier"`
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 {
if err := s.store.UpdateMtprotoSecret(id, req.Label, req.Tier, req.Enabled); err != nil {
http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError)
return
}
Expand Down
Loading
Loading