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.

client_side.go 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package fake
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "crypto/subtle"
  7. "encoding/binary"
  8. "fmt"
  9. "io"
  10. "net"
  11. "slices"
  12. "time"
  13. )
  14. const (
  15. TypeHandshakeClient = 0x01
  16. RandomLen = 32
  17. // record_type(1) + version(2) + size(2) + handshake_type(1) + uint24_length(3) + client_version(2)
  18. RandomOffset = 1 + 2 + 2 + 1 + 3 + 2
  19. sniDNSNamesListType = 0
  20. )
  21. var (
  22. emptyRandom = [RandomLen]byte{}
  23. extTypeSNI = [2]byte{}
  24. )
  25. type ClientHello struct {
  26. Random [RandomLen]byte
  27. SessionID []byte
  28. CipherSuite uint16
  29. }
  30. func ReadClientHello(
  31. conn net.Conn,
  32. secret []byte,
  33. hostname string,
  34. tolerateTimeSkewness time.Duration,
  35. ) (*ClientHello, error) {
  36. // This is how FakeTLS is organized:
  37. // 1. We create sha256 HMAC with a given secret
  38. // 2. We dump there a whole TLS frame except of the fact that random
  39. // is filled with all zeroes
  40. // 3. Digest is computed. This digest should be XORed with
  41. // original client random
  42. // 4. New digest should be all 0 except of last 4 bytes
  43. // 5. Last 4 bytes are little endian uint32 of UNIX timestamp when
  44. // this message was created.
  45. clientHelloCopy, handshakeReader, err := parseClientHello(conn)
  46. if err != nil {
  47. return nil, fmt.Errorf("cannot read client hello: %w", err)
  48. }
  49. hello, err := parseHandshake(handshakeReader)
  50. if err != nil {
  51. return nil, fmt.Errorf("cannot parse handshake: %w", err)
  52. }
  53. sniHostnames, err := parseSNI(handshakeReader)
  54. if err != nil {
  55. return nil, fmt.Errorf("cannot parse SNI: %w", err)
  56. }
  57. if !slices.Contains(sniHostnames, hostname) {
  58. return nil, fmt.Errorf("cannot find %s in %v", hostname, sniHostnames)
  59. }
  60. digest := hmac.New(sha256.New, secret)
  61. // we write a copy of the handshake with client random all nullified.
  62. digest.Write(clientHelloCopy.Next(RandomOffset))
  63. clientHelloCopy.Next(RandomLen)
  64. digest.Write(emptyRandom[:])
  65. digest.Write(clientHelloCopy.Bytes())
  66. computed := digest.Sum(nil)
  67. for i := range RandomLen {
  68. computed[i] ^= hello.Random[i]
  69. }
  70. if subtle.ConstantTimeCompare(emptyRandom[:RandomLen-4], computed[:RandomLen-4]) != 1 {
  71. return nil, ErrBadDigest
  72. }
  73. timestamp := int64(binary.LittleEndian.Uint32(computed[RandomLen-4:]))
  74. createdAt := time.Unix(timestamp, 0)
  75. if tdiff := time.Since(createdAt).Abs(); tdiff > tolerateTimeSkewness {
  76. return nil, fmt.Errorf("timestamp %q is too old %s", createdAt, tdiff)
  77. }
  78. return hello, nil
  79. }
  80. func parseHandshake(r io.Reader) (*ClientHello, error) {
  81. // A protocol version of "3,3" (meaning TLS 1.2) is given.
  82. header := [2]byte{}
  83. if _, err := io.ReadFull(r, header[:]); err != nil {
  84. return nil, fmt.Errorf("cannot read client version: %w", err)
  85. }
  86. hello := &ClientHello{}
  87. if _, err := io.ReadFull(r, hello.Random[:]); err != nil {
  88. return nil, fmt.Errorf("cannot read client random: %w", err)
  89. }
  90. if _, err := io.ReadFull(r, header[:1]); err != nil {
  91. return nil, fmt.Errorf("cannot read session ID length: %w", err)
  92. }
  93. hello.SessionID = make([]byte, int(header[0]))
  94. if _, err := io.ReadFull(r, hello.SessionID); err != nil {
  95. return nil, fmt.Errorf("cannot read session id: %w", err)
  96. }
  97. if _, err := io.ReadFull(r, header[:]); err != nil {
  98. return nil, fmt.Errorf("cannot read cipher suite length: %w", err)
  99. }
  100. cipherSuiteLen := int64(binary.BigEndian.Uint16(header[:]))
  101. // we do not care about picking up any cipher. we pick the first one,
  102. // so it is always should be present.
  103. if _, err := io.ReadFull(r, header[:]); err != nil {
  104. return nil, fmt.Errorf("cannot read first cipher suite: %w", err)
  105. }
  106. hello.CipherSuite = binary.BigEndian.Uint16(header[:])
  107. if _, err := io.CopyN(io.Discard, r, cipherSuiteLen-2); err != nil {
  108. return nil, fmt.Errorf("cannot skip remaining cipher suites: %w", err)
  109. }
  110. if _, err := io.ReadFull(r, header[:1]); err != nil {
  111. return nil, fmt.Errorf("cannot read compression methods length: %w", err)
  112. }
  113. if _, err := io.CopyN(io.Discard, r, int64(header[0])); err != nil {
  114. return nil, fmt.Errorf("cannot skip compression methods: %w", err)
  115. }
  116. return hello, nil
  117. }
  118. func parseSNI(r io.Reader) ([]string, error) {
  119. header := [2]byte{}
  120. if _, err := io.ReadFull(r, header[:]); err != nil {
  121. return nil, fmt.Errorf("cannot read length of TLS extensions: %w", err)
  122. }
  123. extensionsLength := int64(binary.BigEndian.Uint16(header[:]))
  124. buf := &bytes.Buffer{}
  125. buf.Grow(int(extensionsLength))
  126. if _, err := io.CopyN(buf, r, extensionsLength); err != nil {
  127. return nil, fmt.Errorf("cannot read extensions: %w", err)
  128. }
  129. for buf.Len() > 0 {
  130. // 00 00 - assigned value for extension "server name"
  131. // 00 18 - 0x18 (24) bytes of "server name" extension data follows
  132. // 00 16 - 0x16 (22) bytes of first (and only) list entry follows
  133. // 00 - list entry is type 0x00 "DNS hostname"
  134. // 00 13 - 0x13 (19) bytes of hostname follows
  135. // 65 78 61 ... 6e 65 74 - "example.ulfheim.net"
  136. // 00 00 - assigned value for extension "server name"
  137. extTypeB := buf.Next(2)
  138. if len(extTypeB) != 2 {
  139. return nil, fmt.Errorf("cannot read extension type: %v", extTypeB)
  140. }
  141. // 00 18 - 0x18 (24) bytes of "server name" extension data follows
  142. lengthB := buf.Next(2)
  143. if len(lengthB) != 2 {
  144. return nil, fmt.Errorf("cannot read extension %v length: %v", extTypeB, lengthB)
  145. }
  146. length := int(binary.BigEndian.Uint16(lengthB))
  147. extDataB := buf.Next(length)
  148. if len(extDataB) != length {
  149. return nil, fmt.Errorf("cannot read extension %v data: len %d != %d", extTypeB, length, len(extDataB))
  150. }
  151. if !bytes.Equal(extTypeB, extTypeSNI[:]) {
  152. continue
  153. }
  154. buf.Reset()
  155. buf.Write(extDataB)
  156. // 00 16 - 0x16 (22) bytes of first (and only) list entry follows
  157. lengthB = buf.Next(2)
  158. if len(lengthB) != 2 {
  159. return nil, fmt.Errorf("cannot read the length of the SNI record: %v", lengthB)
  160. }
  161. length = int(binary.BigEndian.Uint16(lengthB))
  162. if length == 0 {
  163. return nil, nil
  164. }
  165. listType, err := buf.ReadByte()
  166. if err != nil {
  167. return nil, fmt.Errorf("cannot read SNI list type: %w", err)
  168. }
  169. // 00 - list entry is type 0x00 "DNS hostname"
  170. if listType != sniDNSNamesListType {
  171. return nil, fmt.Errorf("incorrect SNI list type %#x", listType)
  172. }
  173. names := []string{}
  174. for buf.Len() > 0 {
  175. // 00 13 - 0x13 (19) bytes of hostname follows
  176. lengthB = buf.Next(2)
  177. if len(lengthB) != 2 {
  178. return nil, fmt.Errorf("incorrect length of the hostname: %v", lengthB)
  179. }
  180. length = int(binary.BigEndian.Uint16(lengthB))
  181. name := buf.Next(length)
  182. if len(name) != length {
  183. return nil, fmt.Errorf("incorrect length of SNI hostname: len %d != %d", length, len(name))
  184. }
  185. names = append(names, string(name))
  186. }
  187. return names, nil
  188. }
  189. return nil, nil
  190. }