utls_client.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. func (c *utlsConnWrapper) ReaderReplaceable() bool {
  91. return true
  92. }
  93. func (c *utlsConnWrapper) WriterReplaceable() bool {
  94. return true
  95. }
  96. type utlsALPNWrapper struct {
  97. utlsConnWrapper
  98. nextProtocols []string
  99. }
  100. func (c *utlsALPNWrapper) HandshakeContext(ctx context.Context) error {
  101. if len(c.nextProtocols) > 0 {
  102. err := c.BuildHandshakeState()
  103. if err != nil {
  104. return err
  105. }
  106. for _, extension := range c.Extensions {
  107. if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN {
  108. alpnExtension.AlpnProtocols = c.nextProtocols
  109. err = c.BuildHandshakeState()
  110. if err != nil {
  111. return err
  112. }
  113. break
  114. }
  115. }
  116. }
  117. return c.UConn.HandshakeContext(ctx)
  118. }
  119. func NewUTLSClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
  120. var serverName string
  121. if options.ServerName != "" {
  122. serverName = options.ServerName
  123. } else if serverAddress != "" {
  124. serverName = serverAddress
  125. }
  126. if serverName == "" && !options.Insecure {
  127. return nil, E.New("missing server_name or insecure=true")
  128. }
  129. var tlsConfig utls.Config
  130. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  131. tlsConfig.RootCAs = adapter.RootPoolFromContext(ctx)
  132. if !options.DisableSNI {
  133. tlsConfig.ServerName = serverName
  134. }
  135. if options.Insecure {
  136. tlsConfig.InsecureSkipVerify = options.Insecure
  137. } else if options.DisableSNI {
  138. if options.Reality != nil && options.Reality.Enabled {
  139. return nil, E.New("disable_sni is unsupported in reality")
  140. }
  141. tlsConfig.InsecureServerNameToVerify = serverName
  142. }
  143. if len(options.ALPN) > 0 {
  144. tlsConfig.NextProtos = options.ALPN
  145. }
  146. if options.MinVersion != "" {
  147. minVersion, err := ParseTLSVersion(options.MinVersion)
  148. if err != nil {
  149. return nil, E.Cause(err, "parse min_version")
  150. }
  151. tlsConfig.MinVersion = minVersion
  152. }
  153. if options.MaxVersion != "" {
  154. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  155. if err != nil {
  156. return nil, E.Cause(err, "parse max_version")
  157. }
  158. tlsConfig.MaxVersion = maxVersion
  159. }
  160. if options.CipherSuites != nil {
  161. find:
  162. for _, cipherSuite := range options.CipherSuites {
  163. for _, tlsCipherSuite := range tls.CipherSuites() {
  164. if cipherSuite == tlsCipherSuite.Name {
  165. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  166. continue find
  167. }
  168. }
  169. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  170. }
  171. }
  172. var certificate []byte
  173. if len(options.Certificate) > 0 {
  174. certificate = []byte(strings.Join(options.Certificate, "\n"))
  175. } else if options.CertificatePath != "" {
  176. content, err := os.ReadFile(options.CertificatePath)
  177. if err != nil {
  178. return nil, E.Cause(err, "read certificate")
  179. }
  180. certificate = content
  181. }
  182. if len(certificate) > 0 {
  183. certPool := x509.NewCertPool()
  184. if !certPool.AppendCertsFromPEM(certificate) {
  185. return nil, E.New("failed to parse certificate:\n\n", certificate)
  186. }
  187. tlsConfig.RootCAs = certPool
  188. }
  189. id, err := uTLSClientHelloID(options.UTLS.Fingerprint)
  190. if err != nil {
  191. return nil, err
  192. }
  193. uConfig := &UTLSClientConfig{ctx, &tlsConfig, id, options.Fragment, time.Duration(options.FragmentFallbackDelay), options.RecordFragment}
  194. if options.ECH != nil && options.ECH.Enabled {
  195. if options.Reality != nil && options.Reality.Enabled {
  196. return nil, E.New("Reality is conflict with ECH")
  197. }
  198. return parseECHClientConfig(ctx, uConfig, options)
  199. } else {
  200. return uConfig, nil
  201. }
  202. }
  203. var (
  204. randomFingerprint utls.ClientHelloID
  205. randomizedFingerprint utls.ClientHelloID
  206. )
  207. func init() {
  208. modernFingerprints := []utls.ClientHelloID{
  209. utls.HelloChrome_Auto,
  210. utls.HelloFirefox_Auto,
  211. utls.HelloEdge_Auto,
  212. utls.HelloSafari_Auto,
  213. utls.HelloIOS_Auto,
  214. }
  215. randomFingerprint = modernFingerprints[rand.Intn(len(modernFingerprints))]
  216. weights := utls.DefaultWeights
  217. weights.TLSVersMax_Set_VersionTLS13 = 1
  218. weights.FirstKeyShare_Set_CurveP256 = 0
  219. randomizedFingerprint = utls.HelloRandomized
  220. randomizedFingerprint.Seed, _ = utls.NewPRNGSeed()
  221. randomizedFingerprint.Weights = &weights
  222. }
  223. func uTLSClientHelloID(name string) (utls.ClientHelloID, error) {
  224. switch name {
  225. case "chrome_psk", "chrome_psk_shuffle", "chrome_padding_psk_shuffle", "chrome_pq", "chrome_pq_psk":
  226. fallthrough
  227. case "chrome", "":
  228. return utls.HelloChrome_Auto, nil
  229. case "firefox":
  230. return utls.HelloFirefox_Auto, nil
  231. case "edge":
  232. return utls.HelloEdge_Auto, nil
  233. case "safari":
  234. return utls.HelloSafari_Auto, nil
  235. case "360":
  236. return utls.Hello360_Auto, nil
  237. case "qq":
  238. return utls.HelloQQ_Auto, nil
  239. case "ios":
  240. return utls.HelloIOS_Auto, nil
  241. case "android":
  242. return utls.HelloAndroid_11_OkHttp, nil
  243. case "random":
  244. return randomFingerprint, nil
  245. case "randomized":
  246. return randomizedFingerprint, nil
  247. default:
  248. return utls.ClientHelloID{}, E.New("unknown uTLS fingerprint: ", name)
  249. }
  250. }