1
0

utls_client.go 8.2 KB

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