ech_client.go 6.6 KB

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