std_client.go 6.2 KB

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