Compare commits

..
8 Commits
Author SHA1 Message Date
Fangliding 75a9977537 format 2026-11-26 21:24:20 +08:00
Fangliding fcf0e2378a refine 2026-11-26 21:19:36 +08:00
Fangliding bd62d6ffcb Fix 2026-11-26 21:09:22 +08:00
Fangliding e04430d18f Refactor 2026-11-26 21:09:20 +08:00
Fangliding 2e9bac5648 simple clear 2026-11-26 21:09:18 +08:00
Fangliding 5d796c827a test 2026-11-26 21:09:16 +08:00
Roman RublevandFangliding ed6718a367 SS2022 inbound: Don't end a UDP session when its first source address expires
The relay session context was derived from the inbound connection of the
source address that created the session. After a client changes its source
address (NAT rebinding), the UDP worker of the old address is cleaned up after
~2 minutes of inactivity and cancels that context, which tears down the
dispatched outbound flow; the next packet then creates a brand-new session and
outbound flow (new local port on the server, reset replay window).

Sessions are routed by client session ID (SIP022 3.2.4), so detach the session
context from the originating connection's cancellation and let the session's
own inactivity timer govern its lifetime.
2026-11-26 21:09:14 +08:00
Roman RublevandFangliding 2ac088f627 SS2022 inbound: Fix data races and duplicate acceptance when decoding one UDP session concurrently
Packets of one client session can be processed by two inbound workers at
the same time (e.g. the client's old and new source address after a NAT
rebinding). The sliding window was checked and updated in two separate
critical sections, and clientBodyCipher and the session's User were read
without the lock, so the same packet ID could be accepted more than once
and go test -race reported data races.

