1
0

utls_client.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. //go:build with_utls
  2. package tls
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "math/rand"
  8. "net"
  9. "os"
  10. "strings"
  11. "time"
  12. "github.com/sagernet/sing-box/adapter"
  13. "github.com/sagernet/sing-box/common/tlsfragment"
  14. "github.com/sagernet/sing-box/option"
  15. E "github.com/sagernet/sing/common/exceptions"
  16. "github.com/sagernet/sing/common/ntp"
  17. utls "github.com/metacubex/utls"
  18. "golang.org/x/net/http2"
  19. )
  20. type UTLSClientConfig struct {
  21. ctx context.Context
  22. config *utls.Config
  23. id utls.ClientHelloID
  24. fragment bool
  25. fragmentFallbackDelay time.Duration
  26. recordFragment bool
  27. }
  28. func (c *UTLSClientConfig) ServerName() string {
  29. return c.config.ServerName
  30. }
  31. func (c *UTLSClientConfig) SetServerName(serverName string) {
  32. c.config.ServerName = serverName
  33. }
  34. func (c *UTLSClientConfig) NextProtos() []string {
  35. return c.config.NextProtos
  36. }
  37. func (c *UTLSClientConfig) SetNextProtos(nextProto []string) {
  38. if len(nextProto) == 1 && nextProto[0] == http2.NextProtoTLS {
  39. nextProto = append(nextProto, "http/1.1")
  40. }
  41. c.config.NextProtos = nextProto
  42. }
  43. func (c *UTLSClientConfig) Config() (*STDConfig, error) {
  44. return nil, E.New("unsupported usage for uTLS")
  45. }
  46. func (c *UTLSClientConfig) Client(conn net.Conn) (Conn, error) {
  47. if c.recordFragment {
  48. conn = tf.NewConn(conn, c.ctx, c.fragment, c.recordFragment, c.fragmentFallbackDelay)
  49. }
  50. return &utlsALPNWrapper{utlsConnWrapper{utls.UClient(conn, c.config.Clone(), c.id)}, c.config.NextProtos}, nil
  51. }
  52. func (c *UTLSClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) {
  53. c.config.SessionIDGenerator = generator
  54. }
  55. func (c *UTLSClientConfig) Clone() Config {
  56. return &UTLSClientConfig{
  57. c.ctx, c.config.Clone(), c.id, c.fragment, c.fragmentFallbackDelay, c.recordFragment,
  58. }
  59. }
  60. func (c *UTLSClientConfig) ECHConfigList() []byte {
  61. return c.config.EncryptedClientHelloConfigList
  62. }
  63. func (c *UTLSClientConfig) SetECHConfigList(EncryptedClientHelloConfigList []byte) {
  64. c.config.EncryptedClientHelloConfigList = EncryptedClientHelloConfigList
  65. }
  66. type utlsConnWrapper struct {
  67. *utls.UConn
  68. }
  69. func (c *utlsConnWrapper) ConnectionState() tls.ConnectionState {
  70. state := c.Conn.ConnectionState()
  71. //nolint:staticcheck
  72. return tls.ConnectionState{
  73. Version: state.Version,
  74. HandshakeComplete: state.HandshakeComplete,
  75. DidResume: state.DidResume,
  76. CipherSuite: state.CipherSuite,
  77. NegotiatedProtocol: state.NegotiatedProtocol,
  78. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  79. ServerName: state.ServerName,
  80. PeerCertificates: state.PeerCertificates,
  81. VerifiedChains: state.VerifiedChains,
  82. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  83. OCSPResponse: state.OCSPResponse,
  84. TLSUnique: state.TLSUnique,
  85. }
  86. }
  87. func (c *utlsConnWrapper) Upstream() any {
  88. return c.UConn
  89. }
  90. type utlsALPNWrapper struct {
  91. utlsConnWrapper
  92. nextProtocols []string
  93. }
  94. func (c *utlsALPNWrapper) HandshakeContext(ctx context.Context) error {
  95. if len(c.nextProtocols) > 0 {
  96. err := c.BuildHandshakeState()
  97. if err != nil {
  98. return err
  99. }
  100. for _, extension := range c.Extensions {
  101. if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN {
  102. alpnExtension.AlpnProtocols = c.nextProtocols
  103. err = c.BuildHandshakeState()
  104. if err != nil {
  105. return err
  106. }
  107. break
  108. }
  109. }
  110. }
  111. return c.UConn.HandshakeContext(ctx)
  112. }
  113. func NewUTLSClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
  114. var serverName string
  115. if options.ServerName != "" {
  116. serverName = options.ServerName
  117. } else if serverAddress != "" {
  118. serverName = serverAddress
  119. }
  120. if serverName == "" && !options.Insecure {
  121. return nil, E.New("missing server_name or insecure=true")
  122. }
  123. var tlsConfig utls.Config
  124. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  125. tlsConfig.RootCAs = adapter.RootPoolFromContext(ctx)
  126. tlsConfig.ServerName = serverName
  127. if options.Insecure {
  128. tlsConfig.InsecureSkipVerify = options.Insecure
  129. } else if options.DisableSNI {
  130. return nil, E.New("disable_sni is unsupported in uTLS")
  131. }
  132. if len(options.ALPN) > 0 {
  133. tlsConfig.NextProtos = options.ALPN
  134. }
  135. if options.MinVersion != "" {
  136. minVersion, err := ParseTLSVersion(options.MinVersion)
  137. if err != nil {
  138. return nil, E.Cause(err, "parse min_version")
  139. }
  140. tlsConfig.MinVersion = minVersion
  141. }
  142. if options.MaxVersion != "" {
  143. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  144. if err != nil {
  145. return nil, E.Cause(err, "parse max_version")
  146. }
  147. tlsConfig.MaxVersion = maxVersion
  148. }
  149. if options.CipherSuites != nil {
  150. find:
  151. for _, cipherSuite := range options.CipherSuites {
  152. for _, tlsCipherSuite := range tls.CipherSuites() {
  153. if cipherSuite == tlsCipherSuite.Name {
  154. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  155. continue find
  156. }
  157. }
  158. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  159. }
  160. }
  161. var certificate []byte
  162. if len(options.Certificate) > 0 {
  163. certificate = []byte(strings.Join(options.Certificate, "\n"))
  164. } else if options.CertificatePath != "" {
  165. content, err := os.ReadFile(options.CertificatePath)
  166. if err != nil {
  167. return nil, E.Cause(err, "read certificate")
  168. }
  169. certificate = content
  170. }
  171. if len(certificate) > 0 {
  172. certPool := x509.NewCertPool()
  173. if !certPool.AppendCertsFromPEM(certificate) {
  174. return nil, E.New("failed to parse certificate:\n\n", certificate)
  175. }
  176. tlsConfig.RootCAs = certPool
  177. }
  178. id, err := uTLSClientHelloID(options.UTLS.Fingerprint)
  179. if err != nil {
  180. return nil, err
  181. }
  182. uConfig := &UTLSClientConfig{ctx, &tlsConfig, id, options.Fragment, time.Duration(options.FragmentFallbackDelay), options.RecordFragment}
  183. if options.ECH != nil && options.ECH.Enabled {
  184. if options.Reality != nil && options.Reality.Enabled {
  185. return nil, E.New("Reality is conflict with ECH")
  186. }
  187. return parseECHClientConfig(ctx, uConfig, options)
  188. } else {
  189. return uConfig, nil
  190. }
  191. }
  192. var (
  193. randomFingerprint utls.ClientHelloID
  194. randomizedFingerprint utls.ClientHelloID
  195. )
  196. func init() {
  197. modernFingerprints := []utls.ClientHelloID{
  198. utls.HelloChrome_Auto,
  199. utls.HelloFirefox_Auto,
  200. utls.HelloEdge_Auto,
  201. utls.HelloSafari_Auto,
  202. utls.HelloIOS_Auto,
  203. }
  204. randomFingerprint = modernFingerprints[rand.Intn(len(modernFingerprints))]
  205. weights := utls.DefaultWeights
  206. weights.TLSVersMax_Set_VersionTLS13 = 1
  207. weights.FirstKeyShare_Set_CurveP256 = 0
  208. randomizedFingerprint = utls.HelloRandomized
  209. randomizedFingerprint.Seed, _ = utls.NewPRNGSeed()
  210. randomizedFingerprint.Weights = &weights
  211. }
  212. func uTLSClientHelloID(name string) (utls.ClientHelloID, error) {
  213. switch name {
  214. case "chrome_psk", "chrome_psk_shuffle", "chrome_padding_psk_shuffle", "chrome_pq", "chrome_pq_psk":
  215. fallthrough
  216. case "chrome", "":
  217. return utls.HelloChrome_Auto, nil
  218. case "firefox":
  219. return utls.HelloFirefox_Auto, nil
  220. case "edge":
  221. return utls.HelloEdge_Auto, nil
  222. case "safari":
  223. return utls.HelloSafari_Auto, nil
  224. case "360":
  225. return utls.Hello360_Auto, nil
  226. case "qq":
  227. return utls.HelloQQ_Auto, nil
  228. case "ios":
  229. return utls.HelloIOS_Auto, nil
  230. case "android":
  231. return utls.HelloAndroid_11_OkHttp, nil
  232. case "random":
  233. return randomFingerprint, nil
  234. case "randomized":
  235. return randomizedFingerprint, nil
  236. default:
  237. return utls.ClientHelloID{}, E.New("unknown uTLS fingerprint: ", name)
  238. }
  239. }