utls_client.go 6.3 KB

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