ech_client.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. if options.DisableSNI {
  87. tlsConfig.ServerName = "127.0.0.1"
  88. } else {
  89. tlsConfig.ServerName = serverName
  90. }
  91. if options.Insecure {
  92. tlsConfig.InsecureSkipVerify = options.Insecure
  93. } else if options.DisableSNI {
  94. tlsConfig.InsecureSkipVerify = true
  95. tlsConfig.VerifyConnection = func(state cftls.ConnectionState) error {
  96. verifyOptions := x509.VerifyOptions{
  97. DNSName: serverName,
  98. Intermediates: x509.NewCertPool(),
  99. }
  100. for _, cert := range state.PeerCertificates[1:] {
  101. verifyOptions.Intermediates.AddCert(cert)
  102. }
  103. _, err := state.PeerCertificates[0].Verify(verifyOptions)
  104. return err
  105. }
  106. }
  107. if len(options.ALPN) > 0 {
  108. tlsConfig.NextProtos = options.ALPN
  109. }
  110. if options.MinVersion != "" {
  111. minVersion, err := ParseTLSVersion(options.MinVersion)
  112. if err != nil {
  113. return nil, E.Cause(err, "parse min_version")
  114. }
  115. tlsConfig.MinVersion = minVersion
  116. }
  117. if options.MaxVersion != "" {
  118. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  119. if err != nil {
  120. return nil, E.Cause(err, "parse max_version")
  121. }
  122. tlsConfig.MaxVersion = maxVersion
  123. }
  124. if options.CipherSuites != nil {
  125. find:
  126. for _, cipherSuite := range options.CipherSuites {
  127. for _, tlsCipherSuite := range cftls.CipherSuites() {
  128. if cipherSuite == tlsCipherSuite.Name {
  129. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  130. continue find
  131. }
  132. }
  133. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  134. }
  135. }
  136. var certificate []byte
  137. if len(options.Certificate) > 0 {
  138. certificate = []byte(strings.Join(options.Certificate, "\n"))
  139. } else if options.CertificatePath != "" {
  140. content, err := os.ReadFile(options.CertificatePath)
  141. if err != nil {
  142. return nil, E.Cause(err, "read certificate")
  143. }
  144. certificate = content
  145. }
  146. if len(certificate) > 0 {
  147. certPool := x509.NewCertPool()
  148. if !certPool.AppendCertsFromPEM(certificate) {
  149. return nil, E.New("failed to parse certificate:\n\n", certificate)
  150. }
  151. tlsConfig.RootCAs = certPool
  152. }
  153. // ECH Config
  154. tlsConfig.ECHEnabled = true
  155. tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled
  156. tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled
  157. var echConfig []byte
  158. if len(options.ECH.Config) > 0 {
  159. echConfig = []byte(strings.Join(options.ECH.Config, "\n"))
  160. } else if options.ECH.ConfigPath != "" {
  161. content, err := os.ReadFile(options.ECH.ConfigPath)
  162. if err != nil {
  163. return nil, E.Cause(err, "read ECH config")
  164. }
  165. echConfig = content
  166. }
  167. if len(echConfig) > 0 {
  168. block, rest := pem.Decode(echConfig)
  169. if block == nil || block.Type != "ECH CONFIGS" || len(rest) > 0 {
  170. return nil, E.New("invalid ECH configs pem")
  171. }
  172. echConfigs, err := cftls.UnmarshalECHConfigs(block.Bytes)
  173. if err != nil {
  174. return nil, E.Cause(err, "parse ECH configs")
  175. }
  176. tlsConfig.ClientECHConfigs = echConfigs
  177. } else {
  178. tlsConfig.GetClientECHConfigs = fetchECHClientConfig(ctx)
  179. }
  180. return &echClientConfig{&tlsConfig}, nil
  181. }
  182. func fetchECHClientConfig(ctx context.Context) func(_ context.Context, serverName string) ([]cftls.ECHConfig, error) {
  183. return func(_ context.Context, serverName string) ([]cftls.ECHConfig, error) {
  184. message := &mDNS.Msg{
  185. MsgHdr: mDNS.MsgHdr{
  186. RecursionDesired: true,
  187. },
  188. Question: []mDNS.Question{
  189. {
  190. Name: serverName + ".",
  191. Qtype: mDNS.TypeHTTPS,
  192. Qclass: mDNS.ClassINET,
  193. },
  194. },
  195. }
  196. response, err := service.FromContext[adapter.DNSRouter](ctx).Exchange(ctx, message, adapter.DNSQueryOptions{})
  197. if err != nil {
  198. return nil, err
  199. }
  200. if response.Rcode != mDNS.RcodeSuccess {
  201. return nil, dns.RCodeError(response.Rcode)
  202. }
  203. for _, rr := range response.Answer {
  204. switch resource := rr.(type) {
  205. case *mDNS.HTTPS:
  206. for _, value := range resource.Value {
  207. if value.Key().String() == "ech" {
  208. echConfig, err := base64.StdEncoding.DecodeString(value.String())
  209. if err != nil {
  210. return nil, E.Cause(err, "decode ECH config")
  211. }
  212. return cftls.UnmarshalECHConfigs(echConfig)
  213. }
  214. }
  215. default:
  216. return nil, E.New("unknown resource record type: ", resource.Header().Rrtype)
  217. }
  218. }
  219. return nil, E.New("no ECH config found")
  220. }
  221. }