ech_client.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. //go:build with_ech
  2. package tls
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "net"
  9. "net/netip"
  10. "os"
  11. "github.com/sagernet/sing-box/adapter"
  12. "github.com/sagernet/sing-box/option"
  13. cftls "github.com/sagernet/sing-box/transport/cloudflaretls"
  14. "github.com/sagernet/sing-dns"
  15. E "github.com/sagernet/sing/common/exceptions"
  16. mDNS "github.com/miekg/dns"
  17. )
  18. type echClientConfig struct {
  19. config *cftls.Config
  20. }
  21. func (e *echClientConfig) NextProtos() []string {
  22. return e.config.NextProtos
  23. }
  24. func (e *echClientConfig) SetNextProtos(nextProto []string) {
  25. e.config.NextProtos = nextProto
  26. }
  27. func (e *echClientConfig) Config() (*STDConfig, error) {
  28. return nil, E.New("unsupported usage for ECH")
  29. }
  30. func (e *echClientConfig) Client(conn net.Conn) Conn {
  31. return &echConnWrapper{cftls.Client(conn, e.config)}
  32. }
  33. type echConnWrapper struct {
  34. *cftls.Conn
  35. }
  36. func (c *echConnWrapper) ConnectionState() tls.ConnectionState {
  37. state := c.Conn.ConnectionState()
  38. return tls.ConnectionState{
  39. Version: state.Version,
  40. HandshakeComplete: state.HandshakeComplete,
  41. DidResume: state.DidResume,
  42. CipherSuite: state.CipherSuite,
  43. NegotiatedProtocol: state.NegotiatedProtocol,
  44. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  45. ServerName: state.ServerName,
  46. PeerCertificates: state.PeerCertificates,
  47. VerifiedChains: state.VerifiedChains,
  48. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  49. OCSPResponse: state.OCSPResponse,
  50. TLSUnique: state.TLSUnique,
  51. }
  52. }
  53. func newECHClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
  54. var serverName string
  55. if options.ServerName != "" {
  56. serverName = options.ServerName
  57. } else if serverAddress != "" {
  58. if _, err := netip.ParseAddr(serverName); err != nil {
  59. serverName = serverAddress
  60. }
  61. }
  62. if serverName == "" && !options.Insecure {
  63. return nil, E.New("missing server_name or insecure=true")
  64. }
  65. var tlsConfig cftls.Config
  66. if options.DisableSNI {
  67. tlsConfig.ServerName = "127.0.0.1"
  68. } else {
  69. tlsConfig.ServerName = serverName
  70. }
  71. if options.Insecure {
  72. tlsConfig.InsecureSkipVerify = options.Insecure
  73. } else if options.DisableSNI {
  74. tlsConfig.InsecureSkipVerify = true
  75. tlsConfig.VerifyConnection = func(state cftls.ConnectionState) error {
  76. verifyOptions := x509.VerifyOptions{
  77. DNSName: serverName,
  78. Intermediates: x509.NewCertPool(),
  79. }
  80. for _, cert := range state.PeerCertificates[1:] {
  81. verifyOptions.Intermediates.AddCert(cert)
  82. }
  83. _, err := state.PeerCertificates[0].Verify(verifyOptions)
  84. return err
  85. }
  86. }
  87. if len(options.ALPN) > 0 {
  88. tlsConfig.NextProtos = options.ALPN
  89. }
  90. if options.MinVersion != "" {
  91. minVersion, err := ParseTLSVersion(options.MinVersion)
  92. if err != nil {
  93. return nil, E.Cause(err, "parse min_version")
  94. }
  95. tlsConfig.MinVersion = minVersion
  96. }
  97. if options.MaxVersion != "" {
  98. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  99. if err != nil {
  100. return nil, E.Cause(err, "parse max_version")
  101. }
  102. tlsConfig.MaxVersion = maxVersion
  103. }
  104. if options.CipherSuites != nil {
  105. find:
  106. for _, cipherSuite := range options.CipherSuites {
  107. for _, tlsCipherSuite := range cftls.CipherSuites() {
  108. if cipherSuite == tlsCipherSuite.Name {
  109. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  110. continue find
  111. }
  112. }
  113. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  114. }
  115. }
  116. var certificate []byte
  117. if options.Certificate != "" {
  118. certificate = []byte(options.Certificate)
  119. } else if options.CertificatePath != "" {
  120. content, err := os.ReadFile(options.CertificatePath)
  121. if err != nil {
  122. return nil, E.Cause(err, "read certificate")
  123. }
  124. certificate = content
  125. }
  126. if len(certificate) > 0 {
  127. certPool := x509.NewCertPool()
  128. if !certPool.AppendCertsFromPEM(certificate) {
  129. return nil, E.New("failed to parse certificate:\n\n", certificate)
  130. }
  131. tlsConfig.RootCAs = certPool
  132. }
  133. // ECH Config
  134. tlsConfig.ECHEnabled = true
  135. tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled
  136. tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled
  137. if options.ECH.Config != "" {
  138. clientConfigContent, err := base64.StdEncoding.DecodeString(options.ECH.Config)
  139. if err != nil {
  140. return nil, err
  141. }
  142. clientConfig, err := cftls.UnmarshalECHConfigs(clientConfigContent)
  143. if err != nil {
  144. return nil, err
  145. }
  146. tlsConfig.ClientECHConfigs = clientConfig
  147. } else {
  148. tlsConfig.GetClientECHConfigs = fetchECHClientConfig(router)
  149. }
  150. return &echClientConfig{&tlsConfig}, nil
  151. }
  152. const typeHTTPS = 65
  153. func fetchECHClientConfig(router adapter.Router) func(ctx context.Context, serverName string) ([]cftls.ECHConfig, error) {
  154. return func(ctx context.Context, serverName string) ([]cftls.ECHConfig, error) {
  155. message := &mDNS.Msg{
  156. MsgHdr: mDNS.MsgHdr{
  157. RecursionDesired: true,
  158. },
  159. Question: []mDNS.Question{
  160. {
  161. Name: serverName + ".",
  162. Qtype: mDNS.TypeHTTPS,
  163. Qclass: mDNS.ClassINET,
  164. },
  165. },
  166. }
  167. response, err := router.Exchange(ctx, message)
  168. if err != nil {
  169. return nil, err
  170. }
  171. if response.Rcode != mDNS.RcodeSuccess {
  172. return nil, dns.RCodeError(response.Rcode)
  173. }
  174. for _, rr := range response.Answer {
  175. switch resource := rr.(type) {
  176. case *mDNS.HTTPS:
  177. for _, value := range resource.Value {
  178. if value.Key().String() == "ech" {
  179. echConfig, err := base64.StdEncoding.DecodeString(value.String())
  180. if err != nil {
  181. return nil, E.Cause(err, "decode ECH config")
  182. }
  183. return cftls.UnmarshalECHConfigs(echConfig)
  184. }
  185. }
  186. default:
  187. return nil, E.New("unknown resource record type: ", resource.Header().Rrtype)
  188. }
  189. }
  190. return nil, E.New("no ECH config found")
  191. }
  192. }