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
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

init.go 9.9KB

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