std_client.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package tls
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "net"
  8. "net/netip"
  9. "os"
  10. "strings"
  11. "github.com/sagernet/sing-box/adapter"
  12. "github.com/sagernet/sing-box/option"
  13. "github.com/sagernet/sing-dns"
  14. E "github.com/sagernet/sing/common/exceptions"
  15. "github.com/sagernet/sing/common/ntp"
  16. aTLS "github.com/sagernet/sing/common/tls"
  17. "github.com/sagernet/sing/service"
  18. mDNS "github.com/miekg/dns"
  19. )
  20. var _ ConfigCompat = (*STDClientConfig)(nil)
  21. type STDClientConfig struct {
  22. config *tls.Config
  23. }
  24. func (s *STDClientConfig) ServerName() string {
  25. return s.config.ServerName
  26. }
  27. func (s *STDClientConfig) SetServerName(serverName string) {
  28. s.config.ServerName = serverName
  29. }
  30. func (s *STDClientConfig) NextProtos() []string {
  31. return s.config.NextProtos
  32. }
  33. func (s *STDClientConfig) SetNextProtos(nextProto []string) {
  34. s.config.NextProtos = nextProto
  35. }
  36. func (s *STDClientConfig) Config() (*STDConfig, error) {
  37. return s.config, nil
  38. }
  39. func (s *STDClientConfig) Client(conn net.Conn) (Conn, error) {
  40. return tls.Client(conn, s.config), nil
  41. }
  42. func (s *STDClientConfig) Clone() Config {
  43. return &STDClientConfig{s.config.Clone()}
  44. }
  45. type STDECHClientConfig struct {
  46. STDClientConfig
  47. }
  48. func (s *STDClientConfig) ClientHandshake(ctx context.Context, conn net.Conn) (aTLS.Conn, error) {
  49. if len(s.config.EncryptedClientHelloConfigList) == 0 {
  50. message := &mDNS.Msg{
  51. MsgHdr: mDNS.MsgHdr{
  52. RecursionDesired: true,
  53. },
  54. Question: []mDNS.Question{
  55. {
  56. Name: mDNS.Fqdn(s.config.ServerName),
  57. Qtype: mDNS.TypeHTTPS,
  58. Qclass: mDNS.ClassINET,
  59. },
  60. },
  61. }
  62. dnsRouter := service.FromContext[adapter.Router](ctx)
  63. response, err := dnsRouter.Exchange(ctx, message)
  64. if err != nil {
  65. return nil, E.Cause(err, "fetch ECH config list")
  66. }
  67. if response.Rcode != mDNS.RcodeSuccess {
  68. return nil, E.Cause(dns.RCodeError(response.Rcode), "fetch ECH config list")
  69. }
  70. for _, rr := range response.Answer {
  71. switch resource := rr.(type) {
  72. case *mDNS.HTTPS:
  73. for _, value := range resource.Value {
  74. if value.Key().String() == "ech" {
  75. echConfigList, err := base64.StdEncoding.DecodeString(value.String())
  76. if err != nil {
  77. return nil, E.Cause(err, "decode ECH config")
  78. }
  79. s.config.EncryptedClientHelloConfigList = echConfigList
  80. }
  81. }
  82. }
  83. }
  84. return nil, E.New("no ECH config found in DNS records")
  85. }
  86. tlsConn, err := s.Client(conn)
  87. if err != nil {
  88. return nil, err
  89. }
  90. err = tlsConn.HandshakeContext(ctx)
  91. if err != nil {
  92. return nil, err
  93. }
  94. return tlsConn, nil
  95. }
  96. func (s *STDECHClientConfig) Clone() Config {
  97. return &STDECHClientConfig{STDClientConfig{s.config.Clone()}}
  98. }
  99. func NewSTDClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, 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 tls.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. tlsConfig.InsecureSkipVerify = true
  122. tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
  123. verifyOptions := x509.VerifyOptions{
  124. DNSName: serverName,
  125. Intermediates: x509.NewCertPool(),
  126. }
  127. for _, cert := range state.PeerCertificates[1:] {
  128. verifyOptions.Intermediates.AddCert(cert)
  129. }
  130. _, err := state.PeerCertificates[0].Verify(verifyOptions)
  131. return err
  132. }
  133. }
  134. if len(options.ALPN) > 0 {
  135. tlsConfig.NextProtos = options.ALPN
  136. }
  137. if options.MinVersion != "" {
  138. minVersion, err := ParseTLSVersion(options.MinVersion)
  139. if err != nil {
  140. return nil, E.Cause(err, "parse min_version")
  141. }
  142. tlsConfig.MinVersion = minVersion
  143. }
  144. if options.MaxVersion != "" {
  145. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  146. if err != nil {
  147. return nil, E.Cause(err, "parse max_version")
  148. }
  149. tlsConfig.MaxVersion = maxVersion
  150. }
  151. if options.CipherSuites != nil {
  152. find:
  153. for _, cipherSuite := range options.CipherSuites {
  154. for _, tlsCipherSuite := range tls.CipherSuites() {
  155. if cipherSuite == tlsCipherSuite.Name {
  156. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  157. continue find
  158. }
  159. }
  160. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  161. }
  162. }
  163. var certificate []byte
  164. if len(options.Certificate) > 0 {
  165. certificate = []byte(strings.Join(options.Certificate, "\n"))
  166. } else if options.CertificatePath != "" {
  167. content, err := os.ReadFile(options.CertificatePath)
  168. if err != nil {
  169. return nil, E.Cause(err, "read certificate")
  170. }
  171. certificate = content
  172. }
  173. if len(certificate) > 0 {
  174. certPool := x509.NewCertPool()
  175. if !certPool.AppendCertsFromPEM(certificate) {
  176. return nil, E.New("failed to parse certificate:\n\n", certificate)
  177. }
  178. tlsConfig.RootCAs = certPool
  179. }
  180. if options.ECH != nil && options.ECH.Enabled {
  181. var echConfig []byte
  182. if len(options.ECH.Config) > 0 {
  183. echConfig = []byte(strings.Join(options.ECH.Config, "\n"))
  184. } else if options.ECH.ConfigPath != "" {
  185. content, err := os.ReadFile(options.ECH.ConfigPath)
  186. if err != nil {
  187. return nil, E.Cause(err, "read ECH config")
  188. }
  189. echConfig = content
  190. }
  191. if echConfig != nil {
  192. tlsConfig.EncryptedClientHelloConfigList = echConfig
  193. }
  194. return &STDECHClientConfig{STDClientConfig{&tlsConfig}}, nil
  195. }
  196. return &STDClientConfig{&tlsConfig}, nil
  197. }