utls_client.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. //go:build with_utls
  2. package tls
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "math/rand"
  8. "net"
  9. "net/netip"
  10. "os"
  11. "strings"
  12. "github.com/sagernet/sing-box/adapter"
  13. "github.com/sagernet/sing-box/option"
  14. E "github.com/sagernet/sing/common/exceptions"
  15. "github.com/sagernet/sing/common/ntp"
  16. utls "github.com/metacubex/utls"
  17. "golang.org/x/net/http2"
  18. )
  19. type UTLSClientConfig struct {
  20. config *utls.Config
  21. id utls.ClientHelloID
  22. }
  23. func (e *UTLSClientConfig) ServerName() string {
  24. return e.config.ServerName
  25. }
  26. func (e *UTLSClientConfig) SetServerName(serverName string) {
  27. e.config.ServerName = serverName
  28. }
  29. func (e *UTLSClientConfig) NextProtos() []string {
  30. return e.config.NextProtos
  31. }
  32. func (e *UTLSClientConfig) SetNextProtos(nextProto []string) {
  33. if len(nextProto) == 1 && nextProto[0] == http2.NextProtoTLS {
  34. nextProto = append(nextProto, "http/1.1")
  35. }
  36. e.config.NextProtos = nextProto
  37. }
  38. func (e *UTLSClientConfig) Config() (*STDConfig, error) {
  39. return nil, E.New("unsupported usage for uTLS")
  40. }
  41. func (e *UTLSClientConfig) Client(conn net.Conn) (Conn, error) {
  42. return &utlsALPNWrapper{utlsConnWrapper{utls.UClient(conn, e.config.Clone(), e.id)}, e.config.NextProtos}, nil
  43. }
  44. func (e *UTLSClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) {
  45. e.config.SessionIDGenerator = generator
  46. }
  47. func (e *UTLSClientConfig) Clone() Config {
  48. return &UTLSClientConfig{
  49. config: e.config.Clone(),
  50. id: e.id,
  51. }
  52. }
  53. type utlsConnWrapper struct {
  54. *utls.UConn
  55. }
  56. func (c *utlsConnWrapper) ConnectionState() tls.ConnectionState {
  57. state := c.Conn.ConnectionState()
  58. //nolint:staticcheck
  59. return tls.ConnectionState{
  60. Version: state.Version,
  61. HandshakeComplete: state.HandshakeComplete,
  62. DidResume: state.DidResume,
  63. CipherSuite: state.CipherSuite,
  64. NegotiatedProtocol: state.NegotiatedProtocol,
  65. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  66. ServerName: state.ServerName,
  67. PeerCertificates: state.PeerCertificates,
  68. VerifiedChains: state.VerifiedChains,
  69. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  70. OCSPResponse: state.OCSPResponse,
  71. TLSUnique: state.TLSUnique,
  72. }
  73. }
  74. func (c *utlsConnWrapper) Upstream() any {
  75. return c.UConn
  76. }
  77. type utlsALPNWrapper struct {
  78. utlsConnWrapper
  79. nextProtocols []string
  80. }
  81. func (c *utlsALPNWrapper) HandshakeContext(ctx context.Context) error {
  82. if len(c.nextProtocols) > 0 {
  83. err := c.BuildHandshakeState()
  84. if err != nil {
  85. return err
  86. }
  87. for _, extension := range c.Extensions {
  88. if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN {
  89. alpnExtension.AlpnProtocols = c.nextProtocols
  90. err = c.BuildHandshakeState()
  91. if err != nil {
  92. return err
  93. }
  94. break
  95. }
  96. }
  97. }
  98. return c.UConn.HandshakeContext(ctx)
  99. }
  100. func NewUTLSClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (*UTLSClientConfig, error) {
  101. var serverName string
  102. if options.ServerName != "" {
  103. serverName = options.ServerName
  104. } else if serverAddress != "" {
  105. if _, err := netip.ParseAddr(serverName); err != nil {
  106. serverName = serverAddress
  107. }
  108. }
  109. if serverName == "" && !options.Insecure {
  110. return nil, E.New("missing server_name or insecure=true")
  111. }
  112. var tlsConfig utls.Config
  113. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  114. tlsConfig.RootCAs = adapter.RootPoolFromContext(ctx)
  115. if options.DisableSNI {
  116. tlsConfig.ServerName = "127.0.0.1"
  117. } else {
  118. tlsConfig.ServerName = serverName
  119. }
  120. if options.Insecure {
  121. tlsConfig.InsecureSkipVerify = options.Insecure
  122. } else if options.DisableSNI {
  123. return nil, E.New("disable_sni is unsupported in uTLS")
  124. }
  125. if len(options.ALPN) > 0 {
  126. tlsConfig.NextProtos = options.ALPN
  127. }
  128. if options.MinVersion != "" {
  129. minVersion, err := ParseTLSVersion(options.MinVersion)
  130. if err != nil {
  131. return nil, E.Cause(err, "parse min_version")
  132. }
  133. tlsConfig.MinVersion = minVersion
  134. }
  135. if options.MaxVersion != "" {
  136. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  137. if err != nil {
  138. return nil, E.Cause(err, "parse max_version")
  139. }
  140. tlsConfig.MaxVersion = maxVersion
  141. }
  142. if options.CipherSuites != nil {
  143. find:
  144. for _, cipherSuite := range options.CipherSuites {
  145. for _, tlsCipherSuite := range tls.CipherSuites() {
  146. if cipherSuite == tlsCipherSuite.Name {
  147. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  148. continue find
  149. }
  150. }
  151. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  152. }
  153. }
  154. var certificate []byte
  155. if len(options.Certificate) > 0 {
  156. certificate = []byte(strings.Join(options.Certificate, "\n"))
  157. } else if options.CertificatePath != "" {
  158. content, err := os.ReadFile(options.CertificatePath)
  159. if err != nil {
  160. return nil, E.Cause(err, "read certificate")
  161. }
  162. certificate = content
  163. }
  164. if len(certificate) > 0 {
  165. certPool := x509.NewCertPool()
  166. if !certPool.AppendCertsFromPEM(certificate) {
  167. return nil, E.New("failed to parse certificate:\n\n", certificate)
  168. }
  169. tlsConfig.RootCAs = certPool
  170. }
  171. id, err := uTLSClientHelloID(options.UTLS.Fingerprint)
  172. if err != nil {
  173. return nil, err
  174. }
  175. return &UTLSClientConfig{&tlsConfig, id}, nil
  176. }
  177. var (
  178. randomFingerprint utls.ClientHelloID
  179. randomizedFingerprint utls.ClientHelloID
  180. )
  181. func init() {
  182. modernFingerprints := []utls.ClientHelloID{
  183. utls.HelloChrome_Auto,
  184. utls.HelloFirefox_Auto,
  185. utls.HelloEdge_Auto,
  186. utls.HelloSafari_Auto,
  187. utls.HelloIOS_Auto,
  188. }
  189. randomFingerprint = modernFingerprints[rand.Intn(len(modernFingerprints))]
  190. weights := utls.DefaultWeights
  191. weights.TLSVersMax_Set_VersionTLS13 = 1
  192. weights.FirstKeyShare_Set_CurveP256 = 0
  193. randomizedFingerprint = utls.HelloRandomized
  194. randomizedFingerprint.Seed, _ = utls.NewPRNGSeed()
  195. randomizedFingerprint.Weights = &weights
  196. }
  197. func uTLSClientHelloID(name string) (utls.ClientHelloID, error) {
  198. switch name {
  199. case "chrome_psk", "chrome_psk_shuffle", "chrome_padding_psk_shuffle", "chrome_pq":
  200. fallthrough
  201. case "chrome", "":
  202. return utls.HelloChrome_Auto, nil
  203. case "firefox":
  204. return utls.HelloFirefox_Auto, nil
  205. case "edge":
  206. return utls.HelloEdge_Auto, nil
  207. case "safari":
  208. return utls.HelloSafari_Auto, nil
  209. case "360":
  210. return utls.Hello360_Auto, nil
  211. case "qq":
  212. return utls.HelloQQ_Auto, nil
  213. case "ios":
  214. return utls.HelloIOS_Auto, nil
  215. case "android":
  216. return utls.HelloAndroid_11_OkHttp, nil
  217. case "random":
  218. return randomFingerprint, nil
  219. case "randomized":
  220. return randomizedFingerprint, nil
  221. default:
  222. return utls.ClientHelloID{}, E.New("unknown uTLS fingerprint: ", name)
  223. }
  224. }