ech_client.go 6.7 KB

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