Re-check the window and publish the cached body cipher in one critical
section after the packet is fully validated, and always initialize the
session's User under the lock.
2026-11-26 21:09:05 +08:00
112 changed files with 2289 additions and 5598 deletions
+4
View File
@@ -7,6 +7,7 @@ import (
"github.com/xtls/xray-core/app/proxyman"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/core"
@@ -183,6 +184,9 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound
Mark: streamSettings.SocketSettings.Mark,
})
}
if streamSettings != nil && (streamSettings.ProtocolName == "splithttp" || streamSettings.ProtocolName == "masque") {
ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
}
return NewAlwaysOnInboundHandler(ctx, tag, receiverSettings, proxySettings)
}
+3 -31
View File
@@ -48,8 +48,7 @@ type tcpWorker struct {
hub internet.Listener
ctx context.Context
cancel context.CancelFunc
ctx context.Context
}
func getTProxyType(s *internet.MemoryStreamConfig) internet.SocketConfig_TProxyMode {
@@ -133,11 +132,6 @@ func (w *tcpWorker) Proxy() proxy.Inbound {
}
func (w *tcpWorker) Start() error {
if w.ctx == nil {
w.ctx = context.Background()
}
w.ctx, w.cancel = context.WithCancel(w.ctx)
ctx := context.Background()
if v, ok := w.proxy.(*hysteria_proxy.Server); ok {
@@ -155,9 +149,6 @@ func (w *tcpWorker) Start() error {
}
func (w *tcpWorker) Close() error {
if w.cancel != nil {
w.cancel()
}
var errs []interface{}
if w.hub != nil {
if err := common.Close(w.hub); err != nil {
@@ -282,8 +273,7 @@ type udpWorker struct {
checker *task.Periodic
activeConn map[connID]*udpConn
ctx context.Context
cancel context.CancelFunc
ctx context.Context
}
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
@@ -417,11 +407,6 @@ func (w *udpWorker) clean() error {
}
func (w *udpWorker) Start() error {
if w.ctx == nil {
w.ctx = context.Background()
}
w.ctx, w.cancel = context.WithCancel(w.ctx)
w.activeConn = make(map[connID]*udpConn, 16)
ctx := context.Background()
h, err := udp.ListenUDP(ctx, w.address, w.port, w.stream, udp.HubCapacity(256))
@@ -443,10 +428,6 @@ func (w *udpWorker) Close() error {
w.Lock()
defer w.Unlock()
if w.cancel != nil {
w.cancel()
}
var errs []interface{}
if w.hub != nil {
@@ -491,8 +472,7 @@ type dsWorker struct {
hub internet.Listener
ctx context.Context
cancel context.CancelFunc
ctx context.Context
}
func (w *dsWorker) callback(conn stat.Connection) {
@@ -537,11 +517,6 @@ func (w *dsWorker) Port() net.Port {
}
func (w *dsWorker) Start() error {
if w.ctx == nil {
w.ctx = context.Background()
}
w.ctx, w.cancel = context.WithCancel(w.ctx)
ctx := context.Background()
hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn stat.Connection) {
go w.callback(conn)
@@ -554,9 +529,6 @@ func (w *dsWorker) Start() error {
}
func (w *dsWorker) Close() error {
if w.cancel != nil {
w.cancel()
}
var errs []interface{}
if w.hub != nil {
if err := common.Close(w.hub); err != nil {
+23 -3
View File
@@ -15,6 +15,8 @@ const (
var ErrBufferFull = errors.New("buffer is full")
var pool = bytespool.GetPool(Size)
// ownership represents the data owner of the buffer.
type ownership uint8
@@ -37,7 +39,16 @@ type Buffer struct {
// New creates a Buffer with 0 length and 8K capacity, managed.
func New() *Buffer {
return &Buffer{v: bytespool.Alloc(Size)}
buf := pool.Get().([]byte)
if cap(buf) >= Size {
buf = buf[:Size]
} else {
buf = make([]byte, Size)
}
return &Buffer{
v: buf,
}
}
// NewExisted creates a standard size Buffer with an existed bytearray, managed.
@@ -69,7 +80,16 @@ func FromBytes(b []byte) *Buffer {
// StackNew creates a new Buffer object on stack, managed.
// This method is for buffers that is released in the same function.
func StackNew() Buffer {
return Buffer{v: bytespool.Alloc(Size)}
buf := pool.Get().([]byte)
if cap(buf) >= Size {
buf = buf[:Size]
} else {
buf = make([]byte, Size)
}
return Buffer{
v: buf,
}
}
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
@@ -93,7 +113,7 @@ func (b *Buffer) Release() {
switch b.ownership {
case managed:
if cap(p) == Size {
bytespool.Free(p)
pool.Put(p)
}
case bytespools:
bytespool.Free(p)
+55 -67
View File
@@ -1,84 +1,72 @@
package bytespool
import (
"math/bits"
"sync"
)
import "sync"
const (
minShift = 10 // 1KB
maxShift = 16 // 64KB
numPools = maxShift - minShift + 1
minSize = 1 << minShift
maxSize = 1 << maxShift
)
// pools hold array pointers (*[N]byte) to avoid interface boxing allocations on Put.
var pools = [numPools]sync.Pool{
{New: func() any { return new([1 << 10]byte) }},
{New: func() any { return new([1 << 11]byte) }},
{New: func() any { return new([1 << 12]byte) }},
{New: func() any { return new([1 << 13]byte) }},
{New: func() any { return new([1 << 14]byte) }},
{New: func() any { return new([1 << 15]byte) }},
{New: func() any { return new([1 << 16]byte) }},
func createAllocFunc(size int32) func() interface{} {
return func() interface{} {
return make([]byte, size)
}
}
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024.
// The following parameters controls the size of buffer pools.
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
// Package buf is guaranteed to not use buffers larger than the largest pool.
// Other packets may use larger buffers.
const (
numPools = 4
sizeMulti = 4
)
var (
pool [numPools]sync.Pool
poolSize [numPools]int32
)
func init() {
size := int32(2048)
for i := 0; i < numPools; i++ {
pool[i] = sync.Pool{
New: createAllocFunc(size),
}
poolSize[i] = size
size *= sizeMulti
}
}
// GetPool returns a sync.Pool that generates bytes array with at least the given size.
// It may return nil if no such pool exists.
//
// xray:api:stable
func GetPool(size int32) *sync.Pool {
for idx, ps := range poolSize {
if size <= ps {
return &pool[idx]
}
}
return nil
}
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
//
// xray:api:stable
func Alloc(size int32) []byte {
if size > maxSize {
return make([]byte, size)
}
index := 0
if size > minSize {
index = bits.Len32(uint32(size-1)) - minShift
}
p := pools[index].Get()
switch index {
case 0:
return p.(*[1 << 10]byte)[:]
case 1:
return p.(*[1 << 11]byte)[:]
case 2:
return p.(*[1 << 12]byte)[:]
case 3:
return p.(*[1 << 13]byte)[:]
case 4:
return p.(*[1 << 14]byte)[:]
case 5:
return p.(*[1 << 15]byte)[:]
case 6:
return p.(*[1 << 16]byte)[:]
default:
panic("invalid pool index")
pool := GetPool(size)
if pool != nil {
return pool.Get().([]byte)
}
return make([]byte, size)
}
// Free puts a byte slice into the internal pool.
//
// xray:api:stable
func Free(b []byte) {
c := cap(b)
if c < minSize || c > maxSize {
return
}
index := bits.Len(uint(c)) - 1 - minShift
switch index {
case 0:
pools[0].Put((*[1 << 10]byte)(b[:1<<10]))
case 1:
pools[1].Put((*[1 << 11]byte)(b[:1<<11]))
case 2:
pools[2].Put((*[1 << 12]byte)(b[:1<<12]))
case 3:
pools[3].Put((*[1 << 13]byte)(b[:1<<13]))
case 4:
pools[4].Put((*[1 << 14]byte)(b[:1<<14]))
case 5:
pools[5].Put((*[1 << 15]byte)(b[:1<<15]))
case 6:
pools[6].Put((*[1 << 16]byte)(b[:1<<16]))
size := int32(cap(b))
b = b[0:cap(b)]
for i := numPools - 1; i >= 0; i-- {
if size >= poolSize[i] {
pool[i].Put(b)
return
}
}
}
-12
View File
@@ -23,15 +23,3 @@ func IDFromContext(ctx context.Context) ID {
}
return 0
}
// ContextWithParents returns a new context derived from the father
// but also cancels when the mother is done.
func ContextWithParents(father, mother context.Context) (context.Context, context.CancelFunc) {
child, cancel := context.WithCancel(father)
stop := context.AfterFunc(mother, cancel)
newCancel := func() {
stop()
cancel()
}
return child, newCancel
}
+12 -4
View File
@@ -191,10 +191,18 @@ func getConfig() string {
{
"protocol": "vless",
"settings": {
"address": "1.2.3.4",
"port": 1234,
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
"encryption": "none"
"vnext": [
{
"address": "1.2.3.4",
"port": 1234,
"users": [
{
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
"encryption": "none"
}
]
}
]
},
"tag": "XHTTP_IN",
"streamSettings": {
+1
View File
@@ -71,6 +71,7 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
}
common.CloseIfExists(t.checkTask)
t.checkTask = newCheckTask
t.Update()
common.Must(newCheckTask.Start())
}
+7 -3
View File
@@ -58,11 +58,15 @@ func (t *Periodic) Start() error {
return nil
}
t.running = true
t.timer = time.AfterFunc(t.Interval, func() {
t.checkedExecute()
})
t.access.Unlock()
if err := t.checkedExecute(); err != nil {
t.access.Lock()
t.running = false
t.access.Unlock()
return err
}
return nil
}
+6 -6
View File
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
common.Must(task.Start())
time.Sleep(time.Second * 5)
common.Must(task.Close())
if value != 2 {
t.Fatal("expected 2, but got ", value)
if value != 3 {
t.Fatal("expected 3, but got ", value)
}
time.Sleep(time.Second * 4)
if value != 2 {
t.Fatal("expected 2, but got ", value)
if value != 3 {
t.Fatal("expected 3, but got ", value)
}
common.Must(task.Start())
time.Sleep(time.Second * 3)
if value != 3 {
t.Fatal("Expected 3, but ", value)
if value != 5 {
t.Fatal("Expected 5, but ", value)
}
common.Must(task.Close())
}
+11 -3
View File
@@ -6,11 +6,19 @@ import (
// TypedSyncMap is a wrapper of sync.Map that provides type-safe for keys and values.
// No need to use type assertions every time, so you can have more time to enjoy other things like GochiUsa
// K is key type, V is value type
// It is recommended to use pointer types for V because sync.Map might return nil
// If sync.Map methods returned nil, it will return the zero value of the type V.
type TypedSyncMap[K, V any] struct {
syncMap sync.Map
syncMap *sync.Map
}
// NewTypedSyncMap creates a new TypedSyncMap
// K is key type, V is value type
// It is recommended to use pointer types for V because sync.Map might return nil
// If sync.Map methods really returned nil, it will return the zero value of the type V
func NewTypedSyncMap[K any, V any]() *TypedSyncMap[K, V] {
return &TypedSyncMap[K, V]{
syncMap: &sync.Map{},
}
}
// Clear deletes all the entries, resulting in an empty Map.
+2 -2
View File
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
go 1.27
require (
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
github.com/bufbuild/protocompile v0.14.1
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
github.com/golang/mock v1.7.0-rc.1
@@ -36,7 +36,7 @@ require (
google.golang.org/protobuf v1.36.12
h12.io/socks v1.0.3
layeh.com/gopher-luar v1.0.11
lukechampine.com/blake3 v1.5.3
lukechampine.com/blake3 v1.5.1
mvdan.cc/gofumpt v0.12.0
)
+4 -4
View File
@@ -1,5 +1,5 @@
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a h1:uCIlOCbXUtBkFk47HxIkQieCkV+zKv5VCDawLtj3Pkc=
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
@@ -168,7 +168,7 @@ h12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo=
h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck=
layeh.com/gopher-luar v1.0.11 h1:8zJudpKI6HWkoh9eyyNFaTM79PY6CAPcIr6X/KTiliw=
layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk=
lukechampine.com/blake3 v1.5.3 h1:q4Ru9Zisjt/knP3KQYuk63VDPnREbSOA6cuL6UwrDlI=
lukechampine.com/blake3 v1.5.3/go.mod h1:+mObCTICmKFFJzAZ+4qqw23+LrWOuO+Zfj3DQiNQFXs=
lukechampine.com/blake3 v1.5.1 h1:ITRyxe0LlLZcPUWOZ3Taz8mbug/ptn7jbbeeij5ZiPo=
lukechampine.com/blake3 v1.5.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
+62 -23
View File
@@ -1,6 +1,9 @@
package conf
import (
"encoding/json"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/http"
@@ -46,37 +49,73 @@ func (c *HTTPServerConfig) Build() (proto.Message, error) {
return config, nil
}
type HTTPRemoteConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type HTTPClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Username string `json:"user"`
Password string `json:"pass"`
Headers map[string]string `json:"headers"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Username string `json:"user"`
Password string `json:"pass"`
Servers []*HTTPRemoteConfig `json:"servers"`
Headers map[string]string `json:"headers"`
}
func (v *HTTPClientConfig) Build() (proto.Message, error) {
config := new(http.ClientConfig)
server := &protocol.ServerEndpoint{
Address: v.Address.Build(),
Port: uint32(v.Port),
}
if len(v.Username) > 0 {
account := &HTTPAccount{
Username: v.Username,
Password: v.Password,
if v.Address != nil {
v.Servers = []*HTTPRemoteConfig{
{
Address: v.Address,
Port: v.Port,
},
}
user := &protocol.User{
Level: v.Level,
Email: v.Email,
Account: serial.ToTypedMessage(account.Build()),
if len(v.Username) > 0 {
v.Servers[0].Users = []json.RawMessage{{}}
}
server.User = user
}
config.Server = server
if len(v.Servers) != 1 {
return nil, errors.New(`HTTP settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple HTTP outbounds and routing balancer instead`)
}
for _, serverConfig := range v.Servers {
if len(serverConfig.Users) > 1 {
return nil, errors.New(`HTTP servers: "users" should have one member at most. Multiple members in "users" should use multiple HTTP outbounds and routing balancer instead`)
}
server := &protocol.ServerEndpoint{
Address: serverConfig.Address.Build(),
Port: uint32(serverConfig.Port),
}
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if v.Address != nil {
user.Level = v.Level
user.Email = v.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("failed to parse HTTP user").Base(err)
}
}
account := new(HTTPAccount)
if v.Address != nil {
account.Username = v.Username
account.Password = v.Password
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("failed to parse HTTP account").Base(err)
}
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = user
break
}
config.Server = server
break
}
config.Header = make([]*http.Header, 0, 32)
for key, value := range v.Headers {
config.Header = append(config.Header, &http.Header{
+48 -22
View File
@@ -177,7 +177,7 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
return config, nil
}
type ShadowsocksClientConfig struct {
type ShadowsocksServerTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
@@ -186,43 +186,69 @@ type ShadowsocksClientConfig struct {
Password string `json:"password"`
}
type ShadowsocksClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Cipher string `json:"method"`
Password string `json:"password"`
Servers []*ShadowsocksServerTarget `json:"servers"`
}
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
errors.PrintNonRemovalDeprecatedFeatureWarning("Shadowsocks (with no Forward Secrecy, etc.)", "VLESS Encryption")
if v.Address == nil {
if v.Address != nil {
v.Servers = []*ShadowsocksServerTarget{
{
Address: v.Address,
Port: v.Port,
Level: v.Level,
Email: v.Email,
Cipher: v.Cipher,
Password: v.Password,
},
}
}
if len(v.Servers) != 1 {
return nil, errors.New(`Shadowsocks settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Shadowsocks outbounds and routing balancer instead`)
}
server := v.Servers[0]
if server.Address == nil {
return nil, errors.New("Shadowsocks server address is not set.")
}
if v.Port == 0 {
if server.Port == 0 {
return nil, errors.New("Invalid Shadowsocks port.")
}
if v.Password == "" {
if server.Password == "" {
return nil, errors.New("Shadowsocks password is not specified.")
}
if _, err := shadowsocks_2022.GetCipherMethod(v.Cipher); err == nil {
config := &shadowsocks_2022.ClientConfig{
Address: v.Address.Build(),
Port: uint32(v.Port),
Method: v.Cipher,
Key: v.Password,
}
if _, err := shadowsocks_2022.GetCipherMethod(server.Cipher); err == nil {
config := new(shadowsocks_2022.ClientConfig)
config.Address = server.Address.Build()
config.Port = uint32(server.Port)
config.Method = server.Cipher
config.Key = server.Password
return config, nil
}
config := new(shadowsocks.ClientConfig)
if cipherFromString(v.Cipher) == shadowsocks.CipherType_UNKNOWN {
return nil, errors.New("unknown cipher method: ", v.Cipher)
account := &shadowsocks.Account{
Password: server.Password,
}
account.CipherType = cipherFromString(server.Cipher)
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
return nil, errors.New("unknown cipher method: ", server.Cipher)
}
ss := &protocol.ServerEndpoint{
Address: v.Address.Build(),
Port: uint32(v.Port),
Address: server.Address.Build(),
Port: uint32(server.Port),
User: &protocol.User{
Level: uint32(v.Level),
Email: v.Email,
Account: serial.ToTypedMessage(&shadowsocks.Account{
Password: v.Password,
CipherType: cipherFromString(v.Cipher),
}),
Level: uint32(server.Level),
Email: server.Email,
Account: serial.ToTypedMessage(account),
},
}
config.Server = ss
+61 -22
View File
@@ -1,6 +1,9 @@
package conf
import (
"encoding/json"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/socks"
@@ -64,35 +67,71 @@ func (v *SocksServerConfig) Build() (proto.Message, error) {
return config, nil
}
type SocksRemoteConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type SocksClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Username string `json:"user"`
Password string `json:"pass"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Username string `json:"user"`
Password string `json:"pass"`
Servers []*SocksRemoteConfig `json:"servers"`
}
func (v *SocksClientConfig) Build() (proto.Message, error) {
config := new(socks.ClientConfig)
server := &protocol.ServerEndpoint{
Address: v.Address.Build(),
Port: uint32(v.Port),
}
if len(v.Username) > 0 {
account := &SocksAccount{
Username: v.Username,
Password: v.Password,
if v.Address != nil {
v.Servers = []*SocksRemoteConfig{
{
Address: v.Address,
Port: v.Port,
},
}
user := &protocol.User{
Level: v.Level,
Email: v.Email,
Account: serial.ToTypedMessage(account.Build()),
if len(v.Username) > 0 {
v.Servers[0].Users = []json.RawMessage{{}}
}
server.User = user
}
config.Server = server
if len(v.Servers) != 1 {
return nil, errors.New(`SOCKS settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple SOCKS outbounds and routing balancer instead`)
}
for _, serverConfig := range v.Servers {
if len(serverConfig.Users) > 1 {
return nil, errors.New(`SOCKS servers: "users" should have one member at most. Multiple members in "users" should use multiple SOCKS outbounds and routing balancer instead`)
}
server := &protocol.ServerEndpoint{
Address: serverConfig.Address.Build(),
Port: uint32(serverConfig.Port),
}
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if v.Address != nil {
user.Level = v.Level
user.Email = v.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("failed to parse Socks user").Base(err)
}
}
account := new(SocksAccount)
if v.Address != nil {
account.Username = v.Username
account.Password = v.Password
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("failed to parse socks account").Base(err)
}
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = user
break
}
config.Server = server
break
}
return config, nil
}
+29
View File
@@ -53,6 +53,35 @@ func TestSocksOutboundConfig(t *testing.T) {
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"servers": [{
"address": "127.0.0.1",
"port": 1234,
"users": [
{"user": "test user", "pass": "test pass", "email": "test@email.com"}
]
}]
}`,
Parser: loadJSON(creator),
Output: &socks.ClientConfig{
Server: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 1234,
User: &protocol.User{
Email: "test@email.com",
Account: serial.ToTypedMessage(&socks.Account{
Username: "test user",
Password: "test pass",
}),
},
},
},
},
{
Input: `{
"address": "127.0.0.1",
+1 -26
View File
@@ -975,17 +975,6 @@ type XMC struct {
// NoPadding disables padding. An explicit empty "paddings" array means the
// same; an absent one keeps the built-in preset.
NoPadding bool `json:"noPadding,omitempty"`
// Custom payload channels that carry the tunnel byte stream and the startup
// padding. Both ends must use the same pair; empty keeps the defaults
// (xmc:data / xmc:pad). Vanilla's "minecraft" namespace is rejected.
DataChannel string `json:"dataChannel,omitempty"`
PaddingChannel string `json:"paddingChannel,omitempty"`
// Minecraft network protocol number the client advertises, for example 777
// for 26.3. Zero detects it from the peer's status response (cached per
// destination) and falls back to the newest version the mask knows. Set it to
// skip detection or to pin a version; the server follows whatever the client
// names.
ProtocolVersion uint32 `json:"protocolVersion,omitempty"`
}
type XMCPaddingTurn struct {
@@ -1051,21 +1040,7 @@ func (c *XMC) Build() (proto.Message, error) {
if noPadding && len(c.Paddings) > 0 {
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
}
if err := xmc.ValidateProtocolVersion(c.ProtocolVersion); err != nil {
return nil, fmt.Errorf("minecraft protocolVersion: %w", err)
}
config := &xmc.Config{
Hostname: c.Hostname,
NoPadding: noPadding,
DataChannel: c.DataChannel,
PaddingChannel: c.PaddingChannel,
ProtocolVersion: c.ProtocolVersion,
}
dataChannel, paddingChannel, channelErr := config.ChannelIDs()
if channelErr != nil {
return nil, fmt.Errorf("minecraft channels: %w", channelErr)
}
config.DataChannel, config.PaddingChannel = dataChannel, paddingChannel
config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding}
for i, turn := range c.Paddings {
minimum, maximum, err := ParseRangeString(turn.Length)
if err != nil {
@@ -242,93 +242,3 @@ func TestXMCBuildDisablesPadding(t *testing.T) {
t.Fatalf("expected an exclusive padding error, got %v", err)
}
}
func xmcTestProfiles() []XMCProfile {
return []XMCProfile{{
Username: "TestUser",
UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value",
TexturesSignature: "textures-signature",
}}
}
func TestXMCBuildChannels(t *testing.T) {
built, err := (&XMC{
Password: "test-password",
Profiles: xmcTestProfiles(),
DataChannel: "myxmc:stream",
PaddingChannel: "myxmc:noise",
}).Build()
if err != nil {
t.Fatalf("build XMC config: %v", err)
}
config := built.(*xmc.Config)
if config.DataChannel != "myxmc:stream" || config.PaddingChannel != "myxmc:noise" {
t.Fatalf("channels = %q, %q", config.DataChannel, config.PaddingChannel)
}
}
func TestXMCBuildChannelDefaults(t *testing.T) {
built, err := (&XMC{Password: "test-password", Profiles: xmcTestProfiles()}).Build()
if err != nil {
t.Fatalf("build XMC config: %v", err)
}
config := built.(*xmc.Config)
if config.DataChannel != xmc.DefaultDataChannel || config.PaddingChannel != xmc.DefaultPaddingChannel {
t.Fatalf("default channels = %q, %q", config.DataChannel, config.PaddingChannel)
}
}
func TestXMCBuildRejectsChannels(t *testing.T) {
cases := map[string]struct {
data string
padding string
}{
"vanilla_namespace": {"minecraft:data", ""},
"no_colon": {"xmcdata", ""},
"empty_path": {"xmc:", ""},
"uppercase": {"Xmc:data", ""},
"same_channel": {"xmc:same", "xmc:same"},
"too_long": {strings.Repeat("a", 129) + ":b", ""},
}
for name, test := range cases {
_, err := (&XMC{
Password: "test-password",
Profiles: xmcTestProfiles(),
DataChannel: test.data,
PaddingChannel: test.padding,
}).Build()
if err == nil || !strings.Contains(err.Error(), "channel") {
t.Fatalf("%s: expected a channel error, got %v", name, err)
}
}
}
func TestXMCBuildProtocolVersion(t *testing.T) {
profile := XMCProfile{
Username: "TestUser",
UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value",
TexturesSignature: "textures-signature",
}
built, err := (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}}).Build()
if err != nil {
t.Fatalf("build default XMC config: %v", err)
}
if got := built.(*xmc.Config).ProtocolVersion; got != 0 {
t.Fatalf("default protocol version = %d, want 0 (newest)", got)
}
built, err = (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}, ProtocolVersion: 775}).Build()
if err != nil {
t.Fatalf("build XMC config with a protocol version: %v", err)
}
if got := built.(*xmc.Config).ProtocolVersion; got != 775 {
t.Fatalf("protocol version = %d, want 775", got)
}
if _, err = (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}, ProtocolVersion: 778}).Build(); err == nil || !strings.Contains(err.Error(), "unsupported protocol version 778") {
t.Fatalf("expected an unknown protocol version to be rejected, got %v", err)
}
}
+6 -3
View File
@@ -532,7 +532,7 @@ func TestXDriveOutboundConfig(t *testing.T) {
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
} {
if err := build(input); err != nil {
t.Errorf("%s: %v", input, err)
@@ -541,9 +541,12 @@ func TestXDriveOutboundConfig(t *testing.T) {
for _, c := range []struct{ input, err string }{
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"settings.multiplex.concurrency"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"xudpConcurrency": 8}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
{`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
+60 -21
View File
@@ -17,41 +17,76 @@ import (
"google.golang.org/protobuf/proto"
)
// TrojanClientConfig is configuration of trojan servers
type TrojanClientConfig struct {
// TrojanServerTarget is configuration of a single trojan server
type TrojanServerTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Password string `json:"password"`
Flow string `json:"flow"`
}
// TrojanClientConfig is configuration of trojan servers
type TrojanClientConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Password string `json:"password"`
Flow string `json:"flow"`
Servers []*TrojanServerTarget `json:"servers"`
}
// Build implements Buildable
func (c *TrojanClientConfig) Build() (proto.Message, error) {
errors.PrintNonRemovalDeprecatedFeatureWarning("Trojan (with no Flow, etc.)", "VLESS with Flow & Seed")
if c.Address != nil {
c.Servers = []*TrojanServerTarget{
{
Address: c.Address,
Port: c.Port,
Level: c.Level,
Email: c.Email,
Password: c.Password,
Flow: c.Flow,
},
}
}
if len(c.Servers) != 1 {
return nil, errors.New(`Trojan settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Trojan outbounds and routing balancer instead`)
}
config := &trojan.ClientConfig{}
if c.Address == nil {
return nil, errors.New("Trojan server address is not set.")
}
if c.Port == 0 {
return nil, errors.New("Invalid Trojan port.")
}
if c.Password == "" {
return nil, errors.New("Trojan password is not specified.")
}
for _, rec := range c.Servers {
if rec.Address == nil {
return nil, errors.New("Trojan server address is not set.")
}
if rec.Port == 0 {
return nil, errors.New("Invalid Trojan port.")
}
if rec.Password == "" {
return nil, errors.New("Trojan password is not specified.")
}
if rec.Flow != "" {
return nil, errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
}
config.Server = &protocol.ServerEndpoint{
Address: c.Address.Build(),
Port: uint32(c.Port),
User: &protocol.User{
Level: uint32(c.Level),
Email: c.Email,
Account: serial.ToTypedMessage(&trojan.Account{
Password: c.Password,
}),
},
config.Server = &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
User: &protocol.User{
Level: uint32(rec.Level),
Email: rec.Email,
Account: serial.ToTypedMessage(&trojan.Account{
Password: rec.Password,
}),
},
}
break
}
return config, nil
@@ -72,6 +107,7 @@ type TrojanUserConfig struct {
Password string `json:"password"`
Level byte `json:"level"`
Email string `json:"email"`
Flow string `json:"flow"`
}
// TrojanServerConfig is Inbound configuration
@@ -95,6 +131,9 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
processClient := func(idx int) error {
rawUser := c.Users[idx]
if rawUser.Flow != "" {
return errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
}
config.Users[idx] = &protocol.User{
Level: uint32(rawUser.Level),
-1
View File
@@ -159,7 +159,6 @@ func TestTunConfigGUID(t *testing.T) {
for _, guid := range []string{
"xray0",
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
"6ba7b8109-dad-11d1-80b4-00c04fd430c8", // the right length, a hyphen out of place
"6ba7b8109dad11d180b400c04fd430c8",
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
+134 -89
View File
@@ -256,19 +256,26 @@ func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
})
}
type VLessOutboundVnext struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type VLessOutboundConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Id string `json:"id"`
Flow string `json:"flow"`
Seed string `json:"seed"`
Encryption string `json:"encryption"`
Multiplex *MultiplexConfig `json:"multiplex"`
Reverse *VLessReverseConfig `json:"reverse"`
Testpre uint32 `json:"testpre"`
Testseed []uint32 `json:"testseed"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
Id string `json:"id"`
Flow string `json:"flow"`
Seed string `json:"seed"`
Encryption string `json:"encryption"`
Multiplex *MultiplexConfig `json:"multiplex"`
Reverse *VLessReverseConfig `json:"reverse"`
Testpre uint32 `json:"testpre"`
Testseed []uint32 `json:"testseed"`
Vnext []*VLessOutboundVnext `json:"vnext"`
}
// Build implements Buildable
@@ -279,92 +286,130 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
}
config := &outbound.Config{Multiplex: multiplex}
if c.Address == nil {
return nil, errors.New(`VLESS: "address" is not set`)
}
uid, err := uuid.ParseString(c.Id)
if err != nil {
return nil, err
}
switch c.Flow {
case "":
case vless.XRV, vless.XRV + "-udp443":
default:
return nil, errors.New(`VLESS users: "flow" doesn't support "` + c.Flow + `" in this version`)
}
spec := &protocol.ServerEndpoint{
Address: c.Address.Build(),
Port: uint32(c.Port),
}
user := &protocol.User{
Level: c.Level,
Email: c.Email,
}
account := &vless.Account{
Id: uid.String(),
Flow: c.Flow,
// Seed: c.Seed,
Encryption: c.Encryption,
Testpre: c.Testpre,
Testseed: c.Testseed,
}
if c.Reverse != nil {
rvs, err := c.Reverse.Build()
if err != nil {
return nil, err
if c.Address != nil {
c.Vnext = []*VLessOutboundVnext{
{
Address: c.Address,
Port: c.Port,
Users: []json.RawMessage{{}},
},
}
account.Reverse = rvs
}
if !func() bool {
s := strings.Split(account.Encryption, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return false
if len(c.Vnext) != 1 {
return nil, errors.New(`VLESS settings: "vnext" should have one and only one member. Multiple endpoints in "vnext" should use multiple VLESS outbounds and routing balancer instead`)
}
for _, rec := range c.Vnext {
if rec.Address == nil {
return nil, errors.New(`VLESS vnext: "address" is not set`)
}
switch s[1] {
case "native":
case "xorpub":
account.XorMode = 1
case "random":
account.XorMode = 2
default:
return false
if len(rec.Users) != 1 {
return nil, errors.New(`VLESS vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VLESS outbounds and routing balancer instead`)
}
switch s[2] {
case "1rtt":
case "0rtt":
account.Seconds = 1
default:
return false
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
}
padding := 0
for _, r := range s[3:] {
if len(r) < 20 {
padding += len(r) + 1
continue
for _, rawUser := range rec.Users {
user := new(protocol.User)
if c.Address != nil {
user.Level = c.Level
user.Email = c.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New(`VLESS users: invalid user`).Base(err)
}
}
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
return false
account := new(vless.Account)
if c.Address != nil {
account.Id = c.Id
account.Flow = c.Flow
//account.Seed = c.Seed
account.Encryption = c.Encryption
if c.Reverse != nil {
rvs, err := c.Reverse.Build()
if err != nil {
return nil, err
}
account.Reverse = rvs
}
account.Testpre = c.Testpre
account.Testseed = c.Testseed
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New(`VLESS users: invalid user`).Base(err)
}
// validateOutboundTransportSecurity needs to see these
c.Encryption = account.Encryption
c.Address = rec.Address
if account.Reverse != nil { // may not be reached: error json unmarshal
return nil, errors.New(`VLESS users: please use simplified outbound's config style to use "reverse"`)
}
}
u, err := uuid.ParseString(account.Id)
if err != nil {
return nil, err
}
account.Id = u.String()
switch account.Flow {
case "":
case vless.XRV, vless.XRV + "-udp443":
default:
return nil, errors.New(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
}
if !func() bool {
s := strings.Split(account.Encryption, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return false
}
switch s[1] {
case "native":
case "xorpub":
account.XorMode = 1
case "random":
account.XorMode = 2
default:
return false
}
switch s[2] {
case "1rtt":
case "0rtt":
account.Seconds = 1
default:
return false
}
padding := 0
for _, r := range s[3:] {
if len(r) < 20 {
padding += len(r) + 1
continue
}
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
return false
}
}
account.Encryption = account.Encryption[27+len(s[2]):]
if padding > 0 {
account.Padding = account.Encryption[:padding-1]
account.Encryption = account.Encryption[padding:]
}
return true
}() && account.Encryption != "none" {
if account.Encryption == "" {
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
}
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
}
user.Account = serial.ToTypedMessage(account)
spec.User = user
break
}
account.Encryption = account.Encryption[27+len(s[2]):]
if padding > 0 {
account.Padding = account.Encryption[:padding-1]
account.Encryption = account.Encryption[padding:]
}
return true
}() && account.Encryption != "none" {
if account.Encryption == "" {
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
}
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
config.Vnext = spec
break
}
user.Account = serial.ToTypedMessage(account)
spec.User = user
config.Vnext = spec
return config, nil
}
+35
View File
@@ -18,6 +18,41 @@ func TestVLessOutbound(t *testing.T) {
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"vnext": [{
"address": "example.com",
"port": 443,
"users": [
{
"id": "27848739-7e62-4138-9fd3-098a63964b6b",
"flow": "xtls-rprx-vision-udp443",
"encryption": "none",
"level": 0
}
]
}]
}`,
Parser: loadJSON(creator),
Output: &outbound.Config{
Vnext: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Domain{
Domain: "example.com",
},
},
Port: 443,
User: &protocol.User{
Account: serial.ToTypedMessage(&vless.Account{
Id: "27848739-7e62-4138-9fd3-098a63964b6b",
Flow: "xtls-rprx-vision-udp443",
Encryption: "none",
}),
Level: 0,
},
},
},
},
{
Input: `{
"address": "example.com",
+69 -30
View File
@@ -102,15 +102,22 @@ func (c *VMessInboundConfig) Build() (proto.Message, error) {
return config, nil
}
type VMessOutboundTarget struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"`
}
type VMessOutboundConfig struct {
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
ID string `json:"id"`
Security string `json:"security"`
Experiments string `json:"experiments"`
Multiplex *MultiplexConfig `json:"multiplex"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
ID string `json:"id"`
Security string `json:"security"`
Experiments string `json:"experiments"`
Receivers []*VMessOutboundTarget `json:"vnext"`
Multiplex *MultiplexConfig `json:"multiplex"`
}
// Build implements Buildable
@@ -122,30 +129,62 @@ func (c *VMessOutboundConfig) Build() (proto.Message, error) {
return nil, err
}
config := &outbound.Config{Multiplex: multiplex}
if c.Address != nil {
c.Receivers = []*VMessOutboundTarget{
{
Address: c.Address,
Port: c.Port,
Users: []json.RawMessage{{}},
},
}
}
if len(c.Receivers) != 1 {
return nil, errors.New(`VMess settings: "vnext" should have one and only one member. Multiple endpoints in "vnext" should use multiple VMess outbounds and routing balancer instead`)
}
for _, rec := range c.Receivers {
if len(rec.Users) != 1 {
return nil, errors.New(`VMess vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VMess outbounds and routing balancer instead`)
}
if rec.Address == nil {
return nil, errors.New(`VMess vnext: "address" is not set`)
}
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
Port: uint32(rec.Port),
}
for _, rawUser := range rec.Users {
user := new(protocol.User)
if c.Address != nil {
user.Level = c.Level
user.Email = c.Email
} else {
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, errors.New("invalid VMess user").Base(err)
}
}
account := new(VMessAccount)
if c.Address != nil {
account.ID = c.ID
account.Security = c.Security
account.Experiments = c.Experiments
} else {
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, errors.New("invalid VMess user").Base(err)
}
}
if c.Address == nil {
return nil, errors.New(`VMess: "address" is not set`)
}
uid, err := uuid.ParseString(c.ID)
if err != nil {
return nil, err
}
u, err := uuid.ParseString(account.ID)
if err != nil {
return nil, err
}
account.ID = u.String()
account := &VMessAccount{
ID: uid.String(),
Security: c.Security,
Experiments: c.Experiments,
user.Account = serial.ToTypedMessage(account.Build())
spec.User = user
break
}
config.Receiver = spec
break
}
spec := &protocol.ServerEndpoint{
Address: c.Address.Build(),
Port: uint32(c.Port),
User: &protocol.User{
Level: c.Level,
Email: c.Email,
Account: serial.ToTypedMessage(account.Build()),
},
}
config.Receiver = spec
return config, nil
}
+36
View File
@@ -18,6 +18,42 @@ func TestVMessOutbound(t *testing.T) {
}
runMultiTestCase(t, []TestCase{
{
Input: `{
"vnext": [{
"address": "127.0.0.1",
"port": 80,
"users": [
{
"id": "e641f5ad-9397-41e3-bf1a-e8740dfed019",
"email": "love@example.com",
"level": 255
}
]
}]
}`,
Parser: loadJSON(creator),
Output: &outbound.Config{
Receiver: &protocol.ServerEndpoint{
Address: &net.IPOrDomain{
Address: &net.IPOrDomain_Ip{
Ip: []byte{127, 0, 0, 1},
},
},
Port: 80,
User: &protocol.User{
Email: "love@example.com",
Level: 255,
Account: serial.ToTypedMessage(&vmess.Account{
Id: "e641f5ad-9397-41e3-bf1a-e8740dfed019",
SecuritySettings: &protocol.SecurityConfig{
Type: protocol.SecurityType_AUTO,
},
}),
},
},
},
},
{
Input: `{
"address": "127.0.0.1",
+4 -14
View File
@@ -238,7 +238,7 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
}
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
if requiresTransportSecurity(tjCfg.Address) {
if requiresTransportSecurity(tjCfg.Servers[0].Address) {
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
}
}
@@ -265,13 +265,8 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortLis
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
}
// Reverse opens its own multiplexed connection.
if account.Reverse == nil {
if c.Multiplex == nil {
c.Multiplex = &vless.Multiplex{Concurrency: 128}
}
if c.Multiplex.XudpProxyUDP443 == "skip" {
return errors.New(`the xdrive transport does not support "xudpProxyUDP443":"skip"`)
}
if account.Reverse == nil && (c.Multiplex.GetConcurrency() == 0 || c.Multiplex.GetXudpProxyUDP443() == "skip") {
return errors.New(`the xdrive transport needs positive "settings.multiplex.concurrency" and does not support "xudpProxyUDP443":"skip"`)
}
if account.Testpre != 0 {
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
@@ -372,15 +367,10 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
if err != nil {
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
}
if senderSettings.StreamSettings != nil && senderSettings.StreamSettings.ProtocolName == "splithttp" {
if v, ok := ts.(*outbound.Config); ok && v.Multiplex != nil && v.Multiplex.Concurrency != 0 {
errors.LogWarning(context.Background(), `ATTENTION: Using VLESS Multiplex over XHTTP XMUX`)
}
}
if err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
return nil, err
}
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
return nil, err
}
-24
View File
@@ -1,24 +0,0 @@
package proxy
import (
"context"
"math/rand/v2"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/signal"
)
// wait to drain all the possible incoming UDP data
// because re-established QUIC UDP may bypass the sniffer
func DropUDP(ctx context.Context, reader buf.Reader) {
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, func() {
cancel()
}, time.Duration(30+rand.N(60))*time.Second)
context.AfterFunc(ctx, func() {
common.Interrupt(reader)
})
buf.Copy(reader, buf.Discard, buf.UpdateActivity(timer))
}
+1 -1
View File
@@ -606,7 +606,7 @@ func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverri
if c, ok := iConn.(*net.PacketConnWrapper); ok {
// If DialDest is a domain, it will be resolved in dialer
// check this behavior and add it to map
resolvedUDPAddr := &utils.TypedSyncMap[string, net.Address]{}
resolvedUDPAddr := utils.NewTypedSyncMap[string, net.Address]()
if DialDest.Address.Family().IsDomain() {
resolvedUDPAddr.Store(DialDest.Address.Domain(), net.DestinationFromAddr(conn.RemoteAddr()).Address)
}
+17 -29
View File
@@ -1,12 +1,10 @@
package account
import (
"context"
"sync"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/utils"
"github.com/google/uuid"
"google.golang.org/protobuf/proto"
@@ -26,9 +24,6 @@ func (a *Account) AsAccount() (protocol.Account, error) {
type MemoryAccount struct {
Auth string
VR net.Port
Ctx context.Context
Cancel context.CancelFunc
}
func (a *MemoryAccount) Equals(other protocol.Account) bool {
@@ -45,8 +40,8 @@ func (a *MemoryAccount) ToProto() proto.Message {
}
type Validator struct {
users utils.TypedSyncMap[string, *protocol.MemoryUser]
ids utils.TypedSyncMap[uuid.UUID, *protocol.MemoryUser]
users sync.Map
ids sync.Map
mu sync.Mutex
}
@@ -56,10 +51,8 @@ func NewValidator() *Validator {
func (v *Validator) Add(user *protocol.MemoryUser) (err error) {
v.mu.Lock()
a := user.Account.(*MemoryAccount)
a.Ctx, a.Cancel = context.WithCancel(context.Background())
v.users.Store(a.Auth, user)
if id, err := uuid.Parse(a.Auth); err == nil {
v.users.Store(user.Account.(*MemoryAccount).Auth, user)
if id, err := uuid.Parse(user.Account.(*MemoryAccount).Auth); err == nil {
id[6] = 0
id[7] = 0
v.ids.Store(id, user)
@@ -71,15 +64,13 @@ func (v *Validator) Add(user *protocol.MemoryUser) (err error) {
func (v *Validator) DelByEmail(email string) (err error) {
v.mu.Lock()
if user := v.GetByEmail(email); user != nil {
a := user.Account.(*MemoryAccount)
auth := a.Auth
auth := user.Account.(*MemoryAccount).Auth
v.users.Delete(auth)
if id, err := uuid.Parse(auth); err == nil {
id[6] = 0
id[7] = 0
v.ids.Delete(id)
}
a.Cancel()
}
v.mu.Unlock()
return
@@ -89,16 +80,13 @@ func (v *Validator) Get(auth string) (user *protocol.MemoryUser) {
if id, err := uuid.Parse(auth); err == nil {
if user = v.GetByID(id); user != nil {
VR := net.PortFromBytes(id[6:8])
orig := user.Account.(*MemoryAccount)
if orig.VR != VR {
if user.Account.(*MemoryAccount).VR != VR {
user = &protocol.MemoryUser{
Email: user.Email,
Level: user.Level,
Account: &MemoryAccount{
Auth: auth,
VR: VR,
Ctx: orig.Ctx,
Cancel: orig.Cancel,
Auth: auth,
VR: VR,
},
}
}
@@ -106,7 +94,7 @@ func (v *Validator) Get(auth string) (user *protocol.MemoryUser) {
return
}
if value, ok := v.users.Load(auth); ok {
user = value
user = value.(*protocol.MemoryUser)
}
return
}
@@ -115,15 +103,15 @@ func (v *Validator) GetByID(id uuid.UUID) (user *protocol.MemoryUser) {
id[6] = 0
id[7] = 0
if value, ok := v.ids.Load(id); ok {
user = value
user = value.(*protocol.MemoryUser)
}
return
}
func (v *Validator) GetByEmail(email string) (user *protocol.MemoryUser) {
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
if value.Email == email {
user = value
v.users.Range(func(key, value any) bool {
if value.(*protocol.MemoryUser).Email == email {
user = value.(*protocol.MemoryUser)
return false
}
return true
@@ -132,15 +120,15 @@ func (v *Validator) GetByEmail(email string) (user *protocol.MemoryUser) {
}
func (v *Validator) GetAll() (users []*protocol.MemoryUser) {
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
users = append(users, value)
v.users.Range(func(key, value any) bool {
users = append(users, value.(*protocol.MemoryUser))
return true
})
return
}
func (v *Validator) GetCount() (count int64) {
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
v.users.Range(func(key, value any) bool {
count++
return true
})
@@ -148,7 +136,7 @@ func (v *Validator) GetCount() (count int64) {
}
func (v *Validator) NotEmpty() (not_empty bool) {
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
v.users.Range(func(key, value any) bool {
not_empty = true
return false
})
+14 -39
View File
@@ -5,7 +5,6 @@ import (
go_errors "errors"
"io"
"math/rand"
"slices"
"github.com/apernet/quic-go"
"github.com/xtls/xray-core/common"
@@ -175,15 +174,10 @@ func init() {
}))
}
// UDPWriter is not safe for concurrent writes.
type UDPWriter struct {
writer io.Writer
addr string
buf [buf.Size]byte
// Last b.UDP and its NetAddr, which allocates on every call.
lastUDP net.Destination
lastUDPAddr string
}
func (w *UDPWriter) SendMessage(msg *UDPMessage) error {
@@ -199,21 +193,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
for i, b := range mb {
addr := w.addr
if b.UDP != nil {
if *b.UDP != w.lastUDP {
w.lastUDP = *b.UDP
w.lastUDPAddr = b.UDP.NetAddr()
}
addr = w.lastUDPAddr
addr = b.UDP.NetAddr()
}
msg := &UDPMessage{
SessionID: 0,
PacketID: 0,
FragID: 0,
FragCount: 1,
Addr: addr,
Data: b.Bytes(),
}
err := w.SendMessage(msg)
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
var errTooLarge *quic.DatagramTooLargeError
if go_errors.As(err, &errTooLarge) {
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
for _, fMsg := range fMsgs {
@@ -234,59 +228,40 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
return nil
}
// UDPReader is not safe for concurrent reads.
type UDPReader struct {
reader io.Reader
df *Defragger
firstBuf *buf.Buffer
// Last message address and its parsed destination.
lastAddr string
lastDest net.Destination
packet [1500]byte
msg UDPMessage
}
func (r *UDPReader) ReadFrom(p []byte) (n int, addr *net.Destination, err error) {
for {
n, err := r.reader.Read(r.packet[:])
var packet [1500]byte
n, err := r.reader.Read(packet[:])
if err != nil {
return 0, nil, err
}
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); err != nil {
msg, err := ParseUDPMessage(packet[:n])
if err != nil {
continue
}
msg := &r.msg
if msg.FragCount > 1 {
// The defragger keeps fragments between calls, so they must not alias packet.
frag := *msg
frag.Data = slices.Clone(msg.Data)
msg = &frag
}
dfMsg := r.df.Feed(msg)
if dfMsg == nil {
continue
}
if dfMsg.Addr != r.lastAddr {
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
if err != nil {
continue
}
r.lastAddr = dfMsg.Addr
r.lastDest = dest
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
if err != nil {
continue
}
if len(p) < len(dfMsg.Data) {
continue
}
// Callers can rewrite the packet destination in place.
dest := r.lastDest
return copy(p, dfMsg.Data), &dest, nil
}
}
-147
View File
@@ -1,147 +0,0 @@
package hysteria
import (
"bytes"
"io"
"testing"
"github.com/apernet/quic-go"
"github.com/xtls/xray-core/common/buf"
xnet "github.com/xtls/xray-core/common/net"
)
// datagramReader returns one datagram per Read, like a QUIC datagram stream.
type datagramReader struct {
msgs [][]byte
}
func (r *datagramReader) Read(p []byte) (int, error) {
if len(r.msgs) == 0 {
return 0, io.EOF
}
n := copy(p, r.msgs[0])
r.msgs = r.msgs[1:]
return n, nil
}
func newTestReader(msgs []UDPMessage) *UDPReader {
datagrams := make([][]byte, len(msgs))
for i := range msgs {
datagrams[i] = make([]byte, msgs[i].Size())
msgs[i].Serialize(datagrams[i])
}
return &UDPReader{reader: &datagramReader{msgs: datagrams}, df: &Defragger{}}
}
func TestUDPReaderFragments(t *testing.T) {
want := &UDPMessage{PacketID: 1, Addr: "example.com:443", Data: bytes.Repeat([]byte("0123456789"), 20)}
frags := FragUDPMessage(want, 100)
if len(frags) < 2 {
t.Fatalf("got %d fragments, want at least 2", len(frags))
}
p := make([]byte, buf.Size)
n, dest, err := newTestReader(frags).ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, want.Data, want.Addr)
}
}
func TestUDPReaderDestinations(t *testing.T) {
msgs := []UDPMessage{
{Addr: "203.0.113.1:53", Data: []byte("first")},
{Addr: "203.0.113.1:53", Data: []byte("second")},
{Addr: "203.0.113.2:53", Data: []byte("third")},
}
r := newTestReader(msgs)
p := make([]byte, buf.Size)
for i, want := range msgs {
n, dest, err := r.ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
t.Errorf("packet %d: got %q to %v, want %q to %s", i, p[:n], dest, want.Data, want.Addr)
}
// Callers rewrite the destination in place, the next packet must not see it.
dest.Port = 5353
}
}
type captureWriter struct {
writes [][]byte
}
func (w *captureWriter) Write(p []byte) (int, error) {
w.writes = append(w.writes, bytes.Clone(p))
return len(p), nil
}
func TestUDPWriterAddress(t *testing.T) {
ip := xnet.UDPDestination(xnet.ParseAddress("203.0.113.1"), 53)
domain := xnet.UDPDestination(xnet.DomainAddress("example.com"), 53)
cw := &captureWriter{}
w := &UDPWriter{writer: cw, addr: "198.51.100.1:1"}
for _, tc := range []struct {
udp *xnet.Destination
want string
}{
{&ip, "203.0.113.1:53"},
{&domain, "example.com:53"},
{nil, "198.51.100.1:1"},
{&ip, "203.0.113.1:53"},
} {
b := buf.FromBytes([]byte("data"))
b.UDP = tc.udp
if err := w.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
t.Fatal(err)
}
msg, err := ParseUDPMessage(cw.writes[len(cw.writes)-1])
if err != nil {
t.Fatal(err)
}
if msg.Addr != tc.want {
t.Errorf("address = %q, want %q", msg.Addr, tc.want)
}
}
}
// fragmentingWriter rejects datagrams larger than max, like a QUIC connection.
type fragmentingWriter struct {
max int
writes [][]byte
}
func (w *fragmentingWriter) Write(p []byte) (int, error) {
if len(p) > w.max {
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(w.max)}
}
w.writes = append(w.writes, bytes.Clone(p))
return len(p), nil
}
func TestUDPWriterFragmentation(t *testing.T) {
data := bytes.Repeat([]byte("0123456789"), 20)
fw := &fragmentingWriter{max: 100}
w := &UDPWriter{writer: fw, addr: "example.com:443"}
if err := w.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(data)}); err != nil {
t.Fatal(err)
}
if len(fw.writes) < 2 {
t.Fatalf("got %d datagrams, want at least 2", len(fw.writes))
}
r := &UDPReader{reader: &datagramReader{msgs: fw.writes}, df: &Defragger{}}
p := make([]byte, buf.Size)
n, dest, err := r.ReadFrom(p)
if err != nil {
t.Fatal(err)
}
if dest.NetAddr() != w.addr || !bytes.Equal(p[:n], data) {
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, data, w.addr)
}
}
+20 -28
View File
@@ -1,6 +1,7 @@
package hysteria
import (
"bytes"
"encoding/binary"
"fmt"
"io"
@@ -182,44 +183,35 @@ func (m *UDPMessage) Serialize(buf []byte) int {
}
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
m := new(UDPMessage)
if err := parseUDPMessage(msg, "", m); err != nil {
m := &UDPMessage{}
buf := bytes.NewBuffer(msg)
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
return nil, err
}
return m, nil
}
// parseUDPMessage parses msg into m. m.Data aliases msg; m.Addr is lastAddr
// when they are equal, so an unchanged address is not allocated again.
func parseUDPMessage(msg []byte, lastAddr string, m *UDPMessage) error {
if len(msg) < 8 {
return io.ErrUnexpectedEOF
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); err != nil {
return nil, err
}
lAddr, n, err := quicvarint.Parse(msg[8:])
if err := binary.Read(buf, binary.BigEndian, &m.FragID); err != nil {
return nil, err
}
if err := binary.Read(buf, binary.BigEndian, &m.FragCount); err != nil {
return nil, err
}
lAddr, err := quicvarint.Read(buf)
if err != nil {
return err
return nil, err
}
if lAddr == 0 || lAddr > MaxMessageLength {
return errors.New("invalid address length")
return nil, errors.New("invalid address length")
}
bs := msg[8+n:]
bs := buf.Bytes()
if len(bs) <= int(lAddr) {
// We use <= instead of < here as we expect at least one byte of data after the address
return errors.New("invalid message length")
return nil, errors.New("invalid message length")
}
*m = UDPMessage{
SessionID: binary.BigEndian.Uint32(msg),
PacketID: binary.BigEndian.Uint16(msg[4:]),
FragID: msg[6],
FragCount: msg[7],
Data: bs[lAddr:],
}
if string(bs[:lAddr]) == lastAddr {
m.Addr = lastAddr
} else {
m.Addr = string(bs[:lAddr])
}
return nil
m.Addr = string(bs[:lAddr])
m.Data = bs[lAddr:]
return m, nil
}
// varintPut is like quicvarint.Append, but instead of appending to a slice,
-49
View File
@@ -1,49 +0,0 @@
package hysteria
import (
"bytes"
"reflect"
"testing"
)
func TestParseUDPMessage(t *testing.T) {
want := &UDPMessage{PacketID: 1, FragID: 2, FragCount: 3, Addr: "example.com:443", Data: []byte("hello")}
msg := make([]byte, want.Size())
want.Serialize(msg)
for _, lastAddr := range []string{"", want.Addr, "other:1"} {
got := new(UDPMessage)
if err := parseUDPMessage(msg, lastAddr, got); err != nil {
t.Fatalf("lastAddr %q: %v", lastAddr, err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("lastAddr %q: got %+v, want %+v", lastAddr, got, want)
}
}
}
func TestParseUDPMessageInvalid(t *testing.T) {
msg := &UDPMessage{Addr: "example.com:443", Data: []byte("hello")}
buf := make([]byte, msg.Size())
msg.Serialize(buf)
zeroAddrLen := bytes.Clone(buf)
zeroAddrLen[8] = 0 // Address length varint follows the 8-byte header
noData := &UDPMessage{Addr: msg.Addr}
noDataBuf := make([]byte, noData.Size())
noData.Serialize(noDataBuf)
for _, tc := range []struct {
name string
msg []byte
}{
{"short header", buf[:7]},
{"zero address length", zeroAddrLen},
{"no data after address", noDataBuf},
} {
if _, err := ParseUDPMessage(tc.msg); err == nil {
t.Errorf("%s: expected error", tc.name)
}
}
}
+1 -6
View File
@@ -6,7 +6,6 @@ import (
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
c "github.com/xtls/xray-core/common/ctx"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
@@ -96,11 +95,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con
user := v.User()
if user != nil {
inbound.User = user
a := user.Account.(*account.MemoryAccount)
inbound.VlessRoute = a.VR
var cancel context.CancelFunc
ctx, cancel = c.ContextWithParents(ctx, a.Ctx)
defer cancel()
inbound.VlessRoute = user.Account.(*account.MemoryAccount).VR
}
}
-6
View File
@@ -1,7 +1,6 @@
package masque
import (
"context"
"crypto/subtle"
"strings"
"sync"
@@ -17,9 +16,6 @@ func (a *Account) AsAccount() (protocol.Account, error) {
type MemoryAccount struct {
Password string
Ctx context.Context
Cancel context.CancelFunc
}
func (a *MemoryAccount) Equals(other protocol.Account) bool {
@@ -57,7 +53,6 @@ func (v *validator) add(user *protocol.MemoryUser) error {
if _, found := v.users[email]; found {
return errors.New("user ", user.Email, " already exists")
}
account.Ctx, account.Cancel = context.WithCancel(context.Background())
v.users[email] = user
return nil
}
@@ -71,7 +66,6 @@ func (v *validator) delByEmail(email string) (*protocol.MemoryUser, error) {
return nil, errors.New("user ", email, " not found")
}
delete(v.users, key)
user.Account.(*MemoryAccount).Cancel()
return user, nil
}
+1 -1
View File
@@ -511,7 +511,7 @@ func (s *Server) HandleConnection(conn net.Conn, dest net.Destination) {
}
defer t.untrack(conn)
ctx, cancel := c.ContextWithParents(s.ctx, t.user.Account.(*MemoryAccount).Ctx)
ctx, cancel := context.WithCancel(s.ctx)
defer cancel()
ctx = c.ContextWithID(ctx, session.NewID())
inbound := session.Inbound{
+1 -3
View File
@@ -369,12 +369,10 @@ func (d *closingDispatcher) DispatchLink(_ context.Context, _ net.Destination, l
func TestServerKeepsConnectionOpenWhenWriterCloses(t *testing.T) {
conn := &stackConn{}
dispatcher := &closingDispatcher{conn: conn}
userCtx, userCancel := context.WithCancel(context.Background())
defer userCancel()
s := &Server{
ctx: context.Background(),
dispatcher: dispatcher,
tunnels: map[netip.Addr]*serverTunnel{netip.MustParseAddr("10.13.0.2"): newServerTunnel(nil, &protocol.MemoryUser{Account: &MemoryAccount{Ctx: userCtx, Cancel: userCancel}})},
tunnels: map[netip.Addr]*serverTunnel{netip.MustParseAddr("10.13.0.2"): newServerTunnel(nil, &protocol.MemoryUser{})},
}
s.HandleConnection(conn, net.TCPDestination(net.ParseAddress("192.0.2.1"), 443))
-4
View File
@@ -2,7 +2,6 @@ package shadowsocks
import (
"bytes"
"context"
"crypto/cipher"
"crypto/md5"
"crypto/sha1"
@@ -25,9 +24,6 @@ type MemoryAccount struct {
CipherType CipherType
Key []byte
Password string
Ctx context.Context
Cancel context.CancelFunc
}
var ErrIVNotUnique = errors.New("IV is not unique")
-12
View File
@@ -6,7 +6,6 @@ import (
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
c "github.com/xtls/xray-core/common/ctx"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
@@ -131,12 +130,6 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
inbound := session.InboundFromContext(ctx)
var dest *net.Destination
var userCancel context.CancelFunc
defer func() {
if userCancel != nil {
userCancel()
}
}()
reader := buf.NewPacketReader(conn)
for {
mpayload, err := reader.ReadMultiBuffer()
@@ -157,7 +150,6 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
request, data, err = DecodeUDPPacket(s.validator, payload)
if err == nil {
inbound.User = request.User
ctx, userCancel = c.ContextWithParents(ctx, request.User.Account.(*MemoryAccount).Ctx)
}
}
@@ -228,10 +220,6 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis
}
inbound.User = request.User
var userCancel context.CancelFunc
ctx, userCancel = c.ContextWithParents(ctx, request.User.Account.(*MemoryAccount).Ctx)
defer userCancel()
dest := request.Destination()
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: conn.RemoteAddr(),
-5
View File
@@ -1,7 +1,6 @@
package shadowsocks
import (
"context"
"crypto/cipher"
"crypto/hmac"
"crypto/sha256"
@@ -34,9 +33,6 @@ func (v *Validator) Add(u *protocol.MemoryUser) error {
if !account.Cipher.IsAEAD() && len(v.users) > 0 {
return errors.New("The cipher is not support Single-port Multi-user")
}
if account.Ctx == nil {
account.Ctx, account.Cancel = context.WithCancel(context.Background())
}
v.users = append(v.users, u)
if !v.behaviorFused {
@@ -62,7 +58,6 @@ func (v *Validator) Del(email string) error {
for i, u := range v.users {
if strings.EqualFold(u.Email, email) {
idx = i
u.Account.(*MemoryAccount).Cancel()
break
}
}
-4
View File
@@ -2,7 +2,6 @@ package shadowsocks_2022
import (
"bytes"
"context"
"encoding/base64"
"google.golang.org/protobuf/proto"
@@ -13,9 +12,6 @@ import (
// MemoryAccount is an account type converted from Account.
type MemoryAccount struct {
Key []byte
Ctx context.Context
Cancel context.CancelFunc
}
// AsAccount implements protocol.AsAccount.
+3 -12
View File
@@ -11,7 +11,6 @@ import (
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/antireplay"
"github.com/xtls/xray-core/common/buf"
c "github.com/xtls/xray-core/common/ctx"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
@@ -76,8 +75,8 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
networks: networks,
method: method,
masterPSK: masterPSK,
usersByHash: &utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]{},
usersByEmail: &utils.TypedSyncMap[string, *protocol.MemoryUser]{},
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
saltFilter: antireplay.NewMapFilter[[32]byte](60),
udpCodec: udpCodec,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
@@ -122,8 +121,6 @@ func (i *MultiUserInbound) AddUser(ctx context.Context, u *protocol.MemoryUser)
return ErrBadKey
}
memAcc.Ctx, memAcc.Cancel = context.WithCancel(context.Background())
pskHash := DeriveUserPSKHash(memAcc.Key)
i.usersByHash.Store(pskHash, u)
if emailKey != "" {
@@ -149,11 +146,9 @@ func (i *MultiUserInbound) RemoveUser(ctx context.Context, email string) error {
return errors.New("user ", email, " not found")
}
a := u.Account.(*MemoryAccount)
pskHash := DeriveUserPSKHash(a.Key)
pskHash := DeriveUserPSKHash(u.Account.(*MemoryAccount).Key)
i.usersByHash.Delete(pskHash)
i.userCount.Add(-1)
a.Cancel()
return nil
}
@@ -248,10 +243,6 @@ func (i *MultiUserInbound) processTCP(ctx context.Context, conn net.Conn, dispat
inbound := session.InboundFromContext(ctx)
inbound.User = user
var cancel context.CancelFunc
ctx, cancel = c.ContextWithParents(ctx, user.Account.(*MemoryAccount).Ctx)
defer cancel()
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: conn.RemoteAddr(),
To: dest,
+1 -1
View File
@@ -131,7 +131,7 @@ type UDPSessionManager struct {
func NewUDPSessionManager(timeout time.Duration) *UDPSessionManager {
return &UDPSessionManager{
sessions: &utils.TypedSyncMap[uint64, *ServerUDPSession]{},
sessions: utils.NewTypedSyncMap[uint64, *ServerUDPSession](),
timeout: timeout,
}
}
+1 -8
View File
@@ -5,7 +5,6 @@ import (
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
c "github.com/xtls/xray-core/common/ctx"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
@@ -66,13 +65,7 @@ func (s *ServerUDPSession) EnsureLink(
// UDP Session might travel across multiple connections
// don't bind its lifetime to a parent context
var sessCtx context.Context
var cancel context.CancelFunc
if s.User != nil && s.User.Account != nil {
sessCtx, cancel = c.ContextWithParents(context.WithoutCancel(ctx), s.User.Account.(*MemoryAccount).Ctx)
} else {
sessCtx, cancel = context.WithCancel(context.WithoutCancel(ctx))
}
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
inbound := session.InboundFromContext(sessCtx)
if inbound != nil {
newInbound := *inbound
-4
View File
@@ -1,7 +1,6 @@
package trojan
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
@@ -16,9 +15,6 @@ import (
type MemoryAccount struct {
Password string
Key []byte
Ctx context.Context
Cancel context.CancelFunc
}
// AsAccount implements protocol.AsAccount.
-5
View File
@@ -9,7 +9,6 @@ import (
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
c "github.com/xtls/xray-core/common/ctx"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
@@ -227,10 +226,6 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con
inbound.User = user
sessionPolicy = s.policyManager.ForLevel(user.Level)
var cancel context.CancelFunc
ctx, cancel = c.ContextWithParents(ctx, user.Account.(*MemoryAccount).Ctx)
defer cancel()
if destination.Network == net.Network_UDP { // handle udp request
return s.handleUDPPayload(ctx, sessionPolicy, &PacketReader{Reader: clientReader}, &PacketWriter{Writer: conn}, dispatcher)
}
+18 -16
View File
@@ -1,32 +1,29 @@
package trojan
import (
"context"
"strings"
"sync"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/utils"
)
// Validator stores valid trojan users.
type Validator struct {
// Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
email utils.TypedSyncMap[string, *protocol.MemoryUser]
users utils.TypedSyncMap[string, *protocol.MemoryUser]
email sync.Map
users sync.Map
}
// Add a trojan user, Email must be empty or unique.
func (v *Validator) Add(u *protocol.MemoryUser) error {
a := u.Account.(*MemoryAccount)
a.Ctx, a.Cancel = context.WithCancel(context.Background())
if u.Email != "" {
_, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
if loaded {
return errors.New("User ", u.Email, " already exists.")
}
}
v.users.Store(hexString(a.Key), u)
v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u)
return nil
}
@@ -41,29 +38,34 @@ func (v *Validator) Del(e string) error {
return errors.New("User ", e, " not found.")
}
v.email.Delete(le)
a := u.Account.(*MemoryAccount)
v.users.Delete(hexString(a.Key))
a.Cancel()
v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key))
return nil
}
// Get a trojan user with hashed key, nil if user doesn't exist.
func (v *Validator) Get(hash string) *protocol.MemoryUser {
u, _ := v.users.Load(hash)
return u
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
// Get a trojan user with hashed key, nil if user doesn't exist.
func (v *Validator) GetByEmail(email string) *protocol.MemoryUser {
u, _ := v.email.Load(strings.ToLower(email))
return u
email = strings.ToLower(email)
u, _ := v.email.Load(email)
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
// Get all users
func (v *Validator) GetAll() []*protocol.MemoryUser {
u := make([]*protocol.MemoryUser, 0, 100)
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
u = append(u, value)
v.email.Range(func(key, value interface{}) bool {
u = append(u, value.(*protocol.MemoryUser))
return true
})
return u
@@ -72,7 +74,7 @@ func (v *Validator) GetAll() []*protocol.MemoryUser {
// Get users count
func (v *Validator) GetCount() int64 {
var c int64 = 0
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
v.email.Range(func(key, value interface{}) bool {
c++
return true
})
-16
View File
@@ -5,7 +5,6 @@ import (
"net"
"sync"
"github.com/google/uuid"
"github.com/xtls/xray-core/common/errors"
)
@@ -50,18 +49,3 @@ func (updater *InterfaceUpdater) Update() {
updater.iface = got
errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index)
}
// ParseGUID parses a canonical textual GUID, as in
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
// The form is all that is accepted, not the other ones uuid.Parse takes,
// such as one without hyphens; the length check is what rules those out.
func ParseGUID(s string) ([16]byte, error) {
if len(s) != 36 {
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
}
id, err := uuid.Parse(s)
if err != nil {
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
}
return id, nil
}
+21
View File
@@ -0,0 +1,21 @@
package tun
import (
"github.com/google/uuid"
"github.com/xtls/xray-core/common/errors"
)
// ParseGUID parses a canonical textual GUID, as in
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
// The form is all that is accepted, not the other ones uuid.Parse takes,
// such as one without hyphens; the length check is what rules those out.
func ParseGUID(s string) ([16]byte, error) {
if len(s) != 36 {
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
}
id, err := uuid.Parse(s)
if err != nil {
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
}
return id, nil
}
+54
View File
@@ -0,0 +1,54 @@
package tun_test
import (
"testing"
"github.com/xtls/xray-core/proxy/tun"
)
func TestParseGUID(t *testing.T) {
for _, c := range []struct {
guid string
raw [16]byte
}{
{"00000000-0000-0000-0000-000000000000", [16]byte{}},
{"00010203-0405-0607-0809-0a0b0c0d0e0f", [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
{"6ba7b810-9dad-11d1-80b4-00c04fd430c8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
{"6BA7B810-9DAD-11D1-80B4-00C04FD430C8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
{"ffffffff-ffff-ffff-ffff-ffffffffffff", [16]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
} {
raw, err := tun.ParseGUID(c.guid)
if err != nil {
t.Errorf("ParseGUID(%q) failed: %v", c.guid, err)
continue
}
if raw != c.raw {
t.Errorf("ParseGUID(%q) = %x, want %x", c.guid, raw, c.raw)
}
}
}
func TestParseGUIDInvalid(t *testing.T) {
for _, guid := range []string{
"",
" ",
"xray0",
// right characters, wrong places of the hyphens
"6ba7b8109-dad-11d1-80b4-00c04fd430c8",
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
"6ba7b810-9dad-11d1-80b4-00c04fd430c88",
"6ba7b810-9dad-11d1-80b4_00c04fd430c8",
// not hexadecimal
"6ba7b81g-9dad-11d1-80b4-00c04fd430c8",
"6ba7b810-9dad-11d1-80b4-00c04fd430cg",
// forms other than the canonical one
"6ba7b8109dad11d180b400c04fd430c8",
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"6ba7b810-9dad-11d1-80b4-00c04fd430c8 ",
} {
if raw, err := tun.ParseGUID(guid); err == nil {
t.Errorf("ParseGUID(%q) = %x, want an error", guid, raw)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//go:build windows
package tun
import (
"crypto/md5"
"testing"
"unsafe"
"golang.org/x/sys/windows"
)
func TestAdapterGUID(t *testing.T) {
// a configured GUID has to be the adapter GUID the text names: the groups
// are field values, not the bytes of the text in order
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
if err != nil {
t.Fatal(err)
}
want := windows.GUID{
Data1: 0x01020304,
Data2: 0x0506,
Data3: 0x0708,
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
}
if *guid != want {
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
}
// the same struct Windows builds from that text, and the text Windows shows
// for it
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
t.Fatal(err)
} else if *guid != fromText {
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
}
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
t.Errorf("adapterGUID = %s, want %s", got, want)
}
// without one, the bytes of the MD5 of the name, as they always were; that
// GUID is never read back as text, so its byte order does not matter
guid, err = adapterGUID("xray0", "")
if err != nil {
t.Fatal(err)
}
sum := md5.Sum([]byte("xray0"))
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
t.Errorf("adapterGUID = %x, want %x", got, sum)
}
if _, err := adapterGUID("xray0", "xray0"); err == nil {
t.Error("an invalid guid was accepted")
}
}
+390
View File
@@ -0,0 +1,390 @@
//go:build freebsd
package tun
import (
"context"
"errors"
"io/fs"
"net/netip"
"strings"
"testing"
)
type probeCall struct {
inboundTag string
source string
address string
}
// stubDNSRouting replaces the routing probe for the duration of a test and
// records how it was called, so tests can assert the probe is representative.
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
t.Helper()
original := verifyDNSRouting
calls := []probeCall{}
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
calls = append(calls, probeCall{inboundTag, source, address})
return err
}
t.Cleanup(func() { verifyDNSRouting = original })
return &calls
}
// recorder installs a resolvconf stub for the duration of a test and returns
// the captured invocations, each as the arguments followed by the stdin in
// angle brackets when there was one. An empty failOn succeeds every call;
// otherwise the named subcommand fails.
func recorder(t *testing.T, failOn string) *[]string {
t.Helper()
original := resolvconfRunner
calls := []string{}
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
call := strings.Join(args, " ")
if stdin != "" {
call += " <" + stdin + ">"
}
calls = append(calls, call)
if failOn != "" && len(args) > 0 && args[0] == failOn {
return nil, errors.New("boom")
}
return nil, nil
}
t.Cleanup(func() { resolvconfRunner = original })
return &calls
}
// files replaces the resolver files read by the applied check for the
// duration of a test. A path not in the map does not exist.
func files(t *testing.T, contents map[string]string) {
t.Helper()
original := readResolverFile
readResolverFile = func(path string) ([]byte, error) {
if data, ok := contents[path]; ok {
return []byte(data), nil
}
return nil, fs.ErrNotExist
}
t.Cleanup(func() { readResolverFile = original })
}
// takenOver is what the libc subscriber writes once the TUN's nameserver is
// the exclusive one.
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
// place.
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
func optedInTun() *FreeBSDTun {
return &FreeBSDTun{
options: &Config{
Name: "tun7",
Gateway: []string{"192.168.100.1/30"},
AutoSystemDnsToGateway: true,
},
name: "tun7",
gateway: netip.MustParsePrefix("192.168.100.1/30"),
local: netip.MustParseAddr("192.168.100.2"),
}
}
func joined(calls []string) string {
return strings.Join(calls, " | ")
}
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
probes := stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.options.AutoSystemDnsToGateway = false
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != 0 || len(*probes) != 0 {
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the option is off")
}
}
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
stubDNSRouting(t, errors.New("no route"))
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the probe fails")
}
if len(*calls) != 0 {
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the probe fails")
}
}
// On FreeBSD the addresses are the other way round from Linux: the local
// address is the one after the gateway, and the gateway itself has no owner,
// so a packet to it is routed into the TUN. The probe has to carry that pair,
// and the resolver has to be pointed at the gateway.
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
probes := stubDNSRouting(t, nil)
recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*probes) != 1 {
t.Fatalf("expected one probe, got %d", len(*probes))
}
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
if (*probes)[0] != want {
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
}
}
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !t1.systemDNSSet {
t.Fatal("systemDNSSet should be true after a successful takeover")
}
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
if got := joined(*calls); got != want {
t.Errorf("resolvconf calls = %q, want %q", got, want)
}
}
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
// the entry for the interface, but runs no subscriber, so success has to be
// confirmed in what the subscribers wrote.
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the nameserver did not reach a resolver")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not take")
}
if !strings.HasSuffix(joined(*calls), "-d tun7") {
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
}
}
func TestConfigureSystemDNSIdempotent(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
before := len(*calls)
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != before {
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
}
}
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-a")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when resolvconf -a fails")
}
if t1.systemDNSSet || t1.systemDNSDirty {
t.Error("a failed add leaves nothing to clean up")
}
if len(*calls) != 1 {
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
}
}
// If the removal after a failed check fails too, the entry may still be
// installed, so the state has to be remembered rather than silently dropped.
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
stubDNSRouting(t, nil)
recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the check fails")
}
if !t1.systemDNSDirty {
t.Error("a failed removal must leave the resolver marked dirty")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not complete")
}
}
// A dirty resolver is retried before anything new is applied.
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSDirty = true
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := joined(*calls)
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
t.Errorf("expected the stale removal first, got %q", got)
}
if t1.systemDNSDirty {
t.Error("a successful retry should clear the dirty flag")
}
if !t1.systemDNSSet {
t.Error("the takeover should proceed once the retry succeeds")
}
}
func TestUnsetSystemDNSRemoves(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("setup failed: %v", err)
}
*calls = nil
t1.unsetSystemDNS()
if t1.systemDNSSet {
t.Error("systemDNSSet should be false after unset")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
}
t1.unsetSystemDNS()
if len(*calls) != 1 {
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
}
}
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSSet = true
t1.unsetSystemDNS()
if !t1.systemDNSDirty {
t.Error("a failed removal during unset must be remembered")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("expected a removal attempt, got %q", got)
}
}
func TestResolvconfAppliedLibc(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": takenOver})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": untouched})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
}
}
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
// ignored and the DHCP nameservers stay listed, so the system falls back to
// them; that is the leak the option exists to close, and it must not pass.
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("another nameserver alongside the TUN's must not count as applied")
}
}
// A loopback nameserver alongside is a local resolver that resolvconf feeds
// (local_unbound with the libc subscriber left on), not a leak.
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("192.168.100.10 must not match 192.168.100.1")
}
}
// local-unbound-setup turns the libc subscriber off and has resolvconf write
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
func TestResolvconfAppliedUnbound(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("unbound still forwarding to the old server must not count as applied")
}
}
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
files(t, map[string]string{})
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
t.Error("a missing resolv.conf is an error, not a verdict")
}
}
-382
View File
@@ -3,11 +3,7 @@
package tun
import (
"context"
"errors"
"io/fs"
"net/netip"
"strings"
"testing"
"golang.org/x/net/route"
@@ -152,381 +148,3 @@ func TestDefaultRouteFamilyRejectsShortAddrs(t *testing.T) {
t.Fatal("message without addresses must not match")
}
}
type probeCall struct {
inboundTag string
source string
address string
}
// stubDNSRouting replaces the routing probe for the duration of a test and
// records how it was called, so tests can assert the probe is representative.
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
t.Helper()
original := verifyDNSRouting
calls := []probeCall{}
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
calls = append(calls, probeCall{inboundTag, source, address})
return err
}
t.Cleanup(func() { verifyDNSRouting = original })
return &calls
}
// recorder installs a resolvconf stub for the duration of a test and returns
// the captured invocations, each as the arguments followed by the stdin in
// angle brackets when there was one. An empty failOn succeeds every call;
// otherwise the named subcommand fails.
func recorder(t *testing.T, failOn string) *[]string {
t.Helper()
original := resolvconfRunner
calls := []string{}
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
call := strings.Join(args, " ")
if stdin != "" {
call += " <" + stdin + ">"
}
calls = append(calls, call)
if failOn != "" && len(args) > 0 && args[0] == failOn {
return nil, errors.New("boom")
}
return nil, nil
}
t.Cleanup(func() { resolvconfRunner = original })
return &calls
}
// files replaces the resolver files read by the applied check for the
// duration of a test. A path not in the map does not exist.
func files(t *testing.T, contents map[string]string) {
t.Helper()
original := readResolverFile
readResolverFile = func(path string) ([]byte, error) {
if data, ok := contents[path]; ok {
return []byte(data), nil
}
return nil, fs.ErrNotExist
}
t.Cleanup(func() { readResolverFile = original })
}
// takenOver is what the libc subscriber writes once the TUN's nameserver is
// the exclusive one.
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
// place.
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
func optedInTun() *FreeBSDTun {
return &FreeBSDTun{
options: &Config{
Name: "tun7",
Gateway: []string{"192.168.100.1/30"},
AutoSystemDnsToGateway: true,
},
name: "tun7",
gateway: netip.MustParsePrefix("192.168.100.1/30"),
local: netip.MustParseAddr("192.168.100.2"),
}
}
func joined(calls []string) string {
return strings.Join(calls, " | ")
}
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
probes := stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.options.AutoSystemDnsToGateway = false
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != 0 || len(*probes) != 0 {
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the option is off")
}
}
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
stubDNSRouting(t, errors.New("no route"))
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the probe fails")
}
if len(*calls) != 0 {
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the probe fails")
}
}
// On FreeBSD the addresses are the other way round from Linux: the local
// address is the one after the gateway, and the gateway itself has no owner,
// so a packet to it is routed into the TUN. The probe has to carry that pair,
// and the resolver has to be pointed at the gateway.
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
probes := stubDNSRouting(t, nil)
recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*probes) != 1 {
t.Fatalf("expected one probe, got %d", len(*probes))
}
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
if (*probes)[0] != want {
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
}
}
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !t1.systemDNSSet {
t.Fatal("systemDNSSet should be true after a successful takeover")
}
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
if got := joined(*calls); got != want {
t.Errorf("resolvconf calls = %q, want %q", got, want)
}
}
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
// the entry for the interface, but runs no subscriber, so success has to be
// confirmed in what the subscribers wrote.
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the nameserver did not reach a resolver")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not take")
}
if !strings.HasSuffix(joined(*calls), "-d tun7") {
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
}
}
func TestConfigureSystemDNSIdempotent(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
before := len(*calls)
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(*calls) != before {
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
}
}
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-a")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when resolvconf -a fails")
}
if t1.systemDNSSet || t1.systemDNSDirty {
t.Error("a failed add leaves nothing to clean up")
}
if len(*calls) != 1 {
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
}
}
// If the removal after a failed check fails too, the entry may still be
// installed, so the state has to be remembered rather than silently dropped.
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
stubDNSRouting(t, nil)
recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": untouched})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
t.Fatal("expected an error when the check fails")
}
if !t1.systemDNSDirty {
t.Error("a failed removal must leave the resolver marked dirty")
}
if t1.systemDNSSet {
t.Error("systemDNSSet must stay false when the takeover did not complete")
}
}
// A dirty resolver is retried before anything new is applied.
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSDirty = true
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := joined(*calls)
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
t.Errorf("expected the stale removal first, got %q", got)
}
if t1.systemDNSDirty {
t.Error("a successful retry should clear the dirty flag")
}
if !t1.systemDNSSet {
t.Error("the takeover should proceed once the retry succeeds")
}
}
func TestUnsetSystemDNSRemoves(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
t.Fatalf("setup failed: %v", err)
}
*calls = nil
t1.unsetSystemDNS()
if t1.systemDNSSet {
t.Error("systemDNSSet should be false after unset")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
}
t1.unsetSystemDNS()
if len(*calls) != 1 {
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
}
}
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
stubDNSRouting(t, nil)
calls := recorder(t, "-d")
files(t, map[string]string{"/etc/resolv.conf": takenOver})
t1 := optedInTun()
t1.systemDNSSet = true
t1.unsetSystemDNS()
if !t1.systemDNSDirty {
t.Error("a failed removal during unset must be remembered")
}
if got := joined(*calls); got != "-d tun7" {
t.Errorf("expected a removal attempt, got %q", got)
}
}
func TestResolvconfAppliedLibc(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": takenOver})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": untouched})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
}
}
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
// ignored and the DHCP nameservers stay listed, so the system falls back to
// them; that is the leak the option exists to close, and it must not pass.
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("another nameserver alongside the TUN's must not count as applied")
}
}
// A loopback nameserver alongside is a local resolver that resolvconf feeds
// (local_unbound with the libc subscriber left on), not a leak.
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("192.168.100.10 must not match 192.168.100.1")
}
}
// local-unbound-setup turns the libc subscriber off and has resolvconf write
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
func TestResolvconfAppliedUnbound(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
})
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
}
}
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
files(t, map[string]string{
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
})
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
t.Error("unbound still forwarding to the old server must not count as applied")
}
}
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
files(t, map[string]string{})
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
t.Error("a missing resolv.conf is an error, not a verdict")
}
}
+204
View File
@@ -0,0 +1,204 @@
//go:build linux && !android
package tun
import (
"context"
"strings"
"testing"
"github.com/xtls/xray-core/app/dispatcher"
appdns "github.com/xtls/xray-core/app/dns"
"github.com/xtls/xray-core/app/proxyman"
_ "github.com/xtls/xray-core/app/proxyman/inbound"
_ "github.com/xtls/xray-core/app/proxyman/outbound"
"github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core"
proxydns "github.com/xtls/xray-core/proxy/dns"
"github.com/xtls/xray-core/proxy/freedom"
)
const (
routeTestInboundTag = "tun"
routeTestSource = "192.168.100.1"
routeTestDNSAddress = "192.168.100.2"
)
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
func port53Rule() *router.RoutingRule {
return &router.RoutingRule{
InboundTag: []string{routeTestInboundTag},
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
}
}
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
// that only matches because the real request carries a source.
func sourceBlockRule(ip []byte) *router.RoutingRule {
return &router.RoutingRule{
SourceIp: []*geodata.IPRule{{
Value: &geodata.IPRule_Custom{
Custom: &geodata.CIDRRule{
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
},
},
}},
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
}
}
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
// running resolver. The instance is placed in the context through the key core
// exports for tests.
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
t.Helper()
apps := []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&router.Config{Rule: rules}),
}
if withDNSApp {
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
}
instance, err := core.New(&core.Config{
App: apps,
Outbound: []*core.OutboundHandlerConfig{
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
},
})
if err != nil {
t.Fatalf("core.New: %v", err)
}
t.Cleanup(func() { _ = instance.Close() })
return context.WithValue(context.Background(), core.XrayKey(1), instance)
}
func udpNameServer(ip []byte) []*appdns.NameServer {
return []*appdns.NameServer{{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
Port: 53,
},
}}
}
// localNameServer is a name server pointed at "localhost", which app/dns
// resolves through the system resolver.
func localNameServer() *appdns.NameServer {
return &appdns.NameServer{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
Port: 53,
},
}
}
// These drive the real feature lookup and the real router. verifyDNSRouting is
// the same function ConfigureSystemDNS calls, so a false positive here is a
// false positive in the takeover decision itself, which is what assertions on
// the resolvectl arguments could never catch.
func TestVerifyDNSRoutingDecisions(t *testing.T) {
tests := []struct {
name string
withDNSApp bool
nameServers []*appdns.NameServer
rules []*router.RoutingRule
wantErr string
}{
{
name: "independent upstream reaches the dns outbound",
withDNSApp: true,
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "",
},
{
name: "no dns section falls back to the system resolver",
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "dns section without name servers falls back too",
withDNSApp: true,
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
// An independent upstream is not enough on its own: name servers are
// selected per domain, so a local one can still be the one chosen.
// The refusal is deliberately domain-agnostic for that reason.
name: "a local name server alongside an independent one",
withDNSApp: true,
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "a rule on the interface address diverts the real query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{192, 168, 100, 1}),
port53Rule(),
},
wantErr: "does not handle DNS",
},
{
name: "a rule on another address does not match it",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{10, 0, 0, 1}),
port53Rule(),
},
wantErr: "",
},
{
name: "no rule matches the query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
wantErr: "no route",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
return
}
if err == nil {
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
}
})
}
}
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
// carries IPv6 addresses.
func TestVerifyDNSRoutingIPv6(t *testing.T) {
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
}
}
@@ -9,18 +9,6 @@ import (
"testing"
"github.com/vishvananda/netlink"
"github.com/xtls/xray-core/app/dispatcher"
appdns "github.com/xtls/xray-core/app/dns"
"github.com/xtls/xray-core/app/proxyman"
_ "github.com/xtls/xray-core/app/proxyman/inbound"
_ "github.com/xtls/xray-core/app/proxyman/outbound"
"github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/core"
proxydns "github.com/xtls/xray-core/proxy/dns"
"github.com/xtls/xray-core/proxy/freedom"
)
// testLink returns a minimal netlink.Link whose Attrs().Name is name, so the
@@ -455,185 +443,3 @@ func TestBuildResolvectlArgs(t *testing.T) {
})
}
}
const (
routeTestInboundTag = "tun"
routeTestSource = "192.168.100.1"
routeTestDNSAddress = "192.168.100.2"
)
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
func port53Rule() *router.RoutingRule {
return &router.RoutingRule{
InboundTag: []string{routeTestInboundTag},
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
}
}
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
// that only matches because the real request carries a source.
func sourceBlockRule(ip []byte) *router.RoutingRule {
return &router.RoutingRule{
SourceIp: []*geodata.IPRule{{
Value: &geodata.IPRule_Custom{
Custom: &geodata.CIDRRule{
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
},
},
}},
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
}
}
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
// running resolver. The instance is placed in the context through the key core
// exports for tests.
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
t.Helper()
apps := []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(&router.Config{Rule: rules}),
}
if withDNSApp {
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
}
instance, err := core.New(&core.Config{
App: apps,
Outbound: []*core.OutboundHandlerConfig{
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
},
})
if err != nil {
t.Fatalf("core.New: %v", err)
}
t.Cleanup(func() { _ = instance.Close() })
return context.WithValue(context.Background(), core.XrayKey(1), instance)
}
func udpNameServer(ip []byte) []*appdns.NameServer {
return []*appdns.NameServer{{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
Port: 53,
},
}}
}
// localNameServer is a name server pointed at "localhost", which app/dns
// resolves through the system resolver.
func localNameServer() *appdns.NameServer {
return &appdns.NameServer{
Address: &net.Endpoint{
Network: net.Network_UDP,
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
Port: 53,
},
}
}
// These drive the real feature lookup and the real router. verifyDNSRouting is
// the same function ConfigureSystemDNS calls, so a false positive here is a
// false positive in the takeover decision itself, which is what assertions on
// the resolvectl arguments could never catch.
func TestVerifyDNSRoutingDecisions(t *testing.T) {
tests := []struct {
name string
withDNSApp bool
nameServers []*appdns.NameServer
rules []*router.RoutingRule
wantErr string
}{
{
name: "independent upstream reaches the dns outbound",
withDNSApp: true,
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "",
},
{
name: "no dns section falls back to the system resolver",
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "dns section without name servers falls back too",
withDNSApp: true,
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
// An independent upstream is not enough on its own: name servers are
// selected per domain, so a local one can still be the one chosen.
// The refusal is deliberately domain-agnostic for that reason.
name: "a local name server alongside an independent one",
withDNSApp: true,
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
rules: []*router.RoutingRule{port53Rule()},
wantErr: "system resolver",
},
{
name: "a rule on the interface address diverts the real query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{192, 168, 100, 1}),
port53Rule(),
},
wantErr: "does not handle DNS",
},
{
name: "a rule on another address does not match it",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
rules: []*router.RoutingRule{
sourceBlockRule([]byte{10, 0, 0, 1}),
port53Rule(),
},
wantErr: "",
},
{
name: "no rule matches the query",
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
wantErr: "no route",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
if tt.wantErr == "" {
if err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
return
}
if err == nil {
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
}
})
}
}
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
// carries IPv6 addresses.
func TestVerifyDNSRoutingIPv6(t *testing.T) {
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
t.Fatalf("expected the takeover to be accepted, got: %v", err)
}
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
}
}
-106
View File
@@ -710,109 +710,3 @@ func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, erro
}
return net.InterfaceByIndex(int(index))
}
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
// keeps Xray's own connections out of the TUN. With weak host send or
// forwarding on for an IP version on the bound interface, Windows sends them
// where the routes lead, into the TUN, from that interface's address, and
// drops what comes back to that address through the TUN, so they stall.
//
// For the IP versions routed to the TUN, weak host send is turned off on the
// bound interface while the TUN runs, and turned on again when the TUN stops
// or another interface takes over. Forwarding is what Mobile Hotspot and
// Internet Connection Sharing need, so it is only reported.
type outboundGuard struct {
sync.Mutex
families []winipcfg.AddressFamily
luid winipcfg.LUID // of the interface last checked
name string // of that interface
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
forwarding bool // whether forwarding was on there
stopped bool
}
// check turns weak host send off on the bound interface, and warns when
// forwarding comes on there, but not again while it stays on.
func (g *outboundGuard) check() {
g.Lock()
defer g.Unlock()
if g.stopped {
return
}
var luid winipcfg.LUID
var name string
if iface := updater.Get(); iface != nil {
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
name = iface.Name
}
if luid != g.luid {
g.restoreLocked()
g.luid, g.name = luid, name
g.forwarding = false // to warn about the new interface as well
}
if luid == 0 {
return
}
var forwarding []string
for _, family := range g.families {
row, err := luid.IPInterface(family)
if err != nil {
continue // the interface lacks that IP version
}
if row.ForwardingEnabled {
forwarding = append(forwarding, familyName(family))
}
if !row.WeakHostSend {
continue
}
if err := setWeakHostSend(row, false); err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
continue
}
if !slices.Contains(g.turnedOff, family) {
g.turnedOff = append(g.turnedOff, family)
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
}
}
wasOn := g.forwarding
g.forwarding = len(forwarding) > 0
if g.forwarding && !wasOn {
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
}
}
// restore turns weak host send on again where check turned it off, for good.
func (g *outboundGuard) restore() {
g.Lock()
defer g.Unlock()
g.restoreLocked()
g.stopped = true
}
func (g *outboundGuard) restoreLocked() {
for _, family := range g.turnedOff {
row, err := g.luid.IPInterface(family)
if err == nil {
err = setWeakHostSend(row, true)
}
if err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
}
}
g.turnedOff = nil
}
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
row.WeakHostSend = on
if row.Family == windows.AF_INET {
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
}
return row.Set()
}
func familyName(family winipcfg.AddressFamily) string {
if family == windows.AF_INET {
return "IPv4"
}
return "IPv6"
}
+120
View File
@@ -0,0 +1,120 @@
//go:build windows
package tun
import (
"context"
"slices"
"strings"
"sync"
"github.com/xtls/xray-core/common/errors"
"golang.org/x/sys/windows"
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
)
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
// keeps Xray's own connections out of the TUN. With weak host send or
// forwarding on for an IP version on the bound interface, Windows sends them
// where the routes lead, into the TUN, from that interface's address, and
// drops what comes back to that address through the TUN, so they stall.
//
// For the IP versions routed to the TUN, weak host send is turned off on the
// bound interface while the TUN runs, and turned on again when the TUN stops
// or another interface takes over. Forwarding is what Mobile Hotspot and
// Internet Connection Sharing need, so it is only reported.
type outboundGuard struct {
sync.Mutex
families []winipcfg.AddressFamily
luid winipcfg.LUID // of the interface last checked
name string // of that interface
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
forwarding bool // whether forwarding was on there
stopped bool
}
// check turns weak host send off on the bound interface, and warns when
// forwarding comes on there, but not again while it stays on.
func (g *outboundGuard) check() {
g.Lock()
defer g.Unlock()
if g.stopped {
return
}
var luid winipcfg.LUID
var name string
if iface := updater.Get(); iface != nil {
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
name = iface.Name
}
if luid != g.luid {
g.restoreLocked()
g.luid, g.name = luid, name
g.forwarding = false // to warn about the new interface as well
}
if luid == 0 {
return
}
var forwarding []string
for _, family := range g.families {
row, err := luid.IPInterface(family)
if err != nil {
continue // the interface lacks that IP version
}
if row.ForwardingEnabled {
forwarding = append(forwarding, familyName(family))
}
if !row.WeakHostSend {
continue
}
if err := setWeakHostSend(row, false); err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
continue
}
if !slices.Contains(g.turnedOff, family) {
g.turnedOff = append(g.turnedOff, family)
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
}
}
wasOn := g.forwarding
g.forwarding = len(forwarding) > 0
if g.forwarding && !wasOn {
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
}
}
// restore turns weak host send on again where check turned it off, for good.
func (g *outboundGuard) restore() {
g.Lock()
defer g.Unlock()
g.restoreLocked()
g.stopped = true
}
func (g *outboundGuard) restoreLocked() {
for _, family := range g.turnedOff {
row, err := g.luid.IPInterface(family)
if err == nil {
err = setWeakHostSend(row, true)
}
if err != nil {
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
}
}
g.turnedOff = nil
}
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
row.WeakHostSend = on
if row.Family == windows.AF_INET {
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
}
return row.Set()
}
func familyName(family winipcfg.AddressFamily) string {
if family == windows.AF_INET {
return "IPv4"
}
return "IPv6"
}
@@ -4,7 +4,6 @@ package tun
import (
"context"
"crypto/md5"
go_errors "errors"
"net"
"net/netip"
@@ -341,46 +340,3 @@ func TestFlushDNSCache(t *testing.T) {
t.Fatal(err)
}
}
func TestAdapterGUID(t *testing.T) {
// a configured GUID has to be the adapter GUID the text names: the groups
// are field values, not the bytes of the text in order
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
if err != nil {
t.Fatal(err)
}
want := windows.GUID{
Data1: 0x01020304,
Data2: 0x0506,
Data3: 0x0708,
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
}
if *guid != want {
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
}
// the same struct Windows builds from that text, and the text Windows shows
// for it
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
t.Fatal(err)
} else if *guid != fromText {
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
}
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
t.Errorf("adapterGUID = %s, want %s", got, want)
}
// without one, the bytes of the MD5 of the name, as they always were; that
// GUID is never read back as text, so its byte order does not matter
guid, err = adapterGUID("xray0", "")
if err != nil {
t.Fatal(err)
}
sum := md5.Sum([]byte("xray0"))
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
t.Errorf("adapterGUID = %x, want %x", got, sum)
}
if _, err := adapterGUID("xray0", "xray0"); err == nil {
t.Error("an invalid guid was accepted")
}
}
+14
View File
@@ -8,6 +8,20 @@ import (
"github.com/xtls/xray-core/common/net"
)
// BenchmarkUDPNewSession measures what one new UDP flow costs the
// inbound while it stays open: QUIC and DNS open many short flows, and each
// one lives until the connection idle timeout.
func BenchmarkUDPNewSession(b *testing.B) {
u := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {}, nil)
dst := net.UDPDestination(net.ParseAddress("1.1.1.1"), 443)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
src := net.UDPDestination(net.IPAddress([]byte{10, byte(i >> 16), byte(i >> 8), byte(i)}), net.Port(1024+i%60000))
u.HandlePacket(src, dst, &buf.Buffer{})
}
}
func TestPacketQueueOrderAndClose(t *testing.T) {
q := newPacketQueue(udpQueueLimit)
for i := 0; i < 3; i++ {
+82
View File
@@ -0,0 +1,82 @@
package tun
import (
"runtime"
"testing"
"github.com/xtls/xray-core/common/buf"
)
const benchBatch = 64
// Raw cost of queueing and draining a small burst, as one flow's reader does.
func BenchmarkQueueBurstChan(b *testing.B) {
ch := make(chan *buf.Buffer, udpQueueLimit)
p := &buf.Buffer{}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for j := 0; j < benchBatch; j++ {
ch <- p
}
for j := 0; j < benchBatch; j++ {
<-ch
}
}
}
func BenchmarkQueueBurstPacketQueue(b *testing.B) {
q := newPacketQueue(udpQueueLimit)
p := &buf.Buffer{}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for j := 0; j < benchBatch; j++ {
q.push(p)
}
for j := 0; j < benchBatch; j++ {
q.pop()
}
}
}
// Producer and consumer on different goroutines; the producer yields when the
// queue is full instead of spinning, like a blocking channel send would.
func BenchmarkQueueStreamChan(b *testing.B) {
ch := make(chan *buf.Buffer, udpQueueLimit)
p := &buf.Buffer{}
done := make(chan struct{})
go func() {
for range ch {
}
close(done)
}()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
ch <- p
}
close(ch)
<-done
}
func BenchmarkQueueStreamPacketQueue(b *testing.B) {
q := newPacketQueue(udpQueueLimit)
p := &buf.Buffer{}
done := make(chan struct{})
go func() {
for {
if _, ok := q.pop(); !ok {
break
}
}
close(done)
}()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for !q.push(p) {
runtime.Gosched()
}
}
q.close()
<-done
}
@@ -80,3 +80,43 @@ func TestExpandWfpBlockLeak(t *testing.T) {
}
}
}
func TestLeakCovers(t *testing.T) {
for _, c := range []struct {
value string
protocol string
port uint16
covers bool
}{
{"tcp", "tcp", 1, true},
{"tcp", "udp", 53, false},
{"udp/53", "udp", 53, true},
{"udp/53", "udp", 54, false},
{"tcp/10-20", "tcp", 10, true},
{"tcp/10-20", "tcp", 20, true},
{"tcp/10-20", "tcp", 21, false},
{"tcp/10-20", "tcp", 9, false},
{"53", "udp", 53, true},
{"53", "tcp", 53, true},
{"10-20", "tcp", 15, true},
{"10-20", "udp", 21, false},
{"1.1.1.0/24:udp/53", "udp", 53, true},
{"[::/0]:tcp", "tcp", 443, true},
{"[2001:db8::/32]:53", "tcp", 53, true},
{"0.0.0.0/0:icmp", "udp", 53, false},
{"all", "udp", 53, true},
{"1.1.1.1/32:all", "tcp", 1, true},
{"allexceptlan", "udp", 53, false},
{"misconfigtun", "udp", 53, false},
{"windnsclient", "udp", 53, false},
} {
l, ok := parseLeak(c.value)
if !ok {
t.Errorf("%q was not parsed", c.value)
continue
}
if got := l.covers(c.protocol, c.port); got != c.covers {
t.Errorf("%q covers %s/%d = %v", c.value, c.protocol, c.port, got)
}
}
}
-5
View File
@@ -1,8 +1,6 @@
package vless
import (
"context"
"google.golang.org/protobuf/proto"
"github.com/xtls/xray-core/common/errors"
@@ -45,9 +43,6 @@ type MemoryAccount struct {
Testpre uint32
Testseed []uint32
Ctx context.Context
Cancel context.CancelFunc
}
// Equals implements protocol.Account.Equals().
+2 -3
View File
@@ -4,7 +4,6 @@ import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/net"
@@ -49,7 +48,7 @@ func TestRequestSerialization(t *testing.T) {
_, actualRequest, actualAddons, _, err := DecodeRequestHeader(false, nil, &buffer, Validator)
common.Must(err)
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{}), cmpopts.IgnoreFields(vless.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
@@ -121,7 +120,7 @@ func TestMuxRequest(t *testing.T) {
_, actualRequest, actualAddons, _, err := DecodeRequestHeader(false, nil, &buffer, Validator)
common.Must(err)
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{}), cmpopts.IgnoreFields(vless.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
-12
View File
@@ -13,7 +13,6 @@ import (
"github.com/xtls/xray-core/app/dispatcher"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
c "github.com/xtls/xray-core/common/ctx"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
@@ -37,7 +36,6 @@ import (
"github.com/xtls/xray-core/proxy/vless/multiplex"
"github.com/xtls/xray-core/proxy/vless/reverse"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet"
"github.com/xtls/xray-core/transport/internet/reality"
"github.com/xtls/xray-core/transport/internet/stat"
"github.com/xtls/xray-core/transport/internet/tls"
@@ -526,12 +524,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
}
errors.LogInfo(ctx, "received request for ", request.Destination())
if stream, ok := session.StreamSettingsFromContext(h.ctx).(*internet.MemoryStreamConfig); ok && stream.ProtocolName == "xdrive" {
if request.Command != protocol.RequestCommandMux && request.Command != protocol.RequestCommandRvs {
return errors.New("VLESS over XDRIVE: inbound received a non-Mux/Rvs request")
}
}
inbound := session.InboundFromContext(ctx)
if inbound == nil {
panic("no inbound metadata")
@@ -542,10 +534,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
account := request.User.Account.(*vless.MemoryAccount)
var cancel context.CancelFunc
ctx, cancel = c.ContextWithParents(ctx, account.Ctx)
defer cancel()
if account.Reverse != nil && request.Command != protocol.RequestCommandRvs {
return errors.New("for safety reasons, user " + account.ID.String() + " is not allowed to use forward proxy")
}
+9 -13
View File
@@ -12,7 +12,6 @@ import (
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/proxy"
"github.com/xtls/xray-core/proxy/vless"
"github.com/xtls/xray-core/transport"
)
@@ -42,19 +41,17 @@ type Client struct {
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
c := &Client{config: config}
maxReuseTimes := uint32(1024)
if network == "xdrive" {
maxReuseTimes = 0 // unlimited
config.Concurrency = max(config.Concurrency, 128)
if config.XudpConcurrency > 0 {
config.XudpConcurrency = max(config.XudpConcurrency, 128)
pool := func(concurrency int32) *Pool {
return NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(concurrency), MaxConnection: 1024}, open)
}
if concurrency := config.GetConcurrency(); concurrency > 0 {
if network == "xdrive" {
concurrency = max(concurrency, 128)
}
c.tcp = pool(concurrency)
}
if config.Concurrency > 0 {
c.tcp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.Concurrency), MaxConnection: maxReuseTimes}, open)
}
if config.XudpConcurrency > 0 {
c.udp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.XudpConcurrency), MaxConnection: maxReuseTimes}, open)
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
c.udp = pool(concurrency)
}
return c
}
@@ -75,7 +72,6 @@ func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, erro
if target.Network == net.Network_UDP && target.Port == 443 {
switch c.config.GetXudpProxyUDP443() {
case "reject", "":
proxy.DropUDP(ctx, link.Reader)
return true, errors.New("XUDP rejected UDP/443 traffic")
case "skip":
return false, nil
+1 -3
View File
@@ -26,9 +26,7 @@ func TestClientUDP443Policy(t *testing.T) {
opened = true
return nil, nil, context.Canceled
})
r, w := pipe.New()
common.Close(w)
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
handled, err := client.Dispatch(ctx, &transport.Link{})
wantRejected := policy == "reject"
if opened || handled != wantRejected || (err != nil) != wantRejected {
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
+7 -7
View File
@@ -191,13 +191,6 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
rec := h.server
var conn stat.Connection
account := rec.User.Account.(*vless.MemoryAccount)
if !native && ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 && account.Flow == vless.XRV {
proxy.DropUDP(ctx, link.Reader)
return nil, nil, errors.New("XTLS rejected UDP/443 traffic")
}
if h.testpre > 0 {
h.initpre.Do(func() {
h.preConns = make(chan *ConnExpire)
@@ -279,20 +272,27 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
request.Address, request.Port = target.Address, target.Port
}
account := request.User.Account.(*vless.MemoryAccount)
requestAddons := &encoding.Addons{
Flow: account.Flow,
}
var input *bytes.Reader
var rawInput **bytes.Buffer
allowUDP443 := false
switch requestAddons.Flow {
case vless.XRV + "-udp443":
allowUDP443 = true
requestAddons.Flow = requestAddons.Flow[:16]
fallthrough
case vless.XRV:
ob.CanSpliceCopy = 2
switch request.Command {
case protocol.RequestCommandUDP:
if !allowUDP443 && request.Port == 443 {
return nil, nil, errors.New("XTLS rejected UDP/443 traffic")
}
case protocol.RequestCommandTCP, protocol.RequestCommandMux, protocol.RequestCommandRvs:
var target net.Conn
if commonConn, ok := conn.(*encryption.CommonConn); ok {
+18 -16
View File
@@ -1,12 +1,11 @@
package vless
import (
"context"
"strings"
"sync"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/utils"
"github.com/xtls/xray-core/common/uuid"
)
@@ -28,21 +27,19 @@ func ProcessUUID(id [16]byte) [16]byte {
// MemoryValidator stores valid VLESS users.
type MemoryValidator struct {
// Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
email utils.TypedSyncMap[string, *protocol.MemoryUser]
users utils.TypedSyncMap[[16]byte, *protocol.MemoryUser]
email sync.Map
users sync.Map
}
// Add a VLESS user, Email must be empty or unique.
func (v *MemoryValidator) Add(u *protocol.MemoryUser) error {
a := u.Account.(*MemoryAccount)
a.Ctx, a.Cancel = context.WithCancel(context.Background())
if u.Email != "" {
_, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
if loaded {
return errors.New("User ", u.Email, " already exists.")
}
}
v.users.Store(ProcessUUID(a.ID.UUID()), u)
v.users.Store(ProcessUUID(u.Account.(*MemoryAccount).ID.UUID()), u)
return nil
}
@@ -57,29 +54,34 @@ func (v *MemoryValidator) Del(e string) error {
return errors.New("User ", e, " not found.")
}
v.email.Delete(le)
a := u.Account.(*MemoryAccount)
v.users.Delete(ProcessUUID(a.ID.UUID()))
a.Cancel()
v.users.Delete(ProcessUUID(u.(*protocol.MemoryUser).Account.(*MemoryAccount).ID.UUID()))
return nil
}
// Get a VLESS user with UUID, nil if user doesn't exist.
func (v *MemoryValidator) Get(id uuid.UUID) *protocol.MemoryUser {
u, _ := v.users.Load(ProcessUUID(id))
return u
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
// Get a VLESS user with email, nil if user doesn't exist.
func (v *MemoryValidator) GetByEmail(email string) *protocol.MemoryUser {
u, _ := v.email.Load(strings.ToLower(email))
return u
email = strings.ToLower(email)
u, _ := v.email.Load(email)
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
// Get all users
func (v *MemoryValidator) GetAll() []*protocol.MemoryUser {
u := make([]*protocol.MemoryUser, 0, 100)
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
u = append(u, value)
v.email.Range(func(key, value interface{}) bool {
u = append(u, value.(*protocol.MemoryUser))
return true
})
return u
@@ -88,7 +90,7 @@ func (v *MemoryValidator) GetAll() []*protocol.MemoryUser {
// Get users count
func (v *MemoryValidator) GetCount() int64 {
var c int64 = 0
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
v.email.Range(func(key, value interface{}) bool {
c++
return true
})
-4
View File
@@ -1,7 +1,6 @@
package vmess
import (
"context"
"strings"
"google.golang.org/protobuf/proto"
@@ -20,9 +19,6 @@ type MemoryAccount struct {
AuthenticatedLengthExperiment bool
NoTerminationSignal bool
Ctx context.Context
Cancel context.CancelFunc
}
// Equals implements protocol.Account.
+2 -3
View File
@@ -5,7 +5,6 @@ import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/net"
@@ -59,7 +58,7 @@ func TestRequestSerialization(t *testing.T) {
actualRequest, err := server.DecodeRequestHeader(buffer, false)
common.Must(err)
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{}), cmpopts.IgnoreFields(vmess.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
@@ -148,7 +147,7 @@ func TestMuxRequest(t *testing.T) {
actualRequest, err := server.DecodeRequestHeader(buffer, false)
common.Must(err)
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{}), cmpopts.IgnoreFields(vmess.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
}
-5
View File
@@ -9,7 +9,6 @@ import (
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
c "github.com/xtls/xray-core/common/ctx"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net"
@@ -236,10 +235,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
inbound.CanSpliceCopy = 3
inbound.User = request.User
var cancel context.CancelFunc
ctx, cancel = c.ContextWithParents(ctx, request.User.Account.(*vmess.MemoryAccount).Ctx)
defer cancel()
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
if err != nil {
return errors.New("failed to start decoding").Base(err)
+1 -5
View File
@@ -1,7 +1,6 @@
package vmess
import (
"context"
"crypto/hmac"
"crypto/sha256"
"hash/crc64"
@@ -44,7 +43,6 @@ func (v *TimedUserValidator) Add(u *protocol.MemoryUser) error {
if !ok {
return errors.New("account type is incorrect")
}
account.Ctx, account.Cancel = context.WithCancel(context.Background())
if !v.behaviorFused {
hashkdf := hmac.New(sha256.New, []byte("VMESSBSKDF"))
hashkdf.Write(account.ID.Bytes())
@@ -95,11 +93,9 @@ func (v *TimedUserValidator) Remove(email string) bool {
for i, u := range v.users {
if strings.EqualFold(u.Email, email) {
idx = i
a := u.Account.(*MemoryAccount)
var cmdkeyfl [16]byte
copy(cmdkeyfl[:], a.ID.CmdKey())
copy(cmdkeyfl[:], u.Account.(*MemoryAccount).ID.CmdKey())
v.aeadDecoderHolder.RemoveUser(cmdkeyfl)
a.Cancel()
break
}
}
-4
View File
@@ -1,7 +1,6 @@
package wireguard
import (
"context"
"encoding/hex"
"net/netip"
@@ -37,9 +36,6 @@ type MemoryAccount struct {
AllowedIPs []netip.Prefix
PreSharedKey string
KeepAlive string
Ctx context.Context
Cancel context.CancelFunc
}
func (a *MemoryAccount) Equals(other protocol.Account) bool {
+14 -23
View File
@@ -17,7 +17,6 @@ import (
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/utils"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/policy"
"github.com/xtls/xray-core/features/routing"
@@ -49,7 +48,7 @@ type Server struct {
mu sync.Mutex
pub [32]byte
users *utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]
users *sync.Map
}
func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
@@ -99,15 +98,13 @@ func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
var pub [32]byte
curve25519.ScalarBaseMult(&pub, pri)
users := &utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]{}
users := &sync.Map{}
for _, u := range conf.Users {
user, err := u.ToMemoryUser()
if err != nil {
return nil, err
}
peer := user.Account.(*MemoryAccount)
peer.Ctx, peer.Cancel = context.WithCancel(context.Background())
users.Store(peer.Pub, user)
users.Store(user.Account.(*MemoryAccount).Pub, user)
}
s := &Server{
@@ -161,7 +158,6 @@ func (s *Server) AddUser(ctx context.Context, user *protocol.MemoryUser) error {
if err != nil {
return err
}
peer.Ctx, peer.Cancel = context.WithCancel(context.Background())
s.users.Store(peer.Pub, user)
return nil
}
@@ -179,15 +175,14 @@ func (s *Server) RemoveUser(ctx context.Context, email string) error {
return err
}
s.users.Delete(peer.Pub)
peer.Cancel()
}
return nil
}
func (s *Server) GetUser(ctx context.Context, email string) (user *protocol.MemoryUser) {
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
if value.Email == email {
user = value
s.users.Range(func(key, value any) bool {
if value.(*protocol.MemoryUser).Email == email {
user = value.(*protocol.MemoryUser)
return false
}
return true
@@ -196,11 +191,11 @@ func (s *Server) GetUser(ctx context.Context, email string) (user *protocol.Memo
}
func (s *Server) GetUserByAddr(ctx context.Context, addr netip.Addr) (user *protocol.MemoryUser) {
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
peer := value.Account.(*MemoryAccount)
s.users.Range(func(key, value any) bool {
peer := value.(*protocol.MemoryUser).Account.(*MemoryAccount)
for i := range peer.AllowedIPs {
if peer.AllowedIPs[i].Contains(addr) {
user = value
user = value.(*protocol.MemoryUser)
return false
}
}
@@ -210,15 +205,15 @@ func (s *Server) GetUserByAddr(ctx context.Context, addr netip.Addr) (user *prot
}
func (s *Server) GetUsers(ctx context.Context) (users []*protocol.MemoryUser) {
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
users = append(users, value)
s.users.Range(func(key, value interface{}) bool {
users = append(users, value.(*protocol.MemoryUser))
return true
})
return
}
func (s *Server) GetUsersCount(context.Context) (count int64) {
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
s.users.Range(func(key, value interface{}) bool {
count++
return true
})
@@ -300,8 +295,8 @@ func (s *Server) Start() error {
dev := device.NewDevice(s.tun, bind, logger)
var cfg strings.Builder
cfg.WriteString("private_key=" + s.conf.SecretKey + "\n")
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
peer := value.Account.(*MemoryAccount)
s.users.Range(func(key, value any) bool {
peer := value.(*protocol.MemoryUser).Account.(*MemoryAccount)
cfg.WriteString("public_key=" + hex.EncodeToString(peer.Pub[:]) + "\n")
for i := range peer.AllowedIPs {
cfg.WriteString("allowed_ip=" + peer.AllowedIPs[i].String() + "\n")
@@ -355,10 +350,6 @@ func (s *Server) HandleConnection(conn net.Conn, dest net.Destination) {
return
}
var userCancel context.CancelFunc
ctx, userCancel = c.ContextWithParents(ctx, user.Account.(*MemoryAccount).Ctx)
defer userCancel()
source := net.DestinationFromAddr(remote)
inbound := session.Inbound{
Name: "wireguard",
+4 -10
View File
@@ -4,6 +4,7 @@ import (
"context"
"io"
"net/netip"
"sync"
"sync/atomic"
"testing"
@@ -11,7 +12,6 @@ import (
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/utils"
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/transport"
)
@@ -54,16 +54,10 @@ func (d *closingDispatcher) DispatchLink(_ context.Context, _ net.Destination, l
func TestServerKeepsConnectionOpenWhenWriterCloses(t *testing.T) {
conn := &stackConn{}
dispatcher := &closingDispatcher{conn: conn}
users := &utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]{}
userCtx, userCancel := context.WithCancel(context.Background())
defer userCancel()
users := &sync.Map{}
users.Store([32]byte{1}, &protocol.MemoryUser{
Email: "love@xray.com",
Account: &MemoryAccount{
AllowedIPs: []netip.Prefix{netip.MustParsePrefix("10.0.0.2/32")},
Ctx: userCtx,
Cancel: userCancel,
},
Email: "love@xray.com",
Account: &MemoryAccount{AllowedIPs: []netip.Prefix{netip.MustParsePrefix("10.0.0.2/32")}},
})
s := &Server{ctx: context.Background(), dispatcher: dispatcher, users: users}
s.HandleConnection(conn, net.TCPDestination(net.ParseAddress("192.0.2.1"), 443))
+1 -2
View File
@@ -255,11 +255,10 @@ func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig
}
ips, err := LookupForIP(dest.Address.Domain(), finalStrategy, src)
if err != nil {
errors.LogErrorInner(ctx, err, "failed to resolve ip")
if sockopt.DomainStrategy.ForceIP() {
errors.LogErrorInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain())
return nil, err
}
errors.LogInfoInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain(), ", but continue due to USEIP* strategy")
} else if sockopt.HappyEyeballs == nil || sockopt.HappyEyeballs.TryDelayMs == 0 || sockopt.HappyEyeballs.MaxConcurrentTry == 0 || len(ips) < 2 || len(sockopt.DialerProxy) > 0 || dest.Network != net.Network_TCP {
dest.Address = net.IPAddress(ips[dice.Roll(len(ips))])
errors.LogInfo(ctx, "replace destination with "+dest.String())
+5 -12
View File
@@ -175,14 +175,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
c.decref(msg, addr)
return
}
kind := decoded[8] & 0x3F
fragmented := decoded[8]&0xC0 == 0xC0
dataOffset := 9 + 3
if fragmented {
dataOffset += 3
}
if TypeMap_[decoded[0]&3] != uint16(msg.Questions[0].Type) ||
(kind != 3 && kind != 8) || (kind == 3 && n <= dataOffset) || (kind == 8 && n != 9+8) {
if TypeMap_[decoded[0]&3] != uint16(msg.Questions[0].Type) || (decoded[8]&0x3F != 3 && decoded[8]&0x3F != 8) || (decoded[8]&0x3F == 3 && n < 9+3+1) || (decoded[8]&0x3F == 8 && n != 9+8) {
msg.Header.Response = true
msg.Header.Authoritative = true
msg.Header.RCode = dnsmessage.RCodeSuccess
@@ -208,14 +201,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
c.decref(msg, addr)
}
if kind == 8 {
if decoded[8]&0x3F == 8 {
return
}
p := pool4K.Get().([]byte)
p = p[:0]
if fragmented {
if decoded[8]&0xC0 == 0xC0 {
out := pool4K.Get().([]byte)
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[dataOffset:n])
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[15:n])
pool4K.Put(p[:cap(p)])
if n > 0 {
p = out[:n]
@@ -224,7 +217,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
return
}
} else {
p = append(p, decoded[dataOffset:n]...)
p = append(p, decoded[12:n]...)
}
select {
case <-c.closeCh:
@@ -1,77 +0,0 @@
package xmc
import (
"fmt"
"regexp"
"strings"
)
const (
// DefaultDataChannel carries the tunnel byte stream and DefaultPaddingChannel
// carries the startup padding. Both ends must agree on the pair, and the
// defaults are public constants, so a deployment that wants a different
// fingerprint renames them on both sides.
DefaultDataChannel = "xmc:data"
DefaultPaddingChannel = "xmc:pad"
// MaxChannelIDLength bounds a channel id. The id travels in every custom
// payload header, so a long one is pure overhead; vanilla itself has no
// limit beyond the string encoding.
MaxChannelIDLength = 128
)
var (
channelNamespacePattern = regexp.MustCompile(`^[a-z0-9_.-]+$`)
channelPathPattern = regexp.MustCompile(`^[a-z0-9/._-]+$`)
)
// ChannelIDs returns the two configured custom payload channels, filling in the
// defaults for empty fields. Both are validated because both ends have to
// register them as Minecraft resource locations.
func (c *Config) ChannelIDs() (dataChannel, paddingChannel string, err error) {
dataChannel = c.DataChannel
if dataChannel == "" {
dataChannel = DefaultDataChannel
}
paddingChannel = c.PaddingChannel
if paddingChannel == "" {
paddingChannel = DefaultPaddingChannel
}
if err = ValidateChannelID(dataChannel); err != nil {
return "", "", fmt.Errorf("data channel: %w", err)
}
if err = ValidateChannelID(paddingChannel); err != nil {
return "", "", fmt.Errorf("padding channel: %w", err)
}
if dataChannel == paddingChannel {
return "", "", fmt.Errorf("data and padding channels must differ: %q", dataChannel)
}
return dataChannel, paddingChannel, nil
}
// ValidateChannelID checks one custom payload id as a Minecraft resource
// location: namespace:path with vanilla's character rules. The "minecraft"
// namespace is reserved, because every vanilla custom payload id lives there and
// reusing one would make the tunnel collide with the game.
func ValidateChannelID(id string) error {
if id == "" {
return fmt.Errorf("empty channel id")
}
if len(id) > MaxChannelIDLength {
return fmt.Errorf("channel id %q is longer than %d bytes", id, MaxChannelIDLength)
}
namespace, path, found := strings.Cut(id, ":")
if !found || strings.Contains(path, ":") {
return fmt.Errorf("channel id %q is not namespace:path", id)
}
if namespace == "" || namespace == ".." || !channelNamespacePattern.MatchString(namespace) {
return fmt.Errorf("channel id %q has an invalid namespace: only a-z, 0-9, '_', '.' and '-' are allowed, and it cannot be \"..\"", id)
}
if namespace == "minecraft" {
return fmt.Errorf("channel id %q uses the vanilla \"minecraft\" namespace; vanilla custom payload ids belong to the game", id)
}
if path == "" || !channelPathPattern.MatchString(path) {
return fmt.Errorf("channel id %q has an invalid path: only a-z, 0-9, '_', '-', '.' and '/' are allowed", id)
}
return nil
}
@@ -1,188 +0,0 @@
package xmc
import (
"bytes"
"strings"
"testing"
"time"
)
func TestChannelIDsDefaults(t *testing.T) {
dataChannel, paddingChannel, err := (&Config{}).ChannelIDs()
if err != nil {
t.Fatalf("default channels: %v", err)
}
if dataChannel != DefaultDataChannel || paddingChannel != DefaultPaddingChannel {
t.Fatalf("defaults = %q, %q", dataChannel, paddingChannel)
}
}
func TestChannelIDsConfigured(t *testing.T) {
config := &Config{DataChannel: "myxmc:stream", PaddingChannel: "myxmc:noise"}
dataChannel, paddingChannel, err := config.ChannelIDs()
if err != nil {
t.Fatalf("configured channels: %v", err)
}
if dataChannel != "myxmc:stream" || paddingChannel != "myxmc:noise" {
t.Fatalf("channels = %q, %q", dataChannel, paddingChannel)
}
}
func TestChannelIDsRejectEqualChannels(t *testing.T) {
config := &Config{DataChannel: "myxmc:same", PaddingChannel: "myxmc:same"}
if _, _, err := config.ChannelIDs(); err == nil {
t.Fatal("expected an error for one channel used twice")
}
}
func TestValidateChannelID(t *testing.T) {
tests := []struct {
id string
ok bool
}{
{"xmc:data", true},
{"a:b", true},
{"my-xmc:v1/main.data", true},
{strings.Repeat("a", 126) + ":b", true}, // exactly 128 bytes
{"", false},
{"xmcdata", false},
{"xmc:data:extra", false},
{":data", false},
{"xmc:", false},
{"Xmc:data", false},
{"xmc:Data", false},
{"..:data", false},
{"xmc:data space", false},
{"xmc:data!", false},
{"minecraft:data", false},
{"minecraft:brand", false},
{strings.Repeat("a", 127) + ":b", false}, // 129 bytes
}
for _, test := range tests {
err := ValidateChannelID(test.id)
if test.ok && err != nil {
t.Fatalf("%q: unexpected error %v", test.id, err)
}
if !test.ok && err == nil {
t.Fatalf("%q: expected an error", test.id)
}
}
}
// TestPaddingFramingDependsOnChannelLength pins that the exact frame lengths of
// a captured preset follow the configured channel name instead of the default.
func TestPaddingFramingDependsOnChannelLength(t *testing.T) {
const channel = "my-long-namespace:padding-channel"
framing := newPaddingFraming(channel)
if got, want := framing.overhead(), defaultPaddingFraming.overhead()+len(channel)-len(DefaultPaddingChannel); got != want {
t.Fatalf("overhead = %d, want %d", got, want)
}
for _, length := range []int{1024, 48 * 1024, 1024 * 1024} {
plan, err := framing.plan(length)
if err != nil {
t.Fatalf("plan %d: %v", length, err)
}
total := 0
for _, frameLength := range plan {
if _, ok := framing.frameDataLength(frameLength); !ok {
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
}
total += frameLength
}
if total != length {
t.Fatalf("plan %d totals %d", length, total)
}
}
}
// TestPaddingChannelIsConfigurable checks that the startup-padding reader drains
// exactly the configured channel and leaves every other payload alone.
func TestPaddingChannelIsConfigurable(t *testing.T) {
const paddingChannel = "myxmc:noise"
packetID := paddingFramePacketID(configurationPacketIDs121, false)
build := func() []byte {
var wire bytes.Buffer
channel := String(paddingChannel)
padding := RestBytes(make([]byte, 64))
if err := writePacket(&wire, packetID, &channel, &padding); err != nil {
t.Fatal(err)
}
following := String(DefaultDataChannel)
payload := RestBytes("tunnel bytes")
if err := writePacket(&wire, packetID, &following, &payload); err != nil {
t.Fatal(err)
}
return wire.Bytes()
}
channelOf := func(frame []byte) string {
t.Helper()
packet, err := readPacket(bytes.NewReader(frame))
if err != nil {
t.Fatal(err)
}
var channel String
if err := channel.readFrom(bytes.NewReader(packet.data)); err != nil {
t.Fatal(err)
}
return string(channel)
}
frame, err := readPastPadding(bytes.NewReader(build()), packetID, paddingChannel)
if err != nil {
t.Fatalf("readPastPadding: %v", err)
}
if got := channelOf(frame); got != DefaultDataChannel {
t.Fatalf("drained past the configured padding channel, got %q", got)
}
// A different configured name must not silently drop the frame.
frame, err = readPastPadding(bytes.NewReader(build()), packetID, "other:pad")
if err != nil {
t.Fatalf("readPastPadding with another channel: %v", err)
}
if got := channelOf(frame); got != paddingChannel {
t.Fatalf("expected the unrecognized frame back, got %q", got)
}
}
// TestTickStreamUsesConfiguredChannels checks that a configured pair reaches the
// wire: data payloads on the data channel, idle ticks on the padding channel.
func TestTickStreamUsesConfiguredChannels(t *testing.T) {
const (
dataChannel = "myxmc:stream"
paddingChannel = "myxmc:noise"
)
writer := &tickTestWriter{}
stream := newTickStream(nil, writer, true, configurationPacketIDs121, dataChannel, paddingChannel)
defer stream.Stop()
if _, err := stream.Write([]byte("hello")); err != nil {
t.Fatal(err)
}
time.Sleep(120 * time.Millisecond)
stream.Stop()
_ = stream.Flush()
seenData, seenPadding := false, false
for _, batch := range writer.snapshot() {
for _, packet := range readTickBatch(t, batch) {
channel, payload := tickPacketChannelAndPayload(t, packet)
switch channel {
case dataChannel:
seenData = true
if !bytes.Equal(payload, []byte("hello")) {
t.Fatalf("data payload = %q", payload)
}
case paddingChannel:
seenPadding = true
default:
t.Fatalf("unexpected channel %q", channel)
}
}
}
if !seenData || !seenPadding {
t.Fatalf("configured channels not used: data=%v padding=%v", seenData, seenPadding)
}
}
+96 -260
View File
@@ -23,11 +23,6 @@ type clientConn struct {
state clientState
// protocol selects the packet ids and field shapes of the login the client
// performs. The server picks its own row from the handshake, so both ends
// agree without a negotiation round trip.
protocol protocolVersion
handshakeLock sync.Mutex
lifecycleMu sync.Mutex
closed bool
@@ -35,11 +30,9 @@ type clientConn struct {
password string
rsaPublicKey []byte
hostname string
dataChannel string
paddingChannel string
yggdrasil *yggdrasilAuth
paddingSchedule []paddingTurn
packet *tickStream
packet *packetStream
deadlines *connectionDeadlines
done chan struct{}
@@ -53,7 +46,7 @@ var (
clientStateProxy clientState = 2
)
func newClientConn(c net.Conn, protocol protocolVersion, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth, dataChannel, paddingChannel string) (*clientConn, error) {
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth) (*clientConn, error) {
if len(rsaPublicKey) == 0 && yggdrasil == nil {
return nil, fmt.Errorf("empty rsa public key")
}
@@ -68,14 +61,11 @@ func newClientConn(c net.Conn, protocol protocolVersion, profiles []loginProfile
writer: c,
c: c,
state: clientStateHandshake,
protocol: protocol,
handshakeLock: sync.Mutex{},
profiles: profiles,
password: password,
rsaPublicKey: rsaPublicKey,
hostname: hostname,
dataChannel: dataChannel,
paddingChannel: paddingChannel,
yggdrasil: yggdrasil,
paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c),
@@ -102,10 +92,10 @@ func (c *clientConn) handshake() error {
defer func() { _ = c.deadlines.endHandshake() }()
var (
protocolNumber Varint = c.protocol.number
serverAddress String = String(c.hostname)
serverPort UnsignedShort = UnsignedShort(25565)
nextState Varint = Varint(2)
protocolVersion Varint = Varint(775)
serverAddress String = String(c.hostname)
serverPort UnsignedShort = UnsignedShort(25565)
nextState Varint = Varint(2)
)
host, portString, err := net.SplitHostPort(c.c.RemoteAddr().String())
@@ -120,37 +110,11 @@ func (c *clientConn) handshake() error {
}
}
err = writePacket(c.writer, handshakeServerboundIntention, &protocolNumber, &serverAddress, &serverPort, &nextState)
err = writePacket(c.writer, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState)
if err != nil {
return fmt.Errorf("write handshake packet: %w", err)
}
// The session server keeps a single server id per profile: only the last
// /join answers hasJoined. One account is therefore one login at a time, so
// the whole exchange is serialized per account until the server has verified
// the player and answered with Login Finished. Releasing the lock after
// /join alone is not enough: a second login would overwrite the session
// while the first server is still polling hasJoined, and that server would
// disconnect with unverified_username.
//
// The lock is released as soon as the login is verified, before the startup
// padding (which takes time on purpose) so a queue of connections still
// logs in at the API's pace rather than at the peer's padding pace. A peer
// that never answers holds this account's logins until the handshake
// deadline, which is the same wait its own connection would have.
releaseLogin := func() {}
if c.yggdrasil != nil {
c.yggdrasil.loginMu.Lock()
released := false
releaseLogin = func() {
if !released {
released = true
c.yggdrasil.loginMu.Unlock()
}
}
defer releaseLogin()
}
// Login Start
var selectedProfile loginProfile
if c.yggdrasil != nil {
@@ -175,156 +139,57 @@ func (c *clientConn) handshake() error {
}
username := String(selectedProfile.Username)
err = writePacket(c.writer, c.protocol.login.serverboundLoginStart, &username, &selectedProfile.UUID)
err = writePacket(c.writer, 0x00, &username, &selectedProfile.UUID)
if err != nil {
return fmt.Errorf("write login start: %w", err)
}
// From here the server drives the login: Encryption Request, then optionally
// Set Compression, then Login Finished; queries and cookie requests can
// appear at any point between them, so the client loops over the login
// packets like a vanilla one instead of expecting a fixed sequence.
//
// The encryption exchange is mandatory. XMC exists to look like a licensed
// player joining an online-mode server (with a third-party API in Yggdrasil
// mode), and an offline-mode login skips the encryption request entirely, so
// there is nothing to reproduce and nothing to authenticate.
handledEncryption := false
joinedSession := false
for {
pkt, readErr := readPacket(c.reader)
if readErr != nil {
return fmt.Errorf("read login packet: %w", readErr)
}
switch pkt.packetID {
case c.protocol.login.clientboundHello:
if handledEncryption {
return fmt.Errorf("duplicate encryption request")
}
handledEncryption = true
updatedProfile, joined, helloErr := c.handleEncryptionRequest(pkt, selectedProfile)
if helloErr != nil {
return helloErr
}
selectedProfile = updatedProfile
joinedSession = joined
case c.protocol.login.clientboundLoginCompression:
// Set Compression is not compressed itself and must be handled before
// the packet that follows it, which already uses the compressed
// framing. The threshold only decides whether the framing applies:
// this writer never compresses, so a server-side threshold does not
// shrink padding turns.
var threshold Varint
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
}
if threshold >= 0 {
c.reader = newCompressionReader(c.reader)
c.writer = newCompressionWriter(c.writer)
}
case c.protocol.login.clientboundCustomQuery:
// A vanilla 26.x client answers a login query with a null payload: the
// server-driven login extensions of older versions are gone, and a
// server that still asks gets an explicit "no answer".
if answerErr := c.answerCustomQuery(pkt); answerErr != nil {
return answerErr
}
case c.protocol.login.clientboundCookieRequest:
if answerErr := c.answerCookieRequest(pkt); answerErr != nil {
return answerErr
}
case c.protocol.login.clientboundLoginDisconnect:
var reason String
if readErr := pkt.readFields(&reason); readErr != nil {
return fmt.Errorf("authentication rejected")
}
if isProtocolVersionReject(string(reason)) {
forgetProbedVersions()
}
return fmt.Errorf("authentication rejected: %s", reason)
case c.protocol.login.clientboundLoginFinished:
if !handledEncryption {
return fmt.Errorf("server finished the login without an encryption request: offline-mode servers are not supported")
}
receivedProfile, finishErr := c.readLoginFinished(pkt)
if finishErr != nil {
return fmt.Errorf("read login finished fields: %w", finishErr)
}
// Login Finished is written only after the server's hasJoined
// succeeded, so the session is verified and the next login for this
// account may join.
releaseLogin()
if verifyErr := c.verifyLoginProfile(receivedProfile, selectedProfile, joinedSession); verifyErr != nil {
return verifyErr
}
selectedProfile = receivedProfile
loginAcknowledgedLength, writeErr := writePacketWithLength(c.writer, c.protocol.login.serverboundLoginAcknowledged)
if writeErr != nil {
return fmt.Errorf("write login acknowledged: %w", writeErr)
}
return c.startProxy(loginAcknowledgedLength)
default:
return fmt.Errorf("unexpected login packet: 0x%02x", pkt.packetID)
}
// Encryption Request
pkt, err := readPacket(c.reader)
if err != nil {
return fmt.Errorf("read encryption request: %w", err)
}
if pkt.packetID != 0x01 {
return fmt.Errorf("bad encrypt request packet id")
}
}
// handleEncryptionRequest performs the shared-secret exchange and reports the
// session profile plus whether the session server was joined, which decides how
// strictly the returned game profile can be checked.
func (c *clientConn) handleEncryptionRequest(pkt *mcPacket, profile loginProfile) (loginProfile, bool, error) {
var (
serverId String
publicKey Bytes
verifyToken Bytes
shouldAuthenticate Boolean
serverId String
publicKey Bytes
verifyToken Bytes
)
err := pkt.readFields(&serverId, &publicKey, &verifyToken, &shouldAuthenticate)
err = pkt.readFields(&serverId, &publicKey, &verifyToken)
if err != nil {
return profile, false, fmt.Errorf("read encryption request fields: %w", err)
}
// shouldAuthenticate is false for an offline-mode server that still encrypts.
// XMC only reproduces the online-mode login, so the client does not pretend
// to authenticate against it.
if c.yggdrasil != nil && !shouldAuthenticate {
return profile, false, fmt.Errorf("server asked the client not to authenticate: offline-mode servers are not supported")
return fmt.Errorf("read encryption request fields: %w", err)
}
if c.yggdrasil == nil && !bytes.Equal(publicKey, c.rsaPublicKey) {
return profile, false, fmt.Errorf("server public key mismatch")
return fmt.Errorf("server public key mismatch")
}
k, err := x509.ParsePKIXPublicKey(publicKey)
if err != nil {
return profile, false, fmt.Errorf("parse server public key: %w", err)
return fmt.Errorf("parse server public key: %w", err)
}
rsaPublicKey, ok := k.(*rsa.PublicKey)
if !ok {
return profile, false, fmt.Errorf("parse server public key: not rsa")
return fmt.Errorf("parse server public key: not rsa")
}
if rsaPublicKey.N.BitLen() < 1024 {
return profile, false, fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen())
return fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen())
}
sharedSecret := make([]byte, 16)
if _, err = rand.Read(sharedSecret); err != nil {
return profile, false, fmt.Errorf("generate shared secret: %w", err)
return fmt.Errorf("generate shared secret: %w", err)
}
encryptedSharedSecret, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, sharedSecret)
if err != nil {
return profile, false, fmt.Errorf("encrypt shared secret: %w", err)
return fmt.Errorf("encrypt shared secret: %w", err)
}
if c.yggdrasil == nil {
@@ -333,132 +198,107 @@ func (c *clientConn) handleEncryptionRequest(pkt *mcPacket, profile loginProfile
encryptedVerifyToken, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, verifyToken)
if err != nil {
return profile, false, fmt.Errorf("encrypt verify token: %w", err)
return fmt.Errorf("encrypt verify token: %w", err)
}
// Send Encryption Response, then switch the ciphers on: vanilla starts
// encrypting only after the response itself has been written.
// Send Encryption Response
err = writePacket(
c.writer,
c.protocol.login.serverboundKey,
0x01,
(*Bytes)(&encryptedSharedSecret),
(*Bytes)(&encryptedVerifyToken),
)
if err != nil {
return profile, false, fmt.Errorf("write encryption response: %w", err)
return fmt.Errorf("write encryption response: %w", err)
}
// Enable encryption
c.reader, err = newCryptoReader(c.reader, sharedSecret)
if err != nil {
return profile, false, fmt.Errorf("new crypto reader: %w", err)
return fmt.Errorf("new crypto reader: %w", err)
}
c.writer, err = newCryptoWriter(c.writer, sharedSecret)
if err != nil {
return profile, false, fmt.Errorf("new crypto writer: %w", err)
return fmt.Errorf("new crypto writer: %w", err)
}
// Online mode: join the session with the digest of the handshake data so the
// server can verify it through hasJoined. The password mode has no session
// server; its login is authenticated by the pre-shared password instead.
if c.yggdrasil == nil {
return profile, false, nil
if c.yggdrasil != nil {
// Standard online-mode login: join the session with the hash of the
// handshake data, the server verifies it through hasJoined.
serverID := minecraftServerID(string(serverId), sharedSecret, publicKey)
token, joinErr := c.yggdrasil.join(context.Background(), serverID)
if joinErr != nil {
return fmt.Errorf("yggdrasil session join: %w", joinErr)
}
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
if uuidErr != nil {
return fmt.Errorf("yggdrasil session join: %w", uuidErr)
}
selectedProfile = loginProfile{
Username: token.profile.Name,
UUID: profileUUID,
}
}
serverID := minecraftServerID(string(serverId), sharedSecret, publicKey)
token, joinErr := c.yggdrasil.join(context.Background(), serverID)
if joinErr != nil {
return profile, false, fmt.Errorf("yggdrasil session join: %w", joinErr)
pkt, err = readPacket(c.reader)
if err != nil {
return fmt.Errorf("read login finished: %w", err)
}
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
if uuidErr != nil {
return profile, false, fmt.Errorf("yggdrasil session join: %w", uuidErr)
// Set Compression is not compressed itself and must be handled before the
// packet that follows it, which already uses the compressed framing. The
// threshold only decides whether the framing applies: this writer never
// compresses, so a server-side threshold does not shrink padding turns.
if pkt.packetID == 0x03 {
var threshold Varint
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
}
if threshold >= 0 {
c.reader = newCompressionReader(c.reader)
c.writer = newCompressionWriter(c.writer)
}
pkt, err = readPacket(c.reader)
if err != nil {
return fmt.Errorf("read login finished: %w", err)
}
}
if pkt.packetID == 0x00 {
var reason String
if readErr := pkt.readFields(&reason); readErr != nil {
return fmt.Errorf("authentication rejected")
}
return fmt.Errorf("authentication rejected: %s", reason)
}
if pkt.packetID != 0x02 {
return fmt.Errorf("bad login finished packet id: %d", pkt.packetID)
}
return loginProfile{Username: token.profile.Name, UUID: profileUUID}, true, nil
}
// answerCustomQuery replies to a login query with a null payload, which is what
// a vanilla 26.x client sends.
func (c *clientConn) answerCustomQuery(pkt *mcPacket) error {
var transactionID Varint
if err := pkt.readFields(&transactionID); err != nil {
return fmt.Errorf("read login query: %w", err)
receivedProfile, err := readLoginSuccess(pkt)
if err != nil {
return fmt.Errorf("read login finished fields: %w", err)
}
// The answer payload is nullable; a vanilla 26.x client leaves it absent.
answered := Boolean(false)
if err := writePacket(c.writer, c.protocol.login.serverboundCustomQueryAnswer, &transactionID, &answered); err != nil {
return fmt.Errorf("write login query answer: %w", err)
}
return nil
}
// answerCookieRequest replies with an absent cookie, like a client that has
// never received a cookie for the key.
func (c *clientConn) answerCookieRequest(pkt *mcPacket) error {
var key String
if err := pkt.readFields(&key); err != nil {
return fmt.Errorf("read login cookie request: %w", err)
}
// The cookie is nullable; an absent value means "no cookie for this key".
answered := Boolean(false)
if err := writePacket(c.writer, c.protocol.login.serverboundCookieResponse, &key, &answered); err != nil {
return fmt.Errorf("write login cookie response: %w", err)
}
return nil
}
// readLoginFinished reads the game profile and, from 26.2 on, the connection
// session id that follows it. Trailing bytes are ignored on purpose: Mojang has
// appended a field to this packet before, and a client that needs an exact
// length would stop pairing on the next release.
func (c *clientConn) readLoginFinished(pkt *mcPacket) (loginProfile, error) {
var (
profile loginProfile
username String
)
fields := []field{&profile.UUID, &username, &profile.Properties}
if c.protocol.loginFinishedSessionID {
var sessionID UUID
fields = append(fields, &sessionID)
}
if err := pkt.readFields(fields...); err != nil {
return loginProfile{}, err
}
profile.Username = string(username)
return profile, nil
}
// verifyLoginProfile checks the profile the server returned. A session join
// pins the identity to the Yggdrasil account and its signed textures; the
// pre-shared password mode compares the configured profile; an offline-mode
// server derives the profile from the name, so it is accepted as it is.
func (c *clientConn) verifyLoginProfile(received, selected loginProfile, joinedSession bool) error {
switch {
case joinedSession:
if !sameProfileIdentity(received, selected) {
if c.yggdrasil != nil {
if !sameProfileIdentity(receivedProfile, selectedProfile) {
return fmt.Errorf("login profile mismatch")
}
if err := c.yggdrasil.verifyLoginProfile(received); err != nil {
return fmt.Errorf("verify login profile: %w", err)
}
case c.yggdrasil == nil:
if !sameLoginProfile(received, selected) {
return fmt.Errorf("login profile mismatch")
if verifyErr := c.yggdrasil.verifyLoginProfile(receivedProfile); verifyErr != nil {
return fmt.Errorf("verify login profile: %w", verifyErr)
}
} else if !sameLoginProfile(receivedProfile, selectedProfile) {
return fmt.Errorf("login profile mismatch")
}
return nil
}
// startProxy runs the startup padding and hands the connection to the tick
// stream. It is called once the login reached the configuration state.
func (c *clientConn) startProxy(loginAcknowledgedLength int) error {
c.reader = newPaddingReader(c.reader, true, c.paddingChannel, c.protocol.configuration)
if err := runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause, c.paddingChannel, c.protocol.configuration); err != nil {
loginAcknowledgedLength, err := writePacketWithLength(c.writer, 0x03)
if err != nil {
return fmt.Errorf("write login acknowledged: %w", err)
}
c.reader = newPaddingReader(c.reader, true)
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil {
_ = c.Close() // Unblock the startup reader if writing failed.
return fmt.Errorf("run startup padding: %w", err)
}
packet := newTickStream(c.reader, c.writer, true, c.protocol.configuration, c.dataChannel, c.paddingChannel)
packet := newPacketStream(c.reader, c.writer, true)
c.lifecycleMu.Lock()
if c.closed {
c.lifecycleMu.Unlock()
@@ -499,10 +339,6 @@ func (c *clientConn) Close() error {
c.lifecycleMu.Unlock()
c.closeOnce.Do(func() { close(c.done) })
if packet != nil {
// Write returns once data is queued for the next tick, so a graceful
// close has to flush the last tick instead of dropping it.
_ = c.c.SetWriteDeadline(time.Now().Add(time.Second))
_ = packet.Flush()
packet.Stop()
}
return c.c.Close()
+2 -59
View File
@@ -1,12 +1,10 @@
package xmc
import (
"context"
"fmt"
"math"
"time"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
@@ -32,49 +30,6 @@ func (c *Config) wrapClientAuth() (*yggdrasilAuth, error) {
)
}
// gameVersion resolves an explicitly configured protocol row. A configured
// value has to be a known row, because a guessed packet id breaks the login in a
// way that looks like a network failure.
func (c *Config) gameVersion() (protocolVersion, error) {
if err := ValidateProtocolVersion(c.ProtocolVersion); err != nil {
return protocolVersion{}, err
}
if c.ProtocolVersion == 0 {
return latestProtocolVersion, nil
}
version, _ := protocolVersionByNumber(Varint(c.ProtocolVersion))
return version, nil
}
// clientProtocol resolves the row the client advertises in its handshake. A
// configured protocol_version is used as-is; zero asks the peer for its status,
// because a vanilla server rejects a client that names another version, and the
// status response carries the version its login expects.
//
// The probe is cached per destination, so a normal connection pays it once in a
// while rather than on every dial. A peer that does not answer status (or is
// behind another transport) falls back to the newest row, which is what a
// client of the newest release sends.
func (c *Config) clientProtocol(dest *net.Destination, dialer *finalmask.Dialer) (protocolVersion, error) {
if err := ValidateProtocolVersion(c.ProtocolVersion); err != nil {
return protocolVersion{}, err
}
if c.ProtocolVersion != 0 {
return c.gameVersion()
}
number, name, err := detectProtocolVersion(dest, c.Hostname, dialer)
if err != nil {
errors.LogWarning(context.Background(), "XMC: cannot detect the peer's protocol version (", err, "), advertising ", latestProtocolVersion.name, " (", latestProtocolVersion.number, "); set protocolVersion to pin it")
return latestProtocolVersion, nil
}
version, ok := protocolVersionByNumber(number)
if !ok {
return protocolVersion{}, fmt.Errorf("the peer reports Minecraft %q (protocol %d), which is not in the supported table (%s); set protocolVersion to override the detection", name, number, protocolVersionRange())
}
return version, nil
}
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
profiles, err := profilesFromConfig(c.Profiles)
if err != nil {
@@ -84,14 +39,6 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
dataChannel, paddingChannel, err := c.ChannelIDs()
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
protocol, err := c.clientProtocol(dest, dialer)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
auth, err := c.wrapClientAuth()
if err != nil {
@@ -109,7 +56,7 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
rsaPublicKey = c.RsaPublicKey
}
cc, err := newClientConn(conn, protocol, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth, dataChannel, paddingChannel)
cc, err := newClientConn(conn, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
@@ -126,10 +73,6 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
dataChannel, paddingChannel, err := c.ChannelIDs()
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
var verifier *yggdrasilVerifier
if c.Yggdrasil != nil {
@@ -142,7 +85,7 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
return nil, fmt.Errorf("minecraft finalmask: empty profiles")
}
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier, dataChannel, paddingChannel)
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
+5 -44
View File
@@ -189,24 +189,9 @@ type Config struct {
Yggdrasil *Yggdrasil `protobuf:"bytes,13,opt,name=yggdrasil,proto3" json:"yggdrasil,omitempty"`
// Disables startup padding. The configuration sets this for an explicit
// empty "paddings" array, which an unset repeated field cannot express.
NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"`
// Custom payload channel that carries the tunnel byte stream, and the one
// that carries startup padding. Both ends must use the same pair; empty
// keeps the built-in default. Both are namespace:path resource locations,
// so vanilla's "minecraft" namespace is rejected: those ids belong to the
// game, and reusing one would collide with a vanilla payload.
DataChannel string `protobuf:"bytes,15,opt,name=data_channel,json=dataChannel,proto3" json:"data_channel,omitempty"`
PaddingChannel string `protobuf:"bytes,16,opt,name=padding_channel,json=paddingChannel,proto3" json:"padding_channel,omitempty"`
// Minecraft release the client advertises in its handshake, as a network
// protocol number (for example 777 for 26.3). Zero probes the peer: the
// client asks for its status and advertises the protocol the peer reports,
// falling back to the newest version the mask knows when the peer does not
// answer (the probe result is cached per destination). Set it to skip the
// probe or to pin a version; the server always follows the version the
// client names.
ProtocolVersion uint32 `protobuf:"varint,17,opt,name=protocol_version,json=protocolVersion,proto3" json:"protocol_version,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
@@ -295,27 +280,6 @@ func (x *Config) GetNoPadding() bool {
return false
}
func (x *Config) GetDataChannel() string {
if x != nil {
return x.DataChannel
}
return ""
}
func (x *Config) GetPaddingChannel() string {
if x != nil {
return x.PaddingChannel
}
return ""
}
func (x *Config) GetProtocolVersion() uint32 {
if x != nil {
return x.ProtocolVersion
}
return 0
}
type Padding struct {
state protoimpl.MessageState `protogen:"open.v1"`
LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"`
@@ -415,7 +379,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\x03api\x18\x01 \x01(\tR\x03api\x12\x1a\n" +
"\busername\x18\x02 \x01(\tR\busername\x12\x1a\n" +
"\bpassword\x18\x03 \x01(\tR\bpassword\x12\x16\n" +
"\x06player\x18\x04 \x01(\tR\x06player\"\x92\x04\n" +
"\x06player\x18\x04 \x01(\tR\x06player\"\x9b\x03\n" +
"\x06Config\x12\x1a\n" +
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
@@ -426,10 +390,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddings\x12N\n" +
"\tyggdrasil\x18\r \x01(\v20.xray.transport.internet.finalmask.xmc.YggdrasilR\tyggdrasil\x12\x1d\n" +
"\n" +
"no_padding\x18\x0e \x01(\bR\tnoPadding\x12!\n" +
"\fdata_channel\x18\x0f \x01(\tR\vdataChannel\x12'\n" +
"\x0fpadding_channel\x18\x10 \x01(\tR\x0epaddingChannel\x12)\n" +
"\x10protocol_version\x18\x11 \x01(\rR\x0fprotocolVersionJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
"no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
"\aPadding\x12\x1d\n" +
"\n" +
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
@@ -53,21 +53,6 @@ message Config {
// Disables startup padding. The configuration sets this for an explicit
// empty "paddings" array, which an unset repeated field cannot express.
bool no_padding = 14;
// Custom payload channel that carries the tunnel byte stream, and the one
// that carries startup padding. Both ends must use the same pair; empty
// keeps the built-in default. Both are namespace:path resource locations,
// so vanilla's "minecraft" namespace is rejected: those ids belong to the
// game, and reusing one would collide with a vanilla payload.
string data_channel = 15;
string padding_channel = 16;
// Minecraft release the client advertises in its handshake, as a network
// protocol number (for example 777 for 26.3). Zero probes the peer: the
// client asks for its status and advertises the protocol the peer reports,
// falling back to the newest version the mask knows when the peer does not
// answer (the probe result is cached per destination). Set it to skip the
// probe or to pin a version; the server always follows the version the
// client names.
uint32 protocol_version = 17;
}
message Padding {
@@ -16,10 +16,10 @@ func TestClientRejectsLongLegacyPassword(t *testing.T) {
profiles := []loginProfile{{Username: "TestUser"}}
publicKey := []byte{0x01}
if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err != nil {
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil); err != nil {
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
}
if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err == nil {
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil); err == nil {
t.Fatal("expected the long password to be rejected")
}
}
@@ -130,7 +130,7 @@ func TestCloseCancelsPaddingPause(t *testing.T) {
client, server := net.Pipe()
defer server.Close()
conn, err := newClientConn(client, latestProtocolVersion, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel)
conn, err := newClientConn(client, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil)
if err != nil {
t.Fatal(err)
}
+1 -11
View File
@@ -1,7 +1,6 @@
package xmc
import (
"bytes"
"crypto/rsa"
"crypto/sha256"
"fmt"
@@ -14,16 +13,9 @@ type sha256Stream struct {
buf []byte
}
// newSHA256Stream returns a stream seeded with a private copy of seed. The
// seed is hashed lazily on every refill, so retaining the caller's slice lets a
// later append on the same base array rewrite an already-created stream.
// DeriveRSAKey builds "<password>-p-prime" and "<password>-q-prime" from one
// password buffer: with a shared array the second append overwrote the first
// stream's seed, both primes then came from the "-q-prime" stream, and the
// resulting N factored at the first step of Fermat's method.
func newSHA256Stream(seed []byte) *sha256Stream {
return &sha256Stream{
seed: bytes.Clone(seed),
seed: seed,
}
}
@@ -64,8 +56,6 @@ func derivePrime(stream *sha256Stream) *big.Int {
func DeriveRSAKey(password string) (*rsa.PrivateKey, error) {
seed := []byte(password)
// Both appends may write into seed's spare capacity; that is harmless
// because each stream keeps its own copy of the bytes it was given.
pStream := newSHA256Stream(append(seed, []byte("-p-prime")...))
qStream := newSHA256Stream(append(seed, []byte("-q-prime")...))
@@ -1,241 +0,0 @@
package xmc
import (
"bytes"
"crypto/rsa"
"crypto/sha256"
"encoding/hex"
"fmt"
"math/big"
"strings"
"sync"
"testing"
)
// fermatFactorsInOneStep reports whether the public modulus alone discloses the
// private key. One iteration of Fermat's method yields a square exactly when N
// is the product of two primes with a small gap, which is what happens when p
// and q are derived from the same stream (p == q repaired by stepping q to the
// next prime).
func fermatFactorsInOneStep(n *big.Int) bool {
a := new(big.Int).Sqrt(n)
a.Add(a, big.NewInt(1))
b2 := new(big.Int).Sub(new(big.Int).Mul(a, a), n)
if b2.Sign() < 0 {
return false
}
b := new(big.Int).Sqrt(b2)
return new(big.Int).Mul(b, b).Cmp(b2) == 0
}
func requireUsableKey(t *testing.T, password string) *rsa.PrivateKey {
t.Helper()
key, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("DeriveRSAKey(%q): %v", password, err)
}
if key.N.BitLen() != 1024 {
t.Fatalf("%q: N is %d bits, want 1024", password, key.N.BitLen())
}
if key.E != 65537 {
t.Fatalf("%q: E is %d, want 65537", password, key.E)
}
if len(key.Primes) != 2 {
t.Fatalf("%q: got %d primes, want 2", password, len(key.Primes))
}
if key.Primes[0].Cmp(key.Primes[1]) == 0 {
t.Fatalf("%q (%d bytes): p == q", password, len(password))
}
if fermatFactorsInOneStep(key.N) {
t.Fatalf("%q (%d bytes): N factors at the first Fermat step, p and q are neighbouring primes", password, len(password))
}
if got := new(big.Int).Mul(key.Primes[0], key.Primes[1]); got.Cmp(key.N) != 0 {
t.Fatalf("%q: p*q != N", password)
}
return key
}
// TestNewSHA256StreamOwnsItsSeed is the direct regression test for the aliasing
// defect: the stream hashes its seed on every refill, so it must not retain a
// slice whose backing array a caller may still append to.
func TestNewSHA256StreamOwnsItsSeed(t *testing.T) {
password := []byte(strings.Repeat("k", 100))
// Mimic []byte(password) handing out a buffer with spare capacity, which is
// what made the two DeriveRSAKey appends overlap in the first place.
shared := make([]byte, len(password), len(password)+2*32)
copy(shared, password)
pStream := newSHA256Stream(append(shared, []byte("-p-prime")...))
qStream := newSHA256Stream(append(shared, []byte("-q-prime")...))
if bytes.HasSuffix(pStream.seed, []byte("-q-prime")) {
t.Fatalf("p stream seed was rewritten by the q stream's append: %q", pStream.seed)
}
if !bytes.HasPrefix(pStream.seed, password) || !bytes.HasSuffix(pStream.seed, []byte("-p-prime")) {
t.Fatalf("p stream seed = %q, want <password>-p-prime", pStream.seed)
}
if !bytes.HasPrefix(qStream.seed, password) || !bytes.HasSuffix(qStream.seed, []byte("-q-prime")) {
t.Fatalf("q stream seed = %q, want <password>-q-prime", qStream.seed)
}
if &pStream.seed[0] == &qStream.seed[0] {
t.Fatal("both streams share one backing array")
}
// Whatever happens to the caller's buffer afterwards, the streams are fixed.
for i := range shared {
shared[i] = 'z'
}
if !bytes.HasPrefix(pStream.seed, password) || !bytes.HasPrefix(qStream.seed, password) {
t.Fatal("stream seed follows the caller's buffer after construction")
}
}
func referenceStreamBytes(seed string, blocks int) []byte {
out := make([]byte, 0, blocks*sha256.Size)
for i := 0; i < blocks; i++ {
h := sha256.New()
h.Write([]byte(seed))
fmt.Fprintf(h, "-%d", i)
out = append(out, h.Sum(nil)...)
}
return out
}
func TestSHA256StreamMatchesReference(t *testing.T) {
for _, seed := range []string{
"",
"password",
strings.Repeat("a", 113),
"00000000-0000-0000-0000-000000000000-p-prime",
} {
got := make([]byte, 3*sha256.Size)
if _, err := newSHA256Stream([]byte(seed)).Read(got); err != nil {
t.Fatalf("seed %q: %v", seed, err)
}
want := referenceStreamBytes(seed, 3)
if !bytes.Equal(got, want) {
t.Fatalf("seed %q: keystream mismatch", seed)
}
}
}
// TestDeriveRSAKeyAllPasswordLengths sweeps every password length the login
// accepts. Lengths whose allocation rounded up left spare capacity for the
// "-p-prime"/"-q-prime" appends (33-40, 49-56, 65-72, 81-88, 97-104, 113 at the
// time of the fix), but the whole range is checked so a change in allocator size
// classes or escape analysis cannot reintroduce the defect unnoticed.
func TestDeriveRSAKeyAllPasswordLengths(t *testing.T) {
for n := 1; n <= MaxLegacyPasswordLength; n++ {
n := n
t.Run(fmt.Sprintf("len-%03d", n), func(t *testing.T) {
requireUsableKey(t, strings.Repeat("a", n))
})
}
}
// TestDeriveRSAKeyBoundaryLengths pins the lengths next to the capacity
// boundaries where the pre-fix code switched between aliasing and reallocating.
func TestDeriveRSAKeyBoundaryLengths(t *testing.T) {
for _, n := range []int{15, 16, 17, 23, 24, 25, 31, 32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57, 63, 64, 65, 71, 72, 73, 79, 80, 81, 87, 88, 89, 95, 96, 97, 103, 104, 105, 111, 112, 113} {
n := n
t.Run(fmt.Sprintf("len-%03d", n), func(t *testing.T) {
requireUsableKey(t, strings.Repeat("b", n))
})
}
}
// TestDeriveRSAKeyNonASCIIPasswords covers multi-byte passwords: the affected
// ranges are byte lengths, so a 12-character CJK password is a 36-byte one.
func TestDeriveRSAKeyNonASCIIPasswords(t *testing.T) {
passwords := map[string]string{
"cjk-33-bytes": strings.Repeat("密", 11),
"cjk-36-bytes": strings.Repeat("密", 12),
"emoji-36-bytes": strings.Repeat("🔒", 9),
"mixed-utf8": "密码-Password-密码-0123456789-密码-0123",
"embedded-nul": "abc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
"all-high-bytes": strings.Repeat("\xff", 40),
"surrogate-ish-41": strings.Repeat("é", 20) + "x",
}
for name, password := range passwords {
password := password
t.Run(name, func(t *testing.T) {
t.Logf("password is %d bytes", len(password))
requireUsableKey(t, password)
})
}
}
// TestDeriveRSAKeyExtremeInputs keeps the derivation total over sizes far
// outside what the login accepts: it is called from configuration building, so
// it must not panic or depend on a particular capacity.
func TestDeriveRSAKeyExtremeInputs(t *testing.T) {
cases := map[string]string{
"empty": "",
"one-byte": "x",
"max-accepted": strings.Repeat("m", MaxLegacyPasswordLength),
"just-over-max": strings.Repeat("m", MaxLegacyPasswordLength+1),
"four-kibibytes": strings.Repeat("m", 4096),
}
for name, password := range cases {
password := password
t.Run(name, func(t *testing.T) {
requireUsableKey(t, password)
})
}
}
// TestDeriveRSAKeyDeterministic checks that both ends of a connection derive the
// same key, including when several goroutines build configurations at once.
func TestDeriveRSAKeyDeterministic(t *testing.T) {
const password = "00000000-0000-0000-0000-000000000000"
want := requireUsableKey(t, password).N
const workers = 8
results := make([]*big.Int, workers)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
key, err := DeriveRSAKey(password)
if err != nil {
panic(err)
}
results[i] = key.N
}(i)
}
wg.Wait()
for i, n := range results {
if n.Cmp(want) != 0 {
t.Fatalf("worker %d derived a different modulus", i)
}
}
}
// TestDeriveRSAKeyKnownAnswers pins the derivation. The key is a wire-level
// shared secret: changing it for an unaffected password would break every
// existing deployment, so the digests below must only ever change on purpose.
// The 8-, 18- and 32-byte entries are byte-identical to what the aliasing code
// derived, which is the compatibility promise of the fix; the 36- and 113-byte
// entries were the ones whose key had to change.
func TestDeriveRSAKeyKnownAnswers(t *testing.T) {
cases := []struct {
password string
nDigest string
}{
{"password", "cf683eb5c302ca70"},
{"padding-regression", "b9e1f7f9b936fb8d"},
{strings.Repeat("a", 32), "6692488374c0e7aa"},
{"00000000-0000-0000-0000-000000000000", "6d971fd64a5c0981"},
{strings.Repeat("m", MaxLegacyPasswordLength), "45b0e2f0dd483585"},
}
for _, c := range cases {
key := requireUsableKey(t, c.password)
digest := sha256.Sum256(key.N.Bytes())
got := hex.EncodeToString(digest[:8])
if got != c.nDigest {
t.Fatalf("%d-byte password: N digest %s, want %s (wire-compatibility break)", len(c.password), got, c.nDigest)
}
}
}
@@ -1,647 +0,0 @@
package xmc
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"io"
"math/big"
"net"
"strings"
"sync"
"testing"
"time"
)
// The Encryption Response is the one place where a peer can get an answer out of
// the mask before it holds any secret, so every check on it has to be
// indistinguishable from every other. These tests drive the real serverConn.login
// over a scripted stream, so what the peer writes and what the server answers are
// both exact and no socket timing is involved.
// scriptedServer is one XMC server whose login a test drives packet by packet.
type scriptedServer struct {
t *testing.T
key *rsa.PrivateKey
conn *serverConn
reader *feedReader
writer *syncWriter
challenge []byte
// requestLength is how many bytes the Encryption Request occupied, so the
// answer (everything after it) can be decrypted on its own.
requestLength int
// respond feeds one Encryption Response and returns the server's answer.
respond func(sharedSecret, verifyToken []byte) loginOutcome
}
// loginOutcome is what a peer observes after it wrote one Encryption Response:
// the bytes the server sent back and the error login() ended with.
type loginOutcome struct {
answer []byte
err error
}
// newScriptedServer runs login() up to the Encryption Response. The peer sends
// the Login Start a client would and reads the Encryption Request back.
func newScriptedServer(t *testing.T, password string, profiles []loginProfile) *scriptedServer {
t.Helper()
return newScriptedServerAs(t, password, profiles, profiles[0].Username, profiles[0].UUID)
}
// newScriptedServerAs is newScriptedServer for a peer that logs in as a name the
// profile list does not contain, which is how the whitelist rejection is reached.
func newScriptedServerAs(t *testing.T, password string, profiles []loginProfile, loginName string, loginUUID UUID) *scriptedServer {
t.Helper()
key, err := DeriveRSAKey("oracle-test-password")
if err != nil {
t.Fatal(err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatal(err)
}
var inbound bytes.Buffer
if err := writePacket(&inbound, latestProtocolVersion.login.serverboundLoginStart, new(String(loginName)), &loginUUID); err != nil {
t.Fatal(err)
}
s := &scriptedServer{
t: t,
key: key,
reader: newFeedReader(inbound.Bytes()),
writer: &syncWriter{},
}
s.conn = &serverConn{
reader: s.reader,
c: &discardConn{},
state: serverStateHandshake,
protocol: latestProtocolVersion,
profiles: profiles,
password: password,
rsaPrivateKey: key,
rsaPublicKey: publicKey,
dataChannel: DefaultDataChannel,
paddingChannel: DefaultPaddingChannel,
deadlines: newConnectionDeadlines(&discardConn{}),
done: make(chan struct{}),
yggdrasil: nil,
paddingSchedule: nil,
}
// The Encryption Request goes straight to the peer's socket, so it lands in
// the same buffer the encrypted answer will.
s.conn.writer = s.writer
loginDone := make(chan error, 1)
go func() { loginDone <- s.conn.login() }()
// The Encryption Request is one packet and the server writes it as it goes;
// wait until it is fully there instead of reading a writer that is still
// being filled.
deadline := time.Now().Add(10 * time.Second)
for {
// A frame that decoded fully is the only reliable signal that the
// server has written all of it; counting frames would accept a
// half-written one.
if frames, ok := decodeAllPackets(s.writer.snapshot()); ok && frames == 1 {
break
}
if time.Now().After(deadline) {
select {
case loginErr := <-loginDone:
t.Fatalf("login returned before the encryption request: %v (wrote % x)", loginErr, s.writer.snapshot())
default:
}
t.Fatalf("the server did not write the encryption request: % x", s.writer.snapshot())
}
time.Sleep(time.Millisecond)
}
// Parse the Encryption Request from a snapshot: the buffer keeps every byte
// the server writes, later answers included.
written := s.writer.snapshot()
s.requestLength = countFrameBytes(written)
request, err := readPacket(bytes.NewReader(written))
if err != nil {
t.Fatalf("read encryption request: %v", err)
}
if request.packetID != latestProtocolVersion.login.clientboundHello {
t.Fatalf("login packet id = 0x%02x, want the encryption request", request.packetID)
}
var (
serverID String
publicKeyField Bytes
verifyToken Bytes
shouldAuthenticate Boolean
)
if err := request.readFields(&serverID, &publicKeyField, &verifyToken, &shouldAuthenticate); err != nil {
t.Fatalf("read encryption request fields: %v", err)
}
s.challenge = verifyToken
// Feed the Encryption Response when the peer answers, and collect the
// server's reply afterwards.
s.respond = func(sharedSecret, verifyToken []byte) loginOutcome {
sharedField := Bytes(append([]byte(nil), sharedSecret...))
tokenField := Bytes(append([]byte(nil), verifyToken...))
frame, err := encodePacket(latestProtocolVersion.login.serverboundKey, &sharedField, &tokenField)
if err != nil {
t.Fatalf("encode encryption response: %v", err)
}
s.reader.feed(frame)
return s.await(loginDone)
}
return s
}
// await waits for login() to return and returns everything the server wrote.
func (s *scriptedServer) await(done <-chan error) loginOutcome {
s.t.Helper()
select {
case err := <-done:
return loginOutcome{answer: s.answer(), err: err}
case <-time.After(20 * time.Second):
s.t.Fatal("login did not return")
return loginOutcome{}
}
}
// validToken builds the second block a password-mode client sends: the challenge
// followed by the password, encrypted with the server's public key.
func (s *scriptedServer) validToken(password string) []byte {
s.t.Helper()
plaintext := append(append([]byte(nil), s.challenge...), []byte(password)...)
return s.encrypt(plaintext)
}
// encrypt builds one PKCS#1 v1.5 block with the public key, exactly as a client
// does with Cipher.getInstance("RSA"). The ciphertext is emitted in its shortest
// form, so the tests also cover a peer whose implementation does not write the
// full modulus width.
func (s *scriptedServer) encrypt(plaintext []byte) []byte {
s.t.Helper()
k := s.key.Size()
if len(plaintext) > k-11 {
s.t.Fatalf("plaintext of %d bytes does not fit a %d-byte block", len(plaintext), k)
}
em := make([]byte, k)
em[1] = 0x02
padding := em[2 : k-1-len(plaintext)]
if _, err := io.ReadFull(rand.Reader, padding); err != nil {
s.t.Fatal(err)
}
for i := range padding {
for padding[i] == 0 {
if _, err := io.ReadFull(rand.Reader, padding[i:i+1]); err != nil {
s.t.Fatal(err)
}
}
}
copy(em[k-len(plaintext):], plaintext)
m := new(big.Int).SetBytes(em)
c := new(big.Int).Exp(m, big.NewInt(int64(s.key.E)), s.key.N)
return c.Bytes()
}
// answer returns everything the server wrote after the Encryption Request.
func (s *scriptedServer) answer() []byte {
written := s.writer.snapshot()
if s.requestLength > len(written) {
return nil
}
return append([]byte(nil), written[s.requestLength:]...)
}
// decryptDisconnect decrypts the answer with the session key the test chose and
// returns the reason of the Login Disconnect inside it. Every server in these
// tests closes with that packet, so a peer that holds the key sees exactly this.
func (s *scriptedServer) decryptDisconnect(answer, sessionKey []byte) string {
s.t.Helper()
block, err := newAESCipher(sessionKey)
if err != nil {
s.t.Fatal(err)
}
plaintext := make([]byte, len(answer))
newCFB8Decrypt(block, sessionKey).XORKeyStream(plaintext, answer)
packet, err := readPacket(bytes.NewReader(plaintext))
if err != nil {
s.t.Fatalf("decrypt answer: %v (plaintext % x)", err, plaintext)
}
if packet.packetID != latestProtocolVersion.login.clientboundLoginDisconnect {
s.t.Fatalf("packet id in the encrypted answer = 0x%02x, want a login disconnect", packet.packetID)
}
var reason String
if err := packet.readFields(&reason); err != nil {
s.t.Fatalf("read disconnect reason: %v", err)
}
return string(reason)
}
// decodeAllPackets counts the packets a byte stream holds and reports whether
// the stream ended on a packet boundary and every packet decoded. A single
// frame that grows while it is being written therefore reports ok == false.
func decodeAllPackets(data []byte) (int, bool) {
frames := 0
rest := data
for len(rest) > 0 {
var length int
size := 0
for {
if size >= len(rest) {
return frames, false
}
b := rest[size]
length |= int(b&0x7f) << (7 * size)
size++
if b&0x80 == 0 {
break
}
}
if size+length > len(rest) {
return frames, false
}
if _, err := readPacket(bytes.NewReader(rest[:size+length])); err != nil {
return frames, false
}
rest = rest[size+length:]
frames++
}
return frames, true
}
// syncWriter is the peer's socket: login() writes to it from its own goroutine
// while the test reads, so every access is under one lock.
type syncWriter struct {
mu sync.Mutex
buf bytes.Buffer
}
func (w *syncWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.buf.Write(p)
}
func (w *syncWriter) snapshot() []byte {
w.mu.Lock()
defer w.mu.Unlock()
return append([]byte(nil), w.buf.Bytes()...)
}
// feedReader hands a running login() the bytes the peer writes, one feed at a
// time, which a bytes.Reader cannot do once login() holds it.
type feedReader struct {
mu sync.Mutex
cond *sync.Cond
pending []byte
closed bool
}
func newFeedReader(initial []byte) *feedReader {
r := &feedReader{pending: append([]byte(nil), initial...)}
r.cond = sync.NewCond(&r.mu)
return r
}
func (r *feedReader) feed(data []byte) {
r.mu.Lock()
defer r.mu.Unlock()
r.pending = append(r.pending, data...)
r.cond.Broadcast()
}
func (r *feedReader) Read(p []byte) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
for len(r.pending) == 0 && !r.closed {
r.cond.Wait()
}
if len(r.pending) == 0 {
return 0, io.EOF
}
n := copy(p, r.pending)
r.pending = r.pending[n:]
return n, nil
}
// discardConn satisfies net.Conn for a scripted server that never blocks.
type discardConn struct{}
func (discardConn) Read([]byte) (int, error) { return 0, io.EOF }
func (discardConn) Write(p []byte) (int, error) { return len(p), nil }
func (discardConn) Close() error { return nil }
func (discardConn) LocalAddr() net.Addr { return nil }
func (discardConn) RemoteAddr() net.Addr { return nil }
func (discardConn) SetDeadline(time.Time) error { return nil }
func (discardConn) SetReadDeadline(time.Time) error { return nil }
func (discardConn) SetWriteDeadline(time.Time) error { return nil }
// TestEncryptionResponseBadSecretIsRandom checks the fallback itself: a block
// that does not unpad to exactly sixteen bytes must leave a random secret, not a
// truncated one and not the bytes the peer sent.
func TestEncryptionResponseBadSecretIsRandom(t *testing.T) {
s := newScriptedServer(t, "right-password", []loginProfile{{Username: "TestUser"}})
bad := s.encrypt(make([]byte, aesKeyLength))
bad[0] ^= 0xff
seen := make(map[string]bool)
for range 8 {
secret, block, ok := s.conn.decryptSharedSecret(bad)
if !ok || block == nil {
t.Fatal("a bad block must still yield a session key to carry on with")
}
seen[string(secret)] = true
}
if len(seen) < 2 {
t.Fatal("every bad block produced the same session key; the fallback is not random")
}
// A block that unpads to the wrong length must take the same fallback. The
// plaintext is not a session key, so it must not be used as one.
for _, length := range []int{0, 1, 15, 17, 117} {
short := s.encrypt(make([]byte, length))
first, _, ok := s.conn.decryptSharedSecret(short)
if !ok {
t.Fatalf("%d-byte message: no session key", length)
}
second, _, ok := s.conn.decryptSharedSecret(short)
if !ok {
t.Fatalf("%d-byte message: no session key", length)
}
if bytes.Equal(first, second) {
t.Fatalf("%d-byte message: the fallback secret repeats", length)
}
if len(first) != aesKeyLength {
t.Fatalf("%d-byte message: secret is %d bytes", length, len(first))
}
}
secret, _, ok := s.conn.decryptSharedSecret(s.encrypt(make([]byte, aesKeyLength)))
if !ok || !bytes.Equal(secret, make([]byte, aesKeyLength)) {
t.Fatalf("a valid block did not yield its plaintext: %x", secret)
}
}
// TestEncryptionResponseDoesNotRevealPadding is the regression test for
// GHSA-ggm8-658p-x4mr. The pre-fix server called rsa.DecryptPKCS1v15 and
// returned before installing CFB8 when the padding or the plaintext length was
// wrong, so an invalid block closed the connection with no answer while a valid
// one got an encrypted Login Disconnect: one oracle bit per attempt against a
// static, public RSA key. The fixed server carries on with a random secret, so
// every one of these blocks must produce an answer of exactly the same length as
// the block a peer can verify, and none of them may be rejected before the
// cipher is installed.
func TestEncryptionResponseDoesNotRevealPadding(t *testing.T) {
profiles := []loginProfile{{Username: "TestUser"}}
password := "right-password"
// Baseline: a well-formed block the peer chose the plaintext of, so it can
// decrypt the answer. The password is wrong, which is what an oracle query
// uses to make the server reach its single rejection.
baselineServer := newScriptedServer(t, password, profiles)
baseline := baselineServer.respond(baselineServer.encrypt(make([]byte, aesKeyLength)), baselineServer.validToken("wrong-password"))
if baseline.err == nil {
t.Fatal("the encryption response with a wrong password was accepted")
}
if len(baseline.answer) == 0 {
t.Fatal("a valid block with a wrong password was not answered inside the encrypted stream")
}
if reason := baselineServer.decryptDisconnect(baseline.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "authservers_down") {
t.Fatalf("baseline disconnect reason = %s", reason)
}
want := len(baseline.answer)
blocks := []struct {
name string
make func(*scriptedServer) []byte
}{
{"valid padding, empty message", func(s *scriptedServer) []byte { return s.encrypt(nil) }},
{"valid padding, one-byte message", func(s *scriptedServer) []byte { return s.encrypt([]byte{1}) }},
{"valid padding, fifteen-byte message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, 15)) }},
{"valid padding, seventeen-byte message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, 17)) }},
{"valid padding, longest message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, s.key.Size()-11)) }},
{"ciphertext zero", func(s *scriptedServer) []byte { return make([]byte, s.key.Size()) }},
{"ciphertext one", func(s *scriptedServer) []byte {
block := make([]byte, s.key.Size())
block[len(block)-1] = 1
return block
}},
{"ciphertext equal to the modulus", func(s *scriptedServer) []byte {
return s.key.N.FillBytes(make([]byte, s.key.Size()))
}},
{"empty field", func(*scriptedServer) []byte { return nil }},
{"field longer than the modulus", func(*scriptedServer) []byte {
block := make([]byte, 1023)
if _, err := rand.Read(block); err != nil {
t.Fatal(err)
}
return block
}},
}
var fallbackCiphertexts [][]byte
for _, tc := range blocks {
t.Run(tc.name, func(t *testing.T) {
s := newScriptedServer(t, password, profiles)
out := s.respond(tc.make(s), s.validToken("wrong-password"))
if out.err == nil {
t.Fatal("the encryption response was accepted")
}
if strings.Contains(out.err.Error(), "verify token mismatch") {
t.Fatalf("the block was rejected before the cipher was installed: %v", out.err)
}
if len(out.answer) != want {
t.Fatalf("answer is %d bytes, want %d: the response depends on the shared-secret block", len(out.answer), want)
}
fallbackCiphertexts = append(fallbackCiphertexts, out.answer)
})
}
// The fallback secret is random per connection, so two runs of the same
// invalid block must not produce the same answer bytes.
t.Run("fallback is fresh per connection", func(t *testing.T) {
if len(fallbackCiphertexts) < 2 {
t.Fatal("not enough answers collected")
}
if bytes.Equal(fallbackCiphertexts[0], fallbackCiphertexts[1]) {
t.Fatal("the same ciphertext was sent for two random session keys")
}
})
// The shape of an adaptive query: take a ciphertext that decrypts to a
// session key and perturb it one bit at a time. Whatever padding each
// perturbation happens to produce, the answer must keep the same length.
t.Run("modified captured ciphertexts", func(t *testing.T) {
s := newScriptedServer(t, password, profiles)
captured := s.encrypt(make([]byte, aesKeyLength))
for i := range 16 {
modified := append([]byte(nil), captured...)
modified[i%len(modified)] ^= 1 << (i % 8)
query := newScriptedServer(t, password, profiles)
out := query.respond(modified, query.validToken("wrong-password"))
if out.err == nil {
t.Fatal("the modified ciphertext was accepted")
}
if len(out.answer) != want {
t.Fatalf("query %d answered %d bytes, want %d", i, len(out.answer), want)
}
}
})
}
// TestEncryptionResponseChallengeIsPubliclyCheckable pins the one difference the
// server keeps on purpose: vanilla validates the challenge before it installs
// the cipher, so a wrong challenge closes the connection unencrypted. The
// challenge is four random bytes the server sent a moment ago, so that shape
// discloses nothing.
func TestEncryptionResponseChallengeIsPubliclyCheckable(t *testing.T) {
profiles := []loginProfile{{Username: "TestUser"}}
s := newScriptedServer(t, "right-password", profiles)
wrongChallenge := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.encrypt([]byte{1, 2, 3, 4}))
if wrongChallenge.err == nil || !strings.Contains(wrongChallenge.err.Error(), "verify token mismatch") {
t.Fatalf("a wrong challenge was not rejected: %v", wrongChallenge.err)
}
if len(wrongChallenge.answer) != 0 {
t.Fatalf("a bad challenge got %d bytes back, want an unencrypted close", len(wrongChallenge.answer))
}
s = newScriptedServer(t, "right-password", profiles)
goodChallenge := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("wrong-password"))
if goodChallenge.err == nil {
t.Fatal("a wrong password was accepted")
}
if len(goodChallenge.answer) == 0 {
t.Fatal("a good challenge with a wrong password was not answered inside the encrypted stream")
}
}
// TestEncryptionResponseRejectionsAreInsideTheStream checks what a peer that
// holds the session key actually receives: a Login Disconnect, with the reason
// vanilla uses. The whitelist answer is only reachable after the password
// matched, so a guesser never sees it.
func TestEncryptionResponseRejectionsAreInsideTheStream(t *testing.T) {
t.Run("wrong password", func(t *testing.T) {
s := newScriptedServer(t, "right-password", []loginProfile{{Username: "TestUser"}})
out := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("wrong-password"))
if out.err == nil {
t.Fatal("a wrong password was accepted")
}
if reason := s.decryptDisconnect(out.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "multiplayer.disconnect.authservers_down") {
t.Fatalf("disconnect reason = %s", reason)
}
})
t.Run("unknown profile", func(t *testing.T) {
profiles := []loginProfile{{Username: "Known", UUID: UUID{9, 9, 9}}}
s := newScriptedServerAs(t, "right-password", profiles, "TestUser", UUID{1, 2, 3})
out := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("right-password"))
if out.err == nil {
t.Fatal("an unknown profile was accepted")
}
if reason := s.decryptDisconnect(out.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "not white-listed") {
t.Fatalf("disconnect reason = %s", reason)
}
// The same answer, from a peer that sent a block it cannot use, must be
// the same length: the whitelist rejection cannot become an oracle for
// the block either.
bad := newScriptedServerAs(t, "right-password", profiles, "TestUser", UUID{1, 2, 3})
badOut := bad.respond(make([]byte, bad.key.Size()), bad.validToken("right-password"))
if badOut.err == nil {
t.Fatal("an unknown profile with an invalid shared secret was accepted")
}
if len(badOut.answer) != len(out.answer) {
t.Fatalf("invalid shared secret answered %d bytes, valid one %d", len(badOut.answer), len(out.answer))
}
})
}
// TestEncryptionResponseExtremeFields checks the shapes at the edges of the two
// fields: they must fail cleanly, without a panic and without a different shape
// than any other failure, and the field-length limit itself is the only place
// where the packet is refused before decryption - which is public framing the
// peer chose.
func TestEncryptionResponseExtremeFields(t *testing.T) {
profiles := []loginProfile{{Username: "TestUser"}}
baseline := func(t *testing.T, shared, token []byte) loginOutcome {
t.Helper()
s := newScriptedServer(t, "right-password", profiles)
return s.respond(shared, token)
}
t.Run("empty token field", func(t *testing.T) {
out := baseline(t, make([]byte, 128), nil)
if out.err == nil || !strings.Contains(out.err.Error(), "verify token mismatch") {
t.Fatalf("empty token: %v", out.err)
}
if len(out.answer) != 0 {
t.Fatalf("empty token got %d bytes", len(out.answer))
}
})
t.Run("token field one byte under the packet field limit", func(t *testing.T) {
out := baseline(t, make([]byte, 128), make([]byte, 1023))
if out.err == nil || !strings.Contains(out.err.Error(), "verify token mismatch") {
t.Fatalf("oversized token: %v", out.err)
}
if len(out.answer) != 0 {
t.Fatalf("oversized token got %d bytes", len(out.answer))
}
})
t.Run("token field at the packet field limit", func(t *testing.T) {
out := baseline(t, make([]byte, 128), make([]byte, 1024))
if out.err == nil || !strings.Contains(out.err.Error(), "read encrypt response") {
t.Fatalf("token field at the limit: %v", out.err)
}
if len(out.answer) != 0 {
t.Fatalf("token field at the limit got %d bytes", len(out.answer))
}
})
t.Run("shared secret field at the packet field limit", func(t *testing.T) {
out := baseline(t, make([]byte, 1024), nil)
if out.err == nil || !strings.Contains(out.err.Error(), "read encrypt response") {
t.Fatalf("shared secret field at the limit: %v", out.err)
}
if len(out.answer) != 0 {
t.Fatalf("shared secret field at the limit got %d bytes", len(out.answer))
}
})
}
// countFrameBytes returns the byte length of the first frame in data.
func countFrameBytes(data []byte) int {
var length int
size := 0
for {
if size >= len(data) {
return len(data)
}
b := data[size]
length |= int(b&0x7f) << (7 * size)
size++
if b&0x80 == 0 {
break
}
}
return size + length
}
@@ -1,91 +0,0 @@
package xmc
import (
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/subtle"
)
const (
// aesKeyLength is the shared secret length vanilla's Crypt counts its
// cipher on, and the length an XMC client encrypts.
aesKeyLength = 16
)
// decryptSharedSecret recovers the AES shared secret and builds its cipher block
// without turning the Encryption Response into a Bleichenbacher oracle.
//
// The wire format is a bare RSA / PKCS#1 v1.5 block, because that is what a
// vanilla client writes (Crypt.encryptUsingKey -> Cipher.getInstance("RSA") ->
// doFinal) and a mask that answered anything else would stop pairing with one.
// Reading it with rsa.DecryptPKCS1v15 and acting on the error - which is what
// this server used to do - lets a peer tell a valid block from an invalid one
// without knowing the key. The key is static (derived from the password) and
// public, so a captured shared secret could then be attacked offline forever.
//
// rsa.DecryptPKCS1v15SessionKey is the RFC 3218 countermeasure, and the one the
// advisory names: a random sixteen-byte secret is chosen first, the block is
// decrypted into it, and the random value survives unless the plaintext is
// exactly sixteen bytes. The padding verdict and the length verdict are folded
// into one constant-time copy, so neither is reported; the private-key operation
// runs on the constant-time FIPS module and the padding scan is branch-free.
// Nothing downstream can branch on the padding either, because a peer that did
// not send a valid block does not learn the secret the server carries on with.
//
// The challenge block is the opposite case and keeps vanilla's behaviour; see
// decryptVerifyToken.
func (c *serverConn) decryptSharedSecret(encryptedSharedSecret []byte) ([]byte, cipher.Block, bool) {
secret := make([]byte, aesKeyLength)
if _, err := rand.Read(secret); err != nil {
return nil, nil, false
}
// An error here means the field did not decode to a number below the
// modulus: it was longer than the modulus, or equal to or above N. Both are
// properties of the peer's own bytes, not a padding verdict, and the random
// secret stands either way, so the error is dropped on purpose.
_ = rsa.DecryptPKCS1v15SessionKey(nil, c.rsaPrivateKey, encryptedSharedSecret, secret)
// A secret the AES layer cannot use cannot happen here - the buffer is
// sixteen bytes either way - but the caller must not be able to reach a
// panic through it, so it folds into the same boolean.
block, err := newAESCipher(secret)
if err != nil {
return nil, nil, false
}
return secret, block, true
}
// decryptVerifyToken recovers the challenge block. It is not a secret-bearing
// plaintext: the challenge is the four random bytes the server sent a moment
// ago, so a failed padding here discloses nothing that is not already public.
// Vanilla treats it the same way (ServerboundKeyPacket.isChallengeValid turns
// bad padding into the same protocol error a wrong challenge produces), and the
// outcome is the one difference vanilla draws too: a bad token closes the
// connection before the cipher is installed, a good one fails inside it.
//
// Unlike the shared secret this must return the whole message, because password
// mode carries the password after the challenge in the same block, so
// rsa.DecryptPKCS1v15 is the right call: its error is the public padding
// verdict vanilla already draws, and its length is not secret.
func decryptVerifyToken(key *rsa.PrivateKey, encryptedVerifyToken []byte) ([]byte, bool) {
plaintext, err := rsa.DecryptPKCS1v15(nil, key, encryptedVerifyToken)
if err != nil {
return nil, false
}
return plaintext, true
}
// challengesEqual compares the challenge the server sent with the plaintext the
// peer returned. In password mode the password follows the challenge in the same
// block, so a longer plaintext that starts with the challenge is a match;
// vanilla compares the whole plaintext, which works there because its client
// sends the challenge alone. The comparison is constant time, and only the
// length check is not, which is public data deciding a public question.
func challengesEqual(want, got []byte) bool {
if len(got) < len(want) {
return false
}
return subtle.ConstantTimeCompare(want, got[:len(want)]) == 1
}
@@ -9,22 +9,10 @@ import (
"time"
)
// TestHandshakeWithBidirectionalPadding performs the whole login for the oldest
// and the newest row: 1.21.1 has no Login Finished session id, 26.3 does, so the
// test covers both packet shapes end to end.
func TestHandshakeWithBidirectionalPadding(t *testing.T) {
for _, version := range []protocolVersion{protocolVersions[0], latestProtocolVersion} {
t.Run(version.name, func(t *testing.T) {
testHandshakeVersions(t, version)
})
}
}
func testHandshakeVersions(t *testing.T, version protocolVersion) {
t.Helper()
t.Run("pipe", func(t *testing.T) {
client, server := net.Pipe()
testHandshakeWithPadding(t, version, client, server, 64*1024)
testHandshakeWithPadding(t, client, server, 64*1024)
})
t.Run("tcp", func(t *testing.T) {
listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
@@ -50,11 +38,11 @@ func testHandshakeVersions(t *testing.T, version protocolVersion) {
t.Fatal(err)
}
}
testHandshakeWithPadding(t, version, client, server, maxPaddingTurnLength)
testHandshakeWithPadding(t, client, server, maxPaddingTurnLength)
})
}
func testHandshakeWithPadding(t *testing.T, version protocolVersion, clientRaw, serverRaw net.Conn, length int64) {
func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, length int64) {
t.Helper()
defer clientRaw.Close()
defer serverRaw.Close()
@@ -84,12 +72,12 @@ func testHandshakeWithPadding(t *testing.T, version protocolVersion, clientRaw,
if err != nil {
t.Fatal(err)
}
client, err := newClientConn(clientRaw, version, profiles, "password", publicKey, "localhost", paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel)
client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule, nil)
if err != nil {
t.Fatal(err)
}
defer client.Close()
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel)
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil)
if err != nil {
t.Fatal(err)
}
@@ -1,308 +0,0 @@
package xmc
import (
"bytes"
"crypto/x509"
"io"
"net"
"strings"
"testing"
"time"
)
func newLoginTestClient(t *testing.T, conn net.Conn, version protocolVersion) *clientConn {
t.Helper()
key, err := DeriveRSAKey("login-flow")
if err != nil {
t.Fatal(err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatal(err)
}
client, err := newClientConn(conn, version, []loginProfile{{Username: "TestUser"}}, "password", publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel)
if err != nil {
t.Fatal(err)
}
return client
}
// TestClientHandshakeAdvertisesConfiguredVersion checks that the handshake
// carries the row selected in the configuration, which is what lets one binary
// pair with servers of different releases.
func TestClientHandshakeAdvertisesConfiguredVersion(t *testing.T) {
for _, number := range []Varint{767, 775, 777} {
version, ok := protocolVersionByNumber(number)
if !ok {
t.Fatalf("protocol %d is missing from the table", number)
}
clientRaw, serverRaw := net.Pipe()
client := newLoginTestClient(t, clientRaw, version)
go func() { _ = client.handshake() }()
if err := serverRaw.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
t.Fatal(err)
}
packet, err := readPacket(serverRaw)
if err != nil {
t.Fatalf("protocol %d: read handshake: %v", number, err)
}
if packet.packetID != handshakeServerboundIntention {
t.Fatalf("protocol %d: handshake packet id = 0x%02x", number, packet.packetID)
}
var (
gotNumber Varint
address String
port UnsignedShort
nextState Varint
)
if err := packet.readFields(&gotNumber, &address, &port, &nextState); err != nil {
t.Fatalf("protocol %d: read handshake fields: %v", number, err)
}
if gotNumber != number {
t.Fatalf("handshake advertised %d, want %d", gotNumber, number)
}
if nextState != 2 {
t.Fatalf("handshake intent = %d, want login (2)", nextState)
}
_ = clientRaw.Close()
_ = serverRaw.Close()
}
}
// TestClientLoginAnswers checks the two optional login exchanges a vanilla 26.x
// client answers: a custom query gets a null payload, a cookie request gets an
// absent cookie. Both use the ids of the selected version.
func TestClientLoginAnswers(t *testing.T) {
version := latestProtocolVersion
t.Run("custom query", func(t *testing.T) {
var wire, out bytes.Buffer
transactionID := Varint(7)
if err := writePacket(&wire, version.login.clientboundCustomQuery, &transactionID, new(String("test:query"))); err != nil {
t.Fatal(err)
}
request, err := readPacket(&wire)
if err != nil {
t.Fatal(err)
}
client := &clientConn{protocol: version, writer: &out}
if err := client.answerCustomQuery(request); err != nil {
t.Fatal(err)
}
answer, err := readPacket(&out)
if err != nil {
t.Fatal(err)
}
if answer.packetID != version.login.serverboundCustomQueryAnswer {
t.Fatalf("answer packet id = 0x%02x", answer.packetID)
}
// transaction id 7, then the nullable payload marker for "no payload".
if !bytes.Equal(answer.data, []byte{0x07, 0x00}) {
t.Fatalf("answer body = %x", answer.data)
}
})
t.Run("cookie request", func(t *testing.T) {
var wire, out bytes.Buffer
if err := writePacket(&wire, version.login.clientboundCookieRequest, new(String("test:cookie"))); err != nil {
t.Fatal(err)
}
request, err := readPacket(&wire)
if err != nil {
t.Fatal(err)
}
client := &clientConn{protocol: version, writer: &out}
if err := client.answerCookieRequest(request); err != nil {
t.Fatal(err)
}
answer, err := readPacket(&out)
if err != nil {
t.Fatal(err)
}
if answer.packetID != version.login.serverboundCookieResponse {
t.Fatalf("answer packet id = 0x%02x", answer.packetID)
}
var key String
if err := answer.readFields(&key); err != nil {
t.Fatal(err)
}
if string(key) != "test:cookie" {
t.Fatalf("cookie key = %q", string(key))
}
})
}
// TestReadLoginFinished checks both shapes of the packet: before 26.2 the body
// ends after the game profile, from 26.2 on a session id follows it. Trailing
// bytes are ignored, because Mojang has appended a field to this packet before.
func TestReadLoginFinished(t *testing.T) {
for _, version := range []protocolVersion{protocolVersions[0], latestProtocolVersion} {
var (
wire bytes.Buffer
profile = loginProfile{Username: "TestUser", UUID: UUID{1, 2, 3}}
name = String("TestUser")
)
fields := []field{&profile.UUID, &name, &profile.Properties}
if version.loginFinishedSessionID {
sessionID := UUID{9, 9, 9}
fields = append(fields, &sessionID)
}
if err := writePacket(&wire, version.login.clientboundLoginFinished, fields...); err != nil {
t.Fatal(err)
}
packet, err := readPacket(&wire)
if err != nil {
t.Fatal(err)
}
client := &clientConn{protocol: version}
got, err := client.readLoginFinished(packet)
if err != nil {
t.Fatalf("%s (%d): read login finished: %v", version.name, version.number, err)
}
if got.Username != "TestUser" || got.UUID != profile.UUID {
t.Fatalf("%s (%d): profile = %q %x", version.name, version.number, got.Username, got.UUID)
}
// One missing session id must fail, so the flag cannot silently rot.
if version.loginFinishedSessionID {
var short bytes.Buffer
username := String("TestUser")
if err := writePacket(&short, version.login.clientboundLoginFinished, &profile.UUID, &username, &profile.Properties); err != nil {
t.Fatal(err)
}
packet, err := readPacket(&short)
if err != nil {
t.Fatal(err)
}
if _, err := client.readLoginFinished(packet); err == nil {
t.Fatalf("%s: login finished without a session id was accepted", version.name)
}
}
}
}
// TestServerRejectsUnknownProtocolVersion checks the server answers a version
// outside the table with the same Login Disconnect a vanilla server sends,
// instead of guessing packet ids.
func TestServerRejectsUnknownProtocolVersion(t *testing.T) {
key, err := DeriveRSAKey("login-flow")
if err != nil {
t.Fatal(err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatal(err)
}
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
server, err := wrapConnServer(serverRaw, []loginProfile{{Username: "TestUser"}}, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, nil, nil, DefaultDataChannel, DefaultPaddingChannel)
if err != nil {
t.Fatal(err)
}
handshakeResult := make(chan error, 1)
go func() { handshakeResult <- server.handshake() }()
if err := clientRaw.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
t.Fatal(err)
}
var (
protocolNumber Varint = 999
address String = "localhost"
port UnsignedShort = 25565
nextState Varint = 2
)
if err := writePacket(clientRaw, handshakeServerboundIntention, &protocolNumber, &address, &port, &nextState); err != nil {
t.Fatal(err)
}
packet, err := readPacket(clientRaw)
if err != nil {
t.Fatalf("read login disconnect: %v", err)
}
if packet.packetID != latestProtocolVersion.login.clientboundLoginDisconnect {
t.Fatalf("disconnect packet id = 0x%02x", packet.packetID)
}
var reason String
if err := packet.readFields(&reason); err != nil {
t.Fatal(err)
}
if !strings.Contains(string(reason), "multiplayer.disconnect.incompatible") {
t.Fatalf("disconnect reason = %s", string(reason))
}
if err := <-handshakeResult; err == nil || !strings.Contains(err.Error(), "unsupported protocol version") {
t.Fatalf("handshake error = %v", err)
}
}
// TestClientRejectsOfflineLogin checks the client refuses a login that never
// asks for encryption: XMC reproduces the online-mode login, and an offline
// server has none of it.
func TestClientRejectsOfflineLogin(t *testing.T) {
version := latestProtocolVersion
clientRaw, serverRaw := net.Pipe()
defer clientRaw.Close()
defer serverRaw.Close()
client := newLoginTestClient(t, clientRaw, version)
handshakeResult := make(chan error, 1)
go func() { handshakeResult <- client.handshake() }()
if err := serverRaw.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
t.Fatal(err)
}
if _, err := readPacket(serverRaw); err != nil {
t.Fatalf("read handshake: %v", err)
}
if _, err := readPacket(serverRaw); err != nil {
t.Fatalf("read login start: %v", err)
}
// An offline-mode server answers Login Start with Login Finished directly.
var (
profile = loginProfile{Username: "TestUser", UUID: UUID{1}}
username = String("TestUser")
session = UUID{9}
)
if err := writePacket(serverRaw, version.login.clientboundLoginFinished, &profile.UUID, &username, &profile.Properties, &session); err != nil {
t.Fatal(err)
}
err := <-handshakeResult
if err == nil || !strings.Contains(err.Error(), "offline-mode servers are not supported") {
t.Fatalf("handshake error = %v", err)
}
}
// TestClientRejectsUnauthenticatedServer checks that a server which still
// encrypts but tells the client not to authenticate is refused in Yggdrasil
// mode: that flag is an offline-mode server.
func TestClientRejectsUnauthenticatedServer(t *testing.T) {
version := latestProtocolVersion
var wire bytes.Buffer
var (
serverID String
publicKey Bytes = Bytes{1, 2, 3}
challenge Bytes = Bytes{4, 5, 6, 7}
shouldAuthenticate Boolean
)
if err := writePacket(&wire, version.login.clientboundHello, &serverID, &publicKey, &challenge, &shouldAuthenticate); err != nil {
t.Fatal(err)
}
request, err := readPacket(&wire)
if err != nil {
t.Fatal(err)
}
client := &clientConn{protocol: version, writer: io.Discard, yggdrasil: &yggdrasilAuth{}}
if _, _, err := client.handleEncryptionRequest(request, loginProfile{}); err == nil || !strings.Contains(err.Error(), "offline-mode servers are not supported") {
t.Fatalf("handle encryption request error = %v", err)
}
}
+53 -229
View File
@@ -4,173 +4,52 @@ import (
"bytes"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
)
const (
configurationClientboundCustomPayload = 0x01
configurationServerboundCustomPayload = 0x02
configurationKeepAlive = 0x04
packetChannel = "xmc:data"
maxPacketData = 24 * 1024
keepAlivePeriod = 15 * time.Second
// tickInterval is one Minecraft game tick. After the handshake the proxy
// stream is emitted in one batch per tick so that the connection keeps the
// 20 Hz shape of a real client instead of turning into a bulk TCP stream.
tickInterval = 50 * time.Millisecond
// maxQueuedData bounds proxy data waiting for the next tick. Write blocks
// once the queue is full, so a slow peer pushes back to the proxy instead
// of growing memory without bound.
maxQueuedData = 4 * 1024 * 1024
// tickPaddingSize keeps every tick non-empty in both directions, like the
// small per-tick packets a real client and server keep sending while idle.
tickPaddingSize = 1
)
// tickStream carries the raw proxy byte stream in Minecraft configuration
// packetStream carries the raw proxy byte stream in Minecraft configuration
// custom payload packets. The configuration state provides bidirectional
// payload packets and keep-alives without requiring version-specific world data.
//
// Proxy writes are queued and flushed once per game tick (50 ms). Each tick
// always emits at least one small padding frame, so an idle connection keeps
// the same 20 Hz cadence as a real client. Data that does not fit in one
// payload is split over several payloads in the same tick, which keeps the
// per-tick burst shape without an artificial bandwidth cap.
type tickStream struct {
type packetStream struct {
reader io.Reader
writer io.Writer
isClient bool
// packetIDs are the configuration-state ids of the negotiated version: the
// custom payload pair that carries the tunnel plus the keep-alives, pings,
// cookies and disconnects a peer may send before the tunnel starts.
packetIDs configurationPacketIDs
// Configured custom payload channels: the data one carries proxy bytes, the
// padding one keeps an idle tick non-empty. Both ends must use the same pair.
dataChannel string
paddingChannel string
readMu sync.Mutex
pending []byte
writeMu sync.Mutex
queueMu sync.Mutex
queueCond *sync.Cond
queue []byte
closed bool
pending []byte
keepAliveID atomic.Int64
done chan struct{}
stopOnce sync.Once
}
func newTickStream(reader io.Reader, writer io.Writer, isClient bool, packetIDs configurationPacketIDs, dataChannel, paddingChannel string) *tickStream {
s := &tickStream{
reader: reader,
writer: writer,
isClient: isClient,
packetIDs: packetIDs,
dataChannel: dataChannel,
paddingChannel: paddingChannel,
done: make(chan struct{}),
func newPacketStream(reader io.Reader, writer io.Writer, isClient bool) *packetStream {
s := &packetStream{
reader: reader,
writer: writer,
isClient: isClient,
done: make(chan struct{}),
}
s.queueCond = sync.NewCond(&s.queueMu)
go s.tickLoop()
if !isClient {
go s.keepAliveLoop()
}
return s
}
func (s *tickStream) tickLoop() {
ticker := time.NewTicker(tickInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := s.flushTick(); err != nil {
s.Stop()
return
}
case <-s.done:
return
}
}
}
// flushTick writes one game tick worth of packets in a single network write:
// queued proxy data first, then one small padding frame. Data is split into
// payloads of at most maxPacketData bytes, but every payload stays in this
// tick's batch, so a busy connection looks like Minecraft chunk bursts rather
// than a continuous stream.
func (s *tickStream) flushTick() error {
s.writeMu.Lock()
defer s.writeMu.Unlock()
data := s.takeQueue()
var batch bytes.Buffer
if err := s.writeDataPackets(&batch, data); err != nil {
return err
}
if err := writeCustomPayload(&batch, s.localCustomPayloadID(), s.paddingChannel, make([]byte, tickPaddingSize)); err != nil {
return err
}
if _, err := s.writer.Write(batch.Bytes()); err != nil {
return fmt.Errorf("write minecraft tick: %w", err)
}
return nil
}
// Flush writes queued proxy data immediately instead of waiting for the next
// tick. Close uses it so the last bytes are not dropped after Write returned.
func (s *tickStream) Flush() error {
s.writeMu.Lock()
defer s.writeMu.Unlock()
data := s.takeQueue()
if len(data) == 0 {
return nil
}
var batch bytes.Buffer
if err := s.writeDataPackets(&batch, data); err != nil {
return err
}
_, err := s.writer.Write(batch.Bytes())
return err
}
func (s *tickStream) takeQueue() []byte {
s.queueMu.Lock()
defer s.queueMu.Unlock()
data := s.queue
s.queue = nil
s.queueCond.Broadcast()
return data
}
func (s *tickStream) writeDataPackets(batch *bytes.Buffer, data []byte) error {
for len(data) > 0 {
n := min(len(data), maxPacketData)
if err := writeCustomPayload(batch, s.localCustomPayloadID(), s.dataChannel, data[:n]); err != nil {
return err
}
data = data[n:]
}
return nil
}
func writeCustomPayload(w io.Writer, packetID int, channel string, payload []byte) error {
name := String(channel)
data := RestBytes(payload)
return writePacket(w, packetID, &name, &data)
}
func (s *tickStream) Read(p []byte) (int, error) {
func (s *packetStream) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
@@ -191,7 +70,7 @@ func (s *tickStream) Read(p []byte) (int, error) {
}
if packet.packetID == s.remoteCustomPayloadID() {
payload, ok, err := parseCustomPayload(packet, s.dataChannel)
payload, ok, err := parseCustomPayload(packet)
if err != nil {
return 0, err
}
@@ -206,99 +85,70 @@ func (s *tickStream) Read(p []byte) (int, error) {
return n, nil
}
// Everything else in this state is server chatter: the client answers
// what a vanilla client answers and skips the rest (registry data, tags,
// dialogs...), which is what keeps it working across releases. The server
// side only reads tunnel data, so it skips all of it.
if !s.isClient {
continue
}
switch packet.packetID {
case s.packetIDs.clientboundKeepAlive:
if packet.packetID == configurationKeepAlive {
var id Long
if err := packet.readFields(&id); err != nil {
return 0, fmt.Errorf("read minecraft keep-alive: %w", err)
}
if err := s.writeKeepAlive(s.packetIDs.serverboundKeepAlive, id); err != nil {
return 0, err
if s.isClient {
if err := s.writeKeepAlive(id); err != nil {
return 0, err
}
}
case s.packetIDs.clientboundPing:
// Configuration Ping is answered with Pong, like a real client. The
// id is a plain 32-bit integer here, not a varint.
var id Int
if err := packet.readFields(&id); err != nil {
return 0, fmt.Errorf("read minecraft ping: %w", err)
}
if err := s.writePong(id); err != nil {
return 0, err
}
case s.packetIDs.clientboundCookieRequest:
if err := s.writeCookieResponse(packet); err != nil {
return 0, err
}
case s.packetIDs.clientboundDisconnect:
var reason String
_ = packet.readFields(&reason)
return 0, fmt.Errorf("minecraft disconnected: %s", string(reason))
}
}
}
func (s *tickStream) Write(p []byte) (int, error) {
func (s *packetStream) Write(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
s.queueMu.Lock()
for len(s.queue) >= maxQueuedData && !s.closed {
s.queueCond.Wait()
}
if s.closed {
s.queueMu.Unlock()
return 0, net.ErrClosed
}
s.queue = append(s.queue, p...)
s.queueMu.Unlock()
s.writeMu.Lock()
defer s.writeMu.Unlock()
return len(p), nil
written := 0
for written < len(p) {
end := written + maxPacketData
if end > len(p) {
end = len(p)
}
channel := String(packetChannel)
payload := RestBytes(p[written:end])
if err := writePacket(s.writer, s.localCustomPayloadID(), &channel, &payload); err != nil {
return written, fmt.Errorf("write minecraft custom payload: %w", err)
}
written = end
}
return written, nil
}
func (s *tickStream) Stop() {
s.stopOnce.Do(func() {
s.queueMu.Lock()
s.closed = true
s.queue = nil
s.queueCond.Broadcast()
s.queueMu.Unlock()
close(s.done)
})
func (s *packetStream) Stop() {
s.stopOnce.Do(func() { close(s.done) })
}
func (s *tickStream) localCustomPayloadID() int {
func (s *packetStream) localCustomPayloadID() int {
if s.isClient {
return s.packetIDs.serverboundCustomPayload
return configurationServerboundCustomPayload
}
return s.packetIDs.clientboundCustomPayload
return configurationClientboundCustomPayload
}
func (s *tickStream) remoteCustomPayloadID() int {
func (s *packetStream) remoteCustomPayloadID() int {
if s.isClient {
return s.packetIDs.clientboundCustomPayload
return configurationClientboundCustomPayload
}
return s.packetIDs.serverboundCustomPayload
return configurationServerboundCustomPayload
}
func parseCustomPayload(packet *mcPacket, dataChannel string) ([]byte, bool, error) {
func parseCustomPayload(packet *mcPacket) ([]byte, bool, error) {
r := bytes.NewReader(packet.data)
var channel String
if err := channel.readFrom(r); err != nil {
return nil, false, fmt.Errorf("read minecraft custom payload channel: %w", err)
}
if string(channel) != dataChannel {
if string(channel) != packetChannel {
return nil, false, nil
}
payload := make([]byte, r.Len())
@@ -308,49 +158,23 @@ func parseCustomPayload(packet *mcPacket, dataChannel string) ([]byte, bool, err
return payload, true, nil
}
func (s *tickStream) writeKeepAlive(packetID int, id Long) error {
func (s *packetStream) writeKeepAlive(id Long) error {
s.writeMu.Lock()
defer s.writeMu.Unlock()
if err := writePacket(s.writer, packetID, &id); err != nil {
if err := writePacket(s.writer, configurationKeepAlive, &id); err != nil {
return fmt.Errorf("write minecraft keep-alive: %w", err)
}
return nil
}
// writePong answers a configuration Ping, which a vanilla client always does.
func (s *tickStream) writePong(id Int) error {
s.writeMu.Lock()
defer s.writeMu.Unlock()
if err := writePacket(s.writer, s.packetIDs.serverboundPong, &id); err != nil {
return fmt.Errorf("write minecraft pong: %w", err)
}
return nil
}
// writeCookieResponse answers a cookie request with an absent cookie, which is
// what a client that never received one sends.
func (s *tickStream) writeCookieResponse(request *mcPacket) error {
var key String
if err := request.readFields(&key); err != nil {
return fmt.Errorf("read minecraft cookie request: %w", err)
}
s.writeMu.Lock()
defer s.writeMu.Unlock()
answered := Boolean(false)
if err := writePacket(s.writer, s.packetIDs.serverboundCookieResponse, &key, &answered); err != nil {
return fmt.Errorf("write minecraft cookie response: %w", err)
}
return nil
}
func (s *tickStream) keepAliveLoop() {
func (s *packetStream) keepAliveLoop() {
ticker := time.NewTicker(keepAlivePeriod)
defer ticker.Stop()
for {
select {
case <-ticker.C:
id := Long(s.keepAliveID.Add(1))
if err := s.writeKeepAlive(s.packetIDs.clientboundKeepAlive, id); err != nil {
if err := s.writeKeepAlive(id); err != nil {
return
}
case <-s.done:
+75 -98
View File
@@ -29,97 +29,19 @@ const (
// every connection, so it is rejected when the configuration is built.
maxPaddingScheduleDelay = handshakeTimeout - 10*time.Second
// Frame padding carries the startup padding in ordinary Minecraft custom
// payload packets so that a vanilla server can parse the whole connection
// without taking the pipeline over. The channel is deliberately different
// from the packet stream channel: both ends drop unknown payloads.
paddingFrameChannel = "xmc:pad"
// Serverbound custom payload data is capped at 32767 bytes by
// ServerboundCustomPayloadPacket; keep the same budget in both directions.
maxPaddingFrameDataLength = 32767
// Length varint, packet id, channel length varint and the channel itself.
paddingFrameOverhead = 1 + 1 + 1 + len(paddingFrameChannel)
)
// defaultPaddingFraming is the framing of the built-in padding channel. A
// configured channel name changes the frame overhead, so the framing travels
// with the channel instead of being a package constant.
var defaultPaddingFraming = newPaddingFraming(DefaultPaddingChannel)
// paddingFraming is the custom payload framing of one channel. Frame padding
// carries the startup padding in ordinary Minecraft custom payload packets so
// that a vanilla server can parse the whole connection without taking the
// pipeline over; the channel name decides the frame overhead, so every exact
// frame length the captured presets ask for depends on it.
type paddingFraming struct {
channel string
}
func newPaddingFraming(channel string) paddingFraming {
return paddingFraming{channel: channel}
}
// overhead is the length varint, the packet id, the channel length varint and
// the channel itself, for the smallest length varint.
func (f paddingFraming) overhead() int {
return 1 + 1 + 1 + len(f.channel)
}
func (f paddingFraming) maxFrameLength() int {
return f.frameLength(maxPaddingFrameDataLength)
}
// frameLength is the wire size of a custom payload frame whose payload body is
// dataLength bytes long.
func (f paddingFraming) frameLength(dataLength int) int {
bodyLength := 1 + 1 + len(f.channel) + dataLength
return varintSize(Varint(bodyLength)) + bodyLength
}
// frameDataLength is the payload body that makes a frame exactly frameLength
// bytes long. Some lengths are unreachable because the length varint grows in
// steps.
func (f paddingFraming) frameDataLength(frameLength int) (int, bool) {
for overhead := f.overhead(); overhead <= f.overhead()+2; overhead++ {
dataLength := frameLength - overhead
if dataLength < 0 || dataLength > maxPaddingFrameDataLength {
continue
}
if f.frameLength(dataLength) == frameLength {
return dataLength, true
}
}
return 0, false
}
// plan splits length bytes into reachable frame sizes. The result is exact
// whenever a partition exists; a length below the smallest frame (the captured
// 2-byte turns) is rounded up to that frame.
func (f paddingFraming) plan(length int) ([]int, error) {
if length <= 0 {
return nil, nil
}
overhead := f.overhead()
if length < overhead {
return []int{overhead}, nil
}
maxFrameLength := f.maxFrameLength()
frameLengths := make([]int, 0, length/paddingBufferLength+1)
for remaining := length; remaining > 0; {
candidate := min(remaining, maxFrameLength)
picked := 0
for ; candidate >= overhead; candidate-- {
if _, ok := f.frameDataLength(candidate); !ok {
continue
}
rest := remaining - candidate
if rest > 0 && rest < overhead {
continue
}
picked = candidate
break
}
if picked == 0 {
return nil, fmt.Errorf("cannot frame %d padding bytes", length)
}
frameLengths = append(frameLengths, picked)
remaining -= picked
}
return frameLengths, nil
}
var maxPaddingFrameLength = paddingFrameLength(maxPaddingFrameDataLength)
type paddingVariant struct {
chunks []int
@@ -175,14 +97,13 @@ func pausePadding(done <-chan struct{}, d time.Duration) error {
// Minecraft packets that carry nothing to compare an early arrival against, and
// the startup reader drains them on its own while this schedule writes. A peer
// that stalls is bounded by maxPaddingScheduleDelay instead.
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error, paddingChannel string, packetIDs configurationPacketIDs) error {
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error) error {
if len(schedule) == 0 {
return nil
}
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
return err
}
framing := newPaddingFraming(paddingChannel)
for i, turn := range schedule {
prefixLength := 0
@@ -207,7 +128,7 @@ func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength i
if err := sleep(delay); err != nil {
return err
}
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(packetIDs, isClient), framing); err != nil {
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
return fmt.Errorf("write padding turn %d: %w", i, err)
}
}
@@ -274,19 +195,18 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
// paddingFramePacketID returns the configuration-state custom payload packet id
// used by the side that sends the padding bytes; both values come from the
// negotiated version's configuration protocol, so no proxy-specific id ever
// reaches the wire.
func paddingFramePacketID(packetIDs configurationPacketIDs, isClient bool) int {
// vanilla configuration protocol, so no proxy-specific id ever reaches the wire.
func paddingFramePacketID(isClient bool) int {
if isClient {
return packetIDs.serverboundCustomPayload
return configurationServerboundCustomPayload
}
return packetIDs.clientboundCustomPayload
return configurationClientboundCustomPayload
}
// writePaddingTurnFrames writes one padding turn as a sequence of valid
// Minecraft custom payload frames. Only the framing is native: payload bodies
// stay zero-filled, so the captured traffic shape is kept.
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int, framing paddingFraming) (int, error) {
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int) (int, error) {
startDelay, err := randomPaddingDelay(turn.startDelay)
if err != nil {
return 0, fmt.Errorf("select padding start delay: %w", err)
@@ -321,7 +241,7 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
}
zeros := make([]byte, maxPaddingFrameDataLength)
channel := String(framing.channel)
channel := String(paddingFrameChannel)
written := 0
for i, chunkLength := range chunks {
if i < len(delays) {
@@ -333,12 +253,12 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
return written, delayErr
}
}
frameLengths, planErr := framing.plan(chunkLength)
frameLengths, planErr := paddingFramePlan(chunkLength)
if planErr != nil {
return written, planErr
}
for _, frameLength := range frameLengths {
dataLength, ok := framing.frameDataLength(frameLength)
dataLength, ok := paddingFrameDataLength(frameLength)
if !ok {
return written, fmt.Errorf("unframed padding length %d", frameLength)
}
@@ -352,6 +272,63 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
return written, nil
}
// paddingFrameLength is the wire size of a custom payload frame whose payload
// body is dataLength bytes long.
func paddingFrameLength(dataLength int) int {
bodyLength := 1 + 1 + len(paddingFrameChannel) + dataLength
return varintSize(Varint(bodyLength)) + bodyLength
}
// paddingFrameDataLength is the payload body that makes a frame exactly
// frameLength bytes long. Some lengths are unreachable because the length
// varint grows in steps.
func paddingFrameDataLength(frameLength int) (int, bool) {
for overhead := paddingFrameOverhead; overhead <= paddingFrameOverhead+2; overhead++ {
dataLength := frameLength - overhead
if dataLength < 0 || dataLength > maxPaddingFrameDataLength {
continue
}
if paddingFrameLength(dataLength) == frameLength {
return dataLength, true
}
}
return 0, false
}
// paddingFramePlan splits length bytes into reachable frame sizes. The result is
// exact whenever a partition exists; a length below the smallest frame (the
// captured 2-byte turns) is rounded up to that frame.
func paddingFramePlan(length int) ([]int, error) {
if length <= 0 {
return nil, nil
}
if length < paddingFrameOverhead {
return []int{paddingFrameOverhead}, nil
}
frameLengths := make([]int, 0, length/paddingBufferLength+1)
for remaining := length; remaining > 0; {
candidate := min(remaining, maxPaddingFrameLength)
picked := 0
for ; candidate >= paddingFrameOverhead; candidate-- {
if _, ok := paddingFrameDataLength(candidate); !ok {
continue
}
rest := remaining - candidate
if rest > 0 && rest < paddingFrameOverhead {
continue
}
picked = candidate
break
}
if picked == 0 {
return nil, fmt.Errorf("cannot frame %d padding bytes", length)
}
frameLengths = append(frameLengths, picked)
remaining -= picked
}
return frameLengths, nil
}
func selectPaddingVariant(turn paddingTurn, prefixLength int) (int, []int, []paddingDelayRange, error) {
if len(turn.variants) == 0 {
minimum, maximum := turn.minLength, turn.maxLength
@@ -12,8 +12,8 @@ import (
func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
for dataLength := 0; dataLength <= maxPaddingFrameDataLength; dataLength++ {
frameLength := defaultPaddingFraming.frameLength(dataLength)
got, ok := defaultPaddingFraming.frameDataLength(frameLength)
frameLength := paddingFrameLength(dataLength)
got, ok := paddingFrameDataLength(frameLength)
if !ok || got != dataLength {
t.Fatalf("data length %d -> frame %d -> data %d (ok=%v)", dataLength, frameLength, got, ok)
}
@@ -21,18 +21,18 @@ func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
}
func TestPaddingFramePlanTotals(t *testing.T) {
lengths := []int{defaultPaddingFraming.overhead(), defaultPaddingFraming.overhead() + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, defaultPaddingFraming.maxFrameLength() - 1, defaultPaddingFraming.maxFrameLength(), defaultPaddingFraming.maxFrameLength() + 1, 3 * defaultPaddingFraming.maxFrameLength(), 1024 * 1024}
lengths := []int{paddingFrameOverhead, paddingFrameOverhead + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, maxPaddingFrameLength - 1, maxPaddingFrameLength, maxPaddingFrameLength + 1, 3 * maxPaddingFrameLength, 1024 * 1024}
for _, length := range lengths {
plan, err := defaultPaddingFraming.plan(length)
plan, err := paddingFramePlan(length)
if err != nil {
t.Fatalf("plan %d: %v", length, err)
}
total := 0
for _, frameLength := range plan {
if _, ok := defaultPaddingFraming.frameDataLength(frameLength); !ok {
if _, ok := paddingFrameDataLength(frameLength); !ok {
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
}
if frameLength > defaultPaddingFraming.maxFrameLength() {
if frameLength > maxPaddingFrameLength {
t.Fatalf("plan %d contains oversized frame %d", length, frameLength)
}
total += frameLength
@@ -44,11 +44,11 @@ func TestPaddingFramePlanTotals(t *testing.T) {
}
func TestPaddingFramePlanRoundsUpShortTurn(t *testing.T) {
plan, err := defaultPaddingFraming.plan(2)
plan, err := paddingFramePlan(2)
if err != nil {
t.Fatal(err)
}
if len(plan) != 1 || plan[0] != defaultPaddingFraming.overhead() {
if len(plan) != 1 || plan[0] != paddingFrameOverhead {
t.Fatalf("short turn plan = %v", plan)
}
}
@@ -57,12 +57,12 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
turns := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
{direction: paddingClientToServer, minLength: 2, maxLength: 2},
{direction: paddingClientToServer, minLength: defaultPaddingFraming.maxFrameLength(), maxLength: defaultPaddingFraming.maxFrameLength()},
{direction: paddingClientToServer, minLength: 3*defaultPaddingFraming.maxFrameLength() + 7, maxLength: 3*defaultPaddingFraming.maxFrameLength() + 7},
{direction: paddingClientToServer, minLength: maxPaddingFrameLength, maxLength: maxPaddingFrameLength},
{direction: paddingClientToServer, minLength: 3*maxPaddingFrameLength + 7, maxLength: 3*maxPaddingFrameLength + 7},
}
for i, turn := range turns {
var buffer bytes.Buffer
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationPacketIDs121.serverboundCustomPayload, defaultPaddingFraming)
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationServerboundCustomPayload)
if err != nil {
t.Fatalf("turn %d: %v", i, err)
}
@@ -81,10 +81,10 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
if err != nil {
t.Fatalf("turn %d frame %d is not a valid packet: %v", i, frames, err)
}
if packet.packetID != configurationPacketIDs121.serverboundCustomPayload {
if packet.packetID != configurationServerboundCustomPayload {
t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID)
}
_, ok, err := parseCustomPayload(packet, DefaultDataChannel)
_, ok, err := parseCustomPayload(packet)
if err != nil {
t.Fatalf("turn %d frame %d: %v", i, frames, err)
}
@@ -107,7 +107,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
}
var out bytes.Buffer
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause); err != nil {
t.Fatal(err)
}
@@ -119,7 +119,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
if err != nil {
t.Fatalf("padding stream is not a valid packet stream: %v", err)
}
if packet.packetID != configurationPacketIDs121.serverboundCustomPayload {
if packet.packetID != configurationServerboundCustomPayload {
t.Fatalf("unexpected packet id %d in padding stream", packet.packetID)
}
total += before - reader.Len()
@@ -135,7 +135,7 @@ func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
}
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err == nil {
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause); err == nil {
t.Fatal("expected an error for a prefixed server-to-client first turn")
}
}
@@ -144,7 +144,7 @@ func noPaddingPause(time.Duration) error { return nil }
func TestRunPaddingScheduleWithoutTurns(t *testing.T) {
var out bytes.Buffer
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause); err != nil {
t.Fatal(err)
}
if out.Len() != 0 {
@@ -167,7 +167,7 @@ func TestRunPaddingScheduleStopsWhenClosed(t *testing.T) {
pauses++
return net.ErrClosed
}
err := runPaddingSchedule(&out, true, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121)
err := runPaddingSchedule(&out, true, 2, schedule, sleep)
if !errors.Is(err, net.ErrClosed) {
t.Fatalf("expected net.ErrClosed, got %v", err)
}
@@ -208,7 +208,7 @@ func TestPaddingDelayLeadsIntoTheTurn(t *testing.T) {
}
return nil
}
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep); err != nil {
t.Fatal(err)
}
return events
@@ -246,7 +246,7 @@ func TestPaddingDelayRangeJittersOnlyTheSender(t *testing.T) {
}
return nil
}
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep); err != nil {
t.Fatal(err)
}
return pauses
@@ -19,16 +19,16 @@ type paddingReader struct {
// writing. Buffer only the first non-padding packet, then let the caller resume
// reading the underlying stream. This keeps memory bounded without requiring
// matching padding lengths or an extra end-of-padding packet on the wire.
func newPaddingReader(reader io.Reader, isClient bool, paddingChannel string, packetIDs configurationPacketIDs) io.Reader {
func newPaddingReader(reader io.Reader, isClient bool) io.Reader {
first := make(chan paddingReadResult, 1)
go func() {
frame, err := readPastPadding(reader, paddingFramePacketID(packetIDs, !isClient), paddingChannel)
frame, err := readPastPadding(reader, paddingFramePacketID(!isClient))
first <- paddingReadResult{frame: frame, err: err}
}()
return &paddingReader{reader: reader, first: first}
}
func readPastPadding(reader io.Reader, packetID int, paddingChannel string) ([]byte, error) {
func readPastPadding(reader io.Reader, packetID int) ([]byte, error) {
for {
packet, err := readPacket(reader)
if err != nil {
@@ -36,7 +36,7 @@ func readPastPadding(reader io.Reader, packetID int, paddingChannel string) ([]b
}
if packet.packetID == packetID {
var channel String
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && string(channel) == paddingChannel {
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && channel == paddingFrameChannel {
continue
}
}
@@ -10,9 +10,9 @@ import (
func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
for _, isClient := range []bool{true, false} {
packetID := paddingFramePacketID(configurationPacketIDs121, !isClient)
packetID := paddingFramePacketID(!isClient)
var wire bytes.Buffer
paddingChannel := String(DefaultPaddingChannel)
paddingChannel := String(paddingFrameChannel)
padding := RestBytes(make([]byte, 1024))
if err := writePacket(&wire, packetID, &paddingChannel, &padding); err != nil {
t.Fatal(err)
@@ -24,15 +24,15 @@ func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
t.Fatal(err)
}
id := Long(42)
if err := writePacket(&want, configurationPacketIDs121.clientboundKeepAlive, &id); err != nil {
if err := writePacket(&want, configurationKeepAlive, &id); err != nil {
t.Fatal(err)
}
channel := String(DefaultDataChannel)
channel := String(packetChannel)
if err := writePacket(&want, packetID, &channel, &payload); err != nil {
t.Fatal(err)
}
wire.Write(want.Bytes())
got, err := io.ReadAll(newPaddingReader(&wire, isClient, DefaultPaddingChannel, configurationPacketIDs121))
got, err := io.ReadAll(newPaddingReader(&wire, isClient))
if err != nil {
t.Fatal(err)
}
@@ -52,7 +52,7 @@ func TestPaddingReaderReadErrors(t *testing.T) {
{name: "truncated", wire: []byte{2, 1}, err: io.ErrUnexpectedEOF},
} {
t.Run(test.name, func(t *testing.T) {
reader := newPaddingReader(bytes.NewReader(test.wire), true, DefaultPaddingChannel, configurationPacketIDs121)
reader := newPaddingReader(bytes.NewReader(test.wire), true)
if _, err := reader.Read(make([]byte, 1)); !errors.Is(err, test.err) {
t.Fatalf("got %v, want %v", err, test.err)
}
@@ -63,7 +63,7 @@ func TestPaddingReaderReadErrors(t *testing.T) {
func TestPaddingReaderUnblocksOnClose(t *testing.T) {
client, server := net.Pipe()
defer server.Close()
reader := newPaddingReader(client, true, DefaultPaddingChannel, configurationPacketIDs121)
reader := newPaddingReader(client, true)
if n, err := reader.Read(nil); n != 0 || err != nil {
t.Fatalf("empty read = %d, %v", n, err)
}
+14 -13
View File
@@ -184,18 +184,19 @@ func propertyListFromYggdrasil(properties []yggdrasilProperty) loginProperties {
return result
}
// writeLoginFinished writes the Login Finished packet. From 26.2 on the packet
// also carries the connection session id, which the client only uses for its
// own telemetry, so one value per process is enough.
func writeLoginFinished(w io.Writer, version protocolVersion, profile loginProfile) error {
username := String(profile.Username)
fields := []field{&profile.UUID, &username, &profile.Properties}
if version.loginFinishedSessionID {
sessionID, err := serverSessionID()
if err != nil {
return err
}
fields = append(fields, &sessionID)
func readLoginSuccess(packet *mcPacket) (loginProfile, error) {
var (
profile loginProfile
username String
)
if err := packet.readFields(&profile.UUID, &username, &profile.Properties); err != nil {
return loginProfile{}, err
}
return writePacket(w, version.login.clientboundLoginFinished, fields...)
profile.Username = string(username)
return profile, nil
}
func writeLoginSuccess(w io.Writer, profile loginProfile) error {
username := String(profile.Username)
return writePacket(w, 0x02, &profile.UUID, &username, &profile.Properties)
}
+2 -25
View File
@@ -238,29 +238,6 @@ func (v *UnsignedShort) writeTo(w io.Writer) error {
return nil
}
// Int is a big-endian 32-bit integer, which is how vanilla encodes packet ids
// that are not counting up from zero (Ping, Pong). It is not a Varint: using the
// wrong one decodes as a valid-looking packet and fails later with a decoder
// exception on the peer.
type Int int32
func (v *Int) readFrom(r io.Reader) error {
var buf [4]byte
if _, err := io.ReadFull(r, buf[:]); err != nil {
return fmt.Errorf("read int: %w", err)
}
*v = Int(int32(buf[0])<<24 | int32(buf[1])<<16 | int32(buf[2])<<8 | int32(buf[3]))
return nil
}
func (v *Int) writeTo(w io.Writer) error {
buf := []byte{byte(*v >> 24), byte(*v >> 16), byte(*v >> 8), byte(*v)}
if _, err := w.Write(buf); err != nil {
return fmt.Errorf("write int: %w", err)
}
return nil
}
type Long int64
func (v *Long) readFrom(r io.Reader) error {
@@ -466,6 +443,6 @@ func writeFull(w io.Writer, p []byte) error {
return nil
}
func writeDisconnectPacket(w io.Writer, packetID int, reason string) error {
return writePacket(w, packetID, new(String(reason)))
func writeDisconnectPacket(w io.Writer, reason string) error {
return writePacket(w, 0x00, new(String(reason)))
}
@@ -1,154 +0,0 @@
// Status probe used to pick the protocol version of the peer.
package xmc
import (
"encoding/json"
"fmt"
"strconv"
"sync"
"time"
xnet "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
const (
// protocolProbeTimeout bounds one status round trip. A peer that cannot
// answer status in this time is not going to answer the login either.
protocolProbeTimeout = 5 * time.Second
// protocolProbeTTL keeps detection off the connection path: a real client
// refreshes a server's status in its server list, not once per join.
protocolProbeTTL = 10 * time.Minute
// maxProtocolProbeEntries bounds the cache. A proxy can dial many different
// destinations, and each entry is three words.
maxProtocolProbeEntries = 256
)
// statusVersion is the part of the status JSON the probe reads. Vanilla reports
// its own protocol version there, and the login it accepts is that version.
type statusVersion struct {
Version struct {
Name string `json:"name"`
Protocol int32 `json:"protocol"`
} `json:"version"`
}
type protocolProbeEntry struct {
number Varint
name string
expires time.Time
}
var protocolProbeCache = struct {
mu sync.Mutex
entries map[string]protocolProbeEntry
}{entries: make(map[string]protocolProbeEntry)}
// probeProtocolVersion asks the peer for its status and returns the protocol
// number and release name it reports.
//
// The probe is a second TCP connection to the same destination, exactly what a
// client does when it refreshes a server in its list, so the peer sees nothing
// unusual. It only works when the destination speaks plain Minecraft: for a
// destination behind another transport, set protocol_version instead.
func probeProtocolVersion(dest *xnet.Destination, hostname string, dialer *finalmask.Dialer) (Varint, string, error) {
if dest == nil {
return 0, "", fmt.Errorf("status probe: no destination")
}
if dialer == nil || dialer.DialTCP == nil {
return 0, "", fmt.Errorf("status probe: no TCP dialer")
}
conn, err := dialer.DialTCP(*dest)
if err != nil {
return 0, "", fmt.Errorf("status probe: dial: %w", err)
}
defer conn.Close()
if err := conn.SetDeadline(time.Now().Add(protocolProbeTimeout)); err != nil {
return 0, "", fmt.Errorf("status probe: set deadline: %w", err)
}
address := String(hostname)
if address == "" {
address = String(dest.Address.String())
}
var (
protocolNumber Varint = latestProtocolVersion.number
port UnsignedShort = UnsignedShort(dest.Port.Value())
nextState Varint = 1 // status
)
if err := writePacket(conn, handshakeServerboundIntention, &protocolNumber, &address, &port, &nextState); err != nil {
return 0, "", fmt.Errorf("status probe: write handshake: %w", err)
}
if err := writePacket(conn, statusServerboundRequest); err != nil {
return 0, "", fmt.Errorf("status probe: write status request: %w", err)
}
packet, err := readPacket(conn)
if err != nil {
return 0, "", fmt.Errorf("status probe: read status response: %w", err)
}
if packet.packetID != statusClientboundResponse {
return 0, "", fmt.Errorf("status probe: unexpected status packet id: 0x%02x", packet.packetID)
}
var payload String
if err := packet.readFields(&payload); err != nil {
return 0, "", fmt.Errorf("status probe: read status payload: %w", err)
}
var status statusVersion
if err := json.Unmarshal([]byte(payload), &status); err != nil {
return 0, "", fmt.Errorf("status probe: decode status response: %w", err)
}
if status.Version.Protocol <= 0 {
return 0, "", fmt.Errorf("status probe: status response has no version")
}
return Varint(status.Version.Protocol), status.Version.Name, nil
}
// detectProtocolVersion returns the peer's protocol version, reusing a recent
// probe for the same destination.
func detectProtocolVersion(dest *xnet.Destination, hostname string, dialer *finalmask.Dialer) (Varint, string, error) {
key := protocolProbeKey(dest)
now := time.Now()
protocolProbeCache.mu.Lock()
if entry, ok := protocolProbeCache.entries[key]; ok && entry.expires.After(now) {
protocolProbeCache.mu.Unlock()
return entry.number, entry.name, nil
}
protocolProbeCache.mu.Unlock()
number, name, err := probeProtocolVersion(dest, hostname, dialer)
if err != nil {
return 0, "", err
}
protocolProbeCache.mu.Lock()
if len(protocolProbeCache.entries) >= maxProtocolProbeEntries {
for cachedKey, entry := range protocolProbeCache.entries {
if entry.expires.Before(now) {
delete(protocolProbeCache.entries, cachedKey)
}
}
if len(protocolProbeCache.entries) >= maxProtocolProbeEntries {
clear(protocolProbeCache.entries)
}
}
protocolProbeCache.entries[key] = protocolProbeEntry{number: number, name: name, expires: now.Add(protocolProbeTTL)}
protocolProbeCache.mu.Unlock()
return number, name, nil
}
// forgetProbedVersions drops every cached detection. A login rejected with a
// version mismatch means the cached row is stale (the peer was upgraded, or the
// detection was wrong), so the next attempt has to ask again instead of waiting
// for the TTL.
func forgetProbedVersions() {
protocolProbeCache.mu.Lock()
clear(protocolProbeCache.entries)
protocolProbeCache.mu.Unlock()
}
func protocolProbeKey(dest *xnet.Destination) string {
return dest.Network.String() + "|" + dest.Address.String() + "|" + strconv.Itoa(int(dest.Port.Value()))
}
@@ -1,251 +0,0 @@
package xmc
import (
"fmt"
"net"
"strconv"
"strings"
"testing"
"time"
xnet "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/transport/internet/finalmask"
)
// statusTestServer answers exactly one status exchange with the given version.
func statusTestServer(t *testing.T, listener net.Listener, protocol int32, name string) {
t.Helper()
go func() {
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
if _, err := readPacket(conn); err != nil {
return
}
if _, err := readPacket(conn); err != nil {
return
}
payload := String(fmt.Sprintf(`{"description":"test","players":{"max":0,"online":0},"version":{"name":%q,"protocol":%d}}`, name, protocol))
_ = writePacket(conn, statusClientboundResponse, &payload)
}()
}
func statusTestDestination(t *testing.T, listener net.Listener) xnet.Destination {
t.Helper()
dest, err := xnet.ParseDestination("tcp:" + listener.Addr().String())
if err != nil {
t.Fatal(err)
}
return dest
}
func statusTestDialer(dialErr error) *finalmask.Dialer {
return &finalmask.Dialer{DialTCP: func(dest xnet.Destination) (net.Conn, error) {
if dialErr != nil {
return nil, dialErr
}
return net.Dial("tcp", net.JoinHostPort(dest.Address.String(), strconv.Itoa(int(dest.Port.Value()))))
}}
}
// TestProbeProtocolVersion reads the version out of the status response, which
// is the version the peer's login expects.
func TestProbeProtocolVersion(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
statusTestServer(t, listener, 767, "1.21.1")
dest := statusTestDestination(t, listener)
number, name, err := probeProtocolVersion(&dest, "localhost", statusTestDialer(nil))
if err != nil {
t.Fatalf("probe: %v", err)
}
if number != 767 || name != "1.21.1" {
t.Fatalf("probe = %d %q, want 767 \"1.21.1\"", number, name)
}
}
func TestProbeProtocolVersionRejectsBrokenPeer(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
go func() {
conn, err := listener.Accept()
if err != nil {
return
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
_, _ = readPacket(conn)
_, _ = readPacket(conn)
payload := String(`{"description":"no version here"}`)
_ = writePacket(conn, statusClientboundResponse, &payload)
}()
dest := statusTestDestination(t, listener)
if _, _, err := probeProtocolVersion(&dest, "localhost", statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "no version") {
t.Fatalf("probe error = %v", err)
}
if _, _, err := probeProtocolVersion(&dest, "localhost", nil); err == nil || !strings.Contains(err.Error(), "no TCP dialer") {
t.Fatalf("nil dialer error = %v", err)
}
if _, _, err := probeProtocolVersion(nil, "localhost", statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "no destination") {
t.Fatalf("nil destination error = %v", err)
}
}
// TestDetectProtocolVersionCaches checks a destination is probed once per TTL:
// the second call must answer from the cache even though dialing now fails.
func TestDetectProtocolVersionCaches(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
statusTestServer(t, listener, 776, "26.2")
dest := statusTestDestination(t, listener)
number, name, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(nil))
if err != nil {
t.Fatalf("detect: %v", err)
}
if number != 776 || name != "26.2" {
t.Fatalf("detect = %d %q", number, name)
}
if err := listener.Close(); err != nil {
t.Fatal(err)
}
number, _, err = detectProtocolVersion(&dest, "localhost", statusTestDialer(fmt.Errorf("must not dial")))
if err != nil {
t.Fatalf("cached detect: %v", err)
}
if number != 776 {
t.Fatalf("cached detect = %d", number)
}
}
// TestClientProtocol covers the three ways the client picks its row: a
// configured version, a detected one, and the fallback when the peer does not
// answer status.
func TestClientProtocol(t *testing.T) {
t.Run("configured", func(t *testing.T) {
// No destination and no dialer: a configured version must not probe.
version, err := (&Config{ProtocolVersion: 775}).clientProtocol(nil, nil)
if err != nil || version.number != 775 {
t.Fatalf("configured = %v, %v", version.number, err)
}
})
t.Run("detected", func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
statusTestServer(t, listener, 767, "1.21.1")
dest := statusTestDestination(t, listener)
version, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil))
if err != nil || version.number != 767 || version.name != "1.21.1" {
t.Fatalf("detected = %v %q, %v", version.number, version.name, err)
}
})
t.Run("unknown", func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
statusTestServer(t, listener, 999, "999")
dest := statusTestDestination(t, listener)
if _, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "not in the supported table") {
t.Fatalf("unknown version error = %v", err)
}
})
t.Run("probe failure falls back to the newest row", func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
address := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
dest, err := xnet.ParseDestination("tcp:" + address)
if err != nil {
t.Fatal(err)
}
version, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil))
if err != nil {
t.Fatalf("fallback: %v", err)
}
if version.number != latestProtocolVersion.number {
t.Fatalf("fallback version = %d, want %d", version.number, latestProtocolVersion.number)
}
})
}
// TestForgetProbedVersions covers a stale detection: after a version mismatch
// the cache is dropped, so the next connection probes again instead of reusing
// the row the peer no longer speaks.
func TestForgetProbedVersions(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
statusTestServer(t, listener, 767, "1.21.1")
dest := statusTestDestination(t, listener)
if number, _, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(nil)); err != nil || number != 767 {
t.Fatalf("detect = %v, %v", number, err)
}
forgetProbedVersions()
// The peer now reports another version; a cached answer would hide it.
listener2, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener2.Close()
statusTestServer(t, listener2, 775, "26.1")
dest2 := statusTestDestination(t, listener2)
// A dialer that fails proves the cache was consulted; after forgetting, the
// same destination must probe again.
if err := listener.Close(); err != nil {
t.Fatal(err)
}
if number, _, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(fmt.Errorf("must probe again"))); err == nil {
t.Fatalf("stale cache was reused: %v", number)
}
if number, _, err := detectProtocolVersion(&dest2, "localhost", statusTestDialer(nil)); err != nil || number != 775 {
t.Fatalf("fresh detect = %v, %v", number, err)
}
}
func TestIsProtocolVersionReject(t *testing.T) {
for _, reason := range []string{
`{"translate":"multiplayer.disconnect.incompatible","with":["26.3"]}`,
`{"translate":"multiplayer.disconnect.outdated_client","with":["26.3"]}`,
} {
if !isProtocolVersionReject(reason) {
t.Fatalf("%s should be a version reject", reason)
}
}
if isProtocolVersionReject(`{"translate":"multiplayer.disconnect.not_whitelisted"}`) {
t.Fatal("a whitelist reject is not a version reject")
}
}

Some files were not shown because too many files have changed in this diff Show More