ech.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. //go:build go1.23
  2. // +build go1.23
  3. package tls
  4. import (
  5. "bytes"
  6. "context"
  7. "crypto/tls"
  8. "io"
  9. "net/http"
  10. "sync"
  11. "time"
  12. "github.com/miekg/dns"
  13. "github.com/v2fly/v2ray-core/v5/common/net"
  14. "github.com/v2fly/v2ray-core/v5/transport/internet"
  15. )
  16. func ApplyECH(c *Config, config *tls.Config) error {
  17. var ECHConfig []byte
  18. var err error
  19. if len(c.EchConfig) > 0 {
  20. ECHConfig = c.EchConfig
  21. } else { // ECH config > DOH lookup
  22. if config.ServerName == "" {
  23. return newError("Using DOH for ECH needs serverName")
  24. }
  25. ECHConfig, err = QueryRecord(c.ServerName, c.Ech_DOHserver)
  26. if err != nil {
  27. return err
  28. }
  29. }
  30. config.EncryptedClientHelloConfigList = ECHConfig
  31. return nil
  32. }
  33. type record struct {
  34. record []byte
  35. expire time.Time
  36. }
  37. var (
  38. dnsCache = make(map[string]record)
  39. mutex sync.RWMutex
  40. )
  41. func QueryRecord(domain string, server string) ([]byte, error) {
  42. mutex.Lock()
  43. rec, found := dnsCache[domain]
  44. if found && rec.expire.After(time.Now()) {
  45. mutex.Unlock()
  46. return rec.record, nil
  47. }
  48. mutex.Unlock()
  49. newError("Trying to query ECH config for domain: ", domain, " with ECH server: ", server).AtDebug().WriteToLog()
  50. record, ttl, err := dohQuery(server, domain)
  51. if err != nil {
  52. return []byte{}, err
  53. }
  54. if ttl < 600 {
  55. ttl = 600
  56. }
  57. mutex.Lock()
  58. defer mutex.Unlock()
  59. rec.record = record
  60. rec.expire = time.Now().Add(time.Second * time.Duration(ttl))
  61. dnsCache[domain] = rec
  62. return record, nil
  63. }
  64. func dohQuery(server string, domain string) ([]byte, uint32, error) {
  65. m := new(dns.Msg)
  66. m.SetQuestion(dns.Fqdn(domain), dns.TypeHTTPS)
  67. m.Id = 0
  68. msg, err := m.Pack()
  69. if err != nil {
  70. return []byte{}, 0, err
  71. }
  72. tr := &http.Transport{
  73. IdleConnTimeout: 90 * time.Second,
  74. ForceAttemptHTTP2: true,
  75. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  76. dest, err := net.ParseDestination(network + ":" + addr)
  77. if err != nil {
  78. return nil, err
  79. }
  80. conn, err := internet.DialSystem(ctx, dest, nil)
  81. if err != nil {
  82. return nil, err
  83. }
  84. return conn, nil
  85. },
  86. }
  87. client := &http.Client{
  88. Timeout: 5 * time.Second,
  89. Transport: tr,
  90. }
  91. req, err := http.NewRequest("POST", server, bytes.NewReader(msg))
  92. if err != nil {
  93. return []byte{}, 0, err
  94. }
  95. req.Header.Set("Content-Type", "application/dns-message")
  96. resp, err := client.Do(req)
  97. if err != nil {
  98. return []byte{}, 0, err
  99. }
  100. defer resp.Body.Close()
  101. respBody, err := io.ReadAll(resp.Body)
  102. if err != nil {
  103. return []byte{}, 0, err
  104. }
  105. if resp.StatusCode != http.StatusOK {
  106. return []byte{}, 0, newError("query failed with response code:", resp.StatusCode)
  107. }
  108. respMsg := new(dns.Msg)
  109. err = respMsg.Unpack(respBody)
  110. if err != nil {
  111. return []byte{}, 0, err
  112. }
  113. if len(respMsg.Answer) > 0 {
  114. for _, answer := range respMsg.Answer {
  115. if https, ok := answer.(*dns.HTTPS); ok && https.Hdr.Name == dns.Fqdn(domain) {
  116. for _, v := range https.Value {
  117. if echConfig, ok := v.(*dns.SVCBECHConfig); ok {
  118. newError(context.Background(), "Get ECH config:", echConfig.String(), " TTL:", respMsg.Answer[0].Header().Ttl).AtDebug().WriteToLog()
  119. return echConfig.ECH, answer.Header().Ttl, nil
  120. }
  121. }
  122. }
  123. }
  124. }
  125. return []byte{}, 0, newError("no ech record found")
  126. }