Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ECH: client support TLS Encrypted Client Hello #3813

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 24 additions & 13 deletions infra/conf/transport_internet.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,8 @@ type TLSConfig struct {
PinnedPeerCertificateChainSha256 *[]string `json:"pinnedPeerCertificateChainSha256"`
PinnedPeerCertificatePublicKeySha256 *[]string `json:"pinnedPeerCertificatePublicKeySha256"`
MasterKeyLog string `json:"masterKeyLog"`
ECHConfig string `json:"echConfig"`
ECHDOHServer string `json:"echDohServer"`
}

// Build implements Buildable.
Expand Down Expand Up @@ -443,7 +445,16 @@ func (c *TLSConfig) Build() (proto.Message, error) {
}
}

if c.ECHConfig != "" {
ECHConfig, err := base64.StdEncoding.DecodeString(c.ECHConfig)
if err != nil {
return nil, errors.New("invalid ECH Config", c.ECHConfig)
}
config.EchConfig = ECHConfig
}

config.MasterKeyLog = c.MasterKeyLog
config.Ech_DOHserver = c.ECHDOHServer

return config, nil
}
Expand Down Expand Up @@ -757,19 +768,19 @@ func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
}

type StreamConfig struct {
Network *TransportProtocol `json:"network"`
Security string `json:"security"`
TLSSettings *TLSConfig `json:"tlsSettings"`
REALITYSettings *REALITYConfig `json:"realitySettings"`
TCPSettings *TCPConfig `json:"tcpSettings"`
KCPSettings *KCPConfig `json:"kcpSettings"`
WSSettings *WebSocketConfig `json:"wsSettings"`
HTTPSettings *HTTPConfig `json:"httpSettings"`
SocketSettings *SocketConfig `json:"sockopt"`
GRPCConfig *GRPCConfig `json:"grpcSettings"`
GUNConfig *GRPCConfig `json:"gunSettings"`
HTTPUPGRADESettings *HttpUpgradeConfig `json:"httpupgradeSettings"`
SplitHTTPSettings *SplitHTTPConfig `json:"splithttpSettings"`
Network *TransportProtocol `json:"network"`
Security string `json:"security"`
TLSSettings *TLSConfig `json:"tlsSettings"`
REALITYSettings *REALITYConfig `json:"realitySettings"`
TCPSettings *TCPConfig `json:"tcpSettings"`
KCPSettings *KCPConfig `json:"kcpSettings"`
WSSettings *WebSocketConfig `json:"wsSettings"`
HTTPSettings *HTTPConfig `json:"httpSettings"`
SocketSettings *SocketConfig `json:"sockopt"`
GRPCConfig *GRPCConfig `json:"grpcSettings"`
GUNConfig *GRPCConfig `json:"gunSettings"`
HTTPUPGRADESettings *HttpUpgradeConfig `json:"httpupgradeSettings"`
SplitHTTPSettings *SplitHTTPConfig `json:"splithttpSettings"`
}

// Build implements Buildable.
Expand Down
12 changes: 9 additions & 3 deletions transport/internet/tls/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tls

