Skip to content
Scratch-netPublic

About

High-performance Telegram MTProxy with TLS fronting, Middle-End, WEB support, probe resistance, and per-user analytics. Bypass censorship undetected.

Topics

Resources

Stars

129 stars

Watchers

1 watching

Forks

Repository files navigation

telEgo Logo

telEgo

High-performance Telegram MTProxy in Go with TLS fronting, Telegram Middle-End, and native WEB protocol support

Tests Lint Coverage Release Go Reference License

Quick Install • Features • Installation • Quick Start • Configuration • Middle-End • WEB Proxy • Docker • Nginx + LE • Performance

English | Русский


Telegram blocked in your country? telEgo shapes proxy traffic as TLS records and forwards unrecognized connections to the mask host. Quick start


Quick Managed Install

Before installation, point a DNS hostname at the VPS.

Make sure that Docker is available and public TCP ports 80, 443, and 9443 are free. Then run:

curl -fsSL https://raw.githubusercontent.com/Scratch-net/telego/main/examples/gateway/install.sh \
  | sh -s -- --domain proxy.example.com --email admin@example.com

The installer configures Telego, Nginx, the TLS certificate, automatic renewal, and persistent host storage.

The installer selects the https carrier, because some filtered networks break WebSocket connections. ME starts automatically and uses direct routing until its connections are ready.

By default, WEB uses port 443 and MTProxy uses port 9443. Use --mtproxy-port 443 to put both on port 443.

Add --no-web if you only need MTProxy and the ordinary probe site.

If you already run Telego, copy the existing users into the generated [secrets] section.

Read the managed gateway guide for updates, backups, carrier selection, and removal.


Features

Networking

  • Event-driven I/O — Built on gnet with epoll/kqueue for maximum efficiency
  • Telegram Middle-End — Routes authenticated MTProxy and native WEB streams through persistent gnet link pools
  • Native WEB Proxy — Optional gnet HTTPS or WebSocket carrier for Telegram Desktop behind Nginx
  • Owned-buffer relaying — Output buffers remain owned until socket drain or disposal
  • Buffer pooling — Reuses buffers where their lifetime permits, with retained-memory accounting for queued output
  • Optimized TCP — TCP_NODELAY, TCP_QUICKACK, 64KB buffers, SO_REUSEPORT

Security

  • TLS Fronting — Uses the mask host's TLS profile to shape FakeTLS handshakes
  • Probe Resistance — Forwards unrecognized clients to the mask host
  • Replay Protection — 64-shard LRU cache with TTL expiration (hashicorp/golang-lru)
  • Key Zeroization — Sensitive data (session IDs, random bytes) zeroed on connection close
  • Desync Detection — Detects crypto state divergence via abnormal frame sizes
  • Dual Protocol Support — FakeTLS (ee) and raw Obfuscated2 (dd) with auto-detection on single port
  • Dynamic Record Sizer (DRS) — Outbound TLS ApplicationData starts with 1369-byte records and ramps to full size after 8 records or 128 KB, mimicking Chrome/Firefox steady-state record patterns
  • Split-TLS — First outbound ApplicationData record is emitted as a 1-byte record to defeat passive signatures keyed on the first record
  • Profile-matched cert record — The fake certificate record in the FakeTLS ServerHello is sized to match the mask host's real certificate record, so the accept path and the probe (splice) path present identical TLS record lengths
  • Post-quantum key share — When a client offers the hybrid X25519MLKEM768 group, the synthetic ServerHello answers with a matching key share instead of downgrading to classical x25519 (a passive group-downgrade tell)
  • SNI-following mask — Optional safelist of domains; an unrecognized probe whose SNI is safelisted is forwarded to that domain's own server, so the on-wire conversation matches the SNI it claimed
  • Several cover domains — Optional extra SNI domains for chosen secrets. Each domain has its own ServerHello template, certificate, and probe target

Operations

  • Multi-user Support — Named secrets with per-user tracking and logging
  • ME Link Repair — Replaces failed physical links without moving healthy bindings or rebuilding every DC pool
  • ME Link Refresh — Prepares replacements for unused links before retirement, with bounded candidates and per-DC availability counters
  • Connection Tracking — Unique connection IDs for easy log correlation
  • Connection Limits — Per-IP connection limits and per-user IP limits with smart blocking (only blocks IPs with active connections when evicted, allowing legitimate reconnections)
  • Prometheus Metrics — Per-user connection counts, traffic, and blocked IP statistics
  • DC Probing — Automatic RTT-based DC address sorting at startup
  • Config Hot-Reload — SIGHUP and file watching for runtime config changes
  • Clock Self-Correction — Optional startup sync of the handshake time-skew window from a remote HTTP Date header, so a wrong server clock doesn't reject every client
  • Stale-Connection Recovery — Optional close of relays whose server reply goes unanswered by the client, recovering iOS clients stuck on "Updating" after a long background
  • Graceful Shutdown — Clean connection draining on SIGTERM/SIGINT
  • Structured Logging — JSON and text output with configurable levels

Deployment

  • Unix Socket Support — Bind to Unix sockets for reverse proxy setups
  • PROXY Protocol — Accept v1/v2 headers from HAProxy/nginx to preserve client IPs
  • SOCKS5 Upstream — Route direct DC traffic, ME links, and artifact requests through a SOCKS5 proxy

Installation

From Source

Source builds require Go 1.27.4 or later and the complete repository, including third_party/gnet.

git clone https://github.com/Scratch-net/telego.git
cd telego
make build

Pre-built Binaries

Download from Releases.

The local gnet replacement prevents installation with go install …@version. Use the source build or a pre-built binary instead.


Quick Start

1. Generate a secret:

telego generate www.google.com
# secret=0123456789abcdef0123456789abcdef  <- put this in config
# ee_link=tg://proxy?server=YOUR_IP&port=443&secret=ee...  <- FakeTLS (recommended)
# dd_link=tg://proxy?server=YOUR_IP&port=443&secret=dd...  <- raw Obfuscated2

2. Create config.toml:

