tls.go 6.9 KB

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