Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Highly opinionated MTPROTO proxy for Telegram

License

NotificationsYou must be signed in to change notification settings

9seconds/mtg

Repository files navigation

Highly-opinionated (ex-bullshit-free) MTPROTO proxy forTelegram.

CIcodecovGo Reference

If you use v1.0 or upgrade broke you proxy, please read the chapterVersion 2

Rationale

There are several available proxies for Telegram MTPROTO available. Hereare the most notable:

You can use any of these. They work great and all implementations havefeature parity now. This includes support of adtag, replay attackprotection, domain fronting, faketls, and so on. mtg has a similargoal: to give a possibility to connect to Telegram in a restricted,censored environment. But it does it slightly differently in detailsthat probably matter.

  • Resource-efficient

    It has to be resource-efficient. It does not mean that you will seethe smallest memory usage. It means that it will try to use allocatedresources in zero-waste mode, reusing as much memory as possible andso on.

  • Easily deployable

    I strongly believe that Telegram proxies should follow the way ofShadowSocks: promoted channels is a strangeway of doing business I suppose. I think the only viable way is tohave a proxy that can be restored anywhere easily.

  • A single secret

    I think that multiple secrets solve no problems and just complexsoftware. I also believe that in the case of throwout proxies, thisthe feature is a useless luxury.

  • No adtag support

    Please readVersion 2 chapter.

  • No management WebUI

    This is an implementation of a simple lightweight proxy. I won't do that.

  • Proxy chaining

    mtg has the support ofSOCKS5proxies. So, in theory, you can run this proxy as a frontendand route traffic viav2ray,Gost,Trojan, or any other projectyou like.

  • Native blocklist support

    Previously, this was delegated to theFireHOLproject or similar ones which track attacks and publish a list ofpotentially dangerous IPs. mtg has native support of such blocklists.

  • Can be used as a library

    mtg v2 was redesigned in a way so it can be embedded into yoursoftware (written in Golang) with a minimum effort + you can replacesome parts with those you want.

Version 2

If you use version 1.x before, you are probably noticed some majorbackward non-compatible details:

  1. Configuration file
  2. Removed support of adtag

For the configuration file, please check out the full example in thisrepository. It has a lot of comments and most of the options areoptional. We do have onlysecret andbind-to sections mandatory.Other sections in the example configuration file are filled with defaultvalues.

Adtag support was removed completely. This was done to debloat mtg andkeep it simple and obvious. Hopefully, this goal is achieved and thesource code is clean and straightforward enough.

I always was quite skeptical about adtag. In my POV, a proxy as a fatbig connectivity point for hundreds of clients is an illusion. If youwork in a censored environment, the first thing that authority does isIP blocking. For us, it means, those big proxies that can benefit fromhaving a pinned channel are going to be blocked in a minute.

Proxy has to be intimate. It has to be shared within a small group asa family or maybe your college friends. It has to have a small numberof connections and never publicly announced its presence. It has to flyunder the radar. If the proxy is detected, you need to be able to givea rebirth on a new IP address as soon as possible. I do no think thathaving some special channel for such a use case makes any sense.

But other details like replay attack protection, domain fronting,accurate FakeTLS implementation, IP blacklisting, and proxychaining matter here. If you work in censored perimeter likeGFW-protectedcountry, you probably want to have an MTPROTO proxy asa frontend that transports traffic via cloaked tunnelsmade byTrojan,Shadowsocks,v2ray,orGost. That's why you have to havethe support of chaining as a first-class citizen.

Yes, this is possible and doable with optional adtag support. But thetruth is that the MTPROTO proxy for Telegram is just a thing that eitherwork as a normal client (direct mode) or doing some RPC calls inTLlanguage (adtag support). Iunderstand the intention of the developers and I understand that theywere under high pressure fighting withRKN anddoing TON after that. Nothing is ideal. But for the proxy, it means thatsource code is full of complex non-trivial code which is required onlyto support a feature that we barely need.