[general]
bind-to = "0.0.0.0:443"

[secrets]
alice = "0123456789abcdef0123456789abcdef"

[tls-fronting]
mask-host = "www.google.com"

3. Run:

telego run -c config.toml -l

The -l flag prints Telegram proxy links with auto-detected public IP.


Protocol Modes

telEgo supports two MTProxy protocol variants on a single port with auto-detection:

Mode Secret Prefix Description Best For
FakeTLS (ee) ee... TLS-wrapped Obfuscated2 Maximum stealth, censorship bypass
Raw (dd) dd... Plain Obfuscated2 Compatibility, lower overhead

FakeTLS (ee) wraps traffic in TLS records that imitate HTTPS. The secret includes the mask hostname for SNI validation. Telego forwards unrecognized connections to the mask host for probe resistance.

Raw (dd) sends Obfuscated2 directly without TLS wrapping. Lower overhead but easier to fingerprint. Useful for compatibility with older clients or when TLS fronting isn't needed.

Both modes use the same 16-byte secret key. The ee or dd prefix in the client link determines which mode the client uses. telEgo auto-detects the protocol from the first bytes of each connection.


Telegram Middle-End

Telegram Middle-End (ME) is Telegram's upstream transport for MTProxy servers. Telego routes authenticated MTProxy and native WEB streams through ME.

Both the public listener and the ME link engine use gnet. Telego keeps four physical links for each signed Telegram DC.

Each ME request uses the public source IP of its selected link. This behavior supports SOCKS5 egress and hosts with multiple public IPs.

Telegram proxy registration and proxy-tag are optional. Without a tag, Telego sends untagged ME requests and ME still works.

ME is enabled by default. Telego prepares and checks ME connections in the background while new clients use direct DC connections.

For ME connections, allow HTTPS to core.telegram.org and TCP to the ME endpoints in the Telegram artifacts. Private direct sockets also need UDP STUN access or a correct nat-ip. Any NAT on direct links must preserve TCP source ports.

Use this optional section to change the ME configuration:

[middle-end]
# enabled = false # Uncomment to disable ME and its background connection attempts.
# proxy-tag = "0123456789abcdef0123456789abcdef" # Optional tag issued by Telegram
# socks5 = "127.0.0.1:1080"
# nat-ip = "YOUR_PUBLIC_IP" # Usually empty. Automatic STUN supports Docker bridge networks.

Restart Telego after a change to this section. An absent section or enabled value enables ME. An explicit enabled = false disables it.

On upgrade, remove an existing enabled = false to use the default. Configurations without that override start ME automatically.

INFO logs report whether ME is established, unavailable, or explicitly disabled. If setup fails, new clients use direct routing while Telego retries.

Telego replaces a failed link in place. Healthy bindings and healthy DC pools stay on their existing physical links.

Each physical slot has independent probes and repair. A slow slot does not stop probes on the other slots.

Before a repaired link accepts bindings, its replacement must complete the handshake and return a matching RPC pong within 10 seconds.

Unused links become eligible for refresh after 45–60 seconds. Telego completes the replacement handshake and RPC probe before it retires the current link.

The current link stays available during preparation. A new client binding cancels the replacement.

After artifact rotation, healthy old bindings keep their links and probes without a retirement deadline. Retiring generations do not repair or refresh links.

Telego permits at most two live generation managers, including a candidate. Before the next candidate needs this capacity, Telego closes the oldest retiring generation.

This capacity retirement can interrupt old bindings. A failed candidate leaves the active generation unchanged but cannot restore those interrupted bindings.

Before ME is ready, the direct DC path stays available. If ME cannot accept a binding, the direct DC path also stays available.

Each connection keeps its selected route until it closes.


Native Telegram WEB Proxy

Telego includes an optional WEB proxy for Telegram Desktop. It uses a separate private gnet HTTP/1.1 listener behind Nginx.

Nginx keeps the real TLS certificate and the ordinary website. MTProxy can share port 443 or use a different public port.

Add this section to enable WEB for existing secrets:

[web-proxy]
enabled = true
hostname = "proxy.example.com"
carrier = "websocket"
bind-to = "127.0.0.1:8080"
trusted-proxy-cidrs = ["127.0.0.1/32"]

WEB streams enter the shared MTProxy session core directly on gnet. The default path creates no internal TCP or Unix connection.

An explicit backend value selects a local TCP or Unix socket for compatibility. This path retains the authenticated PROXY preface. Nginx terminates real TLS in both paths.

The installer selects https and also configures Nginx to forward WebSocket upgrades. Repeat installations preserve the saved carrier. websocket-lanes remains available for separate stream queues. It requires more connections and handshakes, and its performance depends on the client, network, and workload.

The carrier value selects one of four transports:

Value Transport Requirements
https One serialized fetch and long-poll carrier Default when carrier is empty or absent, and installer default.
https-lanes One fetch and long-poll lane for each Telegram stream Alternative for deployments without WebSocket support. Requires public HTTP/2.
websocket One multiplexed WebSocket for the WEB session Shares one connection across streams. Some filtered networks break it. Forward HTTP/1.1 Upgrade and Connection headers to Telego.
websocket-lanes One WebSocket for each Telegram stream Separate stream queues, with additional connections and handshakes. Requires HTTP/1.1 upgrade forwarding.

Current Telegram Desktop manages the WEB carrier. The user does not need to open or keep a browser tab.

In WebSocket modes, the carrier opens same-host wss connections through Nginx. In HTTPS modes, it uses fetch requests and long polls.

You must route every request from the Nginx TLS server to this listener. This rule prevents carrier headers from bypassing Telego.

The setup uses two private fallback statuses.

  • Status 418 preserves an ordinary website request.
  • Status 419 removes carrier credentials before public-site delivery.

Run Telego with -l to print the plain and dd WEB links. Telego derives both links from each existing base secret.

Use --web-host to print WEB links when you generate a new secret:

telego generate www.google.com --web-host proxy.example.com

The same command works through Docker because the image runs Telego as its entry point:

docker run --rm scratchnet/telego:latest \
  generate www.google.com --web-host proxy.example.com

