Skip to content

MTProto front door for Telegram, with managed secrets - #12

Merged
GlobalTechInfo merged 4 commits into
mainfrom
feat/mtproto
Oct 17, 2026
Merged

GlobalTechInfo merged 4 commits into
mainfrom
feat/mtproto

Conversation

@GlobalTechInfo

@GlobalTechInfo GlobalTechInfo commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

Why

Telegram speaks neither SOCKS5 nor HTTP, so every other front door in this service was of no use to it. Unlike REALITY, this cannot be handed to xray — I checked, and xray ships an mtproto outbound but no inbound — so the protocol is implemented here and the client's obfuscated stream relayed to the datacenter it asked for.

Wire compatibility is proven, not asserted

The primitives are AES-256-CTR and SHA-256 from the standard library, and the layout is Telegram's. Rather than trust my reading of it, the tests run the handshake against gotd/td, an independent implementation, in both directions:

  • our server handshake against their client (including a 4KB payload round trip)
  • our client handshake against their server, with the datacenter id checked on their side

A proxy that is only self-consistent connects to nothing — that is the trap this avoids. github.com/gotd/td is a test-only dependency; go list -deps . contains no gotd and the binary's dependency tree is unchanged.

Four bugs, most found by running it

  • Short TCP writes silently truncated messages. Telegram traffic is much larger than a socket buffer, so this is the difference between working and appearing intermittently broken. Sessions now write in full, and a test pushes 200KB through a pipe that accepts 64 bytes at a time.
  • The listener kept a snapshot copy of the secrets, so revoking one in the dashboard changed nothing until a restart. It now reads the live set per connection.
  • Deleting the last secret quietly minted a replacement — handing out a credential the operator had just refused. Generation happens at startup only, and a test asserts it.
  • With one secret configured I had skipped the transport tag check, reasoning there was nothing to disambiguate. That meant serving anyone. The tag is the proof that a client knows the secret, so it is always checked; a test now asserts junk is refused.

The tag doubles as the multi-secret check: 64 random bytes decrypted with the wrong secret do not yield a recognisable tag, so one read identifies which secret a client is using.

What you get

MTPROTO_ENABLED=true, and the first secret is generated on first start. The dashboard's Telegram panel adds, disables and revokes per-phone secrets; changes apply at once, since the set is read per connection. Backup needs no change — the secrets are inside the SQLite file VACUUM INTO already snapshots.

Verified live

  • A real Telegram client implementation (gotd) completed the handshake against the running service and the proxy dialled Telegram's own DC2 — mtproto session relayed client=127.0.0.1 dc=2 address=149.154.167.51:443.
  • After revoking that secret, the next connection was not relayed: the relayed-session count stayed at 1.

gofmt/go vet clean; full suite green with and without Xray; -race clean, which caught a genuine race where DC overrides were cached in package-level variables read by concurrent connection goroutines — they are now parsed once at startup.

Not in this PR

Fake TLS. It is a separate wrapper around this stream, and obfuscated2 is what Telegram apps accept today, so the working part lands first. The camouflage layer is the harder half to get byte-exact and should be its own change with its own verification.

Also worth stating plainly: the transport looks like random bytes, which is what every Telegram proxy looks like on the wire. If the port must look like a website to an active prober, that remains REALITY's job — and Telegram does not speak VLESS.

Summary by CodeRabbit

  • New Features
    • Added an optional Telegram MTProto proxy, disabled by default, with configurable listener and data-center settings.
    • Added dashboard controls to create, copy, enable, disable, and revoke proxy secrets. Changes take effect immediately.
  • Documentation
    • Added setup guidance, configuration details, and information about managing and backing up MTProto secrets.

Until now the REALITY client list was a comma-joined config value, so
revoking a UUID meant editing configuration and restarting the service. A
management screen that only takes effect on restart is a trap, so this
makes the change real.

The list lives in a vless_clients table, one row per client. Precedence is
unchanged in spirit: REALITY_CLIENT_IDS still pins the list from
configuration and now says so, because accepting edits that quietly do
nothing is worse than refusing them. An id left behind by the old
comma-joined value is adopted into the table on first run rather than
dropped -- otherwise the first dashboard change would revoke a client
that is still in the field.

Making it live meant teaching the xray supervisor to re-point itself. The
reload carries a config that has already passed `xray run --test`, so an
invalid change is refused and the running front door keeps serving; the
supervisor is the only thing that stops and starts the child, and it
answers once the new child is actually accepting connections. Measured
live: an add applies in 0.08s.

