sing-box/common/tls/ech_client.go

243 lines
6.6 KiB
Go
Raw Normal View History

2022-09-09 10:19:50 +00:00
//go:build with_ech
package tls
import (
"context"
"crypto/tls"
2022-09-09 10:19:50 +00:00
"crypto/x509"
"encoding/base64"
2023-08-29 05:43:42 +00:00
"encoding/pem"
2022-09-09 10:19:50 +00:00
"net"
"net/netip"
"os"
2023-08-29 05:43:42 +00:00
"strings"
2022-09-09 10:19:50 +00:00
2022-10-31 05:30:01 +00:00
cftls "github.com/sagernet/cloudflare-tls"
2022-09-09 10:19:50 +00:00
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-dns"
E "github.com/sagernet/sing/common/exceptions"
2023-08-29 05:43:42 +00:00
"github.com/sagernet/sing/common/ntp"
"github.com/sagernet/sing/service"
2022-09-09 10:19:50 +00:00
mDNS "github.com/miekg/dns"
)
type echClientConfig struct {
config *cftls.Config
}
func (c *echClientConfig) ServerName() string {
return c.config.ServerName
}
func (c *echClientConfig) SetServerName(serverName string) {
c.config.ServerName = serverName
}
func (c *echClientConfig) NextProtos() []string {
return c.config.NextProtos
}
func (c *echClientConfig) SetNextProtos(nextProto []string) {
c.config.NextProtos = nextProto
2022-09-09 10:19:50 +00:00
}
func (c *echClientConfig) Config() (*STDConfig, error) {
2022-09-09 10:19:50 +00:00
return nil, E.New("unsupported usage for ECH")
}
func (c *echClientConfig) Client(conn net.Conn) (Conn, error) {
return &echConnWrapper{cftls.Client(conn, c.config)}, nil
}
func (c *echClientConfig) Clone() Config {
return &echClientConfig{
config: c.config.Clone(),
}
}
type echConnWrapper struct {
*cftls.Conn
}
func (c *echConnWrapper) ConnectionState() tls.ConnectionState {
state := c.Conn.ConnectionState()
return tls.ConnectionState{
Version: state.Version,
HandshakeComplete: state.HandshakeComplete,
DidResume: state.DidResume,
CipherSuite: state.CipherSuite,
NegotiatedProtocol: state.NegotiatedProtocol,
NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
ServerName: state.ServerName,
PeerCertificates: state.PeerCertificates,
VerifiedChains: state.VerifiedChains,
SignedCertificateTimestamps: state.SignedCertificateTimestamps,
OCSPResponse: state.OCSPResponse,
TLSUnique: state.TLSUnique,
}
2022-09-09 10:19:50 +00:00
}
func (c *echConnWrapper) Upstream() any {
return c.Conn
}
2023-08-29 05:43:42 +00:00
func NewECHClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
2022-09-09 10:19:50 +00:00
var serverName string
if options.ServerName != "" {
serverName = options.ServerName
} else if serverAddress != "" {
if _, err := netip.ParseAddr(serverName); err != nil {
serverName = serverAddress
}
}
if serverName == "" && !options.Insecure {
return nil, E.New("missing server_name or insecure=true")
}
var tlsConfig cftls.Config
2023-08-29 05:43:42 +00:00
tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
2022-09-09 10:19:50 +00:00
if options.DisableSNI {
tlsConfig.ServerName = "127.0.0.1"
} else {
tlsConfig.ServerName = serverName
}
if options.Insecure {
tlsConfig.InsecureSkipVerify = options.Insecure
} else if options.DisableSNI {
tlsConfig.InsecureSkipVerify = true
tlsConfig.VerifyConnection = func(state cftls.ConnectionState) error {
2022-09-09 10:19:50 +00:00
verifyOptions := x509.VerifyOptions{
DNSName: serverName,
Intermediates: x509.NewCertPool(),
}
for _, cert := range state.PeerCertificates[1:] {
verifyOptions.Intermediates.AddCert(cert)
}
_, err := state.PeerCertificates[0].Verify(verifyOptions)
return err
}
}
if len(options.ALPN) > 0 {
tlsConfig.NextProtos = options.ALPN
}
if options.MinVersion != "" {
minVersion, err := ParseTLSVersion(options.MinVersion)
if err != nil {
return nil, E.Cause(err, "parse min_version")
}
tlsConfig.MinVersion = minVersion
}
if options.MaxVersion != "" {
maxVersion, err := ParseTLSVersion(options.MaxVersion)
if err != nil {
return nil, E.Cause(err, "parse max_version")
}
tlsConfig.MaxVersion = maxVersion
}
if options.CipherSuites != nil {
find:
for _, cipherSuite := range options.CipherSuites {
for _, tlsCipherSuite := range cftls.CipherSuites() {
2022-09-09 10:19:50 +00:00
if cipherSuite == tlsCipherSuite.Name {
tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
continue find
}
}
return nil, E.New("unknown cipher_suite: ", cipherSuite)
}
}
var certificate []byte
2023-09-19 11:59:07 +00:00
if len(options.Certificate) > 0 {
certificate = []byte(strings.Join(options.Certificate, "\n"))
2022-09-09 10:19:50 +00:00
} else if options.CertificatePath != "" {
content, err := os.ReadFile(options.CertificatePath)
if err != nil {
return nil, E.Cause(err, "read certificate")
}
certificate = content
}
if len(certificate) > 0 {
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(certificate) {
return nil, E.New("failed to parse certificate:\n\n", certificate)
}
tlsConfig.RootCAs = certPool
}
// ECH Config
tlsConfig.ECHEnabled = true
tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled
tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled
var echConfig []byte
2023-08-29 05:43:42 +00:00
if len(options.ECH.Config) > 0 {
echConfig = []byte(strings.Join(options.ECH.Config, "\n"))
} else if options.ECH.ConfigPath != "" {
content, err := os.ReadFile(options.ECH.ConfigPath)
if err != nil {
return nil, E.Cause(err, "read ECH config")
}
echConfig = content
}
if len(echConfig) > 0 {
block, rest := pem.Decode(echConfig)
2023-08-29 05:43:42 +00:00
if block == nil || block.Type != "ECH CONFIGS" || len(rest) > 0 {
return nil, E.New("invalid ECH configs pem")
2022-09-09 10:19:50 +00:00
}
2023-08-29 05:43:42 +00:00
echConfigs, err := cftls.UnmarshalECHConfigs(block.Bytes)
2022-09-09 10:19:50 +00:00
if err != nil {
2023-08-29 05:43:42 +00:00
return nil, E.Cause(err, "parse ECH configs")
2022-09-09 10:19:50 +00:00
}
2023-08-29 05:43:42 +00:00
tlsConfig.ClientECHConfigs = echConfigs
2022-09-09 10:19:50 +00:00
} else {
2023-08-29 05:43:42 +00:00
tlsConfig.GetClientECHConfigs = fetchECHClientConfig(ctx)
2022-09-09 10:19:50 +00:00
}
return &echClientConfig{&tlsConfig}, nil
2022-09-09 10:19:50 +00:00
}
2023-08-29 05:43:42 +00:00
func fetchECHClientConfig(ctx context.Context) func(_ context.Context, serverName string) ([]cftls.ECHConfig, error) {
return func(_ context.Context, serverName string) ([]cftls.ECHConfig, error) {
2022-09-13 08:18:39 +00:00
message := &mDNS.Msg{
MsgHdr: mDNS.MsgHdr{
2022-09-09 10:19:50 +00:00
RecursionDesired: true,
},
2022-09-13 08:18:39 +00:00
Question: []mDNS.Question{
2022-09-09 10:19:50 +00:00
{
2022-09-13 08:18:39 +00:00
Name: serverName + ".",
Qtype: mDNS.TypeHTTPS,
Qclass: mDNS.ClassINET,
2022-09-09 10:19:50 +00:00
},
},
}
response, err := service.FromContext[adapter.Router](ctx).Exchange(ctx, message)
2022-09-09 10:19:50 +00:00
if err != nil {
return nil, err
}
2022-09-13 08:18:39 +00:00
if response.Rcode != mDNS.RcodeSuccess {
return nil, dns.RCodeError(response.Rcode)
2022-09-09 10:19:50 +00:00
}
2022-09-13 08:18:39 +00:00
for _, rr := range response.Answer {
2022-09-09 10:19:50 +00:00
switch resource := rr.(type) {
case *mDNS.HTTPS:
for _, value := range resource.Value {
if value.Key().String() == "ech" {
echConfig, err := base64.StdEncoding.DecodeString(value.String())
if err != nil {
return nil, E.Cause(err, "decode ECH config")
}
return cftls.UnmarshalECHConfigs(echConfig)
2022-09-09 10:19:50 +00:00
}
}
default:
return nil, E.New("unknown resource record type: ", resource.Header().Rrtype)
}
}
return nil, E.New("no ECH config found")
}
}