So, to have a reasonable MTPROTO proxy, adtag support was removed. Thisis a rare chance in my career where software v2 debloats a previousversion. It feels so good :)

Version 1 and 2

I do continue to support both versions 1 and 2. But in a different mode.

Version 1 is now officially in maintenance mode. It means that I won'tmake any new features or improvements there. You can consider a featurefreeze there. No bugs are going to be fixed there except for criticalones. PRs are welcome though. The goal is to keep it working. It willget some periodical updates like updates to the new Golang version ofdependencies version bump, but that's mostly it.

If you want to have mtg withadtag support, please use version 1.

Version 2 is going to have all my love, active support, bug fixing, etc.It is under active development and maintenance.

This project has several main branches

  1. master branchcontains a bleeding edge. It may potentially have some featureswhich will break your source code.
  2. stable branch containsdumps of a master branch when we consider it 'stable'. This is abranch you probably want to pick.
  3. v2 has a developmentof the v2.x version. In theory, it is the same asmaster but thiswill change when we have v3.x.
  4. v1 has a version 1.x.

Getting started

Download a tool

Download binaries

Binaries can be downloaded from the release page. Also, you can downloaddocker image.

For the current version, please download like

docker pull nineseconds/mtg:2

For version 1:

docker pull nineseconds/mtg:1

You may also check bothDockerHub andGithubRegistry.Please do not chooselatest orstable if you want to avoidsurprises. Always choose some version tag.

Also, if you havego installed, you can always download this tool withgo get:

go install github.com/9seconds/mtg/v2@latest

Build from sources

git clone https://github.com/9seconds/mtg.gitcd mtgmake static

or for the docker image:

make docker

Generate secret

If you already have a secret in Base64 format or that, which starts withee,you can skip this chapter. Otherwise:

$mtg generate-secret google.com7ibaERuTSGPH1RdztfYnN4tnb29nbGUuY29t

or

$mtg generate-secret --hex google.comee473ce5d4958eb5f968c87680a23854a0676f6f676c652e636f6d

equivalent commands with docker:

$docker run --rm nineseconds/mtg:2 generate-secret google.com7ibaERuTSGPH1RdztfYnN4tnb29nbGUuY29t$docker run --rm nineseconds/mtg:2 generate-secret --hex google.comee473ce5d4958eb5f968c87680a23854a0676f6f676c652e636f6d

This secret is a keystone for a proxy and your password for a client.You need to keep it secured.

We recommend choosing a hostname wisely. Here we have agoogle.combut in reality, all providers can easily detect that this is not aGoogle. Google has a list of networks it officially uses and your IPaddress won't probably belong to it. It is a great idea to hide behindsome domain that has some relation to this IP address.

For example, you've bought a VPS fromDigitalOcean. Then it might be a good idea togenerate a secret fordigitalocean.com then.

Simple run mode

mtg supports 2 modes: simple and normal. Simple mode allows startingproxy with a small subset of configuration options you usually want tomodify. This is quite good for oneliners that you can copy-paste and donot bother about external files whatsoever.

Let's take a look:

Usage: mtg simple-run <bind-to> <secret>Run proxy without config file.Arguments:  <bind-to>    A host:port to bind proxy to.  <secret>     Proxy secret.Flags:  -h, --help                           Show context-sensitive help.  -v, --version                        Print version.  -d, --debug                          Run in debug mode.  -c, --concurrency=8192               Max number of concurrent connection to proxy.  -b, --tcp-buffer="4KB"               Size of TCP buffer to use.  -i, --prefer-ip="prefer-ipv6"        IP preference. By default we prefer IPv6 with fallback to IPv4.  -p, --domain-fronting-port=443       A port to access for domain fronting.  -n, --doh-ip=9.9.9.9                 IP address of DNS-over-HTTP to use.  -t, --timeout=10s                    Network timeout to use  -a, --antireplay-cache-size="1MB"    A size of anti-replay cache to use.