The positional hostname is the FakeTLS mask hostname. The --web-host value is the public WEB proxy hostname.

The --web-host value must match [web-proxy].hostname and the TLS certificate in Nginx.

Read the WEB proxy example for the Compose files and certificate renewal procedure.

The optional [web-proxy].base-path serves WEB under a path on the existing HTTPS port. For example, base-path = "telegram/test" supports a separate instance at /telegram/test/. Separate instances can share the same public hostname and port 443.

Configure the path in both Telego and Nginx. The Nginx route location ^~ /telegram/test/ must forward the complete path to that instance's private WEB listener. Use proxy_pass without a URI suffix or trailing slash.

Use --web-base-path telegram/test with --web-host to generate compatible links. The path must match the Telego configuration. A path change requires new client links and a Telego restart. An empty base path keeps existing root links unchanged. Path links require a Telegram client with WEB base-path support.

For a new VPS, use the quick managed install. The installer can also disable WEB or select a separate MTProxy port.

Read the gateway guide for full instructions.

Use the manual example for an existing website or a custom Nginx layout.

The WEB configuration is inactive by default. Configurations without [web-proxy] continue to use the existing MTProxy startup path.

WEB behind a CDN

You can put the WEB hostname behind a CDN. Before you do, read these limits:

  • Cloudflare reports that since June 9, 2025, users in Russia load only the first 16 KB of web assets from Cloudflare (Cloudflare blog). A CDN does not help on these networks.
  • Use a CDN only for networks where you measured that it works.

With a CDN, Nginx receives connections from CDN edge addresses. The example Nginx configuration sends X-Forwarded-For $remote_addr to Telego. Telego uses this address for per-IP and per-user limits. Without more configuration, all clients share the address of the CDN edge, and the limits apply to the CDN edge.

To keep the client address, configure the Nginx realip module:

# Repeat for each published address range of the CDN.
set_real_ip_from <cdn-range>;
# Use the header that the CDN documents, for example CF-Connecting-IP for Cloudflare.
real_ip_header CF-Connecting-IP;

Nginx then sets $remote_addr to the client address. Keep the CDN address list current. An address range that is missing makes those clients share one address.

Experimental connection rotation

Some censors freeze one TCP connection after about 15-20 KB from the server to the client. They do not send a reset. More HTTP requests on the same connection do not help. A new connection gets a new byte budget.

The https carrier can rotate connections. This mode is an opt-in experiment. Do not use it if WEB works without it.

  1. Set carrier = "https".
  2. Set carrier-batch-kib to a small value, for example 4. This value limits each carrier body and each downlink DATA frame. The default is 2048.
  3. In the Nginx TLS server block, close each connection after a few requests:
keepalive_requests 3;   # close the connection after 3 requests (HTTP/1.1 and HTTP/2)
keepalive_time 30s;     # close the connection after 30 seconds

The browser then opens a new connection for the next request.

The costs are high:

  • Each new connection needs a full TLS handshake. The certificate chain uses part of the byte budget of the connection.
  • Throughput becomes very low. Each connection carries only a few small responses.
  • Each new connection sends a SYN. If synlimit.sh protects the WEB port, each client IP can open 48 connections per minute, with a burst of 24. Rotation can reach this limit, and then new connections get a reset.
  • Some censors block a port for about 2 minutes after a burst of SYN packets. Fast rotation can cause this block.
  • keepalive_requests and keepalive_time apply to every request in that server block, including the ordinary website.

If you use rotation, set stream-download = false. A stream keeps one response open on one connection.

Streamed download

Without streaming, the https carrier sends one long poll for each downlink batch. Each batch then waits for one round trip.

With stream-download, the bridge keeps one download response open. Telego sends each new downlink frame in that response at once. This option is on by default for carrier = "https". The default does not apply to other carriers, and an explicit stream-download = true with another carrier is an error. Set stream-download = false to use only ordinary long polls.

  • A streamed response ends after the long-poll time (25 seconds) or when it reaches the batch size.
  • If a stream breaks, the bridge asks for the same batch again with an ordinary long poll. Telego sends the complete batch again, and the bridge skips the frames that it already delivered.
  • After any error, the bridge uses ordinary long polls until Telegram Desktop loads a new bridge page.
  • Nginx must not buffer the response. The shipped templates set proxy_buffering off. Telego also sends X-Accel-Buffering: no.
  • The bridge asks for a stream with the Accept: application/vnd.telego.web-stream request header. Nginx forwards it without a configuration change.

Fair WebSocket queue

The websocket carrier sends all Telegram streams through one WebSocket. The browser delivers only complete messages. In arrival order, with up to 2048 KiB in one message, a small reply can wait behind a large media download.

websocket-fair-queue changes the order of each message:

  • WINDOW control frames go first.
  • DATA and CLOSE frames rotate across streams. The frames of one stream keep their order.
  • Each message carries at most 160 KiB (two full 64 KiB backend reads plus small frames).

This option is on by default for carrier = "websocket". The default does not apply to other carriers, and an explicit websocket-fair-queue = true with another carrier is an error. Smaller messages need more browser events. Set websocket-fair-queue = false to send frames in arrival order.

Experimental padding of the first frames

Set pad-first-frames = true to pad the first 8 carrier batches in each direction. Telego and the bridge add one padding frame, which the other side discards. The sizes follow Xray Vision: a batch under 900 bytes grows to 900 plus 0-500 bytes, and a longer batch gets 0-256 more bytes. Padding never makes a batch larger than carrier-batch-kib.

This option works only with carrier = "https" or carrier = "websocket". It is off by default because:

  • Padding adds bytes to each connection.
  • The available evidence shows that the censor freezes a connection after a byte count. It does not use frame sizes. Padding can make that limit come sooner.

Configuration

Telego rejects unknown TOML keys, negative limits, and invalid TLS ports. Error messages identify the configuration fields that need correction. Zero retains its documented default or unlimited meaning.

Config Reference

