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
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

init.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // mtglib defines a package with MTPROTO proxy.
  2. //
  3. // Since mtg itself is build as an example of how to work with mtglib, it worth
  4. // to telling a couple of words about a project organization.
  5. //
  6. // A core object of the project is [mtglib.Proxy]. This is a proxy you expect:
  7. // that one which you configure, set to serve on a listener and/or shutdown on
  8. // application termination.
  9. //
  10. // But it also has a core logic unrelated to Telegram per se: anti replay
  11. // cache, network connectivity (who knows, maybe you want to have a native
  12. // VMESS integration) and so on.
  13. //
  14. // You can supply such parts to a proxy with interfaces. The rest of the
  15. // packages in mtg define some default implementations of these interfaces. But
  16. // if you want to integrate it with, let say, influxdb, you can do it easily.
  17. package mtglib
  18. import (
  19. "context"
  20. "errors"
  21. "net"
  22. "net/http"
  23. "time"
  24. "github.com/9seconds/mtg/v2/essentials"
  25. )
  26. var (
  27. // ErrSecretEmpty is returned if you are trying to create a proxy but do not
  28. // provide a secret.
  29. ErrSecretEmpty = errors.New("secret is empty")
  30. // ErrSecretInvalid is returned if you are trying to create a proxy but secret
  31. // value is invalid (no host or payload are zeroes).
  32. ErrSecretInvalid = errors.New("secret is invalid")
  33. // ErrNetworkIsNotDefined is returned if you are trying to create a proxy but
  34. // network value is undefined.
  35. ErrNetworkIsNotDefined = errors.New("network is not defined")
  36. // ErrAntiReplayCacheIsNotDefined is returned if you are trying to create a
  37. // proxy but anti replay cache value is undefined.
  38. ErrAntiReplayCacheIsNotDefined = errors.New("anti-replay cache is not defined")
  39. // ErrIPBlocklistIsNotDefined is returned if you are trying to create a proxy
  40. // but ip blocklist instance is not defined.
  41. ErrIPBlocklistIsNotDefined = errors.New("ip blocklist is not defined")
  42. // ErrIPAllowlistIsNotDefined is returned if you are trying to create a proxy
  43. // but ip allowlist instance is not defined.
  44. ErrIPAllowlistIsNotDefined = errors.New("ip allowlist is not defined")
  45. // ErrEventStreamIsNotDefined is returned if you are trying to create a proxy
  46. // but event stream instance is not defined.
  47. ErrEventStreamIsNotDefined = errors.New("event stream is not defined")
  48. // ErrLoggerIsNotDefined is returned if you are trying to create a proxy but
  49. // logger is not defined.
  50. ErrLoggerIsNotDefined = errors.New("logger is not defined")
  51. )
  52. const (
  53. // DefaultConcurrency is a default max count of simultaneously connected
  54. // clients.
  55. DefaultConcurrency = 4096
  56. // DefaultBufferSize is a default size of a copy buffer.
  57. //
  58. // Deprecated: this setting no longer makes any effect.
  59. DefaultBufferSize = 16 * 1024 // 16 kib
  60. // DefaultDomainFrontingPort is a default port (HTTPS) to connect to in case
  61. // of probe-resistance activity.
  62. DefaultDomainFrontingPort = 443
  63. // DefaultIdleTimeout is a default timeout for closing a connection in case of
  64. // idling.
  65. //
  66. // Deprecated: no longer in use because of changed TCP relay algorithm.
  67. DefaultIdleTimeout = time.Minute
  68. // DefaultTolerateTimeSkewness is a default timeout for time skewness on a
  69. // faketls timeout verification.
  70. DefaultTolerateTimeSkewness = 3 * time.Second
  71. // DefaultPreferIP is a default value for Telegram IP connectivity preference.
  72. DefaultPreferIP = "prefer-ipv6"
  73. // SecretKeyLength defines a length of the secret bytes used by Telegram and a
  74. // proxy.
  75. SecretKeyLength = 16
  76. // ConnectionIDBytesLength defines a count of random bytes used to generate a
  77. // stream/connection ids.
  78. ConnectionIDBytesLength = 16
  79. // TCPRelayReadTimeout defines a max time period between two consecuitive
  80. // reads from Telegram after which connection will be terminated. This is
  81. // required to abort stale connections.
  82. TCPRelayReadTimeout = 20 * time.Second
  83. // DoppelGangerPerRaid defines a number of requests to each URL
  84. // per raid.
  85. DoppelGangerPerRaid = 10
  86. // DoppelGangerEach defines a time period between each crawl attempt.
  87. DoppelGangerEach = 6 * time.Hour
  88. )
  89. // Network defines a knowledge how to work with a network. It may sound fun but
  90. // it encapsulates all the knowledge how to properly establish connections to
  91. // remote hosts and configure HTTP clients.
  92. //
  93. // For example, if you want to use SOCKS5 proxy, you probably want to have all
  94. // traffic routed to this proxy: telegram connections, http requests and so on.
  95. // This knowledge is encapsulated into instances of such interface.
  96. //
  97. // mtglib uses Network for:
  98. // 1. Dialing to Telegram
  99. // 2. Dialing to front domain
  100. // 3. Doing HTTP requests (for example, for FireHOL ipblocklist).
  101. type Network interface {
  102. // Dial establishes context-free TCP connections.
  103. Dial(network, address string) (essentials.Conn, error)
  104. // DialContext dials using a context. This is a preferable way of
  105. // establishing TCP connections.
  106. DialContext(ctx context.Context, network, address string) (essentials.Conn, error)
  107. // MakeHTTPClient build an HTTP client with given dial function. If nothing is
  108. // provided, then DialContext of this interface is going to be used.
  109. MakeHTTPClient(func(ctx context.Context, network, address string) (essentials.Conn, error)) *http.Client
  110. // NativeDialer returns a configured instance of native dialer that
  111. // skips proxy connections or any other irrelevant settings.
  112. NativeDialer() *net.Dialer
  113. }
  114. // AntiReplayCache is an interface that is used to detect replay attacks based
  115. // on some traffic fingerprints.
  116. //
  117. // Replay attacks are probe attacks whose main goal is to identify if server
  118. // software can be classified in some way. For example, if you send some HTTP
  119. // request to a web server, then you can expect that this server will respond
  120. // with HTTP response back.
  121. //
  122. // There is a problem though. Let's imagine, that connection is encrypted.
  123. // Let's imagine, that it is encrypted with some static key like [ShadowSocks].
  124. // In that case, in theory, if you repeat the same bytes, you can get the same
  125. // responses. Let's imagine, that you've cracked the key. then if you send the
  126. // same bytes, you can decrypt a response and see its structure. Based on its
  127. // structure you can identify if this server is SOCKS5, MTPROTO proxy etc.
  128. //
  129. // This is just one example, maybe not the best or not the most relevant. In
  130. // real life, different organizations use such replay attacks to perform some
  131. // reverse engineering of the proxy, do some statical analysis to identify
  132. // server software.
  133. //
  134. // There are many ways how to protect your proxy against them. One is domain
  135. // fronting which is a core part of mtg. Another one is to collect some
  136. // 'handshake fingerprints' and forbid duplication.
  137. //
  138. // So, it one is sending the same byte flow right after you (or a couple of
  139. // hours after), mtg should detect that and reject this connection (or redirect
  140. // to fronting domain).
  141. //
  142. // [ShadowSocks]: https://shadowsocks.org/assets/whitepaper.pdf
  143. type AntiReplayCache interface {
  144. // Seen before checks if this set of bytes was observed before or not. If it
  145. // is required to store this information somewhere else, then it has to do
  146. // that.
  147. SeenBefore(data []byte) bool
  148. }
  149. // IPBlocklist filters requests based on IP address.
  150. //
  151. // If this filter has an IP address, then mtg closes a request without reading
  152. // anything from a socket. It also does not give such request to a worker pool,
  153. // so in worst cases you can expect that you invoke this object more frequent
  154. // than defined proxy concurrency.
  155. type IPBlocklist interface {
  156. // Contains checks if given IP address belongs to this blocklist If. it is, a
  157. // connection is terminated .
  158. Contains(net.IP) bool
  159. // Run starts a background update procedure for a blocklist
  160. Run(time.Duration)
  161. // Shutdown stops a blocklist. It is assumed that none will access it after.
  162. Shutdown()
  163. }
  164. // Event is a data structure which is populated during mtg request processing
  165. // lifecycle. Each request popluates many events:
  166. // 1. Client connected
  167. // 2. Request is finished
  168. // 3. Connection to Telegram server is established
  169. //
  170. // and so on. All these events are data structures but all of them must conform
  171. // the same interface.
  172. type Event interface {
  173. // StreamID returns an identifier of the stream, connection, request, you name
  174. // it. All events within the same stream returns the same stream id.
  175. StreamID() string
  176. // Timestamp returns a timestamp when this event was generated.
  177. Timestamp() time.Time
  178. }
  179. // EventStream is an abstraction that accepts a set of events produced by mtg.
  180. // Its main goal is to inject your logging or monitoring system.
  181. //
  182. // The idea is simple. When mtg works, it emits a set of events during a
  183. // lifecycle of the requestor: EventStart, EventFinish etc. mtg is a producer
  184. // which puts these events into a stream. Responsibility of the stream is to
  185. // deliver this event to consumers/observers. There might be many different
  186. // observers (for example, you want to have both statsd and prometheus), mtg
  187. // should know nothing about them.
  188. type EventStream interface {
  189. // Send delivers an event to observers. Given context has to be respected. If
  190. // the context is closed, all blocking operations should be released ASAP.
  191. //
  192. // It is possible that context is closed but the message is delivered.
  193. // EventStream implementations should solve this issue somehow.
  194. Send(context.Context, Event)
  195. }
  196. // Logger defines an interface of the logger used by mtglib.
  197. //
  198. // Each logger has a name. It is possible to stack names to organize poor-man
  199. // namespaces. Also, each logger must be able to bind parameters to avoid
  200. // pushing them all the time.
  201. //
  202. // Example
  203. //
  204. // logger := SomeLogger{} logger = logger.BindStr("ip", net.IP{127, 0, 0, 1})
  205. // logger.Info("Hello")
  206. //
  207. // In that case, ip is bound as a parameter. It is a great idea to put this
  208. // parameter somewhere in a log message.
  209. //
  210. // logger1 = logger.BindStr("param1", "11") logger2 = logger.BindInt("param2",
  211. // 11)
  212. //
  213. // logger1 should see no param2 and vice versa, logger2 should not see param1
  214. // If you attach a parameter to a logger, parents should not know about that.
  215. type Logger interface {
  216. // Named returns a new logger with a bound name. Name chaining is allowed and
  217. // appreciated.
  218. Named(name string) Logger
  219. // BindInt binds new integer parameter to a new logger instance.
  220. BindInt(name string, value int) Logger
  221. // BindStr binds new string parameter to a new logger instance.
  222. BindStr(name, value string) Logger
  223. // BindJSON binds a new JSON-encoded string to a new logger instance.
  224. BindJSON(name, value string) Logger
  225. // Printf is to support log.Logger behavior.
  226. Printf(format string, args ...any)
  227. // Info puts a message about some normal situation.
  228. Info(msg string)
  229. // InfoError puts a message about some normal situation but this situation is
  230. // related to a given error.
  231. InfoError(msg string, err error)
  232. // Warning puts a message about some extraordinary situation worth to look at.
  233. Warning(msg string)
  234. // WarningError puts a message about some extraordinary situation worth to
  235. // look at. This situation is related to a given error.
  236. WarningError(msg string, err error)
  237. // Debug puts a message useful for debugging only.
  238. Debug(msg string)
  239. // Debug puts a message useful for debugging only. This message is related to
  240. // a given error.
  241. DebugError(msg string, err error)
  242. }