mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-30 21:58:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
919d0ae8eb | ||
|
|
8eac7b41b3 | ||
|
|
ded8443fee | ||
|
|
5780f0df90 | ||
|
|
4d0bfb4d0d | ||
|
|
db6664bd68 | ||
|
|
67756b3674 | ||
|
|
9576662b8e | ||
|
|
c5ccb356aa | ||
|
|
b56ffef338 | ||
|
|
862e59a2f2 | ||
|
|
35805f9377 | ||
|
|
5d8b20239f |
@@ -7,7 +7,6 @@ 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"
|
||||
@@ -184,9 +183,6 @@ 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
-23
@@ -15,8 +15,6 @@ const (
|
||||
|
||||
var ErrBufferFull = errors.New("buffer is full")
|
||||
|
||||
var pool = bytespool.GetPool(Size)
|
||||
|
||||
// ownership represents the data owner of the buffer.
|
||||
type ownership uint8
|
||||
|
||||
@@ -39,16 +37,7 @@ type Buffer struct {
|
||||
|
||||
// New creates a Buffer with 0 length and 8K capacity, managed.
|
||||
func New() *Buffer {
|
||||
buf := pool.Get().([]byte)
|
||||
if cap(buf) >= Size {
|
||||
buf = buf[:Size]
|
||||
} else {
|
||||
buf = make([]byte, Size)
|
||||
}
|
||||
|
||||
return &Buffer{
|
||||
v: buf,
|
||||
}
|
||||
return &Buffer{v: bytespool.Alloc(Size)}
|
||||
}
|
||||
|
||||
// NewExisted creates a standard size Buffer with an existed bytearray, managed.
|
||||
@@ -80,16 +69,7 @@ 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 {
|
||||
buf := pool.Get().([]byte)
|
||||
if cap(buf) >= Size {
|
||||
buf = buf[:Size]
|
||||
} else {
|
||||
buf = make([]byte, Size)
|
||||
}
|
||||
|
||||
return Buffer{
|
||||
v: buf,
|
||||
}
|
||||
return Buffer{v: bytespool.Alloc(Size)}
|
||||
}
|
||||
|
||||
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
|
||||
@@ -113,7 +93,7 @@ func (b *Buffer) Release() {
|
||||
switch b.ownership {
|
||||
case managed:
|
||||
if cap(p) == Size {
|
||||
pool.Put(p)
|
||||
bytespool.Free(p)
|
||||
}
|
||||
case bytespools:
|
||||
bytespool.Free(p)
|
||||
|
||||
+64
-52
@@ -1,72 +1,84 @@
|
||||
package bytespool
|
||||
|
||||
import "sync"
|
||||
import (
|
||||
"math/bits"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func createAllocFunc(size int32) func() interface{} {
|
||||
return func() interface{} {
|
||||
return make([]byte, size)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
minShift = 10 // 1KB
|
||||
maxShift = 16 // 64KB
|
||||
numPools = maxShift - minShift + 1
|
||||
minSize = 1 << minShift
|
||||
maxSize = 1 << maxShift
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
// 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) }},
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024.
|
||||
//
|
||||
// xray:api:stable
|
||||
func Alloc(size int32) []byte {
|
||||
pool := GetPool(size)
|
||||
if pool != nil {
|
||||
return pool.Get().([]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")
|
||||
}
|
||||
return make([]byte, size)
|
||||
}
|
||||
|
||||
// Free puts a byte slice into the internal pool.
|
||||
//
|
||||
// xray:api:stable
|
||||
func Free(b []byte) {
|
||||
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
|
||||
}
|
||||
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]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,18 +191,10 @@ func getConfig() string {
|
||||
{
|
||||
"protocol": "vless",
|
||||
"settings": {
|
||||
"vnext": [
|
||||
{
|
||||
"address": "1.2.3.4",
|
||||
"port": 1234,
|
||||
"users": [
|
||||
{
|
||||
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
|
||||
"encryption": "none"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
"address": "1.2.3.4",
|
||||
"port": 1234,
|
||||
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
|
||||
"encryption": "none"
|
||||
},
|
||||
"tag": "XHTTP_IN",
|
||||
"streamSettings": {
|
||||
|
||||
@@ -71,7 +71,6 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
|
||||
}
|
||||
common.CloseIfExists(t.checkTask)
|
||||
t.checkTask = newCheckTask
|
||||
t.Update()
|
||||
common.Must(newCheckTask.Start())
|
||||
}
|
||||
|
||||
|
||||
@@ -58,15 +58,11 @@ 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
|
||||
}
|
||||
|
||||
|
||||
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 5)
|
||||
common.Must(task.Close())
|
||||
if value != 3 {
|
||||
t.Fatal("expected 3, but got ", value)
|
||||
if value != 2 {
|
||||
t.Fatal("expected 2, but got ", value)
|
||||
}
|
||||
time.Sleep(time.Second * 4)
|
||||
if value != 3 {
|
||||
t.Fatal("expected 3, but got ", value)
|
||||
if value != 2 {
|
||||
t.Fatal("expected 2, but got ", value)
|
||||
}
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 3)
|
||||
if value != 5 {
|
||||
t.Fatal("Expected 5, but ", value)
|
||||
if value != 3 {
|
||||
t.Fatal("Expected 3, but ", value)
|
||||
}
|
||||
common.Must(task.Close())
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
|
||||
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.1
|
||||
lukechampine.com/blake3 v1.5.3
|
||||
mvdan.cc/gofumpt v0.12.0
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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/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/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.1 h1:ITRyxe0LlLZcPUWOZ3Taz8mbug/ptn7jbbeeij5ZiPo=
|
||||
lukechampine.com/blake3 v1.5.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
lukechampine.com/blake3 v1.5.3 h1:q4Ru9Zisjt/knP3KQYuk63VDPnREbSOA6cuL6UwrDlI=
|
||||
lukechampine.com/blake3 v1.5.3/go.mod h1:+mObCTICmKFFJzAZ+4qqw23+LrWOuO+Zfj3DQiNQFXs=
|
||||
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
|
||||
mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
|
||||
|
||||
+24
-63
@@ -1,9 +1,6 @@
|
||||
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"
|
||||
@@ -49,73 +46,37 @@ 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"`
|
||||
Servers []*HTTPRemoteConfig `json:"servers"`
|
||||
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"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
}
|
||||
|
||||
func (v *HTTPClientConfig) Build() (proto.Message, error) {
|
||||
config := new(http.ClientConfig)
|
||||
if v.Address != nil {
|
||||
v.Servers = []*HTTPRemoteConfig{
|
||||
{
|
||||
Address: v.Address,
|
||||
Port: v.Port,
|
||||
},
|
||||
}
|
||||
if len(v.Username) > 0 {
|
||||
v.Servers[0].Users = []json.RawMessage{{}}
|
||||
}
|
||||
|
||||
server := &protocol.ServerEndpoint{
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
}
|
||||
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
|
||||
if len(v.Username) > 0 {
|
||||
account := &HTTPAccount{
|
||||
Username: v.Username,
|
||||
Password: v.Password,
|
||||
}
|
||||
user := &protocol.User{
|
||||
Level: v.Level,
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(account.Build()),
|
||||
}
|
||||
server.User = user
|
||||
}
|
||||
|
||||
config.Server = server
|
||||
config.Header = make([]*http.Header, 0, 32)
|
||||
for key, value := range v.Headers {
|
||||
config.Header = append(config.Header, &http.Header{
|
||||
|
||||
+22
-48
@@ -177,7 +177,7 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type ShadowsocksServerTarget struct {
|
||||
type ShadowsocksClientConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level byte `json:"level"`
|
||||
@@ -186,69 +186,43 @@ type ShadowsocksServerTarget 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 {
|
||||
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 {
|
||||
if v.Address == nil {
|
||||
return nil, errors.New("Shadowsocks server address is not set.")
|
||||
}
|
||||
if server.Port == 0 {
|
||||
if v.Port == 0 {
|
||||
return nil, errors.New("Invalid Shadowsocks port.")
|
||||
}
|
||||
if server.Password == "" {
|
||||
if v.Password == "" {
|
||||
return nil, errors.New("Shadowsocks password is not specified.")
|
||||
}
|
||||
|
||||
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
|
||||
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,
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
config := new(shadowsocks.ClientConfig)
|
||||
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)
|
||||
if cipherFromString(v.Cipher) == shadowsocks.CipherType_UNKNOWN {
|
||||
return nil, errors.New("unknown cipher method: ", v.Cipher)
|
||||
}
|
||||
ss := &protocol.ServerEndpoint{
|
||||
Address: server.Address.Build(),
|
||||
Port: uint32(server.Port),
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
User: &protocol.User{
|
||||
Level: uint32(server.Level),
|
||||
Email: server.Email,
|
||||
Account: serial.ToTypedMessage(account),
|
||||
Level: uint32(v.Level),
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(&shadowsocks.Account{
|
||||
Password: v.Password,
|
||||
CipherType: cipherFromString(v.Cipher),
|
||||
}),
|
||||
},
|
||||
}
|
||||
config.Server = ss
|
||||
|
||||
+23
-62
@@ -1,9 +1,6 @@
|
||||
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"
|
||||
@@ -67,71 +64,35 @@ 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"`
|
||||
Servers []*SocksRemoteConfig `json:"servers"`
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"user"`
|
||||
Password string `json:"pass"`
|
||||
}
|
||||
|
||||
func (v *SocksClientConfig) Build() (proto.Message, error) {
|
||||
config := new(socks.ClientConfig)
|
||||
if v.Address != nil {
|
||||
v.Servers = []*SocksRemoteConfig{
|
||||
{
|
||||
Address: v.Address,
|
||||
Port: v.Port,
|
||||
},
|
||||
}
|
||||
if len(v.Username) > 0 {
|
||||
v.Servers[0].Users = []json.RawMessage{{}}
|
||||
}
|
||||
|
||||
server := &protocol.ServerEndpoint{
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
}
|
||||
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
|
||||
if len(v.Username) > 0 {
|
||||
account := &SocksAccount{
|
||||
Username: v.Username,
|
||||
Password: v.Password,
|
||||
}
|
||||
user := &protocol.User{
|
||||
Level: v.Level,
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(account.Build()),
|
||||
}
|
||||
server.User = user
|
||||
}
|
||||
|
||||
config.Server = server
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -53,35 +53,6 @@ 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",
|
||||
|
||||
@@ -975,6 +975,17 @@ 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 {
|
||||
@@ -1040,7 +1051,21 @@ func (c *XMC) Build() (proto.Message, error) {
|
||||
if noPadding && len(c.Paddings) > 0 {
|
||||
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
|
||||
}
|
||||
config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding}
|
||||
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
|
||||
for i, turn := range c.Paddings {
|
||||
minimum, maximum, err := ParseRangeString(turn.Length)
|
||||
if err != nil {
|
||||
|
||||
@@ -242,3 +242,93 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
@@ -541,12 +541,9 @@ 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 + `}, ` + 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 + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + 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": {"address": "127.0.0.1", "port": 443, ` + 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"},
|
||||
|
||||
+21
-60
@@ -17,76 +17,41 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// TrojanServerTarget is configuration of a single trojan server
|
||||
type TrojanServerTarget struct {
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// 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{}
|
||||
|
||||
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`, ``)
|
||||
}
|
||||
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.")
|
||||
}
|
||||
|
||||
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
|
||||
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,
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
return config, nil
|
||||
@@ -107,7 +72,6 @@ type TrojanUserConfig struct {
|
||||
Password string `json:"password"`
|
||||
Level byte `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Flow string `json:"flow"`
|
||||
}
|
||||
|
||||
// TrojanServerConfig is Inbound configuration
|
||||
@@ -131,9 +95,6 @@ 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),
|
||||
|
||||
@@ -159,6 +159,7 @@ 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",
|
||||
|
||||
+96
-141
@@ -256,26 +256,19 @@ 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"`
|
||||
Vnext []*VLessOutboundVnext `json:"vnext"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
@@ -286,130 +279,92 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
|
||||
if c.Address != nil {
|
||||
c.Vnext = []*VLessOutboundVnext{
|
||||
{
|
||||
Address: c.Address,
|
||||
Port: c.Port,
|
||||
Users: []json.RawMessage{{}},
|
||||
},
|
||||
}
|
||||
if c.Address == nil {
|
||||
return nil, errors.New(`VLESS: "address" is not set`)
|
||||
}
|
||||
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`)
|
||||
}
|
||||
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`)
|
||||
}
|
||||
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(`VLESS users: invalid user`).Base(err)
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
config.Vnext = spec
|
||||
break
|
||||
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
|
||||
}
|
||||
account.Reverse = rvs
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
config.Vnext = spec
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -18,41 +18,6 @@ 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",
|
||||
|
||||
+31
-70
@@ -102,22 +102,15 @@ 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"`
|
||||
Receivers []*VMessOutboundTarget `json:"vnext"`
|
||||
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"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
@@ -129,62 +122,30 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
u, err := uuid.ParseString(account.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.ID = u.String()
|
||||
|
||||
user.Account = serial.ToTypedMessage(account.Build())
|
||||
spec.User = user
|
||||
break
|
||||
}
|
||||
config.Receiver = spec
|
||||
break
|
||||
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
|
||||
}
|
||||
|
||||
account := &VMessAccount{
|
||||
ID: uid.String(),
|
||||
Security: c.Security,
|
||||
Experiments: c.Experiments,
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -18,42 +18,6 @@ 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",
|
||||
|
||||
+14
-4
@@ -238,7 +238,7 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
||||
}
|
||||
|
||||
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
|
||||
if requiresTransportSecurity(tjCfg.Servers[0].Address) {
|
||||
if requiresTransportSecurity(tjCfg.Address) {
|
||||
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
|
||||
}
|
||||
}
|
||||
@@ -265,8 +265,13 @@ 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 && (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.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.Testpre != 0 {
|
||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
||||
@@ -367,10 +372,15 @@ 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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
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))
|
||||
}
|
||||
+39
-14
@@ -5,6 +5,7 @@ import (
|
||||
go_errors "errors"
|
||||
"io"
|
||||
"math/rand"
|
||||
"slices"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -174,10 +175,15 @@ 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 {
|
||||
@@ -193,21 +199,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
for i, b := range mb {
|
||||
addr := w.addr
|
||||
if b.UDP != nil {
|
||||
addr = b.UDP.NetAddr()
|
||||
if *b.UDP != w.lastUDP {
|
||||
w.lastUDP = *b.UDP
|
||||
w.lastUDPAddr = b.UDP.NetAddr()
|
||||
}
|
||||
addr = w.lastUDPAddr
|
||||
}
|
||||
|
||||
msg := &UDPMessage{
|
||||
SessionID: 0,
|
||||
PacketID: 0,
|
||||
FragID: 0,
|
||||
FragCount: 1,
|
||||
Addr: addr,
|
||||
Data: b.Bytes(),
|
||||
}
|
||||
|
||||
err := w.SendMessage(msg)
|
||||
var errTooLarge *quic.DatagramTooLargeError
|
||||
if go_errors.As(err, &errTooLarge) {
|
||||
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
|
||||
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
|
||||
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
|
||||
for _, fMsg := range fMsgs {
|
||||
@@ -228,40 +234,59 @@ 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 {
|
||||
var packet [1500]byte
|
||||
|
||||
n, err := r.reader.Read(packet[:])
|
||||
n, err := r.reader.Read(r.packet[:])
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
msg, err := ParseUDPMessage(packet[:n])
|
||||
if err != nil {
|
||||
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); 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
|
||||
}
|
||||
|
||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||
if err != 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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
+28
-20
@@ -1,7 +1,6 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -183,35 +182,44 @@ func (m *UDPMessage) Serialize(buf []byte) int {
|
||||
}
|
||||
|
||||
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
|
||||
m := &UDPMessage{}
|
||||
buf := bytes.NewBuffer(msg)
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
|
||||
m := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, "", m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); 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.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)
|
||||
lAddr, n, err := quicvarint.Parse(msg[8:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
if lAddr == 0 || lAddr > MaxMessageLength {
|
||||
return nil, errors.New("invalid address length")
|
||||
return errors.New("invalid address length")
|
||||
}
|
||||
bs := buf.Bytes()
|
||||
bs := msg[8+n:]
|
||||
if len(bs) <= int(lAddr) {
|
||||
// We use <= instead of < here as we expect at least one byte of data after the address
|
||||
return nil, errors.New("invalid message length")
|
||||
return errors.New("invalid message length")
|
||||
}
|
||||
m.Addr = string(bs[:lAddr])
|
||||
m.Data = bs[lAddr:]
|
||||
return m, nil
|
||||
*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
|
||||
}
|
||||
|
||||
// varintPut is like quicvarint.Append, but instead of appending to a slice,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,21 +53,23 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
udpCodec, err := NewUDPServerCodec(method, psk, 500*time.Second)
|
||||
user := &protocol.MemoryUser{
|
||||
Email: config.Email,
|
||||
Level: uint32(config.Level),
|
||||
}
|
||||
|
||||
udpCodec, err := NewUDPServerCodec(method, psk, user, 500*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
return &Inbound{
|
||||
networks: networks,
|
||||
method: method,
|
||||
psk: psk,
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
user: &protocol.MemoryUser{
|
||||
Email: config.Email,
|
||||
Level: uint32(config.Level),
|
||||
},
|
||||
networks: networks,
|
||||
method: method,
|
||||
psk: psk,
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
user: user,
|
||||
udpCodec: udpCodec,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}, nil
|
||||
@@ -155,20 +157,12 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
|
||||
}
|
||||
|
||||
for _, b := range mb {
|
||||
decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
||||
sessionItem, decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
||||
b.Release()
|
||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
||||
continue
|
||||
}
|
||||
|
||||
sessionItem := i.udpCodec.GetSession(decoded.SessionID)
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = i.user
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
|
||||
@@ -2,8 +2,6 @@ package shadowsocks_2022
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -34,16 +32,15 @@ func init() {
|
||||
|
||||
type MultiUserInbound struct {
|
||||
sync.Mutex
|
||||
networks []net.Network
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
|
||||
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
userCount atomic.Int64
|
||||
saltFilter *antireplay.ReplayFilter[[32]byte]
|
||||
udpSessions *UDPSessionManager
|
||||
udpMasterCipher cipher.Block
|
||||
policyManager policy.Manager
|
||||
networks []net.Network
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
|
||||
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
userCount atomic.Int64
|
||||
saltFilter *antireplay.ReplayFilter[[32]byte]
|
||||
udpCodec *UDPMultiServerCodec
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) {
|
||||
@@ -68,22 +65,21 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
|
||||
return nil, err
|
||||
}
|
||||
|
||||
masterBlock, err := method.NewBlock(masterPSK)
|
||||
udpCodec, err := NewUDPMultiServerCodec(method, masterPSK, 500*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
i := &MultiUserInbound{
|
||||
networks: networks,
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
|
||||
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
udpSessions: NewUDPSessionManager(500 * time.Second),
|
||||
udpMasterCipher: masterBlock,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
networks: networks,
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
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),
|
||||
}
|
||||
|
||||
for idx, user := range config.Users {
|
||||
@@ -281,68 +277,26 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
|
||||
for _, b := range mb {
|
||||
// In multi-user UDP:
|
||||
// Packet header is 16 bytes: Encrypted(SessionID + PacketID)
|
||||
// Followed by 16 bytes EIH
|
||||
packetBytes := b.Bytes()
|
||||
if len(packetBytes) < 32+1+8+2 {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
var rawHeader [16]byte
|
||||
i.udpMasterCipher.Decrypt(rawHeader[:], packetBytes[:16])
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := i.udpSessions.GetOrCreate(sessionID)
|
||||
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
var userPSK []byte
|
||||
var currentUser *protocol.MemoryUser
|
||||
sessionItem.Lock()
|
||||
currentUser = sessionItem.User
|
||||
userPSK = sessionItem.UserPSK
|
||||
sessionItem.Unlock()
|
||||
|
||||
if currentUser == nil {
|
||||
// Decrypt EIH
|
||||
decryptedHash := DecryptUDPEIH(i.udpMasterCipher, rawHeader[:], packetBytes[16:32])
|
||||
|
||||
user, ok := i.usersByHash.Load(decryptedHash)
|
||||
sessionItem, decoded, user, err := i.udpCodec.DecodePacket(b.Bytes(), func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool) {
|
||||
u, ok := i.usersByHash.Load(hash)
|
||||
if !ok {
|
||||
b.Release()
|
||||
continue
|
||||
return nil, nil, false
|
||||
}
|
||||
currentUser = user
|
||||
userPSK = user.Account.(*MemoryAccount).Key
|
||||
}
|
||||
|
||||
decoded, err := sessionItem.DecryptAESPayload(i.method, userPSK, sessionID, packetID, rawHeader[:], packetBytes[32:])
|
||||
return u, u.Account.(*MemoryAccount).Key, true
|
||||
})
|
||||
b.Release()
|
||||
if err != nil {
|
||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
||||
continue
|
||||
}
|
||||
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = currentUser
|
||||
sessionItem.UserPSK = userPSK
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
} else {
|
||||
userPSK := user.Account.(*MemoryAccount).Key
|
||||
var err error
|
||||
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
|
||||
return i.udpCodec.EncodeServerPacket(decoded.SessionID, userPSK, replyDest, payload)
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -356,7 +310,3 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (i *MultiUserInbound) encodeServerUDPPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.udpSessions.EncodeServerPacket(i.method, userPSK, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
@@ -243,16 +243,14 @@ func (i *RelayInbound) processUDP(ctx context.Context, conn stat.Connection, dis
|
||||
dest.Network = net.Network_UDP
|
||||
|
||||
sessionItem := i.udpSessions.GetOrCreate(sessionID)
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = &protocol.MemoryUser{
|
||||
Email: targetDest.email,
|
||||
Level: targetDest.level,
|
||||
}
|
||||
sessionItem.User = &protocol.MemoryUser{
|
||||
Email: targetDest.email,
|
||||
Level: targetDest.level,
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
|
||||
@@ -30,7 +30,7 @@ type Outbound struct {
|
||||
method *CipherMethod
|
||||
pskList [][]byte
|
||||
finalPSK []byte
|
||||
udpCodec *UDPPacketCodec
|
||||
udpCodec *UDPClientCodec
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
@@ -50,9 +50,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Outbound, error) {
|
||||
}
|
||||
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
udpCodec, err := NewUDPPacketCodec(method, pskList)
|
||||
udpCodec, err := NewUDPClientCodec(method, pskList)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to create udp packet codec").Base(err)
|
||||
return nil, errors.New("failed to create udp client codec").Base(err)
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
|
||||
+292
-147
@@ -7,33 +7,78 @@ import (
|
||||
"io"
|
||||
"math"
|
||||
mrand "math/rand/v2"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
)
|
||||
|
||||
type UDPCodec struct {
|
||||
type UDPClientCodec struct {
|
||||
method *CipherMethod
|
||||
pskList [][]byte
|
||||
psk []byte
|
||||
blockCipher cipher.Block
|
||||
blockCiphers []cipher.Block
|
||||
chachaCipher cipher.AEAD
|
||||
}
|
||||
|
||||
func NewUDPClientCodec(method *CipherMethod, pskList [][]byte) (*UDPClientCodec, error) {
|
||||
if len(pskList) == 0 {
|
||||
return nil, errors.New("empty psk list")
|
||||
}
|
||||
if method.IsChaCha && len(pskList) > 1 {
|
||||
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
|
||||
}
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
c := &UDPClientCodec{
|
||||
method: method,
|
||||
pskList: pskList,
|
||||
psk: finalPSK,
|
||||
}
|
||||
var err error
|
||||
if method.IsChaCha {
|
||||
c.chachaCipher, err = method.NewUDPCipher(finalPSK)
|
||||
} else {
|
||||
c.blockCipher, err = method.NewBlock(finalPSK)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(pskList) > 1 {
|
||||
c.blockCiphers = make([]cipher.Block, len(pskList))
|
||||
for i, psk := range pskList {
|
||||
c.blockCiphers[i], err = method.NewBlock(psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPClientCodec, error) {
|
||||
return NewUDPClientCodec(method, pskList)
|
||||
}
|
||||
|
||||
type UDPServerCodec struct {
|
||||
method *CipherMethod
|
||||
psk []byte
|
||||
user *protocol.MemoryUser
|
||||
blockCipher cipher.Block
|
||||
chachaCipher cipher.AEAD
|
||||
sessions *UDPSessionManager
|
||||
}
|
||||
|
||||
type (
|
||||
UDPPacketCodec = UDPCodec
|
||||
UDPServerCodec = UDPCodec
|
||||
)
|
||||
|
||||
func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
|
||||
c := &UDPCodec{
|
||||
method: method,
|
||||
psk: psk,
|
||||
func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUser, sessionTimeout time.Duration) (*UDPServerCodec, error) {
|
||||
c := &UDPServerCodec{
|
||||
method: method,
|
||||
psk: psk,
|
||||
user: user,
|
||||
sessions: NewUDPSessionManager(sessionTimeout),
|
||||
}
|
||||
var err error
|
||||
if method.IsChaCha {
|
||||
@@ -47,46 +92,129 @@ func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPCodec, error) {
|
||||
if method.IsChaCha && len(pskList) > 1 {
|
||||
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
|
||||
}
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
c, err := newUDPCodec(method, finalPSK)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.pskList = pskList
|
||||
if len(pskList) > 1 {
|
||||
c.blockCiphers = make([]cipher.Block, len(pskList))
|
||||
for i, psk := range pskList {
|
||||
c.blockCiphers[i], err = method.NewBlock(psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPServerCodec(method *CipherMethod, psk []byte, sessionTimeout time.Duration) (*UDPCodec, error) {
|
||||
c, err := newUDPCodec(method, psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.sessions = NewUDPSessionManager(sessionTimeout)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) Sessions() *UDPSessionManager {
|
||||
func (c *UDPServerCodec) Sessions() *UDPSessionManager {
|
||||
return c.sessions
|
||||
}
|
||||
|
||||
func (c *UDPCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
func (c *UDPServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
if c.sessions == nil {
|
||||
return nil
|
||||
}
|
||||
return c.sessions.GetOrCreate(sessionID)
|
||||
return c.sessions.Get(sessionID)
|
||||
}
|
||||
|
||||
type UDPMultiServerCodec struct {
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
masterBlock cipher.Block
|
||||
sessions *UDPSessionManager
|
||||
}
|
||||
|
||||
func NewUDPMultiServerCodec(method *CipherMethod, masterPSK []byte, sessionTimeout time.Duration) (*UDPMultiServerCodec, error) {
|
||||
if method.IsChaCha {
|
||||
return nil, errors.New("multi-user is not supported for chacha20-poly1305")
|
||||
}
|
||||
masterBlock, err := method.NewBlock(masterPSK)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UDPMultiServerCodec{
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
masterBlock: masterBlock,
|
||||
sessions: NewUDPSessionManager(sessionTimeout),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) Sessions() *UDPSessionManager {
|
||||
return c.sessions
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
if c.sessions == nil {
|
||||
return nil
|
||||
}
|
||||
return c.sessions.Get(sessionID)
|
||||
}
|
||||
|
||||
type UserLookupFunc func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool)
|
||||
|
||||
func (c *UDPMultiServerCodec) DecodePacket(data []byte, userLookup UserLookupFunc) (*ServerUDPSession, DecodedUDPPacket, *protocol.MemoryUser, error) {
|
||||
if len(data) < 2*AESBlockSize+AEADTagSize+RequestHeaderFixedChunkLength {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketTooShort
|
||||
}
|
||||
|
||||
var rawHeader [16]byte
|
||||
c.masterBlock.Decrypt(rawHeader[:], data[:16])
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := c.sessions.Get(sessionID)
|
||||
var currentUser *protocol.MemoryUser
|
||||
var userPSK []byte
|
||||
var bodyAead cipher.AEAD
|
||||
|
||||
if sessionItem != nil {
|
||||
sessionItem.Lock()
|
||||
currentUser = sessionItem.User
|
||||
userPSK = sessionItem.UserPSK
|
||||
bodyAead = sessionItem.clientBodyCipher
|
||||
sessionItem.Unlock()
|
||||
|
||||
if currentUser != nil {
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketIdNotUnique
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if currentUser == nil {
|
||||
decryptedHash := DecryptUDPEIH(c.masterBlock, rawHeader[:], data[16:32])
|
||||
user, psk, ok := userLookup(decryptedHash)
|
||||
if !ok {
|
||||
return nil, DecodedUDPPacket{}, nil, errors.New("user not found")
|
||||
}
|
||||
currentUser = user
|
||||
userPSK = psk
|
||||
}
|
||||
|
||||
if bodyAead == nil {
|
||||
bodyKey := DeriveSessionSubKey(userPSK, rawHeader[:8], c.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = c.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[32:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, err
|
||||
}
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrBadHeaderType
|
||||
}
|
||||
|
||||
if sessionItem == nil {
|
||||
sessionItem = c.sessions.GetOrCreate(sessionID)
|
||||
}
|
||||
if !sessionItem.Commit(packetID, bodyAead, currentUser, userPSK) {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return sessionItem, decoded, currentUser, nil
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) EncodeServerPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return c.sessions.EncodeServerPacket(c.method, userPSK, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
type DecodedUDPPacket struct {
|
||||
@@ -193,44 +321,42 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUDPPacket, error) {
|
||||
if len(data) < PacketMinimalHeaderSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
if c.method.IsChaCha {
|
||||
if len(data) < PacketNonceSize+AEADTagSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
nonce := data[:PacketNonceSize]
|
||||
ciphertext := data[PacketNonceSize:]
|
||||
plain, err := c.chachaCipher.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||
}
|
||||
if len(plain) < 16+1+8+2 {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(plain[:8])
|
||||
packetID := binary.BigEndian.Uint64(plain[8:16])
|
||||
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
|
||||
sessionItem.AddPacketID(packetID)
|
||||
return decoded, nil
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.Commit(packetID, nil, c.user, c.psk) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
return sessionItem, decoded, nil
|
||||
}
|
||||
|
||||
// AES mode
|
||||
@@ -239,49 +365,48 @@ func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
sessionItem := c.sessions.Get(sessionID)
|
||||
var bodyAead cipher.AEAD
|
||||
if sessionItem != nil {
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
sessionItem.Lock()
|
||||
bodyAead = sessionItem.clientBodyCipher
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
|
||||
return sessionItem.DecryptAESPayload(c.method, c.psk, sessionID, packetID, rawHeader[:], data[16:])
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) DecryptAESPayload(method *CipherMethod, psk []byte, sessionID, packetID uint64, rawHeader, bodyCipher []byte) (DecodedUDPPacket, error) {
|
||||
bodyAead := s.clientBodyCipher
|
||||
isNewCipher := false
|
||||
if bodyAead == nil {
|
||||
bodyKey := DeriveSessionSubKey(psk, rawHeader[:8], method.KeySaltLength)
|
||||
bodyKey := DeriveSessionSubKey(c.psk, rawHeader[:8], c.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = method.NewAEAD(bodyKey)
|
||||
bodyAead, err = c.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
isNewCipher = true
|
||||
}
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[16:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
|
||||
s.AddPacketID(packetID)
|
||||
|
||||
if isNewCipher {
|
||||
s.clientBodyCipher = bodyAead
|
||||
if sessionItem == nil {
|
||||
sessionItem = c.sessions.GetOrCreate(sessionID)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
if !sessionItem.Commit(packetID, bodyAead, c.user, c.psk) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
return sessionItem, decoded, nil
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error {
|
||||
@@ -303,6 +428,9 @@ func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) e
|
||||
if method.IsChaCha {
|
||||
var err error
|
||||
s.serverChaCha, err = method.NewUDPCipher(psk)
|
||||
if err != nil {
|
||||
s.ServerSessionID = 0
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -387,11 +515,12 @@ func (s *ServerUDPSession) EncodeServerPacket(method *CipherMethod, clientSessio
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
func (c *UDPServerCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return c.sessions.EncodeServerPacket(c.method, c.psk, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
type serverSessionState struct {
|
||||
sync.Mutex
|
||||
sessionID uint64
|
||||
window *SlidingWindow
|
||||
cipher cipher.AEAD
|
||||
@@ -399,21 +528,24 @@ type serverSessionState struct {
|
||||
}
|
||||
|
||||
func (st *serverSessionState) check(packetID uint64) bool {
|
||||
if st.window == nil {
|
||||
st.window = new(SlidingWindow)
|
||||
}
|
||||
st.Lock()
|
||||
defer st.Unlock()
|
||||
return st.window.Check(packetID)
|
||||
}
|
||||
|
||||
func (st *serverSessionState) add(packetID uint64) {
|
||||
if st.window == nil {
|
||||
st.window = new(SlidingWindow)
|
||||
func (st *serverSessionState) commit(packetID uint64, now int64) bool {
|
||||
st.Lock()
|
||||
defer st.Unlock()
|
||||
if !st.window.CheckAndAdd(packetID) {
|
||||
return false
|
||||
}
|
||||
st.window.Add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
return true
|
||||
}
|
||||
|
||||
type ClientUDPSession struct {
|
||||
codec *UDPCodec
|
||||
mu sync.Mutex
|
||||
codec *UDPClientCodec
|
||||
clientSessionID uint64
|
||||
nextPacketID atomic.Uint64
|
||||
clientBodyCipher cipher.AEAD
|
||||
@@ -421,7 +553,7 @@ type ClientUDPSession struct {
|
||||
old atomic.Pointer[serverSessionState]
|
||||
}
|
||||
|
||||
func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
var sessID [8]byte
|
||||
if _, err := io.ReadFull(rand.Reader, sessID[:]); err != nil {
|
||||
return nil, err
|
||||
@@ -446,51 +578,43 @@ func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ClientUDPSession) getServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||
cur := s.current.Load()
|
||||
if cur != nil && cur.sessionID == sessionID {
|
||||
func (s *ClientUDPSession) findServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||
if cur := s.current.Load(); cur != nil && cur.sessionID == sessionID {
|
||||
return cur, nil
|
||||
}
|
||||
|
||||
old := s.old.Load()
|
||||
if old != nil && old.sessionID == sessionID {
|
||||
if now-old.lastSeen.Load() > 60 {
|
||||
s.old.CompareAndSwap(old, nil)
|
||||
return nil, errors.New("old server session expired")
|
||||
if old := s.old.Load(); old != nil {
|
||||
if old.sessionID == sessionID {
|
||||
if now-old.lastSeen.Load() > 60 {
|
||||
return nil, errors.New("old server session expired")
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
|
||||
// New server session:
|
||||
// Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
|
||||
if old != nil && now-old.lastSeen.Load() < 60 {
|
||||
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
|
||||
}
|
||||
|
||||
var bodyAead cipher.AEAD
|
||||
if !s.codec.method.IsChaCha {
|
||||
var sessBytes [8]byte
|
||||
binary.BigEndian.PutUint64(sessBytes[:], sessionID)
|
||||
bodyKey := DeriveSessionSubKey(s.codec.psk, sessBytes[:], s.codec.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = s.codec.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
|
||||
if now-old.lastSeen.Load() < 60 {
|
||||
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *ClientUDPSession) transitionServerSession(sessionID uint64, cipher cipher.AEAD, now int64) (*serverSessionState, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if st, err := s.findServerSession(sessionID, now); st != nil || err != nil {
|
||||
return st, err
|
||||
}
|
||||
|
||||
newState := &serverSessionState{
|
||||
sessionID: sessionID,
|
||||
cipher: bodyAead,
|
||||
window: new(SlidingWindow),
|
||||
cipher: cipher,
|
||||
}
|
||||
newState.lastSeen.Store(now)
|
||||
|
||||
if cur == nil {
|
||||
s.current.CompareAndSwap(nil, newState)
|
||||
return s.current.Load(), nil
|
||||
if cur := s.current.Load(); cur != nil {
|
||||
s.old.Store(cur)
|
||||
}
|
||||
|
||||
s.old.Store(cur)
|
||||
s.current.Store(newState)
|
||||
return newState, nil
|
||||
}
|
||||
@@ -505,7 +629,7 @@ func (s *ClientUDPSession) EncodePacket(dest net.Destination, payload []byte) (*
|
||||
|
||||
var paddingLen int
|
||||
if dest.Port == 53 && len(payload) < MaxPaddingLength {
|
||||
paddingLen = mrand.IntN(MaxPaddingLength) + 1
|
||||
paddingLen = mrand.IntN(MaxPaddingLength-len(payload)) + 1
|
||||
}
|
||||
|
||||
addrPortLen := AddrPortLength(dest)
|
||||
@@ -620,6 +744,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
||||
if s.codec.method.IsChaCha {
|
||||
if len(data) < PacketNonceSize+AEADTagSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
@@ -637,20 +763,10 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(plain[:8])
|
||||
packetID := binary.BigEndian.Uint64(plain[8:16])
|
||||
|
||||
now := time.Now().Unix()
|
||||
st, err := s.getServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeServer {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
@@ -658,8 +774,20 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||
}
|
||||
|
||||
st.add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
st, err := s.findServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if st == nil {
|
||||
st, err = s.transitionServerSession(sessionID, nil, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if !st.commit(packetID, now) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
@@ -670,19 +798,29 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
now := time.Now().Unix()
|
||||
st, err := s.getServerSession(sessionID, now)
|
||||
st, err := s.findServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
|
||||
var bodyAead cipher.AEAD
|
||||
if st != nil {
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
bodyAead = st.cipher
|
||||
} else {
|
||||
var sessBytes [8]byte
|
||||
binary.BigEndian.PutUint64(sessBytes[:], sessionID)
|
||||
bodyKey := DeriveSessionSubKey(s.codec.psk, sessBytes[:], s.codec.method.KeySaltLength)
|
||||
bodyAead, err = s.codec.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
bodyAead := st.cipher
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[16:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, data[16:], nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
@@ -691,7 +829,6 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeServer {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
@@ -699,8 +836,16 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||
}
|
||||
|
||||
st.add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
if st == nil {
|
||||
st, err = s.transitionServerSession(sessionID, bodyAead, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if !st.commit(packetID, now) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
// Verify downstream destination can decode both packets
|
||||
method, err := GetCipherMethod(MethodAES128GCM)
|
||||
common.Must(err)
|
||||
destCodec, err := NewUDPServerCodec(method, destKey, 300*time.Second)
|
||||
destCodec, err := NewUDPServerCodec(method, destKey, nil, 300*time.Second)
|
||||
common.Must(err)
|
||||
|
||||
mu.Lock()
|
||||
@@ -202,7 +202,8 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
t.Fatalf("expected 2 received packets at destination, got %d", len(pkts))
|
||||
}
|
||||
|
||||
dec1, err := destCodec.DecodePacket(pkts[0])
|
||||
dec1, dec2 := DecodedUDPPacket{}, DecodedUDPPacket{}
|
||||
_, dec1, err = destCodec.DecodePacket(pkts[0])
|
||||
if err != nil {
|
||||
t.Fatalf("dest failed to decode packet 1: %v", err)
|
||||
}
|
||||
@@ -210,7 +211,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
t.Fatalf("dec1 mismatch: sess=%x, pktID=%d, payload=%s", dec1.SessionID, dec1.PacketID, string(dec1.Payload))
|
||||
}
|
||||
|
||||
dec2, err := destCodec.DecodePacket(pkts[1])
|
||||
_, dec2, err = destCodec.DecodePacket(pkts[1])
|
||||
if err != nil {
|
||||
t.Fatalf("dest failed to decode packet 2: %v", err)
|
||||
}
|
||||
|
||||
@@ -100,19 +100,27 @@ type ServerUDPSession struct {
|
||||
func (s *ServerUDPSession) CheckPacketID(packetID uint64) bool {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.Window == nil {
|
||||
s.Window = new(SlidingWindow)
|
||||
}
|
||||
return s.Window.Check(packetID)
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) AddPacketID(packetID uint64) {
|
||||
func (s *ServerUDPSession) Commit(packetID uint64, bodyAead cipher.AEAD, user *protocol.MemoryUser, userPSK []byte) bool {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.Window == nil {
|
||||
s.Window = new(SlidingWindow)
|
||||
if s.User != nil && user != nil && s.User != user {
|
||||
return false
|
||||
}
|
||||
s.Window.Add(packetID)
|
||||
if !s.Window.CheckAndAdd(packetID) {
|
||||
return false
|
||||
}
|
||||
if s.clientBodyCipher == nil && bodyAead != nil {
|
||||
s.clientBodyCipher = bodyAead
|
||||
}
|
||||
if s.User == nil && user != nil {
|
||||
s.User = user
|
||||
s.UserPSK = userPSK
|
||||
}
|
||||
s.LastActive.Store(time.Now().Unix())
|
||||
return true
|
||||
}
|
||||
|
||||
type UDPSessionManager struct {
|
||||
@@ -128,6 +136,13 @@ func NewUDPSessionManager(timeout time.Duration) *UDPSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
func (m *UDPSessionManager) Get(sessionID uint64) *ServerUDPSession {
|
||||
if s, ok := m.sessions.Load(sessionID); ok {
|
||||
return s
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||
now := time.Now().Unix()
|
||||
if s, ok := m.sessions.Load(sessionID); ok {
|
||||
@@ -137,6 +152,7 @@ func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||
|
||||
s := &ServerUDPSession{
|
||||
SessionID: sessionID,
|
||||
Window: new(SlidingWindow),
|
||||
manager: m,
|
||||
}
|
||||
s.LastActive.Store(now)
|
||||
|
||||
@@ -63,10 +63,16 @@ func (s *ServerUDPSession) EnsureLink(
|
||||
|
||||
s.currentConn.Store(conn)
|
||||
|
||||
sessCtx, cancel := context.WithCancel(ctx)
|
||||
// UDP Session might travel across multiple connections
|
||||
// don't bind its lifetime to a parent context
|
||||
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
inbound := session.InboundFromContext(sessCtx)
|
||||
if inbound != nil && s.User != nil {
|
||||
inbound.User = s.User
|
||||
if inbound != nil {
|
||||
newInbound := *inbound
|
||||
if s.User != nil {
|
||||
newInbound.User = s.User
|
||||
}
|
||||
sessCtx = session.ContextWithInbound(sessCtx, &newInbound)
|
||||
}
|
||||
var email string
|
||||
var level uint32
|
||||
|
||||
@@ -265,7 +265,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
|
||||
clientCodec, err := NewUDPPacketCodec(method, [][]byte{psk})
|
||||
common.Must(err)
|
||||
serverCodec, err := NewUDPServerCodec(method, psk, time.Minute)
|
||||
serverCodec, err := NewUDPServerCodec(method, psk, nil, time.Minute)
|
||||
common.Must(err)
|
||||
|
||||
session, err := clientCodec.NewClientSession()
|
||||
@@ -277,7 +277,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
rawCopy := make([]byte, pktBuf.Len())
|
||||
copy(rawCopy, pktBuf.Bytes())
|
||||
|
||||
decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
|
||||
_, decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
|
||||
common.Must(err)
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
@@ -291,7 +291,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
}
|
||||
|
||||
// Replay same packet wire bytes should fail with ErrPacketIdNotUnique
|
||||
_, err = serverCodec.DecodePacket(rawCopy)
|
||||
_, _, err = serverCodec.DecodePacket(rawCopy)
|
||||
if err != ErrPacketIdNotUnique {
|
||||
t.Fatalf("expected ErrPacketIdNotUnique on replay, got: %v", err)
|
||||
}
|
||||
@@ -427,7 +427,7 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
|
||||
|
||||
clientCodec, err := NewUDPPacketCodec(method, [][]byte{rawKey})
|
||||
common.Must(err)
|
||||
serverCodec, err := NewUDPServerCodec(method, rawKey, time.Minute)
|
||||
serverCodec, err := NewUDPServerCodec(method, rawKey, nil, time.Minute)
|
||||
common.Must(err)
|
||||
|
||||
session, err := clientCodec.NewClientSession()
|
||||
@@ -448,9 +448,9 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
|
||||
defer pkt2.Release()
|
||||
|
||||
// Server decodes both
|
||||
dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
|
||||
_, dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
|
||||
common.Must(err)
|
||||
dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
|
||||
_, dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
|
||||
common.Must(err)
|
||||
|
||||
if dec1.SessionID != session.ClientSessionID() || dec2.SessionID != session.ClientSessionID() {
|
||||
|
||||
@@ -337,7 +337,7 @@ func WriteTCPRequest(w io.Writer, method *CipherMethod, pskList [][]byte, dest n
|
||||
addrPortLen := AddrPortLength(dest)
|
||||
varHeaderLen := addrPortLen + 2 + paddingLen + payloadLen
|
||||
|
||||
totalHandshakeLen := int32(method.KeySaltLength + len(pskList)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||
totalHandshakeLen := int32(method.KeySaltLength + (len(pskList)-1)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||
handshakeBuf := buf.NewWithSize(totalHandshakeLen)
|
||||
defer handshakeBuf.Release()
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
@@ -49,3 +50,18 @@ 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
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
//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")
|
||||
}
|
||||
}
|
||||
@@ -1,390 +0,0 @@
|
||||
//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")
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,11 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/net/route"
|
||||
@@ -148,3 +152,381 @@ 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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
//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,6 +9,18 @@ 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
|
||||
@@ -443,3 +455,185 @@ 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")
|
||||
}
|
||||
}
|
||||
@@ -710,3 +710,109 @@ 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"
|
||||
}
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
//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,6 +4,7 @@ package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
go_errors "errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
@@ -340,3 +341,46 @@ 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")
|
||||
}
|
||||
}
|
||||
@@ -8,20 +8,6 @@ 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++ {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
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,43 +80,3 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ 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"
|
||||
@@ -524,6 +525,12 @@ 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")
|
||||
|
||||
@@ -12,6 +12,7 @@ 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"
|
||||
)
|
||||
@@ -41,17 +42,19 @@ 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}
|
||||
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)
|
||||
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)
|
||||
}
|
||||
c.tcp = pool(concurrency)
|
||||
}
|
||||
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
|
||||
c.udp = 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)
|
||||
}
|
||||
return c
|
||||
}
|
||||
@@ -72,6 +75,7 @@ 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
|
||||
|
||||
@@ -26,7 +26,9 @@ func TestClientUDP443Policy(t *testing.T) {
|
||||
opened = true
|
||||
return nil, nil, context.Canceled
|
||||
})
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{})
|
||||
r, w := pipe.New()
|
||||
common.Close(w)
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
|
||||
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)
|
||||
|
||||
@@ -191,6 +191,13 @@ 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)
|
||||
@@ -272,27 +279,20 @@ 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 {
|
||||
|
||||
@@ -255,10 +255,11 @@ 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())
|
||||
|
||||
@@ -175,7 +175,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
c.decref(msg, addr)
|
||||
return
|
||||
}
|
||||
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) {
|
||||
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) {
|
||||
msg.Header.Response = true
|
||||
msg.Header.Authoritative = true
|
||||
msg.Header.RCode = dnsmessage.RCodeSuccess
|
||||
@@ -201,14 +208,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
c.decref(msg, addr)
|
||||
}
|
||||
|
||||
if decoded[8]&0x3F == 8 {
|
||||
if kind == 8 {
|
||||
return
|
||||
}
|
||||
p := pool4K.Get().([]byte)
|
||||
p = p[:0]
|
||||
if decoded[8]&0xC0 == 0xC0 {
|
||||
if fragmented {
|
||||
out := pool4K.Get().([]byte)
|
||||
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[15:n])
|
||||
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[dataOffset:n])
|
||||
pool4K.Put(p[:cap(p)])
|
||||
if n > 0 {
|
||||
p = out[:n]
|
||||
@@ -217,7 +224,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
p = append(p, decoded[12:n]...)
|
||||
p = append(p, decoded[dataOffset:n]...)
|
||||
}
|
||||
select {
|
||||
case <-c.closeCh:
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,11 @@ 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
|
||||
@@ -30,9 +35,11 @@ type clientConn struct {
|
||||
password string
|
||||
rsaPublicKey []byte
|
||||
hostname string
|
||||
dataChannel string
|
||||
paddingChannel string
|
||||
yggdrasil *yggdrasilAuth
|
||||
paddingSchedule []paddingTurn
|
||||
packet *packetStream
|
||||
packet *tickStream
|
||||
deadlines *connectionDeadlines
|
||||
|
||||
done chan struct{}
|
||||
@@ -46,7 +53,7 @@ var (
|
||||
clientStateProxy clientState = 2
|
||||
)
|
||||
|
||||
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth) (*clientConn, error) {
|
||||
func newClientConn(c net.Conn, protocol protocolVersion, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth, dataChannel, paddingChannel string) (*clientConn, error) {
|
||||
if len(rsaPublicKey) == 0 && yggdrasil == nil {
|
||||
return nil, fmt.Errorf("empty rsa public key")
|
||||
}
|
||||
@@ -61,11 +68,14 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
|
||||
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),
|
||||
@@ -92,10 +102,10 @@ func (c *clientConn) handshake() error {
|
||||
defer func() { _ = c.deadlines.endHandshake() }()
|
||||
|
||||
var (
|
||||
protocolVersion Varint = Varint(775)
|
||||
serverAddress String = String(c.hostname)
|
||||
serverPort UnsignedShort = UnsignedShort(25565)
|
||||
nextState Varint = Varint(2)
|
||||
protocolNumber Varint = c.protocol.number
|
||||
serverAddress String = String(c.hostname)
|
||||
serverPort UnsignedShort = UnsignedShort(25565)
|
||||
nextState Varint = Varint(2)
|
||||
)
|
||||
|
||||
host, portString, err := net.SplitHostPort(c.c.RemoteAddr().String())
|
||||
@@ -110,11 +120,37 @@ func (c *clientConn) handshake() error {
|
||||
}
|
||||
}
|
||||
|
||||
err = writePacket(c.writer, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState)
|
||||
err = writePacket(c.writer, handshakeServerboundIntention, &protocolNumber, &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 {
|
||||
@@ -139,57 +175,156 @@ func (c *clientConn) handshake() error {
|
||||
}
|
||||
username := String(selectedProfile.Username)
|
||||
|
||||
err = writePacket(c.writer, 0x00, &username, &selectedProfile.UUID)
|
||||
err = writePacket(c.writer, c.protocol.login.serverboundLoginStart, &username, &selectedProfile.UUID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write login start: %w", err)
|
||||
}
|
||||
|
||||
// Encryption Request
|
||||
pkt, err := readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encryption request: %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)
|
||||
}
|
||||
|
||||
if pkt.packetID != 0x01 {
|
||||
return fmt.Errorf("bad encrypt request packet id")
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
serverId String
|
||||
publicKey Bytes
|
||||
verifyToken Bytes
|
||||
shouldAuthenticate Boolean
|
||||
)
|
||||
|
||||
err = pkt.readFields(&serverId, &publicKey, &verifyToken)
|
||||
err := pkt.readFields(&serverId, &publicKey, &verifyToken, &shouldAuthenticate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encryption request fields: %w", err)
|
||||
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")
|
||||
}
|
||||
|
||||
if c.yggdrasil == nil && !bytes.Equal(publicKey, c.rsaPublicKey) {
|
||||
return fmt.Errorf("server public key mismatch")
|
||||
return profile, false, fmt.Errorf("server public key mismatch")
|
||||
}
|
||||
|
||||
k, err := x509.ParsePKIXPublicKey(publicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse server public key: %w", err)
|
||||
return profile, false, fmt.Errorf("parse server public key: %w", err)
|
||||
}
|
||||
|
||||
rsaPublicKey, ok := k.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return fmt.Errorf("parse server public key: not rsa")
|
||||
return profile, false, fmt.Errorf("parse server public key: not rsa")
|
||||
}
|
||||
if rsaPublicKey.N.BitLen() < 1024 {
|
||||
return fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen())
|
||||
return profile, false, 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 fmt.Errorf("generate shared secret: %w", err)
|
||||
return profile, false, fmt.Errorf("generate shared secret: %w", err)
|
||||
}
|
||||
|
||||
encryptedSharedSecret, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encrypt shared secret: %w", err)
|
||||
return profile, false, fmt.Errorf("encrypt shared secret: %w", err)
|
||||
}
|
||||
|
||||
if c.yggdrasil == nil {
|
||||
@@ -198,107 +333,132 @@ func (c *clientConn) handshake() error {
|
||||
|
||||
encryptedVerifyToken, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, verifyToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encrypt verify token: %w", err)
|
||||
return profile, false, fmt.Errorf("encrypt verify token: %w", err)
|
||||
}
|
||||
|
||||
// Send Encryption Response
|
||||
// Send Encryption Response, then switch the ciphers on: vanilla starts
|
||||
// encrypting only after the response itself has been written.
|
||||
err = writePacket(
|
||||
c.writer,
|
||||
0x01,
|
||||
c.protocol.login.serverboundKey,
|
||||
(*Bytes)(&encryptedSharedSecret),
|
||||
(*Bytes)(&encryptedVerifyToken),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write encryption response: %w", err)
|
||||
return profile, false, fmt.Errorf("write encryption response: %w", err)
|
||||
}
|
||||
|
||||
// Enable encryption
|
||||
c.reader, err = newCryptoReader(c.reader, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new crypto reader: %w", err)
|
||||
return profile, false, fmt.Errorf("new crypto reader: %w", err)
|
||||
}
|
||||
|
||||
c.writer, err = newCryptoWriter(c.writer, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new crypto writer: %w", err)
|
||||
return profile, false, fmt.Errorf("new crypto writer: %w", err)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
// 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
|
||||
}
|
||||
|
||||
pkt, err = readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login finished: %w", err)
|
||||
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)
|
||||
}
|
||||
// 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)
|
||||
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
|
||||
if uuidErr != nil {
|
||||
return profile, false, fmt.Errorf("yggdrasil session join: %w", uuidErr)
|
||||
}
|
||||
return loginProfile{Username: token.profile.Name, UUID: profileUUID}, true, nil
|
||||
}
|
||||
|
||||
receivedProfile, err := readLoginSuccess(pkt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login finished fields: %w", err)
|
||||
// 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)
|
||||
}
|
||||
if c.yggdrasil != nil {
|
||||
if !sameProfileIdentity(receivedProfile, selectedProfile) {
|
||||
// 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) {
|
||||
return fmt.Errorf("login profile mismatch")
|
||||
}
|
||||
if verifyErr := c.yggdrasil.verifyLoginProfile(receivedProfile); verifyErr != nil {
|
||||
return fmt.Errorf("verify login profile: %w", verifyErr)
|
||||
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")
|
||||
}
|
||||
} else if !sameLoginProfile(receivedProfile, selectedProfile) {
|
||||
return fmt.Errorf("login profile mismatch")
|
||||
}
|
||||
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 {
|
||||
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 {
|
||||
_ = c.Close() // Unblock the startup reader if writing failed.
|
||||
return fmt.Errorf("run startup padding: %w", err)
|
||||
}
|
||||
|
||||
packet := newPacketStream(c.reader, c.writer, true)
|
||||
packet := newTickStream(c.reader, c.writer, true, c.protocol.configuration, c.dataChannel, c.paddingChannel)
|
||||
c.lifecycleMu.Lock()
|
||||
if c.closed {
|
||||
c.lifecycleMu.Unlock()
|
||||
@@ -339,6 +499,10 @@ 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()
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
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"
|
||||
)
|
||||
@@ -30,6 +32,49 @@ 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 {
|
||||
@@ -39,6 +84,14 @@ 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 {
|
||||
@@ -56,7 +109,7 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
|
||||
rsaPublicKey = c.RsaPublicKey
|
||||
}
|
||||
|
||||
cc, err := newClientConn(conn, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth)
|
||||
cc, err := newClientConn(conn, protocol, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth, dataChannel, paddingChannel)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
@@ -73,6 +126,10 @@ 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 {
|
||||
@@ -85,7 +142,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)
|
||||
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier, dataChannel, paddingChannel)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
|
||||
@@ -189,9 +189,24 @@ 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"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
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
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
@@ -280,6 +295,27 @@ 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"`
|
||||
@@ -379,7 +415,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\"\x9b\x03\n" +
|
||||
"\x06player\x18\x04 \x01(\tR\x06player\"\x92\x04\n" +
|
||||
"\x06Config\x12\x1a\n" +
|
||||
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
|
||||
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
|
||||
@@ -390,7 +426,10 @@ 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\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\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" +
|
||||
"\aPadding\x12\x1d\n" +
|
||||
"\n" +
|
||||
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
|
||||
|
||||
@@ -53,6 +53,21 @@ 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, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil); err != nil {
|
||||
if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err != nil {
|
||||
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
|
||||
}
|
||||
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil); err == nil {
|
||||
if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); 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, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil)
|
||||
conn, err := newClientConn(client, latestProtocolVersion, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
@@ -13,9 +14,16 @@ 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: seed,
|
||||
seed: bytes.Clone(seed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +64,8 @@ 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")...))
|
||||
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,647 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
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,10 +9,22 @@ 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, client, server, 64*1024)
|
||||
testHandshakeWithPadding(t, version, 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)})
|
||||
@@ -38,11 +50,11 @@ func TestHandshakeWithBidirectionalPadding(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
testHandshakeWithPadding(t, client, server, maxPaddingTurnLength)
|
||||
testHandshakeWithPadding(t, version, client, server, maxPaddingTurnLength)
|
||||
})
|
||||
}
|
||||
|
||||
func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, length int64) {
|
||||
func testHandshakeWithPadding(t *testing.T, version protocolVersion, clientRaw, serverRaw net.Conn, length int64) {
|
||||
t.Helper()
|
||||
defer clientRaw.Close()
|
||||
defer serverRaw.Close()
|
||||
@@ -72,12 +84,12 @@ func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, lengt
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule, nil)
|
||||
client, err := newClientConn(clientRaw, version, profiles, "password", publicKey, "localhost", paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil)
|
||||
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -4,52 +4,173 @@ 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
|
||||
)
|
||||
|
||||
// packetStream carries the raw proxy byte stream in Minecraft configuration
|
||||
// tickStream 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.
|
||||
type packetStream struct {
|
||||
//
|
||||
// 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 {
|
||||
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
|
||||
writeMu sync.Mutex
|
||||
pending []byte
|
||||
|
||||
writeMu sync.Mutex
|
||||
|
||||
queueMu sync.Mutex
|
||||
queueCond *sync.Cond
|
||||
queue []byte
|
||||
closed bool
|
||||
|
||||
keepAliveID atomic.Int64
|
||||
done chan struct{}
|
||||
stopOnce sync.Once
|
||||
}
|
||||
|
||||
func newPacketStream(reader io.Reader, writer io.Writer, isClient bool) *packetStream {
|
||||
s := &packetStream{
|
||||
reader: reader,
|
||||
writer: writer,
|
||||
isClient: isClient,
|
||||
done: make(chan struct{}),
|
||||
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{}),
|
||||
}
|
||||
s.queueCond = sync.NewCond(&s.queueMu)
|
||||
go s.tickLoop()
|
||||
if !isClient {
|
||||
go s.keepAliveLoop()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *packetStream) Read(p []byte) (int, error) {
|
||||
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) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -70,7 +191,7 @@ func (s *packetStream) Read(p []byte) (int, error) {
|
||||
}
|
||||
|
||||
if packet.packetID == s.remoteCustomPayloadID() {
|
||||
payload, ok, err := parseCustomPayload(packet)
|
||||
payload, ok, err := parseCustomPayload(packet, s.dataChannel)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -85,70 +206,99 @@ func (s *packetStream) Read(p []byte) (int, error) {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
if packet.packetID == configurationKeepAlive {
|
||||
// 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:
|
||||
var id Long
|
||||
if err := packet.readFields(&id); err != nil {
|
||||
return 0, fmt.Errorf("read minecraft keep-alive: %w", err)
|
||||
}
|
||||
if s.isClient {
|
||||
if err := s.writeKeepAlive(id); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := s.writeKeepAlive(s.packetIDs.serverboundKeepAlive, 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 *packetStream) Write(p []byte) (int, error) {
|
||||
func (s *tickStream) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
|
||||
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
|
||||
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()
|
||||
|
||||
return written, nil
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (s *packetStream) Stop() {
|
||||
s.stopOnce.Do(func() { close(s.done) })
|
||||
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) localCustomPayloadID() int {
|
||||
func (s *tickStream) localCustomPayloadID() int {
|
||||
if s.isClient {
|
||||
return configurationServerboundCustomPayload
|
||||
return s.packetIDs.serverboundCustomPayload
|
||||
}
|
||||
return configurationClientboundCustomPayload
|
||||
return s.packetIDs.clientboundCustomPayload
|
||||
}
|
||||
|
||||
func (s *packetStream) remoteCustomPayloadID() int {
|
||||
func (s *tickStream) remoteCustomPayloadID() int {
|
||||
if s.isClient {
|
||||
return configurationClientboundCustomPayload
|
||||
return s.packetIDs.clientboundCustomPayload
|
||||
}
|
||||
return configurationServerboundCustomPayload
|
||||
return s.packetIDs.serverboundCustomPayload
|
||||
}
|
||||
|
||||
func parseCustomPayload(packet *mcPacket) ([]byte, bool, error) {
|
||||
func parseCustomPayload(packet *mcPacket, dataChannel string) ([]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) != packetChannel {
|
||||
if string(channel) != dataChannel {
|
||||
return nil, false, nil
|
||||
}
|
||||
payload := make([]byte, r.Len())
|
||||
@@ -158,23 +308,49 @@ func parseCustomPayload(packet *mcPacket) ([]byte, bool, error) {
|
||||
return payload, true, nil
|
||||
}
|
||||
|
||||
func (s *packetStream) writeKeepAlive(id Long) error {
|
||||
func (s *tickStream) writeKeepAlive(packetID int, id Long) error {
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
if err := writePacket(s.writer, configurationKeepAlive, &id); err != nil {
|
||||
if err := writePacket(s.writer, packetID, &id); err != nil {
|
||||
return fmt.Errorf("write minecraft keep-alive: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *packetStream) keepAliveLoop() {
|
||||
// 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() {
|
||||
ticker := time.NewTicker(keepAlivePeriod)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
id := Long(s.keepAliveID.Add(1))
|
||||
if err := s.writeKeepAlive(id); err != nil {
|
||||
if err := s.writeKeepAlive(s.packetIDs.clientboundKeepAlive, id); err != nil {
|
||||
return
|
||||
}
|
||||
case <-s.done:
|
||||
|
||||
@@ -29,19 +29,97 @@ 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)
|
||||
)
|
||||
|
||||
var maxPaddingFrameLength = paddingFrameLength(maxPaddingFrameDataLength)
|
||||
// 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
|
||||
}
|
||||
|
||||
type paddingVariant struct {
|
||||
chunks []int
|
||||
@@ -97,13 +175,14 @@ 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) error {
|
||||
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error, paddingChannel string, packetIDs configurationPacketIDs) 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
|
||||
@@ -128,7 +207,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(isClient)); err != nil {
|
||||
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(packetIDs, isClient), framing); err != nil {
|
||||
return fmt.Errorf("write padding turn %d: %w", i, err)
|
||||
}
|
||||
}
|
||||
@@ -195,18 +274,19 @@ 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
|
||||
// vanilla configuration protocol, so no proxy-specific id ever reaches the wire.
|
||||
func paddingFramePacketID(isClient bool) int {
|
||||
// negotiated version's configuration protocol, so no proxy-specific id ever
|
||||
// reaches the wire.
|
||||
func paddingFramePacketID(packetIDs configurationPacketIDs, isClient bool) int {
|
||||
if isClient {
|
||||
return configurationServerboundCustomPayload
|
||||
return packetIDs.serverboundCustomPayload
|
||||
}
|
||||
return configurationClientboundCustomPayload
|
||||
return packetIDs.clientboundCustomPayload
|
||||
}
|
||||
|
||||
// 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) (int, error) {
|
||||
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int, framing paddingFraming) (int, error) {
|
||||
startDelay, err := randomPaddingDelay(turn.startDelay)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("select padding start delay: %w", err)
|
||||
@@ -241,7 +321,7 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
|
||||
}
|
||||
|
||||
zeros := make([]byte, maxPaddingFrameDataLength)
|
||||
channel := String(paddingFrameChannel)
|
||||
channel := String(framing.channel)
|
||||
written := 0
|
||||
for i, chunkLength := range chunks {
|
||||
if i < len(delays) {
|
||||
@@ -253,12 +333,12 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
|
||||
return written, delayErr
|
||||
}
|
||||
}
|
||||
frameLengths, planErr := paddingFramePlan(chunkLength)
|
||||
frameLengths, planErr := framing.plan(chunkLength)
|
||||
if planErr != nil {
|
||||
return written, planErr
|
||||
}
|
||||
for _, frameLength := range frameLengths {
|
||||
dataLength, ok := paddingFrameDataLength(frameLength)
|
||||
dataLength, ok := framing.frameDataLength(frameLength)
|
||||
if !ok {
|
||||
return written, fmt.Errorf("unframed padding length %d", frameLength)
|
||||
}
|
||||
@@ -272,63 +352,6 @@ 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 := paddingFrameLength(dataLength)
|
||||
got, ok := paddingFrameDataLength(frameLength)
|
||||
frameLength := defaultPaddingFraming.frameLength(dataLength)
|
||||
got, ok := defaultPaddingFraming.frameDataLength(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{paddingFrameOverhead, paddingFrameOverhead + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, maxPaddingFrameLength - 1, maxPaddingFrameLength, maxPaddingFrameLength + 1, 3 * maxPaddingFrameLength, 1024 * 1024}
|
||||
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}
|
||||
for _, length := range lengths {
|
||||
plan, err := paddingFramePlan(length)
|
||||
plan, err := defaultPaddingFraming.plan(length)
|
||||
if err != nil {
|
||||
t.Fatalf("plan %d: %v", length, err)
|
||||
}
|
||||
total := 0
|
||||
for _, frameLength := range plan {
|
||||
if _, ok := paddingFrameDataLength(frameLength); !ok {
|
||||
if _, ok := defaultPaddingFraming.frameDataLength(frameLength); !ok {
|
||||
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
|
||||
}
|
||||
if frameLength > maxPaddingFrameLength {
|
||||
if frameLength > defaultPaddingFraming.maxFrameLength() {
|
||||
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 := paddingFramePlan(2)
|
||||
plan, err := defaultPaddingFraming.plan(2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(plan) != 1 || plan[0] != paddingFrameOverhead {
|
||||
if len(plan) != 1 || plan[0] != defaultPaddingFraming.overhead() {
|
||||
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: maxPaddingFrameLength, maxLength: maxPaddingFrameLength},
|
||||
{direction: paddingClientToServer, minLength: 3*maxPaddingFrameLength + 7, maxLength: 3*maxPaddingFrameLength + 7},
|
||||
{direction: paddingClientToServer, minLength: defaultPaddingFraming.maxFrameLength(), maxLength: defaultPaddingFraming.maxFrameLength()},
|
||||
{direction: paddingClientToServer, minLength: 3*defaultPaddingFraming.maxFrameLength() + 7, maxLength: 3*defaultPaddingFraming.maxFrameLength() + 7},
|
||||
}
|
||||
for i, turn := range turns {
|
||||
var buffer bytes.Buffer
|
||||
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationServerboundCustomPayload)
|
||||
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationPacketIDs121.serverboundCustomPayload, defaultPaddingFraming)
|
||||
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 != configurationServerboundCustomPayload {
|
||||
if packet.packetID != configurationPacketIDs121.serverboundCustomPayload {
|
||||
t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID)
|
||||
}
|
||||
_, ok, err := parseCustomPayload(packet)
|
||||
_, ok, err := parseCustomPayload(packet, DefaultDataChannel)
|
||||
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); err != nil {
|
||||
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); 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 != configurationServerboundCustomPayload {
|
||||
if packet.packetID != configurationPacketIDs121.serverboundCustomPayload {
|
||||
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); err == nil {
|
||||
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); 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); err != nil {
|
||||
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); 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)
|
||||
err := runPaddingSchedule(&out, true, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121)
|
||||
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); err != nil {
|
||||
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); 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); err != nil {
|
||||
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); 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) io.Reader {
|
||||
func newPaddingReader(reader io.Reader, isClient bool, paddingChannel string, packetIDs configurationPacketIDs) io.Reader {
|
||||
first := make(chan paddingReadResult, 1)
|
||||
go func() {
|
||||
frame, err := readPastPadding(reader, paddingFramePacketID(!isClient))
|
||||
frame, err := readPastPadding(reader, paddingFramePacketID(packetIDs, !isClient), paddingChannel)
|
||||
first <- paddingReadResult{frame: frame, err: err}
|
||||
}()
|
||||
return &paddingReader{reader: reader, first: first}
|
||||
}
|
||||
|
||||
func readPastPadding(reader io.Reader, packetID int) ([]byte, error) {
|
||||
func readPastPadding(reader io.Reader, packetID int, paddingChannel string) ([]byte, error) {
|
||||
for {
|
||||
packet, err := readPacket(reader)
|
||||
if err != nil {
|
||||
@@ -36,7 +36,7 @@ func readPastPadding(reader io.Reader, packetID int) ([]byte, error) {
|
||||
}
|
||||
if packet.packetID == packetID {
|
||||
var channel String
|
||||
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && channel == paddingFrameChannel {
|
||||
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && string(channel) == paddingChannel {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
|
||||
func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
|
||||
for _, isClient := range []bool{true, false} {
|
||||
packetID := paddingFramePacketID(!isClient)
|
||||
packetID := paddingFramePacketID(configurationPacketIDs121, !isClient)
|
||||
var wire bytes.Buffer
|
||||
paddingChannel := String(paddingFrameChannel)
|
||||
paddingChannel := String(DefaultPaddingChannel)
|
||||
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, configurationKeepAlive, &id); err != nil {
|
||||
if err := writePacket(&want, configurationPacketIDs121.clientboundKeepAlive, &id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
channel := String(packetChannel)
|
||||
channel := String(DefaultDataChannel)
|
||||
if err := writePacket(&want, packetID, &channel, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wire.Write(want.Bytes())
|
||||
got, err := io.ReadAll(newPaddingReader(&wire, isClient))
|
||||
got, err := io.ReadAll(newPaddingReader(&wire, isClient, DefaultPaddingChannel, configurationPacketIDs121))
|
||||
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)
|
||||
reader := newPaddingReader(bytes.NewReader(test.wire), true, DefaultPaddingChannel, configurationPacketIDs121)
|
||||
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)
|
||||
reader := newPaddingReader(client, true, DefaultPaddingChannel, configurationPacketIDs121)
|
||||
if n, err := reader.Read(nil); n != 0 || err != nil {
|
||||
t.Fatalf("empty read = %d, %v", n, err)
|
||||
}
|
||||
|
||||
@@ -184,19 +184,18 @@ func propertyListFromYggdrasil(properties []yggdrasilProperty) loginProperties {
|
||||
return result
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
profile.Username = string(username)
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
func writeLoginSuccess(w io.Writer, profile loginProfile) error {
|
||||
// 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)
|
||||
return writePacket(w, 0x02, &profile.UUID, &username, &profile.Properties)
|
||||
fields := []field{&profile.UUID, &username, &profile.Properties}
|
||||
if version.loginFinishedSessionID {
|
||||
sessionID, err := serverSessionID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fields = append(fields, &sessionID)
|
||||
}
|
||||
return writePacket(w, version.login.clientboundLoginFinished, fields...)
|
||||
}
|
||||
|
||||
@@ -238,6 +238,29 @@ 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 {
|
||||
@@ -443,6 +466,6 @@ func writeFull(w io.Writer, p []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeDisconnectPacket(w io.Writer, reason string) error {
|
||||
return writePacket(w, 0x00, new(String(reason)))
|
||||
func writeDisconnectPacket(w io.Writer, packetID int, reason string) error {
|
||||
return writePacket(w, packetID, new(String(reason)))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// 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()))
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// Minecraft protocol table.
|
||||
//
|
||||
// Every packet id XMC writes or matches is the registration order of the packet
|
||||
// type in that version's protocol builder, not a value observed in a capture:
|
||||
// LoginProtocols and ConfigurationProtocols call addPacket in source order and
|
||||
// both ends dispatch on that index. The table keeps those ids in one place and
|
||||
// per version, so a new release is a row instead of an edit spread over the
|
||||
// login, configuration and padding code.
|
||||
//
|
||||
// Rows come from two independent sources, and neither is a packet capture:
|
||||
//
|
||||
// - 767..775 (1.21.1 .. 26.1): minecraft-data's per-version protocol.json
|
||||
// (data/pc/<version>/protocol.json), which stores the same registration
|
||||
// order as a {hex id: packet name} mapping;
|
||||
// - 776..777 (26.2, 26.3): the official jars, LoginProtocols and
|
||||
// ConfigurationProtocols.
|
||||
//
|
||||
// 26.3 is the reason this table exists. It inserts ClientboundPostEffectsPacket
|
||||
// into the configuration clientbound list at 0x0a, after the keep-alive and
|
||||
// before store_cookie, so every id behind it moves by one. Every id XMC uses
|
||||
// stayed put, which is luck rather than design: the list grows by one or two
|
||||
// packets per release (17 clientbound configuration packets in 1.21.1, 21 in
|
||||
// 26.3), and an insertion in front of 0x04 would silently break the tunnel.
|
||||
// Adding a version means adding a row here and an expectation in
|
||||
// protocol_table_test.go, after diffing the two registration lists.
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// handshaking and status packet ids. These have not moved since 1.7 and are
|
||||
// fixed for every version the table covers.
|
||||
const (
|
||||
handshakeServerboundIntention = 0x00
|
||||
statusServerboundRequest = 0x00
|
||||
statusServerboundPing = 0x01
|
||||
statusClientboundResponse = 0x00
|
||||
statusClientboundPong = 0x01
|
||||
)
|
||||
|
||||
// loginPacketIDs is the login state of one version.
|
||||
type loginPacketIDs struct {
|
||||
// Serverbound (client to server).
|
||||
serverboundLoginStart int
|
||||
serverboundKey int
|
||||
serverboundCustomQueryAnswer int
|
||||
serverboundLoginAcknowledged int
|
||||
serverboundCookieResponse int
|
||||
|
||||
// Clientbound (server to client).
|
||||
clientboundLoginDisconnect int
|
||||
clientboundHello int
|
||||
clientboundLoginFinished int
|
||||
clientboundLoginCompression int
|
||||
clientboundCustomQuery int
|
||||
clientboundCookieRequest int
|
||||
}
|
||||
|
||||
// configurationPacketIDs is the part of the configuration state XMC uses: the
|
||||
// custom payload pair that carries the tunnel, the keep-alive and ping that
|
||||
// keep the connection alive like a real one, and the packets that a peer can
|
||||
// send before the tunnel starts, so that they are recognised instead of being
|
||||
// mistaken for tunnel data.
|
||||
type configurationPacketIDs struct {
|
||||
// Serverbound (client to server).
|
||||
serverboundClientInformation int
|
||||
serverboundCookieResponse int
|
||||
serverboundCustomPayload int
|
||||
serverboundKeepAlive int
|
||||
serverboundPong int
|
||||
|
||||
// Clientbound (server to client).
|
||||
clientboundCookieRequest int
|
||||
clientboundCustomPayload int
|
||||
clientboundDisconnect int
|
||||
clientboundKeepAlive int
|
||||
clientboundPing int
|
||||
}
|
||||
|
||||
// protocolVersion describes one Minecraft release for the part of the protocol
|
||||
// the finalmask depends on.
|
||||
type protocolVersion struct {
|
||||
// number is the network protocol version advertised in the handshake and
|
||||
// reported by the status response.
|
||||
number Varint
|
||||
// name is the release name, for example "26.3", as the status response
|
||||
// reports it.
|
||||
name string
|
||||
|
||||
login loginPacketIDs
|
||||
configuration configurationPacketIDs
|
||||
|
||||
// loginFinishedSessionID is set from 26.2 (776) on: Login Finished appends
|
||||
// the connection session id after the game profile, so the client has to
|
||||
// read it and the server has to write it.
|
||||
loginFinishedSessionID bool
|
||||
}
|
||||
|
||||
// The login and configuration ids that 767..777 share. 26.2 added the session
|
||||
// id field, and 26.3 inserted a clientbound configuration packet, but none of
|
||||
// the ids below moved between 1.21.1 and 26.3.
|
||||
var (
|
||||
loginPacketIDs121 = loginPacketIDs{
|
||||
serverboundLoginStart: 0x00,
|
||||
serverboundKey: 0x01,
|
||||
serverboundCustomQueryAnswer: 0x02,
|
||||
serverboundLoginAcknowledged: 0x03,
|
||||
serverboundCookieResponse: 0x04,
|
||||
|
||||
clientboundLoginDisconnect: 0x00,
|
||||
clientboundHello: 0x01,
|
||||
clientboundLoginFinished: 0x02,
|
||||
clientboundLoginCompression: 0x03,
|
||||
clientboundCustomQuery: 0x04,
|
||||
clientboundCookieRequest: 0x05,
|
||||
}
|
||||
|
||||
configurationPacketIDs121 = configurationPacketIDs{
|
||||
serverboundClientInformation: 0x00,
|
||||
serverboundCookieResponse: 0x01,
|
||||
serverboundCustomPayload: 0x02,
|
||||
serverboundKeepAlive: 0x04,
|
||||
serverboundPong: 0x05,
|
||||
|
||||
clientboundCookieRequest: 0x00,
|
||||
clientboundCustomPayload: 0x01,
|
||||
clientboundDisconnect: 0x02,
|
||||
clientboundKeepAlive: 0x04,
|
||||
clientboundPing: 0x05,
|
||||
}
|
||||
)
|
||||
|
||||
// protocolVersions is ordered by protocol number, oldest first. Only releases
|
||||
// the mod's branches target are listed: the configuration state starts at 1.20.5
|
||||
// (766), and XMC is only useful from 1.21 on, so 767 is the oldest row.
|
||||
//
|
||||
// Releases that share a protocol number share a row and cannot be told apart on
|
||||
// the wire; the name is the one the mod's branches use (1.21.2 is 768 like
|
||||
// 1.21.3, 1.21.7 is 772 like 1.21.8, 1.21.10 is 773 like 1.21.9, and 26.1.1 /
|
||||
// 26.1.2 are 775 like 26.1).
|
||||
var protocolVersions = []protocolVersion{
|
||||
{number: 767, name: "1.21.1", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 768, name: "1.21.3", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 769, name: "1.21.4", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 770, name: "1.21.5", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 771, name: "1.21.6", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 772, name: "1.21.8", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 773, name: "1.21.9", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 774, name: "1.21.11", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 775, name: "26.1", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 776, name: "26.2", login: loginPacketIDs121, configuration: configurationPacketIDs121, loginFinishedSessionID: true},
|
||||
{number: 777, name: "26.3", login: loginPacketIDs121, configuration: configurationPacketIDs121, loginFinishedSessionID: true},
|
||||
}
|
||||
|
||||
// latestProtocolVersion is the newest row. It is what the client advertises
|
||||
// unless a version is configured, and what the server reports in its status
|
||||
// response.
|
||||
var latestProtocolVersion = protocolVersions[len(protocolVersions)-1]
|
||||
|
||||
// protocolVersionByNumber finds a row. An unknown number is an error rather
|
||||
// than a guess: a wrong packet id breaks the login in a way that looks like a
|
||||
// network failure, so the configuration has to name a version the table knows.
|
||||
func protocolVersionByNumber(number Varint) (protocolVersion, bool) {
|
||||
for _, version := range protocolVersions {
|
||||
if version.number == number {
|
||||
return version, true
|
||||
}
|
||||
}
|
||||
return protocolVersion{}, false
|
||||
}
|
||||
|
||||
// ValidateProtocolVersion checks a configured network protocol number. Zero is
|
||||
// valid and selects the newest row. Configuration is validated when it is built,
|
||||
// so a version that is not in the table fails before a connection is attempted.
|
||||
func ValidateProtocolVersion(number uint32) error {
|
||||
if number == 0 {
|
||||
return nil
|
||||
}
|
||||
if _, ok := protocolVersionByNumber(Varint(number)); !ok {
|
||||
return fmt.Errorf("unsupported protocol version %d (supported: %s)", number, protocolVersionRange())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// protocolVersionRange describes the supported versions for error messages.
|
||||
func protocolVersionRange() string {
|
||||
first, last := protocolVersions[0], protocolVersions[len(protocolVersions)-1]
|
||||
return fmt.Sprintf("%d (%s) to %d (%s)", first.number, first.name, last.number, last.name)
|
||||
}
|
||||
|
||||
// isProtocolVersionReject recognises the Login Disconnect reasons vanilla sends
|
||||
// when the client named another protocol version, so the cached detection can be
|
||||
// dropped.
|
||||
func isProtocolVersionReject(reason string) bool {
|
||||
return strings.Contains(reason, "multiplayer.disconnect.incompatible") ||
|
||||
strings.Contains(reason, "multiplayer.disconnect.outdated_client")
|
||||
}
|
||||
|
||||
// loginRejectReason is the Login Disconnect reason a vanilla server sends for a
|
||||
// protocol version it does not speak. Vanilla splits the message at 1.20.5
|
||||
// (754): older clients are told to update, newer ones that the server is
|
||||
// incompatible.
|
||||
func loginRejectReason(number Varint) string {
|
||||
if number < 754 {
|
||||
return fmt.Sprintf(`{"translate":"multiplayer.disconnect.outdated_client","with":[%q]}`, latestProtocolVersion.name)
|
||||
}
|
||||
return fmt.Sprintf(`{"translate":"multiplayer.disconnect.incompatible","with":[%q]}`, latestProtocolVersion.name)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestProtocolTablePinsRegistrationOrder pins every id XMC uses against the
|
||||
// source it came from, so that changing a row is a conscious edit and not a
|
||||
// side effect of a refactor:
|
||||
//
|
||||
// - 767..775: minecraft-data data/pc/<version>/protocol.json, keyed by the
|
||||
// packet name in the same order LoginProtocols and ConfigurationProtocols
|
||||
// register them;
|
||||
// - 776..777: the official 26.2 and 26.3 jars.
|
||||
func TestProtocolTablePinsRegistrationOrder(t *testing.T) {
|
||||
wantLogin := loginPacketIDs{
|
||||
serverboundLoginStart: 0x00,
|
||||
serverboundKey: 0x01,
|
||||
serverboundCustomQueryAnswer: 0x02,
|
||||
serverboundLoginAcknowledged: 0x03,
|
||||
serverboundCookieResponse: 0x04,
|
||||
|
||||
clientboundLoginDisconnect: 0x00,
|
||||
clientboundHello: 0x01,
|
||||
clientboundLoginFinished: 0x02,
|
||||
clientboundLoginCompression: 0x03,
|
||||
clientboundCustomQuery: 0x04,
|
||||
clientboundCookieRequest: 0x05,
|
||||
}
|
||||
wantConfiguration := configurationPacketIDs{
|
||||
serverboundClientInformation: 0x00,
|
||||
serverboundCookieResponse: 0x01,
|
||||
serverboundCustomPayload: 0x02,
|
||||
serverboundKeepAlive: 0x04,
|
||||
serverboundPong: 0x05,
|
||||
|
||||
clientboundCookieRequest: 0x00,
|
||||
clientboundCustomPayload: 0x01,
|
||||
clientboundDisconnect: 0x02,
|
||||
clientboundKeepAlive: 0x04,
|
||||
clientboundPing: 0x05,
|
||||
}
|
||||
|
||||
for _, version := range protocolVersions {
|
||||
if version.login != wantLogin {
|
||||
t.Fatalf("%s (%d): login ids = %+v, want %+v", version.name, version.number, version.login, wantLogin)
|
||||
}
|
||||
if version.configuration != wantConfiguration {
|
||||
t.Fatalf("%s (%d): configuration ids = %+v, want %+v", version.name, version.number, version.configuration, wantConfiguration)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestProtocolTableCoverage checks the table is a contiguous, ordered run of
|
||||
// the releases XMC supports, and that the newest row is the default.
|
||||
func TestProtocolTableCoverage(t *testing.T) {
|
||||
if len(protocolVersions) == 0 {
|
||||
t.Fatal("empty protocol table")
|
||||
}
|
||||
for i, version := range protocolVersions {
|
||||
want := Varint(767 + i)
|
||||
if version.number != want {
|
||||
t.Fatalf("row %d is protocol %d, want %d", i, version.number, want)
|
||||
}
|
||||
if version.name == "" {
|
||||
t.Fatalf("row %d (%d) has no release name", i, version.number)
|
||||
}
|
||||
if version.loginFinishedSessionID != (version.number >= 776) {
|
||||
t.Fatalf("%s (%d): loginFinishedSessionID = %v", version.name, version.number, version.loginFinishedSessionID)
|
||||
}
|
||||
}
|
||||
|
||||
if latestProtocolVersion.number != 777 || latestProtocolVersion.name != "26.3" {
|
||||
t.Fatalf("latest row = %s (%d), want 26.3 (777)", latestProtocolVersion.name, latestProtocolVersion.number)
|
||||
}
|
||||
if !latestProtocolVersion.loginFinishedSessionID {
|
||||
t.Fatal("26.3 must carry the Login Finished session id")
|
||||
}
|
||||
if _, ok := protocolVersionByNumber(776); !ok {
|
||||
t.Fatal("26.2 row is missing")
|
||||
}
|
||||
if _, ok := protocolVersionByNumber(775); !ok {
|
||||
t.Fatal("26.1 row is missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolVersionByNumberRejectsUnknown(t *testing.T) {
|
||||
for _, number := range []Varint{0, 1, 766, 778, 9999} {
|
||||
if _, ok := protocolVersionByNumber(number); ok {
|
||||
t.Fatalf("protocol %d should not be in the table", number)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolVersionRange(t *testing.T) {
|
||||
got := protocolVersionRange()
|
||||
for _, want := range []string{"767 (1.21.1)", "777 (26.3)"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("range %q does not contain %q", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginRejectReason checks the vanilla split at 1.20.5 (754): older clients
|
||||
// are told to update, newer ones that the server is incompatible.
|
||||
func TestLoginRejectReason(t *testing.T) {
|
||||
if got := loginRejectReason(700); !strings.Contains(got, "multiplayer.disconnect.outdated_client") {
|
||||
t.Fatalf("old client reason = %s", got)
|
||||
}
|
||||
for _, number := range []Varint{754, 775, 778} {
|
||||
got := loginRejectReason(number)
|
||||
if !strings.Contains(got, "multiplayer.disconnect.incompatible") {
|
||||
t.Fatalf("protocol %d reason = %s", number, got)
|
||||
}
|
||||
if !strings.Contains(got, `"with":["26.3"]`) {
|
||||
t.Fatalf("protocol %d reason has no version argument: %s", number, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatusResponse pins the status JSON shape a vanilla server builds: a
|
||||
// collapsed literal description, player counts with an empty sample, and the
|
||||
// version it speaks.
|
||||
func TestStatusResponse(t *testing.T) {
|
||||
got := statusResponse(latestProtocolVersion)
|
||||
want := `{"description":"A Minecraft Server","players":{"max":20,"online":0,"sample":[]},"version":{"name":"26.3","protocol":777},"enforcesSecureChat":true}`
|
||||
if got != want {
|
||||
t.Fatalf("status = %s\nwant %s", got, want)
|
||||
}
|
||||
if got := statusResponse(protocolVersions[0]); !strings.Contains(got, `"version":{"name":"1.21.1","protocol":767}`) {
|
||||
t.Fatalf("1.21.1 status = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidPlayerName(t *testing.T) {
|
||||
for _, name := range []string{"Notch", "a", "Player_123", "Player.Name-1", strings.Repeat("a", 16)} {
|
||||
if !validPlayerName(name) {
|
||||
t.Fatalf("%q should be a valid 26.x player name", name)
|
||||
}
|
||||
}
|
||||
// 26.x only rejects lengths above sixteen and bytes outside printable ASCII:
|
||||
// spaces and the old "letters, digits, underscore" restriction are gone.
|
||||
for _, name := range []string{strings.Repeat("a", 17), "name with space", "tab\tname", "high\x7f", "unicode\u00e9"} {
|
||||
if validPlayerName(name) {
|
||||
t.Fatalf("%q should be rejected", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGameVersion(t *testing.T) {
|
||||
version, err := (&Config{}).gameVersion()
|
||||
if err != nil || version.number != latestProtocolVersion.number {
|
||||
t.Fatalf("default version = %v, %v", version.number, err)
|
||||
}
|
||||
|
||||
version, err = (&Config{ProtocolVersion: 775}).gameVersion()
|
||||
if err != nil || version.number != 775 {
|
||||
t.Fatalf("configured version = %v, %v", version.number, err)
|
||||
}
|
||||
|
||||
if _, err = (&Config{ProtocolVersion: 778}).gameVersion(); err == nil || !strings.Contains(err.Error(), "unsupported protocol version 778") {
|
||||
t.Fatalf("unknown version error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package xmc
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
@@ -24,12 +23,22 @@ const (
|
||||
// still missing, instead of making every login wait a fixed interval.
|
||||
yggdrasilVerifyFirstPoll = 10 * time.Millisecond
|
||||
yggdrasilVerifyMaxPoll = 200 * time.Millisecond
|
||||
// maxPlayerNameLength is vanilla's Login Start limit (readUtf(16)).
|
||||
maxPlayerNameLength = 16
|
||||
)
|
||||
|
||||
var errYggdrasilNotJoined = errors.New("player did not join the minecraft session")
|
||||
|
||||
// Response by vanilla 26.1.2 server.
|
||||
var statusResponse = `{"description":"A Minecraft Server","players":{"max":20,"online":0},"version":{"name":"26.1.2","protocol":775},"enforcesSecureChat":true}`
|
||||
// serverSessionID is the connection session id that Login Finished carries from
|
||||
// 26.2 on. Vanilla generates it once per server rather than per connection, so
|
||||
// one value for the process has the same shape.
|
||||
var serverSessionID = sync.OnceValues(func() (UUID, error) {
|
||||
var sessionID UUID
|
||||
if _, err := rand.Read(sessionID[:]); err != nil {
|
||||
return UUID{}, fmt.Errorf("generate session id: %w", err)
|
||||
}
|
||||
return sessionID, nil
|
||||
})
|
||||
|
||||
type serverState int
|
||||
|
||||
@@ -45,6 +54,10 @@ type serverConn struct {
|
||||
|
||||
state serverState
|
||||
|
||||
// protocol is the row selected from the client's handshake. Both ends have
|
||||
// to use the same ids, and the client is the side that names the version.
|
||||
protocol protocolVersion
|
||||
|
||||
handshakeLock sync.Mutex
|
||||
lifecycleMu sync.Mutex
|
||||
closed bool
|
||||
@@ -52,9 +65,11 @@ type serverConn struct {
|
||||
password string
|
||||
rsaPrivateKey *rsa.PrivateKey
|
||||
rsaPublicKey []byte
|
||||
dataChannel string
|
||||
paddingChannel string
|
||||
yggdrasil *yggdrasilVerifier
|
||||
paddingSchedule []paddingTurn
|
||||
packet *packetStream
|
||||
packet *tickStream
|
||||
deadlines *connectionDeadlines
|
||||
|
||||
done chan struct{}
|
||||
@@ -75,10 +90,10 @@ func (c *serverConn) handshake() error {
|
||||
defer func() { _ = c.deadlines.endHandshake() }()
|
||||
|
||||
var (
|
||||
protocolVersion Varint
|
||||
serverAddress String
|
||||
serverPort UnsignedShort
|
||||
nextState Varint
|
||||
protocolNumber Varint
|
||||
serverAddress String
|
||||
serverPort UnsignedShort
|
||||
nextState Varint
|
||||
)
|
||||
|
||||
// handshake packet
|
||||
@@ -88,11 +103,11 @@ func (c *serverConn) handshake() error {
|
||||
return fmt.Errorf("read handshake packet: %w", err)
|
||||
}
|
||||
|
||||
if pkt.packetID != 0 {
|
||||
if pkt.packetID != handshakeServerboundIntention {
|
||||
return fmt.Errorf("bad handshake packet id")
|
||||
}
|
||||
|
||||
err = pkt.readFields(&protocolVersion, &serverAddress, &serverPort, &nextState)
|
||||
err = pkt.readFields(&protocolNumber, &serverAddress, &serverPort, &nextState)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read handshake packet: %w", err)
|
||||
}
|
||||
@@ -110,14 +125,14 @@ func (c *serverConn) handshake() error {
|
||||
}
|
||||
|
||||
switch pkt.packetID {
|
||||
case 0: // Status Request
|
||||
case statusServerboundRequest: // Status Request
|
||||
|
||||
err = writePacket(c.writer, 0, new(String(statusResponse)))
|
||||
err = writePacket(c.writer, statusClientboundResponse, new(String(statusResponse(latestProtocolVersion))))
|
||||
if err != nil {
|
||||
return fmt.Errorf("write status response: %w", err)
|
||||
}
|
||||
|
||||
case 1: // Ping
|
||||
case statusServerboundPing: // Ping
|
||||
|
||||
var payload Long
|
||||
err = pkt.readFields(&payload)
|
||||
@@ -125,7 +140,7 @@ func (c *serverConn) handshake() error {
|
||||
return fmt.Errorf("read ping packet: %w", err)
|
||||
}
|
||||
|
||||
err = writePacket(c.writer, 1, &payload)
|
||||
err = writePacket(c.writer, statusClientboundPong, &payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write ping response: %w", err)
|
||||
}
|
||||
@@ -136,167 +151,34 @@ func (c *serverConn) handshake() error {
|
||||
|
||||
return fmt.Errorf("ping")
|
||||
|
||||
case 2:
|
||||
case 2, 3:
|
||||
|
||||
// Login
|
||||
|
||||
// login start
|
||||
|
||||
pkt, err := readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login start packet: %w", err)
|
||||
// Login. A vanilla server starts the login protocol, checks the version
|
||||
// against its own, and only then reads Login Start; TRANSFER shares the
|
||||
// login but is only accepted when the server allows transfers, which the
|
||||
// mask does not.
|
||||
if nextState == 3 {
|
||||
reason := `{"translate":"multiplayer.disconnect.transfers_disabled"}`
|
||||
_ = writePacket(c.writer, latestProtocolVersion.login.clientboundLoginDisconnect, new(String(reason)))
|
||||
return fmt.Errorf("transfers are disabled")
|
||||
}
|
||||
|
||||
if pkt.packetID != 0 {
|
||||
return fmt.Errorf("bad login start packet id")
|
||||
// The version picks the row, not the other way around: the ids are the
|
||||
// registration order of the peer's own protocol, so the client decides.
|
||||
// An unknown version is rejected with the same Login Disconnect a vanilla
|
||||
// server sends for it. The disconnect id is taken from the newest row
|
||||
// because no row matches, and no release has ever moved it.
|
||||
protocol, known := protocolVersionByNumber(protocolNumber)
|
||||
if !known {
|
||||
reason := String(loginRejectReason(protocolNumber))
|
||||
_ = writePacket(c.writer, latestProtocolVersion.login.clientboundLoginDisconnect, &reason)
|
||||
return fmt.Errorf("unsupported protocol version: %d", protocolNumber)
|
||||
}
|
||||
c.protocol = protocol
|
||||
|
||||
var (
|
||||
username String
|
||||
uuid UUID
|
||||
)
|
||||
|
||||
err = pkt.readFields(&username, &uuid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login start packet: %w", err)
|
||||
}
|
||||
profile, found := findProfile(c.profiles, string(username), uuid)
|
||||
|
||||
// encrypt request
|
||||
|
||||
var (
|
||||
serverId String = String("")
|
||||
publicKey Bytes = Bytes(c.rsaPublicKey)
|
||||
verifyToken Bytes = Bytes(make([]byte, 4))
|
||||
shouldAuthenticate Boolean = true
|
||||
)
|
||||
|
||||
if _, err = rand.Read(verifyToken); err != nil {
|
||||
return fmt.Errorf("generate verify token: %w", err)
|
||||
}
|
||||
|
||||
err = writePacket(c.writer, 0x01, &serverId, &publicKey, &verifyToken, &shouldAuthenticate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write encryption request: %w", err)
|
||||
}
|
||||
|
||||
// encrypt response
|
||||
|
||||
var (
|
||||
encryptedSharedSecret Bytes
|
||||
encryptedVerifyToken Bytes
|
||||
|
||||
sharedSecret []byte
|
||||
decryptedVerifyToken []byte
|
||||
)
|
||||
|
||||
pkt, err = readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encrypt response: %w", err)
|
||||
}
|
||||
|
||||
if pkt.packetID != 0x01 {
|
||||
return fmt.Errorf("bad encrypt response packet id")
|
||||
}
|
||||
|
||||
err = pkt.readFields(&encryptedSharedSecret, &encryptedVerifyToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encrypt response: %w", err)
|
||||
}
|
||||
|
||||
sharedSecret, err = rsa.DecryptPKCS1v15(rand.Reader, c.rsaPrivateKey, encryptedSharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt shared secret: %w", err)
|
||||
}
|
||||
if len(sharedSecret) != 16 {
|
||||
return fmt.Errorf("bad shared secret length: %d", len(sharedSecret))
|
||||
}
|
||||
|
||||
decryptedVerifyToken, err = rsa.DecryptPKCS1v15(rand.Reader, c.rsaPrivateKey, encryptedVerifyToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt verify token: %w", err)
|
||||
}
|
||||
|
||||
if len(decryptedVerifyToken) < 4 || !bytes.Equal(verifyToken, decryptedVerifyToken[:4]) {
|
||||
return fmt.Errorf("verify token mismatch")
|
||||
}
|
||||
|
||||
c.reader, err = newCryptoReader(c.reader, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new crypto reader: %w", err)
|
||||
}
|
||||
|
||||
c.writer, err = newCryptoWriter(c.writer, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new crypto writer: %w", err)
|
||||
}
|
||||
|
||||
if c.yggdrasil != nil {
|
||||
// Online-mode login: verify the player through the session server
|
||||
// instead of the pre-shared password and the static profile list.
|
||||
if !bytes.Equal(decryptedVerifyToken, verifyToken) {
|
||||
return fmt.Errorf("verify token mismatch")
|
||||
}
|
||||
|
||||
serverID := minecraftServerID(string(serverId), sharedSecret, c.rsaPublicKey)
|
||||
profile, err = c.verifyYggdrasilLogin(string(username), uuid, serverID)
|
||||
if err != nil {
|
||||
reason := `{"type":"translatable","translate":"multiplayer.disconnect.unverified_username"}`
|
||||
if !errors.Is(err, errYggdrasilNotJoined) {
|
||||
reason = `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}`
|
||||
}
|
||||
if writeErr := writeDisconnectPacket(c.writer, reason); writeErr != nil {
|
||||
return fmt.Errorf("write yggdrasil disconnect: %w", writeErr)
|
||||
}
|
||||
return fmt.Errorf("verify yggdrasil login: %w", err)
|
||||
}
|
||||
} else {
|
||||
// verify password
|
||||
receivedPassword := decryptedVerifyToken[4:]
|
||||
|
||||
if subtle.ConstantTimeCompare(receivedPassword, []byte(c.password)) != 1 {
|
||||
_ = writeDisconnectPacket(c.writer, `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}`)
|
||||
return fmt.Errorf("bad password")
|
||||
}
|
||||
if !found {
|
||||
if err = writeDisconnectPacket(c.writer, `{"text":"You are not white-listed on this server!"}`); err != nil {
|
||||
return fmt.Errorf("write unknown login profile disconnect: %w", err)
|
||||
}
|
||||
return fmt.Errorf("unknown login profile")
|
||||
}
|
||||
}
|
||||
|
||||
if err = writeLoginSuccess(c.writer, profile); err != nil {
|
||||
return fmt.Errorf("write login finished: %w", err)
|
||||
}
|
||||
|
||||
var loginAcknowledgedLength int
|
||||
pkt, loginAcknowledgedLength, err = readPacketWithLength(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login acknowledged: %w", err)
|
||||
}
|
||||
if err = validateLoginAcknowledgedPacket(pkt); err != nil {
|
||||
if err = c.login(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.reader = newPaddingReader(c.reader, false)
|
||||
if err = runPaddingSchedule(c.writer, false, 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 := newPacketStream(c.reader, c.writer, false)
|
||||
c.lifecycleMu.Lock()
|
||||
if c.closed {
|
||||
c.lifecycleMu.Unlock()
|
||||
packet.Stop()
|
||||
return net.ErrClosed
|
||||
}
|
||||
c.packet = packet
|
||||
c.reader = packet
|
||||
c.writer = packet
|
||||
c.state = serverStateProxy
|
||||
c.lifecycleMu.Unlock()
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
@@ -304,6 +186,222 @@ func (c *serverConn) handshake() error {
|
||||
}
|
||||
}
|
||||
|
||||
// login runs the login state once the protocol version is known.
|
||||
func (c *serverConn) login() error {
|
||||
// login start
|
||||
|
||||
pkt, err := readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login start packet: %w", err)
|
||||
}
|
||||
|
||||
if pkt.packetID != c.protocol.login.serverboundLoginStart {
|
||||
return fmt.Errorf("bad login start packet id")
|
||||
}
|
||||
|
||||
var (
|
||||
username String
|
||||
uuid UUID
|
||||
)
|
||||
|
||||
err = pkt.readFields(&username, &uuid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login start packet: %w", err)
|
||||
}
|
||||
if !validPlayerName(string(username)) {
|
||||
return fmt.Errorf("invalid player name: %q", string(username))
|
||||
}
|
||||
profile, found := findProfile(c.profiles, string(username), uuid)
|
||||
|
||||
// encrypt request
|
||||
|
||||
var (
|
||||
serverId String = String("")
|
||||
publicKey Bytes = Bytes(c.rsaPublicKey)
|
||||
verifyToken Bytes = Bytes(make([]byte, 4))
|
||||
shouldAuthenticate Boolean = true
|
||||
)
|
||||
|
||||
if _, err = rand.Read(verifyToken); err != nil {
|
||||
return fmt.Errorf("generate verify token: %w", err)
|
||||
}
|
||||
|
||||
err = writePacket(c.writer, c.protocol.login.clientboundHello, &serverId, &publicKey, &verifyToken, &shouldAuthenticate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write encryption request: %w", err)
|
||||
}
|
||||
|
||||
// encrypt response
|
||||
|
||||
var (
|
||||
encryptedSharedSecret Bytes
|
||||
encryptedVerifyToken Bytes
|
||||
|
||||
sharedSecret []byte
|
||||
decryptedVerifyToken []byte
|
||||
)
|
||||
|
||||
pkt, err = readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encrypt response: %w", err)
|
||||
}
|
||||
|
||||
if pkt.packetID != c.protocol.login.serverboundKey {
|
||||
return fmt.Errorf("bad encrypt response packet id")
|
||||
}
|
||||
|
||||
err = pkt.readFields(&encryptedSharedSecret, &encryptedVerifyToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encrypt response: %w", err)
|
||||
}
|
||||
|
||||
// The order is vanilla's: handleKey runs ServerboundKeyPacket.isChallengeValid
|
||||
// and turns a bad challenge into java.lang.IllegalStateException: Protocol
|
||||
// error before it ever touches the secret key, so a bad challenge closes the
|
||||
// connection unencrypted and a good one fails inside the CFB8 stream. That
|
||||
// difference is drawn by vanilla too and the mask keeps it. The challenge is
|
||||
// the 4 random bytes this server sent moments ago, so an oracle on it
|
||||
// discloses nothing.
|
||||
//
|
||||
// The shared secret is the opposite case: it is the only secret on the wire,
|
||||
// so it is decrypted with the session-key countermeasure and never branched
|
||||
// on. See decryptSharedSecret.
|
||||
decryptedVerifyToken, verifyTokenOK := decryptVerifyToken(c.rsaPrivateKey, encryptedVerifyToken)
|
||||
if !verifyTokenOK || !challengesEqual(verifyToken, decryptedVerifyToken) {
|
||||
return fmt.Errorf("verify token mismatch")
|
||||
}
|
||||
|
||||
sharedSecret, blockCipher, sharedSecretOK := c.decryptSharedSecret(encryptedSharedSecret)
|
||||
if !sharedSecretOK {
|
||||
return fmt.Errorf("decrypt shared secret")
|
||||
}
|
||||
|
||||
c.reader = newCryptoReaderWithBlock(c.reader, blockCipher, sharedSecret)
|
||||
c.writer = newCryptoWriterWithBlock(c.writer, blockCipher, sharedSecret)
|
||||
|
||||
// From here the connection is encrypted and every rejection is a Login
|
||||
// Disconnect inside it, exactly like the rejections vanilla sends after a
|
||||
// successful challenge. Nothing below branches on padding validity and the
|
||||
// password comparison is constant time. A peer that did not send a valid
|
||||
// secret cannot read this answer at all: it is encrypted under a random key
|
||||
// the peer never saw.
|
||||
var reason string
|
||||
if c.yggdrasil != nil {
|
||||
// Online-mode login: verify the player through the session server
|
||||
// instead of the pre-shared password and the static profile list.
|
||||
// Vanilla's client sends the bare challenge back, and this reports an
|
||||
// unknown player to the client rather than the API outage a second
|
||||
// session server round trip would guess at.
|
||||
if len(decryptedVerifyToken) != len(verifyToken) {
|
||||
return fmt.Errorf("verify token mismatch")
|
||||
}
|
||||
|
||||
serverID := minecraftServerID(string(serverId), sharedSecret, c.rsaPublicKey)
|
||||
profile, err = c.verifyYggdrasilLogin(string(username), uuid, serverID)
|
||||
if err != nil {
|
||||
reason = `{"translate":"multiplayer.disconnect.unverified_username"}`
|
||||
if !errors.Is(err, errYggdrasilNotJoined) {
|
||||
reason = `{"translate":"multiplayer.disconnect.authservers_down"}`
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// verify password
|
||||
receivedPassword := decryptedVerifyToken[len(verifyToken):]
|
||||
|
||||
if subtle.ConstantTimeCompare(receivedPassword, []byte(c.password)) != 1 {
|
||||
// A wrong password is reported as an outage, the answer vanilla
|
||||
// gives when the session check that would have authorised the
|
||||
// player fails. Only a peer that already sent the right password can
|
||||
// reach the profile check below, so the whitelist answer is never
|
||||
// visible to a guesser.
|
||||
reason = `{"translate":"multiplayer.disconnect.authservers_down"}`
|
||||
} else if !found {
|
||||
// The password is shared, the profile list is not: only a holder of
|
||||
// the password can ever see this answer.
|
||||
reason = `{"text":"You are not white-listed on this server!"}`
|
||||
}
|
||||
}
|
||||
|
||||
if reason != "" {
|
||||
if writeErr := writeDisconnectPacket(c.writer, c.protocol.login.clientboundLoginDisconnect, reason); writeErr != nil {
|
||||
return fmt.Errorf("write login disconnect: %w", writeErr)
|
||||
}
|
||||
return fmt.Errorf("authentication rejected")
|
||||
}
|
||||
|
||||
// No Set Compression, which is the same wire as a vanilla server with
|
||||
// network-compression-threshold=-1: the startup padding preset reproduces a
|
||||
// login that ran without it, and the tunnel payloads are already compressed
|
||||
// or encrypted by whoever produced them. The client still negotiates the
|
||||
// compressed framing when the peer is a real server that enables it.
|
||||
if err = writeLoginFinished(c.writer, c.protocol, profile); err != nil {
|
||||
return fmt.Errorf("write login finished: %w", err)
|
||||
}
|
||||
|
||||
var loginAcknowledgedLength int
|
||||
pkt, loginAcknowledgedLength, err = readPacketWithLength(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login acknowledged: %w", err)
|
||||
}
|
||||
if err = validateLoginAcknowledgedPacket(pkt, c.protocol.login.serverboundLoginAcknowledged); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.startProxy(loginAcknowledgedLength)
|
||||
}
|
||||
|
||||
// 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 *serverConn) startProxy(loginAcknowledgedLength int) error {
|
||||
c.reader = newPaddingReader(c.reader, false, c.paddingChannel, c.protocol.configuration)
|
||||
if err := runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause, c.paddingChannel, c.protocol.configuration); 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, false, c.protocol.configuration, c.dataChannel, c.paddingChannel)
|
||||
c.lifecycleMu.Lock()
|
||||
if c.closed {
|
||||
c.lifecycleMu.Unlock()
|
||||
packet.Stop()
|
||||
return net.ErrClosed
|
||||
}
|
||||
c.packet = packet
|
||||
c.reader = packet
|
||||
c.writer = packet
|
||||
c.state = serverStateProxy
|
||||
c.lifecycleMu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validPlayerName mirrors vanilla's Login Start check in 26.x: at most sixteen
|
||||
// bytes, all printable ASCII. The older "letters, digits and underscore"
|
||||
// restriction was dropped, so filtering it here would reject players a vanilla
|
||||
// server accepts.
|
||||
func validPlayerName(name string) bool {
|
||||
if len(name) > maxPlayerNameLength {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(name); i++ {
|
||||
if name[i] <= 32 || name[i] >= 127 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// statusResponse is the status JSON a vanilla server of this version builds:
|
||||
// a collapsed literal description, the player counts with an empty sample, and
|
||||
// the version the server speaks.
|
||||
func statusResponse(version protocolVersion) string {
|
||||
return fmt.Sprintf(
|
||||
`{"description":"A Minecraft Server","players":{"max":20,"online":0,"sample":[]},"version":{"name":%q,"protocol":%d},"enforcesSecureChat":true}`,
|
||||
version.name,
|
||||
version.number,
|
||||
)
|
||||
}
|
||||
|
||||
func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID string) (loginProfile, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), yggdrasilVerifyTimeout)
|
||||
defer cancel()
|
||||
@@ -348,8 +446,8 @@ func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID s
|
||||
}
|
||||
}
|
||||
|
||||
func validateLoginAcknowledgedPacket(pkt *mcPacket) error {
|
||||
if pkt.packetID != 0x03 {
|
||||
func validateLoginAcknowledgedPacket(pkt *mcPacket, packetID int) error {
|
||||
if pkt.packetID != packetID {
|
||||
return fmt.Errorf("bad login acknowledged packet id: %d", pkt.packetID)
|
||||
}
|
||||
if len(pkt.data) != 0 {
|
||||
@@ -383,6 +481,10 @@ func (c *serverConn) 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()
|
||||
@@ -413,7 +515,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
|
||||
return c.deadlines.setWriteDeadline(t)
|
||||
}
|
||||
|
||||
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier) (*serverConn, error) {
|
||||
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier, dataChannel, paddingChannel string) (*serverConn, error) {
|
||||
if len(profiles) == 0 && yggdrasil == nil {
|
||||
return nil, fmt.Errorf("empty profiles")
|
||||
}
|
||||
@@ -437,6 +539,8 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
|
||||
password: password,
|
||||
rsaPrivateKey: rsaPrivateKey,
|
||||
rsaPublicKey: rsaPublicKey,
|
||||
dataChannel: dataChannel,
|
||||
paddingChannel: paddingChannel,
|
||||
yggdrasil: yggdrasil,
|
||||
paddingSchedule: paddingSchedule,
|
||||
deadlines: newConnectionDeadlines(c),
|
||||
|
||||
@@ -17,9 +17,9 @@ type cryptoStream struct {
|
||||
}
|
||||
|
||||
func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) {
|
||||
blockCipher, err := aes.NewCipher(sharedSecret)
|
||||
blockCipher, err := newAESCipher(sharedSecret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new aes cipher: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stream := newCFB8Decrypt(blockCipher, sharedSecret)
|
||||
@@ -27,6 +27,27 @@ func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) {
|
||||
return &cryptoStream{stream: stream, r: r}, nil
|
||||
}
|
||||
|
||||
func newAESCipher(sharedSecret []byte) (cipher.Block, error) {
|
||||
blockCipher, err := aes.NewCipher(sharedSecret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new aes cipher: %w", err)
|
||||
}
|
||||
return blockCipher, nil
|
||||
}
|
||||
|
||||
// newCryptoReaderWithBlock is newCryptoReader for a caller that already holds
|
||||
// the cipher block, so the key stays in the caller's hands until it installs the
|
||||
// stream.
|
||||
func newCryptoReaderWithBlock(r io.Reader, blockCipher cipher.Block, sharedSecret []byte) *cryptoStream {
|
||||
return &cryptoStream{stream: newCFB8Decrypt(blockCipher, sharedSecret), r: r}
|
||||
}
|
||||
|
||||
// newCryptoWriterWithBlock is newCryptoWriter for a caller that already holds
|
||||
// the cipher block.
|
||||
func newCryptoWriterWithBlock(w io.Writer, blockCipher cipher.Block, sharedSecret []byte) *cryptoStream {
|
||||
return &cryptoStream{stream: newCFB8Encrypt(blockCipher, sharedSecret), w: w}
|
||||
}
|
||||
|
||||
func (c *cryptoStream) Read(b []byte) (int, error) {
|
||||
if c.r == nil {
|
||||
panic("read on a write-only crypto stream")
|
||||
@@ -50,9 +71,9 @@ func (c *cryptoStream) Read(b []byte) (int, error) {
|
||||
}
|
||||
|
||||
func newCryptoWriter(w io.Writer, sharedSecret []byte) (*cryptoStream, error) {
|
||||
blockCipher, err := aes.NewCipher(sharedSecret)
|
||||
blockCipher, err := newAESCipher(sharedSecret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new aes cipher: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stream := newCFB8Encrypt(blockCipher, sharedSecret)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// tickTestWriter records every batch the tick stream writes to the network.
|
||||
type tickTestWriter struct {
|
||||
mu sync.Mutex
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *tickTestWriter) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.writes = append(w.writes, append([]byte(nil), p...))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (w *tickTestWriter) snapshot() [][]byte {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return append([][]byte(nil), w.writes...)
|
||||
}
|
||||
|
||||
func readTickBatch(t *testing.T, batch []byte) []*mcPacket {
|
||||
t.Helper()
|
||||
r := bytes.NewReader(batch)
|
||||
var packets []*mcPacket
|
||||
for r.Len() > 0 {
|
||||
packet, err := readPacket(r)
|
||||
if err != nil {
|
||||
t.Fatalf("parse tick batch: %v", err)
|
||||
}
|
||||
packets = append(packets, packet)
|
||||
}
|
||||
return packets
|
||||
}
|
||||
|
||||
// tickPacketChannelAndPayload splits one custom payload into its channel name
|
||||
// and the raw payload bytes that follow it.
|
||||
func tickPacketChannelAndPayload(t *testing.T, packet *mcPacket) (string, []byte) {
|
||||
t.Helper()
|
||||
r := bytes.NewReader(packet.data)
|
||||
var channel String
|
||||
if err := channel.readFrom(r); err != nil {
|
||||
t.Fatalf("read tick packet channel: %v", err)
|
||||
}
|
||||
payload, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
t.Fatalf("read tick packet payload: %v", err)
|
||||
}
|
||||
return string(channel), payload
|
||||
}
|
||||
|
||||
func collectTickData(t *testing.T, batches [][]byte) (data []byte, dataPackets, padding int) {
|
||||
t.Helper()
|
||||
for _, batch := range batches {
|
||||
for _, packet := range readTickBatch(t, batch) {
|
||||
channel, payload := tickPacketChannelAndPayload(t, packet)
|
||||
switch channel {
|
||||
case DefaultDataChannel:
|
||||
data = append(data, payload...)
|
||||
dataPackets++
|
||||
case DefaultPaddingChannel:
|
||||
padding++
|
||||
}
|
||||
}
|
||||
}
|
||||
return data, dataPackets, padding
|
||||
}
|
||||
|
||||
// TestTickStreamIdleCadence pins the 20 Hz shape: an idle connection still
|
||||
// emits one small padding frame per tick in both directions.
|
||||
func TestTickStreamIdleCadence(t *testing.T) {
|
||||
writer := &tickTestWriter{}
|
||||
stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel)
|
||||
defer stream.Stop()
|
||||
|
||||
time.Sleep(180 * time.Millisecond)
|
||||
stream.Stop()
|
||||
// Wait for an in-flight tick so the recorded batches are complete.
|
||||
_ = stream.Flush()
|
||||
|
||||
batches := writer.snapshot()
|
||||
if len(batches) < 2 || len(batches) > 6 {
|
||||
t.Fatalf("got %d tick batches in 180ms, want about 3", len(batches))
|
||||
}
|
||||
for i, batch := range batches {
|
||||
packets := readTickBatch(t, batch)
|
||||
if len(packets) != 1 {
|
||||
t.Fatalf("idle tick %d wrote %d packets, want 1", i, len(packets))
|
||||
}
|
||||
if packets[0].packetID != configurationPacketIDs121.serverboundCustomPayload {
|
||||
t.Fatalf("idle tick %d packet id = %d", i, packets[0].packetID)
|
||||
}
|
||||
channel, _ := tickPacketChannelAndPayload(t, packets[0])
|
||||
if channel != DefaultPaddingChannel {
|
||||
t.Fatalf("idle tick %d channel = %q", i, channel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTickStreamSendsQueuedDataInOneTick checks that proxy data is queued and
|
||||
// then emitted as one per-tick batch, split at maxPacketData boundaries.
|
||||
func TestTickStreamSendsQueuedDataInOneTick(t *testing.T) {
|
||||
writer := &tickTestWriter{}
|
||||
stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel)
|
||||
defer stream.Stop()
|
||||
|
||||
payload := bytes.Repeat([]byte("0123456789abcdef"), 4096)
|
||||
if _, err := stream.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(time.Second)
|
||||
var (
|
||||
data []byte
|
||||
dataPackets int
|
||||
padding int
|
||||
)
|
||||
for time.Now().Before(deadline) {
|
||||
batches := writer.snapshot()
|
||||
if len(batches) > 0 {
|
||||
data, dataPackets, padding = collectTickData(t, batches)
|
||||
if len(data) >= len(payload) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
|
||||
if !bytes.Equal(data, payload) {
|
||||
t.Fatalf("got %d payload bytes, want %d", len(data), len(payload))
|
||||
}
|
||||
wantPackets := (len(payload) + maxPacketData - 1) / maxPacketData
|
||||
if dataPackets != wantPackets {
|
||||
t.Fatalf("got %d data packets, want %d", dataPackets, wantPackets)
|
||||
}
|
||||
if padding < 1 {
|
||||
t.Fatal("the tick that carried data did not carry a padding frame")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTickStreamFlushWritesQueuedDataImmediately covers graceful close: data
|
||||
// already accepted by Write must not wait for the next tick.
|
||||
func TestTickStreamFlushWritesQueuedDataImmediately(t *testing.T) {
|
||||
writer := &tickTestWriter{}
|
||||
stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel)
|
||||
defer stream.Stop()
|
||||
|
||||
payload := []byte("flush me")
|
||||
if _, err := stream.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := stream.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, _, _ := collectTickData(t, writer.snapshot())
|
||||
if !bytes.Equal(data, payload) {
|
||||
t.Fatalf("flush delivered %q, want %q", data, payload)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPingPongEncoding pins the configuration ping/pong form: the id is a plain
|
||||
// 32-bit integer, not a varint. Vanilla rejected a varint pong with "Failed to
|
||||
// decode packet 'serverbound/minecraft:pong'", which is why this is tested
|
||||
// separately from the rest of the stream.
|
||||
func TestPingPongEncoding(t *testing.T) {
|
||||
packetIDs := configurationPacketIDs121
|
||||
|
||||
var wire bytes.Buffer
|
||||
pingID := Int(0x01020304)
|
||||
if err := writePacket(&wire, packetIDs.clientboundPing, &pingID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
packet, err := readPacket(&wire)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var received Int
|
||||
if err := packet.readFields(&received); err != nil {
|
||||
t.Fatalf("read ping id as int: %v", err)
|
||||
}
|
||||
if received != pingID {
|
||||
t.Fatalf("ping id = %#x, want %#x", received, pingID)
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
stream := &tickStream{writer: &out, isClient: true, packetIDs: packetIDs}
|
||||
if err := stream.writePong(received); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer, err := readPacket(&out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if answer.packetID != packetIDs.serverboundPong {
|
||||
t.Fatalf("pong packet id = 0x%02x", answer.packetID)
|
||||
}
|
||||
if !bytes.Equal(answer.data, []byte{1, 2, 3, 4}) {
|
||||
t.Fatalf("pong body = %x, want 01020304", answer.data)
|
||||
}
|
||||
}
|
||||
@@ -468,6 +468,14 @@ type yggdrasilAuth struct {
|
||||
|
||||
keyMu sync.Mutex
|
||||
signatureKey *rsa.PublicKey
|
||||
|
||||
// loginMu serializes the login exchange of one account, from Login Start to
|
||||
// the peer's Login Finished. The session server keeps one server id per
|
||||
// profile, so only the most recent /join answers hasJoined; a second login
|
||||
// that started while the first server was still polling would overwrite
|
||||
// that session and the first server would reject it with
|
||||
// unverified_username.
|
||||
loginMu sync.Mutex
|
||||
}
|
||||
|
||||
func newYggdrasilAuth(config *yggdrasilConfig) *yggdrasilAuth {
|
||||
|
||||
@@ -58,6 +58,15 @@ type fakeYggdrasil struct {
|
||||
|
||||
boundProfile string
|
||||
joined map[string]string // serverId -> profile name
|
||||
|
||||
// latestServerID is the server id of the most recent join. A real session
|
||||
// server keeps one id per profile, so with singleSession set only that id
|
||||
// answers hasJoined.
|
||||
latestServerID string
|
||||
singleSession bool
|
||||
// hasJoinedDelay widens the window in which a concurrent join can replace
|
||||
// the session under test.
|
||||
hasJoinedDelay time.Duration
|
||||
}
|
||||
|
||||
func writeFakeYggdrasilJSON(w http.ResponseWriter, status int, body string) {
|
||||
@@ -124,15 +133,30 @@ func newFakeYggdrasilHandler(state *fakeYggdrasil) http.Handler {
|
||||
state.joinCalls++
|
||||
state.boundProfile = request.SelectedProfile
|
||||
state.joined[request.ServerID] = state.profile.Name
|
||||
state.latestServerID = request.ServerID
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
|
||||
mux.HandleFunc(prefix+"/sessionserver/session/minecraft/hasJoined", func(w http.ResponseWriter, r *http.Request) {
|
||||
serverID := r.URL.Query().Get("serverId")
|
||||
username := r.URL.Query().Get("username")
|
||||
|
||||
state.mu.Lock()
|
||||
delay := state.hasJoinedDelay
|
||||
state.mu.Unlock()
|
||||
if delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
|
||||
name, found := state.joined[r.URL.Query().Get("serverId")]
|
||||
if !found || name != r.URL.Query().Get("username") {
|
||||
if state.singleSession && state.latestServerID != serverID {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
name, found := state.joined[serverID]
|
||||
if !found || name != username {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
@@ -358,11 +382,14 @@ func TestHandshakeWithYggdrasil(t *testing.T) {
|
||||
t.Errorf("new verifier: %v", err)
|
||||
return
|
||||
}
|
||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier)
|
||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Errorf("wrap server: %v", err)
|
||||
return
|
||||
}
|
||||
// Write queues the payload for the next tick, so Close has to flush it
|
||||
// before the raw connection is torn down.
|
||||
defer server.Close()
|
||||
|
||||
buf := make([]byte, 1024)
|
||||
n, err := server.Read(buf)
|
||||
@@ -387,7 +414,7 @@ func TestHandshakeWithYggdrasil(t *testing.T) {
|
||||
|
||||
// The client intentionally has no pinned server key: Yggdrasil mode accepts
|
||||
// the key sent by the server and binds it through the session hash.
|
||||
client, err := newClientConn(rawClient, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser"))
|
||||
client, err := newClientConn(rawClient, latestProtocolVersion, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser"), DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
@@ -421,6 +448,128 @@ func TestHandshakeWithYggdrasil(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestYggdrasilConcurrentLoginsSerialized checks that one account never runs two
|
||||
// logins at once. The session server keeps a single server id per profile, so a
|
||||
// concurrent login would overwrite the session of a server that is still polling
|
||||
// hasJoined, and that server would answer unverified_username. The fake API here
|
||||
// behaves like the real one (only the most recent /join answers hasJoined) and
|
||||
// adds latency to make the overwrite window wide.
|
||||
func TestYggdrasilConcurrentLoginsSerialized(t *testing.T) {
|
||||
state, api := newFakeYggdrasilServer(t)
|
||||
state.singleSession = true
|
||||
state.hasJoinedDelay = 25 * time.Millisecond
|
||||
|
||||
const logins = 4
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
password := "yggdrasil-rsa-seed"
|
||||
privateKey, publicKey := deriveTestRSAKey(t, password)
|
||||
|
||||
var servers sync.WaitGroup
|
||||
servers.Add(logins)
|
||||
go func() {
|
||||
for i := 0; i < logins; i++ {
|
||||
rawConn, err := ln.Accept()
|
||||
if err != nil {
|
||||
t.Errorf("accept: %v", err)
|
||||
servers.Done()
|
||||
continue
|
||||
}
|
||||
go func(conn net.Conn) {
|
||||
defer servers.Done()
|
||||
defer conn.Close()
|
||||
|
||||
verifier, err := newYggdrasilVerifier(api)
|
||||
if err != nil {
|
||||
t.Errorf("new verifier: %v", err)
|
||||
return
|
||||
}
|
||||
server, err := wrapConnServer(conn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Errorf("wrap server: %v", err)
|
||||
return
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
buf := make([]byte, 64)
|
||||
n, err := server.Read(buf)
|
||||
if err != nil {
|
||||
t.Errorf("server read: %v", err)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(buf[:n], []byte("ping")) {
|
||||
t.Errorf("unexpected payload: %q", buf[:n])
|
||||
return
|
||||
}
|
||||
if _, err := server.Write([]byte("ok")); err != nil {
|
||||
t.Errorf("server write: %v", err)
|
||||
}
|
||||
}(rawConn)
|
||||
}
|
||||
}()
|
||||
|
||||
// One auth value for all connections, like one Xray process and one account.
|
||||
auth := newTestYggdrasilAuth(t, api, "SkinUser")
|
||||
|
||||
var clients sync.WaitGroup
|
||||
errs := make(chan error, logins)
|
||||
for i := 0; i < logins; i++ {
|
||||
clients.Add(1)
|
||||
go func() {
|
||||
defer clients.Done()
|
||||
|
||||
rawConn, err := net.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
errs <- fmt.Errorf("dial: %w", err)
|
||||
return
|
||||
}
|
||||
defer rawConn.Close()
|
||||
|
||||
client, err := newClientConn(rawConn, latestProtocolVersion, nil, "", nil, "localhost", nil, auth, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
errs <- fmt.Errorf("new client: %w", err)
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
if _, err := client.Write([]byte("ping")); err != nil {
|
||||
errs <- fmt.Errorf("client write: %w", err)
|
||||
return
|
||||
}
|
||||
reply := make([]byte, 2)
|
||||
if err := client.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
if _, err := io.ReadFull(client, reply); err != nil {
|
||||
errs <- fmt.Errorf("client read: %w", err)
|
||||
return
|
||||
}
|
||||
if string(reply) != "ok" {
|
||||
errs <- fmt.Errorf("unexpected reply: %q", reply)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
clients.Wait()
|
||||
servers.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
if state.joinCalls != logins {
|
||||
t.Errorf("join calls = %d, want %d", state.joinCalls, logins)
|
||||
}
|
||||
}
|
||||
|
||||
func TestYggdrasilVerifiesTexturesSignature(t *testing.T) {
|
||||
state, api := newFakeYggdrasilServer(t)
|
||||
auth := newTestYggdrasilAuth(t, api, "SkinUser")
|
||||
@@ -554,7 +703,7 @@ func TestYggdrasilLoginFailure(t *testing.T) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier)
|
||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -568,7 +717,7 @@ func TestYggdrasilLoginFailure(t *testing.T) {
|
||||
}
|
||||
defer rawClient.Close()
|
||||
|
||||
client, err := newClientConn(rawClient, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, ""))
|
||||
client, err := newClientConn(rawClient, latestProtocolVersion, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, ""), DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,11 @@ func (s *Proxy) Proxy(w http.ResponseWriter, r *ProxyRequest) (*Conn, error) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
if ok {
|
||||
return newProxiedConn(streamer.HTTPStream()), nil
|
||||
str, err := streamer.HTTPStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newProxiedConn(str), nil
|
||||
}
|
||||
controller := http.NewResponseController(w)
|
||||
if err := controller.Flush(); err != nil {
|
||||
|
||||
@@ -231,7 +231,11 @@ func TestDialWarpHTTP3(t *testing.T) {
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
str := w.(http3.HTTPStreamer).HTTPStream()
|
||||
str, err := w.(http3.HTTPStreamer).HTTPStream()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
go func() { capsules <- readCapsuleTypes(str, nil) }()
|
||||
b, err := str.ReceiveDatagram(r.Context())
|
||||
if err != nil {
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
http_proto "github.com/xtls/xray-core/common/protocol/http"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
|
||||
@@ -78,10 +79,9 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession {
|
||||
h.sessions.Store(sessionId, s)
|
||||
|
||||
shouldReap := done.New()
|
||||
go func() {
|
||||
time.Sleep(30 * time.Second)
|
||||
time.AfterFunc(30*time.Second, func() {
|
||||
shouldReap.Close()
|
||||
}()
|
||||
})
|
||||
go func() {
|
||||
select {
|
||||
case <-shouldReap.Wait():
|
||||
@@ -222,15 +222,15 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
|
||||
scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs()
|
||||
hasLegacyRefererCompatMarker := request.Header.Get("Referer") != ""
|
||||
if (hasLegacyRefererCompatMarker || obfsPaddingAccepted) && scStreamUpServerSecs.To > 0 {
|
||||
go func() {
|
||||
for {
|
||||
writePadding := &task.Periodic{
|
||||
Execute: func() error {
|
||||
_, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second)
|
||||
}
|
||||
}()
|
||||
return err
|
||||
},
|
||||
Interval: time.Duration(scStreamUpServerSecs.rand()) * time.Second,
|
||||
}
|
||||
defer writePadding.Close()
|
||||
writePadding.Start()
|
||||
}
|
||||
select {
|
||||
case <-request.Context().Done():
|
||||
|
||||
@@ -130,14 +130,6 @@ func (c *UConn) WebsocketHandshakeContext(ctx context.Context) error {
|
||||
config.NextProtos = []string{"http/1.1"}
|
||||
return c.HandshakeContext(ctx)
|
||||
}
|
||||
// Chrome won't send ApplicationSettingsExtension for h1 request
|
||||
if slices.Equal(ALPN, []string{"http/1.1"}) {
|
||||
newExt := slices.DeleteFunc(c.Extensions, func(extension utls.TLSExtension) bool {
|
||||
_, ok := extension.(*utls.ApplicationSettingsExtensionNew)
|
||||
return ok
|
||||
})
|
||||
c.Extensions = newExt
|
||||
}
|
||||
// Iterate over extensions and check for utls.ALPNExtension
|
||||
hasALPNExtension := false
|
||||
for _, extension := range c.Extensions {
|
||||
|
||||
@@ -6,9 +6,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
)
|
||||
|
||||
var _ buf.Writer = (*connection)(nil)
|
||||
@@ -20,25 +22,27 @@ type connection struct {
|
||||
conn *websocket.Conn
|
||||
reader io.Reader
|
||||
remoteAddr net.Addr
|
||||
keepalive *task.Periodic
|
||||
}
|
||||
|
||||
func NewConnection(conn *websocket.Conn, remoteAddr net.Addr, extraReader io.Reader, heartbeatPeriod uint32) *connection {
|
||||
if heartbeatPeriod != 0 {
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(time.Duration(heartbeatPeriod) * time.Second)
|
||||
if err := conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{}); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return &connection{
|
||||
wrappedConn := &connection{
|
||||
conn: conn,
|
||||
remoteAddr: remoteAddr,
|
||||
reader: extraReader,
|
||||
}
|
||||
if heartbeatPeriod != 0 {
|
||||
keepalive := task.Periodic{
|
||||
Execute: func() error {
|
||||
return conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{})
|
||||
},
|
||||
Interval: time.Duration(heartbeatPeriod) * time.Second,
|
||||
}
|
||||
keepalive.Start()
|
||||
wrappedConn.keepalive = &keepalive
|
||||
}
|
||||
|
||||
return wrappedConn
|
||||
}
|
||||
|
||||
// Read implements net.Conn.Read()
|
||||
@@ -93,6 +97,7 @@ func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
}
|
||||
|
||||
func (c *connection) Close() error {
|
||||
common.CloseIfExists(c.keepalive)
|
||||
var errs []interface{}
|
||||
if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
|
||||
errs = append(errs, err)
|
||||
|
||||
Reference in New Issue
Block a user