ech_client.go 6.0 KB

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