mtproto

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mtproto is the Telegram MTProto proxy protocol as a Mistgate node serves it: Fake TLS in front, obfuscated2 inside, a fresh obfuscated2 connection to a Telegram DC behind. The node engine (internal/node/mtproto) owns the listener, the credentials and the decoy site; this package owns one connection from its first byte to its last.

A client with an "ee" secret opens what looks like TLS 1.3 to the node's domain, with an HMAC of the hello under its key in the random field, so the server tells its clients from everyone else without a round trip. The server answers a ServerHello the client checks the same way, and both sides then wrap obfuscated2 in TLS application data records. The client's first 64 bytes inside give the AES-256-CTR keys of its leg, the transport tag and the DC it wants. The server dials that DC (directly, no middle proxy), sends a header with keys of its own and relays, decrypting one leg and encrypting the other; the plaintext between them is the MTProto transport, and its size is what the Observer counts.

Whatever is not an authenticated client of a configured domain (another SNI, a failed HMAC, a replayed hello, a hello outside the clock window, plain HTTP, a browser) goes to Config.Fallback with every byte already read, so a prober talks to the real site the caller puts there. Plain obfuscated2 without Fake TLS is not served: on a node whose port 443 also shows a website it would be a stream of noise nothing else on the port explains.

Sources and the reasons for the limits: design/adr/0010-mtproto.md.

Index

Constants

View Source
const KeyLen = 16

KeyLen is the length of an MTProto proxy key, the 16 bytes every other key of a connection is derived from.

Variables

View Source
var (
	ErrClosed = errors.New("mtproto: server is closed")
	ErrBusy   = errors.New("mtproto: too many handshakes")
)

Functions

func HelloSNI

func HelloSNI(b []byte) string

HelloSNI is the server name in a TLS ClientHello record at the start of b, "" when b does not start with a whole one. A fallback that forwards by name reads it from the bytes Serve hands over.

Types

type Config

type Config struct {
	Credentials []Credential
	// Domains are the SNI names a client may ask for, the domain in the "ee" secret of the links. A hello for another
	// name goes to Fallback without an HMAC. At least one is required.
	Domains  []string
	Dialer   Dialer // nil: net.Dialer
	Now      func() time.Time
	Random   io.Reader // nil: crypto/rand
	Observer Observer
	Log      *slog.Logger // operational warnings only; never secrets or traffic

	// HandshakeTimeout is the hard limit from the first byte to the DC connection; default 10 s. The DC addresses tried
	// share what is left of it, so a blackholed first address leaves time for the others.
	HandshakeTimeout time.Duration
	DialTimeout      time.Duration // at most this per DC address; default 10 s
	StatsInterval    time.Duration // how often an open session reports traffic and is checked for idleness; default 10 s
	// IdleTimeout closes a session that moved no byte either way for this long; default 10 min. Telegram clients ping
	// about once a minute, so a session this quiet is one nobody holds any more.
	IdleTimeout time.Duration
	// MaxSessionsPerCredential bounds the open sessions of one credential (one device); over it a new session is
	// refused. Default 64: a client keeps a main and a media connection per DC it uses and opens a few more for
	// uploads and downloads, about 10-15 per account at the busiest, and one app may hold several accounts behind one
	// proxy. 64 leaves room for that, and stops a leaked key from carrying more than a handful of people.
	MaxSessionsPerCredential int
	// ReplayWindow is how long an authenticated hello is remembered. A hello is accepted only when the client's clock
	// is within half of it from Now, so a hello old enough to have left the cache is refused by its time. Default 10 min.
	ReplayWindow time.Duration
	// ReplayCacheSize bounds the replay cache (about 60 bytes an entry); default 1<<17. Full of live entries, the
	// server refuses new hellos (they go to Fallback) until entries expire.
	ReplayCacheSize int
	// ReplayPerCredential bounds the entries one credential may hold in the replay cache, so one key holder cannot
	// spend the inbound's capacity; default ReplayCacheSize/64 (2048 hellos per window, over 3 a second for the default
	// window, where a client makes a few a minute). Over it that credential's new hellos go to Fallback until its
	// entries expire.
	ReplayPerCredential int
	// MaxHandshakes and MaxHandshakesPerAddr bound unauthenticated connections in progress; over a limit a connection
	// is closed at once. Defaults 1024 and 32 (per IPv4 address or IPv6 /64).
	MaxHandshakes, MaxHandshakesPerAddr int

	PreferIPv6 bool // try a DC's IPv6 addresses first
	// IgnoreTimeSkew accepts hellos whatever the client's clock says. Replays are then caught only while the cache
	// remembers them.
	IgnoreTimeSkew bool
	// DCAddress overrides the address of a DC (called with the DC as the client sent it); false falls through to
	// Telegram's published table.
	DCAddress func(dc int16) (string, bool)
	// Fallback takes every connection that is not an authenticated client, with the bytes read from it so far, and
	// owns it from then on (nil: the connection is closed). It runs on the Serve goroutine; by then the server holds
	// nothing of the connection (no handshake slot, no deadline), so it may serve it there. An authenticated session
	// never reaches it.
	Fallback func(ctx context.Context, conn net.Conn, initial []byte) error
}