[general]
# Network binding (TCP or Unix socket)
bind-to = "0.0.0.0:443"
# bind-to = "/run/telego/telego.sock"  # Unix socket

# Log level: trace, debug, info, warn, error
log-level = "info"

# Accept incoming PROXY protocol headers (from HAProxy/nginx)
# proxy-protocol = false

# TCP peers allowed to send PROXY headers. Empty = any peer.
# Unix socket peers are always allowed. Other peers are direct clients.
# Set this when telego listens on TCP behind a proxy, or a direct client can spoof its IP.
# trusted-proxy-cidrs = ["127.0.0.1/32"]

# Maximum connections per IP (0 = unlimited)
# Applies to ALL connections (including unauthenticated) from a single IP
# max-connections-per-ip = 100

# Maximum concurrent client connections in every mode.
# 0 = derive from the RLIMIT_NOFILE soft limit: (limit - min(256, limit / 2)) / 2,
# because each direct client uses two descriptors (client and DC).
# Middle-End max-connections can only lower this value.
# max-connections = 0

# Max time for handshake before dropping connection (default: 5s; allowed: 1s to 1m)
# handshake-timeout = "5s"

# Maximum unique IPs per user (0 = unlimited)
# Prevents secret sharing - limits how many devices/locations can use one secret
# max-ips-per-user = 3

# How long blocked IPs stay blocked (for max-ips-per-user)
# ip-block-timeout = "5m"

# Correct a skewed server clock at startup from a remote HTTP Date header
# (offset clamped to +-1 day). A wrong VPS clock otherwise rejects every client.
# clock-sync-url = "https://www.cloudflare.com"

# Named secrets (hex format, 32 chars = 16 bytes)
# Generate with: telego generate <hostname>
[secrets]
user1 = "0123456789abcdef0123456789abcdef"
user2 = "fedcba9876543210fedcba9876543210"

# TLS fronting configuration
[tls-fronting]
mask-host = "www.google.com"  # Host to mimic (SNI validation, proxy links)
# mask-port = 443             # Port for mask-host (default: 443)
# cert-host = "127.0.0.1"     # Where to fetch TLS cert (default: mask-host)
# cert-port = 8443            # Cert fetch port (default: mask-port)
# splice-host = "127.0.0.1"   # Forward unrecognized clients here (default: mask-host)
# splice-port = 8080          # Splice port (default: mask-port)
# splice-proxy-protocol = 1   # PROXY protocol to splice: 0=off, 1=v1(text), 2=v2(binary)
# splice-idle-timeout = "5m"  # Idle timeout for spliced connections (default: 5m)
# fake-cert-size = 0          # Fake cert record size; 0 = auto-match mask host (clamp 256..16384)
# mask-sni-safelist = ["www.microsoft.com"]  # Probes with these SNIs front to that domain (off = empty)
# profile-cache-dir = "/var/lib/telego"     # Last good ServerHello profile on disk. Default: $STATE_DIRECTORY or /var/lib/telego. "off" = off

# Anti-DPI record shaping (proxy -> client direction)
# enable-drs = true        # Probe-then-ramp record sizing (1369 -> 16384 bytes after 8 records or 128 KB)
# enable-split-tls = true  # Emit first ApplicationData record as 1 byte

# Extra cover domains (optional). Keep these tables last in [tls-fronting].
# [[tls-fronting.domains]]
# host = "www.microsoft.com"  # SNI and ee link hostname of the listed secrets
# secrets = ["user2"]         # Names from [secrets]; each secret in one domain at most
# cert-host = "127.0.0.1"     # Default: host
# cert-port = 8443            # Default: 443
# splice-host = "127.0.0.1"   # Default: host
# splice-port = 8443          # Default: 443
# splice-proxy-protocol = 0   # Default: 0 (off)
# fake-cert-size = 0          # Default: 0 (match this domain)

# Native Telegram Desktop WEB proxy (optional; requires Nginx with real TLS)
[web-proxy]
enabled = false
carrier = "https"                        # Default and installer default
# Other values: https-lanes, websocket, websocket-lanes
# hostname = "proxy.example.com"            # Required public certificate hostname
# bind-to = "127.0.0.1:8080"               # Private HTTP/1.1 listener
# backend = "127.0.0.1:443"                # Explicit local socket compatibility path
# trusted-proxy-cidrs = ["127.0.0.1/32"]   # Nginx peers allowed to send X-Forwarded-For
# num-event-loops = 0                       # 0 = automatic
# carrier-batch-kib = 0                     # 0 = 2048 KiB. Experimental: 4-2048
# stream-download = true                    # Default on. https carrier only
# websocket-fair-queue = true               # Default on. websocket carrier only
# pad-first-frames = false                  # Experimental. https and websocket carriers only

# Telegram Middle-End transport (enabled by default; changes require a restart)
[middle-end]
# enabled = false                         # Uncomment to disable ME and its background connection attempts.
# proxy-tag = "0123456789abcdef0123456789abcdef" # Optional tag issued by Telegram
# socks5 = "127.0.0.1:1080"                # Defaults to [upstream].socks5
# socks5-username = "proxy-user"
# socks5-password = "proxy-password"
# artifact-proxy = "http://127.0.0.1:3128" # Overrides the artifact proxy only
# nat-ip = "YOUR_PUBLIC_IP"                # Usually empty. Overrides automatic STUN.
# max-connections = 0                       # 0 = 10,000. An override can only reduce it.
# queue-budget-mb = 0                       # 0 = 32 MiB plus 16 KiB

# Performance tuning (all optional)
[performance]
prefer-ip = "prefer-ipv4"    # prefer-ipv4, prefer-ipv6, only-ipv4, only-ipv6
idle-timeout = "5m"          # Connection idle timeout (hot-reloadable)
num-event-loops = 0          # 0 = auto (all CPU cores)
# tcp-buffer-kb = 0          # Legacy setting; accepted but has no effect
# client-silence-close = "12s"  # Close relays whose server reply stays unanswered (fixes iOS "Updating"); 0 = off, minimum 1s

# Upstream (DC connection) settings
[upstream]
# socks5 = "127.0.0.1:1080"  # Route DC traffic through SOCKS5 proxy

