From 8b8eae56d75712dcbf92e3b9cd620eee75216c9f Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Sun, 10 May 2026 18:36:26 +0800 Subject: [PATCH] feat: support simple-obfs for shadowsocks listener --- docs/config.yaml | 3 + listener/config/shadowsocks.go | 22 ++-- listener/inbound/shadowsocks.go | 42 ++++--- listener/inbound/shadowsocks_test.go | 28 +++++ listener/shadowsocks/tcp.go | 19 ++- listener/sing_shadowsocks/server.go | 16 +++ transport/simple-obfs/http.go | 3 +- transport/simple-obfs/http_server.go | 99 ++++++++++++++++ transport/simple-obfs/tls_server.go | 165 +++++++++++++++++++++++++++ 9 files changed, 372 insertions(+), 25 deletions(-) create mode 100644 transport/simple-obfs/http_server.go create mode 100644 transport/simple-obfs/tls_server.go diff --git a/docs/config.yaml b/docs/config.yaml index 44741d353..15e8b7fcf 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -1559,6 +1559,9 @@ listeners: # proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错) password: vlmpIPSyHH6f4S8WVPdRIHIlzmB+GIRfoH3aNJ/t9Gg= cipher: 2022-blake3-aes-256-gcm + # simple-obfs: + # enable: false # 设置为true时开启 + # mode: http # Available: http, tls # shadow-tls: # enable: false # 设置为true时开启 # version: 3 # 支持v1/v2/v3 diff --git a/listener/config/shadowsocks.go b/listener/config/shadowsocks.go index 37bbb7211..2e3a8d7ef 100644 --- a/listener/config/shadowsocks.go +++ b/listener/config/shadowsocks.go @@ -7,14 +7,20 @@ import ( ) type ShadowsocksServer struct { - Enable bool - Listen string - Password string - Cipher string - Udp bool - MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"` - ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"` - KcpTun KcpTun `yaml:"kcp-tun" json:"kcp-tun,omitempty"` + Enable bool + Listen string + Password string + Cipher string + Udp bool + MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"` + ShadowTLS ShadowTLS `yaml:"shadow-tls" json:"shadow-tls,omitempty"` + KcpTun KcpTun `yaml:"kcp-tun" json:"kcp-tun,omitempty"` + SimpleObfs SimpleObfs `yaml:"simple-obfs" json:"simple-obfs,omitempty"` +} + +type SimpleObfs struct { + Enable bool + Mode string } func (t ShadowsocksServer) String() string { diff --git a/listener/inbound/shadowsocks.go b/listener/inbound/shadowsocks.go index b88013a80..cd163b6f6 100644 --- a/listener/inbound/shadowsocks.go +++ b/listener/inbound/shadowsocks.go @@ -11,12 +11,25 @@ import ( type ShadowSocksOption struct { BaseOption - Password string `inbound:"password"` - Cipher string `inbound:"cipher"` - UDP bool `inbound:"udp,omitempty"` - MuxOption MuxOption `inbound:"mux-option,omitempty"` - ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"` - KcpTun KcpTun `inbound:"kcp-tun,omitempty"` + Password string `inbound:"password"` + Cipher string `inbound:"cipher"` + UDP bool `inbound:"udp,omitempty"` + MuxOption MuxOption `inbound:"mux-option,omitempty"` + ShadowTLS ShadowTLS `inbound:"shadow-tls,omitempty"` + KcpTun KcpTun `inbound:"kcp-tun,omitempty"` + SimpleObfs SimpleObfs `inbound:"simple-obfs,omitempty"` +} + +type SimpleObfs struct { + Enable bool `inbound:"enable,omitempty"` + Mode string `inbound:"mode,omitempty"` +} + +func (o SimpleObfs) Build() LC.SimpleObfs { + return LC.SimpleObfs{ + Enable: o.Enable, + Mode: o.Mode, + } } func (o ShadowSocksOption) Equal(config C.InboundConfig) bool { @@ -39,14 +52,15 @@ func NewShadowSocks(options *ShadowSocksOption) (*ShadowSocks, error) { Base: base, config: options, ss: LC.ShadowsocksServer{ - Enable: true, - Listen: base.RawAddress(), - Password: options.Password, - Cipher: options.Cipher, - Udp: options.UDP, - MuxOption: options.MuxOption.Build(), - ShadowTLS: options.ShadowTLS.Build(), - KcpTun: options.KcpTun.Build(), + Enable: true, + Listen: base.RawAddress(), + Password: options.Password, + Cipher: options.Cipher, + Udp: options.UDP, + MuxOption: options.MuxOption.Build(), + ShadowTLS: options.ShadowTLS.Build(), + KcpTun: options.KcpTun.Build(), + SimpleObfs: options.SimpleObfs.Build(), }, }, nil } diff --git a/listener/inbound/shadowsocks_test.go b/listener/inbound/shadowsocks_test.go index 755db2cf8..27f9fa871 100644 --- a/listener/inbound/shadowsocks_test.go +++ b/listener/inbound/shadowsocks_test.go @@ -167,6 +167,34 @@ func TestInboundShadowSocks_ShadowTlsv3(t *testing.T) { testInboundShadowSocksShadowTls(t, inboundOptions, outboundOptions) } +func TestInboundShadowSocks_SimpleObfs_Http(t *testing.T) { + inboundOptions := inbound.ShadowSocksOption{ + SimpleObfs: inbound.SimpleObfs{ + Enable: true, + Mode: "http", + }, + } + outboundOptions := outbound.ShadowSocksOption{ + Plugin: "obfs", + PluginOpts: map[string]any{"mode": "http", "host": realityDest}, + } + testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, false) +} + +func TestInboundShadowSocks_SimpleObfs_Tls(t *testing.T) { + inboundOptions := inbound.ShadowSocksOption{ + SimpleObfs: inbound.SimpleObfs{ + Enable: true, + Mode: "tls", + }, + } + outboundOptions := outbound.ShadowSocksOption{ + Plugin: "obfs", + PluginOpts: map[string]any{"mode": "tls", "host": realityDest}, + } + testInboundShadowSocks(t, inboundOptions, outboundOptions, shadowsocksCipherShortLists, false) +} + func TestInboundShadowSocks_KcpTun(t *testing.T) { if runtime.GOOS == "windows" && strings.HasPrefix(runtime.Version(), "go1.20") { t.Skip("skip kcptun test on windows go1.20") diff --git a/listener/shadowsocks/tcp.go b/listener/shadowsocks/tcp.go index 8ae269ed9..74613dc94 100644 --- a/listener/shadowsocks/tcp.go +++ b/listener/shadowsocks/tcp.go @@ -1,6 +1,7 @@ package shadowsocks import ( + "fmt" "net" "strings" @@ -10,6 +11,7 @@ import ( LC "github.com/metacubex/mihomo/listener/config" "github.com/metacubex/mihomo/listener/sing" "github.com/metacubex/mihomo/transport/shadowsocks/core" + obfs "github.com/metacubex/mihomo/transport/simple-obfs" "github.com/metacubex/mihomo/transport/socks5" ) @@ -20,6 +22,7 @@ type Listener struct { udpListeners []*UDPListener pickCipher core.Cipher handler *sing.ListenerHandler + simpleObfs func(net.Conn) net.Conn } var _listener *Listener @@ -40,9 +43,20 @@ func New(config LC.ShadowsocksServer, tunnel C.Tunnel, additions ...inbound.Addi return nil, err } - sl := &Listener{false, config, nil, nil, pickCipher, h} + sl := &Listener{config: config, pickCipher: pickCipher, handler: h} _listener = sl + if config.SimpleObfs.Enable { + switch config.SimpleObfs.Mode { + case "http": + sl.simpleObfs = obfs.NewHTTPObfsServer + case "tls": + sl.simpleObfs = obfs.NewTLSObfsServer + default: + return nil, fmt.Errorf("unsupported simple obfs mode: %s", config.SimpleObfs.Mode) + } + } + for _, addr := range strings.Split(config.Listen, ",") { addr := addr @@ -111,6 +125,9 @@ func (l *Listener) AddrList() (addrList []net.Addr) { } func (l *Listener) HandleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) { + if l.simpleObfs != nil { + conn = l.simpleObfs(conn) + } conn = l.pickCipher.StreamConn(conn) conn = N.NewDeadlineConn(conn) // embed ss can't handle readDeadline correctly diff --git a/listener/sing_shadowsocks/server.go b/listener/sing_shadowsocks/server.go index e106867d5..287705719 100644 --- a/listener/sing_shadowsocks/server.go +++ b/listener/sing_shadowsocks/server.go @@ -15,6 +15,7 @@ import ( "github.com/metacubex/mihomo/log" "github.com/metacubex/mihomo/ntp" "github.com/metacubex/mihomo/transport/kcptun" + obfs "github.com/metacubex/mihomo/transport/simple-obfs" shadowsocks "github.com/metacubex/sing-shadowsocks" "github.com/metacubex/sing-shadowsocks/shadowaead" @@ -34,6 +35,7 @@ type Listener struct { udpListeners []net.PacketConn service shadowsocks.Service shadowTLS *shadowtls.Service + simpleObfs func(net.Conn) net.Conn } var _listener *Listener @@ -139,6 +141,17 @@ func New(config LC.ShadowsocksServer, tunnel C.Tunnel, additions ...inbound.Addi } } + if config.SimpleObfs.Enable { + switch config.SimpleObfs.Mode { + case "http": + sl.simpleObfs = obfs.NewHTTPObfsServer + case "tls": + sl.simpleObfs = obfs.NewTLSObfsServer + default: + return nil, fmt.Errorf("unsupported simple obfs mode: %s", config.SimpleObfs.Mode) + } + } + var kcptunServer *kcptun.Server if config.KcpTun.Enable { kcptunServer = kcptun.NewServer(config.KcpTun.Config) @@ -268,6 +281,9 @@ 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...) + if l.simpleObfs != nil { + conn = l.simpleObfs(conn) + } err := l.service.NewConnection(ctx, conn, M.Metadata{ Protocol: "shadowsocks", Source: M.SocksaddrFromNet(conn.RemoteAddr()), diff --git a/transport/simple-obfs/http.go b/transport/simple-obfs/http.go index b5b31dccf..8b40e5f21 100644 --- a/transport/simple-obfs/http.go +++ b/transport/simple-obfs/http.go @@ -70,7 +70,7 @@ func (ho *HTTPObfs) Write(b []byte) (int, error) { if err != nil { return 0, err } - req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", randv2.Int()%54, randv2.Int()%2)) + req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", randv2.IntN(54), randv2.IntN(2))) req.Header.Set("Upgrade", "websocket") req.Header.Set("Connection", "Upgrade") req.Host = ho.host @@ -83,7 +83,6 @@ func (ho *HTTPObfs) Write(b []byte) (int, error) { ho.firstRequest = false return len(b), err } - return ho.Conn.Write(b) } diff --git a/transport/simple-obfs/http_server.go b/transport/simple-obfs/http_server.go new file mode 100644 index 000000000..c1925acfd --- /dev/null +++ b/transport/simple-obfs/http_server.go @@ -0,0 +1,99 @@ +package obfs + +import ( + "bufio" + "crypto/rand" + "encoding/base64" + "fmt" + "io" + "net" + "time" + + "github.com/metacubex/http" + "github.com/metacubex/randv2" +) + +type HTTPObfsServer struct { + net.Conn + buf []byte + bio *bufio.Reader + offset int + firstRequest bool + firstResponse bool +} + +func (hos *HTTPObfsServer) Read(b []byte) (int, error) { + if hos.buf != nil { + n := copy(b, hos.buf[hos.offset:]) + hos.offset += n + if hos.offset == len(hos.buf) { + hos.offset = 0 + hos.buf = nil + } + return n, nil + } + + if hos.firstRequest { + bio := bufio.NewReader(hos.Conn) + req, err := http.ReadRequest(bio) + if err != nil { + return 0, err + } + if req.Method != "GET" || req.Header.Get("Connection") != "Upgrade" { + return 0, io.EOF + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + return 0, err + } + n := copy(b, buf) + if n < len(buf) { + hos.buf = buf + hos.offset = n + } + req.Body.Close() + hos.bio = bio + hos.firstRequest = false + return n, nil + } + + return hos.bio.Read(b) +} + +const httpResponseTemplate = "HTTP/1.1 101 Switching Protocols\r\n" + + "Server: nginx/1.%d.%d\r\n" + + "Date: %s\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Accept: %s\r\n" + + "\r\n" + +var vMajor = randv2.IntN(11) +var vMinor = randv2.IntN(12) + +func (hos *HTTPObfsServer) Write(b []byte) (int, error) { + if hos.firstResponse { + randBytes := make([]byte, 16) + rand.Read(randBytes) + date := time.Now().Format(time.RFC1123) + resp := fmt.Sprintf(httpResponseTemplate, vMajor, vMinor, date, base64.URLEncoding.EncodeToString(randBytes)) + _, err := hos.Conn.Write([]byte(resp)) + if err != nil { + return 0, err + } + hos.firstResponse = false + } + return hos.Conn.Write(b) +} + +func NewHTTPObfsServer(conn net.Conn) net.Conn { + return &HTTPObfsServer{ + Conn: conn, + buf: nil, + bio: nil, + offset: 0, + firstRequest: true, + firstResponse: true, + } +} diff --git a/transport/simple-obfs/tls_server.go b/transport/simple-obfs/tls_server.go new file mode 100644 index 000000000..641002da8 --- /dev/null +++ b/transport/simple-obfs/tls_server.go @@ -0,0 +1,165 @@ +package obfs + +import ( + "bytes" + "crypto/rand" + "encoding/binary" + "io" + "net" + "time" + + "github.com/metacubex/mihomo/common/pool" +) + +type TLSObfsServer struct { + net.Conn + remain int + firstRequest bool + sessionTicketDone bool + firstResponse bool +} + +func (tos *TLSObfsServer) read(b []byte, discardN int) (int, error) { + buf := pool.Get(discardN) + _, err := io.ReadFull(tos.Conn, buf) + pool.Put(buf) + if err != nil { + return 0, err + } + + sizeBuf := make([]byte, 2) + _, err = io.ReadFull(tos.Conn, sizeBuf) + if err != nil { + return 0, nil + } + + length := int(binary.BigEndian.Uint16(sizeBuf)) + if length > len(b) { + n, err := tos.Conn.Read(b) + if err != nil { + return n, err + } + tos.remain = length - n + return n, nil + } + + return io.ReadFull(tos.Conn, b[:length]) +} + +// skip SNI & other TLS extensions +func (tos *TLSObfsServer) skipOtherExts() error { + // SNI first + buf := make([]byte, 256) + _, err := tos.read(buf, 7) + if err != nil { + return err + } + + _, err = io.ReadFull(tos.Conn, buf[:4*16+2]) + return err +} + +func (tos *TLSObfsServer) Read(b []byte) (int, error) { + if tos.remain > 0 { + length := tos.remain + if length > len(b) { + length = len(b) + } + + n, err := io.ReadFull(tos.Conn, b[:length]) + tos.remain -= n + return n, err + } + + if tos.firstRequest { + tos.firstRequest = false + return tos.read(b, 9*16-4) + } + + if !tos.sessionTicketDone { + tos.sessionTicketDone = true + err := tos.skipOtherExts() + if err != nil { + return 0, err + } + } + + return tos.read(b, 3) +} + +func (tos *TLSObfsServer) 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 := tos.write(b[i:end]) + if err != nil { + return n, err + } + } + return length, nil +} + +func (tos *TLSObfsServer) write(b []byte) (int, error) { + if tos.firstResponse { + serverHello := makeServerHello(b) + _, err := tos.Conn.Write(serverHello) + tos.firstResponse = false + return len(b), err + } + + buf := pool.GetBuffer() + defer pool.PutBuffer(buf) + buf.Write([]byte{0x17, 0x03, 0x03}) + binary.Write(buf, binary.BigEndian, uint16(len(b))) + buf.Write(b) + _, err := tos.Conn.Write(buf.Bytes()) + if err != nil { + return 0, err + } + return len(b), nil +} + +func NewTLSObfsServer(conn net.Conn) net.Conn { + return &TLSObfsServer{ + Conn: conn, + firstRequest: true, + firstResponse: true, + } +} + +func makeServerHello(data []byte) []byte { + randBytes := make([]byte, 28) + sessionId := make([]byte, 32) + rand.Read(randBytes) + rand.Read(sessionId) + + buf := &bytes.Buffer{} + + buf.WriteByte(0x16) + binary.Write(buf, binary.BigEndian, uint16(0x0301)) + binary.Write(buf, binary.BigEndian, uint16(91)) + buf.Write([]byte{2, 0, 0, 87, 0x03, 0x03}) + binary.Write(buf, binary.BigEndian, uint32(time.Now().Unix())) + buf.Write(randBytes) + buf.WriteByte(32) + buf.Write(sessionId) + + buf.Write([]byte{0xcc, 0xa8}) + buf.WriteByte(0) + buf.Write([]byte{0x00, 0x00}) + buf.Write([]byte{0xff, 0x01, 0x00, 0x01, 0x00}) + buf.Write([]byte{0x00, 0x17, 0x00, 0x00}) + buf.Write([]byte{0x00, 0x0b, 0x00, 0x02, 0x01, 0x00}) + + buf.Write([]byte{0x14, 0x03, 0x03, 0x00, 0x01, 0x01}) + + buf.Write([]byte{0x16, 0x03, 0x03}) + binary.Write(buf, binary.BigEndian, uint16(len(data))) + buf.Write(data) + + return buf.Bytes() +}