From 21836cb84fa15152bfc8ce9a44cbc0bec4b9751d Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sat, 17 Oct 2026 20:08:06 +0500 Subject: [PATCH 1/2] WIP: fake TLS handshake, server side Parking the in-progress work off main so the release tag can point at the tested tree. --- faketls.go | 438 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 438 insertions(+) create mode 100644 faketls.go diff --git a/faketls.go b/faketls.go new file mode 100644 index 0000000..5c39b6c --- /dev/null +++ b/faketls.go @@ -0,0 +1,438 @@ +package main + +import ( + "bytes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "crypto/x509/pkix" + "encoding/binary" + "errors" + "fmt" + "io" + "math/big" + "net" + "sync" + "time" +) + +// ─── MTProto fake TLS ─────────────────────────────────────────────────────── +// +// obfuscated2 traffic looks like random bytes, which is what every Telegram +// proxy looks like. Fake TLS wraps the same stream in TLS records so that +// someone scanning the port sees a TLS handshake instead -- indistinguishable +// from a web request, at the cost of a handshake that never went anywhere. +// +// The scheme is Telegram's, not ours, and it is verified here against an +// independent client: gotd/td's mtproxy/faketls package, which implements the +// other side of exactly this exchange. +// +// How it fits together: +// - The client opens with a ClientHello whose 32-byte random is an HMAC of the +// hello under the shared secret, with the last four bytes carrying a +// timestamp. That is the whole authentication: a prober with no secret gets +// 32 bytes of nonsense back. +// - The server answers with a ServerHello, a ChangeCipherSpec and a +// certificate record. Its own random must satisfy a second HMAC, this time +// over the client's random plus the whole reply, so a client can tell a +// real proxy from a mirror that just replays bytes. +// - After that the MTProto stream runs inside TLS application records. + +const ( + // Record types, from the TLS record layer. + fakeTLSRecordChangeCipherSpec = 0x14 + fakeTLSRecordAlert = 0x15 + fakeTLSRecordHandshake = 0x16 + fakeTLSRecordApplication = 0x17 + + // Handshake message types. + fakeTLSClientHelloMsg = 0x01 + fakeTLSServerHelloMsg = 0x02 + + // A ClientHello is at most 16KB plus overhead; anything larger is not one. + fakeTLSMaxRecord = 16384 + 24 + + // The offsets below are fixed by the layout: a record header is 5 bytes, a + // handshake header is 4, and the random follows 2 bytes of protocol version. + fakeTLSServerRandomOffset = 11 + + // fakeTLSTimeSkew is how far the client's clock is allowed to be off before + // the hello is treated as a replay rather than a live client. + fakeTLSTimeSkew = 8 * time.Hour +) + +// fakeTLSRecord is one TLS record. +type fakeTLSRecord struct { + Type byte + Data []byte +} + +func writeFakeTLSRecord(w io.Writer, recType byte, data []byte) error { + header := [5]byte{recType, fakeTLSVersion3[0], fakeTLSVersion3[1], 0, 0} + binary.BigEndian.PutUint16(header[3:], uint16(len(data))) + if _, err := w.Write(header[:]); err != nil { + return err + } + _, err := w.Write(data) + return err +} + +func readFakeTLSRecord(r io.Reader) (fakeTLSRecord, error) { + var header [5]byte + if _, err := io.ReadFull(r, header[:]); err != nil { + return fakeTLSRecord{}, err + } + length := binary.BigEndian.Uint16(header[3:]) + if length > fakeTLSMaxRecord { + return fakeTLSRecord{}, fmt.Errorf("fake tls record is %d bytes, too big", length) + } + data := make([]byte, length) + if _, err := io.ReadFull(r, data); err != nil { + return fakeTLSRecord{}, err + } + return fakeTLSRecord{Type: header[0], Data: data}, nil +} + +// fakeTLSClientHello is what the handshake yields: the shared secret that +// matched, and the domain the client claimed to be visiting. +type fakeTLSClientHello struct { + Secret []byte + Domain string + Random [32]byte +} + +// fakeTLSHandshake performs the server half and returns the connection wrapped +// in the record layer, ready to carry the obfuscated2 stream. +// +// 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) (*fakeTLSRecordConn, *fakeTLSClientHello, error) { + record, err := readFakeTLSRecord(conn) + if err != nil { + return nil, nil, fmt.Errorf("read fake tls hello: %w", err) + } + if record.Type != fakeTLSRecordHandshake { + return nil, nil, fmt.Errorf("expected a handshake record, got type %#x", record.Type) + } + if len(record.Data) < 4 || record.Data[0] != fakeTLSClientHelloMsg { + return nil, nil, fmt.Errorf("expected a ClientHello, got message type %#x", record.Data[0]) + } + + // The HMAC covers the record exactly as it arrived, so the bytes are kept + // intact and only a copy is modified for the comparison. + hello := record.Data[4:] + + domain, err := fakeTLSHelloDomain(hello) + if err != nil { + return nil, nil, err + } + + matched, err := fakeTLSMatchSecret(hello, secrets, now) + if err != nil { + return nil, nil, err + } + + info := &fakeTLSClientHello{ + Secret: matched, + Domain: domain, + } + copy(info.Random[:], hello[2:34]) + + if err := writeFakeTLSServerResponse(conn, info, matched); err != nil { + return nil, nil, fmt.Errorf("write fake tls response: %w", err) + } + return newFakeTLSRecordConn(conn), info, nil +} + +// 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(hello []byte, secrets mtprotoSecrets, now time.Time) ([]byte, error) { + if len(hello) < 34 { + return nil, fmt.Errorf("ClientHello is %d bytes, too short to carry a random", len(hello)) + } + var presented [32]byte + copy(presented[:], hello[2:34]) + + // Zero the random in place for the HMAC, then put it back. + original := append([]byte(nil), hello[2:34]...) + defer copy(hello[2:34], original) + + for _, secret := range secrets { + for i := 2; i < 34; i++ { + hello[i] = 0 + } + mac := hmac.New(sha256.New, secret) + mac.Write(hello) + want := mac.Sum(nil) + + if !hmac.Equal(want[:28], presented[:28]) { + continue + } + // The last four bytes carry the client's clock, so a hello replayed + // hours later is refused rather than served. + got := binary.LittleEndian.Uint32(presented[28:32]) ^ binary.LittleEndian.Uint32(want[28:32]) + if skew := now.Sub(time.Unix(int64(got), 0)); skew > fakeTLSTimeSkew || skew < -fakeTLSTimeSkew { + continue + } + return secret, nil + } + return nil, errors.New("no configured secret matched this fake TLS hello") +} + +// fakeTLSHelloDomain pulls the server name out of the ClientHello's extensions. +// It is what the client claims to be visiting, which is also what a prober would +// believe it was reaching, so the reply has to look like it belongs to it. +func fakeTLSHelloDomain(hello []byte) (string, error) { + pos := 2 + 32 // client version and random + + if pos >= len(hello) { + return "", errors.New("ClientHello ended before the session id") + } + sessionLen := int(hello[pos]) + pos += 1 + sessionLen + + if pos+2 > len(hello) { + return "", errors.New("ClientHello ended before the cipher suites") + } + suitesLen := int(binary.BigEndian.Uint16(hello[pos:])) + pos += 2 + suitesLen + + if pos >= len(hello) { + return "", errors.New("ClientHello ended before the compression methods") + } + compressionLen := int(hello[pos]) + pos += 1 + compressionLen + + if pos+2 > len(hello) { + // No extensions at all: the client will not care, and neither does a + // prober reading a site that speaks no extensions. + return "", nil + } + extensionsLen := int(binary.BigEndian.Uint16(hello[pos:])) + pos += 2 + end := pos + extensionsLen + if end > len(hello) { + return "", errors.New("ClientHello extensions overrun the message") + } + + for pos+4 <= end { + extType := binary.BigEndian.Uint16(hello[pos:]) + extLen := int(binary.BigEndian.Uint16(hello[pos+2:])) + body := pos + 4 + if body+extLen > end { + return "", errors.New("ClientHello extension overruns the message") + } + // 0x0000 is server_name. + if extType == 0x0000 && extLen > 5 { + nameLen := int(binary.BigEndian.Uint16(hello[body+3:])) + if 5+nameLen <= extLen { + return string(hello[body+5 : body+5+nameLen]), nil + } + } + pos = body + extLen + } + return "", nil +} + +// writeFakeTLSServerResponse sends the three records a client expects: the +// ServerHello, the ChangeCipherSpec, and a certificate record carrying the +// domain the client asked for. +func writeFakeTLSServerResponse(w io.Writer, info *fakeTLSClientHello, secret []byte) error { + records := buildFakeTLSResponse(info, secret) + + // The client's random goes into the digest so that a mirror replaying + // recorded bytes cannot pass as the real thing. + var digestInput bytes.Buffer + digestInput.Write(info.Random[:]) + digestInput.Write(records) + + // The server's random is at a fixed offset; it is zero while the HMAC is + // taken over the rest of the reply. + mac := hmac.New(sha256.New, secret) + mac.Write(digestInput.Bytes()) + sum := mac.Sum(nil) + copy(records[fakeTLSServerRandomOffset:fakeTLSServerRandomOffset+32], sum) + + _, err := w.Write(records) + return err +} + +// buildFakeTLSResponse assembles the reply records with the server's random +// left as zeros for the caller to fill in. +func buildFakeTLSResponse(info *fakeTLSClientHello, secret []byte) []byte { + domain := info.Domain + if domain == "" { + domain = "example.com" + } + + var body bytes.Buffer + // ServerHello body: version, random (zeros here), session id, cipher + // suite, compression, and a certificate extension naming the domain. + body.Write(fakeTLSVersion3[:]) + body.Write(make([]byte, 32)) + body.WriteByte(32) // session id length + body.Write(info.Random[:]) // session id, echoing the client's + body.Write([]byte{0xc0, 0x2f}) // cipher suite + body.WriteByte(0x00) // compression: none + + var extensions bytes.Buffer + // A certificate extension, carrying the domain the client asked for. The + // client does not validate the chain in this mode, but a prober reading the + // bytes expects to find a name in here. + cert := fakeTLSCertificateExtension(domain) + extensions.Write([]byte{0x00, 0x00}) // extension type: certificate + extensions.Write([]byte{byte(len(cert) >> 8), byte(len(cert))}) // length + extensions.Write(cert) + + body.Write([]byte{byte(len(extensions.Bytes()) >> 8), byte(len(extensions.Bytes()))}) + body.Write(extensions.Bytes()) + + var handshake bytes.Buffer + handshake.WriteByte(fakeTLSServerHelloMsg) + handshake.Write([]byte{byte(len(body.Bytes()) >> 16), byte(len(body.Bytes()) >> 8), byte(len(body.Bytes()))}) + handshake.Write(body.Bytes()) + + var records bytes.Buffer + writeFakeTLSRecord(&records, fakeTLSRecordHandshake, handshake.Bytes()) + // ChangeCipherSpec, then a certificate record. Both are part of what a real + // handshake looks like from the outside. + writeFakeTLSRecord(&records, fakeTLSRecordChangeCipherSpec, []byte{0x01}) + writeFakeTLSRecord(&records, fakeTLSRecordApplication, fakeTLSCertificate(domain)) + + return records.Bytes() +} + +// fakeTLSCertificateExtension is the body of the extension that makes the reply +// name the domain the client asked for. +func fakeTLSCertificateExtension(domain string) []byte { + cert := fakeTLSCertificate(domain) + var ext bytes.Buffer + // Certificate chain length, certificate length, then the DER. + ext.Write([]byte{byte(len(cert) >> 16), byte(len(cert) >> 8), byte(len(cert))}) + ext.Write(cert) + // Pad the structure out to the shape of a real one; the client skips over it. + ext.Write(make([]byte, 16)) + return ext.Bytes() +} + +// fakeTLSConn is the record layer after the handshake: MTProto bytes in and out, +// TLS records on the wire. +type fakeTLSRecordConn struct { + conn net.Conn + buf []byte + sentCipher bool +} + +func newFakeTLSRecordConn(conn net.Conn) *fakeTLSRecordConn { + return &fakeTLSRecordConn{conn: conn} +} + +func (c *fakeTLSRecordConn) Read(p []byte) (int, error) { + for len(c.buf) == 0 { + record, err := readFakeTLSRecord(c.conn) + if err != nil { + return 0, err + } + switch record.Type { + case fakeTLSRecordApplication: + c.buf = record.Data + case fakeTLSRecordChangeCipherSpec: + // Part of the handshake, nothing to carry. + case fakeTLSRecordAlert: + return 0, fmt.Errorf("peer sent a TLS alert") + default: + return 0, fmt.Errorf("unexpected TLS record type %#x after the handshake", record.Type) + } + } + n := copy(p, c.buf) + c.buf = c.buf[n:] + return n, nil +} + +func (c *fakeTLSRecordConn) Write(p []byte) (int, error) { + // A real client sends ChangeCipherSpec before its first application record, + // so the server does too: this is a camouflage, and the shape of the traffic + // is the point. + if !c.sentCipher { + if err := writeFakeTLSRecord(c.conn, fakeTLSRecordChangeCipherSpec, []byte{0x01}); err != nil { + return 0, err + } + c.sentCipher = true + } + // Records are limited in size, so a large write becomes several records. + written := 0 + for written < len(p) { + end := written + fakeTLSMaxRecord + if end > len(p) { + end = len(p) + } + if err := writeFakeTLSRecord(c.conn, fakeTLSRecordApplication, p[written:end]); err != nil { + return written, err + } + written = end + } + return len(p), nil +} + +func (c *fakeTLSRecordConn) Close() error { return c.conn.Close() } + +// ─── The camouflage certificate ───────────────────────────────────────────── + +var ( + fakeTLSCertsMu sync.Mutex + fakeTLSCerts = map[string][]byte{} +) + +// fakeTLSCertificate returns a self-signed certificate for the domain the client +// claimed to be visiting. +// +// Generated per domain rather than shipped as a constant: a hardcoded +// certificate is a key everybody shares, and the client does not validate the +// chain in this mode, so there is nothing to gain from shipping one. It is +// generated once per domain and cached, because a prober that connects twice +// must not see two different certificates for the same site. +func fakeTLSCertificate(domain string) []byte { + fakeTLSCertsMu.Lock() + defer fakeTLSCertsMu.Unlock() + + if der, ok := fakeTLSCerts[domain]; ok { + return der + } + + der := generateFakeTLSCertificate(domain) + fakeTLSCerts[domain] = der + return der +} + +func generateFakeTLSCertificate(domain string) []byte { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + // A certificate is decoration here; the stream works without one, so + // fall back to a minimal structure rather than refusing the client. + return []byte{0x30, 0x00} + } + + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + if err != nil { + serial = big.NewInt(1) + } + template := x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: domain, Organization: []string{"Cloudflare Inc."}}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: []string{domain}, + } + der, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) + if err != nil { + return []byte{0x30, 0x00} + } + return der +} From 8bb6e19fff85d220a3619434ca5c8d7ad51122a7 Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sun, 18 Oct 2026 05:09:44 +0500 Subject: [PATCH 2/2] Add MTProto fake TLS, so the Telegram port can look like a website An ee secret carries the same obfuscated2 stream inside TLS records, so someone scanning the port sees a handshake with a real certificate rather than random bytes. One port serves both kinds: the client says which it wants in the secret's prefix, and the server tells them apart by the first byte -- 0x16 is a handshake, anything else is obfuscated2. Verified against gotd/td's fake TLS client, which implements the other side of exactly this exchange: the handshake, payload in both directions, a wrong secret, and a replayed hello. That reference is what turned up two things I had wrong. The client's HMAC covers the record exactly as it arrived, header included. Hashing the payload alone computes a different digest and refuses every real client -- the handshake simply never completed until the raw bytes were carried through. Sending a ChangeCipherSpec before the first application record looks more like a real handshake, but the reference client treats it as stream content rather than framing, so it injects a stray 0x01 at the head of the MTProto stream and desynchronises everything after. The camouflage is not worth corrupting the stream it is meant to hide. Two more things the tests settled. The ClientHello these clients send is built by hand and disagrees with its own length fields -- 34 bytes of cipher suites under a field saying 32 -- so the SNI is found by scanning for a well-formed server_name extension rather than by walking the message. And the domain is cosmetic, so a hello without one falls back to MTPROTO_FAKE_HOST instead of failing the connection; the HMAC is the security check, not the parse. The certificate is generated per domain rather than shipped as a constant. A hardcoded certificate is a key everybody shares, and the client does not validate the chain in this mode, so there is nothing to gain from carrying one in the repository. It is cached per domain, because a prober connecting twice must not see two certificates for the same site. Verified live: an ee secret completes the fake TLS handshake and the proxy dials Telegram's DC2, and a dd secret on the same port relays in plain obfuscated2. The kind is chosen per secret from the dashboard, so both can be handed out from one running service. What is not proven here: the official Telegram apps parse more of the synthetic ServerHello than gotd's client does, and there is no Telegram client in this environment to test against. This is proven against an independent client implementation, which is the strongest claim available here -- not against the official apps. --- .env.example | 5 + README.md | 30 ++++- config.json | 2 + faketls.go | 188 +++++++++++++++--------------- faketls_test.go | 304 ++++++++++++++++++++++++++++++++++++++++++++++++ go.mod | 1 + go.sum | 1 + main.go | 23 +++- mtproto.go | 133 +++++++++++++++++++-- mtproto_test.go | 10 +- web/index.html | 13 ++- 11 files changed, 592 insertions(+), 118 deletions(-) create mode 100644 faketls_test.go diff --git a/.env.example b/.env.example index d03fae7..3dc8cb9 100644 --- a/.env.example +++ b/.env.example @@ -39,6 +39,11 @@ 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 +# Secret kind for newly generated secrets: dd (obfuscated2) or ee (fake TLS). +# Fake TLS makes the port look like a website to a prober. +MTPROTO_SECRET_KIND=dd +# The domain the fake TLS reply is built around when a client does not name one. +# MTPROTO_FAKE_HOST=www.cloudflare.com # ─── Security ────────────────────────────────────────────────────────────── SECURITY_HEADERS_ENABLED=true diff --git a/README.md b/README.md index eee6b93..ebfc71c 100644 --- a/README.md +++ b/README.md @@ -11,7 +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 +- **MTProto** - Telegram's own protocol on its own port, with per-phone secrets managed in the dashboard, in plain obfuscated2 or fake TLS - **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 @@ -189,12 +189,28 @@ 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: +### Two kinds of secret -- **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. +| Prefix | Transport | What a prober sees | +|---|---|---| +| `dd…` | obfuscated2 | Random-looking bytes, which is what every Telegram proxy looks like | +| `ee…` | fake TLS | A TLS handshake with a real certificate, then the same stream inside it | + +Both are managed the same way, and one port serves both: the client says which +it wants in the secret's prefix. `MTPROTO_SECRET_KIND=ee` makes newly generated +secrets fake TLS; `MTPROTO_FAKE_HOST` sets the domain the reply is built around +when a client does not name one. + +The fake TLS certificate is generated per domain rather than shipped as a +constant — a hardcoded certificate is a key everybody shares, and the client does +not validate the chain in this mode. + +Two honest limits: + +- **Without an `ee` secret the port looks like noise.** That is the same as every + Telegram proxy. For a port that must look like a real site, use an `ee` secret + — and know that it is fake TLS, so a censor comparing it against the real site + it claims to be can still tell the difference. - **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. @@ -402,6 +418,8 @@ Edit `config.json` or use environment variables (env vars override config file): | `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 | +| `MTPROTO_SECRET_KIND` | dd | Kind of secret to generate: `dd` obfuscated2, `ee` fake TLS | +| `MTPROTO_FAKE_HOST` | www.cloudflare.com | Domain the fake TLS reply is built around | | `MAX_CONNECTIONS` | 1000 | Max simultaneous connections | | `ADMIN_USER` | admin | Admin dashboard username | | `ADMIN_PASS` | changeme | Admin dashboard password | diff --git a/config.json b/config.json index 335a382..abda8ef 100644 --- a/config.json +++ b/config.json @@ -8,6 +8,8 @@ "mtproto_enabled": false, "mtproto_bind": "0.0.0.0:8443", "mtproto_dcs": "", + "mtproto_secret_kind": "dd", + "mtproto_fake_host": "www.cloudflare.com", "username": "changeme", "password": "changeme", "whitelist": [], diff --git a/faketls.go b/faketls.go index 5c39b6c..5f3d310 100644 --- a/faketls.go +++ b/faketls.go @@ -64,6 +64,10 @@ const ( fakeTLSTimeSkew = 8 * time.Hour ) +// fakeTLSVersion3 is what both sides announce. Matching the version the +// reference client uses is part of looking ordinary. +var fakeTLSVersion3 = [2]byte{0x03, 0x03} + // fakeTLSRecord is one TLS record. type fakeTLSRecord struct { Type byte @@ -81,19 +85,31 @@ func writeFakeTLSRecord(w io.Writer, recType byte, data []byte) error { } func readFakeTLSRecord(r io.Reader) (fakeTLSRecord, error) { + rec, _, err := readFakeTLSRecordRaw(r) + return rec, err +} + +// readFakeTLSRecordRaw also returns the bytes exactly as they arrived, header +// included. The client's HMAC is taken over those precise bytes, so anything +// that re-serialises the record first computes a different digest and rejects +// every real client. +func readFakeTLSRecordRaw(r io.Reader) (fakeTLSRecord, []byte, error) { var header [5]byte if _, err := io.ReadFull(r, header[:]); err != nil { - return fakeTLSRecord{}, err + return fakeTLSRecord{}, nil, err } length := binary.BigEndian.Uint16(header[3:]) if length > fakeTLSMaxRecord { - return fakeTLSRecord{}, fmt.Errorf("fake tls record is %d bytes, too big", length) + return fakeTLSRecord{}, nil, fmt.Errorf("fake tls record is %d bytes, too big", length) } data := make([]byte, length) if _, err := io.ReadFull(r, data); err != nil { - return fakeTLSRecord{}, err + return fakeTLSRecord{}, nil, err } - return fakeTLSRecord{Type: header[0], Data: data}, nil + raw := make([]byte, 0, len(header)+len(data)) + raw = append(raw, header[:]...) + raw = append(raw, data...) + return fakeTLSRecord{Type: header[0], Data: data}, raw, nil } // fakeTLSClientHello is what the handshake yields: the shared secret that @@ -109,8 +125,8 @@ 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) (*fakeTLSRecordConn, *fakeTLSClientHello, error) { - record, err := readFakeTLSRecord(conn) +func fakeTLSHandshake(conn net.Conn, secrets mtprotoSecrets, 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) } @@ -121,16 +137,12 @@ func fakeTLSHandshake(conn net.Conn, secrets mtprotoSecrets, now time.Time) (*fa return nil, nil, fmt.Errorf("expected a ClientHello, got message type %#x", record.Data[0]) } - // The HMAC covers the record exactly as it arrived, so the bytes are kept - // intact and only a copy is modified for the comparison. - hello := record.Data[4:] - - domain, err := fakeTLSHelloDomain(hello) - if err != nil { - return nil, nil, err - } + // The HMAC is taken over the record as it arrived, header included, with the + // random zeroed. Everything after the handshake is parsed from the same + // bytes, so the offsets stay in one place. + domain := fakeTLSHelloDomain(record.Data[4:]) - matched, err := fakeTLSMatchSecret(hello, secrets, now) + matched, err := fakeTLSMatchSecret(raw, secrets, now) if err != nil { return nil, nil, err } @@ -139,9 +151,9 @@ func fakeTLSHandshake(conn net.Conn, secrets mtprotoSecrets, now time.Time) (*fa Secret: matched, Domain: domain, } - copy(info.Random[:], hello[2:34]) + copy(info.Random[:], raw[fakeTLSServerRandomOffset:fakeTLSServerRandomOffset+32]) - if err := writeFakeTLSServerResponse(conn, info, matched); err != nil { + if err := writeFakeTLSServerResponse(conn, info, matched, cloakHost); err != nil { return nil, nil, fmt.Errorf("write fake tls response: %w", err) } return newFakeTLSRecordConn(conn), info, nil @@ -150,23 +162,24 @@ func fakeTLSHandshake(conn net.Conn, secrets mtprotoSecrets, now time.Time) (*fa // 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(hello []byte, secrets mtprotoSecrets, now time.Time) ([]byte, error) { - if len(hello) < 34 { - return nil, fmt.Errorf("ClientHello is %d bytes, too short to carry a random", len(hello)) +func fakeTLSMatchSecret(raw []byte, secrets mtprotoSecrets, 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)) } var presented [32]byte - copy(presented[:], hello[2:34]) + copy(presented[:], raw[randomAt:randomAt+32]) - // Zero the random in place for the HMAC, then put it back. - original := append([]byte(nil), hello[2:34]...) - defer copy(hello[2:34], original) + // Zero the random for the HMAC, then put the client's bytes back. + original := append([]byte(nil), raw[randomAt:randomAt+32]...) + defer copy(raw[randomAt:randomAt+32], original) for _, secret := range secrets { - for i := 2; i < 34; i++ { - hello[i] = 0 + for i := randomAt; i < randomAt+32; i++ { + raw[i] = 0 } mac := hmac.New(sha256.New, secret) - mac.Write(hello) + mac.Write(raw) want := mac.Sum(nil) if !hmac.Equal(want[:28], presented[:28]) { @@ -183,66 +196,55 @@ func fakeTLSMatchSecret(hello []byte, secrets mtprotoSecrets, now time.Time) ([] return nil, errors.New("no configured secret matched this fake TLS hello") } -// fakeTLSHelloDomain pulls the server name out of the ClientHello's extensions. -// It is what the client claims to be visiting, which is also what a prober would -// believe it was reaching, so the reply has to look like it belongs to it. -func fakeTLSHelloDomain(hello []byte) (string, error) { - pos := 2 + 32 // client version and random - - if pos >= len(hello) { - return "", errors.New("ClientHello ended before the session id") - } - sessionLen := int(hello[pos]) - pos += 1 + sessionLen - - if pos+2 > len(hello) { - return "", errors.New("ClientHello ended before the cipher suites") - } - suitesLen := int(binary.BigEndian.Uint16(hello[pos:])) - pos += 2 + suitesLen - - if pos >= len(hello) { - return "", errors.New("ClientHello ended before the compression methods") - } - compressionLen := int(hello[pos]) - pos += 1 + compressionLen - - if pos+2 > len(hello) { - // No extensions at all: the client will not care, and neither does a - // prober reading a site that speaks no extensions. - return "", nil - } - extensionsLen := int(binary.BigEndian.Uint16(hello[pos:])) - pos += 2 - end := pos + extensionsLen - if end > len(hello) { - return "", errors.New("ClientHello extensions overrun the message") +// fakeTLSHelloDomain pulls the server name out of the ClientHello. +// +// It scans for a well-formed server_name extension rather than walking the +// message field by field, because the hellos these clients send are built by +// hand and do not always agree with their own length fields. A prober reading +// the reply expects a name in there; nothing depends on it being right, so a +// hello that does not contain one is not an error -- the caller falls back to a +// domain of its own. +func fakeTLSHelloDomain(hello []byte) string { + for i := 0; i+5 < len(hello); i++ { + // Extension type 0x0000 is server_name. + if hello[i] != 0x00 || hello[i+1] != 0x00 { + continue + } + extLen := int(binary.BigEndian.Uint16(hello[i+2:])) + body := i + 4 + if extLen < 5 || body+extLen > len(hello) { + continue + } + nameLen := int(binary.BigEndian.Uint16(hello[body+3:])) + if 5+nameLen > extLen || nameLen == 0 || nameLen > 253 { + continue + } + name := string(hello[body+5 : body+5+nameLen]) + if looksLikeHostname(name) { + return name + } } + return "" +} - for pos+4 <= end { - extType := binary.BigEndian.Uint16(hello[pos:]) - extLen := int(binary.BigEndian.Uint16(hello[pos+2:])) - body := pos + 4 - if body+extLen > end { - return "", errors.New("ClientHello extension overruns the message") - } - // 0x0000 is server_name. - if extType == 0x0000 && extLen > 5 { - nameLen := int(binary.BigEndian.Uint16(hello[body+3:])) - if 5+nameLen <= extLen { - return string(hello[body+5 : body+5+nameLen]), nil - } +func looksLikeHostname(name string) bool { + for i := 0; i < len(name); i++ { + c := name[i] + switch { + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9': + case c == '.' || c == '-' || c == '_': + default: + return false } - pos = body + extLen } - return "", nil + return name != "" } // writeFakeTLSServerResponse sends the three records a client expects: the // ServerHello, the ChangeCipherSpec, and a certificate record carrying the // domain the client asked for. -func writeFakeTLSServerResponse(w io.Writer, info *fakeTLSClientHello, secret []byte) error { - records := buildFakeTLSResponse(info, secret) +func writeFakeTLSServerResponse(w io.Writer, info *fakeTLSClientHello, secret []byte, cloakHost string) error { + records := buildFakeTLSResponse(info, secret, cloakHost) // The client's random goes into the digest so that a mirror replaying // recorded bytes cannot pass as the real thing. @@ -263,10 +265,15 @@ func writeFakeTLSServerResponse(w io.Writer, info *fakeTLSClientHello, secret [] // buildFakeTLSResponse assembles the reply records with the server's random // left as zeros for the caller to fill in. -func buildFakeTLSResponse(info *fakeTLSClientHello, secret []byte) []byte { +func buildFakeTLSResponse(info *fakeTLSClientHello, secret []byte, cloakHost string) []byte { domain := info.Domain if domain == "" { - domain = "example.com" + // No usable name in the hello, so answer with the one this proxy is + // configured to look like. Either way the bytes on the wire are a name. + domain = cloakHost + } + if domain == "" { + domain = "www.cloudflare.com" } var body bytes.Buffer @@ -322,9 +329,8 @@ func fakeTLSCertificateExtension(domain string) []byte { // fakeTLSConn is the record layer after the handshake: MTProto bytes in and out, // TLS records on the wire. type fakeTLSRecordConn struct { - conn net.Conn - buf []byte - sentCipher bool + conn net.Conn + buf []byte } func newFakeTLSRecordConn(conn net.Conn) *fakeTLSRecordConn { @@ -354,15 +360,13 @@ func (c *fakeTLSRecordConn) Read(p []byte) (int, error) { } func (c *fakeTLSRecordConn) Write(p []byte) (int, error) { - // A real client sends ChangeCipherSpec before its first application record, - // so the server does too: this is a camouflage, and the shape of the traffic - // is the point. - if !c.sentCipher { - if err := writeFakeTLSRecord(c.conn, fakeTLSRecordChangeCipherSpec, []byte{0x01}); err != nil { - return 0, err - } - c.sentCipher = true - } + // No ChangeCipherSpec is sent before the first application record. It looks + // more like a TLS handshake without it, but the reference client treats a + // ChangeCipherSpec as stream content rather than as handshake framing, so + // sending one injects a stray 0x01 at the head of the MTProto stream and + // desynchronises everything after it. The camouflage is not worth corrupting + // the stream it is supposed to be hiding. + // // Records are limited in size, so a large write becomes several records. written := 0 for written < len(p) { diff --git a/faketls_test.go b/faketls_test.go new file mode 100644 index 0000000..15744ba --- /dev/null +++ b/faketls_test.go @@ -0,0 +1,304 @@ +package main + +import ( + "bytes" + "crypto/rand" + "io" + "net" + "strconv" + "testing" + "time" + + "github.com/gotd/td/mtproxy" + "github.com/gotd/td/mtproxy/faketls" + "github.com/gotd/td/mtproxy/obfuscated2" +) + +// gotd ships the client half of fake TLS, so the handshake can be checked +// against an independent implementation rather than against itself. +func TestFakeTLSHandshakeWithGotdClient(t *testing.T) { + secret, err := generateMTProtoSecret("dd") + if err != nil { + t.Fatalf("generate secret: %v", err) + } + key, err := parseMTProtoSecret(secret) + if err != nil { + t.Fatalf("parse secret: %v", err) + } + + client, server := net.Pipe() + defer client.Close() + defer server.Close() + + secrets := mtprotoSecrets{secret: key} + done := make(chan error, 1) + go func() { + _, info, herr := fakeTLSHandshake(server, secrets, time.Now(), "www.cloudflare.com") + if herr != nil { + done <- herr + return + } + if info.Domain != "example.com" { + done <- errUnexpected{info.Domain} + return + } + done <- nil + }() + + clientObf := faketls.NewFakeTLS(rand.Reader, client) + if err := clientObf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 2, mtproxy.Secret{ + Secret: key, + CloakHost: "example.com", + }); err != nil { + t.Fatalf("the reference client refused our server hello: %v", err) + } + if err := <-done; err != nil { + t.Fatalf("our server refused the reference client: %v", err) + } +} + +// After the handshake, the MTProto stream runs inside TLS records, so bytes +// must survive the record layer in both directions. +func TestFakeTLSCarriesAPayloadBothWays(t *testing.T) { + secret, _ := generateMTProtoSecret("dd") + key, _ := parseMTProtoSecret(secret) + + client, server := net.Pipe() + defer client.Close() + defer server.Close() + + serverSide := make(chan *fakeTLSRecordConn, 1) + go func() { + wrapped, _, err := fakeTLSHandshake(server, mtprotoSecrets{secret: key}, time.Now(), "www.cloudflare.com") + if err != nil { + serverSide <- nil + return + } + serverSide <- wrapped + }() + + clientObf := faketls.NewFakeTLS(rand.Reader, client) + if err := clientObf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 2, mtproxy.Secret{ + Secret: key, CloakHost: "example.com", + }); err != nil { + t.Fatalf("handshake: %v", err) + } + + wrapped := <-serverSide + if wrapped == nil { + t.Fatal("the server handshake failed") + } + client.SetDeadline(time.Now().Add(10 * time.Second)) + server.SetDeadline(time.Now().Add(10 * time.Second)) + + up := []byte("bytes inside TLS application records") + go func() { _, _ = clientObf.Write(up) }() + got := make([]byte, len(up)) + if _, err := io.ReadFull(wrapped, got); err != nil { + t.Fatalf("client to server: %v", err) + } + if !bytes.Equal(got, up) { + t.Errorf("server read %q, want %q", got, up) + } + + down := bytes.Repeat([]byte{0x7E}, 9000) // more than one record's worth + go func() { _, _ = wrapped.Write(down) }() + back := make([]byte, len(down)) + if _, err := io.ReadFull(clientObf, back); err != nil { + t.Fatalf("server to client: %v", err) + } + if !bytes.Equal(back, down) { + for i := range down { + if back[i] != down[i] { + t.Fatalf("payload diverges at %d of %d: got %02x want %02x (head % x)", i, len(down), back[i], down[i], back[:8]) + } + } + t.Fatal("payload differs but not byte-wise") + } +} + +// A prober, or a client with the wrong secret, must not get through. +func TestFakeTLSRefusesWrongSecret(t *testing.T) { + secret, _ := generateMTProtoSecret("dd") + key, _ := parseMTProtoSecret(secret) + stranger := make([]byte, 16) + rand.Read(stranger) + + client, server := net.Pipe() + defer client.Close() + defer server.Close() + server.SetDeadline(time.Now().Add(5 * time.Second)) + // A refused client gets no reply at all, so without a deadline it waits + // forever rather than reporting the refusal. + client.SetDeadline(time.Now().Add(5 * time.Second)) + + go func() { + _, _, _ = fakeTLSHandshake(server, mtprotoSecrets{secret: key}, time.Now(), "www.cloudflare.com") + }() + + clientObf := faketls.NewFakeTLS(rand.Reader, client) + err := clientObf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 2, mtproxy.Secret{ + Secret: stranger, CloakHost: "example.com", + }) + if err == nil { + t.Error("a client with the wrong secret completed the fake TLS handshake") + } +} + +// The timestamp in the hello exists so a recorded handshake cannot be replayed +// days later. +func TestFakeTLSRefusesAStaleHello(t *testing.T) { + secret, _ := generateMTProtoSecret("dd") + key, _ := parseMTProtoSecret(secret) + + client, server := net.Pipe() + defer client.Close() + defer server.Close() + server.SetDeadline(time.Now().Add(5 * time.Second)) + client.SetDeadline(time.Now().Add(5 * time.Second)) + + // 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") + }() + + clientObf := faketls.NewFakeTLS(rand.Reader, client) + if err := clientObf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 2, mtproxy.Secret{ + Secret: key, CloakHost: "example.com", + }); err == nil { + t.Error("a hello outside the allowed clock skew was accepted") + } +} + +func TestFakeTLSHelloDomainParsing(t *testing.T) { + secret, _ := generateMTProtoSecret("dd") + key, _ := parseMTProtoSecret(secret) + + client, server := net.Pipe() + defer client.Close() + defer server.Close() + + secrets := mtprotoSecrets{secret: key} + domains := make(chan string, 1) + go func() { + _, info, err := fakeTLSHandshake(server, secrets, time.Now(), "www.cloudflare.com") + if err != nil { + domains <- "" + return + } + domains <- info.Domain + }() + + const want = "camouflage.example.org" + clientObf := faketls.NewFakeTLS(rand.Reader, client) + if err := clientObf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 2, mtproxy.Secret{ + Secret: key, CloakHost: want, + }); err != nil { + t.Fatalf("handshake: %v", err) + } + if got := <-domains; got != want { + t.Errorf("server read domain %q, want %q", got, want) + } +} + +type errUnexpected struct{ got string } + +func (e errUnexpected) Error() string { return "unexpected domain " + e.got } + +// A fake TLS secret has to work through the real listener, not just in +// isolation: one port serving both transports is the whole design. +func TestFakeTLSThroughTheListener(t *testing.T) { + secret, err := generateMTProtoSecretOfKind("ee") + if err != nil { + t.Fatalf("generate: %v", err) + } + key, err := parseMTProtoSecret(secret) + if err != nil { + t.Fatalf("parse: %v", err) + } + if mtprotoSecretKind(secret) != "ee" { + t.Fatalf("secret %q is not recognised as fake TLS", secret) + } + + // A datacenter that echoes, so the relay can be checked end to end. + 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() + session, _, herr := mtprotoAccept(conn, nil, true) + 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, "ee phone"); 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(15 * time.Second)) + + // The two layers nest the way a Telegram client builds them: obfuscated2 on + // the inside, fake TLS on the outside. + tlsLayer := faketls.NewFakeTLS(rand.Reader, client) + if err := tlsLayer.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 3, mtproxy.Secret{ + Secret: key, CloakHost: "www.cloudflare.com", + }); err != nil { + t.Fatalf("fake tls handshake against the listener: %v", err) + } + obf := obfuscated2.NewObfuscated2(rand.Reader, tlsLayer) + if err := obf.Handshake([4]byte{0xdd, 0xdd, 0x51, 0x6d}, 3, mtproxy.Secret{Secret: key}); err != nil { + t.Fatalf("obfuscated2 handshake inside the tls records: %v", err) + } + + payload := []byte("telegram traffic inside a tls-looking handshake") + 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) + } +} diff --git a/go.mod b/go.mod index 816f000..2d9f312 100644 --- a/go.mod +++ b/go.mod @@ -19,6 +19,7 @@ require ( 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/gotd/neo v0.1.5 // 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 diff --git a/go.sum b/go.sum index 21db7d8..b2fcf89 100644 --- a/go.sum +++ b/go.sum @@ -85,6 +85,7 @@ 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.0.0-20201207232520-09787c993a3a/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= diff --git a/main.go b/main.go index 92a66e0..34aa736 100644 --- a/main.go +++ b/main.go @@ -84,6 +84,10 @@ type Config struct { MTProtoBind string `json:"mtproto_bind"` // Datacenter overrides, as dc=address,dc=address. MTProtoDCs string `json:"mtproto_dcs"` + // Which kind of secret to generate: dd (obfuscated2) or ee (fake TLS). + MTProtoSecretKind string `json:"mtproto_secret_kind"` + // The domain the fake TLS reply is built around when the client names none. + MTProtoFakeHost string `json:"mtproto_fake_host"` // 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 @@ -134,6 +138,8 @@ func DefaultConfig() Config { TunnelRateRPS: 5, UDPEnabled: true, MTProtoBind: defaultMTProtoBind, + MTProtoSecretKind: "dd", + MTProtoFakeHost: "www.cloudflare.com", RealityBind: defaultRealityBind, RealityDest: defaultRealityDest, RealityXrayBin: "xray", @@ -299,6 +305,12 @@ func LoadConfig(filename string) (Config, error) { if v := os.Getenv("MTPROTO_DCS"); v != "" { cfg.MTProtoDCs = v } + if v := os.Getenv("MTPROTO_SECRET_KIND"); v != "" { + cfg.MTProtoSecretKind = v + } + if v := os.Getenv("MTPROTO_FAKE_HOST"); v != "" { + cfg.MTProtoFakeHost = v + } // REALITY. Comma-separated lists accept more than one SNI, short id or // VLESS id so a rotation does not need a restart. @@ -1969,12 +1981,21 @@ func (s *ProxyServer) adminHandler() http.Handler { } var req struct { Label string `json:"label"` + // 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"` } 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() + s.configMu.RLock() + kind := s.cfg.MTProtoSecretKind + s.configMu.RUnlock() + if req.Kind != "" { + kind = req.Kind + } + secret, err := generateMTProtoSecret(kind) if err != nil { http.Error(w, "could not generate a secret: "+err.Error(), http.StatusInternalServerError) return diff --git a/mtproto.go b/mtproto.go index b1cc4cb..cec3a61 100644 --- a/mtproto.go +++ b/mtproto.go @@ -139,10 +139,35 @@ func reverse(b []byte) { } } +// prefixConn puts already-read bytes back in front of a connection, so a single +// byte peeked to tell the transports apart does not cost the handshake the byte +// it was looking at. +type prefixConn struct { + net.Conn + prefix []byte +} + +func (c *prefixConn) Read(p []byte) (int, error) { + if len(c.prefix) > 0 { + n := copy(p, c.prefix) + c.prefix = c.prefix[n:] + return n, nil + } + return c.Conn.Read(p) +} + +// mtprotoConn is what a session needs from whatever carries it: a socket for +// obfuscated2, or the record layer of fake TLS. +type mtprotoConn interface { + io.Reader + io.Writer + Close() error +} + // mtprotoSession is one leg of a proxied conversation: an obfuscated stream in // each direction. type mtprotoSession struct { - conn net.Conn + conn mtprotoConn toPeer cipher.Stream from cipher.Stream } @@ -184,7 +209,7 @@ func (s *mtprotoSession) Write(p []byte) (int, error) { // 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) { +func mtprotoAccept(conn mtprotoConn, 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) @@ -331,6 +356,9 @@ type mtprotoServer struct { // have since been revoked. secrets func() mtprotoSecrets overrides map[int]string + // cloakHost is the domain the fake TLS reply is built around when a client + // does not name one of its own. + cloakHost string log *slog.Logger track func(net.Conn) untrack func(net.Conn) @@ -373,9 +401,7 @@ func (m *mtprotoServer) handle(conn net.Conn) { 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) + session, dc, err := m.accept(conn) if err != nil { log.Debug("mtproto handshake refused", "error", err) return @@ -411,11 +437,60 @@ func (m *mtprotoServer) handle(conn net.Conn) { closeBoth() } +// accept reads the client's opening and works out which transport it speaks. +// A TLS handshake starts 0x16; anything else is obfuscated2. The choice comes +// from the first byte, which is what lets one port serve both. +func (m *mtprotoServer) accept(conn net.Conn) (*mtprotoSession, int, error) { + secrets := m.secrets() + + peek := make([]byte, 1) + if _, err := io.ReadFull(conn, peek); err != nil { + return nil, 0, err + } + + // The peeked byte is the first byte of whichever handshake follows, so it is + // pushed back in front of the stream rather than consumed. + conn = &prefixConn{Conn: conn, prefix: peek} + + if peek[0] == fakeTLSRecordHandshake { + // The hello itself carries the HMAC, so the secret is settled before + // anything else is read. + wrapped, hello, err := fakeTLSHandshake(conn, secrets, time.Now(), m.cloakHost) + if err != nil { + return nil, 0, err + } + m.log.Info("fake tls hello accepted", "domain", hello.Domain) + session, dc, err := m.acceptWithSecret(wrapped, hello.Secret) + return session, dc, err + } + + return m.acceptWithAnySecret(conn, secrets) +} + +// acceptWithSecret runs the obfuscated2 handshake with a secret already known, +// which is the case after a fake TLS hello proved it. +func (m *mtprotoServer) acceptWithSecret(conn mtprotoConn, secret []byte) (*mtprotoSession, int, error) { + init := make([]byte, mtprotoInitLen) + if _, err := io.ReadFull(conn, init); err != nil { + return nil, 0, err + } + toPeer, fromPeer, err := mtprotoStreams(init, secret) + if err != nil { + return nil, 0, err + } + toPeer, fromPeer = fromPeer, toPeer + + probe := make([]byte, mtprotoInitLen) + fromPeer.XORKeyStream(probe, init) + dc := int(binary.LittleEndian.Uint16(probe[60:62])) + return &mtprotoSession{conn: conn, toPeer: toPeer, from: fromPeer}, dc, nil +} + // 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) { +func (m *mtprotoServer) acceptWithAnySecret(conn mtprotoConn, secrets mtprotoSecrets) (*mtprotoSession, int, error) { if len(secrets) == 0 { return nil, 0, errors.New("no MTProto secret is configured") } @@ -466,20 +541,53 @@ func copyStream(dst io.Writer, src io.Reader, log *slog.Logger) { // ─── 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) { +// A secret says which transport it belongs to: the dd prefix is obfuscated2, +// the ee prefix is the same stream wearing a TLS handshake. Telegram clients +// choose the transport from the prefix, so the server must too. +func mtprotoSecretKind(stored string) string { + if strings.HasPrefix(stored, "ee") { + return "ee" + } + return "dd" +} + +// generateMTProtoSecret returns a shareable proxy secret. The prefix is +// Telegram's: dd for obfuscated2, ee for the same stream inside a TLS handshake, +// and the client picks the transport from it. +func generateMTProtoSecret(kind string) (string, error) { + return generateMTProtoSecretOfKind(newSecretKind(kind)) +} + +// newSecretKind picks the kind of secret to generate, for a network where plain +// obfuscated2 is blocked and fake TLS is wanted instead. +func newSecretKind(configured string) string { + if strings.EqualFold(strings.TrimSpace(configured), "ee") { + return "ee" + } + return "dd" +} + +func generateMTProtoSecretOfKind(kind string) (string, error) { raw := make([]byte, mtprotoSecretLen) if _, err := rand.Read(raw); err != nil { return "", err } - return "dd" + hex.EncodeToString(raw), nil + if kind != "ee" { + kind = "dd" + } + return kind + 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")) + stored = strings.ToLower(strings.TrimSpace(stored)) + // Both prefixes are Telegram's markers, not part of the key. + trimmed := strings.TrimPrefix(stored, "dd") + if trimmed == stored { + trimmed = strings.TrimPrefix(stored, "ee") + } + key, err := hex.DecodeString(trimmed) if err != nil { return nil, fmt.Errorf("%q is not a hex secret", stored) } @@ -512,6 +620,7 @@ func (s *ProxyServer) startMTProto(secrets mtprotoSecrets) error { cfg: s.cfg, secrets: s.mtprotoLiveSecrets, overrides: parseMTProtoDCOverrides(s.cfg.MTProtoDCs), + cloakHost: orDefault(s.cfg.MTProtoFakeHost, "www.cloudflare.com"), log: s.logger, track: s.trackConn, untrack: s.untrackConn, @@ -552,7 +661,7 @@ func (s *ProxyServer) loadMTProtoSecrets(fallback mtprotoSecrets, generateIfEmpt } } if len(out) == 0 && generateIfEmpty && s.store != nil { - secret, err := generateMTProtoSecret() + secret, err := generateMTProtoSecret(s.cfg.MTProtoSecretKind) if err == nil { if _, err := s.store.CreateMtprotoSecret(secret, "generated"); err == nil { if key, kerr := parseMTProtoSecret(secret); kerr == nil { diff --git a/mtproto_test.go b/mtproto_test.go index a0f7632..a1317bb 100644 --- a/mtproto_test.go +++ b/mtproto_test.go @@ -238,7 +238,7 @@ func (e errUnexpectedDC) Error() string { return "unexpected datacenter " + strc // 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() + secret, err := generateMTProtoSecret("dd") if err != nil { t.Fatalf("generate secret: %v", err) } @@ -384,7 +384,7 @@ func TestMTProtoWriteSurvivesShortWrites(t *testing.T) { // 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() + secret, err := generateMTProtoSecret("dd") if err != nil { t.Fatalf("generate: %v", err) } @@ -431,7 +431,7 @@ func TestMTProtoUnknownSecretRefused(t *testing.T) { } func TestMTProtoSecretFormat(t *testing.T) { - secret, err := generateMTProtoSecret() + secret, err := generateMTProtoSecret("dd") if err != nil { t.Fatalf("generate: %v", err) } @@ -454,7 +454,7 @@ func TestMTProtoSecretFormat(t *testing.T) { } } // Two secrets must differ, or one would be shared by everyone. - other, _ := generateMTProtoSecret() + other, _ := generateMTProtoSecret("dd") if other == secret { t.Error("generated the same secret twice") } @@ -464,7 +464,7 @@ func TestMTProtoSecretFormat(t *testing.T) { // 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() + secret, err := generateMTProtoSecret("dd") if err != nil { t.Fatalf("generate: %v", err) } diff --git a/web/index.html b/web/index.html index b1f07bb..a132f0a 100644 --- a/web/index.html +++ b/web/index.html @@ -267,13 +267,22 @@

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. + once; nothing restarts. A dd secret is obfuscated2; an + ee secret carries the same stream inside a TLS handshake, + which makes the port look like a website to someone scanning it.

+
+ + +
@@ -675,7 +684,7 @@

Settings

async function createMtprotoSecret(){ var msg=document.getElementById('mtproto-msg'); - var body={label:document.getElementById('m-label').value}; + var body={label:document.getElementById('m-label').value,kind:document.getElementById('m-kind').value}; try{ var r=await fetch('/api/mtproto-secrets',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}); if(r.ok){