ech.go 3.2 KB

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