ech_client.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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, error) {
  37. return &echConnWrapper{cftls.Client(conn, e.config)}, nil
  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 (c *echConnWrapper) Upstream() any {
  65. return c.Conn
  66. }
  67. func NewECHClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
  68. var serverName string
  69. if options.ServerName != "" {
  70. serverName = options.ServerName
  71. } else if serverAddress != "" {
  72. if _, err := netip.ParseAddr(serverName); err != nil {
  73. serverName = serverAddress
  74. }
  75. }
  76. if serverName == "" && !options.Insecure {
  77. return nil, E.New("missing server_name or insecure=true")
  78. }
  79. var tlsConfig cftls.Config
  80. tlsConfig.Time = router.TimeFunc()
  81. if options.DisableSNI {
  82. tlsConfig.ServerName = "127.0.0.1"
  83. } else {
  84. tlsConfig.ServerName = serverName
  85. }
  86. if options.Insecure {
  87. tlsConfig.InsecureSkipVerify = options.Insecure
  88. } else if options.DisableSNI {
  89. tlsConfig.InsecureSkipVerify = true
  90. tlsConfig.VerifyConnection = func(state cftls.ConnectionState) error {
  91. verifyOptions := x509.VerifyOptions{
  92. DNSName: serverName,
  93. Intermediates: x509.NewCertPool(),
  94. }
  95. for _, cert := range state.PeerCertificates[1:] {
  96. verifyOptions.Intermediates.AddCert(cert)
  97. }
  98. _, err := state.PeerCertificates[0].Verify(verifyOptions)
  99. return err
  100. }
  101. }
  102. if len(options.ALPN) > 0 {
  103. tlsConfig.NextProtos = options.ALPN
  104. }
  105. if options.MinVersion != "" {
  106. minVersion, err := ParseTLSVersion(options.MinVersion)
  107. if err != nil {
  108. return nil, E.Cause(err, "parse min_version")
  109. }
  110. tlsConfig.MinVersion = minVersion
  111. }
  112. if options.MaxVersion != "" {
  113. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  114. if err != nil {
  115. return nil, E.Cause(err, "parse max_version")
  116. }
  117. tlsConfig.MaxVersion = maxVersion
  118. }
  119. if options.CipherSuites != nil {
  120. find:
  121. for _, cipherSuite := range options.CipherSuites {
  122. for _, tlsCipherSuite := range cftls.CipherSuites() {
  123. if cipherSuite == tlsCipherSuite.Name {
  124. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  125. continue find
  126. }
  127. }
  128. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  129. }
  130. }
  131. var certificate []byte
  132. if options.Certificate != "" {
  133. certificate = []byte(options.Certificate)
  134. } else if options.CertificatePath != "" {
  135. content, err := os.ReadFile(options.CertificatePath)
  136. if err != nil {
  137. return nil, E.Cause(err, "read certificate")
  138. }
  139. certificate = content
  140. }
  141. if len(certificate) > 0 {
  142. certPool := x509.NewCertPool()
  143. if !certPool.AppendCertsFromPEM(certificate) {
  144. return nil, E.New("failed to parse certificate:\n\n", certificate)
  145. }
  146. tlsConfig.RootCAs = certPool
  147. }
  148. // ECH Config
  149. tlsConfig.ECHEnabled = true
  150. tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled
  151. tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled
  152. if options.ECH.Config != "" {
  153. clientConfigContent, err := base64.StdEncoding.DecodeString(options.ECH.Config)
  154. if err != nil {
  155. return nil, err
  156. }
  157. clientConfig, err := cftls.UnmarshalECHConfigs(clientConfigContent)
  158. if err != nil {
  159. return nil, err
  160. }
  161. tlsConfig.ClientECHConfigs = clientConfig
  162. } else {
  163. tlsConfig.GetClientECHConfigs = fetchECHClientConfig(router)
  164. }
  165. return &ECHClientConfig{&tlsConfig}, nil
  166. }
  167. func fetchECHClientConfig(router adapter.Router) func(ctx context.Context, serverName string) ([]cftls.ECHConfig, error) {
  168. return func(ctx context.Context, serverName string) ([]cftls.ECHConfig, error) {
  169. message := &mDNS.Msg{
  170. MsgHdr: mDNS.MsgHdr{
  171. RecursionDesired: true,
  172. },
  173. Question: []mDNS.Question{
  174. {
  175. Name: serverName + ".",
  176. Qtype: mDNS.TypeHTTPS,
  177. Qclass: mDNS.ClassINET,
  178. },
  179. },
  180. }
  181. response, err := router.Exchange(ctx, message)
  182. if err != nil {
  183. return nil, err
  184. }
  185. if response.Rcode != mDNS.RcodeSuccess {
  186. return nil, dns.RCodeError(response.Rcode)
  187. }
  188. for _, rr := range response.Answer {
  189. switch resource := rr.(type) {
  190. case *mDNS.HTTPS:
  191. for _, value := range resource.Value {
  192. if value.Key().String() == "ech" {
  193. echConfig, err := base64.StdEncoding.DecodeString(value.String())
  194. if err != nil {
  195. return nil, E.Cause(err, "decode ECH config")
  196. }
  197. return cftls.UnmarshalECHConfigs(echConfig)
  198. }
  199. }
  200. default:
  201. return nil, E.New("unknown resource record type: ", resource.Header().Rrtype)
  202. }
  203. }
  204. return nil, E.New("no ECH config found")
  205. }
  206. }