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 10KB

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