Fix ECH client cache sharing, retry and protocol wiring

This commit is contained in:
世界
2026-11-24 22:45:19 +08:00
parent f0fbf236f8
commit 0cdfc45e26
10 changed files with 218 additions and 121 deletions
+3 -17
View File
@@ -2,7 +2,6 @@ package httpclient
import (
"context"
stdTLS "crypto/tls"
"io"
"net"
"net/http"
@@ -20,20 +19,10 @@ func dialTLS(ctx context.Context, rawDialer N.Dialer, baseTLSConfig tls.Config,
if baseTLSConfig == nil {
return nil, E.New("TLS transport unavailable")
}
tlsConfig := baseTLSConfig.Clone()
if tlsConfig.ServerName() == "" && destination.IsValid() {
tlsConfig.SetServerName(destination.AddrString())
}
tlsConfig.SetNextProtos(nextProtos)
conn, err := rawDialer.DialContext(ctx, N.NetworkTCP, destination)
tlsConn, err := tls.NewDialer(rawDialer, prepareTLSConfig(baseTLSConfig, destination, nextProtos)).DialTLSContext(ctx, destination)
if err != nil {
return nil, err
}
tlsConn, err := tls.ClientHandshake(ctx, conn, tlsConfig)
if err != nil {
conn.Close()
return nil, err
}
if expectProto != "" && tlsConn.ConnectionState().NegotiatedProtocol != expectProto {
tlsConn.Close()
return nil, errHTTP2Fallback
@@ -103,14 +92,11 @@ func requestAuthority(request *http.Request) string {
return net.JoinHostPort(host, port)
}
func buildSTDTLSConfig(baseTLSConfig tls.Config, destination M.Socksaddr, nextProtos []string) (*stdTLS.Config, error) {
if baseTLSConfig == nil {
return nil, nil
}
func prepareTLSConfig(baseTLSConfig tls.Config, destination M.Socksaddr, nextProtos []string) tls.Config {
tlsConfig := baseTLSConfig.Clone()
if tlsConfig.ServerName() == "" && destination.IsValid() {
tlsConfig.SetServerName(destination.AddrString())
}
tlsConfig.SetNextProtos(nextProtos)
return tlsConfig.STDConfig()
return tlsConfig
}
+11 -12
View File
@@ -15,6 +15,7 @@ import (
"github.com/sagernet/quic-go/http3"
"github.com/sagernet/sing-box/common/tls"
"github.com/sagernet/sing-box/option"
qtls "github.com/sagernet/sing-quic"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
@@ -72,21 +73,19 @@ func newHTTP3RoundTripper(
quicConfig = quicConfig.Clone()
quicConfig.HandshakeIdleTimeout = handshakeTimeout
}
if baseTLSConfig != nil {
var err error
tlsConfig, err = buildSTDTLSConfig(baseTLSConfig, M.ParseSocksaddr(addr), []string{http3.NextProtoH3})
if err != nil {
return nil, err
}
} else {
tlsConfig = tlsConfig.Clone()
tlsConfig.NextProtos = []string{http3.NextProtoH3}
}
conn, err := rawDialer.DialContext(ctx, N.NetworkUDP, M.ParseSocksaddr(addr))
destination := M.ParseSocksaddr(addr)
conn, err := rawDialer.DialContext(ctx, N.NetworkUDP, destination)
if err != nil {
return nil, err
}
quicConn, err := quic.DialEarlyConn(ctx, conn, tlsConfig, quicConfig)
var quicConn *quic.Conn
if baseTLSConfig != nil {
quicConn, err = qtls.DialEarly(ctx, conn, prepareTLSConfig(baseTLSConfig, destination, []string{http3.NextProtoH3}), quicConfig)
} else {
tlsConfig = tlsConfig.Clone()
tlsConfig.NextProtos = []string{http3.NextProtoH3}
quicConn, err = quic.DialEarlyConn(ctx, conn, tlsConfig, quicConfig)
}
if err != nil {
conn.Close()
return nil, err
+21 -10
View File
@@ -145,24 +145,35 @@ func (d *defaultDialer) ListenPacket(ctx context.Context, destination M.Socksadd
}
func (d *defaultDialer) DialTLSContext(ctx context.Context, destination M.Socksaddr) (Conn, error) {
return d.dialContext(ctx, destination, true)
tlsConn, err := d.dialContext(ctx, destination, d.config)
if err == nil {
return tlsConn, nil
}
var echErr *tls.ECHRejectionError
if !errors.As(err, &echErr) || len(echErr.RetryConfigList) == 0 {
return nil, err
}
retryConfig := d.config.Clone()
echTarget := retryConfig
if kTLSConfig, isKTLS := echTarget.(*KTLSClientConfig); isKTLS {
echTarget = kTLSConfig.Config
}
echConfig, isECH := echTarget.(ECHCapableConfig)
if !isECH {
return nil, err
}
echConfig.SetECHConfigList(echErr.RetryConfigList)
return d.dialContext(ctx, destination, retryConfig)
}
func (d *defaultDialer) dialContext(ctx context.Context, destination M.Socksaddr, echRetry bool) (Conn, error) {
func (d *defaultDialer) dialContext(ctx context.Context, destination M.Socksaddr, config Config) (Conn, error) {
conn, err := d.dialer.DialContext(ctx, N.NetworkTCP, destination)
if err != nil {
return nil, err
}
tlsConn, err := aTLS.ClientHandshake(ctx, conn, d.config)
tlsConn, err := aTLS.ClientHandshake(ctx, conn, config)
if err != nil {
conn.Close()
var echErr *tls.ECHRejectionError
if echRetry && errors.As(err, &echErr) && len(echErr.RetryConfigList) > 0 {
if echConfig, isECH := d.config.(ECHCapableConfig); isECH {
echConfig.SetECHConfigList(echErr.RetryConfigList)
return d.dialContext(ctx, destination, false)
}
}
return nil, err
}
return tlsConn, nil
+110 -57
View File
@@ -5,7 +5,6 @@ package tls
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/pem"
"net"
"strings"
@@ -14,6 +13,7 @@ import (
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/dialer"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/dns"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
@@ -57,6 +57,9 @@ func parseECHClientConfig(ctx context.Context, clientConfig ECHCapableConfig, op
dnsRouter: service.FromContext[adapter.DNSRouter](ctx),
domainResolver: domainResolver,
queryServerName: options.ECH.QueryServerName,
state: &echClientState{
entries: make(map[string]echClientEntry),
},
}, nil
}
}
@@ -112,19 +115,31 @@ func parseECHKeys(echKey []byte) ([]tls.EncryptedClientHelloKey, error) {
return echKeys, nil
}
type echClientState struct {
access sync.Mutex
entries map[string]echClientEntry
}
type echClientEntry struct {
configList []byte
expireAt time.Time
}
type ECHClientConfig struct {
ECHCapableConfig
access sync.Mutex
ctx context.Context
dnsRouter adapter.DNSRouter
domainResolver *option.DomainResolveOptions
queryServerName string
lastTTL time.Duration
lastUpdate time.Time
state *echClientState
}
func (s *ECHClientConfig) ClientHandshake(ctx context.Context, conn net.Conn) (aTLS.Conn, error) {
tlsConn, err := s.fetchAndHandshake(ctx, conn)
tlsConfig, err := s.handshakeConfig(ctx)
if err != nil {
return nil, err
}
tlsConn, err := tlsConfig.Client(conn)
if err != nil {
return nil, err
}
@@ -135,68 +150,106 @@ func (s *ECHClientConfig) ClientHandshake(ctx context.Context, conn net.Conn) (a
return tlsConn, nil
}
func (s *ECHClientConfig) fetchAndHandshake(ctx context.Context, conn net.Conn) (aTLS.Conn, error) {
s.access.Lock()
defer s.access.Unlock()
err := s.fetchLocked(ctx)
func (s *ECHClientConfig) handshakeConfig(ctx context.Context) (ECHCapableConfig, error) {
echConfigList, err := s.loadECHConfigList(ctx)
if err != nil {
return nil, err
}
return s.Client(conn)
tlsConfig := s.ECHCapableConfig.Clone().(ECHCapableConfig)
tlsConfig.SetECHConfigList(echConfigList)
return tlsConfig, nil
}
func (s *ECHClientConfig) fetchLocked(ctx context.Context) error {
if len(s.ECHConfigList()) == 0 || s.lastTTL == 0 || time.Since(s.lastUpdate) > s.lastTTL {
queryServerName := s.queryServerName
if queryServerName == "" {
queryServerName = s.ServerName()
func (s *ECHClientConfig) echQueryServerName() string {
if s.queryServerName != "" {
return s.queryServerName
}
return s.ServerName()
}
func (s *ECHClientConfig) loadECHConfigList(ctx context.Context) ([]byte, error) {
queryServerName := s.echQueryServerName()
s.state.access.Lock()
cachedEntry := s.state.entries[queryServerName]
s.state.access.Unlock()
if time.Now().Before(cachedEntry.expireAt) {
return cachedEntry.configList, nil
}
queryOptions, err := dialer.NewDNSQueryOptions(s.ctx, s.domainResolver, true)
if err != nil {
if s.domainResolver == nil || s.domainResolver.Server == "" {
return nil, E.Cause(err, "fetch ECH config list for ", queryServerName, ": ECH config query requires `domain_resolver` or `route.default_domain_resolver`")
}
message := &mDNS.Msg{
MsgHdr: mDNS.MsgHdr{
RecursionDesired: true,
},
Question: []mDNS.Question{
{
Name: mDNS.Fqdn(queryServerName),
Qtype: mDNS.TypeHTTPS,
Qclass: mDNS.ClassINET,
},
return nil, E.Cause(err, "fetch ECH config list for ", queryServerName)
}
message := &mDNS.Msg{
MsgHdr: mDNS.MsgHdr{
RecursionDesired: true,
},
Question: []mDNS.Question{
{
Name: mDNS.Fqdn(queryServerName),
Qtype: mDNS.TypeHTTPS,
Qclass: mDNS.ClassINET,
},
},
}
response, err := s.dnsRouter.Exchange(ctx, message, queryOptions)
if err != nil {
return nil, E.Cause(err, "fetch ECH config list for ", queryServerName)
}
if response.Rcode != mDNS.RcodeSuccess {
return nil, E.Cause(dns.RcodeError(response.Rcode), "fetch ECH config list for ", queryServerName)
}
var (
echConfigList []byte
timeToLive time.Duration
)
match:
for _, rr := range response.Answer {
record, isHTTPS := rr.(*mDNS.HTTPS)
if !isHTTPS {
continue
}
queryOptions, err := dialer.NewDNSQueryOptions(s.ctx, s.domainResolver, true)
if err != nil {
return E.Cause(err, "fetch ECH config list")
}
response, err := s.dnsRouter.Exchange(ctx, message, queryOptions)
if err != nil {
return E.Cause(err, "fetch ECH config list")
}
if response.Rcode != mDNS.RcodeSuccess {
return E.Cause(dns.RcodeError(response.Rcode), "fetch ECH config list")
}
match:
for _, rr := range response.Answer {
switch resource := rr.(type) {
case *mDNS.HTTPS:
for _, value := range resource.Value {
if value.Key().String() == "ech" {
echConfigList, err := base64.StdEncoding.DecodeString(value.String())
if err != nil {
return E.Cause(err, "decode ECH config")
}
s.lastTTL = time.Duration(rr.Header().Ttl) * time.Second
s.lastUpdate = time.Now()
s.SetECHConfigList(echConfigList)
break match
}
}
for _, value := range record.Value {
echConfig, isECHConfig := value.(*mDNS.SVCBECHConfig)
if isECHConfig && len(echConfig.ECH) > 0 {
echConfigList = echConfig.ECH
timeToLive = time.Duration(rr.Header().Ttl) * time.Second
break match
}
}
if len(s.ECHConfigList()) == 0 {
return E.New("no ECH config found in DNS records")
}
}
return nil
if len(echConfigList) == 0 {
return nil, E.New("no ECH config found in DNS records for ", queryServerName)
}
s.state.access.Lock()
defer s.state.access.Unlock()
currentEntry := s.state.entries[queryServerName]
if currentEntry.expireAt.Equal(cachedEntry.expireAt) {
currentEntry = echClientEntry{
configList: echConfigList,
expireAt: time.Now().Add(timeToLive),
}
s.state.entries[queryServerName] = currentEntry
}
return currentEntry.configList, nil
}
func (s *ECHClientConfig) ECHConfigList() []byte {
s.state.access.Lock()
defer s.state.access.Unlock()
return s.state.entries[s.echQueryServerName()].configList
}
func (s *ECHClientConfig) SetECHConfigList(echConfigList []byte) {
queryServerName := s.echQueryServerName()
s.state.access.Lock()
defer s.state.access.Unlock()
s.state.entries[queryServerName] = echClientEntry{
configList: echConfigList,
expireAt: time.Now().Add(C.DefaultDNSTTL * time.Second),
}
}
func (s *ECHClientConfig) Clone() Config {
@@ -206,7 +259,7 @@ func (s *ECHClientConfig) Clone() Config {
dnsRouter: s.dnsRouter,
domainResolver: s.domainResolver,
queryServerName: s.queryServerName,
lastUpdate: s.lastUpdate,
state: s.state,
}
}
+2 -5
View File
@@ -14,13 +14,11 @@ import (
)
func (s *ECHClientConfig) fetchSTDConfig(ctx context.Context) (*STDConfig, error) {
s.access.Lock()
defer s.access.Unlock()
err := s.fetchLocked(ctx)
tlsConfig, err := s.handshakeConfig(ctx)
if err != nil {
return nil, err
}
return s.STDConfig()
return tlsConfig.STDConfig()
}
func (s *ECHClientConfig) Dial(ctx context.Context, conn net.Conn, config *quic.Config) (*quic.Conn, error) {
@@ -59,7 +57,6 @@ func (s *ECHClientConfig) createHTTP3Transport(quicConnPtr **quic.Conn, quicConf
if err != nil {
return nil, err
}
tlsConfig = tlsConfig.Clone()
tlsConfig.NextProtos = []string{http3.NextProtoH3}
quicConn, err := dial(ctx, tlsConfig, config)
if err != nil {
+11 -1
View File
@@ -6,6 +6,7 @@ import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"math/rand"
"net"
"strings"
@@ -147,6 +148,15 @@ func (c *utlsConnWrapper) ConnectionState() tls.ConnectionState {
}
}
func (c *utlsConnWrapper) HandshakeContext(ctx context.Context) error {
err := c.UConn.HandshakeContext(ctx)
var echErr *utls.ECHRejectionError
if errors.As(err, &echErr) {
return &tls.ECHRejectionError{RetryConfigList: echErr.RetryConfigList}
}
return err
}
func (c *utlsConnWrapper) Upstream() any {
return c.UConn
}
@@ -181,7 +191,7 @@ func (c *utlsALPNWrapper) HandshakeContext(ctx context.Context) error {
}
}
}
return c.UConn.HandshakeContext(ctx)
return c.utlsConnWrapper.HandshakeContext(ctx)
}
func NewUTLSClient(ctx context.Context, logger logger.ContextLogger, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
+16 -5
View File
@@ -18,6 +18,7 @@ import (
"github.com/sagernet/sing-box/dns/transport"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
sQUIC "github.com/sagernet/sing-quic"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
E "github.com/sagernet/sing/common/exceptions"
@@ -42,7 +43,7 @@ type HTTP3Transport struct {
destination *url.URL
headers http.Header
serverAddr M.Socksaddr
tlsConfig *tls.STDConfig
tlsConfig tls.Config
transportAccess sync.Mutex
transport *http3.Transport
}
@@ -54,12 +55,19 @@ func NewHTTP3(ctx context.Context, logger log.ContextLogger, tag string, options
}
tlsOptions := common.PtrValueOrDefault(options.TLS)
tlsOptions.Enabled = true
tlsConfig, err := tls.NewClient(ctx, logger, options.Server, tlsOptions)
tlsConfig, err := tls.NewClientWithOptions(tls.ClientOptions{
Context: ctx,
Logger: logger,
ServerAddress: options.Server,
Options: tlsOptions,
DomainResolver: options.DomainResolver,
DirectResolver: true,
})
if err != nil {
return nil, err
}
tlsConfig.SetNextProtos([]string{http3.NextProtoH3})
stdConfig, err := tlsConfig.STDConfig()
_, err = tlsConfig.STDConfig()
if err != nil {
return nil, err
}
@@ -105,7 +113,7 @@ func NewHTTP3(ctx context.Context, logger log.ContextLogger, tag string, options
destination: &destinationURL,
headers: headers,
serverAddr: serverAddr,
tlsConfig: stdConfig,
tlsConfig: tlsConfig,
}
t.transport = t.newTransport()
return t, nil
@@ -113,12 +121,15 @@ func NewHTTP3(ctx context.Context, logger log.ContextLogger, tag string, options
func (t *HTTP3Transport) newTransport() *http3.Transport {
return &http3.Transport{
QUICConfig: &quic.Config{
InitialPacketSize: 1200,
},
Dial: func(ctx context.Context, _ string, _ *tls.STDConfig, cfg *quic.Config) (*quic.Conn, error) {
conn, dialErr := t.dialer.DialContext(ctx, N.NetworkUDP, t.serverAddr)
if dialErr != nil {
return nil, dialErr
}
quicConn, dialErr := quic.DialEarlyConn(ctx, conn, t.tlsConfig, cfg)
quicConn, dialErr := sQUIC.DialEarly(ctx, conn, t.tlsConfig, cfg)
if dialErr != nil {
conn.Close()
return nil, dialErr
+7 -1
View File
@@ -61,6 +61,10 @@ func NewQUIC(ctx context.Context, logger log.ContextLogger, tag string, options
if len(tlsConfig.NextProtos()) == 0 {
tlsConfig.SetNextProtos([]string{"doq"})
}
_, err = tlsConfig.STDConfig()
if err != nil {
return nil, err
}
serverAddr := options.DNSServerAddressOptions.Build()
if serverAddr.Port == 0 {
serverAddr.Port = 853
@@ -114,7 +118,9 @@ func (t *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg,
ctx,
rawConn,
t.tlsConfig,
nil,
&quic.Config{
InitialPacketSize: 1200,
},
)
if err != nil {
rawConn.Close()
+8 -3
View File
@@ -14,6 +14,7 @@ import (
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-shadowtls"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
@@ -38,6 +39,9 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
if options.Version == 0 {
options.Version = 1
}
if options.Version != 2 && options.TLS.ECH != nil && options.TLS.ECH.Enabled {
return nil, E.New("ECH is only supported in ShadowTLS v2")
}
if options.Version == 1 {
options.TLS.MinVersion = "1.2"
@@ -61,10 +65,11 @@ func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextL
return common.Error(tls.ClientHandshake(ctx, conn, tlsConfig))
}
case 3:
if idConfig, loaded := tlsConfig.(tls.WithSessionIDGenerator); loaded {
if _, loaded := tlsConfig.(tls.WithSessionIDGenerator); loaded {
tlsHandshakeFunc = func(ctx context.Context, conn net.Conn, sessionIDGenerator shadowtls.TLSSessionIDGeneratorFunc) error {
idConfig.SetSessionIDGenerator(sessionIDGenerator)
return common.Error(tls.ClientHandshake(ctx, conn, tlsConfig))
handshakeConfig := tlsConfig.Clone()
handshakeConfig.(tls.WithSessionIDGenerator).SetSessionIDGenerator(sessionIDGenerator)
return common.Error(tls.ClientHandshake(ctx, conn, handshakeConfig))
}
} else {
stdTLSConfig, err := tlsConfig.STDConfig()
+29 -10
View File
@@ -294,23 +294,35 @@ func (d *Service) startMeshWithHost(derpServer *derpserver.Server, server *optio
} else {
hostname = server.Server
}
var stdConfig *tls.STDConfig
var (
tlsConfig tls.Config
stdConfig *tls.STDConfig
)
if server.TLS != nil && server.TLS.Enabled {
tlsConfig, err := tls.NewClient(d.ctx, d.logger, hostname, *server.TLS)
tlsConfig, err = tls.NewClientWithOptions(tls.ClientOptions{
Context: d.ctx,
Logger: d.logger,
ServerAddress: hostname,
Options: *server.TLS,
DomainResolver: server.DomainResolver,
})
if err != nil {
return err
}
stdConfig, err = tlsConfig.STDConfig()
if err != nil {
return err
if _, isDynamicECH := tlsConfig.(*tls.ECHClientConfig); !isDynamicECH {
stdConfig, _ = tlsConfig.STDConfig()
}
}
logf := func(format string, args ...any) {
d.logger.Debug(F.ToString("mesh(", hostname, "): ", fmt.Sprintf(format, args...)))
}
meshAddress := M.ParseSocksaddrHostPort(hostname, server.ServerPort)
meshPort := server.ServerPort
if meshPort == 0 && tlsConfig != nil {
meshPort = 443
}
meshAddress := M.ParseSocksaddrHostPort(hostname, meshPort)
var meshHost string
if server.ServerPort != 0 && server.ServerPort != 443 {
if meshPort != 0 && (stdConfig == nil || meshPort != 443) {
meshHost = meshAddress.String()
} else if meshAddress.IsIPv6() {
meshHost = "[" + meshAddress.AddrString() + "]"
@@ -330,9 +342,16 @@ func (d *Service) startMeshWithHost(derpServer *derpserver.Server, server *optio
meshClient.TLSConfig = stdConfig
meshClient.MeshKey = derpServer.MeshKey()
meshClient.WatchConnectionChanges = true
meshClient.SetURLDialer(func(ctx context.Context, network, addr string) (net.Conn, error) {
return meshDialer.DialContext(ctx, network, M.ParseSocksaddrHostPort(server.Server, M.ParseSocksaddr(addr).Port))
})
if tlsConfig != nil && stdConfig == nil {
tlsDialer := tls.NewDialer(meshDialer, tlsConfig)
meshClient.SetURLDialer(func(ctx context.Context, network, addr string) (net.Conn, error) {
return tlsDialer.DialTLSContext(ctx, M.ParseSocksaddrHostPort(server.Server, M.ParseSocksaddr(addr).Port))
})
} else {
meshClient.SetURLDialer(func(ctx context.Context, network, addr string) (net.Conn, error) {
return meshDialer.DialContext(ctx, network, M.ParseSocksaddrHostPort(server.Server, M.ParseSocksaddr(addr).Port))
})
}
add := func(m derp.PeerPresentMessage) { derpServer.AddPacketForwarder(m.Key, meshClient) }
remove := func(m derp.PeerGoneMessage) { derpServer.RemovePacketForwarder(m.Peer, meshClient) }
notifyError := func(err error) { d.logger.Error(err) }