tls.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package tls
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/tls"
  6. "math/big"
  7. "time"
  8. utls "github.com/refraction-networking/utls"
  9. "github.com/xtls/xray-core/common/buf"
  10. "github.com/xtls/xray-core/common/net"
  11. )
  12. type Interface interface {
  13. net.Conn
  14. HandshakeContext(ctx context.Context) error
  15. VerifyHostname(host string) error
  16. NegotiatedProtocol() string
  17. }
  18. var _ buf.Writer = (*Conn)(nil)
  19. var _ Interface = (*Conn)(nil)
  20. type Conn struct {
  21. *tls.Conn
  22. }
  23. const tlsCloseTimeout = 250 * time.Millisecond
  24. func (c *Conn) Close() error {
  25. timer := time.AfterFunc(tlsCloseTimeout, func() {
  26. c.Conn.NetConn().Close()
  27. })
  28. defer timer.Stop()
  29. return c.Conn.Close()
  30. }
  31. func (c *Conn) WriteMultiBuffer(mb buf.MultiBuffer) error {
  32. mb = buf.Compact(mb)
  33. mb, err := buf.WriteMultiBuffer(c, mb)
  34. buf.ReleaseMulti(mb)
  35. return err
  36. }
  37. func (c *Conn) HandshakeAddressContext(ctx context.Context) net.Address {
  38. if err := c.HandshakeContext(ctx); err != nil {
  39. return nil
  40. }
  41. state := c.ConnectionState()
  42. if state.ServerName == "" {
  43. return nil
  44. }
  45. return net.ParseAddress(state.ServerName)
  46. }
  47. func (c *Conn) NegotiatedProtocol() string {
  48. state := c.ConnectionState()
  49. return state.NegotiatedProtocol
  50. }
  51. // Client initiates a TLS client handshake on the given connection.
  52. func Client(c net.Conn, config *tls.Config) net.Conn {
  53. tlsConn := tls.Client(c, config)
  54. return &Conn{Conn: tlsConn}
  55. }
  56. // Server initiates a TLS server handshake on the given connection.
  57. func Server(c net.Conn, config *tls.Config) net.Conn {
  58. tlsConn := tls.Server(c, config)
  59. return &Conn{Conn: tlsConn}
  60. }
  61. type UConn struct {
  62. *utls.UConn
  63. }
  64. var _ Interface = (*UConn)(nil)
  65. func (c *UConn) Close() error {
  66. timer := time.AfterFunc(tlsCloseTimeout, func() {
  67. c.Conn.NetConn().Close()
  68. })
  69. defer timer.Stop()
  70. return c.Conn.Close()
  71. }
  72. func (c *UConn) HandshakeAddressContext(ctx context.Context) net.Address {
  73. if err := c.HandshakeContext(ctx); err != nil {
  74. return nil
  75. }
  76. state := c.ConnectionState()
  77. if state.ServerName == "" {
  78. return nil
  79. }
  80. return net.ParseAddress(state.ServerName)
  81. }
  82. // WebsocketHandshake basically calls UConn.Handshake inside it but it will only send
  83. // http/1.1 in its ALPN.
  84. func (c *UConn) WebsocketHandshakeContext(ctx context.Context) error {
  85. // Build the handshake state. This will apply every variable of the TLS of the
  86. // fingerprint in the UConn
  87. if err := c.BuildHandshakeState(); err != nil {
  88. return err
  89. }
  90. // Iterate over extensions and check for utls.ALPNExtension
  91. hasALPNExtension := false
  92. for _, extension := range c.Extensions {
  93. if alpn, ok := extension.(*utls.ALPNExtension); ok {
  94. hasALPNExtension = true
  95. alpn.AlpnProtocols = []string{"http/1.1"}
  96. break
  97. }
  98. }
  99. if !hasALPNExtension { // Append extension if doesn't exists
  100. c.Extensions = append(c.Extensions, &utls.ALPNExtension{AlpnProtocols: []string{"http/1.1"}})
  101. }
  102. // Rebuild the client hello and do the handshake
  103. if err := c.BuildHandshakeState(); err != nil {
  104. return err
  105. }
  106. return c.HandshakeContext(ctx)
  107. }
  108. func (c *UConn) NegotiatedProtocol() string {
  109. state := c.ConnectionState()
  110. return state.NegotiatedProtocol
  111. }
  112. func UClient(c net.Conn, config *tls.Config, fingerprint *utls.ClientHelloID) net.Conn {
  113. utlsConn := utls.UClient(c, copyConfig(config), *fingerprint)
  114. return &UConn{UConn: utlsConn}
  115. }
  116. func copyConfig(c *tls.Config) *utls.Config {
  117. return &utls.Config{
  118. RootCAs: c.RootCAs,
  119. ServerName: c.ServerName,
  120. InsecureSkipVerify: c.InsecureSkipVerify,
  121. VerifyPeerCertificate: c.VerifyPeerCertificate,
  122. KeyLogWriter: c.KeyLogWriter,
  123. }
  124. }
  125. func init() {
  126. bigInt, _ := rand.Int(rand.Reader, big.NewInt(int64(len(ModernFingerprints))))
  127. stopAt := int(bigInt.Int64())
  128. i := 0
  129. for _, v := range ModernFingerprints {
  130. if i == stopAt {
  131. PresetFingerprints["random"] = v
  132. break
  133. }
  134. i++
  135. }
  136. weights := utls.DefaultWeights
  137. weights.TLSVersMax_Set_VersionTLS13 = 1
  138. weights.FirstKeyShare_Set_CurveP256 = 0
  139. randomized := utls.HelloRandomized
  140. randomized.Seed, _ = utls.NewPRNGSeed()
  141. randomized.Weights = &weights
  142. PresetFingerprints["randomized"] = &randomized
  143. }
  144. func GetFingerprint(name string) (fingerprint *utls.ClientHelloID) {
  145. if name == "" {
  146. return
  147. }
  148. if fingerprint = PresetFingerprints[name]; fingerprint != nil {
  149. return
  150. }
  151. if fingerprint = ModernFingerprints[name]; fingerprint != nil {
  152. return
  153. }
  154. if fingerprint = OtherFingerprints[name]; fingerprint != nil {
  155. return
  156. }
  157. return
  158. }
  159. var PresetFingerprints = map[string]*utls.ClientHelloID{
  160. // Recommended preset options in GUI clients
  161. "chrome": &utls.HelloChrome_Auto,
  162. "firefox": &utls.HelloFirefox_Auto,
  163. "safari": &utls.HelloSafari_Auto,
  164. "ios": &utls.HelloIOS_Auto,
  165. "android": &utls.HelloAndroid_11_OkHttp,
  166. "edge": &utls.HelloEdge_Auto,
  167. "360": &utls.Hello360_Auto,
  168. "qq": &utls.HelloQQ_Auto,
  169. "random": nil,
  170. "randomized": nil,
  171. }
  172. var ModernFingerprints = map[string]*utls.ClientHelloID{
  173. // One of these will be chosen as `random` at startup
  174. "hellofirefox_99": &utls.HelloFirefox_99,
  175. "hellofirefox_102": &utls.HelloFirefox_102,
  176. "hellofirefox_105": &utls.HelloFirefox_105,
  177. "hellochrome_83": &utls.HelloChrome_83,
  178. "hellochrome_87": &utls.HelloChrome_87,
  179. "hellochrome_96": &utls.HelloChrome_96,
  180. "hellochrome_100": &utls.HelloChrome_100,
  181. "hellochrome_102": &utls.HelloChrome_102,
  182. "hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle,
  183. "helloios_13": &utls.HelloIOS_13,
  184. "helloios_14": &utls.HelloIOS_14,
  185. "helloedge_85": &utls.HelloEdge_85,
  186. "helloedge_106": &utls.HelloEdge_106,
  187. "hellosafari_16_0": &utls.HelloSafari_16_0,
  188. "hello360_11_0": &utls.Hello360_11_0,
  189. "helloqq_11_1": &utls.HelloQQ_11_1,
  190. }
  191. var OtherFingerprints = map[string]*utls.ClientHelloID{
  192. // Golang, randomized, auto, and fingerprints that are too old
  193. "hellogolang": &utls.HelloGolang,
  194. "hellorandomized": &utls.HelloRandomized,
  195. "hellorandomizedalpn": &utls.HelloRandomizedALPN,
  196. "hellorandomizednoalpn": &utls.HelloRandomizedNoALPN,
  197. "hellofirefox_auto": &utls.HelloFirefox_Auto,
  198. "hellofirefox_55": &utls.HelloFirefox_55,
  199. "hellofirefox_56": &utls.HelloFirefox_56,
  200. "hellofirefox_63": &utls.HelloFirefox_63,
  201. "hellofirefox_65": &utls.HelloFirefox_65,
  202. "hellochrome_auto": &utls.HelloChrome_Auto,
  203. "hellochrome_58": &utls.HelloChrome_58,
  204. "hellochrome_62": &utls.HelloChrome_62,
  205. "hellochrome_70": &utls.HelloChrome_70,
  206. "hellochrome_72": &utls.HelloChrome_72,
  207. "helloios_auto": &utls.HelloIOS_Auto,
  208. "helloios_11_1": &utls.HelloIOS_11_1,
  209. "helloios_12_1": &utls.HelloIOS_12_1,
  210. "helloandroid_11_okhttp": &utls.HelloAndroid_11_OkHttp,
  211. "helloedge_auto": &utls.HelloEdge_Auto,
  212. "hellosafari_auto": &utls.HelloSafari_Auto,
  213. "hello360_auto": &utls.Hello360_Auto,
  214. "hello360_7_5": &utls.Hello360_7_5,
  215. "helloqq_auto": &utls.HelloQQ_Auto,
  216. }