utls_client.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. return tls.ConnectionState{
  58. Version: state.Version,
  59. HandshakeComplete: state.HandshakeComplete,
  60. DidResume: state.DidResume,
  61. CipherSuite: state.CipherSuite,
  62. NegotiatedProtocol: state.NegotiatedProtocol,
  63. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  64. ServerName: state.ServerName,
  65. PeerCertificates: state.PeerCertificates,
  66. VerifiedChains: state.VerifiedChains,
  67. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  68. OCSPResponse: state.OCSPResponse,
  69. TLSUnique: state.TLSUnique,
  70. }
  71. }
  72. func (c *utlsConnWrapper) Upstream() any {
  73. return c.UConn
  74. }
  75. type utlsALPNWrapper struct {
  76. utlsConnWrapper
  77. nextProtocols []string
  78. }
  79. func (c *utlsALPNWrapper) HandshakeContext(ctx context.Context) error {
  80. if len(c.nextProtocols) > 0 {
  81. err := c.BuildHandshakeState()
  82. if err != nil {
  83. return err
  84. }
  85. for _, extension := range c.Extensions {
  86. if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN {
  87. alpnExtension.AlpnProtocols = c.nextProtocols
  88. err = c.BuildHandshakeState()
  89. if err != nil {
  90. return err
  91. }
  92. break
  93. }
  94. }
  95. }
  96. return c.UConn.HandshakeContext(ctx)
  97. }
  98. func NewUTLSClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (*UTLSClientConfig, error) {
  99. var serverName string
  100. if options.ServerName != "" {
  101. serverName = options.ServerName
  102. } else if serverAddress != "" {
  103. if _, err := netip.ParseAddr(serverName); err != nil {
  104. serverName = serverAddress
  105. }
  106. }
  107. if serverName == "" && !options.Insecure {
  108. return nil, E.New("missing server_name or insecure=true")
  109. }
  110. var tlsConfig utls.Config
  111. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  112. if options.DisableSNI {
  113. tlsConfig.ServerName = "127.0.0.1"
  114. } else {
  115. tlsConfig.ServerName = serverName
  116. }
  117. if options.Insecure {
  118. tlsConfig.InsecureSkipVerify = options.Insecure
  119. } else if options.DisableSNI {
  120. return nil, E.New("disable_sni is unsupported in uTLS")
  121. }
  122. if len(options.ALPN) > 0 {
  123. tlsConfig.NextProtos = options.ALPN
  124. }
  125. if options.MinVersion != "" {
  126. minVersion, err := ParseTLSVersion(options.MinVersion)
  127. if err != nil {
  128. return nil, E.Cause(err, "parse min_version")
  129. }
  130. tlsConfig.MinVersion = minVersion
  131. }
  132. if options.MaxVersion != "" {
  133. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  134. if err != nil {
  135. return nil, E.Cause(err, "parse max_version")
  136. }
  137. tlsConfig.MaxVersion = maxVersion
  138. }
  139. if options.CipherSuites != nil {
  140. find:
  141. for _, cipherSuite := range options.CipherSuites {
  142. for _, tlsCipherSuite := range tls.CipherSuites() {
  143. if cipherSuite == tlsCipherSuite.Name {
  144. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  145. continue find
  146. }
  147. }
  148. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  149. }
  150. }
  151. var certificate []byte
  152. if len(options.Certificate) > 0 {
  153. certificate = []byte(strings.Join(options.Certificate, "\n"))
  154. } else if options.CertificatePath != "" {
  155. content, err := os.ReadFile(options.CertificatePath)
  156. if err != nil {
  157. return nil, E.Cause(err, "read certificate")
  158. }
  159. certificate = content
  160. }
  161. if len(certificate) > 0 {
  162. certPool := x509.NewCertPool()
  163. if !certPool.AppendCertsFromPEM(certificate) {
  164. return nil, E.New("failed to parse certificate:\n\n", certificate)
  165. }
  166. tlsConfig.RootCAs = certPool
  167. }
  168. id, err := uTLSClientHelloID(options.UTLS.Fingerprint)
  169. if err != nil {
  170. return nil, err
  171. }
  172. return &UTLSClientConfig{&tlsConfig, id}, nil
  173. }
  174. var (
  175. randomFingerprint utls.ClientHelloID
  176. randomizedFingerprint utls.ClientHelloID
  177. )
  178. func init() {
  179. modernFingerprints := []utls.ClientHelloID{
  180. utls.HelloChrome_Auto,
  181. utls.HelloFirefox_Auto,
  182. utls.HelloEdge_Auto,
  183. utls.HelloSafari_Auto,
  184. utls.HelloIOS_Auto,
  185. }
  186. randomFingerprint = modernFingerprints[rand.Intn(len(modernFingerprints))]
  187. weights := utls.DefaultWeights
  188. weights.TLSVersMax_Set_VersionTLS13 = 1
  189. weights.FirstKeyShare_Set_CurveP256 = 0
  190. randomizedFingerprint = utls.HelloRandomized
  191. randomizedFingerprint.Seed, _ = utls.NewPRNGSeed()
  192. randomizedFingerprint.Weights = &weights
  193. }
  194. func uTLSClientHelloID(name string) (utls.ClientHelloID, error) {
  195. switch name {
  196. case "chrome", "":
  197. return utls.HelloChrome_Auto, nil
  198. case "chrome_psk":
  199. return utls.HelloChrome_100_PSK, nil
  200. case "chrome_psk_shuffle":
  201. return utls.HelloChrome_112_PSK_Shuf, nil
  202. case "chrome_padding_psk_shuffle":
  203. return utls.HelloChrome_114_Padding_PSK_Shuf, nil
  204. case "chrome_pq":
  205. return utls.HelloChrome_115_PQ, nil
  206. case "chrome_pq_psk":
  207. return utls.HelloChrome_115_PQ_PSK, nil
  208. case "firefox":
  209. return utls.HelloFirefox_Auto, nil
  210. case "edge":
  211. return utls.HelloEdge_Auto, nil
  212. case "safari":
  213. return utls.HelloSafari_Auto, nil
  214. case "360":
  215. return utls.Hello360_Auto, nil
  216. case "qq":
  217. return utls.HelloQQ_Auto, nil
  218. case "ios":
  219. return utls.HelloIOS_Auto, nil
  220. case "android":
  221. return utls.HelloAndroid_11_OkHttp, nil
  222. case "random":
  223. return randomFingerprint, nil
  224. case "randomized":
  225. return randomizedFingerprint, nil
  226. default:
  227. return utls.ClientHelloID{}, E.New("unknown uTLS fingerprint: ", name)
  228. }
  229. }