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..eee6b93 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,6 +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 and +MTProto secrets 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 live in the database; restoring an older or different one invalidates every client you have imported. @@ -611,6 +639,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);