Two refusals worth having. Removing the last client is rejected, because
xray with no clients is a front door that rejects everyone and an operator
should have to mean it. And a refused change restores the row rather than
dropping it, so the database never claims something xray does not do.

Verified live against xray on a real port: a UUID added through the API
served traffic immediately, the same client failed the moment it was
revoked, the untouched client kept working, and xray's own log named the
refusal (proxy/vless/encoding: rejected). Covered end to end in tests too,
including the case the race detector caught on the way: s.cfg is written
under configMu while being read here.
users.password_hash held the password verbatim, so any copy of the
database -- a backup, a stray file, a support attachment -- was a list of
working credentials, for the service and for whatever else those people
reuse the same password on.

PBKDF2-HMAC-SHA256 at 600k iterations, which is the OWASP figure for that
pair, from the standard library. No new dependency for the one thing in a
proxy that must not be improvised, and the cost is paid per login attempt
on an endpoint that already rate-limits guesses.

The parameters are recorded in each stored hash rather than assumed at
verify time, so they can be raised later without invalidating what is on
disk. That also means the stored value chooses the cost, so parsing refuses
anything implausible instead of letting a corrupt or hostile record turn
one login into a memory-exhaustion attack.

Existing installs need no migration: a row from before hashing is verified
against the value it holds, and rewritten on the next successful login.
An install cleans itself up one account at a time.

PROXY_USER/PROXY_PASS and the admin pair are untouched -- they come from
the environment, not the database, so there is nothing to hash and the file
is already a secret the operator controls.

Verified against a running server: a user created through the API lands in
the file as pbkdf2-sha256$iter=600000$..., the plaintext is absent from the
database bytes, the correct password authenticates and a wrong one does not,
a seeded pre-hashing row logs in and is rewritten on the spot, and a
backup of the result contains neither the old nor the new plaintext --
VACUUM INTO leaves no stale copies behind, though the live WAL keeps the
old value until it is checkpointed.
Telegram speaks neither SOCKS5 nor HTTP, so the other protocols here were
of no use to it. Unlike REALITY, this cannot be handed to xray -- I checked,
and xray has an mtproto outbound but no inbound -- so the protocol is
implemented here and the stream relayed to the datacenter the client asked
for.

The primitives are AES-256-CTR and SHA-256 from the standard library. The
layout is Telegram's, and rather than trust my reading of it, the tests run
the handshake against gotd/td, an independent implementation, in both
directions: our server handshake against their client, and ours against
their server. A proxy that is merely self-consistent connects to nothing.
gotd is a test-only dependency; the binary's dependency tree is unchanged.

Four bugs, three of which only a live run or a careful test would show:

- A short TCP write silently truncated messages. Telegram traffic is far
  larger than a socket buffer, so this is the difference between working and
  appearing intermittently broken. Sessions now write in full, and a test
  pushes 200KB through a pipe that accepts 64 bytes at a time.
- The listener kept a snapshot copy of the secrets, so revoking one in the
  dashboard changed nothing until a restart.
- Deleting the last secret quietly minted a replacement, handing out a
  credential the operator had just refused. Generation now happens at
  startup only.
- With a single secret configured I had skipped the transport tag check,
  reasoning there was nothing to disambiguate -- which meant serving anyone
  at all. The tag is the proof that the client knows the secret, so it is
  always checked now; a test asserts a junk tag is refused.

The transport tag doubles as the multi-secret check: 64 random bytes
decrypted with the wrong secret do not produce a recognisable tag, so one
read identifies which secret a client is using.

Verified live against a real Telegram client implementation: the handshake
completes, the proxy dials Telegram's own DC2, and revoking the secret
stops the next connection from being relayed at all.

Fake TLS is not in here. It is a separate wrapper around this stream, and
shipping obfuscated2 first means the thing Telegram apps actually accept is
working before the camouflage layer is attempted.
@coderabbitai

coderabbitai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7ae69f4a-a49d-44c5-868e-797ddae9f436
📥 Commits

Reviewing files that changed from the base of the PR and between 8fbc480 and 0a55e9d.

⛔ Files ignored due to path filters: 1
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing: 9
  • .env.example
  • README.md
  • config.json
  • database.go
  • go.mod
  • main.go
  • mtproto.go
  • mtproto_test.go
  • web/index.html
+------------------------------------+
| Zero-day? Zero chance on my watch. |
+------------------------------------+
  \
   \     /)/)
        ( '')
        /  |
      o(___)
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@GlobalTechInfo
GlobalTechInfo merged commit d61d54f into main Oct 17, 2026
2 of 3 checks passed
@GlobalTechInfo
GlobalTechInfo deleted the feat/mtproto branch October 17, 2026 15:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant