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
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

init.go 10KB

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