So, if you want to startup a proxy with CLI only, you can do something like

$mtg simple-run -n 1.1.1.1 -t 30s -a 512kib 127.0.0.1:3128 7hBO-dCS4EBzenlKbdLFxyNnb29nbGUuY29t

The rest of the configuration will be taken from default values. Buta simple run is fine if you do not have any special requirements orgranular tuning. If you want it, please checkout the configurationfiles.

Prepare a configuration file

Please checkout an example configuration file. All options except ofsecret andbind-to are optional. You can safely have this minimalconfiguration file:

secret ="ee473ce5d4958eb5f968c87680a23854a0676f6f676c652e636f6d"bind-to ="0.0.0.0:443"

This is enough to run the whole application. All otheroptions already have sensible defaults for the app at almost any scale.

Oh, the configuration is done inTOML format.

Run a proxy

Put a binary and a config into your webserver. Just for example,a binary goes to/usr/local/bin/mtg and configuration to/etc/mtg.toml.

Now you can create a systemd unit:

$cat /etc/systemd/system/mtg.service[Unit]Description=mtg - MTProto proxy serverDocumentation=https://github.com/9seconds/mtgAfter=network.target[Service]ExecStart=/usr/local/bin/mtg run /etc/mtg.tomlRestart=alwaysRestartSec=3DynamicUser=trueAmbientCapabilities=CAP_NET_BIND_SERVICE[Install]WantedBy=multi-user.target$sudo systemctl daemon-reload$sudo systemctlenable mtg$sudo systemctl start mtg

or you can run a docker image

docker run -d -v $PWD/config.toml:/config.toml -p 443:3128 --name mtg-proxy --restart=unless-stopped nineseconds/mtg:2

where443 is a host port (a port you want to connect to from aclient), and3128 is the one you have in your config in thebind-tosection.

Access a proxy

Now you can generate some useful links:

$mtg access /etc/mtg.toml{  "ipv4": {    "ip": "x.y.z.a",    "port": 3128,    "tg_url": "tg://proxy?...",    "tg_qrcode": "https://api.qrserver.com/v1/create-qr-code?data...",    "tme_url": "https://t.me/proxy?...",    "tme_qrcode": "https://api.qrserver.com/v1/create-qr-code?data..."  },  "secret": {    "hex": "...",    "base64": "..."  }}

or if you are using docker:

$dockerexec mtg-proxy /mtg access /config.toml

Metrics

Out of the box, mtg works withstatsd andPrometheus. Please check configuration fileexample to get how to set this integration up.

Here goes a list of metrics with their types but without a prefix.

NameTypeTagsDescription
client_connectionsgaugeip_familyCount of processing client connections.
telegram_connectionsgaugetelegram_ip,dcCount of connections to Telegram servers.
domain_fronting_connectionsgaugeip_familyCount of connections to fronting domain.
iplist_sizegaugeip_listA size of either allowlist or blocklist in use.
telegram_trafficcountertelegram_ip,dc,directionCount of bytes, transmitted to/from Telegram.
domain_fronting_trafficcounterdirectionCount of bytes, transmitted to/from fronting domain.
domain_frontingcounterCount of domain fronting events.
concurrency_limitedcounterCount of events, when client connection was rejected due to concurrency limit.
ip_blocklistedcounterip_listCount of events when client connection was rejected because IP was found in the blocklist.
replay_attackscounterCount of detected replay attacks.

Tag meaning:

NameValuesDescription
ip_familyipv4,ipv6A version of the IP protocol.
dcA number of the Telegram DC for a connection.
telegram_ipIP address of the Telegram server.
directionto_client,from_clientA direction of the traffic flow.
ip_listallowlist,blocklistA type of the IP list.

[8]ページ先頭

©2009-2025 Movatter.jp