# Prometheus metrics (optional)
[metrics]
# bind-to = "127.0.0.1:9090"  # Metrics endpoint (empty = disabled)
# path = "/metrics"           # Metrics path
# diagnostics = false         # Private on-demand profiles. Requires a loopback bind and a restart.

CLI Reference

telego run       Start the proxy server
  -c, --config   Path to config file (required)
  -b, --bind     Override bind address
  -l, --link     Print Telegram proxy links on startup (both ee and dd)

telego generate <mask-host> [--web-host <hostname>] [--web-base-path <path>]
                             Generate a new secret
                             Print ee (FakeTLS) and dd (raw) MTProxy links
  --web-host <hostname>      Print plain and dd WEB proxy links
  --web-base-path <path>     Bind WEB links to a path; requires --web-host

telego version   Show version information

telego doctor -c <config> [--timeout 10s] [--cert-source]
                             Verify the fallback TLS certificate and mask hostname

Before the TLS check, telego doctor fails if the splice target or the certificate source is Telego itself. The target is Telego itself when it resolves to the listen address on the listen port. A wildcard listen address matches every local address. The public IP also matches. splice-host and cert-host default to mask-host. When mask-host resolves to the proxy, set them to a different server. Otherwise unrecognized clients are spliced back into Telego again and again. Telego also logs this error at startup, with local addresses and [middle-end] nat-ip only, and starts anyway.

telego doctor also prints these warnings. They do not make the command fail.

  • The checked endpoint does not negotiate X25519MLKEM768. TSPU is reported to block iOS clients when the mask host supports only classical key exchange.
  • No address of a DC answers the MTProto check. The check sends an unauthenticated req_pq_multi and needs a resPQ that echoes its nonce. A connection reset or close fails the check. The check uses [upstream] socks5 when it is set.
  • The A and AAAA records of mask-host do not include the proxy public IP. TSPU is reported to compare them. Doctor uses [middle-end] nat-ip as the public IP. If it is empty, doctor uses STUN. If STUN fails, doctor skips this check.

Docker

Docker Hub

docker run -d \
  --name telego \
  -p 443:443 \
  -v /path/to/config.toml:/config.toml \
  scratchnet/telego:latest

Docker Compose

version: '3.8'
services:
  telego:
    image: scratchnet/telego:latest
    container_name: telego
    restart: unless-stopped
    ports:
      - "443:443"
    volumes:
      - ./config.toml:/config.toml:ro
    cap_add:
      - NET_BIND_SERVICE

TLS Front Profile Cache

[tls-fronting] profile-cache-dir keeps the last good mask ServerHello profile on disk. It is on by default. Without it, a restart with a failed first fetch sends a synthetic ServerHello until a retry succeeds. With it, telego loads the saved profile before the first fetch.

  • If the option is not set, telego uses $STATE_DIRECTORY (set by systemd StateDirectory=), else /var/lib/telego.
  • If telego cannot create or write that default directory at startup, it logs one info line and runs without the cache. Startup does not fail.
  • If you set an absolute path, telego uses it. A failed write logs a warning. It does not stop the refresh.
  • Set profile-cache-dir = "off" to turn the cache off.
  • telego writes the file at most once per hour, with mode 0600.
  • telego ignores a file with a different host or port, a file larger than 64 KiB, a file older than 7 days, or a ServerHello that is not a valid TLS 1.3 record.

The shipped systemd units set StateDirectory=telego, so systemd creates a writable /var/lib/telego. A unit installed by an older release does not have it. The cache is then off until you install the new unit, or add StateDirectory=telego with systemctl edit telego.

The Docker image runs as root, so telego can create /var/lib/telego in the container. That directory is lost when the container is recreated. With --read-only, the cache is off. To keep the cache, mount a writable volume:

docker run -d \
  --name telego \
  -p 443:443 \
  -v /path/to/config.toml:/config.toml \
  -v telego-cache:/var/lib/telego \
  scratchnet/telego:latest

Build Locally

docker build -f dist/Dockerfile.build -t telego .
docker run -d -p 443:443 -v ./config.toml:/config.toml telego

SYN Limit

TSPU can block the proxy port for 2 minutes after a burst of SYN packets. synlimit.sh limits new connections per source IP in the DOCKER-USER chain. It uses the telemt defaults: 48 SYN per minute with a burst of 24. A second lane allows 12 SYN per second with a burst of 24 for iOS-like SYN packets. Packets over the limit get a TCP reset.

The script is optional. It works only with the Docker iptables backend. Docker does not remove rules from DOCKER-USER, but the rules are lost on reboot. To apply them at boot, install the script and the systemd unit:

sudo install -m 0755 synlimit.sh /usr/local/sbin/telego-synlimit
sudo install -m 0644 dist/synlimit@.service /etc/systemd/system/telego-synlimit@.service
sudo systemctl daemon-reload
sudo systemctl enable --now telego-synlimit@443.service

The instance name is the published host port. The script finds the public interface from the default IPv4 route. To set it, run sudo systemctl edit telego-synlimit@443.service and add Environment=PUBLIC_IF=eth0 under [Service].


Behind a Reverse Proxy

telEgo can run behind HAProxy or nginx using Unix sockets and PROXY protocol:

config.toml:

[general]
bind-to = "/run/telego/telego.sock"
proxy-protocol = true
max-connections-per-ip = 100  # DoS protection
max-ips-per-user = 3          # Sharing protection

[secrets]
user1 = "0123456789abcdef0123456789abcdef"

[tls-fronting]
mask-host = "www.google.com"

HAProxy example:

backend telego
    mode tcp
    server telego /run/telego/telego.sock send-proxy-v2

nginx example:

upstream telego {
    server unix:/run/telego/telego.sock;
}

server {
    listen 443;
    proxy_pass telego;
    proxy_protocol on;
}

Choosing a Mask Host

The mask host sets the SNI that censors see for FakeTLS connections.

