utls_client.go 4.9 KB

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