type Credential

type Credential struct {
	ID  string
	Key [KeyLen]byte
}

Credential is one key the server accepts. ID is the caller's name for it: what the Observer reports and what CloseCredential takes. It is not secret; Key is.

func ParseCredential

func ParseCredential(id, secret string) (Credential, error)

ParseCredential reads a proxy secret in any of the forms Telegram links carry: 32 hex characters (a plain obfuscated2 proxy), "dd" and 32 hex (the same with padding), "ee", 32 hex and the Fake TLS domain in hex. All three give the same key. The server speaks only Fake TLS and takes the domains it accepts from Config.Domains, so the domain of an "ee" secret is only checked to be a plausible host name. Errors never quote the secret.

type Dialer

type Dialer interface {
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

Dialer opens the connections to Telegram DCs; *net.Dialer is one.

type Observer

type Observer interface {
	Opened(SessionInfo)
	Closed(SessionInfo)
	AddTraffic(session SessionInfo, up, down uint64)
}

Observer is told about sessions and their plaintext traffic. Calls come from the session's goroutine and must not block or call back into the Server. AddTraffic names the session (not only its credential), so traffic lands where the session was opened even if its credential's key changed meanwhile; a session's last AddTraffic comes before its Closed.

type Server

type Server struct {
	// contains filtered or unexported fields
}

func New

func New(cfg Config) (*Server, error)

func (*Server) CloseAll

func (s *Server) CloseAll()

CloseAll closes every connection, handshakes included, and refuses new ones. The server is done after it.

func (*Server) CloseCredential

func (s *Server) CloseCredential(credID string) int

CloseCredential closes the sessions of a credential and stops its handshakes in progress from opening one. The credential stays accepted for new connections. It returns the number of sessions closed.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, conn net.Conn) error

Serve runs one accepted connection to its end. The returned error says why it ended; it never carries key material or bytes of the stream.

func (*Server) ServeListener

func (s *Server) ServeListener(ctx context.Context, ln net.Listener) error

ServeListener accepts connections from ln and serves each. A connection gets its handshake slot before a goroutine is started for it, so a flood over the limits costs an accept and a close each, not a goroutine. It returns when ln is closed and every connection it started has ended.

func (*Server) SetCredentials

func (s *Server) SetCredentials(creds []Credential) error

SetCredentials replaces the accepted keys. Sessions of a credential that is gone, or whose key changed, are closed now, and a handshake that authenticated with such a key cannot open a session afterwards: registration re-checks the credential under the same lock.

type SessionInfo

type SessionInfo struct {
	ID           uint64
	CredentialID string
	DC           int16
	Tag          Tag
	Remote, SNI  string
	Since        time.Time
}

SessionInfo describes one relayed connection. DC is what the client asked for (negative: media).

type Tag

type Tag uint32

Tag is the MTProto transport inside obfuscated2 (header bytes 56..60). The server does not parse the transport: it writes the same tag to the DC and relays the bytes.

const (
	TagAbridged     Tag = 0xefefefef
	TagIntermediate Tag = 0xeeeeeeee
	TagPadded       Tag = 0xdddddddd
)

func (Tag) String

func (t Tag) String() string

Directories

Path Synopsis
Package mtprototest contains the fake Telegram DC used by proxy tests.
Package mtprototest contains the fake Telegram DC used by proxy tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL