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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. package fake
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "crypto/subtle"
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net"
  12. "slices"
  13. "time"
  14. "github.com/9seconds/mtg/v2/mtglib/internal/tls"
  15. )
  16. const (
  17. TypeHandshakeClient = 0x01
  18. RandomLen = 32
  19. // record_type(1) + version(2) + size(2) + handshake_type(1) + uint24_length(3) + client_version(2)
  20. RandomOffset = 1 + 2 + 2 + 1 + 3 + 2
  21. sniDNSNamesListType = 0
  22. // maxContinuationRecords limits the number of continuation TLS records
  23. // that reassembleTLSHandshake will read. This prevents resource exhaustion
  24. // from adversarial fragmentation.
  25. maxContinuationRecords = 10
  26. )
  27. var (
  28. emptyRandom = [RandomLen]byte{}
  29. extTypeSNI = [2]byte{}
  30. )
  31. type ClientHello struct {
  32. Random [RandomLen]byte
  33. SessionID []byte
  34. CipherSuite uint16
  35. }
  36. func ReadClientHello(
  37. conn net.Conn,
  38. secret []byte,
  39. hostname string,
  40. tolerateTimeSkewness time.Duration,
  41. ) (*ClientHello, error) {
  42. if err := conn.SetReadDeadline(time.Now().Add(ClientHelloReadTimeout)); err != nil {
  43. return nil, fmt.Errorf("cannot set read deadline: %w", err)
  44. }
  45. defer conn.SetReadDeadline(resetDeadline) //nolint: errcheck
  46. // This is how FakeTLS is organized:
  47. // 1. We create sha256 HMAC with a given secret
  48. // 2. We dump there a whole TLS frame except of the fact that random
  49. // is filled with all zeroes
  50. // 3. Digest is computed. This digest should be XORed with
  51. // original client random
  52. // 4. New digest should be all 0 except of last 4 bytes
  53. // 5. Last 4 bytes are little endian uint32 of UNIX timestamp when
  54. // this message was created.
  55. reassembled, err := reassembleTLSHandshake(conn)
  56. if err != nil {
  57. return nil, fmt.Errorf("cannot reassemble TLS records: %w", err)
  58. }
  59. handshakeCopyBuf := &bytes.Buffer{}
  60. reader := io.TeeReader(reassembled, handshakeCopyBuf)
  61. // Skip the TLS record header (validated during reassembly).
  62. // The header still flows through TeeReader into handshakeCopyBuf for HMAC.
  63. if _, err = io.CopyN(io.Discard, reader, tls.SizeHeader); err != nil {
  64. return nil, fmt.Errorf("cannot skip tls header: %w", err)
  65. }
  66. reader, err = parseHandshakeHeader(reader)
  67. if err != nil {
  68. return nil, fmt.Errorf("cannot parse handshake header: %w", err)
  69. }
  70. hello, err := parseHandshake(reader)
  71. if err != nil {
  72. return nil, fmt.Errorf("cannot parse handshake: %w", err)
  73. }
  74. sniHostnames, err := parseSNI(reader)
  75. if err != nil {
  76. return nil, fmt.Errorf("cannot parse SNI: %w", err)
  77. }
  78. if !slices.Contains(sniHostnames, hostname) {
  79. return nil, fmt.Errorf("cannot find %s in %v", hostname, sniHostnames)
  80. }
  81. digest := hmac.New(sha256.New, secret)
  82. // we write a copy of the handshake with client random all nullified.
  83. digest.Write(handshakeCopyBuf.Next(RandomOffset))
  84. handshakeCopyBuf.Next(RandomLen)
  85. digest.Write(emptyRandom[:])
  86. digest.Write(handshakeCopyBuf.Bytes())
  87. computed := digest.Sum(nil)
  88. for i := range RandomLen {
  89. computed[i] ^= hello.Random[i]
  90. }
  91. if subtle.ConstantTimeCompare(emptyRandom[:RandomLen-4], computed[:RandomLen-4]) != 1 {
  92. return nil, ErrBadDigest
  93. }
  94. timestamp := int64(binary.LittleEndian.Uint32(computed[RandomLen-4:]))
  95. createdAt := time.Unix(timestamp, 0)
  96. if tdiff := time.Since(createdAt).Abs(); tdiff > tolerateTimeSkewness {
  97. return nil, fmt.Errorf("timestamp %q is too old %s", createdAt, tdiff)
  98. }
  99. return hello, nil
  100. }
  101. // reassembleTLSHandshake reads one or more TLS records from conn,
  102. // validates the record type and version, and reassembles fragmented
  103. // handshake payloads into a single TLS record.
  104. //
  105. // Per RFC 5246 Section 6.2.1, handshake messages may be fragmented
  106. // across multiple TLS records. DPI bypass tools like ByeDPI use this
  107. // to evade censorship.
  108. //
  109. // The returned buffer contains the full TLS record (header + payload)
  110. // so that callers can include the header in HMAC computation.
  111. func reassembleTLSHandshake(conn io.Reader) (*bytes.Buffer, error) {
  112. header := [tls.SizeHeader]byte{}
  113. if _, err := io.ReadFull(conn, header[:]); err != nil {
  114. return nil, fmt.Errorf("cannot read record header: %w", err)
  115. }
  116. length := int64(binary.BigEndian.Uint16(header[3:]))
  117. payload := &bytes.Buffer{}
  118. if _, err := io.CopyN(payload, conn, length); err != nil {
  119. return nil, fmt.Errorf("cannot read record payload: %w", err)
  120. }
  121. if header[0] != tls.TypeHandshake {
  122. return nil, fmt.Errorf("unexpected record type %#x", header[0])
  123. }
  124. if header[1] != 3 || header[2] != 1 {
  125. return nil, fmt.Errorf("unexpected protocol version %#x %#x", header[1], header[2])
  126. }
  127. // Reassemble fragmented payload. continuationCount caps the total
  128. // number of continuation records across both phases below.
  129. continuationCount := 0
  130. // Phase 1: read continuation records until we have at least the
  131. // 4-byte handshake header (type + uint24 length) to determine the
  132. // expected total size.
  133. for ; payload.Len() < 4 && continuationCount < maxContinuationRecords; continuationCount++ {
  134. prevLen := payload.Len()
  135. if err := readContinuationRecord(conn, payload); err != nil {
  136. payload.Truncate(prevLen) // discard partial data on error
  137. if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
  138. break // no more records — let downstream parsing handle what we have
  139. }
  140. return nil, err
  141. }
  142. }
  143. // Phase 2: we know the expected handshake size — read remaining
  144. // continuation records until the payload is complete.
  145. if payload.Len() >= 4 {
  146. p := payload.Bytes()
  147. expectedTotal := 4 + (int(p[1])<<16 | int(p[2])<<8 | int(p[3]))
  148. if expectedTotal > 0xFFFF {
  149. return nil, fmt.Errorf("handshake message too large: %d bytes", expectedTotal)
  150. }
  151. for ; payload.Len() < expectedTotal && continuationCount < maxContinuationRecords; continuationCount++ {
  152. if err := readContinuationRecord(conn, payload); err != nil {
  153. return nil, err
  154. }
  155. }
  156. if payload.Len() < expectedTotal {
  157. return nil, fmt.Errorf("cannot reassemble handshake: too many continuation records")
  158. }
  159. payload.Truncate(expectedTotal)
  160. }
  161. if payload.Len() > 0xFFFF {
  162. return nil, fmt.Errorf("reassembled payload too large: %d bytes", payload.Len())
  163. }
  164. // Reconstruct a single TLS record with the reassembled payload.
  165. result := &bytes.Buffer{}
  166. result.Grow(tls.SizeHeader + payload.Len())
  167. result.Write(header[:3])
  168. binary.Write(result, binary.BigEndian, uint16(payload.Len())) //nolint:errcheck // bytes.Buffer.Write never fails
  169. result.Write(payload.Bytes())
  170. return result, nil
  171. }
  172. // readContinuationRecord reads the next TLS record header and appends its
  173. // full payload to dst. It returns an error if the record is not a handshake
  174. // record.
  175. func readContinuationRecord(conn io.Reader, dst *bytes.Buffer) error {
  176. nextHeader := [tls.SizeHeader]byte{}
  177. if _, err := io.ReadFull(conn, nextHeader[:]); err != nil {
  178. return fmt.Errorf("cannot read continuation record header: %w", err)
  179. }
  180. if nextHeader[0] != tls.TypeHandshake {
  181. return fmt.Errorf("unexpected continuation record type %#x", nextHeader[0])
  182. }
  183. if nextHeader[1] != 3 || nextHeader[2] != 1 {
  184. return fmt.Errorf("unexpected continuation record version %#x %#x", nextHeader[1], nextHeader[2])
  185. }
  186. nextLength := int64(binary.BigEndian.Uint16(nextHeader[3:]))
  187. if nextLength == 0 {
  188. return fmt.Errorf("zero-length continuation record")
  189. }
  190. if _, err := io.CopyN(dst, conn, nextLength); err != nil {
  191. return fmt.Errorf("cannot read continuation record payload: %w", err)
  192. }
  193. return nil
  194. }
  195. func parseHandshakeHeader(r io.Reader) (io.Reader, error) {
  196. // type(1) + size(3 / uint24)
  197. // 01 - handshake message type 0x01 (client hello)
  198. // 00 00 f4 - 0xF4 (244) bytes of client hello data follows
  199. header := [1 + 3]byte{}
  200. if _, err := io.ReadFull(r, header[:]); err != nil {
  201. return nil, fmt.Errorf("cannot read handshake header: %w", err)
  202. }
  203. if header[0] != TypeHandshakeClient {
  204. return nil, fmt.Errorf("incorrect handshake type: %#x", header[0])
  205. }
  206. // unfortunately there is not uint24 in golang, so we just reust header
  207. header[0] = 0
  208. length := int64(binary.BigEndian.Uint32(header[:]))
  209. buf := &bytes.Buffer{}
  210. _, err := io.CopyN(buf, r, length)
  211. return buf, err
  212. }
  213. func parseHandshake(r io.Reader) (*ClientHello, error) {
  214. // A protocol version of "3,3" (meaning TLS 1.2) is given.
  215. header := [2]byte{}
  216. if _, err := io.ReadFull(r, header[:]); err != nil {
  217. return nil, fmt.Errorf("cannot read client version: %w", err)
  218. }
  219. hello := &ClientHello{}
  220. if _, err := io.ReadFull(r, hello.Random[:]); err != nil {
  221. return nil, fmt.Errorf("cannot read client random: %w", err)
  222. }
  223. if _, err := io.ReadFull(r, header[:1]); err != nil {
  224. return nil, fmt.Errorf("cannot read session ID length: %w", err)
  225. }
  226. hello.SessionID = make([]byte, int(header[0]))
  227. if _, err := io.ReadFull(r, hello.SessionID); err != nil {
  228. return nil, fmt.Errorf("cannot read session id: %w", err)
  229. }
  230. if _, err := io.ReadFull(r, header[:]); err != nil {
  231. return nil, fmt.Errorf("cannot read cipher suite length: %w", err)
  232. }
  233. cipherSuiteLen := int64(binary.BigEndian.Uint16(header[:]))
  234. // we do not care about picking up any cipher. we pick the first one,
  235. // so it is always should be present.
  236. if _, err := io.ReadFull(r, header[:]); err != nil {
  237. return nil, fmt.Errorf("cannot read first cipher suite: %w", err)
  238. }
  239. hello.CipherSuite = binary.BigEndian.Uint16(header[:])
  240. if _, err := io.CopyN(io.Discard, r, cipherSuiteLen-2); err != nil {
  241. return nil, fmt.Errorf("cannot skip remaining cipher suites: %w", err)
  242. }
  243. if _, err := io.ReadFull(r, header[:1]); err != nil {
  244. return nil, fmt.Errorf("cannot read compression methods length: %w", err)
  245. }
  246. if _, err := io.CopyN(io.Discard, r, int64(header[0])); err != nil {
  247. return nil, fmt.Errorf("cannot skip compression methods: %w", err)
  248. }
  249. return hello, nil
  250. }
  251. func parseSNI(r io.Reader) ([]string, error) {
  252. header := [2]byte{}
  253. if _, err := io.ReadFull(r, header[:]); err != nil {
  254. return nil, fmt.Errorf("cannot read length of TLS extensions: %w", err)
  255. }
  256. extensionsLength := int64(binary.BigEndian.Uint16(header[:]))
  257. buf := &bytes.Buffer{}
  258. buf.Grow(int(extensionsLength))
  259. if _, err := io.CopyN(buf, r, extensionsLength); err != nil {
  260. return nil, fmt.Errorf("cannot read extensions: %w", err)
  261. }
  262. for buf.Len() > 0 {
  263. // 00 00 - assigned value for extension "server name"
  264. // 00 18 - 0x18 (24) bytes of "server name" extension data follows
  265. // 00 16 - 0x16 (22) bytes of first (and only) list entry follows
  266. // 00 - list entry is type 0x00 "DNS hostname"
  267. // 00 13 - 0x13 (19) bytes of hostname follows
  268. // 65 78 61 ... 6e 65 74 - "example.ulfheim.net"
  269. // 00 00 - assigned value for extension "server name"
  270. extTypeB := buf.Next(2)
  271. if len(extTypeB) != 2 {
  272. return nil, fmt.Errorf("cannot read extension type: %v", extTypeB)
  273. }
  274. // 00 18 - 0x18 (24) bytes of "server name" extension data follows
  275. lengthB := buf.Next(2)
  276. if len(lengthB) != 2 {
  277. return nil, fmt.Errorf("cannot read extension %v length: %v", extTypeB, lengthB)
  278. }
  279. length := int(binary.BigEndian.Uint16(lengthB))
  280. extDataB := buf.Next(length)
  281. if len(extDataB) != length {
  282. return nil, fmt.Errorf("cannot read extension %v data: len %d != %d", extTypeB, length, len(extDataB))
  283. }
  284. if !bytes.Equal(extTypeB, extTypeSNI[:]) {
  285. continue
  286. }
  287. buf.Reset()
  288. buf.Write(extDataB)
  289. // 00 16 - 0x16 (22) bytes of first (and only) list entry follows
  290. lengthB = buf.Next(2)
  291. if len(lengthB) != 2 {
  292. return nil, fmt.Errorf("cannot read the length of the SNI record: %v", lengthB)
  293. }
  294. length = int(binary.BigEndian.Uint16(lengthB))
  295. if length == 0 {
  296. return nil, nil
  297. }
  298. listType, err := buf.ReadByte()
  299. if err != nil {
  300. return nil, fmt.Errorf("cannot read SNI list type: %w", err)
  301. }
  302. // 00 - list entry is type 0x00 "DNS hostname"
  303. if listType != sniDNSNamesListType {
  304. return nil, fmt.Errorf("incorrect SNI list type %#x", listType)
  305. }
  306. names := []string{}
  307. for buf.Len() > 0 {
  308. // 00 13 - 0x13 (19) bytes of hostname follows
  309. lengthB = buf.Next(2)
  310. if len(lengthB) != 2 {
  311. return nil, fmt.Errorf("incorrect length of the hostname: %v", lengthB)
  312. }
  313. length = int(binary.BigEndian.Uint16(lengthB))
  314. name := buf.Next(length)
  315. if len(name) != length {
  316. return nil, fmt.Errorf("incorrect length of SNI hostname: len %d != %d", length, len(name))
  317. }
  318. names = append(names, string(name))
  319. }
  320. return names, nil
  321. }
  322. return nil, nil
  323. }