From 309cfbd61327f6223f5d777e9a6b62e6587f4e68 Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Tue, 14 Jul 2026 17:22:01 +0800 Subject: [PATCH] chore: reimplement shadowtls --- adapter/outbound/shadowsocks.go | 2 +- adapter/outbound/snell.go | 2 +- common/net/context.go | 22 ++ common/net/context_test.go | 29 ++ go.mod | 1 - go.sum | 2 - listener/inbound/shadowsocks_test.go | 2 +- listener/inbound/snell_test.go | 2 +- listener/shadowtls/listener.go | 75 +++++ listener/sing_shadowsocks/server.go | 67 +---- listener/snell/server.go | 65 +---- transport/shadowtls/client.go | 191 ++++++++++++ transport/shadowtls/protocol.go | 193 ++++++++++++ transport/shadowtls/server.go | 403 ++++++++++++++++++++++++++ transport/shadowtls/server_test.go | 343 ++++++++++++++++++++++ transport/shadowtls/shadowtls.go | 152 ---------- transport/shadowtls/v2.go | 209 +++++++++++++ transport/shadowtls/v3.go | 300 +++++++++++++++++++ transport/sing-shadowtls/shadowtls.go | 100 ------- 19 files changed, 1789 insertions(+), 371 deletions(-) create mode 100644 listener/shadowtls/listener.go create mode 100644 transport/shadowtls/client.go create mode 100644 transport/shadowtls/protocol.go create mode 100644 transport/shadowtls/server.go create mode 100644 transport/shadowtls/server_test.go delete mode 100644 transport/shadowtls/shadowtls.go create mode 100644 transport/shadowtls/v2.go create mode 100644 transport/shadowtls/v3.go delete mode 100644 transport/sing-shadowtls/shadowtls.go diff --git a/adapter/outbound/shadowsocks.go b/adapter/outbound/shadowsocks.go index 08a2247c..8c562a8d 100644 --- a/adapter/outbound/shadowsocks.go +++ b/adapter/outbound/shadowsocks.go @@ -14,8 +14,8 @@ import ( "github.com/metacubex/mihomo/transport/jls" "github.com/metacubex/mihomo/transport/kcptun" "github.com/metacubex/mihomo/transport/restls" + "github.com/metacubex/mihomo/transport/shadowtls" obfs "github.com/metacubex/mihomo/transport/simple-obfs" - shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls" v2rayObfs "github.com/metacubex/mihomo/transport/v2ray-plugin" shadowsocks "github.com/metacubex/sing-shadowsocks2" diff --git a/adapter/outbound/snell.go b/adapter/outbound/snell.go index 7e29b842..ff31a483 100644 --- a/adapter/outbound/snell.go +++ b/adapter/outbound/snell.go @@ -9,8 +9,8 @@ import ( N "github.com/metacubex/mihomo/common/net" "github.com/metacubex/mihomo/common/structure" C "github.com/metacubex/mihomo/constant" + "github.com/metacubex/mihomo/transport/shadowtls" obfs "github.com/metacubex/mihomo/transport/simple-obfs" - shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls" "github.com/metacubex/mihomo/transport/snell" ) diff --git a/common/net/context.go b/common/net/context.go index b170516e..648ed1dc 100644 --- a/common/net/context.go +++ b/common/net/context.go @@ -37,3 +37,25 @@ func SetupContextForConn(ctx context.Context, conn net.Conn) (done func(*error)) } } } + +// RelayContext copies between left and right bidirectionally. +// If ctx is canceled, both connections are closed to interrupt pending I/O. +func RelayContext(ctx context.Context, leftConn, rightConn net.Conn) error { + if ctx.Done() == nil { + Relay(leftConn, rightConn) + return nil + } + + done := make(chan struct{}) + stop := contextutils.AfterFunc(ctx, func() { + _ = leftConn.Close() + _ = rightConn.Close() + close(done) + }) + Relay(leftConn, rightConn) + if !stop() { + <-done + return ctx.Err() + } + return nil +} diff --git a/common/net/context_test.go b/common/net/context_test.go index 8e4c4ad1..be812588 100644 --- a/common/net/context_test.go +++ b/common/net/context_test.go @@ -101,3 +101,32 @@ func TestSetupContextForConnWithTimeout2(t *testing.T) { t.Fatal("conn not be canceled") } } + +func TestRelayContextWithCancel(t *testing.T) { + t.Parallel() + leftConn, leftPeer := N.Pipe() + rightConn, rightPeer := N.Pipe() + defer leftPeer.Close() + defer rightPeer.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + errc := make(chan error) + go func() { + errc <- N.RelayContext(ctx, leftConn, rightConn) + }() + + select { + case <-errc: + t.Fatal("relay stopped before cancel") + case <-time.After(100 * time.Millisecond): + cancel() + } + + select { + case err := <-errc: + assert.ErrorIs(t, err, context.Canceled) + case <-time.After(100 * time.Millisecond): + t.Fatal("relay was not canceled") + } +} diff --git a/go.mod b/go.mod index 63fe855e..cffb067a 100644 --- a/go.mod +++ b/go.mod @@ -37,7 +37,6 @@ require ( github.com/metacubex/sing-quic v0.0.0-20260527143057-68e10a6afdc3 github.com/metacubex/sing-shadowsocks v0.2.12 github.com/metacubex/sing-shadowsocks2 v0.2.7 - github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc github.com/metacubex/sing-tun v0.4.21 github.com/metacubex/sing-vmess v0.2.5 github.com/metacubex/sing-wireguard v0.0.0-20260520151737-7e7c7c1b854c diff --git a/go.sum b/go.sum index 6362b27c..b219457e 100644 --- a/go.sum +++ b/go.sum @@ -167,8 +167,6 @@ github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsa github.com/metacubex/sing-shadowsocks v0.2.12/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU= github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6wVj3PPBVhor3A= github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE= -github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc h1:8wLoFfYQ88iGPL+krQ5tJsI8IAmkFjKpQL2q+y3pvss= -github.com/metacubex/sing-shadowtls v0.0.0-20260517015314-c11c36474edc/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E= github.com/metacubex/sing-tun v0.4.21 h1:MjbPYytM240VH70lO182v2Sg/JthMmx6R6z6E2fCR2I= github.com/metacubex/sing-tun v0.4.21/go.mod h1:g4I/JNplDBhXLF+aQWgFbhNeJPSXQOWS9HvLeNvkgeA= github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE= diff --git a/listener/inbound/shadowsocks_test.go b/listener/inbound/shadowsocks_test.go index 4a466fa7..a288285e 100644 --- a/listener/inbound/shadowsocks_test.go +++ b/listener/inbound/shadowsocks_test.go @@ -14,7 +14,7 @@ import ( "github.com/metacubex/mihomo/transport/jls" "github.com/metacubex/mihomo/transport/kcptun" "github.com/metacubex/mihomo/transport/restls" - shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls" + "github.com/metacubex/mihomo/transport/shadowtls" shadowsocks "github.com/metacubex/sing-shadowsocks" "github.com/metacubex/sing-shadowsocks/shadowaead" diff --git a/listener/inbound/snell_test.go b/listener/inbound/snell_test.go index 5dbb4ddb..80eec443 100644 --- a/listener/inbound/snell_test.go +++ b/listener/inbound/snell_test.go @@ -7,7 +7,7 @@ import ( "github.com/metacubex/mihomo/adapter/outbound" "github.com/metacubex/mihomo/listener/inbound" - shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls" + "github.com/metacubex/mihomo/transport/shadowtls" "github.com/stretchr/testify/assert" ) diff --git a/listener/shadowtls/listener.go b/listener/shadowtls/listener.go new file mode 100644 index 00000000..29c14441 --- /dev/null +++ b/listener/shadowtls/listener.go @@ -0,0 +1,75 @@ +package shadowtls + +import ( + "context" + "net" + "runtime/debug" + + N "github.com/metacubex/mihomo/common/net" + C "github.com/metacubex/mihomo/constant" + LC "github.com/metacubex/mihomo/listener/config" + "github.com/metacubex/mihomo/listener/inner" + "github.com/metacubex/mihomo/log" + "github.com/metacubex/mihomo/transport/shadowtls" +) + +type Builder struct { + config *shadowtls.ServerConfig +} + +func New(config LC.ShadowTLS, tunnel C.Tunnel) (*Builder, error) { + buildHandshake := func(handshake LC.ShadowTLSHandshakeOptions) shadowtls.HandshakeConfig { + return shadowtls.HandshakeConfig{ + Server: handshake.Dest, + DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + return inner.HandleTcp(tunnel, address, handshake.Proxy) + }, + } + } + var handshakeForServerName map[string]shadowtls.HandshakeConfig + if config.Version > 1 { + handshakeForServerName = make(map[string]shadowtls.HandshakeConfig, len(config.HandshakeForServerName)) + for serverName, serverOptions := range config.HandshakeForServerName { + handshakeForServerName[serverName] = buildHandshake(serverOptions) + } + } + users := make([]shadowtls.User, len(config.Users)) + for i, user := range config.Users { + users[i] = shadowtls.User{Name: user.Name, Password: user.Password} + } + var wildcardSNI shadowtls.WildcardSNI + switch config.WildcardSNI { + case "authed": + wildcardSNI = shadowtls.WildcardSNIAuthed + case "all": + wildcardSNI = shadowtls.WildcardSNIAll + default: + wildcardSNI = shadowtls.WildcardSNIOff + } + serverConfig, err := shadowtls.NewServerConfig( + config.Version, + config.Password, + users, + buildHandshake(config.Handshake), + handshakeForServerName, + config.StrictMode, + wildcardSNI, + ) + if err != nil { + return nil, err + } + return &Builder{config: serverConfig}, nil +} + +func (b Builder) NewListener(listener net.Listener) net.Listener { + return N.NewHandleContextListener(context.Background(), listener, func(ctx context.Context, conn net.Conn) (net.Conn, error) { + return shadowtls.Server(ctx, conn, b.config) + }, func(a any) { + stack := debug.Stack() + log.Errorln("shadowtls server panic: %s\n%s", a, stack) + }) +} + +func UserFromConn(conn net.Conn) (string, bool) { + return shadowtls.UserFromConn(conn) +} diff --git a/listener/sing_shadowsocks/server.go b/listener/sing_shadowsocks/server.go index 4641a86d..4ed5ab58 100644 --- a/listener/sing_shadowsocks/server.go +++ b/listener/sing_shadowsocks/server.go @@ -12,6 +12,7 @@ import ( LC "github.com/metacubex/mihomo/listener/config" "github.com/metacubex/mihomo/listener/inner" embedSS "github.com/metacubex/mihomo/listener/shadowsocks" + "github.com/metacubex/mihomo/listener/shadowtls" "github.com/metacubex/mihomo/listener/sing" "github.com/metacubex/mihomo/log" "github.com/metacubex/mihomo/ntp" @@ -23,8 +24,8 @@ import ( shadowsocks "github.com/metacubex/sing-shadowsocks" "github.com/metacubex/sing-shadowsocks/shadowaead" "github.com/metacubex/sing-shadowsocks/shadowaead_2022" - shadowtls "github.com/metacubex/sing-shadowtls" "github.com/metacubex/sing/common" + "github.com/metacubex/sing/common/auth" "github.com/metacubex/sing/common/buf" "github.com/metacubex/sing/common/bufio" M "github.com/metacubex/sing/common/metadata" @@ -37,7 +38,6 @@ type Listener struct { listeners []net.Listener udpListeners []net.PacketConn service shadowsocks.Service - shadowTLS *shadowtls.Service resTLS *restls.ServerConfig jls *jls.ServerConfig simpleObfs func(net.Conn) net.Conn @@ -45,19 +45,6 @@ type Listener struct { var _listener *Listener -// shadowTLSService is a wrapper for shadowsocks.Service to support shadowTLS. -type shadowTLSService struct { - shadowsocks.Service - shadowTLS *shadowtls.Service -} - -func (s *shadowTLSService) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { - if s.shadowTLS != nil { - return s.shadowTLS.NewConnection(ctx, conn, metadata) - } - return s.Service.NewConnection(ctx, conn, metadata) -} - func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (C.MultiAddrListener, error) { var sl *Listener var err error @@ -101,49 +88,12 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel, return nil, err } + var shadowTLSBuilder *shadowtls.Builder if config.ShadowTLS.Enable { - buildHandshake := func(handshake LC.ShadowTLSHandshakeOptions) (handshakeConfig shadowtls.HandshakeConfig) { - handshakeConfig.Server = M.ParseSocksaddr(handshake.Dest) - handshakeConfig.Dialer = sing.NewDialer(tunnel, handshake.Proxy) - return - } - var handshakeForServerName map[string]shadowtls.HandshakeConfig - if config.ShadowTLS.Version > 1 { - handshakeForServerName = make(map[string]shadowtls.HandshakeConfig) - for serverName, serverOptions := range config.ShadowTLS.HandshakeForServerName { - handshakeForServerName[serverName] = buildHandshake(serverOptions) - } - } - var wildcardSNI shadowtls.WildcardSNI - switch config.ShadowTLS.WildcardSNI { - case "authed": - wildcardSNI = shadowtls.WildcardSNIAuthed - case "all": - wildcardSNI = shadowtls.WildcardSNIAll - default: - wildcardSNI = shadowtls.WildcardSNIOff - } - var shadowTLS *shadowtls.Service - shadowTLS, err = shadowtls.NewService(shadowtls.ServiceConfig{ - Version: config.ShadowTLS.Version, - Password: config.ShadowTLS.Password, - Users: common.Map(config.ShadowTLS.Users, func(it LC.ShadowTLSUser) shadowtls.User { - return shadowtls.User{Name: it.Name, Password: it.Password} - }), - Handshake: buildHandshake(config.ShadowTLS.Handshake), - HandshakeForServerName: handshakeForServerName, - StrictMode: config.ShadowTLS.StrictMode, - WildcardSNI: wildcardSNI, - Handler: sl.service, - Logger: log.SingLogger, - }) + shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel) if err != nil { return nil, err } - sl.service = &shadowTLSService{ - Service: sl.service, - shadowTLS: shadowTLS, - } } if config.ResTLS.Enable { @@ -262,6 +212,9 @@ func New(config LC.ShadowsocksServer, lc C.InboundListenConfig, tunnel C.Tunnel, if err != nil { return nil, err } + if shadowTLSBuilder != nil { + l = shadowTLSBuilder.NewListener(l) + } sl.listeners = append(sl.listeners, l) go func() { @@ -315,7 +268,7 @@ func (l *Listener) AddrList() (addrList []net.Addr) { } func (l *Listener) HandleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) { - ctx := sing.WithAdditions(context.TODO(), additions...) + user, loaded := shadowtls.UserFromConn(conn) if l.jls != nil { c, err := jls.Server(context.TODO(), conn, l.jls) if err != nil { @@ -335,6 +288,10 @@ func (l *Listener) HandleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbou if l.simpleObfs != nil { conn = l.simpleObfs(conn) } + ctx := sing.WithAdditions(context.TODO(), additions...) + if loaded { + ctx = auth.ContextWithUser(ctx, user) + } err := l.service.NewConnection(ctx, conn, M.Metadata{ Protocol: "shadowsocks", Source: M.SocksaddrFromNet(conn.RemoteAddr()), diff --git a/listener/snell/server.go b/listener/snell/server.go index 84b63ac5..7c4761fa 100644 --- a/listener/snell/server.go +++ b/listener/snell/server.go @@ -17,15 +17,10 @@ import ( "github.com/metacubex/mihomo/common/utils" C "github.com/metacubex/mihomo/constant" LC "github.com/metacubex/mihomo/listener/config" - "github.com/metacubex/mihomo/listener/sing" - "github.com/metacubex/mihomo/log" + "github.com/metacubex/mihomo/listener/shadowtls" "github.com/metacubex/mihomo/transport/shadowsocks/shadowaead" obfs "github.com/metacubex/mihomo/transport/simple-obfs" "github.com/metacubex/mihomo/transport/snell" - - shadowtls "github.com/metacubex/sing-shadowtls" - "github.com/metacubex/sing/common" - M "github.com/metacubex/sing/common/metadata" ) const maxPacketLength = 0x3fff @@ -34,7 +29,6 @@ type Listener struct { closed bool config LC.SnellServer listeners []net.Listener - shadowTLS *shadowtls.Service } func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (C.MultiAddrListener, error) { @@ -57,46 +51,10 @@ func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit l := &Listener{config: config} + var shadowTLSBuilder *shadowtls.Builder if config.ShadowTLS.Enable { - buildHandshake := func(handshake LC.ShadowTLSHandshakeOptions) (handshakeConfig shadowtls.HandshakeConfig) { - handshakeConfig.Server = M.ParseSocksaddr(handshake.Dest) - handshakeConfig.Dialer = sing.NewDialer(tunnel, handshake.Proxy) - return - } - var handshakeForServerName map[string]shadowtls.HandshakeConfig - if config.ShadowTLS.Version > 1 { - handshakeForServerName = make(map[string]shadowtls.HandshakeConfig) - for serverName, serverOptions := range config.ShadowTLS.HandshakeForServerName { - handshakeForServerName[serverName] = buildHandshake(serverOptions) - } - } - var wildcardSNI shadowtls.WildcardSNI - switch config.ShadowTLS.WildcardSNI { - case "authed": - wildcardSNI = shadowtls.WildcardSNIAuthed - case "all": - wildcardSNI = shadowtls.WildcardSNIAll - default: - wildcardSNI = shadowtls.WildcardSNIOff - } var err error - l.shadowTLS, err = shadowtls.NewService(shadowtls.ServiceConfig{ - Version: config.ShadowTLS.Version, - Password: config.ShadowTLS.Password, - Users: common.Map(config.ShadowTLS.Users, func(it LC.ShadowTLSUser) shadowtls.User { - return shadowtls.User{Name: it.Name, Password: it.Password} - }), - Handshake: buildHandshake(config.ShadowTLS.Handshake), - HandshakeForServerName: handshakeForServerName, - StrictMode: config.ShadowTLS.StrictMode, - WildcardSNI: wildcardSNI, - Handler: sing.FnHandler{ - NewConnectionFn: func(ctx context.Context, conn net.Conn, metadata M.Metadata) error { - l.handleConn(conn, tunnel, sing.AdditionsFromContext(ctx)...) - return nil - }}, - Logger: log.SingLogger, - }) + shadowTLSBuilder, err = shadowtls.New(config.ShadowTLS, tunnel) if err != nil { return nil, err } @@ -111,6 +69,9 @@ func New(config LC.SnellServer, lc C.InboundListenConfig, tunnel C.Tunnel, addit _ = l.Close() return nil, err } + if shadowTLSBuilder != nil { + ln = shadowTLSBuilder.NewListener(ln) + } l.listeners = append(l.listeners, ln) go func(ln net.Listener) { for { @@ -152,19 +113,9 @@ func (l *Listener) AddrList() (addrList []net.Addr) { func (l *Listener) HandleConn(rawConn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) { defer rawConn.Close() - conn := rawConn - if l.shadowTLS != nil { - ctx := sing.WithAdditions(context.TODO(), additions...) - _ = l.shadowTLS.NewConnection(ctx, conn, M.Metadata{ - Protocol: "snell", - Source: M.SocksaddrFromNet(conn.RemoteAddr()), - }) - return + if user, loaded := shadowtls.UserFromConn(rawConn); loaded { + additions = append(append([]inbound.Addition(nil), additions...), inbound.WithInUser(user)) } - l.handleConn(rawConn, tunnel, additions...) -} - -func (l *Listener) handleConn(rawConn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) { conn := rawConn switch l.config.ObfsMode { case "http": diff --git a/transport/shadowtls/client.go b/transport/shadowtls/client.go new file mode 100644 index 00000000..c70bffb3 --- /dev/null +++ b/transport/shadowtls/client.go @@ -0,0 +1,191 @@ +package shadowtls + +import ( + "context" + "crypto/hmac" + "crypto/sha1" + "encoding/hex" + "errors" + "fmt" + "net" + + "github.com/metacubex/mihomo/component/ca" + tlsC "github.com/metacubex/mihomo/component/tls" + "github.com/metacubex/mihomo/log" + + "github.com/metacubex/tls" + "golang.org/x/exp/slices" +) + +const Mode = "shadow-tls" + +var ( + DefaultALPN = []string{"h2", "http/1.1"} + WsALPN = []string{"http/1.1"} +) + +type TLSSessionIDGeneratorFunc func(clientHello []byte, sessionID []byte) error + +type TLSHandshakeFunc func( + ctx context.Context, + conn net.Conn, + sessionIDGenerator TLSSessionIDGeneratorFunc, // for shadow-tls version 3 +) error + +type ShadowTLSOption struct { + Password string + Host string + Fingerprint string + Certificate string + PrivateKey string + ClientFingerprint string + SkipCertVerify bool + NameCertVerify string + Version int + ALPN []string +} + +type ClientConfig struct { + Version int + Password string + StrictMode bool + TLSHandshake TLSHandshakeFunc +} + +type Client struct { + version int + password string + strictMode bool + tlsHandshake TLSHandshakeFunc +} + +func NewClient(config ClientConfig) (*Client, error) { + if err := checkVersion(config.Version); err != nil { + return nil, err + } + return &Client{ + version: config.Version, + password: config.Password, + strictMode: config.StrictMode, + tlsHandshake: config.TLSHandshake, + }, nil +} + +func (c *Client) SetHandshakeFunc(handshakeFunc TLSHandshakeFunc) { + c.tlsHandshake = handshakeFunc +} + +func (c *Client) DialContextConn(ctx context.Context, conn net.Conn) (net.Conn, error) { + if conn == nil || c.tlsHandshake == nil { + return nil, errors.New("shadow-tls: connection and TLS handshake are required") + } + switch c.version { + case 1: + if err := c.tlsHandshake(ctx, conn, nil); err != nil { + return nil, err + } + log.Debugln("[ShadowTLS] client handshake finished") + return conn, nil + case 2: + hashConn := newHashReadConn(conn, c.password) + if err := c.tlsHandshake(ctx, hashConn, nil); err != nil { + return nil, err + } + log.Debugln("[ShadowTLS] client handshake finished") + return newClientConn(hashConn), nil + case 3: + stream := newStreamWrapper(conn, c.password) + if err := c.tlsHandshake(ctx, stream, generateSessionID(c.password)); err != nil { + return nil, err + } + log.Debugln("[ShadowTLS] handshake success") + isTLS13, authorized, serverRandom, readHMAC := stream.Authorized() + if c.strictMode && !isTLS13 { + return nil, errors.New("shadow-tls: TLS 1.3 is not supported") + } + if !authorized { + return nil, errors.New("shadow-tls: traffic hijacked") + } + if log.Level() == log.DEBUG { + log.Debugln("[ShadowTLS] authorized, server random extracted: %s", hex.EncodeToString(serverRandom)) + } + hmacAdd := hmac.New(sha1.New, []byte(c.password)) + _, _ = hmacAdd.Write(serverRandom) + _, _ = hmacAdd.Write([]byte("C")) + hmacVerify := hmac.New(sha1.New, []byte(c.password)) + _, _ = hmacVerify.Write(serverRandom) + _, _ = hmacVerify.Write([]byte("S")) + return newVerifiedConn(conn, hmacAdd, hmacVerify, readHMAC), nil + default: + panic("unreachable") + } +} + +func NewShadowTLS(ctx context.Context, conn net.Conn, option *ShadowTLSOption) (net.Conn, error) { + if option == nil { + return nil, errors.New("shadow-tls: nil client option") + } + if err := checkVersion(option.Version); err != nil { + return nil, err + } + tlsConfig, err := ca.GetTLSConfig(ca.Option{ + TLSConfig: &tls.Config{ + NextProtos: append([]string(nil), option.ALPN...), + MinVersion: tls.VersionTLS12, + InsecureSkipVerify: option.SkipCertVerify, + ServerName: option.Host, + }, + Fingerprint: option.Fingerprint, + NameCertVerify: option.NameCertVerify, + Certificate: option.Certificate, + PrivateKey: option.PrivateKey, + }) + if err != nil { + return nil, err + } + if option.Version == 1 { + tlsConfig.MaxVersion = tls.VersionTLS12 // ShadowTLS v1 only support TLS 1.2 + } + client, err := NewClient(ClientConfig{ + Version: option.Version, + Password: option.Password, + TLSHandshake: uTLSHandshakeFunc(tlsConfig, option.ClientFingerprint, option.Version), + }) + if err != nil { + return nil, err + } + return client.DialContextConn(ctx, conn) +} + +func uTLSHandshakeFunc(config *tls.Config, clientFingerprint string, version int) TLSHandshakeFunc { + return func(ctx context.Context, conn net.Conn, sessionIDGenerator TLSSessionIDGeneratorFunc) error { + tlsConfig := tlsC.UConfig(config) + tlsConfig.SessionIDGenerator = sessionIDGenerator + if version == 1 { + tlsConfig.MaxVersion = tlsC.VersionTLS12 // ShadowTLS v1 only support TLS 1.2 + return tlsC.Client(conn, tlsConfig).HandshakeContext(ctx) + } + if fingerprint, ok := tlsC.GetFingerprint(clientFingerprint); ok { + tlsConn := tlsC.UClient(conn, tlsConfig, fingerprint) + if slices.Equal(tlsConfig.NextProtos, WsALPN) { + if err := tlsC.BuildWebsocketHandshakeState(tlsConn); err != nil { + return err + } + } + if version == 2 { // ShadowTLS v2 not work with X25519MLKEM768 + if err := tlsC.BuildRemovedX25519MLKEM768HandshakeState(tlsConn); err != nil { + return err + } + } + return tlsConn.HandshakeContext(ctx) + } + return tlsC.Client(conn, tlsConfig).HandshakeContext(ctx) + } +} + +func checkVersion(version int) error { + if version < 1 || version > 3 { + return fmt.Errorf("shadow-tls: unknown protocol version: %d", version) + } + return nil +} diff --git a/transport/shadowtls/protocol.go b/transport/shadowtls/protocol.go new file mode 100644 index 00000000..bc826252 --- /dev/null +++ b/transport/shadowtls/protocol.go @@ -0,0 +1,193 @@ +package shadowtls + +import ( + "encoding/binary" + "errors" + "fmt" + "io" + "net" +) + +const ( + tlsRandomSize = 32 + tlsHeaderSize = 5 + tlsSessionIDSize = 32 + + clientHello = 1 + serverHello = 2 + + changeCipherSpec = 20 + alert = 21 + handshake = 22 + applicationData = 23 + + serverRandomIndex = tlsHeaderSize + 1 + 3 + 2 + sessionIDLengthIndex = tlsHeaderSize + 1 + 3 + 2 + tlsRandomSize + tlsHMACHeaderSize = tlsHeaderSize + hmacSize + hmacSize = 4 + maxTLSPlaintext = 16384 +) + +func readFrame(reader io.Reader) ([]byte, error) { + var header [tlsHeaderSize]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + return nil, err + } + length := int(binary.BigEndian.Uint16(header[3:])) + frame := make([]byte, tlsHeaderSize+length) + copy(frame, header[:]) + if _, err := io.ReadFull(reader, frame[tlsHeaderSize:]); err != nil { + return nil, err + } + return frame, nil +} + +func copyUntilHandshakeFinished(dst io.Writer, src io.Reader) error { + seenChangeCipherSpec := false + for { + frame, err := readFrame(src) + if err != nil { + return err + } + if _, err = dst.Write(frame); err != nil { + return err + } + if frame[0] != handshake { + if frame[0] != changeCipherSpec { + return fmt.Errorf("shadow-tls: unexpected TLS record type: %d", frame[0]) + } + if !seenChangeCipherSpec { + seenChangeCipherSpec = true + continue + } + } + if seenChangeCipherSpec { + return nil + } + } +} + +func extractServerName(frame []byte) (string, error) { + if len(frame) < tlsHeaderSize+4 || frame[0] != handshake || frame[tlsHeaderSize] != clientHello { + return "", errors.New("shadow-tls: invalid ClientHello") + } + helloLength := int(frame[tlsHeaderSize+1])<<16 | int(frame[tlsHeaderSize+2])<<8 | int(frame[tlsHeaderSize+3]) + hello := frame[tlsHeaderSize+4:] + if helloLength > len(hello) { + return "", io.ErrUnexpectedEOF + } + hello = hello[:helloLength] + if len(hello) < 2+tlsRandomSize+1 { + return "", io.ErrUnexpectedEOF + } + offset := 2 + tlsRandomSize + sessionIDLength := int(hello[offset]) + offset++ + if offset+sessionIDLength+2 > len(hello) { + return "", io.ErrUnexpectedEOF + } + offset += sessionIDLength + cipherSuitesLength := int(binary.BigEndian.Uint16(hello[offset:])) + offset += 2 + if offset+cipherSuitesLength+1 > len(hello) { + return "", io.ErrUnexpectedEOF + } + offset += cipherSuitesLength + compressionMethodsLength := int(hello[offset]) + offset++ + if offset+compressionMethodsLength == len(hello) { + return "", errors.New("shadow-tls: ClientHello has no SNI") + } + if offset+compressionMethodsLength+2 > len(hello) { + return "", io.ErrUnexpectedEOF + } + offset += compressionMethodsLength + extensionsLength := int(binary.BigEndian.Uint16(hello[offset:])) + offset += 2 + if offset+extensionsLength > len(hello) { + return "", io.ErrUnexpectedEOF + } + extensions := hello[offset : offset+extensionsLength] + for len(extensions) >= 4 { + extensionType := binary.BigEndian.Uint16(extensions) + extensionLength := int(binary.BigEndian.Uint16(extensions[2:])) + extensions = extensions[4:] + if extensionLength > len(extensions) { + return "", io.ErrUnexpectedEOF + } + if extensionType == 0 { + return parseServerNameExtension(extensions[:extensionLength]) + } + extensions = extensions[extensionLength:] + } + return "", errors.New("shadow-tls: ClientHello has no SNI") +} + +func parseServerNameExtension(extension []byte) (string, error) { + if len(extension) < 2 { + return "", io.ErrUnexpectedEOF + } + listLength := int(binary.BigEndian.Uint16(extension)) + if listLength > len(extension)-2 { + return "", io.ErrUnexpectedEOF + } + list := extension[2 : 2+listLength] + for len(list) >= 3 { + nameType := list[0] + nameLength := int(binary.BigEndian.Uint16(list[1:])) + list = list[3:] + if nameLength > len(list) { + return "", io.ErrUnexpectedEOF + } + if nameType == 0 && nameLength > 0 { + return string(list[:nameLength]), nil + } + list = list[nameLength:] + } + return "", errors.New("shadow-tls: ClientHello has no host name") +} + +func extractServerRandom(frame []byte) []byte { + if len(frame) < serverRandomIndex+tlsRandomSize || frame[0] != handshake || frame[tlsHeaderSize] != serverHello { + return nil + } + return append([]byte(nil), frame[serverRandomIndex:serverRandomIndex+tlsRandomSize]...) +} + +func isServerHelloSupportTLS13(frame []byte) bool { + if len(frame) <= sessionIDLengthIndex || frame[0] != handshake || frame[tlsHeaderSize] != serverHello { + return false + } + offset := sessionIDLengthIndex + sessionIDLength := int(frame[offset]) + offset++ + if offset+sessionIDLength+3+2 > len(frame) { + return false + } + offset += sessionIDLength + 3 + extensionsLength := int(binary.BigEndian.Uint16(frame[offset:])) + offset += 2 + if offset+extensionsLength > len(frame) { + return false + } + extensions := frame[offset : offset+extensionsLength] + for len(extensions) >= 4 { + extensionType := binary.BigEndian.Uint16(extensions) + extensionLength := int(binary.BigEndian.Uint16(extensions[2:])) + extensions = extensions[4:] + if extensionLength > len(extensions) { + return false + } + if extensionType == 43 { + return extensionLength == 2 && binary.BigEndian.Uint16(extensions[:2]) == 0x0304 + } + extensions = extensions[extensionLength:] + } + return false +} + +func writeBuffers(writer io.Writer, buffers ...[]byte) error { + netBuffers := net.Buffers(buffers) + _, err := netBuffers.WriteTo(writer) + return err +} diff --git a/transport/shadowtls/server.go b/transport/shadowtls/server.go new file mode 100644 index 00000000..d5d68820 --- /dev/null +++ b/transport/shadowtls/server.go @@ -0,0 +1,403 @@ +package shadowtls + +import ( + "context" + "crypto/hmac" + "crypto/sha1" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "net" + "os" + "strings" + "time" + + N "github.com/metacubex/mihomo/common/net" + "github.com/metacubex/mihomo/log" +) + +var ErrFallbackCompleted = errors.New("shadow-tls: connection relayed to fallback") + +type WildcardSNI int + +const ( + WildcardSNIOff WildcardSNI = iota + WildcardSNIAuthed + WildcardSNIAll +) + +type User struct { + Name string + Password string +} + +type HandshakeConfig struct { + Server string + DialContext func(ctx context.Context, network, address string) (net.Conn, error) +} + +type ServerConfig struct { + version int + password string // for protocol version 2 + users []User // for protocol version 3 + handshake HandshakeConfig + handshakeForServerName map[string]HandshakeConfig // for protocol version 2/3 + strictMode bool // for protocol version 3 + wildcardSNI WildcardSNI // for protocol version 3 +} + +func NewServerConfig( + version int, + password string, + users []User, + handshake HandshakeConfig, + handshakeForServerName map[string]HandshakeConfig, + strictMode bool, + wildcardSNI WildcardSNI, +) (*ServerConfig, error) { + if err := checkVersion(version); err != nil { + return nil, err + } + if version == 3 && len(users) == 0 { + return nil, errors.New("shadow-tls: at least one user is required") + } + if wildcardSNI < WildcardSNIOff || wildcardSNI > WildcardSNIAll { + return nil, errors.New("shadow-tls: invalid wildcard SNI mode") + } + if !handshake.valid() && wildcardSNI == WildcardSNIOff { + return nil, errors.New("shadow-tls: missing default handshake information") + } + if version < 3 && !handshake.valid() { + return nil, errors.New("shadow-tls: missing default handshake information") + } + for serverName, handshakeConfig := range handshakeForServerName { + if serverName == "" || !handshakeConfig.valid() { + return nil, fmt.Errorf("shadow-tls: invalid handshake for server name %q", serverName) + } + } + return &ServerConfig{ + version: version, + password: password, + users: append([]User(nil), users...), + handshake: handshake, + handshakeForServerName: cloneHandshakeMap(handshakeForServerName), + strictMode: strictMode, + wildcardSNI: wildcardSNI, + }, nil +} + +func Server(ctx context.Context, conn net.Conn, config *ServerConfig) (net.Conn, error) { + if conn == nil || config == nil { + return nil, errors.New("shadow-tls: nil connection or server config") + } + var ( + serverConn net.Conn + user string + err error + ) + switch config.version { + case 1: + serverConn, user, err = config.serverV1(ctx, conn) + case 2: + serverConn, user, err = config.serverV2(ctx, conn) + case 3: + serverConn, user, err = config.serverV3(ctx, conn) + default: + panic("unreachable") + } + if err != nil || user == "" { + return serverConn, err + } + return &authenticatedConn{Conn: serverConn, user: user}, nil +} + +func (s *ServerConfig) serverV1(ctx context.Context, conn net.Conn) (net.Conn, string, error) { + handshakeConn, err := s.handshake.dial(ctx) + if err != nil { + return nil, "", fmt.Errorf("shadow-tls: dial handshake server: %w", err) + } + defer handshakeConn.Close() + if err = relayHandshake(conn, handshakeConn); err != nil { + return nil, "", fmt.Errorf("shadow-tls: relay handshake: %w", err) + } + log.Debugln("[ShadowTLS] handshake finished") + return conn, "", nil +} + +func (s *ServerConfig) serverV2(ctx context.Context, conn net.Conn) (net.Conn, string, error) { + clientHello, err := readFrame(conn) + if err != nil { + return nil, "", fmt.Errorf("shadow-tls: read client handshake: %w", err) + } + handshakeConfig := s.selectHandshake(clientHello) + handshakeConn, err := handshakeConfig.dial(ctx) + if err != nil { + return nil, "", fmt.Errorf("shadow-tls: dial handshake server: %w", err) + } + hashConn := newHashWriteConn(conn, s.password) + serverCopyDone := make(chan error, 1) + go func() { + _, copyErr := io.Copy(hashConn, handshakeConn) + serverCopyDone <- copyErr + }() + + request, err := copyUntilHandshakeFinishedV2( + handshakeConn, + N.NewCachedConn(conn, clientHello), + hashConn, + 2, + ) + if err == nil { + log.Debugln("[ShadowTLS] handshake finished") + _ = handshakeConn.Close() + <-serverCopyDone + return N.NewCachedConn(newConn(conn), request), "", nil + } + if errors.Is(err, os.ErrPermission) { + log.Warnln("[ShadowTLS] fallback connection") + hashConn.Fallback() + clientCopyDone := make(chan error, 1) + go func() { + _, copyErr := io.Copy(handshakeConn, conn) + clientCopyDone <- copyErr + }() + var clientCopyErr, serverCopyErr error + select { + case clientCopyErr = <-clientCopyDone: + finishCopyDirection(handshakeConn, conn, clientCopyErr) + serverCopyErr = <-serverCopyDone + case serverCopyErr = <-serverCopyDone: + finishCopyDirection(conn, handshakeConn, serverCopyErr) + clientCopyErr = <-clientCopyDone + } + _ = handshakeConn.Close() + if relayErr := joinCopyErrors(clientCopyErr, serverCopyErr); relayErr != nil { + return nil, "", relayErr + } + return nil, "", ErrFallbackCompleted + } + _ = handshakeConn.Close() + <-serverCopyDone + return nil, "", err +} + +func (s *ServerConfig) serverV3(ctx context.Context, conn net.Conn) (net.Conn, string, error) { + clientHello, err := readFrame(conn) + if err != nil { + return nil, "", fmt.Errorf("shadow-tls: read client handshake: %w", err) + } + serverName, err := extractServerName(clientHello) + if err != nil { + return nil, "", fmt.Errorf("shadow-tls: extract server name: %w", err) + } + user, authErr := verifyClientHello(clientHello, s.users) + handshakeConfig := s.selectV3Handshake(serverName, authErr == nil) + if authErr != nil { + log.Warnln("[ShadowTLS] client hello verify failed: %v", authErr) + return nil, "", s.relayFallback(ctx, conn, clientHello, handshakeConfig) + } + log.Debugln("[ShadowTLS] client hello verify success") + + handshakeConn, err := handshakeConfig.dial(ctx) + if err != nil { + return nil, "", fmt.Errorf("shadow-tls: dial handshake server: %w", err) + } + defer handshakeConn.Close() + if _, err = handshakeConn.Write(clientHello); err != nil { + return nil, "", fmt.Errorf("shadow-tls: write client handshake: %w", err) + } + serverHello, err := readFrame(handshakeConn) + if err != nil { + return nil, "", fmt.Errorf("shadow-tls: read server handshake: %w", err) + } + if _, err = conn.Write(serverHello); err != nil { + return nil, "", fmt.Errorf("shadow-tls: write server handshake: %w", err) + } + serverRandom := extractServerRandom(serverHello) + if serverRandom == nil { + log.Warnln("[ShadowTLS] server random extract failed, will copy bidirectional") + if err = N.RelayContext(ctx, conn, handshakeConn); err != nil { + return nil, "", err + } + return nil, "", ErrFallbackCompleted + } + if s.strictMode && !isServerHelloSupportTLS13(serverHello) { + log.Warnln("[ShadowTLS] TLS 1.3 is not supported, will copy bidirectional") + if err = N.RelayContext(ctx, conn, handshakeConn); err != nil { + return nil, "", err + } + return nil, "", ErrFallbackCompleted + } + if log.Level() == log.DEBUG { + log.Debugln("[ShadowTLS] client authenticated, server random extracted: %s", hex.EncodeToString(serverRandom)) + } + + hmacWrite := hmac.New(sha1.New, []byte(user.Password)) + _, _ = hmacWrite.Write(serverRandom) + hmacAdd := hmac.New(sha1.New, []byte(user.Password)) + _, _ = hmacAdd.Write(serverRandom) + _, _ = hmacAdd.Write([]byte("S")) + hmacVerify := hmac.New(sha1.New, []byte(user.Password)) + resetVerify := func() { hmacReset(hmacVerify, serverRandom, 'C') } + request, err := relayV3Handshake(conn, handshakeConn, user.Password, serverRandom, hmacWrite, hmacVerify, resetVerify) + if err != nil { + return nil, "", fmt.Errorf("shadow-tls: relay handshake: %w", err) + } + log.Debugln("[ShadowTLS] handshake relay finished") + return N.NewCachedConn(newVerifiedConn(conn, hmacAdd, hmacVerify, nil), request), user.Name, nil +} + +func (s *ServerConfig) relayFallback(ctx context.Context, conn net.Conn, prefix []byte, handshakeConfig HandshakeConfig) error { + handshakeConn, err := handshakeConfig.dial(ctx) + if err != nil { + return fmt.Errorf("shadow-tls: dial fallback server: %w", err) + } + if err = N.RelayContext(ctx, N.NewCachedConn(conn, prefix), handshakeConn); err != nil { + return err + } + return ErrFallbackCompleted +} + +func (s *ServerConfig) selectHandshake(clientHello []byte) HandshakeConfig { + serverName, err := extractServerName(clientHello) + if err == nil { + if custom, found := s.handshakeForServerName[serverName]; found { + return custom + } + } + return s.handshake +} + +func (s *ServerConfig) selectV3Handshake(serverName string, authenticated bool) HandshakeConfig { + if custom, found := s.handshakeForServerName[serverName]; found { + return custom + } + handshakeConfig := s.handshake + if s.wildcardSNI == WildcardSNIAll || (authenticated && s.wildcardSNI == WildcardSNIAuthed) { + handshakeConfig.Server = net.JoinHostPort(serverName, "443") + } + return handshakeConfig +} + +type authenticatedConn struct { + net.Conn + user string +} + +func (c *authenticatedConn) Upstream() any { return c.Conn } + +func UserFromConn(conn net.Conn) (string, bool) { + authenticated, ok := conn.(*authenticatedConn) + if !ok { + return "", false + } + return authenticated.user, true +} + +func (c HandshakeConfig) valid() bool { + return c.Server != "" && c.DialContext != nil +} + +func (c HandshakeConfig) dial(ctx context.Context) (net.Conn, error) { + if !c.valid() { + return nil, errors.New("shadow-tls: missing handshake information") + } + return c.DialContext(ctx, "tcp", c.Server) +} + +func cloneHandshakeMap(source map[string]HandshakeConfig) map[string]HandshakeConfig { + if source == nil { + return nil + } + cloned := make(map[string]HandshakeConfig, len(source)) + for key, value := range source { + cloned[key] = value + } + return cloned +} + +func relayHandshake(clientConn, serverConn net.Conn) error { + type result struct { + err error + } + results := make(chan result, 2) + go func() { + results <- result{err: copyUntilHandshakeFinished(serverConn, clientConn)} + }() + go func() { + results <- result{err: copyUntilHandshakeFinished(clientConn, serverConn)} + }() + first := <-results + if first.err != nil { + _ = clientConn.SetDeadline(time.Now()) + _ = serverConn.Close() + } + second := <-results + if first.err != nil { + return first.err + } + return second.err +} + +func relayV3Handshake(clientConn, serverConn net.Conn, password string, serverRandom []byte, hmacWrite, hmacVerify hash.Hash, resetVerify func()) ([]byte, error) { + type result struct { + request []byte + client bool + err error + } + results := make(chan result, 2) + go func() { + request, err := copyByFrameUntilHMACMatches(clientConn, serverConn, hmacVerify, resetVerify) + results <- result{request: request, client: true, err: err} + }() + go func() { + err := copyByFrameWithModification(serverConn, clientConn, password, serverRandom, hmacWrite) + results <- result{err: err} + }() + first := <-results + if first.client && first.err == nil { + _ = serverConn.Close() + <-results + return first.request, nil + } + _ = serverConn.Close() + _ = clientConn.SetDeadline(time.Now()) + second := <-results + if first.err != nil { + return nil, first.err + } + return nil, second.err +} + +func finishCopyDirection(dst, src net.Conn, err error) { + if err == nil { + closeWrite(dst) + return + } + _ = dst.Close() + _ = src.Close() +} + +func closeWrite(conn net.Conn) { + if closer, ok := conn.(interface{ CloseWrite() error }); ok { + _ = closer.CloseWrite() + return + } + _ = conn.Close() +} + +func joinCopyErrors(copyErrors ...error) error { + var result error + for _, err := range copyErrors { + if err == nil || errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) || errors.Is(err, os.ErrDeadlineExceeded) { + continue + } + if strings.Contains(err.Error(), "use of closed network connection") { + continue + } + result = errors.Join(result, err) + } + return result +} diff --git a/transport/shadowtls/server_test.go b/transport/shadowtls/server_test.go new file mode 100644 index 00000000..c553f312 --- /dev/null +++ b/transport/shadowtls/server_test.go @@ -0,0 +1,343 @@ +package shadowtls + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha1" + stdTLS "crypto/tls" + "errors" + "io" + "net" + "testing" + "time" + + "github.com/metacubex/mihomo/component/ca" +) + +const ( + testServerName = "shadowtls.example" + testPassword = "shadowtls-test-password" +) + +func TestServer(t *testing.T) { + testCases := []struct { + name string + version int + fingerprint string + alpn []string + }{ + {name: "v1", version: 1}, + {name: "v2", version: 2}, + {name: "v2-utls-websocket", version: 2, fingerprint: "chrome", alpn: WsALPN}, + {name: "v3", version: 3}, + {name: "v3-utls", version: 3, fingerprint: "chrome"}, + } + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + camouflageAddr := startCamouflageServer(t, testCase.version == 1) + serverConfig := newTestServerConfig(t, testCase.version, camouflageAddr) + frontendAddr, result := startServer(t, serverConfig) + + rawClient, err := net.Dial("tcp", frontendAddr) + if err != nil { + t.Fatal(err) + } + defer rawClient.Close() + setTestDeadline(t, rawClient) + client, err := NewShadowTLS(context.Background(), rawClient, &ShadowTLSOption{ + Password: testPassword, + Host: testServerName, + ClientFingerprint: testCase.fingerprint, + SkipCertVerify: true, + Version: testCase.version, + ALPN: testCase.alpn, + }) + if err != nil { + t.Fatalf("client handshake: %v", err) + } + + clientPayload := bytes.Repeat([]byte("client-payload-"), 3000) + if _, err = client.Write(clientPayload); err != nil { + t.Fatalf("client write: %v", err) + } + serverResult := receiveServerResult(t, result) + if serverResult.err != nil { + t.Fatalf("server handshake: %v", serverResult.err) + } + defer serverResult.conn.Close() + setTestDeadline(t, serverResult.conn) + if testCase.version == 3 && serverResult.user != "test-user" { + t.Fatalf("authenticated user = %q, want test-user", serverResult.user) + } + if testCase.version != 3 && serverResult.user != "" { + t.Fatalf("unexpected authenticated user %q", serverResult.user) + } + gotClientPayload := make([]byte, len(clientPayload)) + if _, err = io.ReadFull(serverResult.conn, gotClientPayload); err != nil { + t.Fatalf("server read: %v", err) + } + if !bytes.Equal(gotClientPayload, clientPayload) { + t.Fatal("server received corrupted client payload") + } + + serverPayload := bytes.Repeat([]byte("server-payload-"), 3000) + if _, err = serverResult.conn.Write(serverPayload); err != nil { + t.Fatalf("server write: %v", err) + } + gotServerPayload := make([]byte, len(serverPayload)) + if _, err = io.ReadFull(client, gotServerPayload); err != nil { + t.Fatalf("client read: %v", err) + } + if !bytes.Equal(gotServerPayload, serverPayload) { + t.Fatal("client received corrupted server payload") + } + }) + } +} + +func TestV3UnauthenticatedConnectionFallsBack(t *testing.T) { + camouflageAddr := startCamouflageServer(t, false) + serverConfig := newTestServerConfig(t, 3, camouflageAddr) + frontendAddr, result := startServer(t, serverConfig) + + rawClient, err := net.Dial("tcp", frontendAddr) + if err != nil { + t.Fatal(err) + } + setTestDeadline(t, rawClient) + client := stdTLS.Client(rawClient, &stdTLS.Config{ + ServerName: testServerName, + InsecureSkipVerify: true, + MinVersion: stdTLS.VersionTLS12, + }) + if err = client.HandshakeContext(context.Background()); err != nil { + t.Fatalf("fallback TLS handshake: %v", err) + } + payload := []byte("ordinary TLS connection") + if _, err = client.Write(payload); err != nil { + t.Fatalf("fallback write: %v", err) + } + response := make([]byte, len(payload)) + if _, err = io.ReadFull(client, response); err != nil { + t.Fatalf("fallback read: %v", err) + } + if !bytes.Equal(response, payload) { + t.Fatalf("fallback response = %q, want %q", response, payload) + } + if err = client.Close(); err != nil { + t.Fatal(err) + } + serverResult := receiveServerResult(t, result) + if !errors.Is(serverResult.err, ErrFallbackCompleted) { + t.Fatalf("server error = %v, want %v", serverResult.err, ErrFallbackCompleted) + } +} + +func TestHandshakeSelectionByServerName(t *testing.T) { + frame := captureClientHello(t, "mapped.example") + if serverName, err := extractServerName(frame); err != nil || serverName != "mapped.example" { + t.Fatalf("extractServerName() = %q, %v", serverName, err) + } + dial := (&net.Dialer{}).DialContext + serverConfig, err := NewServerConfig( + 2, + "", + nil, + HandshakeConfig{Server: "default.example:443", DialContext: dial}, + map[string]HandshakeConfig{ + "mapped.example": {Server: "mapped.example:8443", DialContext: dial}, + }, + false, + WildcardSNIOff, + ) + if err != nil { + t.Fatal(err) + } + if selected := serverConfig.selectHandshake(frame); selected.Server != "mapped.example:8443" { + t.Fatalf("selected server = %q, want mapped.example:8443", selected.Server) + } +} + +func TestV3WildcardSNISelection(t *testing.T) { + defaultHandshake := HandshakeConfig{Server: "default.example:443"} + customHandshake := HandshakeConfig{Server: "custom-upstream.example:443"} + testCases := []struct { + name string + mode WildcardSNI + serverName string + authenticated bool + want string + }{ + {name: "off-authenticated", mode: WildcardSNIOff, serverName: "other.example", authenticated: true, want: defaultHandshake.Server}, + {name: "authed-authenticated", mode: WildcardSNIAuthed, serverName: "other.example", authenticated: true, want: "other.example:443"}, + {name: "authed-fallback", mode: WildcardSNIAuthed, serverName: "other.example", authenticated: false, want: defaultHandshake.Server}, + {name: "all-fallback", mode: WildcardSNIAll, serverName: "other.example", authenticated: false, want: "other.example:443"}, + {name: "custom-fallback", mode: WildcardSNIOff, serverName: "custom.example", authenticated: false, want: customHandshake.Server}, + } + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + serverConfig := &ServerConfig{ + handshake: defaultHandshake, + handshakeForServerName: map[string]HandshakeConfig{"custom.example": customHandshake}, + wildcardSNI: testCase.mode, + } + if got := serverConfig.selectV3Handshake(testCase.serverName, testCase.authenticated).Server; got != testCase.want { + t.Fatalf("selected server = %q, want %q", got, testCase.want) + } + }) + } +} + +func TestVerifiedConnZeroLengthWrite(t *testing.T) { + underlying := new(writeSpyConn) + hmacAdd := hmac.New(sha1.New, []byte(testPassword)) + conn := newVerifiedConn(underlying, hmacAdd, nil, nil) + before := append([]byte(nil), hmacAdd.Sum(nil)...) + + n, err := conn.Write(nil) + if err != nil || n != 0 { + t.Fatalf("Write(nil) = %d, %v; want 0, nil", n, err) + } + if underlying.writes != 0 { + t.Fatalf("underlying writes = %d, want 0", underlying.writes) + } + if !bytes.Equal(hmacAdd.Sum(nil), before) { + t.Fatal("Write(nil) advanced the HMAC state") + } +} + +type writeSpyConn struct { + net.Conn + writes int +} + +func (c *writeSpyConn) Write(p []byte) (int, error) { + c.writes++ + return len(p), nil +} + +type serverResult struct { + conn net.Conn + user string + err error +} + +func newTestServerConfig(t *testing.T, version int, camouflageAddr string) *ServerConfig { + t.Helper() + var users []User + if version == 3 { + users = []User{{Name: "test-user", Password: testPassword}} + } + serverConfig, err := NewServerConfig( + version, + testPassword, + users, + HandshakeConfig{Server: camouflageAddr, DialContext: (&net.Dialer{}).DialContext}, + nil, + version == 3, + WildcardSNIOff, + ) + if err != nil { + t.Fatal(err) + } + return serverConfig +} + +func startServer(t *testing.T, serverConfig *ServerConfig) (string, <-chan serverResult) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + result := make(chan serverResult, 1) + go func() { + conn, acceptErr := listener.Accept() + if acceptErr != nil { + result <- serverResult{err: acceptErr} + return + } + setTestDeadline(t, conn) + shadowConn, serverErr := Server(context.Background(), conn, serverConfig) + user, _ := UserFromConn(shadowConn) + result <- serverResult{conn: shadowConn, user: user, err: serverErr} + }() + return listener.Addr().String(), result +} + +func startCamouflageServer(t *testing.T, tls12Only bool) string { + t.Helper() + certificatePEM, privateKeyPEM, _, err := ca.NewRandomTLSKeyPair(ca.KeyPairTypeP256) + if err != nil { + t.Fatal(err) + } + certificate, err := stdTLS.X509KeyPair([]byte(certificatePEM), []byte(privateKeyPEM)) + if err != nil { + t.Fatal(err) + } + config := &stdTLS.Config{ + Certificates: []stdTLS.Certificate{certificate}, + NextProtos: append([]string(nil), DefaultALPN...), + MinVersion: stdTLS.VersionTLS12, + } + if tls12Only { + config.MaxVersion = stdTLS.VersionTLS12 + } + rawListener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + listener := stdTLS.NewListener(rawListener, config) + t.Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, acceptErr := listener.Accept() + if acceptErr != nil { + return + } + go func() { + defer conn.Close() + setTestDeadline(t, conn) + _, _ = io.Copy(conn, conn) + }() + } + }() + return listener.Addr().String() +} + +func captureClientHello(t *testing.T, serverName string) []byte { + t.Helper() + clientSide, serverSide := net.Pipe() + done := make(chan struct{}) + go func() { + defer close(done) + client := stdTLS.Client(clientSide, &stdTLS.Config{ServerName: serverName, InsecureSkipVerify: true}) + _ = client.Handshake() + }() + frame, err := readFrame(serverSide) + if err != nil { + t.Fatal(err) + } + _ = serverSide.Close() + <-done + return frame +} + +func receiveServerResult(t *testing.T, result <-chan serverResult) serverResult { + t.Helper() + select { + case serverResult := <-result: + return serverResult + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for ShadowTLS server") + return serverResult{} + } +} + +func setTestDeadline(t *testing.T, conn net.Conn) { + t.Helper() + if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { + t.Errorf("set deadline: %v", err) + } +} diff --git a/transport/shadowtls/shadowtls.go b/transport/shadowtls/shadowtls.go deleted file mode 100644 index adbe915b..00000000 --- a/transport/shadowtls/shadowtls.go +++ /dev/null @@ -1,152 +0,0 @@ -package shadowtls - -import ( - "context" - "crypto/hmac" - "crypto/sha1" - "encoding/binary" - "fmt" - "hash" - "io" - "net" - - "github.com/metacubex/mihomo/common/pool" - C "github.com/metacubex/mihomo/constant" - - "github.com/metacubex/tls" -) - -const ( - chunkSize = 1 << 13 - Mode string = "shadow-tls" - hashLen int = 8 - tlsHeaderLen int = 5 -) - -var ( - DefaultALPN = []string{"h2", "http/1.1"} -) - -// ShadowTLS is shadow-tls implementation -type ShadowTLS struct { - net.Conn - password []byte - remain int - firstRequest bool - tlsConfig *tls.Config -} - -type HashedConn struct { - net.Conn - hasher hash.Hash -} - -func newHashedStream(conn net.Conn, password []byte) HashedConn { - return HashedConn{ - Conn: conn, - hasher: hmac.New(sha1.New, password), - } -} - -func (h HashedConn) Read(b []byte) (n int, err error) { - n, err = h.Conn.Read(b) - h.hasher.Write(b[:n]) - return -} - -func (s *ShadowTLS) read(b []byte) (int, error) { - var buf [tlsHeaderLen]byte - _, err := io.ReadFull(s.Conn, buf[:]) - if err != nil { - return 0, fmt.Errorf("shadowtls read failed %w", err) - } - if buf[0] != 0x17 || buf[1] != 0x3 || buf[2] != 0x3 { - return 0, fmt.Errorf("invalid shadowtls header %v", buf) - } - length := int(binary.BigEndian.Uint16(buf[3:])) - - if length > len(b) { - n, err := s.Conn.Read(b) - if err != nil { - return n, err - } - s.remain = length - n - return n, nil - } - - return io.ReadFull(s.Conn, b[:length]) -} - -func (s *ShadowTLS) Read(b []byte) (int, error) { - if s.remain > 0 { - length := s.remain - if length > len(b) { - length = len(b) - } - - n, err := io.ReadFull(s.Conn, b[:length]) - if err != nil { - return n, fmt.Errorf("shadowtls Read failed with %w", err) - } - s.remain -= n - return n, nil - } - - return s.read(b) -} - -func (s *ShadowTLS) Write(b []byte) (int, error) { - length := len(b) - for i := 0; i < length; i += chunkSize { - end := i + chunkSize - if end > length { - end = length - } - - n, err := s.write(b[i:end]) - if err != nil { - return n, fmt.Errorf("shadowtls Write failed with %w, i=%d, end=%d, n=%d", err, i, end, n) - } - } - return length, nil -} - -func (s *ShadowTLS) write(b []byte) (int, error) { - var hashVal []byte - if s.firstRequest { - hashedConn := newHashedStream(s.Conn, s.password) - tlsConn := tls.Client(hashedConn, s.tlsConfig) - // fix tls handshake not timeout - ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout) - defer cancel() - if err := tlsConn.HandshakeContext(ctx); err != nil { - return 0, fmt.Errorf("tls connect failed with %w", err) - } - hashVal = hashedConn.hasher.Sum(nil)[:hashLen] - s.firstRequest = false - } - - buf := pool.GetBuffer() - defer pool.PutBuffer(buf) - buf.Write([]byte{0x17, 0x03, 0x03}) - binary.Write(buf, binary.BigEndian, uint16(len(b)+len(hashVal))) - buf.Write(hashVal) - buf.Write(b) - _, err := s.Conn.Write(buf.Bytes()) - if err != nil { - // return 0 because errors occur here make the - // whole situation irrecoverable - return 0, err - } - return len(b), nil -} - -// NewShadowTLS return a ShadowTLS -func NewShadowTLS(conn net.Conn, password string, tlsConfig *tls.Config) net.Conn { - return &ShadowTLS{ - Conn: conn, - password: []byte(password), - firstRequest: true, - tlsConfig: tlsConfig, - } -} diff --git a/transport/shadowtls/v2.go b/transport/shadowtls/v2.go new file mode 100644 index 00000000..ad922e07 --- /dev/null +++ b/transport/shadowtls/v2.go @@ -0,0 +1,209 @@ +package shadowtls + +import ( + "bytes" + "crypto/hmac" + "crypto/sha1" + "encoding/binary" + "fmt" + "hash" + "io" + "net" + "os" + "sync" + + "github.com/metacubex/mihomo/log" +) + +type hashReadConn struct { + net.Conn + hmac hash.Hash +} + +func newHashReadConn(conn net.Conn, password string) *hashReadConn { + return &hashReadConn{Conn: conn, hmac: hmac.New(sha1.New, []byte(password))} +} + +func (c *hashReadConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + if n > 0 { + _, _ = c.hmac.Write(p[:n]) + } + return n, err +} + +func (c *hashReadConn) Sum() []byte { + return append([]byte(nil), c.hmac.Sum(nil)[:8]...) +} + +type hashWriteConn struct { + net.Conn + mu sync.Mutex + hmac hash.Hash + hasContent bool + lastSum []byte +} + +func newHashWriteConn(conn net.Conn, password string) *hashWriteConn { + return &hashWriteConn{Conn: conn, hmac: hmac.New(sha1.New, []byte(password))} +} + +func (c *hashWriteConn) Write(p []byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + n, err := c.Conn.Write(p) + if c.hmac != nil && n > 0 { + if c.hasContent { + c.lastSum = append(c.lastSum[:0], c.hmac.Sum(nil)[:8]...) + } + _, _ = c.hmac.Write(p[:n]) + c.hasContent = true + } + return n, err +} + +func (c *hashWriteConn) sums() (current, previous []byte, hasContent bool) { + c.mu.Lock() + defer c.mu.Unlock() + if c.hmac != nil { + current = append([]byte(nil), c.hmac.Sum(nil)[:8]...) + } + previous = append([]byte(nil), c.lastSum...) + return current, previous, c.hasContent +} + +func (c *hashWriteConn) Fallback() { + c.mu.Lock() + c.hmac = nil + c.mu.Unlock() +} + +type shadowConn struct { + net.Conn + readRemaining int + writeMu sync.Mutex +} + +func newConn(conn net.Conn) *shadowConn { + return &shadowConn{Conn: conn} +} + +func (c *shadowConn) Read(p []byte) (int, error) { + if c.readRemaining > 0 { + if len(p) > c.readRemaining { + p = p[:c.readRemaining] + } + n, err := c.Conn.Read(p) + c.readRemaining -= n + return n, err + } + var header [tlsHeaderSize]byte + if _, err := io.ReadFull(c.Conn, header[:]); err != nil { + return 0, err + } + if header[0] != applicationData { + return 0, fmt.Errorf("shadow-tls: unexpected TLS record type: %d", header[0]) + } + length := int(binary.BigEndian.Uint16(header[3:])) + readLength := len(p) + if readLength > length { + readLength = length + } + n, err := c.Conn.Read(p[:readLength]) + c.readRemaining = length - n + return n, err +} + +func (c *shadowConn) Write(p []byte) (int, error) { + c.writeMu.Lock() + defer c.writeMu.Unlock() + total := len(p) + if total == 0 { + if err := c.writeRecord(nil); err != nil { + return 0, err + } + return 0, nil + } + for len(p) > 0 { + length := len(p) + if length > maxTLSPlaintext { + length = maxTLSPlaintext + } + if err := c.writeRecord(p[:length]); err != nil { + return total - len(p), err + } + p = p[length:] + } + return total, nil +} + +func (c *shadowConn) writeRecord(p []byte) error { + var header [tlsHeaderSize]byte + header[0] = applicationData + header[1] = 3 + header[2] = 3 + binary.BigEndian.PutUint16(header[3:], uint16(len(p))) + return writeBuffers(c.Conn, header[:], p) +} + +func (c *shadowConn) NeedAdditionalReadDeadline() bool { return true } + +func (c *shadowConn) Upstream() any { return c.Conn } + +type clientConn struct { + *shadowConn + mu sync.Mutex + hashConn *hashReadConn +} + +func newClientConn(hashConn *hashReadConn) *clientConn { + return &clientConn{shadowConn: newConn(hashConn.Conn), hashConn: hashConn} +} + +func (c *clientConn) Write(p []byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.hashConn == nil { + return c.shadowConn.Write(p) + } + prefixed := make([]byte, 8+len(p)) + copy(prefixed, c.hashConn.Sum()) + copy(prefixed[8:], p) + c.hashConn = nil + if _, err := c.shadowConn.Write(prefixed); err != nil { + return 0, err + } + return len(p), nil +} + +func copyUntilHandshakeFinishedV2(dst net.Conn, src io.Reader, hashConn *hashWriteConn, fallbackAfter int) ([]byte, error) { + applicationDataCount := 0 + for { + frame, err := readFrame(src) + if err != nil { + return nil, err + } + if frame[0] == applicationData { + payload := frame[tlsHeaderSize:] + current, previous, hasContent := hashConn.sums() + if hasContent && len(payload) >= 8 { + if bytes.Equal(payload[:8], current) { + log.Debugln("[ShadowTLS] match current hashcode") + return append([]byte(nil), payload[8:]...), nil + } + if len(previous) > 0 && bytes.Equal(payload[:8], previous) { + log.Debugln("[ShadowTLS] match last hashcode") + return append([]byte(nil), payload[8:]...), nil + } + log.Debugln("[ShadowTLS] hashcode mismatch") + } + applicationDataCount++ + } + if _, err = dst.Write(frame); err != nil { + return nil, err + } + if applicationDataCount > fallbackAfter { + return nil, os.ErrPermission + } + } +} diff --git a/transport/shadowtls/v3.go b/transport/shadowtls/v3.go new file mode 100644 index 00000000..51c5c050 --- /dev/null +++ b/transport/shadowtls/v3.go @@ -0,0 +1,300 @@ +package shadowtls + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha1" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "hash" + "io" + "net" + "sync" +) + +func generateSessionID(password string) TLSSessionIDGeneratorFunc { + return func(clientHello []byte, sessionID []byte) error { + const sessionIDStart = 1 + 3 + 2 + tlsRandomSize + 1 + if len(clientHello) < sessionIDStart+tlsSessionIDSize || len(sessionID) < tlsSessionIDSize { + return errors.New("shadow-tls: unexpected ClientHello length") + } + if _, err := rand.Read(sessionID[:tlsSessionIDSize-hmacSize]); err != nil { + return err + } + for i := tlsSessionIDSize - hmacSize; i < tlsSessionIDSize; i++ { + sessionID[i] = 0 + } + h := hmac.New(sha1.New, []byte(password)) + _, _ = h.Write(clientHello[:sessionIDStart]) + _, _ = h.Write(sessionID[:tlsSessionIDSize]) + _, _ = h.Write(clientHello[sessionIDStart+tlsSessionIDSize:]) + copy(sessionID[tlsSessionIDSize-hmacSize:], h.Sum(nil)[:hmacSize]) + return nil + } +} + +type streamWrapper struct { + net.Conn + password string + pending []byte + serverRandom []byte + readHMAC hash.Hash + readHMACKey []byte + isTLS13 bool + authorized bool +} + +func newStreamWrapper(conn net.Conn, password string) *streamWrapper { + return &streamWrapper{Conn: conn, password: password} +} + +func (c *streamWrapper) Authorized() (bool, bool, []byte, hash.Hash) { + return c.isTLS13, c.authorized, c.serverRandom, c.readHMAC +} + +func (c *streamWrapper) Read(p []byte) (int, error) { + if len(c.pending) > 0 { + return c.readPending(p), nil + } + frame, err := readFrame(c.Conn) + if err != nil { + return 0, err + } + switch frame[0] { + case handshake: + // Mirror the server's one-shot seed: only initialize the HMAC chain on the first + // ServerHello so a TLS 1.3 HelloRetryRequest (RFC 8446 section 4.1.4) aligns both peers. + if len(frame) >= serverRandomIndex+tlsRandomSize && frame[tlsHeaderSize] == serverHello && c.readHMAC == nil { + c.serverRandom = append([]byte(nil), frame[serverRandomIndex:serverRandomIndex+tlsRandomSize]...) + c.readHMAC = hmac.New(sha1.New, []byte(c.password)) + _, _ = c.readHMAC.Write(c.serverRandom) + c.readHMACKey = kdf(c.password, c.serverRandom) + c.isTLS13 = isServerHelloSupportTLS13(frame) + c.authorized = !c.isTLS13 + } + case applicationData: + c.authorized = false + if len(frame) > tlsHMACHeaderSize && c.readHMAC != nil { + _, _ = c.readHMAC.Write(frame[tlsHMACHeaderSize:]) + if !hmac.Equal(c.readHMAC.Sum(nil)[:hmacSize], frame[tlsHeaderSize:tlsHMACHeaderSize]) { + return 0, errors.New("shadow-tls v3: HMAC mismatch, possible data corruption") + } + xorSlice(frame[tlsHMACHeaderSize:], c.readHMACKey) + copy(frame[hmacSize:hmacSize+tlsHeaderSize], frame[:tlsHeaderSize]) + frame = frame[hmacSize:] + binary.BigEndian.PutUint16(frame[3:5], uint16(len(frame)-tlsHeaderSize)) + c.authorized = true + } + } + c.pending = frame + return c.readPending(p), nil +} + +func (c *streamWrapper) readPending(p []byte) int { + n := copy(p, c.pending) + c.pending = c.pending[n:] + return n +} + +type verifiedConn struct { + net.Conn + writeMu sync.Mutex + hmacAdd hash.Hash + hmacVerify hash.Hash + hmacIgnore hash.Hash + pending []byte +} + +func newVerifiedConn(conn net.Conn, hmacAdd, hmacVerify, hmacIgnore hash.Hash) *verifiedConn { + return &verifiedConn{ + Conn: conn, + hmacAdd: hmacAdd, + hmacVerify: hmacVerify, + hmacIgnore: hmacIgnore, + } +} + +func (c *verifiedConn) Read(p []byte) (int, error) { + if len(c.pending) > 0 { + return c.readPending(p), nil + } + for { + frame, err := readFrame(c.Conn) + if err != nil { + sendAlert(c.Conn) + return 0, err + } + switch frame[0] { + case alert: + return 0, fmt.Errorf("shadow-tls: remote alert: %w", net.ErrClosed) + case applicationData: + if c.hmacIgnore != nil { + if verifyApplicationData(frame, c.hmacIgnore, false) { + continue + } + c.hmacIgnore = nil + } + if !verifyApplicationData(frame, c.hmacVerify, true) { + sendAlert(c.Conn) + return 0, errors.New("shadow-tls: application data verification failed") + } + c.pending = frame[tlsHMACHeaderSize:] + return c.readPending(p), nil + default: + sendAlert(c.Conn) + return 0, fmt.Errorf("shadow-tls: unexpected TLS record type: %d", frame[0]) + } + } +} + +func (c *verifiedConn) readPending(p []byte) int { + n := copy(p, c.pending) + c.pending = c.pending[n:] + return n +} + +func (c *verifiedConn) Write(p []byte) (int, error) { + c.writeMu.Lock() + defer c.writeMu.Unlock() + total := len(p) + for len(p) > 0 { + length := len(p) + if length > maxTLSPlaintext { + length = maxTLSPlaintext + } + if err := c.writeRecord(p[:length]); err != nil { + return total - len(p), err + } + p = p[length:] + } + return total, nil +} + +func (c *verifiedConn) writeRecord(p []byte) error { + var header [tlsHMACHeaderSize]byte + header[0] = applicationData + header[1] = 3 + header[2] = 3 + binary.BigEndian.PutUint16(header[3:tlsHeaderSize], uint16(hmacSize+len(p))) + _, _ = c.hmacAdd.Write(p) + hmacHash := c.hmacAdd.Sum(nil)[:hmacSize] + _, _ = c.hmacAdd.Write(hmacHash) + copy(header[tlsHeaderSize:], hmacHash) + return writeBuffers(c.Conn, header[:], p) +} + +func (c *verifiedConn) NeedAdditionalReadDeadline() bool { return true } + +func (c *verifiedConn) Upstream() any { return c.Conn } + +func verifyApplicationData(frame []byte, h hash.Hash, update bool) bool { + if len(frame) < tlsHMACHeaderSize || frame[0] != applicationData || frame[1] != 3 || frame[2] != 3 { + return false + } + _, _ = h.Write(frame[tlsHMACHeaderSize:]) + hmacHash := h.Sum(nil)[:hmacSize] + if update { + _, _ = h.Write(hmacHash) + } + return hmac.Equal(frame[tlsHeaderSize:tlsHMACHeaderSize], hmacHash) +} + +func verifyClientHello(frame []byte, users []User) (*User, error) { + const minLength = tlsHeaderSize + 1 + 3 + 2 + tlsRandomSize + 1 + tlsSessionIDSize + const hmacIndex = sessionIDLengthIndex + 1 + tlsSessionIDSize - hmacSize + if len(frame) < minLength { + return nil, io.ErrUnexpectedEOF + } + if frame[0] != handshake || frame[tlsHeaderSize] != clientHello { + return nil, errors.New("shadow-tls: unexpected ClientHello record") + } + if frame[sessionIDLengthIndex] != tlsSessionIDSize { + return nil, errors.New("shadow-tls: unexpected session ID length") + } + for i := range users { + user := &users[i] + h := hmac.New(sha1.New, []byte(user.Password)) + _, _ = h.Write(frame[tlsHeaderSize:hmacIndex]) + _, _ = h.Write([]byte{0, 0, 0, 0}) + _, _ = h.Write(frame[hmacIndex+hmacSize:]) + if hmac.Equal(frame[hmacIndex:hmacIndex+hmacSize], h.Sum(nil)[:hmacSize]) { + return user, nil + } + } + return nil, errors.New("shadow-tls: ClientHello HMAC mismatch") +} + +func copyByFrameUntilHMACMatches(conn, handshakeConn net.Conn, hmacVerify hash.Hash, hmacReset func()) ([]byte, error) { + for { + frame, err := readFrame(conn) + if err != nil { + return nil, fmt.Errorf("shadow-tls: read client record: %w", err) + } + if len(frame) > tlsHMACHeaderSize && frame[0] == applicationData { + hmacReset() + _, _ = hmacVerify.Write(frame[tlsHMACHeaderSize:]) + hmacHash := hmacVerify.Sum(nil)[:hmacSize] + if hmac.Equal(hmacHash, frame[tlsHeaderSize:tlsHMACHeaderSize]) { + hmacReset() + _, _ = hmacVerify.Write(frame[tlsHMACHeaderSize:]) + _, _ = hmacVerify.Write(frame[tlsHeaderSize:tlsHMACHeaderSize]) + return append([]byte(nil), frame[tlsHMACHeaderSize:]...), nil + } + } + if _, err = handshakeConn.Write(frame); err != nil { + return nil, fmt.Errorf("shadow-tls: write client record: %w", err) + } + } +} + +func copyByFrameWithModification(conn, handshakeConn net.Conn, password string, serverRandom []byte, hmacWrite hash.Hash) error { + writeKey := kdf(password, serverRandom) + for { + frame, err := readFrame(conn) + if err != nil { + return fmt.Errorf("shadow-tls: read server record: %w", err) + } + if frame[0] != applicationData { + if _, err = handshakeConn.Write(frame); err != nil { + return fmt.Errorf("shadow-tls: write server record: %w", err) + } + continue + } + xorSlice(frame[tlsHeaderSize:], writeKey) + _, _ = hmacWrite.Write(frame[tlsHeaderSize:]) + binary.BigEndian.PutUint16(frame[3:5], uint16(len(frame)-tlsHeaderSize+hmacSize)) + hmacHash := hmacWrite.Sum(nil)[:hmacSize] + if err = writeBuffers(handshakeConn, frame[:tlsHeaderSize], hmacHash, frame[tlsHeaderSize:]); err != nil { + return fmt.Errorf("shadow-tls: write modified server record: %w", err) + } + } +} + +func kdf(password string, serverRandom []byte) []byte { + hasher := sha256.New() + _, _ = hasher.Write([]byte(password)) + _, _ = hasher.Write(serverRandom) + return hasher.Sum(nil) +} + +func xorSlice(data, key []byte) { + for i := range data { + data[i] ^= key[i%len(key)] + } +} + +func sendAlert(writer io.Writer) { + const recordSize = 31 + record := [recordSize]byte{alert, 3, 3, 0, recordSize - tlsHeaderSize} + if _, err := rand.Read(record[tlsHeaderSize:]); err == nil { + _, _ = writer.Write(record[:]) + } +} + +func hmacReset(h hash.Hash, serverRandom []byte, side byte) { + h.Reset() + _, _ = h.Write(serverRandom) + _, _ = h.Write([]byte{side}) +} diff --git a/transport/sing-shadowtls/shadowtls.go b/transport/sing-shadowtls/shadowtls.go deleted file mode 100644 index ef43e2f6..00000000 --- a/transport/sing-shadowtls/shadowtls.go +++ /dev/null @@ -1,100 +0,0 @@ -package sing_shadowtls - -import ( - "context" - "net" - - "github.com/metacubex/mihomo/component/ca" - tlsC "github.com/metacubex/mihomo/component/tls" - "github.com/metacubex/mihomo/log" - - "github.com/metacubex/sing-shadowtls" - "github.com/metacubex/tls" - "golang.org/x/exp/slices" -) - -const ( - Mode string = "shadow-tls" -) - -var ( - DefaultALPN = []string{"h2", "http/1.1"} - WsALPN = []string{"http/1.1"} -) - -type ShadowTLSOption struct { - Password string - Host string - Fingerprint string - Certificate string - PrivateKey string - ClientFingerprint string - SkipCertVerify bool - NameCertVerify string - Version int - ALPN []string -} - -func NewShadowTLS(ctx context.Context, conn net.Conn, option *ShadowTLSOption) (net.Conn, error) { - tlsConfig, err := ca.GetTLSConfig(ca.Option{ - TLSConfig: &tls.Config{ - NextProtos: option.ALPN, - MinVersion: tls.VersionTLS12, - InsecureSkipVerify: option.SkipCertVerify, - ServerName: option.Host, - }, - Fingerprint: option.Fingerprint, - NameCertVerify: option.NameCertVerify, - Certificate: option.Certificate, - PrivateKey: option.PrivateKey, - }) - if err != nil { - return nil, err - } - - if option.Version == 1 { - tlsConfig.MaxVersion = tls.VersionTLS12 // ShadowTLS v1 only support TLS 1.2 - } - - tlsHandshake := uTLSHandshakeFunc(tlsConfig, option.ClientFingerprint, option.Version) - client, err := shadowtls.NewClient(shadowtls.ClientConfig{ - Version: option.Version, - Password: option.Password, - TLSHandshake: tlsHandshake, - Logger: log.SingLogger, - }) - if err != nil { - return nil, err - } - return client.DialContextConn(ctx, conn) -} - -func uTLSHandshakeFunc(config *tls.Config, clientFingerprint string, version int) shadowtls.TLSHandshakeFunc { - return func(ctx context.Context, conn net.Conn, sessionIDGenerator shadowtls.TLSSessionIDGeneratorFunc) error { - tlsConfig := tlsC.UConfig(config) - tlsConfig.SessionIDGenerator = sessionIDGenerator - if version == 1 { - tlsConfig.MaxVersion = tlsC.VersionTLS12 // ShadowTLS v1 only support TLS 1.2 - tlsConn := tlsC.Client(conn, tlsConfig) - return tlsConn.HandshakeContext(ctx) - } - if clientFingerprint, ok := tlsC.GetFingerprint(clientFingerprint); ok { - tlsConn := tlsC.UClient(conn, tlsConfig, clientFingerprint) - if slices.Equal(tlsConfig.NextProtos, WsALPN) { - err := tlsC.BuildWebsocketHandshakeState(tlsConn) - if err != nil { - return err - } - } - if version == 2 { // ShadowTLS v2 not work with X25519MLKEM768 - err := tlsC.BuildRemovedX25519MLKEM768HandshakeState(tlsConn) - if err != nil { - return err - } - } - return tlsConn.HandshakeContext(ctx) - } - tlsConn := tlsC.Client(conn, tlsConfig) - return tlsConn.HandshakeContext(ctx) - } -}