mirror of
https://github.com/bolucat/Archive.git
synced 2025-12-24 13:28:37 +08:00
Update On Fri Dec 5 19:41:42 CET 2025
This commit is contained in:
@@ -2,43 +2,34 @@ package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/saba-futai/sudoku/apis"
|
||||
"github.com/saba-futai/sudoku/pkg/crypto"
|
||||
"github.com/saba-futai/sudoku/pkg/obfs/httpmask"
|
||||
sudokuobfs "github.com/saba-futai/sudoku/pkg/obfs/sudoku"
|
||||
|
||||
N "github.com/metacubex/mihomo/common/net"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
"github.com/metacubex/mihomo/transport/sudoku"
|
||||
)
|
||||
|
||||
type Sudoku struct {
|
||||
*Base
|
||||
option *SudokuOption
|
||||
table *sudokuobfs.Table
|
||||
baseConf apis.ProtocolConfig
|
||||
baseConf sudoku.ProtocolConfig
|
||||
}
|
||||
|
||||
type SudokuOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Key string `proxy:"key"`
|
||||
AEADMethod string `proxy:"aead-method,omitempty"`
|
||||
PaddingMin *int `proxy:"padding-min,omitempty"`
|
||||
PaddingMax *int `proxy:"padding-max,omitempty"`
|
||||
TableType string `proxy:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
|
||||
HTTPMask bool `proxy:"http-mask,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Key string `proxy:"key"`
|
||||
AEADMethod string `proxy:"aead-method,omitempty"`
|
||||
PaddingMin *int `proxy:"padding-min,omitempty"`
|
||||
PaddingMax *int `proxy:"padding-max,omitempty"`
|
||||
TableType string `proxy:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
|
||||
EnablePureDownlink *bool `proxy:"enable-pure-downlink,omitempty"`
|
||||
HTTPMask bool `proxy:"http-mask,omitempty"`
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
@@ -62,11 +53,21 @@ func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Con
|
||||
defer done(&err)
|
||||
}
|
||||
|
||||
c, err = s.streamConn(c, cfg)
|
||||
c, err = sudoku.ClientHandshake(c, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
addrBuf, err := sudoku.EncodeAddress(cfg.TargetAddress)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode target address failed: %w", err)
|
||||
}
|
||||
|
||||
if _, err = c.Write(addrBuf); err != nil {
|
||||
_ = c.Close()
|
||||
return nil, fmt.Errorf("send target address failed: %w", err)
|
||||
}
|
||||
|
||||
return NewConn(c, s), nil
|
||||
}
|
||||
|
||||
@@ -95,7 +96,7 @@ func (s *Sudoku) ListenPacketContext(ctx context.Context, metadata *C.Metadata)
|
||||
defer done(&err)
|
||||
}
|
||||
|
||||
c, err = s.handshakeConn(c, cfg)
|
||||
c, err = sudoku.ClientHandshake(c, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -120,7 +121,7 @@ func (s *Sudoku) ProxyInfo() C.ProxyInfo {
|
||||
return info
|
||||
}
|
||||
|
||||
func (s *Sudoku) buildConfig(metadata *C.Metadata) (*apis.ProtocolConfig, error) {
|
||||
func (s *Sudoku) buildConfig(metadata *C.Metadata) (*sudoku.ProtocolConfig, error) {
|
||||
if metadata == nil || metadata.DstPort == 0 || !metadata.Valid() {
|
||||
return nil, fmt.Errorf("invalid metadata for sudoku outbound")
|
||||
}
|
||||
@@ -134,47 +135,6 @@ func (s *Sudoku) buildConfig(metadata *C.Metadata) (*apis.ProtocolConfig, error)
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func (s *Sudoku) handshakeConn(rawConn net.Conn, cfg *apis.ProtocolConfig) (_ net.Conn, err error) {
|
||||
if !cfg.DisableHTTPMask {
|
||||
if err = httpmask.WriteRandomRequestHeader(rawConn, cfg.ServerAddress); err != nil {
|
||||
return nil, fmt.Errorf("write http mask failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
obfsConn := sudokuobfs.NewConn(rawConn, cfg.Table, cfg.PaddingMin, cfg.PaddingMax, false)
|
||||
cConn, err := crypto.NewAEADConn(obfsConn, cfg.Key, cfg.AEADMethod)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("setup crypto failed: %w", err)
|
||||
}
|
||||
|
||||
handshake := buildSudokuHandshakePayload(cfg.Key)
|
||||
if _, err = cConn.Write(handshake[:]); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("send handshake failed: %w", err)
|
||||
}
|
||||
|
||||
return cConn, nil
|
||||
}
|
||||
|
||||
func (s *Sudoku) streamConn(rawConn net.Conn, cfg *apis.ProtocolConfig) (_ net.Conn, err error) {
|
||||
cConn, err := s.handshakeConn(rawConn, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
addrBuf, err := sudoku.EncodeAddress(cfg.TargetAddress)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode target address failed: %w", err)
|
||||
}
|
||||
|
||||
if _, err = cConn.Write(addrBuf); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("send target address failed: %w", err)
|
||||
}
|
||||
|
||||
return cConn, nil
|
||||
}
|
||||
|
||||
func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||
if option.Server == "" {
|
||||
return nil, fmt.Errorf("server is required")
|
||||
@@ -194,16 +154,7 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||
return nil, fmt.Errorf("table-type must be prefer_ascii or prefer_entropy")
|
||||
}
|
||||
|
||||
seed := option.Key
|
||||
if recoveredFromKey, err := crypto.RecoverPublicKey(option.Key); err == nil {
|
||||
seed = crypto.EncodePoint(recoveredFromKey)
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
table := sudokuobfs.NewTable(seed, tableType)
|
||||
log.Infoln("[Sudoku] Tables initialized (%s) in %v", tableType, time.Since(start))
|
||||
|
||||
defaultConf := apis.DefaultConfig()
|
||||
defaultConf := sudoku.DefaultConfig()
|
||||
paddingMin := defaultConf.PaddingMin
|
||||
paddingMax := defaultConf.PaddingMax
|
||||
if option.PaddingMin != nil {
|
||||
@@ -218,14 +169,19 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||
if option.PaddingMax == nil && option.PaddingMin != nil && paddingMax < paddingMin {
|
||||
paddingMax = paddingMin
|
||||
}
|
||||
enablePureDownlink := defaultConf.EnablePureDownlink
|
||||
if option.EnablePureDownlink != nil {
|
||||
enablePureDownlink = *option.EnablePureDownlink
|
||||
}
|
||||
|
||||
baseConf := apis.ProtocolConfig{
|
||||
baseConf := sudoku.ProtocolConfig{
|
||||
ServerAddress: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
Key: option.Key,
|
||||
AEADMethod: defaultConf.AEADMethod,
|
||||
Table: table,
|
||||
Table: sudoku.NewTable(sudoku.ClientAEADSeed(option.Key), tableType),
|
||||
PaddingMin: paddingMin,
|
||||
PaddingMax: paddingMax,
|
||||
EnablePureDownlink: enablePureDownlink,
|
||||
HandshakeTimeoutSeconds: defaultConf.HandshakeTimeoutSeconds,
|
||||
DisableHTTPMask: !option.HTTPMask,
|
||||
}
|
||||
@@ -247,17 +203,8 @@ func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||
prefer: option.IPVersion,
|
||||
},
|
||||
option: &option,
|
||||
table: table,
|
||||
baseConf: baseConf,
|
||||
}
|
||||
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||
return outbound, nil
|
||||
}
|
||||
|
||||
func buildSudokuHandshakePayload(key string) [16]byte {
|
||||
var payload [16]byte
|
||||
binary.BigEndian.PutUint64(payload[:8], uint64(time.Now().Unix()))
|
||||
hash := sha256.Sum256([]byte(key))
|
||||
copy(payload[8:], hash[:8])
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/metacubex/mihomo/component/ech"
|
||||
"github.com/metacubex/mihomo/transport/sudoku"
|
||||
"github.com/metacubex/mihomo/transport/vless/encryption"
|
||||
"github.com/saba-futai/sudoku/pkg/crypto"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
)
|
||||
@@ -71,18 +71,12 @@ func Main(args []string) {
|
||||
fmt.Println("Password: " + passwordBase64)
|
||||
fmt.Println("Hash32: " + hash32Base64)
|
||||
case "sudoku-keypair":
|
||||
// Generate Master Key
|
||||
pair, err := crypto.GenerateMasterKey()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// Split the master private key to get Available Private Key
|
||||
availablePrivateKey, err := crypto.SplitPrivateKey(pair.Private)
|
||||
privateKey, publicKey, err := sudoku.GenKeyPair()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// Output: Available Private Key for client, Master Public Key for server
|
||||
fmt.Println("PrivateKey: " + availablePrivateKey)
|
||||
fmt.Println("PublicKey: " + crypto.EncodePoint(pair.Public))
|
||||
fmt.Println("PrivateKey: " + privateKey)
|
||||
fmt.Println("PublicKey: " + publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1049,6 +1049,7 @@ proxies: # socks5
|
||||
padding-max: 7 # 最大填充字节数
|
||||
table-type: prefer_ascii # 可选值:prefer_ascii、prefer_entropy 前者全ascii映射,后者保证熵值(汉明1)低于3
|
||||
http-mask: true # 是否启用http掩码
|
||||
enable-pure-downlink: false # 是否启用混淆下行,false的情况下能在保证数据安全的前提下极大提升下行速度
|
||||
|
||||
# anytls
|
||||
- name: anytls
|
||||
@@ -1589,6 +1590,8 @@ listeners:
|
||||
padding-max: 15 # 填充最大长度,均不建议过大
|
||||
table-type: prefer_ascii # 可选值:prefer_ascii、prefer_entropy 前者全ascii映射,后者保证熵值(汉明1)低于3
|
||||
handshake-timeout: 5 # optional
|
||||
enable-pure-downlink: false # 是否启用混淆下行,false的情况下能在保证数据安全的前提下极大提升下行速度,与客户端保持相同
|
||||
|
||||
|
||||
|
||||
- name: trojan-in-1
|
||||
|
||||
@@ -43,7 +43,7 @@ require (
|
||||
github.com/mroth/weightedrand/v2 v2.1.0
|
||||
github.com/openacid/low v0.1.21
|
||||
github.com/oschwald/maxminddb-golang v1.12.0 // lastest version compatible with golang1.20
|
||||
github.com/saba-futai/sudoku v0.0.1-i
|
||||
github.com/saba-futai/sudoku v0.0.2-b
|
||||
github.com/sagernet/cors v1.2.1
|
||||
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a
|
||||
github.com/samber/lo v1.52.0
|
||||
|
||||
@@ -171,8 +171,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
|
||||
github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
|
||||
github.com/quic-go/qpack v0.4.0 h1:Cr9BXA1sQS2SmDUWjSofMPNKmvF6IiIfDRmgU0w1ZCo=
|
||||
github.com/quic-go/qpack v0.4.0/go.mod h1:UZVnYIfi5GRk+zI9UMaCPsmZ2xKJP7XBUvVyT1Knj9A=
|
||||
github.com/saba-futai/sudoku v0.0.1-i h1:t6H875LSceXaEEwho84GU9OoLa4ieoBo3v+dxpFf4wc=
|
||||
github.com/saba-futai/sudoku v0.0.1-i/go.mod h1:FNtEAA44TSMvHI94o1kri/itbjvSMm1qCrbd0e6MTZY=
|
||||
github.com/saba-futai/sudoku v0.0.2-b h1:IbBjgZe1IzzD4xjaCSAdAy8ZNrwOusT14AwCYm77NwI=
|
||||
github.com/saba-futai/sudoku v0.0.2-b/go.mod h1:Rvggsoprp7HQM7bMIZUd1M27bPj8THRsZdY1dGbIAvo=
|
||||
github.com/sagernet/cors v1.2.1 h1:Cv5Z8y9YSD6Gm+qSpNrL3LO4lD3eQVvbFYJSG7JCMHQ=
|
||||
github.com/sagernet/cors v1.2.1/go.mod h1:O64VyOjjhrkLmQIjF4KGRrJO/5dVXFdpEmCW/eISRAI=
|
||||
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a h1:ObwtHN2VpqE0ZNjr6sGeT00J8uU7JF4cNUdb44/Duis=
|
||||
|
||||
@@ -13,6 +13,7 @@ type SudokuServer struct {
|
||||
PaddingMax *int `json:"padding-max,omitempty"`
|
||||
TableType string `json:"table-type,omitempty"`
|
||||
HandshakeTimeoutSecond *int `json:"handshake-timeout,omitempty"`
|
||||
EnablePureDownlink *bool `json:"enable-pure-downlink,omitempty"`
|
||||
}
|
||||
|
||||
func (s SudokuServer) String() string {
|
||||
|
||||
@@ -5,11 +5,9 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/saba-futai/sudoku/apis"
|
||||
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
LC "github.com/metacubex/mihomo/listener/config"
|
||||
sudokuListener "github.com/metacubex/mihomo/listener/sudoku"
|
||||
"github.com/metacubex/mihomo/listener/sudoku"
|
||||
"github.com/metacubex/mihomo/log"
|
||||
)
|
||||
|
||||
@@ -21,6 +19,7 @@ type SudokuOption struct {
|
||||
PaddingMax *int `inbound:"padding-max,omitempty"`
|
||||
TableType string `inbound:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
|
||||
HandshakeTimeoutSecond *int `inbound:"handshake-timeout,omitempty"`
|
||||
EnablePureDownlink *bool `inbound:"enable-pure-downlink,omitempty"`
|
||||
}
|
||||
|
||||
func (o SudokuOption) Equal(config C.InboundConfig) bool {
|
||||
@@ -30,7 +29,7 @@ func (o SudokuOption) Equal(config C.InboundConfig) bool {
|
||||
type Sudoku struct {
|
||||
*Base
|
||||
config *SudokuOption
|
||||
listeners []*sudokuListener.Listener
|
||||
listeners []*sudoku.Listener
|
||||
serverConf LC.SudokuServer
|
||||
}
|
||||
|
||||
@@ -43,23 +42,16 @@ func NewSudoku(options *SudokuOption) (*Sudoku, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defaultConf := apis.DefaultConfig()
|
||||
|
||||
serverConf := LC.SudokuServer{
|
||||
Enable: true,
|
||||
Listen: base.RawAddress(),
|
||||
Key: options.Key,
|
||||
AEADMethod: options.AEADMethod,
|
||||
PaddingMin: options.PaddingMin,
|
||||
PaddingMax: options.PaddingMax,
|
||||
TableType: options.TableType,
|
||||
}
|
||||
if options.HandshakeTimeoutSecond != nil {
|
||||
serverConf.HandshakeTimeoutSecond = options.HandshakeTimeoutSecond
|
||||
} else {
|
||||
// Use Sudoku default if not specified.
|
||||
v := defaultConf.HandshakeTimeoutSeconds
|
||||
serverConf.HandshakeTimeoutSecond = &v
|
||||
Enable: true,
|
||||
Listen: base.RawAddress(),
|
||||
Key: options.Key,
|
||||
AEADMethod: options.AEADMethod,
|
||||
PaddingMin: options.PaddingMin,
|
||||
PaddingMax: options.PaddingMax,
|
||||
TableType: options.TableType,
|
||||
HandshakeTimeoutSecond: options.HandshakeTimeoutSecond,
|
||||
EnablePureDownlink: options.EnablePureDownlink,
|
||||
}
|
||||
|
||||
return &Sudoku{
|
||||
@@ -94,7 +86,7 @@ func (s *Sudoku) Listen(tunnel C.Tunnel) error {
|
||||
conf := s.serverConf
|
||||
conf.Listen = addr
|
||||
|
||||
l, err := sudokuListener.New(conf, tunnel, s.Additions()...)
|
||||
l, err := sudoku.New(conf, tunnel, s.Additions()...)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
|
||||
@@ -6,9 +6,12 @@ import (
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/outbound"
|
||||
"github.com/metacubex/mihomo/listener/inbound"
|
||||
"github.com/metacubex/mihomo/transport/sudoku"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var sudokuPrivateKey, sudokuPublicKey, _ = sudoku.GenKeyPair()
|
||||
|
||||
func testInboundSudoku(t *testing.T, inboundOptions inbound.SudokuOption, outboundOptions outbound.SudokuOption) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -58,6 +61,14 @@ func TestInboundSudoku_Basic(t *testing.T) {
|
||||
Key: key,
|
||||
}
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
|
||||
t.Run("ed25519key", func(t *testing.T) {
|
||||
inboundOptions := inboundOptions
|
||||
outboundOptions := outboundOptions
|
||||
inboundOptions.Key = sudokuPublicKey
|
||||
outboundOptions.Key = sudokuPrivateKey
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundSudoku_Entropy(t *testing.T) {
|
||||
@@ -71,21 +82,59 @@ func TestInboundSudoku_Entropy(t *testing.T) {
|
||||
TableType: "prefer_entropy",
|
||||
}
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
|
||||
t.Run("ed25519key", func(t *testing.T) {
|
||||
inboundOptions := inboundOptions
|
||||
outboundOptions := outboundOptions
|
||||
inboundOptions.Key = sudokuPublicKey
|
||||
outboundOptions.Key = sudokuPrivateKey
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundSudoku_Padding(t *testing.T) {
|
||||
key := "test_key_padding"
|
||||
min := 10
|
||||
max := 100
|
||||
paddingMin := 10
|
||||
paddingMax := 100
|
||||
inboundOptions := inbound.SudokuOption{
|
||||
Key: key,
|
||||
PaddingMin: &min,
|
||||
PaddingMax: &max,
|
||||
PaddingMin: &paddingMin,
|
||||
PaddingMax: &paddingMax,
|
||||
}
|
||||
outboundOptions := outbound.SudokuOption{
|
||||
Key: key,
|
||||
PaddingMin: &min,
|
||||
PaddingMax: &max,
|
||||
PaddingMin: &paddingMin,
|
||||
PaddingMax: &paddingMax,
|
||||
}
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
|
||||
t.Run("ed25519key", func(t *testing.T) {
|
||||
inboundOptions := inboundOptions
|
||||
outboundOptions := outboundOptions
|
||||
inboundOptions.Key = sudokuPublicKey
|
||||
outboundOptions.Key = sudokuPrivateKey
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboundSudoku_PackedDownlink(t *testing.T) {
|
||||
key := "test_key_packed"
|
||||
enablePure := false
|
||||
inboundOptions := inbound.SudokuOption{
|
||||
Key: key,
|
||||
EnablePureDownlink: &enablePure,
|
||||
}
|
||||
outboundOptions := outbound.SudokuOption{
|
||||
Key: key,
|
||||
EnablePureDownlink: &enablePure,
|
||||
}
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
|
||||
t.Run("ed25519key", func(t *testing.T) {
|
||||
inboundOptions := inboundOptions
|
||||
outboundOptions := outboundOptions
|
||||
inboundOptions.Key = sudokuPublicKey
|
||||
outboundOptions.Key = sudokuPrivateKey
|
||||
testInboundSudoku(t, inboundOptions, outboundOptions)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,9 +6,6 @@ import (
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/saba-futai/sudoku/apis"
|
||||
sudokuobfs "github.com/saba-futai/sudoku/pkg/obfs/sudoku"
|
||||
|
||||
"github.com/metacubex/mihomo/adapter/inbound"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
LC "github.com/metacubex/mihomo/listener/config"
|
||||
@@ -21,7 +18,7 @@ type Listener struct {
|
||||
listener net.Listener
|
||||
addr string
|
||||
closed bool
|
||||
protoConf apis.ProtocolConfig
|
||||
protoConf sudoku.ProtocolConfig
|
||||
}
|
||||
|
||||
// RawAddress implements C.Listener
|
||||
@@ -135,9 +132,7 @@ func New(config LC.SudokuServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
tableType = "prefer_ascii"
|
||||
}
|
||||
|
||||
table := sudokuobfs.NewTable(config.Key, tableType)
|
||||
|
||||
defaultConf := apis.DefaultConfig()
|
||||
defaultConf := sudoku.DefaultConfig()
|
||||
paddingMin := defaultConf.PaddingMin
|
||||
paddingMax := defaultConf.PaddingMax
|
||||
if config.PaddingMin != nil {
|
||||
@@ -152,18 +147,23 @@ func New(config LC.SudokuServer, tunnel C.Tunnel, additions ...inbound.Addition)
|
||||
if config.PaddingMax == nil && config.PaddingMin != nil && paddingMax < paddingMin {
|
||||
paddingMax = paddingMin
|
||||
}
|
||||
enablePureDownlink := defaultConf.EnablePureDownlink
|
||||
if config.EnablePureDownlink != nil {
|
||||
enablePureDownlink = *config.EnablePureDownlink
|
||||
}
|
||||
|
||||
handshakeTimeout := defaultConf.HandshakeTimeoutSeconds
|
||||
if config.HandshakeTimeoutSecond != nil {
|
||||
handshakeTimeout = *config.HandshakeTimeoutSecond
|
||||
}
|
||||
|
||||
protoConf := apis.ProtocolConfig{
|
||||
protoConf := sudoku.ProtocolConfig{
|
||||
Key: config.Key,
|
||||
AEADMethod: defaultConf.AEADMethod,
|
||||
Table: table,
|
||||
Table: sudoku.NewTable(config.Key, tableType),
|
||||
PaddingMin: paddingMin,
|
||||
PaddingMax: paddingMax,
|
||||
EnablePureDownlink: enablePureDownlink,
|
||||
HandshakeTimeoutSeconds: handshakeTimeout,
|
||||
}
|
||||
if config.AEADMethod != "" {
|
||||
|
||||
@@ -2,6 +2,7 @@ package sudoku
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -16,6 +17,10 @@ import (
|
||||
"github.com/metacubex/mihomo/log"
|
||||
)
|
||||
|
||||
type ProtocolConfig = apis.ProtocolConfig
|
||||
|
||||
func DefaultConfig() *ProtocolConfig { return apis.DefaultConfig() }
|
||||
|
||||
type SessionType int
|
||||
|
||||
const (
|
||||
@@ -55,6 +60,37 @@ func (p *preBufferedConn) Read(b []byte) (int, error) {
|
||||
return p.Conn.Read(b)
|
||||
}
|
||||
|
||||
type directionalConn struct {
|
||||
net.Conn
|
||||
reader io.Reader
|
||||
writer io.Writer
|
||||
closers []func() error
|
||||
}
|
||||
|
||||
func (c *directionalConn) Read(p []byte) (int, error) {
|
||||
return c.reader.Read(p)
|
||||
}
|
||||
|
||||
func (c *directionalConn) Write(p []byte) (int, error) {
|
||||
return c.writer.Write(p)
|
||||
}
|
||||
|
||||
func (c *directionalConn) Close() error {
|
||||
var firstErr error
|
||||
for _, fn := range c.closers {
|
||||
if fn == nil {
|
||||
continue
|
||||
}
|
||||
if err := fn(); err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
if err := c.Conn.Close(); err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
return firstErr
|
||||
}
|
||||
|
||||
func absInt64(v int64) int64 {
|
||||
if v < 0 {
|
||||
return -v
|
||||
@@ -62,6 +98,101 @@ func absInt64(v int64) int64 {
|
||||
return v
|
||||
}
|
||||
|
||||
const (
|
||||
downlinkModePure byte = 0x01
|
||||
downlinkModePacked byte = 0x02
|
||||
)
|
||||
|
||||
func downlinkMode(cfg *apis.ProtocolConfig) byte {
|
||||
if cfg.EnablePureDownlink {
|
||||
return downlinkModePure
|
||||
}
|
||||
return downlinkModePacked
|
||||
}
|
||||
|
||||
func buildClientObfsConn(raw net.Conn, cfg *apis.ProtocolConfig) net.Conn {
|
||||
base := sudoku.NewConn(raw, cfg.Table, cfg.PaddingMin, cfg.PaddingMax, false)
|
||||
if cfg.EnablePureDownlink {
|
||||
return base
|
||||
}
|
||||
packed := sudoku.NewPackedConn(raw, cfg.Table, cfg.PaddingMin, cfg.PaddingMax)
|
||||
return &directionalConn{
|
||||
Conn: raw,
|
||||
reader: packed,
|
||||
writer: base,
|
||||
}
|
||||
}
|
||||
|
||||
func buildServerObfsConn(raw net.Conn, cfg *apis.ProtocolConfig, record bool) (*sudoku.Conn, net.Conn) {
|
||||
uplink := sudoku.NewConn(raw, cfg.Table, cfg.PaddingMin, cfg.PaddingMax, record)
|
||||
if cfg.EnablePureDownlink {
|
||||
return uplink, uplink
|
||||
}
|
||||
packed := sudoku.NewPackedConn(raw, cfg.Table, cfg.PaddingMin, cfg.PaddingMax)
|
||||
return uplink, &directionalConn{
|
||||
Conn: raw,
|
||||
reader: uplink,
|
||||
writer: packed,
|
||||
closers: []func() error{packed.Flush},
|
||||
}
|
||||
}
|
||||
|
||||
func buildHandshakePayload(key string) [16]byte {
|
||||
var payload [16]byte
|
||||
binary.BigEndian.PutUint64(payload[:8], uint64(time.Now().Unix()))
|
||||
hash := sha256.Sum256([]byte(key))
|
||||
copy(payload[8:], hash[:8])
|
||||
return payload
|
||||
}
|
||||
|
||||
func NewTable(key string, tableType string) *sudoku.Table {
|
||||
start := time.Now()
|
||||
table := sudoku.NewTable(key, tableType)
|
||||
log.Infoln("[Sudoku] Tables initialized (%s) in %v", tableType, time.Since(start))
|
||||
return table
|
||||
}
|
||||
|
||||
func ClientAEADSeed(key string) string {
|
||||
if recovered, err := crypto.RecoverPublicKey(key); err == nil {
|
||||
return crypto.EncodePoint(recovered)
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// ClientHandshake performs the client-side Sudoku handshake (without sending target address).
|
||||
func ClientHandshake(rawConn net.Conn, cfg *apis.ProtocolConfig) (net.Conn, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("config is required")
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("invalid config: %w", err)
|
||||
}
|
||||
|
||||
if !cfg.DisableHTTPMask {
|
||||
if err := httpmask.WriteRandomRequestHeader(rawConn, cfg.ServerAddress); err != nil {
|
||||
return nil, fmt.Errorf("write http mask failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
obfsConn := buildClientObfsConn(rawConn, cfg)
|
||||
cConn, err := crypto.NewAEADConn(obfsConn, ClientAEADSeed(cfg.Key), cfg.AEADMethod)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("setup crypto failed: %w", err)
|
||||
}
|
||||
|
||||
handshake := buildHandshakePayload(cfg.Key)
|
||||
if _, err := cConn.Write(handshake[:]); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("send handshake failed: %w", err)
|
||||
}
|
||||
if _, err := cConn.Write([]byte{downlinkMode(cfg)}); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("send downlink mode failed: %w", err)
|
||||
}
|
||||
|
||||
return cConn, nil
|
||||
}
|
||||
|
||||
// ServerHandshake performs Sudoku server-side handshake and detects UoT preface.
|
||||
func ServerHandshake(rawConn net.Conn, cfg *apis.ProtocolConfig) (*ServerSession, error) {
|
||||
if cfg == nil {
|
||||
@@ -90,8 +221,8 @@ func ServerHandshake(rawConn net.Conn, cfg *apis.ProtocolConfig) (*ServerSession
|
||||
Conn: rawConn,
|
||||
r: bufReader,
|
||||
}
|
||||
sConn := sudoku.NewConn(bConn, cfg.Table, cfg.PaddingMin, cfg.PaddingMax, true)
|
||||
cConn, err := crypto.NewAEADConn(sConn, cfg.Key, cfg.AEADMethod)
|
||||
sConn, obfsConn := buildServerObfsConn(bConn, cfg, true)
|
||||
cConn, err := crypto.NewAEADConn(obfsConn, cfg.Key, cfg.AEADMethod)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("crypto setup failed: %w", err)
|
||||
}
|
||||
@@ -110,6 +241,16 @@ func ServerHandshake(rawConn net.Conn, cfg *apis.ProtocolConfig) (*ServerSession
|
||||
|
||||
sConn.StopRecording()
|
||||
|
||||
modeBuf := []byte{0}
|
||||
if _, err := io.ReadFull(cConn, modeBuf); err != nil {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("read downlink mode failed: %w", err)
|
||||
}
|
||||
if modeBuf[0] != downlinkMode(cfg) {
|
||||
cConn.Close()
|
||||
return nil, fmt.Errorf("downlink mode mismatch: client=%d server=%d", modeBuf[0], downlinkMode(cfg))
|
||||
}
|
||||
|
||||
firstByte := make([]byte, 1)
|
||||
if _, err := io.ReadFull(cConn, firstByte); err != nil {
|
||||
cConn.Close()
|
||||
@@ -145,3 +286,19 @@ func ServerHandshake(rawConn net.Conn, cfg *apis.ProtocolConfig) (*ServerSession
|
||||
Target: target,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func GenKeyPair() (privateKey, publicKey string, err error) {
|
||||
// Generate Master Key
|
||||
pair, err := crypto.GenerateMasterKey()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// Split the master private key to get Available Private Key
|
||||
availablePrivateKey, err := crypto.SplitPrivateKey(pair.Private)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
privateKey = availablePrivateKey // Available Private Key for client
|
||||
publicKey = crypto.EncodePoint(pair.Public) // Master Public Key for server
|
||||
return
|
||||
}
|
||||
|
||||
230
mihomo/transport/sudoku/handshake_test.go
Normal file
230
mihomo/transport/sudoku/handshake_test.go
Normal file
@@ -0,0 +1,230 @@
|
||||
package sudoku
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/saba-futai/sudoku/apis"
|
||||
sudokuobfs "github.com/saba-futai/sudoku/pkg/obfs/sudoku"
|
||||
)
|
||||
|
||||
func TestPackedConnRoundTrip_WithPadding(t *testing.T) {
|
||||
payload := []byte{0x3a, 0x1f, 0x71, 0x00, 0xff, 0x10, 0x22}
|
||||
tableTypes := []string{"prefer_ascii", "prefer_entropy"}
|
||||
|
||||
for _, tt := range tableTypes {
|
||||
t.Run(tt, func(t *testing.T) {
|
||||
serverConn, clientConn := net.Pipe()
|
||||
defer serverConn.Close()
|
||||
defer clientConn.Close()
|
||||
|
||||
table := sudokuobfs.NewTable("roundtrip-seed", tt)
|
||||
writer := sudokuobfs.NewPackedConn(serverConn, table, 30, 80)
|
||||
reader := sudokuobfs.NewPackedConn(clientConn, table, 30, 80)
|
||||
|
||||
writeErr := make(chan error, 1)
|
||||
go func() {
|
||||
if _, err := writer.Write(payload); err != nil {
|
||||
writeErr <- err
|
||||
return
|
||||
}
|
||||
if err := writer.Flush(); err != nil {
|
||||
writeErr <- err
|
||||
return
|
||||
}
|
||||
writeErr <- serverConn.Close()
|
||||
}()
|
||||
|
||||
done := make(chan struct{})
|
||||
var got []byte
|
||||
var readErr error
|
||||
go func() {
|
||||
got, readErr = io.ReadAll(reader)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("read timeout")
|
||||
}
|
||||
|
||||
if err := <-writeErr; err != nil && err != io.EOF {
|
||||
t.Fatalf("write side error: %v", err)
|
||||
}
|
||||
if readErr != nil && readErr != io.EOF {
|
||||
t.Fatalf("read side error: %v", readErr)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("payload mismatch, want %x got %x", payload, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newPackedConfig(table *sudokuobfs.Table) *apis.ProtocolConfig {
|
||||
cfg := apis.DefaultConfig()
|
||||
cfg.Key = "sudoku-test-key"
|
||||
cfg.Table = table
|
||||
cfg.PaddingMin = 10
|
||||
cfg.PaddingMax = 30
|
||||
cfg.EnablePureDownlink = false
|
||||
cfg.ServerAddress = "example.com:443"
|
||||
cfg.DisableHTTPMask = true
|
||||
return cfg
|
||||
}
|
||||
|
||||
func TestPackedDownlinkSoak(t *testing.T) {
|
||||
const sessions = 16
|
||||
|
||||
table := sudokuobfs.NewTable("soak-seed", "prefer_ascii")
|
||||
cfg := newPackedConfig(table)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, sessions*2)
|
||||
|
||||
for i := 0; i < sessions; i++ {
|
||||
wg.Add(2)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
runPackedTCPSession(id, cfg, errCh)
|
||||
}(i)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
runPackedUoTSession(id, cfg, errCh)
|
||||
}(i)
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("soak test timeout")
|
||||
}
|
||||
|
||||
close(errCh)
|
||||
for err := range errCh {
|
||||
t.Fatalf("soak error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func runPackedTCPSession(id int, cfg *apis.ProtocolConfig, errCh chan<- error) {
|
||||
serverConn, clientConn := net.Pipe()
|
||||
target := fmt.Sprintf("1.1.1.%d:80", (id%200)+1)
|
||||
payload := []byte{0x42, byte(id)}
|
||||
|
||||
// Server side
|
||||
go func() {
|
||||
session, err := ServerHandshake(serverConn, cfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server handshake tcp: %w", err)
|
||||
return
|
||||
}
|
||||
defer session.Conn.Close()
|
||||
|
||||
if session.Type != SessionTypeTCP {
|
||||
errCh <- fmt.Errorf("unexpected session type: %v", session.Type)
|
||||
return
|
||||
}
|
||||
if session.Target != target {
|
||||
errCh <- fmt.Errorf("target mismatch want %s got %s", target, session.Target)
|
||||
return
|
||||
}
|
||||
if _, err := session.Conn.Write(payload); err != nil {
|
||||
errCh <- fmt.Errorf("server write: %w", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
// Client side
|
||||
clientCfg := *cfg
|
||||
cConn, err := ClientHandshake(clientConn, &clientCfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client handshake tcp: %w", err)
|
||||
return
|
||||
}
|
||||
defer cConn.Close()
|
||||
|
||||
addrBuf, err := EncodeAddress(target)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("encode address: %w", err)
|
||||
return
|
||||
}
|
||||
if _, err := cConn.Write(addrBuf); err != nil {
|
||||
errCh <- fmt.Errorf("client send addr: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
buf := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(cConn, buf); err != nil {
|
||||
errCh <- fmt.Errorf("client read: %w", err)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(buf, payload) {
|
||||
errCh <- fmt.Errorf("payload mismatch want %x got %x", payload, buf)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func runPackedUoTSession(id int, cfg *apis.ProtocolConfig, errCh chan<- error) {
|
||||
serverConn, clientConn := net.Pipe()
|
||||
target := "8.8.8.8:53"
|
||||
payload := []byte{0xaa, byte(id)}
|
||||
|
||||
// Server side
|
||||
go func() {
|
||||
session, err := ServerHandshake(serverConn, cfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("server handshake uot: %w", err)
|
||||
return
|
||||
}
|
||||
defer session.Conn.Close()
|
||||
|
||||
if session.Type != SessionTypeUoT {
|
||||
errCh <- fmt.Errorf("unexpected session type: %v", session.Type)
|
||||
return
|
||||
}
|
||||
if err := WriteDatagram(session.Conn, target, payload); err != nil {
|
||||
errCh <- fmt.Errorf("server write datagram: %w", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
// Client side
|
||||
clientCfg := *cfg
|
||||
cConn, err := ClientHandshake(clientConn, &clientCfg)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client handshake uot: %w", err)
|
||||
return
|
||||
}
|
||||
defer cConn.Close()
|
||||
|
||||
if err := WritePreface(cConn); err != nil {
|
||||
errCh <- fmt.Errorf("client write preface: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
addr, data, err := ReadDatagram(cConn)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client read datagram: %w", err)
|
||||
return
|
||||
}
|
||||
if addr != target {
|
||||
errCh <- fmt.Errorf("uot target mismatch want %s got %s", target, addr)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(data, payload) {
|
||||
errCh <- fmt.Errorf("uot payload mismatch want %x got %x", payload, data)
|
||||
return
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user