MTProto 中转

MTProto

MTProtoTelegram 制定的,在 Telegram 服务端 API 与手机客户端之间的通信协议,该协议使用现代密码学作为安全背书,旨在提供安全的 Telegram 通信链路。

MTProto 2.0 图源: Telegram

官方也基于这套协议开源了一套对应的代理服务:

MTProxy

MTProto 在大陆已不可用,此文通过使用 ss-redir 与 ipset + iptables 转发的结合,将 MTProto 的流量通过 Shadowsocks Redir 透明代理转发到 Telegram 服务器中。

获取 Telegram 服务器 IP

可通过 Hurricane Electric 的 BGP 工具,获取到 Telegram 的服务端 IP 地址,从而得到转发目标
Telegram 目前包含三个自治域,分别为 AS59930, AS62014AS62041

通过 BGPView.io 也可以获取 API 友好的数据,得到服务器 IP 段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/python
# -*- coding: utf-8 -*-

# You can also run this code on repl.it
# https://repl.it/repls/UnwelcomeCarelessNumbers

from __future__ import absolute_import, division, \
print_function, unicode_literals

import requests
import json

TELEGRAM_AS = [59930, 62014, 62041]
API_BASE = 'https://api.bgpview.io/asn/{asn}/prefixes'

for asn in TELEGRAM_AS:
as_prefixes = requests.get(API_BASE.format(asn=asn))
as_prefixes = json.loads(as_prefixes.content)
for cidr in as_prefixes['data']['ipv4_prefixes']:
print(cidr['prefix'])

设置 IPSet

之后,对得到的结果写 IP Set:

如果没有安装 `ipset`,可以用以下方式安装:

CentOS: yum install ipset
Debian/Ubuntu: apt install ipset
ArchLinux: pacman -S ipset

1
2
3
ipset create telegram hash:net -!
# Repeat for all results
ipset add telegram x.x.x.x/xx -!

最后,使用 iptables 对这个 set 做 pre-routeing & output 重定向,其中 1080 是 ss-redir 的端口:

1
2
iptables -t nat -A PREROUTING -p tcp -m set --match-set telegram dst -j REDIRECT --to-ports 1080
iptables -t nat -A OUTPUT -p tcp -m set --match-set telegram dst -j REDIRECT --to-ports 1080

建立 MTProto

可以选用官方版,也可以选用 mtprotoproxy(Python) 版:

alexbers/mtprotoproxy

本文选用 Python 版的 mtprotoproxy, Clone 后直接使用 python3 mtprotoproxy.py 即可运行。
或者也可以使用 Docker(compose) 方式启动 docker-compose up --build -d

后续收尾工作

持久化 iptables 配置

使用 iptables-save/iptables-restore 命令即可。

持久化 ipset 配置

可以使用 ipset save 把集合保存到任意地方:

1
ipset save > /etc/ipset.conf.d/telegram.conf
Author

Jason

Posted on

11/06/19

Updated on

10/12/20

Licensed under

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×