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个字符

init.go 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. package mtglib
  2. import (
  3. "context"
  4. "errors"
  5. "net"
  6. "net/http"
  7. "time"
  8. )
  9. var (
  10. ErrSecretEmpty = errors.New("secret is empty")
  11. ErrSecretInvalid = errors.New("secret is invalid")
  12. ErrNetworkIsNotDefined = errors.New("network is not defined")
  13. ErrAntiReplayCacheIsNotDefined = errors.New("anti-replay cache is not defined")
  14. ErrTimeAttackDetectorIsNotDefined = errors.New("time attack detector is not defined")
  15. ErrIPBlocklistIsNotDefined = errors.New("ip blocklist is not defined")
  16. ErrEventStreamIsNotDefined = errors.New("event stream is not defined")
  17. ErrLoggerIsNotDefined = errors.New("logger is not defined")
  18. )
  19. const (
  20. DefaultConcurrency = 4096
  21. DefaultBufferSize = 16 * 1024 // 16 kib
  22. DefaultDomainFrontingPort = 443
  23. DefaultIdleTimeout = time.Minute
  24. DefaultPreferIP = "prefer-ipv6"
  25. )
  26. type Network interface {
  27. Dial(network, address string) (net.Conn, error)
  28. DialContext(ctx context.Context, network, address string) (net.Conn, error)
  29. MakeHTTPClient(func(ctx context.Context, network, address string) (net.Conn, error)) *http.Client
  30. }
  31. // AntiReplayCache is an interface that is used to detect replay attacks
  32. // based on some traffic fingerprints.
  33. //
  34. // Replay attacks are probe attacks whose main goal is to identify if
  35. // server software can be classified in some way. For example, if you
  36. // send some HTTP request to a web server, then you can expect that this
  37. // server will respond with HTTP response back.
  38. //
  39. // There is a problem though. Let's imagine, that connection is
  40. // encrypted. Let's imagine, that it is encrypted with some static key
  41. // like ShadowSocks (https://shadowsocks.org/assets/whitepaper.pdf).
  42. // In that case, in theory, if you repeat the same bytes, you can get
  43. // the same responses. Let's imagine, that you've cracked the key. then
  44. // if you send the same bytes, you can decrypt a response and see its
  45. // structure. Based on its structure you can identify if this server is
  46. // SOCKS5, MTPROTO proxy etc.
  47. //
  48. // This is just one example, maybe not the best or not the most
  49. // relevant. In real life, different organizations use such replay
  50. // attacks to perform some reverse engineering of the proxy, do some
  51. // statical analysis to identify server software.
  52. //
  53. // There are many ways how to protect your proxy against them. One
  54. // is domain fronting which is a core part of mtg. Another one is to
  55. // collect some 'handshake fingerprints' and forbid duplication.
  56. //
  57. // So, it one is sending the same byte flow right after you (or a couple
  58. // of hours after), mtg should detect that and reject this connection
  59. // (or redirect to fronting domain).
  60. type AntiReplayCache interface {
  61. // Seen before checks if this set of bytes was observed before or
  62. // not. If it is required to store this information somewhere else,
  63. // then it has to do that.
  64. SeenBefore(data []byte) bool
  65. }
  66. // IPBlocklist filters requests based on IP address.
  67. //
  68. // If this filter has an IP address, then mtg closes a request without
  69. // reading anything from a socket. It also does not give such request to
  70. // a worker pool, so in worst cases you can expect that you invoke this
  71. // object more frequent than defined proxy concurrency.
  72. type IPBlocklist interface {
  73. // Contains checks if given IP address belongs to this blocklist If.
  74. // it is, a connection is terminated .
  75. Contains(net.IP) bool
  76. }
  77. type Event interface {
  78. StreamID() string
  79. Timestamp() time.Time
  80. }
  81. // EventStream is an abstraction that accepts a set of events produced
  82. // by mtg. Its main goal is to inject your logging or monitoring system.
  83. //
  84. // The idea is simple. When mtg works, it emits a set of events during
  85. // a lifecycle of the requestor: EventStart, EventFinish etc. mtg is a
  86. // producer which puts these events into a stream. Responsibility of
  87. // the stream is to deliver this event to consumers/observers. There
  88. // might be many different observers (for example, you want to have both
  89. // statsd and prometheus), mtg should know nothing about them.
  90. type EventStream interface {
  91. // Send delivers an event to observers. Given context has to be
  92. // respected. If the context is closed, all blocking operations should
  93. // be released ASAP.
  94. //
  95. // It is possible that context is closed but the message is delivered.
  96. // EventStream implementations should solve this issue somehow.
  97. Send(context.Context, Event)
  98. }
  99. type TimeAttackDetector interface {
  100. Valid(time.Time) error
  101. }
  102. // Logger defines an interface of the logger used by mtglib.
  103. //
  104. // Each logger has a name. It is possible to stack names to organize
  105. // poor-man namespaces. Also, each logger must be able to bind
  106. // parameters to avoid pushing them all the time.
  107. //
  108. // Example
  109. //
  110. // logger := SomeLogger{}
  111. // logger = logger.BindStr("ip", net.IP{127, 0, 0, 1})
  112. // logger.Info("Hello")
  113. //
  114. // In that case, ip is bound as a parameter. It is a great idea to
  115. // put this parameter somewhere in a log message.
  116. //
  117. // logger1 = logger.BindStr("param1", "11")
  118. // logger2 = logger.BindInt("param2", 11)
  119. //
  120. // logger1 should see no param2 and vice versa, logger2 should not see param1
  121. // If you attach a parameter to a logger, parents should not know about that.
  122. type Logger interface {
  123. Named(name string) Logger
  124. BindInt(name string, value int) Logger
  125. BindStr(name, value string) Logger
  126. Printf(format string, args ...interface{})
  127. Info(msg string)
  128. InfoError(msg string, err error)
  129. Warning(msg string)
  130. WarningError(msg string, err error)
  131. Debug(msg string)
  132. DebugError(msg string, err error)
  133. }