utls_client.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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.CertificatePublicKeySHA256) > 0 {
  147. if len(options.Certificate) > 0 || options.CertificatePath != "" {
  148. return nil, E.New("certificate_public_key_sha256 is conflict with certificate or certificate_path")
  149. }
  150. tlsConfig.InsecureSkipVerify = true
  151. tlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  152. return verifyPublicKeySHA256(options.CertificatePublicKeySHA256, rawCerts, tlsConfig.Time)
  153. }
  154. }
  155. if len(options.ALPN) > 0 {
  156. tlsConfig.NextProtos = options.ALPN
  157. }
  158. if options.MinVersion != "" {
  159. minVersion, err := ParseTLSVersion(options.MinVersion)
  160. if err != nil {
  161. return nil, E.Cause(err, "parse min_version")
  162. }
  163. tlsConfig.MinVersion = minVersion
  164. }
  165. if options.MaxVersion != "" {
  166. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  167. if err != nil {
  168. return nil, E.Cause(err, "parse max_version")
  169. }
  170. tlsConfig.MaxVersion = maxVersion
  171. }
  172. if options.CipherSuites != nil {
  173. find:
  174. for _, cipherSuite := range options.CipherSuites {
  175. for _, tlsCipherSuite := range tls.CipherSuites() {
  176. if cipherSuite == tlsCipherSuite.Name {
  177. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  178. continue find
  179. }
  180. }
  181. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  182. }
  183. }
  184. var certificate []byte
  185. if len(options.Certificate) > 0 {
  186. certificate = []byte(strings.Join(options.Certificate, "\n"))
  187. } else if options.CertificatePath != "" {
  188. content, err := os.ReadFile(options.CertificatePath)
  189. if err != nil {
  190. return nil, E.Cause(err, "read certificate")
  191. }
  192. certificate = content
  193. }
  194. if len(certificate) > 0 {
  195. certPool := x509.NewCertPool()
  196. if !certPool.AppendCertsFromPEM(certificate) {
  197. return nil, E.New("failed to parse certificate:\n\n", certificate)
  198. }
  199. tlsConfig.RootCAs = certPool
  200. }
  201. id, err := uTLSClientHelloID(options.UTLS.Fingerprint)
  202. if err != nil {
  203. return nil, err
  204. }
  205. var config Config = &UTLSClientConfig{ctx, &tlsConfig, id, options.Fragment, time.Duration(options.FragmentFallbackDelay), options.RecordFragment}
  206. if options.ECH != nil && options.ECH.Enabled {
  207. if options.Reality != nil && options.Reality.Enabled {
  208. return nil, E.New("Reality is conflict with ECH")
  209. }
  210. config, err = parseECHClientConfig(ctx, config.(ECHCapableConfig), options)
  211. if err != nil {
  212. return nil, err
  213. }
  214. }
  215. if (options.KernelRx || options.KernelTx) && !common.PtrValueOrDefault(options.Reality).Enabled {
  216. if !C.IsLinux {
  217. return nil, E.New("kTLS is only supported on Linux")
  218. }
  219. config = &KTLSClientConfig{
  220. Config: config,
  221. logger: logger,
  222. kernelTx: options.KernelTx,
  223. kernelRx: options.KernelRx,
  224. }
  225. }
  226. return config, nil
  227. }
  228. var (
  229. randomFingerprint utls.ClientHelloID
  230. randomizedFingerprint utls.ClientHelloID
  231. )
  232. func init() {
  233. modernFingerprints := []utls.ClientHelloID{
  234. utls.HelloChrome_Auto,
  235. utls.HelloFirefox_Auto,
  236. utls.HelloEdge_Auto,
  237. utls.HelloSafari_Auto,
  238. utls.HelloIOS_Auto,
  239. }
  240. randomFingerprint = modernFingerprints[rand.Intn(len(modernFingerprints))]
  241. weights := utls.DefaultWeights
  242. weights.TLSVersMax_Set_VersionTLS13 = 1
  243. weights.FirstKeyShare_Set_CurveP256 = 0
  244. randomizedFingerprint = utls.HelloRandomized
  245. randomizedFingerprint.Seed, _ = utls.NewPRNGSeed()
  246. randomizedFingerprint.Weights = &weights
  247. }
  248. func uTLSClientHelloID(name string) (utls.ClientHelloID, error) {
  249. switch name {
  250. case "chrome_psk", "chrome_psk_shuffle", "chrome_padding_psk_shuffle", "chrome_pq", "chrome_pq_psk":
  251. fallthrough
  252. case "chrome", "":
  253. return utls.HelloChrome_Auto, nil
  254. case "firefox":
  255. return utls.HelloFirefox_Auto, nil
  256. case "edge":
  257. return utls.HelloEdge_Auto, nil
  258. case "safari":
  259. return utls.HelloSafari_Auto, nil
  260. case "360":
  261. return utls.Hello360_Auto, nil
  262. case "qq":
  263. return utls.HelloQQ_Auto, nil
  264. case "ios":
  265. return utls.HelloIOS_Auto, nil
  266. case "android":
  267. return utls.HelloAndroid_11_OkHttp, nil
  268. case "random":
  269. return randomFingerprint, nil
  270. case "randomized":
  271. return randomizedFingerprint, nil
  272. default:
  273. return utls.ClientHelloID{}, E.New("unknown uTLS fingerprint: ", name)
  274. }
  275. }