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
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

proxy.go 9.9KB

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