utls_client.go 8.2 KB

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