Russian DPI is reported to freeze one TCP connection to a foreign data-centre address after about 15-20 KB from server to client (net4people/bbs#490). The same reports say that some SNI values are on a whitelist and do not get this freeze. The whitelist can be different for each operator. The TCP 16-20 domain whitelist checker measures it and publishes results.

Before you select a whitelisted domain, read these points:

  • It is not verified that FakeTLS connections get the same exemption as other TLS connections.
  • telego doctor warns when the mask host does not resolve to the proxy IP, because TSPU is reported to compare them. A whitelisted domain of another company does not resolve to your proxy. The two recommendations conflict. Test on the networks of your users.
  • Probes are spliced to splice-host, which is mask-host by default. A probe must get the real certificate of the mask host. Do not point splice-host at a server that does not have a certificate for that domain.

Nginx + Let's Encrypt (Real Certificate TLS)

Some censorship systems (e.g., TSPU) validate the TLS certificate against the SNI hostname. If your proxy gets blocked on mobile or connects intermittently, you may need a real certificate for your domain instead of borrowing one from a mask host.

The deploy-nginx.sh script sets up nginx with a Let's Encrypt certificate alongside telego in Docker:

Port 443 (host) --> telego (MTProxy TLS fronting)
                      |-- valid client  --> Telegram DCs
                      |-- cert fetch    --> nginx:8443 (real LE cert)
                      +-- probe/unknown --> nginx:8443 (decoy website)
Port 80  (host) --> nginx (ACME challenges + HTTPS redirect)

Censors and probes see a valid certificate for your domain and a real HTTPS website.

Prerequisites

  • VPS with Docker
  • A domain pointing to your VPS IP (e.g., via FreeDNS)
  • Ports 80 and 443 free
  • Telego config file already in place

Usage

./deploy-nginx.sh -d <domain> -e <email> [options]
Flag Description Default
-d Domain name (required)
-e Email for Let's Encrypt (required)
-D Telego directory ~/telego
-c Telego config filename config.toml
-p Telego port 443

Example:

./deploy-nginx.sh -d myproxy.example.com -e admin@example.com -c config.toml

What it does

  1. If no telego config exists, creates one with the correct [tls-fronting] settings and exits -- add your secrets and re-run
  2. Stops any existing telego and telego-nginx containers
  3. Obtains a Let's Encrypt certificate (standalone mode, skips if cert exists)
  4. Starts nginx (port 80 for ACME, internal port 8443 with the real cert)
  5. Pulls and starts telego on a shared Docker network with nginx
  6. Adds a daily cron job for certificate renewal

First run

On a fresh server, the first run creates the config and exits:

./deploy-nginx.sh -d myproxy.example.com -e admin@example.com
# Config created at: ~/telego/config.toml
# Add at least one secret before running again

Generate a secret and add it to the config:

docker run --rm scratchnet/telego:latest generate myproxy.example.com
# Paste the hex string into [secrets] section of config.toml

Then run the script again to deploy:


Systemd

Install as a systemd service:

sudo make install CONFIG=/etc/telego/config.toml
sudo systemctl enable telego
sudo systemctl start telego

Service file is installed to /etc/systemd/system/telego.service.

Shutdown and exit status

SIGTERM or SIGINT starts a shutdown. The shutdown has a limit of 25 seconds. The log drain after it can take up to 2 more seconds. This fits in a stop timeout of 30 seconds. The default Docker stop timeout is 10 seconds. Use docker stop -t 30 or stop_grace_period: 30s to allow the full shutdown. A second SIGTERM or SIGINT stops the wait immediately. A clean shutdown after a signal exits with status 0. A shutdown that exceeds the limit, or is interrupted by a second signal, exits with a non-zero status. If the public listener or the Middle-End network runtime stops without a signal, Telego exits with a non-zero status. SIGHUP and a closed stderr pipe do not stop the process.

The service file sets Restart=always and TimeoutStopSec=30.


Config Hot-Reload

telEgo supports runtime configuration reloading without restart:

Via SIGHUP:

kill -HUP $(pidof telego)

Automatic: Config file changes are detected via fsnotify (Linux inotify).

Hot-reloadable fields:

  • [general].log-level — Applied immediately
  • [performance].idle-timeout — Applies to new connections
  • [secrets] and [general].disabled-secrets — Applied immediately, without a listener restart

A secret reload works as follows:

  • An added or enabled secret accepts new clients at once.
  • Sessions of an unchanged secret continue.
  • Sessions of a removed or disabled secret are closed. The close reason is secret_revoked.
  • A renamed secret or a secret with a new key counts as a removed secret plus an added secret.
  • If the new config is invalid, telego logs a warning and keeps the current config. For example, disabled-secrets must name only entries in [secrets].
  • A secret host comes from mask-host. If the host changes, the secret change is not applied and a restart is necessary.
  • WEB credentials are made at startup. A removed or disabled secret cannot connect through WEB after the reload, because its inner MTProto handshake fails. An added secret works through WEB only after a restart.
[general]
disabled-secrets = ["bob"]   # bob stays in [secrets] but cannot connect

All other configuration changes require a restart, including listeners, TLS fronting, WEB, ME, metrics, diagnostics, upstream routing, and connection limits.


Performance

Benchmarks

Tested on Intel i9-12900K, Linux 6.6:

Benchmark Throughput Allocations
Raw TCP loopback 6.0 GB/s 0 B/op
AES-CTR encrypt 10.5 GB/s 0 B/op
AES-CTR encrypt+decrypt 5.3 GB/s 0 B/op
Full pipeline (TLS+O2) 4.6 GB/s 5 B/op
TLS frame parse (pooled) 35.5 GB/s 0 B/op
Replay cache lookup 40 ns 32 B/op

Optimizations

  • Striped locking — 64-shard replay cache, 64-shard user IP limiter
  • Buffer pools — 64KB DC buffers, 16KB TLS record buffers
  • Zero-copy crypto — XORKeyStream directly into output buffers
  • Batched writes — Multiple TLS records coalesced into single syscall
  • Lock-free state — Atomic state machine for connection handling
  • Backpressure — Flow control with hysteresis (soft/hard limits) prevents OOM on slow clients without oscillation

Logging

Log producers queue JSON events; one consumer formats and writes them to stderr. The queue holds 4,096 events, including one reserved slot for a fatal event. Info, debug, and trace events can use at most three quarters of the queue. The other 1,024 slots are kept for warning and error events. When the available part of the queue is full, new events are dropped and counted by telego_log_dropped_messages_total. Events submitted after shutdown starts are also dropped and counted. Shutdown and fatal exit allow up to two seconds to drain queued events. A stalled sink can leave events unwritten at exit.

Connections are tracked with unique IDs for easy correlation:

INF gnet proxy started on 0.0.0.0:443
INF Connection limiter enabled: max 100 connections per IP
INF User IP limiter enabled: max 3 IPs per user, block timeout 5m0s
INF [#1:alice] 203.0.113.5:54321 -> DC 2
INF [#2:bob] 198.51.100.10:12345 -> DC 4
INF [#1:alice] DC 2 closed (45.2s) (active: 1)
WRN [#2:bob] DC 4 closed (30s): i/o timeout (active: 0)
  • #N — Connection ID (incremental, unique per session)
  • #N:user — Connection ID with matched secret name
  • Duration shown on close
  • Errors on authenticated connections logged as WARN

Metrics

telEgo exposes Prometheus metrics when configured:

[metrics]
bind-to = "127.0.0.1:9090"

Private runtime diagnostics

Diagnostics are disabled by default. They use the existing metrics listener, without another server or continuous profiling. The configuration requires a literal loopback address and a port from 1 to 65535. DNS names, wildcard addresses, and public addresses are rejected. With diagnostics enabled, the metrics path cannot contain patterns or percent escapes, or use the reserved /debug/pprof prefix.

To enable diagnostics, add diagnostics = true to [metrics]. Then restart Telego. Do not forward the diagnostics routes through Nginx or another public proxy.

Profiles contain internal process details. Requests require a literal loopback HTTP host and a loopback peer. The hostname localhost is not accepted.

Route Output
/debug/pprof/goroutineleak A fresh, filtered text profile with debug=1
/debug/pprof/heap A binary heap profile
/debug/pprof/allocs A binary allocation profile
/debug/pprof/goroutine A binary goroutine profile
/debug/pprof/profile?seconds=10 A binary CPU profile

Only GET requests are accepted. The CPU duration defaults to 10 seconds and accepts integers from 1 to 15. The leak route accepts only optional debug=1. The other snapshot routes accept only optional debug=0. The index, command line, symbol, trace, block, and mutex routes are unavailable.

One profile request can run at a time. Concurrent requests receive HTTP 503 instead of entering a queue. Responses have an 8 MiB limit and a 20-second request timeout. HTTP 413 indicates that a profile exceeds the response limit.

Client cancellation or server shutdown stops CPU profiling. The runtime completes an active leak-detection GC before it can return. The response limit does not bound internal runtime memory or GC duration. A fresh leak profile runs GC and adds temporary load.

The leak profile detects permanently blocked goroutines. A zero count does not exclude live timer workers or other resource leaks.

For a local leak snapshot, run:

curl --fail --max-time 25 http://127.0.0.1:9090/debug/pprof/goroutineleak

To disable diagnostics, set diagnostics = false. Then restart Telego.

Available Metrics

Metric Type Description
telego_connections_active Gauge Active connections per user
telego_ips_active Gauge IPs with active connections per user
telego_ips_tracked Gauge Unique IPs in LRU cache per user
telego_ips_blocked Gauge Currently blocked IPs per user
telego_blocked_total Counter Total IP block events per user
telego_traffic_in_bytes_total Counter Bytes received from clients
telego_traffic_out_bytes_total Counter Bytes sent to clients
telego_handshake_failures_total Counter MTProxy handshake failures by stage
telego_mask_fallbacks_total Counter Connections sent to the mask host, by reason: malformed, unknown_sni, unknown_secret, bad_timestamp, or replay
telego_tls_client_fingerprints Gauge ClientHellos since start, by kind (authenticated or mask_fallback) and ja4. See below.
telego_connection_closes_total Counter Closes of client connections that reached a relay session, by reason. See the reasons below.
telego_replay_cache_evictions_total Counter Replay cache entries evicted before their 10-minute TTL because the cache was full. A growing value means the replay window is shorter. This metric has no labels.
telego_log_dropped_messages_total Counter Log events dropped when the queue is full or shutdown has started. This metric has no labels.
telego_web_websocket_connections_active Gauge Active WEB WebSocket carrier connections. This metric has no labels.
telego_web_sessions_active Gauge Active WEB sessions
telego_web_streams_active Gauge Active WEB backend streams
telego_web_backend_dials_active Gauge WEB backend dials in progress
telego_web_pending_bytes Gauge Bytes charged to WEB pending queues
telego_web_pending_items Gauge Items charged to WEB pending queues
telego_web_sessions_created_total Counter WEB sessions created
telego_web_sessions_closed_total Counter WEB sessions closed by reason
telego_web_carrier_retries_total Counter WEB retries and replays by operation
telego_web_backpressure_total Counter WEB backpressure events by operation
telego_web_websocket_closes_total Counter Closes of opened WEB WebSocket carriers, by reason. See the reasons below.
telego_web_http_write_timeouts_total Counter WEB HTTP carrier connections closed because a response write made no progress before the write timeout. This metric has no labels.
telego_middleend_admitting Gauge Whether an active ME generation accepts new bindings
telego_middleend_links Gauge ME links by generation role, signed DC, and state
telego_middleend_slot_failure_total Counter Physical-link failures
telego_middleend_slot_failure_affected_bindings_total Counter Bindings terminated by physical-link failures
telego_middleend_response_pressure_evictions_total Counter Bindings evicted by response queue limits, by limit, across generations
telego_middleend_response_pressure_discarded_bytes_total Counter Queued response bytes discarded from evicted bindings, by limit
telego_middleend_forced_retirement_total Counter Capacity retirements by reason: artifact_capacity or recovery_capacity
telego_middleend_forced_retirement_affected_bindings_total Counter Bindings interrupted by capacity retirement, by reason
telego_middleend_diagnostic_records_dropped_total Counter Diagnostic records rejected by the full journal. This metric has no labels.
telego_middleend_slot_repair_total Counter Physical-link replacement results
telego_middleend_slot_refreshes_active Gauge Refresh candidate reservations by generation role and signed DC, including cleanup
telego_middleend_slot_refresh_total Counter Lifetime refresh results by signed DC: success, failure, or canceled
telego_middleend_zero_ready_transitions_total Counter Lifetime losses of all ready links for an admitting signed DC
telego_middleend_frontend_routes_active Gauge Active ME and direct-fallback routes
telego_middleend_frontend_route_commits_total Counter Lifetime ME and direct-fallback route selections

Connection, IP, block, and traffic metrics include a user label. Diagnostic metrics use the labels in the table.

telego_tls_client_fingerprints shows the JA4 fingerprints of TLS ClientHellos. kind="authenticated" counts hellos that matched a secret. kind="mask_fallback" counts hellos sent to the mask host, including replays. Each kind shows its 16 most frequent fingerprints. The ja4="other" series is the sum of all other fingerprints of that kind. Telego counts at most 64 fingerprints for each kind. A new fingerprint replaces the least frequent one, so the counts are approximate. The sum of each kind is exact. The values reset when Telego restarts. A fingerprint series disappears when it leaves the top 16. The metric has no client addresses and no user names. Raw obfuscated2 (dd) connections and malformed hellos are not counted.

telego_web_websocket_connections_active has no labels. It counts accepted WebSocket carriers after the HTTP upgrade response leaves Telego.

telego_connection_closes_total counts each client connection once, when it closes. It counts only connections that reached a direct DC relay or a Middle-End binding. Earlier closes are in telego_handshake_failures_total and telego_mask_fallbacks_total. Mask-host splices are not counted. The site that starts the close records the reason. The first recorded reason is used.

Reason Meaning
client_eof The client closed the connection (EOF).
client_error The client socket failed, for example with a reset.
upstream_closed The direct DC connection closed or failed.
middleend_closed Middle-End sent a close for this client (CloseExternal).
middleend_backpressure Telego evicted the binding or closed the client because a Middle-End buffer limit was reached.
middleend_terminal The Middle-End binding ended for a proxy-side reason: link failure, generation retirement, manager close, or a protocol error.
idle_timeout No payload moved in either direction for the idle timeout.
relay_stall_downlink The client accepted no relayed bytes for 100 seconds.
relay_stall_uplink The Telegram DC accepted no relayed bytes for 100 seconds.
output_stall Middle-End output to the client made no progress for the output stall timeout.
client_silence The client-silence breaker closed the connection.
shutdown Telego was stopping.
secret_revoked A config reload removed or disabled the secret of the connection.
other Telego closed the connection for a cause that has no reason, for example a protocol violation.

A WEB logical stream reports a Telego-side close without a recorded reason as client_eof. Its close always passes EOF.

telego_web_websocket_closes_total counts each WebSocket carrier once, after the upgrade completes. The reasons are transport_closed (the socket closed without another reason), session_closed, downlink_error, lane_closed, output_capacity, liveness_timeout, server_close, uplink_error, input_capacity, decode_error, peer_close, encode_error, write_error, and write_timeout.

When debug logging is on, Telego logs one line for each counted client close. The line has the connection ID, user, reason, route, WEB flag, DC, age, and error category.


Architecture

┌─────────────┐     ┌───────────────────────────────┐
│  Telegram   │────▶│            telEgo             │
│   client    │◀────│  ee, dd, and native WEB input │
└─────────────┘     └───────────────┬───────────────┘
                                    │ authenticated session
                         ┌──────────┴──────────┐
                         ▼                     ▼
                 ┌───────────────┐     ┌───────────────┐
                 │ Telegram ME   │     │Direct fallback│
                 │ gnet link pool│     │   connection   │
                 └───────┬───────┘     └───────┬───────┘
                         └──────────┬───────────┘
                                    ▼
                             ┌─────────────┐
                             │ Telegram DC │
                             └─────────────┘

Unauthenticated FakeTLS probes ─────────────▶ mask host

Contributing

Release notes belong in docs/releases/<tag>.md. The release workflow passes this file to GoReleaser.

Before a pull request, run make test. This command runs the local gnet patch regressions and the Telego tests in the three supported build modes. It does not run the upstream gnet test suite.

On Linux with 32-bit executable support, also run make test-32. This command runs the Telego tests with production tags on linux/386 to detect alignment and allocation-size errors. The test and release workflows require this gate. Cross-builds alone do not detect these runtime errors.

Install Node.js 26 to include the WEB bridge behavior tests. These tests run the rendered JavaScript with simulated clocks and sockets. They require no npm packages. CI installs Node explicitly. If Node is absent, local Go tests skip the JavaScript tests. Node is not required to build or run Telego.

The test runner sets GOMAXPROCS=2, one package at a time, two parallel tests, and a 120-second timeout per package. GOMEMLIMIT=512MiB is a soft Go runtime limit. It does not prevent an operating-system OOM.

On Linux with cgroup v2 and a systemd user manager, run make test-limited for local verification. This command caps the complete test process tree at 2 GiB of memory, no swap, 512 tasks, and two CPUs. It runs the gates in sequence and preserves the caller's environment. Other platforms can run make test, but this command has no hard memory limit.

For performance changes, compare the relevant benchmarks before and after the change.


License

Apache License 2.0


Acknowledgments

This project was inspired by and builds upon ideas from:

  • mtg by Sergey Arkhipov — The original Go MTProxy implementation
  • mtprotoproxy by Alexander Borzunov — Python reference implementation
  • telemt — High-performance Rust MTProxy implementation

About

High-performance Telegram MTProxy with TLS fronting, Middle-End, WEB support, probe resistance, and per-user analytics. Bypass censorship undetected.

Topics

Resources

Stars

129 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages