ech_client.go 6.3 KB

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