std_client.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package tls
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "net"
  7. "os"
  8. "strings"
  9. "time"
  10. "github.com/sagernet/sing-box/adapter"
  11. "github.com/sagernet/sing-box/common/tlsfragment"
  12. C "github.com/sagernet/sing-box/constant"
  13. "github.com/sagernet/sing-box/option"
  14. E "github.com/sagernet/sing/common/exceptions"
  15. "github.com/sagernet/sing/common/logger"
  16. "github.com/sagernet/sing/common/ntp"
  17. )
  18. type STDClientConfig struct {
  19. ctx context.Context
  20. config *tls.Config
  21. fragment bool
  22. fragmentFallbackDelay time.Duration
  23. recordFragment bool
  24. }
  25. func (c *STDClientConfig) ServerName() string {
  26. return c.config.ServerName
  27. }
  28. func (c *STDClientConfig) SetServerName(serverName string) {
  29. c.config.ServerName = serverName
  30. }
  31. func (c *STDClientConfig) NextProtos() []string {
  32. return c.config.NextProtos
  33. }
  34. func (c *STDClientConfig) SetNextProtos(nextProto []string) {
  35. c.config.NextProtos = nextProto
  36. }
  37. func (c *STDClientConfig) STDConfig() (*STDConfig, error) {
  38. return c.config, nil
  39. }
  40. func (c *STDClientConfig) Client(conn net.Conn) (Conn, error) {
  41. if c.recordFragment {
  42. conn = tf.NewConn(conn, c.ctx, c.fragment, c.recordFragment, c.fragmentFallbackDelay)
  43. }
  44. return tls.Client(conn, c.config), nil
  45. }
  46. func (c *STDClientConfig) Clone() Config {
  47. return &STDClientConfig{
  48. ctx: c.ctx,
  49. config: c.config.Clone(),
  50. fragment: c.fragment,
  51. fragmentFallbackDelay: c.fragmentFallbackDelay,
  52. recordFragment: c.recordFragment,
  53. }
  54. }
  55. func (c *STDClientConfig) ECHConfigList() []byte {
  56. return c.config.EncryptedClientHelloConfigList
  57. }
  58. func (c *STDClientConfig) SetECHConfigList(EncryptedClientHelloConfigList []byte) {
  59. c.config.EncryptedClientHelloConfigList = EncryptedClientHelloConfigList
  60. }
  61. func NewSTDClient(ctx context.Context, logger logger.ContextLogger, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
  62. var serverName string
  63. if options.ServerName != "" {
  64. serverName = options.ServerName
  65. } else if serverAddress != "" {
  66. serverName = serverAddress
  67. }
  68. if serverName == "" && !options.Insecure {
  69. return nil, E.New("missing server_name or insecure=true")
  70. }
  71. var tlsConfig tls.Config
  72. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  73. tlsConfig.RootCAs = adapter.RootPoolFromContext(ctx)
  74. if !options.DisableSNI {
  75. tlsConfig.ServerName = serverName
  76. }
  77. if options.Insecure {
  78. tlsConfig.InsecureSkipVerify = options.Insecure
  79. } else if options.DisableSNI {
  80. tlsConfig.InsecureSkipVerify = true
  81. tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
  82. verifyOptions := x509.VerifyOptions{
  83. Roots: tlsConfig.RootCAs,
  84. DNSName: serverName,
  85. Intermediates: x509.NewCertPool(),
  86. }
  87. for _, cert := range state.PeerCertificates[1:] {
  88. verifyOptions.Intermediates.AddCert(cert)
  89. }
  90. if tlsConfig.Time != nil {
  91. verifyOptions.CurrentTime = tlsConfig.Time()
  92. }
  93. _, err := state.PeerCertificates[0].Verify(verifyOptions)
  94. return err
  95. }
  96. }
  97. if len(options.ALPN) > 0 {
  98. tlsConfig.NextProtos = options.ALPN
  99. }
  100. if options.MinVersion != "" {
  101. minVersion, err := ParseTLSVersion(options.MinVersion)
  102. if err != nil {
  103. return nil, E.Cause(err, "parse min_version")
  104. }
  105. tlsConfig.MinVersion = minVersion
  106. }
  107. if options.MaxVersion != "" {
  108. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  109. if err != nil {
  110. return nil, E.Cause(err, "parse max_version")
  111. }
  112. tlsConfig.MaxVersion = maxVersion
  113. }
  114. if options.CipherSuites != nil {
  115. find:
  116. for _, cipherSuite := range options.CipherSuites {
  117. for _, tlsCipherSuite := range tls.CipherSuites() {
  118. if cipherSuite == tlsCipherSuite.Name {
  119. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  120. continue find
  121. }
  122. }
  123. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  124. }
  125. }
  126. var certificate []byte
  127. if len(options.Certificate) > 0 {
  128. certificate = []byte(strings.Join(options.Certificate, "\n"))
  129. } else if options.CertificatePath != "" {
  130. content, err := os.ReadFile(options.CertificatePath)
  131. if err != nil {
  132. return nil, E.Cause(err, "read certificate")
  133. }
  134. certificate = content
  135. }
  136. if len(certificate) > 0 {
  137. certPool := x509.NewCertPool()
  138. if !certPool.AppendCertsFromPEM(certificate) {
  139. return nil, E.New("failed to parse certificate:\n\n", certificate)
  140. }
  141. tlsConfig.RootCAs = certPool
  142. }
  143. var config Config = &STDClientConfig{ctx, &tlsConfig, options.Fragment, time.Duration(options.FragmentFallbackDelay), options.RecordFragment}
  144. if options.ECH != nil && options.ECH.Enabled {
  145. var err error
  146. config, err = parseECHClientConfig(ctx, config.(ECHCapableConfig), options)
  147. if err != nil {
  148. return nil, err
  149. }
  150. }
  151. if options.KernelRx || options.KernelTx {
  152. if !C.IsLinux {
  153. return nil, E.New("kTLS is only supported on Linux")
  154. }
  155. config = &KTLSClientConfig{
  156. Config: config,
  157. logger: logger,
  158. kernelTx: options.KernelTx,
  159. kernelRx: options.KernelRx,
  160. }
  161. }
  162. return config, nil
  163. }