utls_client.go 6.5 KB

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