Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

proxy.go 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. package mtglib
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "strconv"
  8. "sync"
  9. "time"
  10. "github.com/9seconds/mtg/v2/essentials"
  11. "github.com/9seconds/mtg/v2/mtglib/internal/dc"
  12. "github.com/9seconds/mtg/v2/mtglib/internal/faketls"
  13. "github.com/9seconds/mtg/v2/mtglib/internal/faketls/record"
  14. "github.com/9seconds/mtg/v2/mtglib/internal/obfuscation"
  15. "github.com/9seconds/mtg/v2/mtglib/internal/relay"
  16. "github.com/panjf2000/ants/v2"
  17. )
  18. // Proxy is an MTPROTO proxy structure.
  19. type Proxy struct {
  20. ctx context.Context
  21. ctxCancel context.CancelFunc
  22. streamWaitGroup sync.WaitGroup
  23. allowFallbackOnUnknownDC bool
  24. tolerateTimeSkewness time.Duration
  25. domainFrontingPort int
  26. domainFrontingIP string
  27. domainFrontingProxyProtocol bool
  28. workerPool *ants.PoolWithFunc
  29. telegram *dc.Telegram
  30. configUpdater *dc.PublicConfigUpdater
  31. clientObfuscatror obfuscation.Obfuscator
  32. secret Secret
  33. network Network
  34. antiReplayCache AntiReplayCache
  35. blocklist IPBlocklist
  36. allowlist IPBlocklist
  37. eventStream EventStream
  38. logger Logger
  39. }
  40. // DomainFrontingAddress returns a host:port pair for a fronting domain.
  41. // If DomainFrontingIP is set, it is used instead of resolving the hostname.
  42. func (p *Proxy) DomainFrontingAddress() string {
  43. host := p.secret.Host
  44. if p.domainFrontingIP != "" {
  45. host = p.domainFrontingIP
  46. }
  47. return net.JoinHostPort(host, strconv.Itoa(p.domainFrontingPort))
  48. }
  49. // ServeConn serves a connection. We do not check IP blocklist and concurrency
  50. // limit here.
  51. func (p *Proxy) ServeConn(conn essentials.Conn) {
  52. p.streamWaitGroup.Add(1)
  53. defer p.streamWaitGroup.Done()
  54. ctx := newStreamContext(p.ctx, p.logger, conn)
  55. defer ctx.Close()
  56. go func() {
  57. <-ctx.Done()
  58. ctx.Close()
  59. }()
  60. p.eventStream.Send(ctx, NewEventStart(ctx.streamID, ctx.ClientIP()))
  61. ctx.logger.Info("Stream has been started")
  62. defer func() {
  63. p.eventStream.Send(ctx, NewEventFinish(ctx.streamID))
  64. ctx.logger.Info("Stream has been finished")
  65. }()
  66. if !p.doFakeTLSHandshake(ctx) {
  67. return
  68. }
  69. if err := p.doObfuscatedHandshake(ctx); err != nil {
  70. p.logger.InfoError("obfuscated handshake is failed", err)
  71. return
  72. }
  73. if err := p.doTelegramCall(ctx); err != nil {
  74. p.logger.WarningError("cannot dial to telegram", err)
  75. return
  76. }
  77. relay.Relay(
  78. ctx,
  79. ctx.logger.Named("relay"),
  80. ctx.telegramConn,
  81. ctx.clientConn,
  82. )
  83. }
  84. // Serve starts a proxy on a given listener.
  85. func (p *Proxy) Serve(listener net.Listener) error {
  86. p.streamWaitGroup.Add(1)
  87. defer p.streamWaitGroup.Done()
  88. for {
  89. conn, err := listener.Accept()
  90. if err != nil {
  91. select {
  92. case <-p.ctx.Done():
  93. return nil
  94. default:
  95. return fmt.Errorf("cannot accept a new connection: %w", err)
  96. }
  97. }
  98. ipAddr := conn.RemoteAddr().(*net.TCPAddr).IP //nolint: forcetypeassert
  99. logger := p.logger.BindStr("ip", ipAddr.String())
  100. if !p.allowlist.Contains(ipAddr) {
  101. conn.Close() //nolint: errcheck
  102. logger.Info("ip was rejected by allowlist")
  103. p.eventStream.Send(p.ctx, NewEventIPAllowlisted(ipAddr))
  104. continue
  105. }
  106. if p.blocklist.Contains(ipAddr) {
  107. conn.Close() //nolint: errcheck
  108. logger.Info("ip was blacklisted")
  109. p.eventStream.Send(p.ctx, NewEventIPBlocklisted(ipAddr))
  110. continue
  111. }
  112. err = p.workerPool.Invoke(conn)
  113. switch {
  114. case err == nil:
  115. case errors.Is(err, ants.ErrPoolClosed):
  116. return nil
  117. case errors.Is(err, ants.ErrPoolOverload):
  118. logger.Info("connection was concurrency limited")
  119. p.eventStream.Send(p.ctx, NewEventConcurrencyLimited())
  120. }
  121. }
  122. }
  123. // Shutdown 'gracefully' shutdowns all connections. Please remember that it
  124. // does not close an underlying listener.
  125. func (p *Proxy) Shutdown() {
  126. p.ctxCancel()
  127. p.streamWaitGroup.Wait()
  128. p.workerPool.Release()
  129. p.configUpdater.Wait()
  130. p.allowlist.Shutdown()
  131. p.blocklist.Shutdown()
  132. }
  133. func (p *Proxy) doFakeTLSHandshake(ctx *streamContext) bool {
  134. rec := record.AcquireRecord()
  135. defer record.ReleaseRecord(rec)
  136. rewind := newConnRewind(ctx.clientConn)
  137. if err := rec.Read(rewind); err != nil {
  138. p.logger.InfoError("cannot read client hello", err)
  139. p.doDomainFronting(ctx, rewind)
  140. return false
  141. }
  142. hello, err := faketls.ParseClientHello(p.secret.Key[:], rec.Payload.Bytes())
  143. if err != nil {
  144. p.logger.InfoError("cannot parse client hello", err)
  145. p.doDomainFronting(ctx, rewind)
  146. return false
  147. }
  148. if err := hello.Valid(p.secret.Host, p.tolerateTimeSkewness); err != nil {
  149. p.logger.
  150. BindStr("hostname", hello.Host).
  151. BindStr("hello-time", hello.Time.String()).
  152. InfoError("invalid faketls client hello", err)
  153. p.doDomainFronting(ctx, rewind)
  154. return false
  155. }
  156. if p.antiReplayCache.SeenBefore(hello.SessionID) {
  157. p.logger.Warning("replay attack has been detected!")
  158. p.eventStream.Send(p.ctx, NewEventReplayAttack(ctx.streamID))
  159. p.doDomainFronting(ctx, rewind)
  160. return false
  161. }
  162. if err := faketls.SendWelcomePacket(rewind, p.secret.Key[:], hello); err != nil {
  163. p.logger.InfoError("cannot send welcome packet", err)
  164. return false
  165. }
  166. ctx.clientConn = &faketls.Conn{
  167. Conn: ctx.clientConn,
  168. }
  169. return true
  170. }
  171. func (p *Proxy) doObfuscatedHandshake(ctx *streamContext) error {
  172. dc, conn, err := p.clientObfuscatror.ReadHandshake(ctx.clientConn)
  173. if err != nil {
  174. return fmt.Errorf("cannot process client handshake: %w", err)
  175. }
  176. ctx.dc = dc
  177. ctx.clientConn = conn
  178. ctx.logger = ctx.logger.BindInt("dc", dc)
  179. return nil
  180. }
  181. func (p *Proxy) doTelegramCall(ctx *streamContext) error {
  182. dcid := ctx.dc
  183. addresses := p.telegram.GetAddresses(dcid)
  184. if len(addresses) == 0 && p.allowFallbackOnUnknownDC {
  185. ctx.logger = ctx.logger.BindInt("original_dc", dcid)
  186. ctx.logger.Warning("unknown DC, fallbacks")
  187. ctx.dc = dc.DefaultDC
  188. addresses = p.telegram.GetAddresses(dc.DefaultDC)
  189. }
  190. var (
  191. conn essentials.Conn
  192. err error
  193. foundAddr dc.Addr
  194. )
  195. for _, addr := range addresses {
  196. conn, err = p.network.Dial(addr.Network, addr.Address)
  197. if err == nil {
  198. foundAddr = addr
  199. break
  200. }
  201. }
  202. if err != nil {
  203. return fmt.Errorf("no addresses to call: %w", err)
  204. }
  205. if conn == nil {
  206. return fmt.Errorf("no available addresses for DC %d", ctx.dc)
  207. }
  208. tgConn, err := foundAddr.Obfuscator.SendHandshake(conn, ctx.dc)
  209. if err != nil {
  210. conn.Close() // nolint: errcheck
  211. return fmt.Errorf("cannot perform server handshake: %w", err)
  212. }
  213. ctx.telegramConn = connTraffic{
  214. Conn: tgConn,
  215. streamID: ctx.streamID,
  216. stream: p.eventStream,
  217. ctx: ctx,
  218. }
  219. p.eventStream.Send(ctx,
  220. NewEventConnectedToDC(ctx.streamID,
  221. conn.RemoteAddr().(*net.TCPAddr).IP, //nolint: forcetypeassert
  222. ctx.dc),
  223. )
  224. return nil
  225. }
  226. func (p *Proxy) doDomainFronting(ctx *streamContext, conn *connRewind) {
  227. p.eventStream.Send(p.ctx, NewEventDomainFronting(ctx.streamID))
  228. conn.Rewind()
  229. frontConn, err := p.network.DialContext(ctx, "tcp", p.DomainFrontingAddress())
  230. if err != nil {
  231. p.logger.WarningError("cannot dial to the fronting domain", err)
  232. return
  233. }
  234. if p.domainFrontingProxyProtocol {
  235. frontConn = newConnProxyProtocol(ctx.clientConn, frontConn)
  236. }
  237. frontConn = connTraffic{
  238. Conn: frontConn,
  239. ctx: ctx,
  240. streamID: ctx.streamID,
  241. stream: p.eventStream,
  242. }
  243. relay.Relay(
  244. ctx,
  245. ctx.logger.Named("domain-fronting"),
  246. frontConn,
  247. conn,
  248. )
  249. }
  250. // NewProxy makes a new proxy instance.
  251. func NewProxy(opts ProxyOpts) (*Proxy, error) {
  252. if err := opts.valid(); err != nil {
  253. return nil, fmt.Errorf("invalid settings: %w", err)
  254. }
  255. tg, err := dc.New(opts.getPreferIP())
  256. if err != nil {
  257. return nil, fmt.Errorf("cannot build telegram dc fetcher: %w", err)
  258. }
  259. ctx, cancel := context.WithCancel(context.Background())
  260. logger := opts.getLogger("proxy")
  261. updatersLogger := logger.Named("telegram-updaters")
  262. proxy := &Proxy{
  263. ctx: ctx,
  264. ctxCancel: cancel,
  265. secret: opts.Secret,
  266. network: opts.Network,
  267. antiReplayCache: opts.AntiReplayCache,
  268. blocklist: opts.IPBlocklist,
  269. allowlist: opts.IPAllowlist,
  270. eventStream: opts.EventStream,
  271. logger: logger,
  272. domainFrontingPort: opts.getDomainFrontingPort(),
  273. domainFrontingIP: opts.DomainFrontingIP,
  274. tolerateTimeSkewness: opts.getTolerateTimeSkewness(),
  275. allowFallbackOnUnknownDC: opts.AllowFallbackOnUnknownDC,
  276. telegram: tg,
  277. configUpdater: dc.NewPublicConfigUpdater(
  278. tg,
  279. updatersLogger.Named("public-config"),
  280. opts.Network.MakeHTTPClient(nil),
  281. ),
  282. clientObfuscatror: obfuscation.Obfuscator{
  283. Secret: opts.Secret.Key[:],
  284. },
  285. domainFrontingProxyProtocol: opts.DomainFrontingProxyProtocol,
  286. }
  287. if opts.AutoUpdate {
  288. proxy.configUpdater.Run(ctx, dc.PublicConfigUpdateURLv4, "tcp4")
  289. proxy.configUpdater.Run(ctx, dc.PublicConfigUpdateURLv6, "tcp6")
  290. }
  291. pool, err := ants.NewPoolWithFunc(opts.getConcurrency(),
  292. func(arg any) {
  293. proxy.ServeConn(arg.(essentials.Conn)) //nolint: forcetypeassert
  294. },
  295. ants.WithLogger(opts.getLogger("ants")),
  296. ants.WithNonblocking(true))
  297. if err != nil {
  298. panic(err)
  299. }
  300. proxy.workerPool = pool
  301. return proxy, nil
  302. }