import (
"bytes"
"context"
"crypto/hmac"
"crypto/tls"
Expand All @@ -10,7 +11,6 @@ import (
"strings"
"sync"
"time"
"bytes"

"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
Expand Down Expand Up @@ -70,7 +70,7 @@ func (c *Config) BuildCertificates() []*tls.Certificate {
continue
}
index := len(certs) - 1
setupOcspTicker(entry, func(isReloaded, isOcspstapling bool){
setupOcspTicker(entry, func(isReloaded, isOcspstapling bool) {
cert := certs[index]
if isReloaded {
if newKeyPair := getX509KeyPair(); newKeyPair != nil {
Expand Down Expand Up @@ -162,7 +162,7 @@ func (c *Config) getCustomCA() []*Certificate {
for _, certificate := range c.Certificate {
if certificate.Usage == Certificate_AUTHORITY_ISSUE {
certs = append(certs, certificate)
setupOcspTicker(certificate, func(isReloaded, isOcspstapling bool){ })
setupOcspTicker(certificate, func(isReloaded, isOcspstapling bool) {})
}
}
return certs
Expand Down Expand Up @@ -390,6 +390,12 @@ func (c *Config) GetTLSConfig(opts ...Option) *tls.Config {
config.KeyLogWriter = writer
}
}
if len(c.EchConfig) > 0 || len(c.Ech_DOHserver) > 0 {
err := ApplyECH(c, config)
if err != nil {
errors.LogError(context.Background(), err)
}
}

return config
}
Expand Down
39 changes: 30 additions & 9 deletions transport/internet/tls/config.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions transport/internet/tls/config.proto
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,6 @@ message Config {
repeated bytes pinned_peer_certificate_public_key_sha256 = 14;

string master_key_log = 15;
bytes ech_config = 16;
string ech_DOHserver = 17;
}
140 changes: 140 additions & 0 deletions transport/internet/tls/ech.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
//go:build go1.23
// +build go1.23

package tls

import (
"bytes"
"context"
"crypto/tls"
"io"
"net/http"
"sync"
"time"

"github.com/miekg/dns"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet"
)

func ApplyECH(c *Config, config *tls.Config) error {
var ECHConfig []byte
var err error

if len(c.EchConfig) > 0 {
ECHConfig = c.EchConfig
} else { // ECH config > DOH lookup
if config.ServerName == "" {
return errors.New("Using DOH for ECH needs serverName")
}
ECHConfig, err = QueryRecord(c.ServerName, c.Ech_DOHserver)
if err != nil {
return err
}
}

config.EncryptedClientHelloConfigList = ECHConfig
return nil
}

type record struct {
record []byte
expire time.Time
}

var (
dnsCache = make(map[string]record)
mutex sync.RWMutex
)

func QueryRecord(domain string, server string) ([]byte, error) {
mutex.Lock()
rec, found := dnsCache[domain]
if found && rec.expire.After(time.Now()) {
mutex.Unlock()
return rec.record, nil
}
mutex.Unlock()

errors.LogDebug(context.Background(), "Trying to query ECH config for domain: ", domain, " with ECH server: ", server)
record, ttl, err := dohQuery(server, domain)
if err != nil {
return []byte{}, err
}

if ttl < 600 {
ttl = 600
}

mutex.Lock()
defer mutex.Unlock()
rec.record = record
rec.expire = time.Now().Add(time.Second * time.Duration(ttl))
dnsCache[domain] = rec
return record, nil
}

func dohQuery(server string, domain string) ([]byte, uint32, error) {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(domain), dns.TypeHTTPS)
m.Id = 0
msg, err := m.Pack()
if err != nil {
return []byte{}, 0, err
}
tr := &http.Transport{
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := net.ParseDestination(network + ":" + addr)
if err != nil {
return nil, err
}
conn, err := internet.DialSystem(ctx, dest, nil)
if err != nil {
return nil, err
}
return conn, nil
},
}
client := &http.Client{
Timeout: 5 * time.Second,
Transport: tr,
}
req, err := http.NewRequest("POST", server, bytes.NewReader(msg))
if err != nil {
return []byte{}, 0, err
}
req.Header.Set("Content-Type", "application/dns-message")
resp, err := client.Do(req)
if err != nil {
return []byte{}, 0, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return []byte{}, 0, err
}
if resp.StatusCode != http.StatusOK {
return []byte{}, 0, errors.New("query failed with response code:", resp.StatusCode)
}
respMsg := new(dns.Msg)
err = respMsg.Unpack(respBody)
if err != nil {
return []byte{}, 0, err
}
if len(respMsg.Answer) > 0 {
for _, answer := range respMsg.Answer {
if https, ok := answer.(*dns.HTTPS); ok && https.Hdr.Name == dns.Fqdn(domain) {
for _, v := range https.Value {
if echConfig, ok := v.(*dns.SVCBECHConfig); ok {
errors.LogDebug(context.Background(), "Get ECH config:", echConfig.String(), " TTL:", respMsg.Answer[0].Header().Ttl)
return echConfig.ECH, answer.Header().Ttl, nil
}
}
}
}
}
return []byte{}, 0, errors.New("no ech record found")
}
14 changes: 14 additions & 0 deletions transport/internet/tls/ech_go121.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//go:build !go1.23
// +build !go1.23

package tls

import (
"crypto/tls"

"github.com/xtls/xray-core/common/errors"
)

func ApplyECH(c *Config, config *tls.Config) error {
return errors.New("Win7 does not support ECH")
}