utls_client.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. //go:build with_utls
  2. package tls
  3. import (
  4. "crypto/tls"
  5. "crypto/x509"
  6. "math/rand"
  7. "net"
  8. "net/netip"
  9. "os"
  10. "github.com/sagernet/sing-box/adapter"
  11. "github.com/sagernet/sing-box/option"
  12. E "github.com/sagernet/sing/common/exceptions"
  13. utls "github.com/sagernet/utls"
  14. "golang.org/x/net/http2"
  15. )
  16. type UTLSClientConfig struct {
  17. config *utls.Config
  18. id utls.ClientHelloID
  19. }
  20. func (e *UTLSClientConfig) ServerName() string {
  21. return e.config.ServerName
  22. }
  23. func (e *UTLSClientConfig) SetServerName(serverName string) {
  24. e.config.ServerName = serverName
  25. }
  26. func (e *UTLSClientConfig) NextProtos() []string {
  27. return e.config.NextProtos
  28. }
  29. func (e *UTLSClientConfig) SetNextProtos(nextProto []string) {
  30. if len(nextProto) == 1 && nextProto[0] == http2.NextProtoTLS {
  31. nextProto = append(nextProto, "http/1.1")
  32. }
  33. e.config.NextProtos = nextProto
  34. }
  35. func (e *UTLSClientConfig) Config() (*STDConfig, error) {
  36. return nil, E.New("unsupported usage for uTLS")
  37. }
  38. func (e *UTLSClientConfig) Client(conn net.Conn) (Conn, error) {
  39. return &utlsConnWrapper{utls.UClient(conn, e.config.Clone(), e.id)}, nil
  40. }
  41. func (e *UTLSClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) {
  42. e.config.SessionIDGenerator = generator
  43. }
  44. func (e *UTLSClientConfig) Clone() Config {
  45. return &UTLSClientConfig{
  46. config: e.config.Clone(),
  47. id: e.id,
  48. }
  49. }
  50. type utlsConnWrapper struct {
  51. *utls.UConn
  52. }
  53. func (c *utlsConnWrapper) ConnectionState() tls.ConnectionState {
  54. state := c.Conn.ConnectionState()
  55. return tls.ConnectionState{
  56. Version: state.Version,
  57. HandshakeComplete: state.HandshakeComplete,
  58. DidResume: state.DidResume,
  59. CipherSuite: state.CipherSuite,
  60. NegotiatedProtocol: state.NegotiatedProtocol,
  61. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  62. ServerName: state.ServerName,
  63. PeerCertificates: state.PeerCertificates,
  64. VerifiedChains: state.VerifiedChains,
  65. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  66. OCSPResponse: state.OCSPResponse,
  67. TLSUnique: state.TLSUnique,
  68. }
  69. }
  70. func (c *utlsConnWrapper) Upstream() any {
  71. return c.UConn
  72. }
  73. func NewUTLSClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (*UTLSClientConfig, error) {
  74. var serverName string
  75. if options.ServerName != "" {
  76. serverName = options.ServerName
  77. } else if serverAddress != "" {
  78. if _, err := netip.ParseAddr(serverName); err != nil {
  79. serverName = serverAddress
  80. }
  81. }
  82. if serverName == "" && !options.Insecure {
  83. return nil, E.New("missing server_name or insecure=true")
  84. }
  85. var tlsConfig utls.Config
  86. tlsConfig.Time = router.TimeFunc()
  87. if options.DisableSNI {
  88. tlsConfig.ServerName = "127.0.0.1"
  89. } else {
  90. tlsConfig.ServerName = serverName
  91. }
  92. if options.Insecure {
  93. tlsConfig.InsecureSkipVerify = options.Insecure
  94. } else if options.DisableSNI {
  95. return nil, E.New("disable_sni is unsupported in uTLS")
  96. }
  97. if len(options.ALPN) > 0 {
  98. tlsConfig.NextProtos = options.ALPN
  99. }
  100. if options.MinVersion != "" {
  101. minVersion, err := ParseTLSVersion(options.MinVersion)
  102. if err != nil {
  103. return nil, E.Cause(err, "parse min_version")
  104. }
  105. tlsConfig.MinVersion = minVersion
  106. }
  107. if options.MaxVersion != "" {
  108. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  109. if err != nil {
  110. return nil, E.Cause(err, "parse max_version")
  111. }
  112. tlsConfig.MaxVersion = maxVersion
  113. }
  114. if options.CipherSuites != nil {
  115. find:
  116. for _, cipherSuite := range options.CipherSuites {
  117. for _, tlsCipherSuite := range tls.CipherSuites() {
  118. if cipherSuite == tlsCipherSuite.Name {
  119. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  120. continue find
  121. }
  122. }
  123. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  124. }
  125. }
  126. var certificate []byte
  127. if options.Certificate != "" {
  128. certificate = []byte(options.Certificate)
  129. } else if options.CertificatePath != "" {
  130. content, err := os.ReadFile(options.CertificatePath)
  131. if err != nil {
  132. return nil, E.Cause(err, "read certificate")
  133. }
  134. certificate = content
  135. }
  136. if len(certificate) > 0 {
  137. certPool := x509.NewCertPool()
  138. if !certPool.AppendCertsFromPEM(certificate) {
  139. return nil, E.New("failed to parse certificate:\n\n", certificate)
  140. }
  141. tlsConfig.RootCAs = certPool
  142. }
  143. id, err := uTLSClientHelloID(options.UTLS.Fingerprint)
  144. if err != nil {
  145. return nil, err
  146. }
  147. return &UTLSClientConfig{&tlsConfig, id}, nil
  148. }
  149. var randomFingerprint utls.ClientHelloID
  150. func init() {
  151. modernFingerprints := []utls.ClientHelloID{
  152. utls.HelloChrome_Auto,
  153. utls.HelloFirefox_Auto,
  154. utls.HelloEdge_Auto,
  155. utls.HelloSafari_Auto,
  156. utls.HelloIOS_Auto,
  157. }
  158. randomFingerprint = modernFingerprints[rand.Intn(len(modernFingerprints))]
  159. }
  160. func uTLSClientHelloID(name string) (utls.ClientHelloID, error) {
  161. switch name {
  162. case "chrome", "":
  163. return utls.HelloChrome_Auto, nil
  164. case "firefox":
  165. return utls.HelloFirefox_Auto, nil
  166. case "edge":
  167. return utls.HelloEdge_Auto, nil
  168. case "safari":
  169. return utls.HelloSafari_Auto, nil
  170. case "360":
  171. return utls.Hello360_Auto, nil
  172. case "qq":
  173. return utls.HelloQQ_Auto, nil
  174. case "ios":
  175. return utls.HelloIOS_Auto, nil
  176. case "android":
  177. return utls.HelloAndroid_11_OkHttp, nil
  178. case "random":
  179. return randomFingerprint, nil
  180. case "randomized":
  181. weights := utls.DefaultWeights
  182. weights.TLSVersMax_Set_VersionTLS13 = 1
  183. weights.FirstKeyShare_Set_CurveP256 = 0
  184. randomized := utls.HelloRandomized
  185. randomized.Seed, _ = utls.NewPRNGSeed()
  186. randomized.Weights = &weights
  187. return randomized, nil
  188. default:
  189. return utls.ClientHelloID{}, E.New("unknown uTLS fingerprint: ", name)
  190. }
  191. }